Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 51b13ce9

History | View | Annotate | Download (365.1 kB)

1
#
2
#
3

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

    
21

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

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

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

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

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

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

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

    
59

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

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

66
  """
67
  return []
68

    
69

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

73
  """
74
  return {}
75

    
76

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

    
80

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

    
84

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

89
  """
90
  return val is not None
91

    
92

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

96
  """
97
  return val is None
98

    
99

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

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

    
106

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

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

    
113

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

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

    
120

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

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

    
127

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

131
  """
132
  return bool(val)
133

    
134

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

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

    
141

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

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

    
149

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

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

    
156

    
157
# Combinator types
158
def _TAnd(*args):
159
  """Combine multiple functions using an AND operation.
160

161
  """
162
  def fn(val):
163
    return compat.all(t(val) for t in args)
164
  return fn
165

    
166

    
167
def _TOr(*args):
168
  """Combine multiple functions using an AND operation.
169

170
  """
171
  def fn(val):
172
    return compat.any(t(val) for t in args)
173
  return fn
174

    
175

    
176
# Type aliases
177

    
178
#: a non-empty string
179
_TNonEmptyString = _TAnd(_TString, _TTrue)
180

    
181

    
182
#: a maybe non-empty string
183
_TMaybeString = _TOr(_TNonEmptyString, _TNone)
184

    
185

    
186
#: a maybe boolean (bool or none)
187
_TMaybeBool = _TOr(_TBool, _TNone)
188

    
189

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

    
193
#: a strictly positive integer
194
_TStrictPositiveInt = _TAnd(_TInt, lambda v: v > 0)
195

    
196

    
197
def _TListOf(my_type):
198
  """Checks if a given value is a list with all elements of the same type.
199

200
  """
201
  return _TAnd(_TList,
202
               lambda lst: compat.all(my_type(v) for v in lst))
203

    
204

    
205
def _TDictOf(key_type, val_type):
206
  """Checks a dict type for the type of its key/values.
207

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

    
214

    
215
# Common opcode attributes
216

    
217
#: output fields for a query operation
218
_POutputFields = ("output_fields", _NoDefault, _TListOf(_TNonEmptyString))
219

    
220

    
221
#: the shutdown timeout
222
_PShutdownTimeout = ("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
223
                     _TPositiveInt)
224

    
225
#: the force parameter
226
_PForce = ("force", False, _TBool)
227

    
228
#: a required instance name (for single-instance LUs)
229
_PInstanceName = ("instance_name", _NoDefault, _TNonEmptyString)
230

    
231

    
232
#: a required node name (for single-node LUs)
233
_PNodeName = ("node_name", _NoDefault, _TNonEmptyString)
234

    
235
#: the migration type (live/non-live)
236
_PMigrationMode = ("mode", None, _TOr(_TNone,
237
                                      _TElemOf(constants.HT_MIGRATION_MODES)))
238

    
239
#: the obsolete 'live' mode (boolean)
240
_PMigrationLive = ("live", None, _TMaybeBool)
241

    
242

    
243
# End types
244
class LogicalUnit(object):
245
  """Logical Unit base class.
246

247
  Subclasses must follow these rules:
248
    - implement ExpandNames
249
    - implement CheckPrereq (except when tasklets are used)
250
    - implement Exec (except when tasklets are used)
251
    - implement BuildHooksEnv
252
    - redefine HPATH and HTYPE
253
    - optionally redefine their run requirements:
254
        REQ_BGL: the LU needs to hold the Big Ganeti Lock exclusively
255

256
  Note that all commands require root permissions.
257

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

263
  """
264
  HPATH = None
265
  HTYPE = None
266
  _OP_PARAMS = []
267
  REQ_BGL = True
268

    
269
  def __init__(self, processor, op, context, rpc):
270
    """Constructor for LogicalUnit.
271

272
    This needs to be overridden in derived classes in order to check op
273
    validity.
274

275
    """
276
    self.proc = processor
277
    self.op = op
278
    self.cfg = context.cfg
279
    self.context = context
280
    self.rpc = rpc
281
    # Dicts used to declare locking needs to mcpu
282
    self.needed_locks = None
283
    self.acquired_locks = {}
284
    self.share_locks = dict.fromkeys(locking.LEVELS, 0)
285
    self.add_locks = {}
286
    self.remove_locks = {}
287
    # Used to force good behavior when calling helper functions
288
    self.recalculate_locks = {}
289
    self.__ssh = None
290
    # logging
291
    self.Log = processor.Log # pylint: disable-msg=C0103
292
    self.LogWarning = processor.LogWarning # pylint: disable-msg=C0103
293
    self.LogInfo = processor.LogInfo # pylint: disable-msg=C0103
294
    self.LogStep = processor.LogStep # pylint: disable-msg=C0103
295
    # support for dry-run
296
    self.dry_run_result = None
297
    # support for generic debug attribute
298
    if (not hasattr(self.op, "debug_level") or
299
        not isinstance(self.op.debug_level, int)):
300
      self.op.debug_level = 0
301

    
302
    # Tasklets
303
    self.tasklets = None
304

    
305
    # The new kind-of-type-system
306
    op_id = self.op.OP_ID
307
    for attr_name, aval, test in self._OP_PARAMS:
308
      if not hasattr(op, attr_name):
309
        if aval == _NoDefault:
310
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
311
                                     (op_id, attr_name), errors.ECODE_INVAL)
312
        else:
313
          if callable(aval):
314
            dval = aval()
315
          else:
316
            dval = aval
317
          setattr(self.op, attr_name, dval)
318
      attr_val = getattr(op, attr_name)
319
      if test == _NoType:
320
        # no tests here
321
        continue
322
      if not callable(test):
323
        raise errors.ProgrammerError("Validation for parameter '%s.%s' failed,"
324
                                     " given type is not a proper type (%s)" %
325
                                     (op_id, attr_name, test))
326
      if not test(attr_val):
327
        logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
328
                      self.op.OP_ID, attr_name, type(attr_val), attr_val)
329
        raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
330
                                   (op_id, attr_name), errors.ECODE_INVAL)
331

    
332
    self.CheckArguments()
333

    
334
  def __GetSSH(self):
335
    """Returns the SshRunner object
336

337
    """
338
    if not self.__ssh:
339
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
340
    return self.__ssh
341

    
342
  ssh = property(fget=__GetSSH)
343

    
344
  def CheckArguments(self):
345
    """Check syntactic validity for the opcode arguments.
346

347
    This method is for doing a simple syntactic check and ensure
348
    validity of opcode parameters, without any cluster-related
349
    checks. While the same can be accomplished in ExpandNames and/or
350
    CheckPrereq, doing these separate is better because:
351

352
      - ExpandNames is left as as purely a lock-related function
353
      - CheckPrereq is run after we have acquired locks (and possible
354
        waited for them)
355

356
    The function is allowed to change the self.op attribute so that
357
    later methods can no longer worry about missing parameters.
358

359
    """
360
    pass
361

    
362
  def ExpandNames(self):
363
    """Expand names for this LU.
364

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

370
    LUs which implement this method must also populate the self.needed_locks
371
    member, as a dict with lock levels as keys, and a list of needed lock names
372
    as values. Rules:
373

374
      - use an empty dict if you don't need any lock
375
      - if you don't need any lock at a particular level omit that level
376
      - don't put anything for the BGL level
377
      - if you want all locks at a level use locking.ALL_SET as a value
378

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

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

387
    Examples::
388

389
      # Acquire all nodes and one instance
390
      self.needed_locks = {
391
        locking.LEVEL_NODE: locking.ALL_SET,
392
        locking.LEVEL_INSTANCE: ['instance1.example.com'],
393
      }
394
      # Acquire just two nodes
395
      self.needed_locks = {
396
        locking.LEVEL_NODE: ['node1.example.com', 'node2.example.com'],
397
      }
398
      # Acquire no locks
399
      self.needed_locks = {} # No, you can't leave it to the default value None
400

401
    """
402
    # The implementation of this method is mandatory only if the new LU is
403
    # concurrent, so that old LUs don't need to be changed all at the same
404
    # time.
405
    if self.REQ_BGL:
406
      self.needed_locks = {} # Exclusive LUs don't need locks.
407
    else:
408
      raise NotImplementedError
409

    
410
  def DeclareLocks(self, level):
411
    """Declare LU locking needs for a level
412

413
    While most LUs can just declare their locking needs at ExpandNames time,
414
    sometimes there's the need to calculate some locks after having acquired
415
    the ones before. This function is called just before acquiring locks at a
416
    particular level, but after acquiring the ones at lower levels, and permits
417
    such calculations. It can be used to modify self.needed_locks, and by
418
    default it does nothing.
419

420
    This function is only called if you have something already set in
421
    self.needed_locks for the level.
422

423
    @param level: Locking level which is going to be locked
424
    @type level: member of ganeti.locking.LEVELS
425

426
    """
427

    
428
  def CheckPrereq(self):
429
    """Check prerequisites for this LU.
430

431
    This method should check that the prerequisites for the execution
432
    of this LU are fulfilled. It can do internode communication, but
433
    it should be idempotent - no cluster or system changes are
434
    allowed.
435

436
    The method should raise errors.OpPrereqError in case something is
437
    not fulfilled. Its return value is ignored.
438

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

442
    """
443
    if self.tasklets is not None:
444
      for (idx, tl) in enumerate(self.tasklets):
445
        logging.debug("Checking prerequisites for tasklet %s/%s",
446
                      idx + 1, len(self.tasklets))
447
        tl.CheckPrereq()
448
    else:
449
      pass
450

    
451
  def Exec(self, feedback_fn):
452
    """Execute the LU.
453

454
    This method should implement the actual work. It should raise
455
    errors.OpExecError for failures that are somewhat dealt with in
456
    code, or expected.
457

458
    """
459
    if self.tasklets is not None:
460
      for (idx, tl) in enumerate(self.tasklets):
461
        logging.debug("Executing tasklet %s/%s", idx + 1, len(self.tasklets))
462
        tl.Exec(feedback_fn)
463
    else:
464
      raise NotImplementedError
465

    
466
  def BuildHooksEnv(self):
467
    """Build hooks environment for this LU.
468

469
    This method should return a three-node tuple consisting of: a dict
470
    containing the environment that will be used for running the
471
    specific hook for this LU, a list of node names on which the hook
472
    should run before the execution, and a list of node names on which
473
    the hook should run after the execution.
474

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

480
    No nodes should be returned as an empty list (and not None).
481

482
    Note that if the HPATH for a LU class is None, this function will
483
    not be called.
484

485
    """
486
    raise NotImplementedError
487

    
488
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
489
    """Notify the LU about the results of its hooks.
490

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

497
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
498
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
499
    @param hook_results: the results of the multi-node hooks rpc call
500
    @param feedback_fn: function used send feedback back to the caller
501
    @param lu_result: the previous Exec result this LU had, or None
502
        in the PRE phase
503
    @return: the new Exec result, based on the previous result
504
        and hook results
505

506
    """
507
    # API must be kept, thus we ignore the unused argument and could
508
    # be a function warnings
509
    # pylint: disable-msg=W0613,R0201
510
    return lu_result
511

    
512
  def _ExpandAndLockInstance(self):
513
    """Helper function to expand and lock an instance.
514

515
    Many LUs that work on an instance take its name in self.op.instance_name
516
    and need to expand it and then declare the expanded name for locking. This
517
    function does it, and then updates self.op.instance_name to the expanded
518
    name. It also initializes needed_locks as a dict, if this hasn't been done
519
    before.
520

521
    """
522
    if self.needed_locks is None:
523
      self.needed_locks = {}
524
    else:
525
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
526
        "_ExpandAndLockInstance called with instance-level locks set"
527
    self.op.instance_name = _ExpandInstanceName(self.cfg,
528
                                                self.op.instance_name)
529
    self.needed_locks[locking.LEVEL_INSTANCE] = self.op.instance_name
530

    
531
  def _LockInstancesNodes(self, primary_only=False):
532
    """Helper function to declare instances' nodes for locking.
533

534
    This function should be called after locking one or more instances to lock
535
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
536
    with all primary or secondary nodes for instances already locked and
537
    present in self.needed_locks[locking.LEVEL_INSTANCE].
538

539
    It should be called from DeclareLocks, and for safety only works if
540
    self.recalculate_locks[locking.LEVEL_NODE] is set.
541

542
    In the future it may grow parameters to just lock some instance's nodes, or
543
    to just lock primaries or secondary nodes, if needed.
544

545
    If should be called in DeclareLocks in a way similar to::
546

547
      if level == locking.LEVEL_NODE:
548
        self._LockInstancesNodes()
549

550
    @type primary_only: boolean
551
    @param primary_only: only lock primary nodes of locked instances
552

553
    """
554
    assert locking.LEVEL_NODE in self.recalculate_locks, \
555
      "_LockInstancesNodes helper function called with no nodes to recalculate"
556

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

    
559
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
560
    # future we might want to have different behaviors depending on the value
561
    # of self.recalculate_locks[locking.LEVEL_NODE]
562
    wanted_nodes = []
563
    for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
564
      instance = self.context.cfg.GetInstanceInfo(instance_name)
565
      wanted_nodes.append(instance.primary_node)
566
      if not primary_only:
567
        wanted_nodes.extend(instance.secondary_nodes)
568

    
569
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
570
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
571
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
572
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
573

    
574
    del self.recalculate_locks[locking.LEVEL_NODE]
575

    
576

    
577
class NoHooksLU(LogicalUnit): # pylint: disable-msg=W0223
578
  """Simple LU which runs no hooks.
579

580
  This LU is intended as a parent for other LogicalUnits which will
581
  run no hooks, in order to reduce duplicate code.
582

583
  """
584
  HPATH = None
585
  HTYPE = None
586

    
587
  def BuildHooksEnv(self):
588
    """Empty BuildHooksEnv for NoHooksLu.
589

590
    This just raises an error.
591

592
    """
593
    assert False, "BuildHooksEnv called for NoHooksLUs"
594

    
595

    
596
class Tasklet:
597
  """Tasklet base class.
598

599
  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
600
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
601
  tasklets know nothing about locks.
602

603
  Subclasses must follow these rules:
604
    - Implement CheckPrereq
605
    - Implement Exec
606

607
  """
608
  def __init__(self, lu):
609
    self.lu = lu
610

    
611
    # Shortcuts
612
    self.cfg = lu.cfg
613
    self.rpc = lu.rpc
614

    
615
  def CheckPrereq(self):
616
    """Check prerequisites for this tasklets.
617

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

622
    The method should raise errors.OpPrereqError in case something is not
623
    fulfilled. Its return value is ignored.
624

625
    This method should also update all parameters to their canonical form if it
626
    hasn't been done before.
627

628
    """
629
    pass
630

    
631
  def Exec(self, feedback_fn):
632
    """Execute the tasklet.
633

634
    This method should implement the actual work. It should raise
635
    errors.OpExecError for failures that are somewhat dealt with in code, or
636
    expected.
637

638
    """
639
    raise NotImplementedError
640

    
641

    
642
def _GetWantedNodes(lu, nodes):
643
  """Returns list of checked and expanded node names.
644

645
  @type lu: L{LogicalUnit}
646
  @param lu: the logical unit on whose behalf we execute
647
  @type nodes: list
648
  @param nodes: list of node names or None for all nodes
649
  @rtype: list
650
  @return: the list of nodes, sorted
651
  @raise errors.ProgrammerError: if the nodes parameter is wrong type
652

653
  """
654
  if not nodes:
655
    raise errors.ProgrammerError("_GetWantedNodes should only be called with a"
656
      " non-empty list of nodes whose name is to be expanded.")
657

    
658
  wanted = [_ExpandNodeName(lu.cfg, name) for name in nodes]
659
  return utils.NiceSort(wanted)
660

    
661

    
662
def _GetWantedInstances(lu, instances):
663
  """Returns list of checked and expanded instance names.
664

665
  @type lu: L{LogicalUnit}
666
  @param lu: the logical unit on whose behalf we execute
667
  @type instances: list
668
  @param instances: list of instance names or None for all instances
669
  @rtype: list
670
  @return: the list of instances, sorted
671
  @raise errors.OpPrereqError: if the instances parameter is wrong type
672
  @raise errors.OpPrereqError: if any of the passed instances is not found
673

674
  """
675
  if instances:
676
    wanted = [_ExpandInstanceName(lu.cfg, name) for name in instances]
677
  else:
678
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
679
  return wanted
680

    
681

    
682
def _GetUpdatedParams(old_params, update_dict,
683
                      use_default=True, use_none=False):
684
  """Return the new version of a parameter dictionary.
685

686
  @type old_params: dict
687
  @param old_params: old parameters
688
  @type update_dict: dict
689
  @param update_dict: dict containing new parameter values, or
690
      constants.VALUE_DEFAULT to reset the parameter to its default
691
      value
692
  @param use_default: boolean
693
  @type use_default: whether to recognise L{constants.VALUE_DEFAULT}
694
      values as 'to be deleted' values
695
  @param use_none: boolean
696
  @type use_none: whether to recognise C{None} values as 'to be
697
      deleted' values
698
  @rtype: dict
699
  @return: the new parameter dictionary
700

701
  """
702
  params_copy = copy.deepcopy(old_params)
703
  for key, val in update_dict.iteritems():
704
    if ((use_default and val == constants.VALUE_DEFAULT) or
705
        (use_none and val is None)):
706
      try:
707
        del params_copy[key]
708
      except KeyError:
709
        pass
710
    else:
711
      params_copy[key] = val
712
  return params_copy
713

    
714

    
715
def _CheckOutputFields(static, dynamic, selected):
716
  """Checks whether all selected fields are valid.
717

718
  @type static: L{utils.FieldSet}
719
  @param static: static fields set
720
  @type dynamic: L{utils.FieldSet}
721
  @param dynamic: dynamic fields set
722

723
  """
724
  f = utils.FieldSet()
725
  f.Extend(static)
726
  f.Extend(dynamic)
727

    
728
  delta = f.NonMatching(selected)
729
  if delta:
730
    raise errors.OpPrereqError("Unknown output fields selected: %s"
731
                               % ",".join(delta), errors.ECODE_INVAL)
732

    
733

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

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

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

    
748

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

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

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

    
761

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

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

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

    
774

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

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

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

    
792

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

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

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

    
803

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

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

    
816

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

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

    
828

    
829
def _GetClusterDomainSecret():
830
  """Reads the cluster domain secret.
831

832
  """
833
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
834
                               strict=True)
835

    
836

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

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

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

    
852

    
853
def _ExpandItemName(fn, name, kind):
854
  """Expand an item name.
855

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

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

    
869

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

    
874

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

    
879

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

885
  This builds the hook environment from individual variables.
886

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

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

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

    
949
  env["INSTANCE_NIC_COUNT"] = nic_count
950

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

    
959
  env["INSTANCE_DISK_COUNT"] = disk_count
960

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

    
965
  return env
966

    
967

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

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

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

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

    
991

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

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

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

    
1029

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

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

    
1045

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

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

    
1056

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

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

    
1070

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

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

    
1079

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

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

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

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

    
1100

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

    
1104

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

1108
  """
1109

    
1110
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
1111

    
1112

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

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

    
1120

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

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

    
1128

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

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

    
1138
  return []
1139

    
1140

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

    
1144
  for dev in instance.disks:
1145
    cfg.SetDiskID(dev, node_name)
1146

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

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

    
1155
  return faulty
1156

    
1157

    
1158
def _CheckIAllocatorOrNode(lu, iallocator_slot, node_slot):
1159
  """Check the sanity of iallocator and node arguments and use the
1160
  cluster-wide iallocator if appropriate.
1161

1162
  Check that at most one of (iallocator, node) is specified. If none is
1163
  specified, then the LU's opcode's iallocator slot is filled with the
1164
  cluster-wide default iallocator.
1165

1166
  @type iallocator_slot: string
1167
  @param iallocator_slot: the name of the opcode iallocator slot
1168
  @type node_slot: string
1169
  @param node_slot: the name of the opcode target node slot
1170

1171
  """
1172
  node = getattr(lu.op, node_slot, None)
1173
  iallocator = getattr(lu.op, iallocator_slot, None)
1174

    
1175
  if node is not None and iallocator is not None:
1176
    raise errors.OpPrereqError("Do not specify both, iallocator and node.",
1177
                               errors.ECODE_INVAL)
1178
  elif node is None and iallocator is None:
1179
    default_iallocator = lu.cfg.GetDefaultIAllocator()
1180
    if default_iallocator:
1181
      setattr(lu.op, iallocator_slot, default_iallocator)
1182
    else:
1183
      raise errors.OpPrereqError("No iallocator or node given and no"
1184
                                 " cluster-wide default iallocator found."
1185
                                 " Please specify either an iallocator or a"
1186
                                 " node, or set a cluster-wide default"
1187
                                 " iallocator.")
1188

    
1189

    
1190
class LUPostInitCluster(LogicalUnit):
1191
  """Logical unit for running hooks after cluster initialization.
1192

1193
  """
1194
  HPATH = "cluster-init"
1195
  HTYPE = constants.HTYPE_CLUSTER
1196

    
1197
  def BuildHooksEnv(self):
1198
    """Build hooks env.
1199

1200
    """
1201
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1202
    mn = self.cfg.GetMasterNode()
1203
    return env, [], [mn]
1204

    
1205
  def Exec(self, feedback_fn):
1206
    """Nothing to do.
1207

1208
    """
1209
    return True
1210

    
1211

    
1212
class LUDestroyCluster(LogicalUnit):
1213
  """Logical unit for destroying the cluster.
1214

1215
  """
1216
  HPATH = "cluster-destroy"
1217
  HTYPE = constants.HTYPE_CLUSTER
1218

    
1219
  def BuildHooksEnv(self):
1220
    """Build hooks env.
1221

1222
    """
1223
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1224
    return env, [], []
1225

    
1226
  def CheckPrereq(self):
1227
    """Check prerequisites.
1228

1229
    This checks whether the cluster is empty.
1230

1231
    Any errors are signaled by raising errors.OpPrereqError.
1232

1233
    """
1234
    master = self.cfg.GetMasterNode()
1235

    
1236
    nodelist = self.cfg.GetNodeList()
1237
    if len(nodelist) != 1 or nodelist[0] != master:
1238
      raise errors.OpPrereqError("There are still %d node(s) in"
1239
                                 " this cluster." % (len(nodelist) - 1),
1240
                                 errors.ECODE_INVAL)
1241
    instancelist = self.cfg.GetInstanceList()
1242
    if instancelist:
1243
      raise errors.OpPrereqError("There are still %d instance(s) in"
1244
                                 " this cluster." % len(instancelist),
1245
                                 errors.ECODE_INVAL)
1246

    
1247
  def Exec(self, feedback_fn):
1248
    """Destroys the cluster.
1249

1250
    """
1251
    master = self.cfg.GetMasterNode()
1252

    
1253
    # Run post hooks on master node before it's removed
1254
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
1255
    try:
1256
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
1257
    except:
1258
      # pylint: disable-msg=W0702
1259
      self.LogWarning("Errors occurred running hooks on %s" % master)
1260

    
1261
    result = self.rpc.call_node_stop_master(master, False)
1262
    result.Raise("Could not disable the master role")
1263

    
1264
    return master
1265

    
1266

    
1267
def _VerifyCertificate(filename):
1268
  """Verifies a certificate for LUVerifyCluster.
1269

1270
  @type filename: string
1271
  @param filename: Path to PEM file
1272

1273
  """
1274
  try:
1275
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1276
                                           utils.ReadFile(filename))
1277
  except Exception, err: # pylint: disable-msg=W0703
1278
    return (LUVerifyCluster.ETYPE_ERROR,
1279
            "Failed to load X509 certificate %s: %s" % (filename, err))
1280

    
1281
  (errcode, msg) = \
1282
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1283
                                constants.SSL_CERT_EXPIRATION_ERROR)
1284

    
1285
  if msg:
1286
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1287
  else:
1288
    fnamemsg = None
1289

    
1290
  if errcode is None:
1291
    return (None, fnamemsg)
1292
  elif errcode == utils.CERT_WARNING:
1293
    return (LUVerifyCluster.ETYPE_WARNING, fnamemsg)
1294
  elif errcode == utils.CERT_ERROR:
1295
    return (LUVerifyCluster.ETYPE_ERROR, fnamemsg)
1296

    
1297
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1298

    
1299

    
1300
class LUVerifyCluster(LogicalUnit):
1301
  """Verifies the cluster status.
1302

1303
  """
1304
  HPATH = "cluster-verify"
1305
  HTYPE = constants.HTYPE_CLUSTER
1306
  _OP_PARAMS = [
1307
    ("skip_checks", _EmptyList,
1308
     _TListOf(_TElemOf(constants.VERIFY_OPTIONAL_CHECKS))),
1309
    ("verbose", False, _TBool),
1310
    ("error_codes", False, _TBool),
1311
    ("debug_simulate_errors", False, _TBool),
1312
    ]
1313
  REQ_BGL = False
1314

    
1315
  TCLUSTER = "cluster"
1316
  TNODE = "node"
1317
  TINSTANCE = "instance"
1318

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

    
1344
  ETYPE_FIELD = "code"
1345
  ETYPE_ERROR = "ERROR"
1346
  ETYPE_WARNING = "WARNING"
1347

    
1348
  class NodeImage(object):
1349
    """A class representing the logical and physical status of a node.
1350

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

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

    
1395
  def ExpandNames(self):
1396
    self.needed_locks = {
1397
      locking.LEVEL_NODE: locking.ALL_SET,
1398
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1399
    }
1400
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1401

    
1402
  def _Error(self, ecode, item, msg, *args, **kwargs):
1403
    """Format an error message.
1404

1405
    Based on the opcode's error_codes parameter, either format a
1406
    parseable error code, or a simpler error string.
1407

1408
    This must be called only from Exec and functions called from Exec.
1409

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

    
1428
  def _ErrorIf(self, cond, *args, **kwargs):
1429
    """Log an error message if the passed condition is True.
1430

1431
    """
1432
    cond = bool(cond) or self.op.debug_simulate_errors
1433
    if cond:
1434
      self._Error(*args, **kwargs)
1435
    # do not mark the operation as failed for WARN cases only
1436
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1437
      self.bad = self.bad or cond
1438

    
1439
  def _VerifyNode(self, ninfo, nresult):
1440
    """Perform some basic validation on data returned from a node.
1441

1442
      - check the result data structure is well formed and has all the
1443
        mandatory fields
1444
      - check ganeti version
1445

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

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

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

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

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

    
1482
    # node seems compatible, we can actually try to look into its results
1483

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

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

    
1498

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

    
1504
    return True
1505

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

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

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

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

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

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

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

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

1546
    """
1547
    if vg_name is None:
1548
      return
1549

    
1550
    node = ninfo.name
1551
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1552

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

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

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

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

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

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

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

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

    
1617

    
1618
  def _VerifyInstance(self, instance, instanceconfig, node_image):
1619
    """Verify an instance.
1620

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

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

    
1628
    node_vol_should = {}
1629
    instanceconfig.MapLVsByNode(node_vol_should)
1630

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

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

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

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

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

1660
    @type reserved: L{ganeti.utils.FieldSet}
1661
    @param reserved: a FieldSet of reserved volume names
1662

1663
    """
1664
    for node, n_img in node_image.items():
1665
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1666
        # skip non-healthy nodes
1667
        continue
1668
      for volume in n_img.volumes:
1669
        test = ((node not in node_vol_should or
1670
                volume not in node_vol_should[node]) and
1671
                not reserved.Matches(volume))
1672
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1673
                      "volume %s is unknown", volume)
1674

    
1675
  def _VerifyOrphanInstances(self, instancelist, node_image):
1676
    """Verify the list of running instances.
1677

1678
    This checks what instances are running but unknown to the cluster.
1679

1680
    """
1681
    for node, n_img in node_image.items():
1682
      for o_inst in n_img.instances:
1683
        test = o_inst not in instancelist
1684
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1685
                      "instance %s on node %s should not exist", o_inst, node)
1686

    
1687
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1688
    """Verify N+1 Memory Resilience.
1689

1690
    Check that if one single node dies we can still start all the
1691
    instances it was primary for.
1692

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

    
1714
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1715
                       master_files):
1716
    """Verifies and computes the node required file checksums.
1717

1718
    @type ninfo: L{objects.Node}
1719
    @param ninfo: the node to check
1720
    @param nresult: the remote results for the node
1721
    @param file_list: required list of files
1722
    @param local_cksum: dictionary of local files and their checksums
1723
    @param master_files: list of files that only masters should have
1724

1725
    """
1726
    node = ninfo.name
1727
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1728

    
1729
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1730
    test = not isinstance(remote_cksum, dict)
1731
    _ErrorIf(test, self.ENODEFILECHECK, node,
1732
             "node hasn't returned file checksum data")
1733
    if test:
1734
      return
1735

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

    
1758
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1759
                      drbd_map):
1760
    """Verifies and the node DRBD status.
1761

1762
    @type ninfo: L{objects.Node}
1763
    @param ninfo: the node to check
1764
    @param nresult: the remote results for the node
1765
    @param instanceinfo: the dict of instances
1766
    @param drbd_helper: the configured DRBD usermode helper
1767
    @param drbd_map: the DRBD map as returned by
1768
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1769

1770
    """
1771
    node = ninfo.name
1772
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1773

    
1774
    if drbd_helper:
1775
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1776
      test = (helper_result == None)
1777
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1778
               "no drbd usermode helper returned")
1779
      if helper_result:
1780
        status, payload = helper_result
1781
        test = not status
1782
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1783
                 "drbd usermode helper check unsuccessful: %s", payload)
1784
        test = status and (payload != drbd_helper)
1785
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1786
                 "wrong drbd usermode helper: %s", payload)
1787

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

    
1803
    # and now check them
1804
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1805
    test = not isinstance(used_minors, (tuple, list))
1806
    _ErrorIf(test, self.ENODEDRBD, node,
1807
             "cannot parse drbd status file: %s", str(used_minors))
1808
    if test:
1809
      # we cannot check drbd status
1810
      return
1811

    
1812
    for minor, (iname, must_exist) in node_drbd.items():
1813
      test = minor not in used_minors and must_exist
1814
      _ErrorIf(test, self.ENODEDRBD, node,
1815
               "drbd minor %d of instance %s is not active", minor, iname)
1816
    for minor in used_minors:
1817
      test = minor not in node_drbd
1818
      _ErrorIf(test, self.ENODEDRBD, node,
1819
               "unallocated drbd minor %d is in use", minor)
1820

    
1821
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1822
    """Builds the node OS structures.
1823

1824
    @type ninfo: L{objects.Node}
1825
    @param ninfo: the node to check
1826
    @param nresult: the remote results for the node
1827
    @param nimg: the node image object
1828

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

    
1833
    remote_os = nresult.get(constants.NV_OSLIST, None)
1834
    test = (not isinstance(remote_os, list) or
1835
            not compat.all(isinstance(v, list) and len(v) == 7
1836
                           for v in remote_os))
1837

    
1838
    _ErrorIf(test, self.ENODEOS, node,
1839
             "node hasn't returned valid OS data")
1840

    
1841
    nimg.os_fail = test
1842

    
1843
    if test:
1844
      return
1845

    
1846
    os_dict = {}
1847

    
1848
    for (name, os_path, status, diagnose,
1849
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1850

    
1851
      if name not in os_dict:
1852
        os_dict[name] = []
1853

    
1854
      # parameters is a list of lists instead of list of tuples due to
1855
      # JSON lacking a real tuple type, fix it:
1856
      parameters = [tuple(v) for v in parameters]
1857
      os_dict[name].append((os_path, status, diagnose,
1858
                            set(variants), set(parameters), set(api_ver)))
1859

    
1860
    nimg.oslist = os_dict
1861

    
1862
  def _VerifyNodeOS(self, ninfo, nimg, base):
1863
    """Verifies the node OS list.
1864

1865
    @type ninfo: L{objects.Node}
1866
    @param ninfo: the node to check
1867
    @param nimg: the node image object
1868
    @param base: the 'template' node we match against (e.g. from the master)
1869

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

    
1874
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1875

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

    
1909
    # check any missing OSes
1910
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
1911
    _ErrorIf(missing, self.ENODEOS, node,
1912
             "OSes present on reference node %s but missing on this node: %s",
1913
             base.name, utils.CommaJoin(missing))
1914

    
1915
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1916
    """Verifies and updates the node volume data.
1917

1918
    This function will update a L{NodeImage}'s internal structures
1919
    with data from the remote call.
1920

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

1927
    """
1928
    node = ninfo.name
1929
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1930

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

    
1944
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1945
    """Verifies and updates the node instance list.
1946

1947
    If the listing was successful, then updates this node's instance
1948
    list. Otherwise, it marks the RPC call as failed for the instance
1949
    list key.
1950

1951
    @type ninfo: L{objects.Node}
1952
    @param ninfo: the node to check
1953
    @param nresult: the remote results for the node
1954
    @param nimg: the node image object
1955

1956
    """
1957
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1958
    test = not isinstance(idata, list)
1959
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1960
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1961
    if test:
1962
      nimg.hyp_fail = True
1963
    else:
1964
      nimg.instances = idata
1965

    
1966
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1967
    """Verifies and computes a node information map
1968

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

1975
    """
1976
    node = ninfo.name
1977
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1978

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

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

    
2004
  def BuildHooksEnv(self):
2005
    """Build hooks env.
2006

2007
    Cluster-Verify hooks just ran in the post phase and their failure makes
2008
    the output be logged in the verify output and the verification to fail.
2009

2010
    """
2011
    all_nodes = self.cfg.GetNodeList()
2012
    env = {
2013
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2014
      }
2015
    for node in self.cfg.GetAllNodesInfo().values():
2016
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
2017

    
2018
    return env, [], all_nodes
2019

    
2020
  def Exec(self, feedback_fn):
2021
    """Verify integrity of cluster, performing various test on nodes.
2022

2023
    """
2024
    self.bad = False
2025
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2026
    verbose = self.op.verbose
2027
    self._feedback_fn = feedback_fn
2028
    feedback_fn("* Verifying global settings")
2029
    for msg in self.cfg.VerifyConfig():
2030
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
2031

    
2032
    # Check the cluster certificates
2033
    for cert_filename in constants.ALL_CERT_FILES:
2034
      (errcode, msg) = _VerifyCertificate(cert_filename)
2035
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
2036

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

    
2052
    # FIXME: verify OS list
2053
    # do local checksums
2054
    master_files = [constants.CLUSTER_CONF_FILE]
2055
    master_node = self.master_node = self.cfg.GetMasterNode()
2056
    master_ip = self.cfg.GetMasterIP()
2057

    
2058
    file_names = ssconf.SimpleStore().GetFileList()
2059
    file_names.extend(constants.ALL_CERT_FILES)
2060
    file_names.extend(master_files)
2061
    if cluster.modify_etc_hosts:
2062
      file_names.append(constants.ETC_HOSTS)
2063

    
2064
    local_checksums = utils.FingerprintFiles(file_names)
2065

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

    
2084
    if vg_name is not None:
2085
      node_verify_param[constants.NV_VGLIST] = None
2086
      node_verify_param[constants.NV_LVLIST] = vg_name
2087
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2088
      node_verify_param[constants.NV_DRBDLIST] = None
2089

    
2090
    if drbd_helper:
2091
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2092

    
2093
    # Build our expected cluster state
2094
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2095
                                                 name=node.name))
2096
                      for node in nodeinfo)
2097

    
2098
    for instance in instancelist:
2099
      inst_config = instanceinfo[instance]
2100

    
2101
      for nname in inst_config.all_nodes:
2102
        if nname not in node_image:
2103
          # ghost node
2104
          gnode = self.NodeImage(name=nname)
2105
          gnode.ghost = True
2106
          node_image[nname] = gnode
2107

    
2108
      inst_config.MapLVsByNode(node_vol_should)
2109

    
2110
      pnode = inst_config.primary_node
2111
      node_image[pnode].pinst.append(instance)
2112

    
2113
      for snode in inst_config.secondary_nodes:
2114
        nimg = node_image[snode]
2115
        nimg.sinst.append(instance)
2116
        if pnode not in nimg.sbp:
2117
          nimg.sbp[pnode] = []
2118
        nimg.sbp[pnode].append(instance)
2119

    
2120
    # At this point, we have the in-memory data structures complete,
2121
    # except for the runtime information, which we'll gather next
2122

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

    
2132
    all_drbd_map = self.cfg.ComputeDRBDMap()
2133

    
2134
    feedback_fn("* Verifying node status")
2135

    
2136
    refos_img = None
2137

    
2138
    for node_i in nodeinfo:
2139
      node = node_i.name
2140
      nimg = node_image[node]
2141

    
2142
      if node_i.offline:
2143
        if verbose:
2144
          feedback_fn("* Skipping offline node %s" % (node,))
2145
        n_offline += 1
2146
        continue
2147

    
2148
      if node == master_node:
2149
        ntype = "master"
2150
      elif node_i.master_candidate:
2151
        ntype = "master candidate"
2152
      elif node_i.drained:
2153
        ntype = "drained"
2154
        n_drained += 1
2155
      else:
2156
        ntype = "regular"
2157
      if verbose:
2158
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2159

    
2160
      msg = all_nvinfo[node].fail_msg
2161
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2162
      if msg:
2163
        nimg.rpc_fail = True
2164
        continue
2165

    
2166
      nresult = all_nvinfo[node].payload
2167

    
2168
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2169
      self._VerifyNodeNetwork(node_i, nresult)
2170
      self._VerifyNodeLVM(node_i, nresult, vg_name)
2171
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2172
                            master_files)
2173
      self._VerifyNodeDrbd(node_i, nresult, instanceinfo, drbd_helper,
2174
                           all_drbd_map)
2175
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2176

    
2177
      self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2178
      self._UpdateNodeInstances(node_i, nresult, nimg)
2179
      self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2180
      self._UpdateNodeOS(node_i, nresult, nimg)
2181
      if not nimg.os_fail:
2182
        if refos_img is None:
2183
          refos_img = nimg
2184
        self._VerifyNodeOS(node_i, nimg, refos_img)
2185

    
2186
    feedback_fn("* Verifying instance status")
2187
    for instance in instancelist:
2188
      if verbose:
2189
        feedback_fn("* Verifying instance %s" % instance)
2190
      inst_config = instanceinfo[instance]
2191
      self._VerifyInstance(instance, inst_config, node_image)
2192
      inst_nodes_offline = []
2193

    
2194
      pnode = inst_config.primary_node
2195
      pnode_img = node_image[pnode]
2196
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2197
               self.ENODERPC, pnode, "instance %s, connection to"
2198
               " primary node failed", instance)
2199

    
2200
      if pnode_img.offline:
2201
        inst_nodes_offline.append(pnode)
2202

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

    
2215
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2216
        i_non_a_balanced.append(instance)
2217

    
2218
      for snode in inst_config.secondary_nodes:
2219
        s_img = node_image[snode]
2220
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2221
                 "instance %s, connection to secondary node failed", instance)
2222

    
2223
        if s_img.offline:
2224
          inst_nodes_offline.append(snode)
2225

    
2226
      # warn that the instance lives on offline nodes
2227
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2228
               "instance lives on offline node(s) %s",
2229
               utils.CommaJoin(inst_nodes_offline))
2230
      # ... or ghost nodes
2231
      for node in inst_config.all_nodes:
2232
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2233
                 "instance lives on ghost node %s", node)
2234

    
2235
    feedback_fn("* Verifying orphan volumes")
2236
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2237
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2238

    
2239
    feedback_fn("* Verifying orphan instances")
2240
    self._VerifyOrphanInstances(instancelist, node_image)
2241

    
2242
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2243
      feedback_fn("* Verifying N+1 Memory redundancy")
2244
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2245

    
2246
    feedback_fn("* Other Notes")
2247
    if i_non_redundant:
2248
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2249
                  % len(i_non_redundant))
2250

    
2251
    if i_non_a_balanced:
2252
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2253
                  % len(i_non_a_balanced))
2254

    
2255
    if n_offline:
2256
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2257

    
2258
    if n_drained:
2259
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2260

    
2261
    return not self.bad
2262

    
2263
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2264
    """Analyze the post-hooks' result
2265

2266
    This method analyses the hook result, handles it, and sends some
2267
    nicely-formatted feedback back to the user.
2268

2269
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2270
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2271
    @param hooks_results: the results of the multi-node hooks rpc call
2272
    @param feedback_fn: function used send feedback back to the caller
2273
    @param lu_result: previous Exec result
2274
    @return: the new Exec result, based on the previous result
2275
        and hook results
2276

2277
    """
2278
    # We only really run POST phase hooks, and are only interested in
2279
    # their results
2280
    if phase == constants.HOOKS_PHASE_POST:
2281
      # Used to change hooks' output to proper indentation
2282
      indent_re = re.compile('^', re.M)
2283
      feedback_fn("* Hooks Results")
2284
      assert hooks_results, "invalid result from hooks"
2285

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

    
2307
      return lu_result
2308

    
2309

    
2310
class LUVerifyDisks(NoHooksLU):
2311
  """Verifies the cluster disks status.
2312

2313
  """
2314
  REQ_BGL = False
2315

    
2316
  def ExpandNames(self):
2317
    self.needed_locks = {
2318
      locking.LEVEL_NODE: locking.ALL_SET,
2319
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2320
    }
2321
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2322

    
2323
  def Exec(self, feedback_fn):
2324
    """Verify integrity of cluster disks.
2325

2326
    @rtype: tuple of three items
2327
    @return: a tuple of (dict of node-to-node_error, list of instances
2328
        which need activate-disks, dict of instance: (node, volume) for
2329
        missing volumes
2330

2331
    """
2332
    result = res_nodes, res_instances, res_missing = {}, [], {}
2333

    
2334
    vg_name = self.cfg.GetVGName()
2335
    nodes = utils.NiceSort(self.cfg.GetNodeList())
2336
    instances = [self.cfg.GetInstanceInfo(name)
2337
                 for name in self.cfg.GetInstanceList()]
2338

    
2339
    nv_dict = {}
2340
    for inst in instances:
2341
      inst_lvs = {}
2342
      if (not inst.admin_up or
2343
          inst.disk_template not in constants.DTS_NET_MIRROR):
2344
        continue
2345
      inst.MapLVsByNode(inst_lvs)
2346
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2347
      for node, vol_list in inst_lvs.iteritems():
2348
        for vol in vol_list:
2349
          nv_dict[(node, vol)] = inst
2350

    
2351
    if not nv_dict:
2352
      return result
2353

    
2354
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
2355

    
2356
    for node in nodes:
2357
      # node_volume
2358
      node_res = node_lvs[node]
2359
      if node_res.offline:
2360
        continue
2361
      msg = node_res.fail_msg
2362
      if msg:
2363
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2364
        res_nodes[node] = msg
2365
        continue
2366

    
2367
      lvs = node_res.payload
2368
      for lv_name, (_, _, lv_online) in lvs.items():
2369
        inst = nv_dict.pop((node, lv_name), None)
2370
        if (not lv_online and inst is not None
2371
            and inst.name not in res_instances):
2372
          res_instances.append(inst.name)
2373

    
2374
    # any leftover items in nv_dict are missing LVs, let's arrange the
2375
    # data better
2376
    for key, inst in nv_dict.iteritems():
2377
      if inst.name not in res_missing:
2378
        res_missing[inst.name] = []
2379
      res_missing[inst.name].append(key)
2380

    
2381
    return result
2382

    
2383

    
2384
class LURepairDiskSizes(NoHooksLU):
2385
  """Verifies the cluster disks sizes.
2386

2387
  """
2388
  _OP_PARAMS = [("instances", _EmptyList, _TListOf(_TNonEmptyString))]
2389
  REQ_BGL = False
2390

    
2391
  def ExpandNames(self):
2392
    if self.op.instances:
2393
      self.wanted_names = []
2394
      for name in self.op.instances:
2395
        full_name = _ExpandInstanceName(self.cfg, name)
2396
        self.wanted_names.append(full_name)
2397
      self.needed_locks = {
2398
        locking.LEVEL_NODE: [],
2399
        locking.LEVEL_INSTANCE: self.wanted_names,
2400
        }
2401
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2402
    else:
2403
      self.wanted_names = None
2404
      self.needed_locks = {
2405
        locking.LEVEL_NODE: locking.ALL_SET,
2406
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2407
        }
2408
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2409

    
2410
  def DeclareLocks(self, level):
2411
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2412
      self._LockInstancesNodes(primary_only=True)
2413

    
2414
  def CheckPrereq(self):
2415
    """Check prerequisites.
2416

2417
    This only checks the optional instance list against the existing names.
2418

2419
    """
2420
    if self.wanted_names is None:
2421
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2422

    
2423
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2424
                             in self.wanted_names]
2425

    
2426
  def _EnsureChildSizes(self, disk):
2427
    """Ensure children of the disk have the needed disk size.
2428

2429
    This is valid mainly for DRBD8 and fixes an issue where the
2430
    children have smaller disk size.
2431

2432
    @param disk: an L{ganeti.objects.Disk} object
2433

2434
    """
2435
    if disk.dev_type == constants.LD_DRBD8:
2436
      assert disk.children, "Empty children for DRBD8?"
2437
      fchild = disk.children[0]
2438
      mismatch = fchild.size < disk.size
2439
      if mismatch:
2440
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2441
                     fchild.size, disk.size)
2442
        fchild.size = disk.size
2443

    
2444
      # and we recurse on this child only, not on the metadev
2445
      return self._EnsureChildSizes(fchild) or mismatch
2446
    else:
2447
      return False
2448

    
2449
  def Exec(self, feedback_fn):
2450
    """Verify the size of cluster disks.
2451

2452
    """
2453
    # TODO: check child disks too
2454
    # TODO: check differences in size between primary/secondary nodes
2455
    per_node_disks = {}
2456
    for instance in self.wanted_instances:
2457
      pnode = instance.primary_node
2458
      if pnode not in per_node_disks:
2459
        per_node_disks[pnode] = []
2460
      for idx, disk in enumerate(instance.disks):
2461
        per_node_disks[pnode].append((instance, idx, disk))
2462

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

    
2499

    
2500
class LURenameCluster(LogicalUnit):
2501
  """Rename the cluster.
2502

2503
  """
2504
  HPATH = "cluster-rename"
2505
  HTYPE = constants.HTYPE_CLUSTER
2506
  _OP_PARAMS = [("name", _NoDefault, _TNonEmptyString)]
2507

    
2508
  def BuildHooksEnv(self):
2509
    """Build hooks env.
2510

2511
    """
2512
    env = {
2513
      "OP_TARGET": self.cfg.GetClusterName(),
2514
      "NEW_NAME": self.op.name,
2515
      }
2516
    mn = self.cfg.GetMasterNode()
2517
    all_nodes = self.cfg.GetNodeList()
2518
    return env, [mn], all_nodes
2519

    
2520
  def CheckPrereq(self):
2521
    """Verify that the passed name is a valid one.
2522

2523
    """
2524
    hostname = netutils.GetHostname(name=self.op.name,
2525
                                    family=self.cfg.GetPrimaryIPFamily())
2526

    
2527
    new_name = hostname.name
2528
    self.ip = new_ip = hostname.ip
2529
    old_name = self.cfg.GetClusterName()
2530
    old_ip = self.cfg.GetMasterIP()
2531
    if new_name == old_name and new_ip == old_ip:
2532
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2533
                                 " cluster has changed",
2534
                                 errors.ECODE_INVAL)
2535
    if new_ip != old_ip:
2536
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2537
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2538
                                   " reachable on the network" %
2539
                                   new_ip, errors.ECODE_NOTUNIQUE)
2540

    
2541
    self.op.name = new_name
2542

    
2543
  def Exec(self, feedback_fn):
2544
    """Rename the cluster.
2545

2546
    """
2547
    clustername = self.op.name
2548
    ip = self.ip
2549

    
2550
    # shutdown the master IP
2551
    master = self.cfg.GetMasterNode()
2552
    result = self.rpc.call_node_stop_master(master, False)
2553
    result.Raise("Could not disable the master role")
2554

    
2555
    try:
2556
      cluster = self.cfg.GetClusterInfo()
2557
      cluster.cluster_name = clustername
2558
      cluster.master_ip = ip
2559
      self.cfg.Update(cluster, feedback_fn)
2560

    
2561
      # update the known hosts file
2562
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2563
      node_list = self.cfg.GetNodeList()
2564
      try:
2565
        node_list.remove(master)
2566
      except ValueError:
2567
        pass
2568
      result = self.rpc.call_upload_file(node_list,
2569
                                         constants.SSH_KNOWN_HOSTS_FILE)
2570
      for to_node, to_result in result.iteritems():
2571
        msg = to_result.fail_msg
2572
        if msg:
2573
          msg = ("Copy of file %s to node %s failed: %s" %
2574
                 (constants.SSH_KNOWN_HOSTS_FILE, to_node, msg))
2575
          self.proc.LogWarning(msg)
2576

    
2577
    finally:
2578
      result = self.rpc.call_node_start_master(master, False, False)
2579
      msg = result.fail_msg
2580
      if msg:
2581
        self.LogWarning("Could not re-enable the master role on"
2582
                        " the master, please restart manually: %s", msg)
2583

    
2584
    return clustername
2585

    
2586

    
2587
class LUSetClusterParams(LogicalUnit):
2588
  """Change the parameters of the cluster.
2589

2590
  """
2591
  HPATH = "cluster-modify"
2592
  HTYPE = constants.HTYPE_CLUSTER
2593
  _OP_PARAMS = [
2594
    ("vg_name", None, _TMaybeString),
2595
    ("enabled_hypervisors", None,
2596
     _TOr(_TAnd(_TListOf(_TElemOf(constants.HYPER_TYPES)), _TTrue), _TNone)),
2597
    ("hvparams", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2598
    ("beparams", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2599
    ("os_hvp", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2600
    ("osparams", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2601
    ("candidate_pool_size", None, _TOr(_TStrictPositiveInt, _TNone)),
2602
    ("uid_pool", None, _NoType),
2603
    ("add_uids", None, _NoType),
2604
    ("remove_uids", None, _NoType),
2605
    ("maintain_node_health", None, _TMaybeBool),
2606
    ("nicparams", None, _TOr(_TDict, _TNone)),
2607
    ("drbd_helper", None, _TOr(_TString, _TNone)),
2608
    ("default_iallocator", None, _TMaybeString),
2609
    ("reserved_lvs", None, _TOr(_TListOf(_TNonEmptyString), _TNone)),
2610
    ]
2611
  REQ_BGL = False
2612

    
2613
  def CheckArguments(self):
2614
    """Check parameters
2615

2616
    """
2617
    if self.op.uid_pool:
2618
      uidpool.CheckUidPool(self.op.uid_pool)
2619

    
2620
    if self.op.add_uids:
2621
      uidpool.CheckUidPool(self.op.add_uids)
2622

    
2623
    if self.op.remove_uids:
2624
      uidpool.CheckUidPool(self.op.remove_uids)
2625

    
2626
  def ExpandNames(self):
2627
    # FIXME: in the future maybe other cluster params won't require checking on
2628
    # all nodes to be modified.
2629
    self.needed_locks = {
2630
      locking.LEVEL_NODE: locking.ALL_SET,
2631
    }
2632
    self.share_locks[locking.LEVEL_NODE] = 1
2633

    
2634
  def BuildHooksEnv(self):
2635
    """Build hooks env.
2636

2637
    """
2638
    env = {
2639
      "OP_TARGET": self.cfg.GetClusterName(),
2640
      "NEW_VG_NAME": self.op.vg_name,
2641
      }
2642
    mn = self.cfg.GetMasterNode()
2643
    return env, [mn], [mn]
2644

    
2645
  def CheckPrereq(self):
2646
    """Check prerequisites.
2647

2648
    This checks whether the given params don't conflict and
2649
    if the given volume group is valid.
2650

2651
    """
2652
    if self.op.vg_name is not None and not self.op.vg_name:
2653
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2654
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2655
                                   " instances exist", errors.ECODE_INVAL)
2656

    
2657
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
2658
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
2659
        raise errors.OpPrereqError("Cannot disable drbd helper while"
2660
                                   " drbd-based instances exist",
2661
                                   errors.ECODE_INVAL)
2662

    
2663
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2664

    
2665
    # if vg_name not None, checks given volume group on all nodes
2666
    if self.op.vg_name:
2667
      vglist = self.rpc.call_vg_list(node_list)
2668
      for node in node_list:
2669
        msg = vglist[node].fail_msg
2670
        if msg:
2671
          # ignoring down node
2672
          self.LogWarning("Error while gathering data on node %s"
2673
                          " (ignoring node): %s", node, msg)
2674
          continue
2675
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2676
                                              self.op.vg_name,
2677
                                              constants.MIN_VG_SIZE)
2678
        if vgstatus:
2679
          raise errors.OpPrereqError("Error on node '%s': %s" %
2680
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2681

    
2682
    if self.op.drbd_helper:
2683
      # checks given drbd helper on all nodes
2684
      helpers = self.rpc.call_drbd_helper(node_list)
2685
      for node in node_list:
2686
        ninfo = self.cfg.GetNodeInfo(node)
2687
        if ninfo.offline:
2688
          self.LogInfo("Not checking drbd helper on offline node %s", node)
2689
          continue
2690
        msg = helpers[node].fail_msg
2691
        if msg:
2692
          raise errors.OpPrereqError("Error checking drbd helper on node"
2693
                                     " '%s': %s" % (node, msg),
2694
                                     errors.ECODE_ENVIRON)
2695
        node_helper = helpers[node].payload
2696
        if node_helper != self.op.drbd_helper:
2697
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
2698
                                     (node, node_helper), errors.ECODE_ENVIRON)
2699

    
2700
    self.cluster = cluster = self.cfg.GetClusterInfo()
2701
    # validate params changes
2702
    if self.op.beparams:
2703
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2704
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2705

    
2706
    if self.op.nicparams:
2707
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2708
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2709
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2710
      nic_errors = []
2711

    
2712
      # check all instances for consistency
2713
      for instance in self.cfg.GetAllInstancesInfo().values():
2714
        for nic_idx, nic in enumerate(instance.nics):
2715
          params_copy = copy.deepcopy(nic.nicparams)
2716
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2717

    
2718
          # check parameter syntax
2719
          try:
2720
            objects.NIC.CheckParameterSyntax(params_filled)
2721
          except errors.ConfigurationError, err:
2722
            nic_errors.append("Instance %s, nic/%d: %s" %
2723
                              (instance.name, nic_idx, err))
2724

    
2725
          # if we're moving instances to routed, check that they have an ip
2726
          target_mode = params_filled[constants.NIC_MODE]
2727
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2728
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2729
                              (instance.name, nic_idx))
2730
      if nic_errors:
2731
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2732
                                   "\n".join(nic_errors))
2733

    
2734
    # hypervisor list/parameters
2735
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2736
    if self.op.hvparams:
2737
      for hv_name, hv_dict in self.op.hvparams.items():
2738
        if hv_name not in self.new_hvparams:
2739
          self.new_hvparams[hv_name] = hv_dict
2740
        else:
2741
          self.new_hvparams[hv_name].update(hv_dict)
2742

    
2743
    # os hypervisor parameters
2744
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2745
    if self.op.os_hvp:
2746
      for os_name, hvs in self.op.os_hvp.items():
2747
        if os_name not in self.new_os_hvp:
2748
          self.new_os_hvp[os_name] = hvs
2749
        else:
2750
          for hv_name, hv_dict in hvs.items():
2751
            if hv_name not in self.new_os_hvp[os_name]:
2752
              self.new_os_hvp[os_name][hv_name] = hv_dict
2753
            else:
2754
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2755

    
2756
    # os parameters
2757
    self.new_osp = objects.FillDict(cluster.osparams, {})
2758
    if self.op.osparams:
2759
      for os_name, osp in self.op.osparams.items():
2760
        if os_name not in self.new_osp:
2761
          self.new_osp[os_name] = {}
2762

    
2763
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2764
                                                  use_none=True)
2765

    
2766
        if not self.new_osp[os_name]:
2767
          # we removed all parameters
2768
          del self.new_osp[os_name]
2769
        else:
2770
          # check the parameter validity (remote check)
2771
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
2772
                         os_name, self.new_osp[os_name])
2773

    
2774
    # changes to the hypervisor list
2775
    if self.op.enabled_hypervisors is not None:
2776
      self.hv_list = self.op.enabled_hypervisors
2777
      for hv in self.hv_list:
2778
        # if the hypervisor doesn't already exist in the cluster
2779
        # hvparams, we initialize it to empty, and then (in both
2780
        # cases) we make sure to fill the defaults, as we might not
2781
        # have a complete defaults list if the hypervisor wasn't
2782
        # enabled before
2783
        if hv not in new_hvp:
2784
          new_hvp[hv] = {}
2785
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2786
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2787
    else:
2788
      self.hv_list = cluster.enabled_hypervisors
2789

    
2790
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2791
      # either the enabled list has changed, or the parameters have, validate
2792
      for hv_name, hv_params in self.new_hvparams.items():
2793
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2794
            (self.op.enabled_hypervisors and
2795
             hv_name in self.op.enabled_hypervisors)):
2796
          # either this is a new hypervisor, or its parameters have changed
2797
          hv_class = hypervisor.GetHypervisor(hv_name)
2798
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2799
          hv_class.CheckParameterSyntax(hv_params)
2800
          _CheckHVParams(self, node_list, hv_name, hv_params)
2801

    
2802
    if self.op.os_hvp:
2803
      # no need to check any newly-enabled hypervisors, since the
2804
      # defaults have already been checked in the above code-block
2805
      for os_name, os_hvp in self.new_os_hvp.items():
2806
        for hv_name, hv_params in os_hvp.items():
2807
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2808
          # we need to fill in the new os_hvp on top of the actual hv_p
2809
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2810
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2811
          hv_class = hypervisor.GetHypervisor(hv_name)
2812
          hv_class.CheckParameterSyntax(new_osp)
2813
          _CheckHVParams(self, node_list, hv_name, new_osp)
2814

    
2815
    if self.op.default_iallocator:
2816
      alloc_script = utils.FindFile(self.op.default_iallocator,
2817
                                    constants.IALLOCATOR_SEARCH_PATH,
2818
                                    os.path.isfile)
2819
      if alloc_script is None:
2820
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
2821
                                   " specified" % self.op.default_iallocator,
2822
                                   errors.ECODE_INVAL)
2823

    
2824
  def Exec(self, feedback_fn):
2825
    """Change the parameters of the cluster.
2826

2827
    """
2828
    if self.op.vg_name is not None:
2829
      new_volume = self.op.vg_name
2830
      if not new_volume:
2831
        new_volume = None
2832
      if new_volume != self.cfg.GetVGName():
2833
        self.cfg.SetVGName(new_volume)
2834
      else:
2835
        feedback_fn("Cluster LVM configuration already in desired"
2836
                    " state, not changing")
2837
    if self.op.drbd_helper is not None:
2838
      new_helper = self.op.drbd_helper
2839
      if not new_helper:
2840
        new_helper = None
2841
      if new_helper != self.cfg.GetDRBDHelper():
2842
        self.cfg.SetDRBDHelper(new_helper)
2843
      else:
2844
        feedback_fn("Cluster DRBD helper already in desired state,"
2845
                    " not changing")
2846
    if self.op.hvparams:
2847
      self.cluster.hvparams = self.new_hvparams
2848
    if self.op.os_hvp:
2849
      self.cluster.os_hvp = self.new_os_hvp
2850
    if self.op.enabled_hypervisors is not None:
2851
      self.cluster.hvparams = self.new_hvparams
2852
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2853
    if self.op.beparams:
2854
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2855
    if self.op.nicparams:
2856
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2857
    if self.op.osparams:
2858
      self.cluster.osparams = self.new_osp
2859

    
2860
    if self.op.candidate_pool_size is not None:
2861
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2862
      # we need to update the pool size here, otherwise the save will fail
2863
      _AdjustCandidatePool(self, [])
2864

    
2865
    if self.op.maintain_node_health is not None:
2866
      self.cluster.maintain_node_health = self.op.maintain_node_health
2867

    
2868
    if self.op.add_uids is not None:
2869
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2870

    
2871
    if self.op.remove_uids is not None:
2872
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2873

    
2874
    if self.op.uid_pool is not None:
2875
      self.cluster.uid_pool = self.op.uid_pool
2876

    
2877
    if self.op.default_iallocator is not None:
2878
      self.cluster.default_iallocator = self.op.default_iallocator
2879

    
2880
    if self.op.reserved_lvs is not None:
2881
      self.cluster.reserved_lvs = self.op.reserved_lvs
2882

    
2883
    self.cfg.Update(self.cluster, feedback_fn)
2884

    
2885

    
2886
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
2887
  """Distribute additional files which are part of the cluster configuration.
2888

2889
  ConfigWriter takes care of distributing the config and ssconf files, but
2890
  there are more files which should be distributed to all nodes. This function
2891
  makes sure those are copied.
2892

2893
  @param lu: calling logical unit
2894
  @param additional_nodes: list of nodes not in the config to distribute to
2895

2896
  """
2897
  # 1. Gather target nodes
2898
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2899
  dist_nodes = lu.cfg.GetOnlineNodeList()
2900
  if additional_nodes is not None:
2901
    dist_nodes.extend(additional_nodes)
2902
  if myself.name in dist_nodes:
2903
    dist_nodes.remove(myself.name)
2904

    
2905
  # 2. Gather files to distribute
2906
  dist_files = set([constants.ETC_HOSTS,
2907
                    constants.SSH_KNOWN_HOSTS_FILE,
2908
                    constants.RAPI_CERT_FILE,
2909
                    constants.RAPI_USERS_FILE,
2910
                    constants.CONFD_HMAC_KEY,
2911
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
2912
                   ])
2913

    
2914
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2915
  for hv_name in enabled_hypervisors:
2916
    hv_class = hypervisor.GetHypervisor(hv_name)
2917
    dist_files.update(hv_class.GetAncillaryFiles())
2918

    
2919
  # 3. Perform the files upload
2920
  for fname in dist_files:
2921
    if os.path.exists(fname):
2922
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2923
      for to_node, to_result in result.items():
2924
        msg = to_result.fail_msg
2925
        if msg:
2926
          msg = ("Copy of file %s to node %s failed: %s" %
2927
                 (fname, to_node, msg))
2928
          lu.proc.LogWarning(msg)
2929

    
2930

    
2931
class LURedistributeConfig(NoHooksLU):
2932
  """Force the redistribution of cluster configuration.
2933

2934
  This is a very simple LU.
2935

2936
  """
2937
  REQ_BGL = False
2938

    
2939
  def ExpandNames(self):
2940
    self.needed_locks = {
2941
      locking.LEVEL_NODE: locking.ALL_SET,
2942
    }
2943
    self.share_locks[locking.LEVEL_NODE] = 1
2944

    
2945
  def Exec(self, feedback_fn):
2946
    """Redistribute the configuration.
2947

2948
    """
2949
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2950
    _RedistributeAncillaryFiles(self)
2951

    
2952

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

2956
  """
2957
  if not instance.disks or disks is not None and not disks:
2958
    return True
2959

    
2960
  disks = _ExpandCheckDisks(instance, disks)
2961

    
2962
  if not oneshot:
2963
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2964

    
2965
  node = instance.primary_node
2966

    
2967
  for dev in disks:
2968
    lu.cfg.SetDiskID(dev, node)
2969

    
2970
  # TODO: Convert to utils.Retry
2971

    
2972
  retries = 0
2973
  degr_retries = 10 # in seconds, as we sleep 1 second each time
2974
  while True:
2975
    max_time = 0
2976
    done = True
2977
    cumul_degraded = False
2978
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
2979
    msg = rstats.fail_msg
2980
    if msg:
2981
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
2982
      retries += 1
2983
      if retries >= 10:
2984
        raise errors.RemoteError("Can't contact node %s for mirror data,"
2985
                                 " aborting." % node)
2986
      time.sleep(6)
2987
      continue
2988
    rstats = rstats.payload
2989
    retries = 0
2990
    for i, mstat in enumerate(rstats):
2991
      if mstat is None:
2992
        lu.LogWarning("Can't compute data for node %s/%s",
2993
                           node, disks[i].iv_name)
2994
        continue
2995

    
2996
      cumul_degraded = (cumul_degraded or
2997
                        (mstat.is_degraded and mstat.sync_percent is None))
2998
      if mstat.sync_percent is not None:
2999
        done = False
3000
        if mstat.estimated_time is not None:
3001
          rem_time = ("%s remaining (estimated)" %
3002
                      utils.FormatSeconds(mstat.estimated_time))
3003
          max_time = mstat.estimated_time
3004
        else:
3005
          rem_time = "no time estimate"
3006
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3007
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3008

    
3009
    # if we're done but degraded, let's do a few small retries, to
3010
    # make sure we see a stable and not transient situation; therefore
3011
    # we force restart of the loop
3012
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3013
      logging.info("Degraded disks found, %d retries left", degr_retries)
3014
      degr_retries -= 1
3015
      time.sleep(1)
3016
      continue
3017

    
3018
    if done or oneshot:
3019
      break
3020

    
3021
    time.sleep(min(60, max_time))
3022

    
3023
  if done:
3024
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3025
  return not cumul_degraded
3026

    
3027

    
3028
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3029
  """Check that mirrors are not degraded.
3030

3031
  The ldisk parameter, if True, will change the test from the
3032
  is_degraded attribute (which represents overall non-ok status for
3033
  the device(s)) to the ldisk (representing the local storage status).
3034

3035
  """
3036
  lu.cfg.SetDiskID(dev, node)
3037

    
3038
  result = True
3039

    
3040
  if on_primary or dev.AssembleOnSecondary():
3041
    rstats = lu.rpc.call_blockdev_find(node, dev)
3042
    msg = rstats.fail_msg
3043
    if msg:
3044
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3045
      result = False
3046
    elif not rstats.payload:
3047
      lu.LogWarning("Can't find disk on node %s", node)
3048
      result = False
3049
    else:
3050
      if ldisk:
3051
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3052
      else:
3053
        result = result and not rstats.payload.is_degraded
3054

    
3055
  if dev.children:
3056
    for child in dev.children:
3057
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3058

    
3059
  return result
3060

    
3061

    
3062
class LUDiagnoseOS(NoHooksLU):
3063
  """Logical unit for OS diagnose/query.
3064

3065
  """
3066
  _OP_PARAMS = [
3067
    _POutputFields,
3068
    ("names", _EmptyList, _TListOf(_TNonEmptyString)),
3069
    ]
3070
  REQ_BGL = False
3071
  _FIELDS_STATIC = utils.FieldSet()
3072
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status", "variants",
3073
                                   "parameters", "api_versions")
3074

    
3075
  def CheckArguments(self):
3076
    if self.op.names:
3077
      raise errors.OpPrereqError("Selective OS query not supported",
3078
                                 errors.ECODE_INVAL)
3079

    
3080
    _CheckOutputFields(static=self._FIELDS_STATIC,
3081
                       dynamic=self._FIELDS_DYNAMIC,
3082
                       selected=self.op.output_fields)
3083

    
3084
  def ExpandNames(self):
3085
    # Lock all nodes, in shared mode
3086
    # Temporary removal of locks, should be reverted later
3087
    # TODO: reintroduce locks when they are lighter-weight
3088
    self.needed_locks = {}
3089
    #self.share_locks[locking.LEVEL_NODE] = 1
3090
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3091

    
3092
  @staticmethod
3093
  def _DiagnoseByOS(rlist):
3094
    """Remaps a per-node return list into an a per-os per-node dictionary
3095

3096
    @param rlist: a map with node names as keys and OS objects as values
3097

3098
    @rtype: dict
3099
    @return: a dictionary with osnames as keys and as value another
3100
        map, with nodes as keys and tuples of (path, status, diagnose,
3101
        variants, parameters, api_versions) as values, eg::
3102

3103
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3104
                                     (/srv/..., False, "invalid api")],
3105
                           "node2": [(/srv/..., True, "", [], [])]}
3106
          }
3107

3108
    """
3109
    all_os = {}
3110
    # we build here the list of nodes that didn't fail the RPC (at RPC
3111
    # level), so that nodes with a non-responding node daemon don't
3112
    # make all OSes invalid
3113
    good_nodes = [node_name for node_name in rlist
3114
                  if not rlist[node_name].fail_msg]
3115
    for node_name, nr in rlist.items():
3116
      if nr.fail_msg or not nr.payload:
3117
        continue
3118
      for (name, path, status, diagnose, variants,
3119
           params, api_versions) in nr.payload:
3120
        if name not in all_os:
3121
          # build a list of nodes for this os containing empty lists
3122
          # for each node in node_list
3123
          all_os[name] = {}
3124
          for nname in good_nodes:
3125
            all_os[name][nname] = []
3126
        # convert params from [name, help] to (name, help)
3127
        params = [tuple(v) for v in params]
3128
        all_os[name][node_name].append((path, status, diagnose,
3129
                                        variants, params, api_versions))
3130
    return all_os
3131

    
3132
  def Exec(self, feedback_fn):
3133
    """Compute the list of OSes.
3134

3135
    """
3136
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
3137
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3138
    pol = self._DiagnoseByOS(node_data)
3139
    output = []
3140

    
3141
    for os_name, os_data in pol.items():
3142
      row = []
3143
      valid = True
3144
      (variants, params, api_versions) = null_state = (set(), set(), set())
3145
      for idx, osl in enumerate(os_data.values()):
3146
        valid = bool(valid and osl and osl[0][1])
3147
        if not valid:
3148
          (variants, params, api_versions) = null_state
3149
          break
3150
        node_variants, node_params, node_api = osl[0][3:6]
3151
        if idx == 0: # first entry
3152
          variants = set(node_variants)
3153
          params = set(node_params)
3154
          api_versions = set(node_api)
3155
        else: # keep consistency
3156
          variants.intersection_update(node_variants)
3157
          params.intersection_update(node_params)
3158
          api_versions.intersection_update(node_api)
3159

    
3160
      for field in self.op.output_fields:
3161
        if field == "name":
3162
          val = os_name
3163
        elif field == "valid":
3164
          val = valid
3165
        elif field == "node_status":
3166
          # this is just a copy of the dict
3167
          val = {}
3168
          for node_name, nos_list in os_data.items():
3169
            val[node_name] = nos_list
3170
        elif field == "variants":
3171
          val = list(variants)
3172
        elif field == "parameters":
3173
          val = list(params)
3174
        elif field == "api_versions":
3175
          val = list(api_versions)
3176
        else:
3177
          raise errors.ParameterError(field)
3178
        row.append(val)
3179
      output.append(row)
3180

    
3181
    return output
3182

    
3183

    
3184
class LURemoveNode(LogicalUnit):
3185
  """Logical unit for removing a node.
3186

3187
  """
3188
  HPATH = "node-remove"
3189
  HTYPE = constants.HTYPE_NODE
3190
  _OP_PARAMS = [
3191
    _PNodeName,
3192
    ]
3193

    
3194
  def BuildHooksEnv(self):
3195
    """Build hooks env.
3196

3197
    This doesn't run on the target node in the pre phase as a failed
3198
    node would then be impossible to remove.
3199

3200
    """
3201
    env = {
3202
      "OP_TARGET": self.op.node_name,
3203
      "NODE_NAME": self.op.node_name,
3204
      }
3205
    all_nodes = self.cfg.GetNodeList()
3206
    try:
3207
      all_nodes.remove(self.op.node_name)
3208
    except ValueError:
3209
      logging.warning("Node %s which is about to be removed not found"
3210
                      " in the all nodes list", self.op.node_name)
3211
    return env, all_nodes, all_nodes
3212

    
3213
  def CheckPrereq(self):
3214
    """Check prerequisites.
3215

3216
    This checks:
3217
     - the node exists in the configuration
3218
     - it does not have primary or secondary instances
3219
     - it's not the master
3220

3221
    Any errors are signaled by raising errors.OpPrereqError.
3222

3223
    """
3224
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3225
    node = self.cfg.GetNodeInfo(self.op.node_name)
3226
    assert node is not None
3227

    
3228
    instance_list = self.cfg.GetInstanceList()
3229

    
3230
    masternode = self.cfg.GetMasterNode()
3231
    if node.name == masternode:
3232
      raise errors.OpPrereqError("Node is the master node,"
3233
                                 " you need to failover first.",
3234
                                 errors.ECODE_INVAL)
3235

    
3236
    for instance_name in instance_list:
3237
      instance = self.cfg.GetInstanceInfo(instance_name)
3238
      if node.name in instance.all_nodes:
3239
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3240
                                   " please remove first." % instance_name,
3241
                                   errors.ECODE_INVAL)
3242
    self.op.node_name = node.name
3243
    self.node = node
3244

    
3245
  def Exec(self, feedback_fn):
3246
    """Removes the node from the cluster.
3247

3248
    """
3249
    node = self.node
3250
    logging.info("Stopping the node daemon and removing configs from node %s",
3251
                 node.name)
3252

    
3253
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3254

    
3255
    # Promote nodes to master candidate as needed
3256
    _AdjustCandidatePool(self, exceptions=[node.name])
3257
    self.context.RemoveNode(node.name)
3258

    
3259
    # Run post hooks on the node before it's removed
3260
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3261
    try:
3262
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3263
    except:
3264
      # pylint: disable-msg=W0702
3265
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3266

    
3267
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3268
    msg = result.fail_msg
3269
    if msg:
3270
      self.LogWarning("Errors encountered on the remote node while leaving"
3271
                      " the cluster: %s", msg)
3272

    
3273
    # Remove node from our /etc/hosts
3274
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3275
      # FIXME: this should be done via an rpc call to node daemon
3276
      utils.RemoveHostFromEtcHosts(node.name)
3277
      _RedistributeAncillaryFiles(self)
3278

    
3279

    
3280
class LUQueryNodes(NoHooksLU):
3281
  """Logical unit for querying nodes.
3282

3283
  """
3284
  # pylint: disable-msg=W0142
3285
  _OP_PARAMS = [
3286
    _POutputFields,
3287
    ("names", _EmptyList, _TListOf(_TNonEmptyString)),
3288
    ("use_locking", False, _TBool),
3289
    ]
3290
  REQ_BGL = False
3291

    
3292
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
3293
                    "master_candidate", "offline", "drained"]
3294

    
3295
  _FIELDS_DYNAMIC = utils.FieldSet(
3296
    "dtotal", "dfree",
3297
    "mtotal", "mnode", "mfree",
3298
    "bootid",
3299
    "ctotal", "cnodes", "csockets",
3300
    )
3301

    
3302
  _FIELDS_STATIC = utils.FieldSet(*[
3303
    "pinst_cnt", "sinst_cnt",
3304
    "pinst_list", "sinst_list",
3305
    "pip", "sip", "tags",
3306
    "master",
3307
    "role"] + _SIMPLE_FIELDS
3308
    )
3309

    
3310
  def CheckArguments(self):
3311
    _CheckOutputFields(static=self._FIELDS_STATIC,
3312
                       dynamic=self._FIELDS_DYNAMIC,
3313
                       selected=self.op.output_fields)
3314

    
3315
  def ExpandNames(self):
3316
    self.needed_locks = {}
3317
    self.share_locks[locking.LEVEL_NODE] = 1
3318

    
3319
    if self.op.names:
3320
      self.wanted = _GetWantedNodes(self, self.op.names)
3321
    else:
3322
      self.wanted = locking.ALL_SET
3323

    
3324
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3325
    self.do_locking = self.do_node_query and self.op.use_locking
3326
    if self.do_locking:
3327
      # if we don't request only static fields, we need to lock the nodes
3328
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
3329

    
3330
  def Exec(self, feedback_fn):
3331
    """Computes the list of nodes and their attributes.
3332

3333
    """
3334
    all_info = self.cfg.GetAllNodesInfo()
3335
    if self.do_locking:
3336
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
3337
    elif self.wanted != locking.ALL_SET:
3338
      nodenames = self.wanted
3339
      missing = set(nodenames).difference(all_info.keys())
3340
      if missing:
3341
        raise errors.OpExecError(
3342
          "Some nodes were removed before retrieving their data: %s" % missing)
3343
    else:
3344
      nodenames = all_info.keys()
3345

    
3346
    nodenames = utils.NiceSort(nodenames)
3347
    nodelist = [all_info[name] for name in nodenames]
3348

    
3349
    # begin data gathering
3350

    
3351
    if self.do_node_query:
3352
      live_data = {}
3353
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
3354
                                          self.cfg.GetHypervisorType())
3355
      for name in nodenames:
3356
        nodeinfo = node_data[name]
3357
        if not nodeinfo.fail_msg and nodeinfo.payload:
3358
          nodeinfo = nodeinfo.payload
3359
          fn = utils.TryConvert
3360
          live_data[name] = {
3361
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
3362
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
3363
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
3364
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
3365
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
3366
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
3367
            "bootid": nodeinfo.get('bootid', None),
3368
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
3369
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
3370
            }
3371
        else:
3372
          live_data[name] = {}
3373
    else:
3374
      live_data = dict.fromkeys(nodenames, {})
3375

    
3376
    node_to_primary = dict([(name, set()) for name in nodenames])
3377
    node_to_secondary = dict([(name, set()) for name in nodenames])
3378

    
3379
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
3380
                             "sinst_cnt", "sinst_list"))
3381
    if inst_fields & frozenset(self.op.output_fields):
3382
      inst_data = self.cfg.GetAllInstancesInfo()
3383

    
3384
      for inst in inst_data.values():
3385
        if inst.primary_node in node_to_primary:
3386
          node_to_primary[inst.primary_node].add(inst.name)
3387
        for secnode in inst.secondary_nodes:
3388
          if secnode in node_to_secondary:
3389
            node_to_secondary[secnode].add(inst.name)
3390

    
3391
    master_node = self.cfg.GetMasterNode()
3392

    
3393
    # end data gathering
3394

    
3395
    output = []
3396
    for node in nodelist:
3397
      node_output = []
3398
      for field in self.op.output_fields:
3399
        if field in self._SIMPLE_FIELDS:
3400
          val = getattr(node, field)
3401
        elif field == "pinst_list":
3402
          val = list(node_to_primary[node.name])
3403
        elif field == "sinst_list":
3404
          val = list(node_to_secondary[node.name])
3405
        elif field == "pinst_cnt":
3406
          val = len(node_to_primary[node.name])
3407
        elif field == "sinst_cnt":
3408
          val = len(node_to_secondary[node.name])
3409
        elif field == "pip":
3410
          val = node.primary_ip
3411
        elif field == "sip":
3412
          val = node.secondary_ip
3413
        elif field == "tags":
3414
          val = list(node.GetTags())
3415
        elif field == "master":
3416
          val = node.name == master_node
3417
        elif self._FIELDS_DYNAMIC.Matches(field):
3418
          val = live_data[node.name].get(field, None)
3419
        elif field == "role":
3420
          if node.name == master_node:
3421
            val = "M"
3422
          elif node.master_candidate:
3423
            val = "C"
3424
          elif node.drained:
3425
            val = "D"
3426
          elif node.offline:
3427
            val = "O"
3428
          else:
3429
            val = "R"
3430
        else:
3431
          raise errors.ParameterError(field)
3432
        node_output.append(val)
3433
      output.append(node_output)
3434

    
3435
    return output
3436

    
3437

    
3438
class LUQueryNodeVolumes(NoHooksLU):
3439
  """Logical unit for getting volumes on node(s).
3440

3441
  """
3442
  _OP_PARAMS = [
3443
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
3444
    ("output_fields", _NoDefault, _TListOf(_TNonEmptyString)),
3445
    ]
3446
  REQ_BGL = False
3447
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3448
  _FIELDS_STATIC = utils.FieldSet("node")
3449

    
3450
  def CheckArguments(self):
3451
    _CheckOutputFields(static=self._FIELDS_STATIC,
3452
                       dynamic=self._FIELDS_DYNAMIC,
3453
                       selected=self.op.output_fields)
3454

    
3455
  def ExpandNames(self):
3456
    self.needed_locks = {}
3457
    self.share_locks[locking.LEVEL_NODE] = 1
3458
    if not self.op.nodes:
3459
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3460
    else:
3461
      self.needed_locks[locking.LEVEL_NODE] = \
3462
        _GetWantedNodes(self, self.op.nodes)
3463

    
3464
  def Exec(self, feedback_fn):
3465
    """Computes the list of nodes and their attributes.
3466

3467
    """
3468
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3469
    volumes = self.rpc.call_node_volumes(nodenames)
3470

    
3471
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3472
             in self.cfg.GetInstanceList()]
3473

    
3474
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3475

    
3476
    output = []
3477
    for node in nodenames:
3478
      nresult = volumes[node]
3479
      if nresult.offline:
3480
        continue
3481
      msg = nresult.fail_msg
3482
      if msg:
3483
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3484
        continue
3485

    
3486
      node_vols = nresult.payload[:]
3487
      node_vols.sort(key=lambda vol: vol['dev'])
3488

    
3489
      for vol in node_vols:
3490
        node_output = []
3491
        for field in self.op.output_fields:
3492
          if field == "node":
3493
            val = node
3494
          elif field == "phys":
3495
            val = vol['dev']
3496
          elif field == "vg":
3497
            val = vol['vg']
3498
          elif field == "name":
3499
            val = vol['name']
3500
          elif field == "size":
3501
            val = int(float(vol['size']))
3502
          elif field == "instance":
3503
            for inst in ilist:
3504
              if node not in lv_by_node[inst]:
3505
                continue
3506
              if vol['name'] in lv_by_node[inst][node]:
3507
                val = inst.name
3508
                break
3509
            else:
3510
              val = '-'
3511
          else:
3512
            raise errors.ParameterError(field)
3513
          node_output.append(str(val))
3514

    
3515
        output.append(node_output)
3516

    
3517
    return output
3518

    
3519

    
3520
class LUQueryNodeStorage(NoHooksLU):
3521
  """Logical unit for getting information on storage units on node(s).
3522

3523
  """
3524
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3525
  _OP_PARAMS = [
3526
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
3527
    ("storage_type", _NoDefault, _CheckStorageType),
3528
    ("output_fields", _NoDefault, _TListOf(_TNonEmptyString)),
3529
    ("name", None, _TMaybeString),
3530
    ]
3531
  REQ_BGL = False
3532

    
3533
  def CheckArguments(self):
3534
    _CheckOutputFields(static=self._FIELDS_STATIC,
3535
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3536
                       selected=self.op.output_fields)
3537

    
3538
  def ExpandNames(self):
3539
    self.needed_locks = {}
3540
    self.share_locks[locking.LEVEL_NODE] = 1
3541

    
3542
    if self.op.nodes:
3543
      self.needed_locks[locking.LEVEL_NODE] = \
3544
        _GetWantedNodes(self, self.op.nodes)
3545
    else:
3546
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3547

    
3548
  def Exec(self, feedback_fn):
3549
    """Computes the list of nodes and their attributes.
3550

3551
    """
3552
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3553

    
3554
    # Always get name to sort by
3555
    if constants.SF_NAME in self.op.output_fields:
3556
      fields = self.op.output_fields[:]
3557
    else:
3558
      fields = [constants.SF_NAME] + self.op.output_fields
3559

    
3560
    # Never ask for node or type as it's only known to the LU
3561
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3562
      while extra in fields:
3563
        fields.remove(extra)
3564

    
3565
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3566
    name_idx = field_idx[constants.SF_NAME]
3567

    
3568
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3569
    data = self.rpc.call_storage_list(self.nodes,
3570
                                      self.op.storage_type, st_args,
3571
                                      self.op.name, fields)
3572

    
3573
    result = []
3574

    
3575
    for node in utils.NiceSort(self.nodes):
3576
      nresult = data[node]
3577
      if nresult.offline:
3578
        continue
3579

    
3580
      msg = nresult.fail_msg
3581
      if msg:
3582
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3583
        continue
3584

    
3585
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3586

    
3587
      for name in utils.NiceSort(rows.keys()):
3588
        row = rows[name]
3589

    
3590
        out = []
3591

    
3592
        for field in self.op.output_fields:
3593
          if field == constants.SF_NODE:
3594
            val = node
3595
          elif field == constants.SF_TYPE:
3596
            val = self.op.storage_type
3597
          elif field in field_idx:
3598
            val = row[field_idx[field]]
3599
          else:
3600
            raise errors.ParameterError(field)
3601

    
3602
          out.append(val)
3603

    
3604
        result.append(out)
3605

    
3606
    return result
3607

    
3608

    
3609
class LUModifyNodeStorage(NoHooksLU):
3610
  """Logical unit for modifying a storage volume on a node.
3611

3612
  """
3613
  _OP_PARAMS = [
3614
    _PNodeName,
3615
    ("storage_type", _NoDefault, _CheckStorageType),
3616
    ("name", _NoDefault, _TNonEmptyString),
3617
    ("changes", _NoDefault, _TDict),
3618
    ]
3619
  REQ_BGL = False
3620

    
3621
  def CheckArguments(self):
3622
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3623

    
3624
    storage_type = self.op.storage_type
3625

    
3626
    try:
3627
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3628
    except KeyError:
3629
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3630
                                 " modified" % storage_type,
3631
                                 errors.ECODE_INVAL)
3632

    
3633
    diff = set(self.op.changes.keys()) - modifiable
3634
    if diff:
3635
      raise errors.OpPrereqError("The following fields can not be modified for"
3636
                                 " storage units of type '%s': %r" %
3637
                                 (storage_type, list(diff)),
3638
                                 errors.ECODE_INVAL)
3639

    
3640
  def ExpandNames(self):
3641
    self.needed_locks = {
3642
      locking.LEVEL_NODE: self.op.node_name,
3643
      }
3644

    
3645
  def Exec(self, feedback_fn):
3646
    """Computes the list of nodes and their attributes.
3647

3648
    """
3649
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3650
    result = self.rpc.call_storage_modify(self.op.node_name,
3651
                                          self.op.storage_type, st_args,
3652
                                          self.op.name, self.op.changes)
3653
    result.Raise("Failed to modify storage unit '%s' on %s" %
3654
                 (self.op.name, self.op.node_name))
3655

    
3656

    
3657
class LUAddNode(LogicalUnit):
3658
  """Logical unit for adding node to the cluster.
3659

3660
  """
3661
  HPATH = "node-add"
3662
  HTYPE = constants.HTYPE_NODE
3663
  _OP_PARAMS = [
3664
    _PNodeName,
3665
    ("primary_ip", None, _NoType),
3666
    ("secondary_ip", None, _TMaybeString),
3667
    ("readd", False, _TBool),
3668
    ]
3669

    
3670
  def CheckArguments(self):
3671
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
3672
    # validate/normalize the node name
3673
    self.hostname = netutils.GetHostname(name=self.op.node_name,
3674
                                         family=self.primary_ip_family)
3675
    self.op.node_name = self.hostname.name
3676

    
3677
  def BuildHooksEnv(self):
3678
    """Build hooks env.
3679

3680
    This will run on all nodes before, and on all nodes + the new node after.
3681

3682
    """
3683
    env = {
3684
      "OP_TARGET": self.op.node_name,
3685
      "NODE_NAME": self.op.node_name,
3686
      "NODE_PIP": self.op.primary_ip,
3687
      "NODE_SIP": self.op.secondary_ip,
3688
      }
3689
    nodes_0 = self.cfg.GetNodeList()
3690
    nodes_1 = nodes_0 + [self.op.node_name, ]
3691
    return env, nodes_0, nodes_1
3692

    
3693
  def CheckPrereq(self):
3694
    """Check prerequisites.
3695

3696
    This checks:
3697
     - the new node is not already in the config
3698
     - it is resolvable
3699
     - its parameters (single/dual homed) matches the cluster
3700

3701
    Any errors are signaled by raising errors.OpPrereqError.
3702

3703
    """
3704
    cfg = self.cfg
3705
    hostname = self.hostname
3706
    node = hostname.name
3707
    primary_ip = self.op.primary_ip = hostname.ip
3708
    if self.op.secondary_ip is None:
3709
      if self.primary_ip_family == netutils.IP6Address.family:
3710
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
3711
                                   " IPv4 address must be given as secondary",
3712
                                   errors.ECODE_INVAL)
3713
      self.op.secondary_ip = primary_ip
3714

    
3715
    secondary_ip = self.op.secondary_ip
3716
    if not netutils.IP4Address.IsValid(secondary_ip):
3717
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
3718
                                 " address" % secondary_ip, errors.ECODE_INVAL)
3719

    
3720
    node_list = cfg.GetNodeList()
3721
    if not self.op.readd and node in node_list:
3722
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3723
                                 node, errors.ECODE_EXISTS)
3724
    elif self.op.readd and node not in node_list:
3725
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3726
                                 errors.ECODE_NOENT)
3727

    
3728
    self.changed_primary_ip = False
3729

    
3730
    for existing_node_name in node_list:
3731
      existing_node = cfg.GetNodeInfo(existing_node_name)
3732

    
3733
      if self.op.readd and node == existing_node_name:
3734
        if existing_node.secondary_ip != secondary_ip:
3735
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3736
                                     " address configuration as before",
3737
                                     errors.ECODE_INVAL)
3738
        if existing_node.primary_ip != primary_ip:
3739
          self.changed_primary_ip = True
3740

    
3741
        continue
3742

    
3743
      if (existing_node.primary_ip == primary_ip or
3744
          existing_node.secondary_ip == primary_ip or
3745
          existing_node.primary_ip == secondary_ip or
3746
          existing_node.secondary_ip == secondary_ip):
3747
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3748
                                   " existing node %s" % existing_node.name,
3749
                                   errors.ECODE_NOTUNIQUE)
3750

    
3751
    # check that the type of the node (single versus dual homed) is the
3752
    # same as for the master
3753
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
3754
    master_singlehomed = myself.secondary_ip == myself.primary_ip
3755
    newbie_singlehomed = secondary_ip == primary_ip
3756
    if master_singlehomed != newbie_singlehomed:
3757
      if master_singlehomed:
3758
        raise errors.OpPrereqError("The master has no private ip but the"
3759
                                   " new node has one",
3760
                                   errors.ECODE_INVAL)
3761
      else:
3762
        raise errors.OpPrereqError("The master has a private ip but the"
3763
                                   " new node doesn't have one",
3764
                                   errors.ECODE_INVAL)
3765

    
3766
    # checks reachability
3767
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3768
      raise errors.OpPrereqError("Node not reachable by ping",
3769
                                 errors.ECODE_ENVIRON)
3770

    
3771
    if not newbie_singlehomed:
3772
      # check reachability from my secondary ip to newbie's secondary ip
3773
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3774
                           source=myself.secondary_ip):
3775
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3776
                                   " based ping to noded port",
3777
                                   errors.ECODE_ENVIRON)
3778

    
3779
    if self.op.readd:
3780
      exceptions = [node]
3781
    else:
3782
      exceptions = []
3783

    
3784
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3785

    
3786
    if self.op.readd:
3787
      self.new_node = self.cfg.GetNodeInfo(node)
3788
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
3789
    else:
3790
      self.new_node = objects.Node(name=node,
3791
                                   primary_ip=primary_ip,
3792
                                   secondary_ip=secondary_ip,
3793
                                   master_candidate=self.master_candidate,
3794
                                   offline=False, drained=False)
3795

    
3796
  def Exec(self, feedback_fn):
3797
    """Adds the new node to the cluster.
3798

3799
    """
3800
    new_node = self.new_node
3801
    node = new_node.name
3802

    
3803
    # for re-adds, reset the offline/drained/master-candidate flags;
3804
    # we need to reset here, otherwise offline would prevent RPC calls
3805
    # later in the procedure; this also means that if the re-add
3806
    # fails, we are left with a non-offlined, broken node
3807
    if self.op.readd:
3808
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3809
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3810
      # if we demote the node, we do cleanup later in the procedure
3811
      new_node.master_candidate = self.master_candidate
3812
      if self.changed_primary_ip:
3813
        new_node.primary_ip = self.op.primary_ip
3814

    
3815
    # notify the user about any possible mc promotion
3816
    if new_node.master_candidate:
3817
      self.LogInfo("Node will be a master candidate")
3818

    
3819
    # check connectivity
3820
    result = self.rpc.call_version([node])[node]
3821
    result.Raise("Can't get version information from node %s" % node)
3822
    if constants.PROTOCOL_VERSION == result.payload:
3823
      logging.info("Communication to node %s fine, sw version %s match",
3824
                   node, result.payload)
3825
    else:
3826
      raise errors.OpExecError("Version mismatch master version %s,"
3827
                               " node version %s" %
3828
                               (constants.PROTOCOL_VERSION, result.payload))
3829

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

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

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

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

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

    
3879

    
3880
class LUSetNodeParams(LogicalUnit):
3881
  """Modifies the parameters of a node.
3882

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

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

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

    
3915
    self.lock_all = self.op.auto_promote and self.might_demote
3916

    
3917

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

    
3924
  def BuildHooksEnv(self):
3925
    """Build hooks env.
3926

3927
    This runs on the master node.
3928

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

    
3940
  def CheckPrereq(self):
3941
    """Check prerequisites.
3942

3943
    This only checks the instance list against the existing names.
3944

3945
    """
3946
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3947

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

    
3957

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

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

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

    
3983
    return
3984

    
3985
  def Exec(self, feedback_fn):
3986
    """Modifies a node.
3987

3988
    """
3989
    node = self.node
3990

    
3991
    result = []
3992
    changed_mc = False
3993

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

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

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

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

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

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

    
4043
    return result
4044

    
4045

    
4046
class LUPowercycleNode(NoHooksLU):
4047
  """Powercycles a node.
4048

4049
  """
4050
  _OP_PARAMS = [
4051
    _PNodeName,
4052
    _PForce,
4053
    ]
4054
  REQ_BGL = False
4055

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

    
4063
  def ExpandNames(self):
4064
    """Locking for PowercycleNode.
4065

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

4069
    """
4070
    self.needed_locks = {}
4071

    
4072
  def Exec(self, feedback_fn):
4073
    """Reboots a node.
4074

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

    
4081

    
4082
class LUQueryClusterInfo(NoHooksLU):
4083
  """Query cluster configuration.
4084

4085
  """
4086
  REQ_BGL = False
4087

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

    
4091
  def Exec(self, feedback_fn):
4092
    """Return cluster config.
4093

4094
    """
4095
    cluster = self.cfg.GetClusterInfo()
4096
    os_hvp = {}
4097

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

    
4105
    # Convert ip_family to ip_version
4106
    primary_ip_version = constants.IP4_VERSION
4107
    if cluster.primary_ip_family == netutils.IP6Address.family:
4108
      primary_ip_version = constants.IP6_VERSION
4109

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

    
4143
    return result
4144

    
4145

    
4146
class LUQueryConfigValues(NoHooksLU):
4147
  """Return configuration values.
4148

4149
  """
4150
  _OP_PARAMS = [_POutputFields]
4151
  REQ_BGL = False
4152
  _FIELDS_DYNAMIC = utils.FieldSet()
4153
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4154
                                  "watcher_pause")
4155

    
4156
  def CheckArguments(self):
4157
    _CheckOutputFields(static=self._FIELDS_STATIC,
4158
                       dynamic=self._FIELDS_DYNAMIC,
4159
                       selected=self.op.output_fields)
4160

    
4161
  def ExpandNames(self):
4162
    self.needed_locks = {}
4163

    
4164
  def Exec(self, feedback_fn):
4165
    """Dump a representation of the cluster config to the standard output.
4166

4167
    """
4168
    values = []
4169
    for field in self.op.output_fields:
4170
      if field == "cluster_name":
4171
        entry = self.cfg.GetClusterName()
4172
      elif field == "master_node":
4173
        entry = self.cfg.GetMasterNode()
4174
      elif field == "drain_flag":
4175
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4176
      elif field == "watcher_pause":
4177
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4178
      else:
4179
        raise errors.ParameterError(field)
4180
      values.append(entry)
4181
    return values
4182

    
4183

    
4184
class LUActivateInstanceDisks(NoHooksLU):
4185
  """Bring up an instance's disks.
4186

4187
  """
4188
  _OP_PARAMS = [
4189
    _PInstanceName,
4190
    ("ignore_size", False, _TBool),
4191
    ]
4192
  REQ_BGL = False
4193

    
4194
  def ExpandNames(self):
4195
    self._ExpandAndLockInstance()
4196
    self.needed_locks[locking.LEVEL_NODE] = []
4197
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4198

    
4199
  def DeclareLocks(self, level):
4200
    if level == locking.LEVEL_NODE:
4201
      self._LockInstancesNodes()
4202

    
4203
  def CheckPrereq(self):
4204
    """Check prerequisites.
4205

4206
    This checks that the instance is in the cluster.
4207

4208
    """
4209
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4210
    assert self.instance is not None, \
4211
      "Cannot retrieve locked instance %s" % self.op.instance_name
4212
    _CheckNodeOnline(self, self.instance.primary_node)
4213

    
4214
  def Exec(self, feedback_fn):
4215
    """Activate the disks.
4216

4217
    """
4218
    disks_ok, disks_info = \
4219
              _AssembleInstanceDisks(self, self.instance,
4220
                                     ignore_size=self.op.ignore_size)
4221
    if not disks_ok:
4222
      raise errors.OpExecError("Cannot activate block devices")
4223

    
4224
    return disks_info
4225

    
4226

    
4227
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4228
                           ignore_size=False):
4229
  """Prepare the block devices for an instance.
4230

4231
  This sets up the block devices on all nodes.
4232

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

4250
  """
4251
  device_info = []
4252
  disks_ok = True
4253
  iname = instance.name
4254
  disks = _ExpandCheckDisks(instance, disks)
4255

    
4256
  # With the two passes mechanism we try to reduce the window of
4257
  # opportunity for the race condition of switching DRBD to primary
4258
  # before handshaking occured, but we do not eliminate it
4259

    
4260
  # The proper fix would be to wait (with some limits) until the
4261
  # connection has been made and drbd transitions from WFConnection
4262
  # into any other network-connected state (Connected, SyncTarget,
4263
  # SyncSource, etc.)
4264

    
4265
  # 1st pass, assemble on all nodes in secondary mode
4266
  for inst_disk in disks:
4267
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4268
      if ignore_size:
4269
        node_disk = node_disk.Copy()
4270
        node_disk.UnsetSize()
4271
      lu.cfg.SetDiskID(node_disk, node)
4272
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
4273
      msg = result.fail_msg
4274
      if msg:
4275
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4276
                           " (is_primary=False, pass=1): %s",
4277
                           inst_disk.iv_name, node, msg)
4278
        if not ignore_secondaries:
4279
          disks_ok = False
4280

    
4281
  # FIXME: race condition on drbd migration to primary
4282

    
4283
  # 2nd pass, do only the primary node
4284
  for inst_disk in disks:
4285
    dev_path = None
4286

    
4287
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4288
      if node != instance.primary_node:
4289
        continue
4290
      if ignore_size:
4291
        node_disk = node_disk.Copy()
4292
        node_disk.UnsetSize()
4293
      lu.cfg.SetDiskID(node_disk, node)
4294
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
4295
      msg = result.fail_msg
4296
      if msg:
4297
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4298
                           " (is_primary=True, pass=2): %s",
4299
                           inst_disk.iv_name, node, msg)
4300
        disks_ok = False
4301
      else:
4302
        dev_path = result.payload
4303

    
4304
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4305

    
4306
  # leave the disks configured for the primary node
4307
  # this is a workaround that would be fixed better by
4308
  # improving the logical/physical id handling
4309
  for disk in disks:
4310
    lu.cfg.SetDiskID(disk, instance.primary_node)
4311

    
4312
  return disks_ok, device_info
4313

    
4314

    
4315
def _StartInstanceDisks(lu, instance, force):
4316
  """Start the disks of an instance.
4317

4318
  """
4319
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4320
                                           ignore_secondaries=force)
4321
  if not disks_ok:
4322
    _ShutdownInstanceDisks(lu, instance)
4323
    if force is not None and not force:
4324
      lu.proc.LogWarning("", hint="If the message above refers to a"
4325
                         " secondary node,"
4326
                         " you can retry the operation using '--force'.")
4327
    raise errors.OpExecError("Disk consistency error")
4328

    
4329

    
4330
class LUDeactivateInstanceDisks(NoHooksLU):
4331
  """Shutdown an instance's disks.
4332

4333
  """
4334
  _OP_PARAMS = [
4335
    _PInstanceName,
4336
    ]
4337
  REQ_BGL = False
4338

    
4339
  def ExpandNames(self):
4340
    self._ExpandAndLockInstance()
4341
    self.needed_locks[locking.LEVEL_NODE] = []
4342
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4343

    
4344
  def DeclareLocks(self, level):
4345
    if level == locking.LEVEL_NODE:
4346
      self._LockInstancesNodes()
4347

    
4348
  def CheckPrereq(self):
4349
    """Check prerequisites.
4350

4351
    This checks that the instance is in the cluster.
4352

4353
    """
4354
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4355
    assert self.instance is not None, \
4356
      "Cannot retrieve locked instance %s" % self.op.instance_name
4357

    
4358
  def Exec(self, feedback_fn):
4359
    """Deactivate the disks
4360

4361
    """
4362
    instance = self.instance
4363
    _SafeShutdownInstanceDisks(self, instance)
4364

    
4365

    
4366
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4367
  """Shutdown block devices of an instance.
4368

4369
  This function checks if an instance is running, before calling
4370
  _ShutdownInstanceDisks.
4371

4372
  """
4373
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4374
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4375

    
4376

    
4377
def _ExpandCheckDisks(instance, disks):
4378
  """Return the instance disks selected by the disks list
4379

4380
  @type disks: list of L{objects.Disk} or None
4381
  @param disks: selected disks
4382
  @rtype: list of L{objects.Disk}
4383
  @return: selected instance disks to act on
4384

4385
  """
4386
  if disks is None:
4387
    return instance.disks
4388
  else:
4389
    if not set(disks).issubset(instance.disks):
4390
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4391
                                   " target instance")
4392
    return disks
4393

    
4394

    
4395
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4396
  """Shutdown block devices of an instance.
4397

4398
  This does the shutdown on all nodes of the instance.
4399

4400
  If the ignore_primary is false, errors on the primary node are
4401
  ignored.
4402

4403
  """
4404
  all_result = True
4405
  disks = _ExpandCheckDisks(instance, disks)
4406

    
4407
  for disk in disks:
4408
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4409
      lu.cfg.SetDiskID(top_disk, node)
4410
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4411
      msg = result.fail_msg
4412
      if msg:
4413
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4414
                      disk.iv_name, node, msg)
4415
        if not ignore_primary or node != instance.primary_node:
4416
          all_result = False
4417
  return all_result
4418

    
4419

    
4420
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4421
  """Checks if a node has enough free memory.
4422

4423
  This function check if a given node has the needed amount of free
4424
  memory. In case the node has less memory or we cannot get the
4425
  information from the node, this function raise an OpPrereqError
4426
  exception.
4427

4428
  @type lu: C{LogicalUnit}
4429
  @param lu: a logical unit from which we get configuration data
4430
  @type node: C{str}
4431
  @param node: the node to check
4432
  @type reason: C{str}
4433
  @param reason: string to use in the error message
4434
  @type requested: C{int}
4435
  @param requested: the amount of memory in MiB to check for
4436
  @type hypervisor_name: C{str}
4437
  @param hypervisor_name: the hypervisor to ask for memory stats
4438
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4439
      we cannot check the node
4440

4441
  """
4442
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
4443
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4444
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4445
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4446
  if not isinstance(free_mem, int):
4447
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4448
                               " was '%s'" % (node, free_mem),
4449
                               errors.ECODE_ENVIRON)
4450
  if requested > free_mem:
4451
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
4452
                               " needed %s MiB, available %s MiB" %
4453
                               (node, reason, requested, free_mem),
4454
                               errors.ECODE_NORES)
4455

    
4456

    
4457
def _CheckNodesFreeDisk(lu, nodenames, requested):
4458
  """Checks if nodes have enough free disk space in the default VG.
4459

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

4465
  @type lu: C{LogicalUnit}
4466
  @param lu: a logical unit from which we get configuration data
4467
  @type nodenames: C{list}
4468
  @param nodenames: the list of node names to check
4469
  @type requested: C{int}
4470
  @param requested: the amount of disk in MiB to check for
4471
  @raise errors.OpPrereqError: if the node doesn't have enough disk, or
4472
      we cannot check the node
4473

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

    
4492

    
4493
class LUStartupInstance(LogicalUnit):
4494
  """Starts an instance.
4495

4496
  """
4497
  HPATH = "instance-start"
4498
  HTYPE = constants.HTYPE_INSTANCE
4499
  _OP_PARAMS = [
4500
    _PInstanceName,
4501
    _PForce,
4502
    ("hvparams", _EmptyDict, _TDict),
4503
    ("beparams", _EmptyDict, _TDict),
4504
    ]
4505
  REQ_BGL = False
4506

    
4507
  def CheckArguments(self):
4508
    # extra beparams
4509
    if self.op.beparams:
4510
      # fill the beparams dict
4511
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
4512

    
4513
  def ExpandNames(self):
4514
    self._ExpandAndLockInstance()
4515

    
4516
  def BuildHooksEnv(self):
4517
    """Build hooks env.
4518

4519
    This runs on master, primary and secondary nodes of the instance.
4520

4521
    """
4522
    env = {
4523
      "FORCE": self.op.force,
4524
      }
4525
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4526
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4527
    return env, nl, nl
4528

    
4529
  def CheckPrereq(self):
4530
    """Check prerequisites.
4531

4532
    This checks that the instance is in the cluster.
4533

4534
    """
4535
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4536
    assert self.instance is not None, \
4537
      "Cannot retrieve locked instance %s" % self.op.instance_name
4538

    
4539
    # extra hvparams
4540
    if self.op.hvparams:
4541
      # check hypervisor parameter syntax (locally)
4542
      cluster = self.cfg.GetClusterInfo()
4543
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
4544
      filled_hvp = cluster.FillHV(instance)
4545
      filled_hvp.update(self.op.hvparams)
4546
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
4547
      hv_type.CheckParameterSyntax(filled_hvp)
4548
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
4549

    
4550
    _CheckNodeOnline(self, instance.primary_node)
4551

    
4552
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4553
    # check bridges existence
4554
    _CheckInstanceBridgesExist(self, instance)
4555

    
4556
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4557
                                              instance.name,
4558
                                              instance.hypervisor)
4559
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4560
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4561
    if not remote_info.payload: # not running already
4562
      _CheckNodeFreeMemory(self, instance.primary_node,
4563
                           "starting instance %s" % instance.name,
4564
                           bep[constants.BE_MEMORY], instance.hypervisor)
4565

    
4566
  def Exec(self, feedback_fn):
4567
    """Start the instance.
4568

4569
    """
4570
    instance = self.instance
4571
    force = self.op.force
4572

    
4573
    self.cfg.MarkInstanceUp(instance.name)
4574

    
4575
    node_current = instance.primary_node
4576

    
4577
    _StartInstanceDisks(self, instance, force)
4578

    
4579
    result = self.rpc.call_instance_start(node_current, instance,
4580
                                          self.op.hvparams, self.op.beparams)
4581
    msg = result.fail_msg
4582
    if msg:
4583
      _ShutdownInstanceDisks(self, instance)
4584
      raise errors.OpExecError("Could not start instance: %s" % msg)
4585

    
4586

    
4587
class LURebootInstance(LogicalUnit):
4588
  """Reboot an instance.
4589

4590
  """
4591
  HPATH = "instance-reboot"
4592
  HTYPE = constants.HTYPE_INSTANCE
4593
  _OP_PARAMS = [
4594
    _PInstanceName,
4595
    ("ignore_secondaries", False, _TBool),
4596
    ("reboot_type", _NoDefault, _TElemOf(constants.REBOOT_TYPES)),
4597
    _PShutdownTimeout,
4598
    ]
4599
  REQ_BGL = False
4600

    
4601
  def ExpandNames(self):
4602
    self._ExpandAndLockInstance()
4603

    
4604
  def BuildHooksEnv(self):
4605
    """Build hooks env.
4606

4607
    This runs on master, primary and secondary nodes of the instance.
4608

4609
    """
4610
    env = {
4611
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
4612
      "REBOOT_TYPE": self.op.reboot_type,
4613
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
4614
      }
4615
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4616
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4617
    return env, nl, nl
4618

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

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

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

    
4629
    _CheckNodeOnline(self, instance.primary_node)
4630

    
4631
    # check bridges existence
4632
    _CheckInstanceBridgesExist(self, instance)
4633

    
4634
  def Exec(self, feedback_fn):
4635
    """Reboot the instance.
4636

4637
    """
4638
    instance = self.instance
4639
    ignore_secondaries = self.op.ignore_secondaries
4640
    reboot_type = self.op.reboot_type
4641

    
4642
    node_current = instance.primary_node
4643

    
4644
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
4645
                       constants.INSTANCE_REBOOT_HARD]:
4646
      for disk in instance.disks:
4647
        self.cfg.SetDiskID(disk, node_current)
4648
      result = self.rpc.call_instance_reboot(node_current, instance,
4649
                                             reboot_type,
4650
                                             self.op.shutdown_timeout)
4651
      result.Raise("Could not reboot instance")
4652
    else:
4653
      result = self.rpc.call_instance_shutdown(node_current, instance,
4654
                                               self.op.shutdown_timeout)
4655
      result.Raise("Could not shutdown instance for full reboot")
4656
      _ShutdownInstanceDisks(self, instance)
4657
      _StartInstanceDisks(self, instance, ignore_secondaries)
4658
      result = self.rpc.call_instance_start(node_current, instance, None, None)
4659
      msg = result.fail_msg
4660
      if msg:
4661
        _ShutdownInstanceDisks(self, instance)
4662
        raise errors.OpExecError("Could not start instance for"
4663
                                 " full reboot: %s" % msg)
4664

    
4665
    self.cfg.MarkInstanceUp(instance.name)
4666

    
4667

    
4668
class LUShutdownInstance(LogicalUnit):
4669
  """Shutdown an instance.
4670

4671
  """
4672
  HPATH = "instance-stop"
4673
  HTYPE = constants.HTYPE_INSTANCE
4674
  _OP_PARAMS = [
4675
    _PInstanceName,
4676
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, _TPositiveInt),
4677
    ]
4678
  REQ_BGL = False
4679

    
4680
  def ExpandNames(self):
4681
    self._ExpandAndLockInstance()
4682

    
4683
  def BuildHooksEnv(self):
4684
    """Build hooks env.
4685

4686
    This runs on master, primary and secondary nodes of the instance.
4687

4688
    """
4689
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4690
    env["TIMEOUT"] = self.op.timeout
4691
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4692
    return env, nl, nl
4693

    
4694
  def CheckPrereq(self):
4695
    """Check prerequisites.
4696

4697
    This checks that the instance is in the cluster.
4698

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

    
4705
  def Exec(self, feedback_fn):
4706
    """Shutdown the instance.
4707

4708
    """
4709
    instance = self.instance
4710
    node_current = instance.primary_node
4711
    timeout = self.op.timeout
4712
    self.cfg.MarkInstanceDown(instance.name)
4713
    result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
4714
    msg = result.fail_msg
4715
    if msg:
4716
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
4717

    
4718
    _ShutdownInstanceDisks(self, instance)
4719

    
4720

    
4721
class LUReinstallInstance(LogicalUnit):
4722
  """Reinstall an instance.
4723

4724
  """
4725
  HPATH = "instance-reinstall"
4726
  HTYPE = constants.HTYPE_INSTANCE
4727
  _OP_PARAMS = [
4728
    _PInstanceName,
4729
    ("os_type", None, _TMaybeString),
4730
    ("force_variant", False, _TBool),
4731
    ]
4732
  REQ_BGL = False
4733

    
4734
  def ExpandNames(self):
4735
    self._ExpandAndLockInstance()
4736

    
4737
  def BuildHooksEnv(self):
4738
    """Build hooks env.
4739

4740
    This runs on master, primary and secondary nodes of the instance.
4741

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

    
4747
  def CheckPrereq(self):
4748
    """Check prerequisites.
4749

4750
    This checks that the instance is in the cluster and is not running.
4751

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

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

    
4764
    if self.op.os_type is not None:
4765
      # OS verification
4766
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
4767
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
4768

    
4769
    self.instance = instance
4770

    
4771
  def Exec(self, feedback_fn):
4772
    """Reinstall the instance.
4773

4774
    """
4775
    inst = self.instance
4776

    
4777
    if self.op.os_type is not None:
4778
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
4779
      inst.os = self.op.os_type
4780
      self.cfg.Update(inst, feedback_fn)
4781

    
4782
    _StartInstanceDisks(self, inst, None)
4783
    try:
4784
      feedback_fn("Running the instance OS create scripts...")
4785
      # FIXME: pass debug option from opcode to backend
4786
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
4787
                                             self.op.debug_level)
4788
      result.Raise("Could not install OS for instance %s on node %s" %
4789
                   (inst.name, inst.primary_node))
4790
    finally:
4791
      _ShutdownInstanceDisks(self, inst)
4792

    
4793

    
4794
class LURecreateInstanceDisks(LogicalUnit):
4795
  """Recreate an instance's missing disks.
4796

4797
  """
4798
  HPATH = "instance-recreate-disks"
4799
  HTYPE = constants.HTYPE_INSTANCE
4800
  _OP_PARAMS = [
4801
    _PInstanceName,
4802
    ("disks", _EmptyList, _TListOf(_TPositiveInt)),
4803
    ]
4804
  REQ_BGL = False
4805

    
4806
  def ExpandNames(self):
4807
    self._ExpandAndLockInstance()
4808

    
4809
  def BuildHooksEnv(self):
4810
    """Build hooks env.
4811

4812
    This runs on master, primary and secondary nodes of the instance.
4813

4814
    """
4815
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4816
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4817
    return env, nl, nl
4818

    
4819
  def CheckPrereq(self):
4820
    """Check prerequisites.
4821

4822
    This checks that the instance is in the cluster and is not running.
4823

4824
    """
4825
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4826
    assert instance is not None, \
4827
      "Cannot retrieve locked instance %s" % self.op.instance_name
4828
    _CheckNodeOnline(self, instance.primary_node)
4829

    
4830
    if instance.disk_template == constants.DT_DISKLESS:
4831
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4832
                                 self.op.instance_name, errors.ECODE_INVAL)
4833
    _CheckInstanceDown(self, instance, "cannot recreate disks")
4834

    
4835
    if not self.op.disks:
4836
      self.op.disks = range(len(instance.disks))
4837
    else:
4838
      for idx in self.op.disks:
4839
        if idx >= len(instance.disks):
4840
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
4841
                                     errors.ECODE_INVAL)
4842

    
4843
    self.instance = instance
4844

    
4845
  def Exec(self, feedback_fn):
4846
    """Recreate the disks.
4847

4848
    """
4849
    to_skip = []
4850
    for idx, _ in enumerate(self.instance.disks):
4851
      if idx not in self.op.disks: # disk idx has not been passed in
4852
        to_skip.append(idx)
4853
        continue
4854

    
4855
    _CreateDisks(self, self.instance, to_skip=to_skip)
4856

    
4857

    
4858
class LURenameInstance(LogicalUnit):
4859
  """Rename an instance.
4860

4861
  """
4862
  HPATH = "instance-rename"
4863
  HTYPE = constants.HTYPE_INSTANCE
4864
  _OP_PARAMS = [
4865
    _PInstanceName,
4866
    ("new_name", _NoDefault, _TNonEmptyString),
4867
    ("ip_check", False, _TBool),
4868
    ("name_check", True, _TBool),
4869
    ]
4870

    
4871
  def CheckArguments(self):
4872
    """Check arguments.
4873

4874
    """
4875
    if self.op.ip_check and not self.op.name_check:
4876
      # TODO: make the ip check more flexible and not depend on the name check
4877
      raise errors.OpPrereqError("Cannot do ip check without a name check",
4878
                                 errors.ECODE_INVAL)
4879

    
4880
  def BuildHooksEnv(self):
4881
    """Build hooks env.
4882

4883
    This runs on master, primary and secondary nodes of the instance.
4884

4885
    """
4886
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4887
    env["INSTANCE_NEW_NAME"] = self.op.new_name
4888
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4889
    return env, nl, nl
4890

    
4891
  def CheckPrereq(self):
4892
    """Check prerequisites.
4893

4894
    This checks that the instance is in the cluster and is not running.
4895

4896
    """
4897
    self.op.instance_name = _ExpandInstanceName(self.cfg,
4898
                                                self.op.instance_name)
4899
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4900
    assert instance is not None
4901
    _CheckNodeOnline(self, instance.primary_node)
4902
    _CheckInstanceDown(self, instance, "cannot rename")
4903
    self.instance = instance
4904

    
4905
    new_name = self.op.new_name
4906
    if self.op.name_check:
4907
      hostname = netutils.GetHostname(name=new_name)
4908
      new_name = hostname.name
4909
      if (self.op.ip_check and
4910
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
4911
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4912
                                   (hostname.ip, new_name),
4913
                                   errors.ECODE_NOTUNIQUE)
4914

    
4915
    instance_list = self.cfg.GetInstanceList()
4916
    if new_name in instance_list:
4917
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4918
                                 new_name, errors.ECODE_EXISTS)
4919

    
4920
  def Exec(self, feedback_fn):
4921
    """Reinstall the instance.
4922

4923
    """
4924
    inst = self.instance
4925
    old_name = inst.name
4926

    
4927
    if inst.disk_template == constants.DT_FILE:
4928
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4929

    
4930
    self.cfg.RenameInstance(inst.name, self.op.new_name)
4931
    # Change the instance lock. This is definitely safe while we hold the BGL
4932
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
4933
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
4934

    
4935
    # re-read the instance from the configuration after rename
4936
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
4937

    
4938
    if inst.disk_template == constants.DT_FILE:
4939
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4940
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
4941
                                                     old_file_storage_dir,
4942
                                                     new_file_storage_dir)
4943
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
4944
                   " (but the instance has been renamed in Ganeti)" %
4945
                   (inst.primary_node, old_file_storage_dir,
4946
                    new_file_storage_dir))
4947

    
4948
    _StartInstanceDisks(self, inst, None)
4949
    try:
4950
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
4951
                                                 old_name, self.op.debug_level)
4952
      msg = result.fail_msg
4953
      if msg:
4954
        msg = ("Could not run OS rename script for instance %s on node %s"
4955
               " (but the instance has been renamed in Ganeti): %s" %
4956
               (inst.name, inst.primary_node, msg))
4957
        self.proc.LogWarning(msg)
4958
    finally:
4959
      _ShutdownInstanceDisks(self, inst)
4960

    
4961
    return inst.name
4962

    
4963

    
4964
class LURemoveInstance(LogicalUnit):
4965
  """Remove an instance.
4966

4967
  """
4968
  HPATH = "instance-remove"
4969
  HTYPE = constants.HTYPE_INSTANCE
4970
  _OP_PARAMS = [
4971
    _PInstanceName,
4972
    ("ignore_failures", False, _TBool),
4973
    _PShutdownTimeout,
4974
    ]
4975
  REQ_BGL = False
4976

    
4977
  def ExpandNames(self):
4978
    self._ExpandAndLockInstance()
4979
    self.needed_locks[locking.LEVEL_NODE] = []
4980
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4981

    
4982
  def DeclareLocks(self, level):
4983
    if level == locking.LEVEL_NODE:
4984
      self._LockInstancesNodes()
4985

    
4986
  def BuildHooksEnv(self):
4987
    """Build hooks env.
4988

4989
    This runs on master, primary and secondary nodes of the instance.
4990

4991
    """
4992
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4993
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
4994
    nl = [self.cfg.GetMasterNode()]
4995
    nl_post = list(self.instance.all_nodes) + nl
4996
    return env, nl, nl_post
4997

    
4998
  def CheckPrereq(self):
4999
    """Check prerequisites.
5000

5001
    This checks that the instance is in the cluster.
5002

5003
    """
5004
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5005
    assert self.instance is not None, \
5006
      "Cannot retrieve locked instance %s" % self.op.instance_name
5007

    
5008
  def Exec(self, feedback_fn):
5009
    """Remove the instance.
5010

5011
    """
5012
    instance = self.instance
5013
    logging.info("Shutting down instance %s on node %s",
5014
                 instance.name, instance.primary_node)
5015

    
5016
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5017
                                             self.op.shutdown_timeout)
5018
    msg = result.fail_msg
5019
    if msg:
5020
      if self.op.ignore_failures:
5021
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5022
      else:
5023
        raise errors.OpExecError("Could not shutdown instance %s on"
5024
                                 " node %s: %s" %
5025
                                 (instance.name, instance.primary_node, msg))
5026

    
5027
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5028

    
5029

    
5030
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5031
  """Utility function to remove an instance.
5032

5033
  """
5034
  logging.info("Removing block devices for instance %s", instance.name)
5035

    
5036
  if not _RemoveDisks(lu, instance):
5037
    if not ignore_failures:
5038
      raise errors.OpExecError("Can't remove instance's disks")
5039
    feedback_fn("Warning: can't remove instance's disks")
5040

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

    
5043
  lu.cfg.RemoveInstance(instance.name)
5044

    
5045
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5046
    "Instance lock removal conflict"
5047

    
5048
  # Remove lock for the instance
5049
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5050

    
5051

    
5052
class LUQueryInstances(NoHooksLU):
5053
  """Logical unit for querying instances.
5054

5055
  """
5056
  # pylint: disable-msg=W0142
5057
  _OP_PARAMS = [
5058
    ("output_fields", _NoDefault, _TListOf(_TNonEmptyString)),
5059
    ("names", _EmptyList, _TListOf(_TNonEmptyString)),
5060
    ("use_locking", False, _TBool),
5061
    ]
5062
  REQ_BGL = False
5063
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
5064
                    "serial_no", "ctime", "mtime", "uuid"]
5065
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
5066
                                    "admin_state",
5067
                                    "disk_template", "ip", "mac", "bridge",
5068
                                    "nic_mode", "nic_link",
5069
                                    "sda_size", "sdb_size", "vcpus", "tags",
5070
                                    "network_port", "beparams",
5071
                                    r"(disk)\.(size)/([0-9]+)",
5072
                                    r"(disk)\.(sizes)", "disk_usage",
5073
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
5074
                                    r"(nic)\.(bridge)/([0-9]+)",
5075
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
5076
                                    r"(disk|nic)\.(count)",
5077
                                    "hvparams",
5078
                                    ] + _SIMPLE_FIELDS +
5079
                                  ["hv/%s" % name
5080
                                   for name in constants.HVS_PARAMETERS
5081
                                   if name not in constants.HVC_GLOBALS] +
5082
                                  ["be/%s" % name
5083
                                   for name in constants.BES_PARAMETERS])
5084
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state",
5085
                                   "oper_ram",
5086
                                   "oper_vcpus",
5087
                                   "status")
5088

    
5089

    
5090
  def CheckArguments(self):
5091
    _CheckOutputFields(static=self._FIELDS_STATIC,
5092
                       dynamic=self._FIELDS_DYNAMIC,
5093
                       selected=self.op.output_fields)
5094

    
5095
  def ExpandNames(self):
5096
    self.needed_locks = {}
5097
    self.share_locks[locking.LEVEL_INSTANCE] = 1
5098
    self.share_locks[locking.LEVEL_NODE] = 1
5099

    
5100
    if self.op.names:
5101
      self.wanted = _GetWantedInstances(self, self.op.names)
5102
    else:
5103
      self.wanted = locking.ALL_SET
5104

    
5105
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
5106
    self.do_locking = self.do_node_query and self.op.use_locking
5107
    if self.do_locking:
5108
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
5109
      self.needed_locks[locking.LEVEL_NODE] = []
5110
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5111

    
5112
  def DeclareLocks(self, level):
5113
    if level == locking.LEVEL_NODE and self.do_locking:
5114
      self._LockInstancesNodes()
5115

    
5116
  def Exec(self, feedback_fn):
5117
    """Computes the list of nodes and their attributes.
5118

5119
    """
5120
    # pylint: disable-msg=R0912
5121
    # way too many branches here
5122
    all_info = self.cfg.GetAllInstancesInfo()
5123
    if self.wanted == locking.ALL_SET:
5124
      # caller didn't specify instance names, so ordering is not important
5125
      if self.do_locking:
5126
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5127
      else:
5128
        instance_names = all_info.keys()
5129
      instance_names = utils.NiceSort(instance_names)
5130
    else:
5131
      # caller did specify names, so we must keep the ordering
5132
      if self.do_locking:
5133
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
5134
      else:
5135
        tgt_set = all_info.keys()
5136
      missing = set(self.wanted).difference(tgt_set)
5137
      if missing:
5138
        raise errors.OpExecError("Some instances were removed before"
5139
                                 " retrieving their data: %s" % missing)
5140
      instance_names = self.wanted
5141

    
5142
    instance_list = [all_info[iname] for iname in instance_names]
5143

    
5144
    # begin data gathering
5145

    
5146
    nodes = frozenset([inst.primary_node for inst in instance_list])
5147
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
5148

    
5149
    bad_nodes = []
5150
    off_nodes = []
5151
    if self.do_node_query:
5152
      live_data = {}
5153
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
5154
      for name in nodes:
5155
        result = node_data[name]
5156
        if result.offline:
5157
          # offline nodes will be in both lists
5158
          off_nodes.append(name)
5159
        if result.fail_msg:
5160
          bad_nodes.append(name)
5161
        else:
5162
          if result.payload:
5163
            live_data.update(result.payload)
5164
          # else no instance is alive
5165
    else:
5166
      live_data = dict([(name, {}) for name in instance_names])
5167

    
5168
    # end data gathering
5169

    
5170
    HVPREFIX = "hv/"
5171
    BEPREFIX = "be/"
5172
    output = []
5173
    cluster = self.cfg.GetClusterInfo()
5174
    for instance in instance_list:
5175
      iout = []
5176
      i_hv = cluster.FillHV(instance, skip_globals=True)
5177
      i_be = cluster.FillBE(instance)
5178
      i_nicp = [cluster.SimpleFillNIC(nic.nicparams) for nic in instance.nics]
5179
      for field in self.op.output_fields:
5180
        st_match = self._FIELDS_STATIC.Matches(field)
5181
        if field in self._SIMPLE_FIELDS:
5182
          val = getattr(instance, field)
5183
        elif field == "pnode":
5184
          val = instance.primary_node
5185
        elif field == "snodes":
5186
          val = list(instance.secondary_nodes)
5187
        elif field == "admin_state":
5188
          val = instance.admin_up
5189
        elif field == "oper_state":
5190
          if instance.primary_node in bad_nodes:
5191
            val = None
5192
          else:
5193
            val = bool(live_data.get(instance.name))
5194
        elif field == "status":
5195
          if instance.primary_node in off_nodes:
5196
            val = "ERROR_nodeoffline"
5197
          elif instance.primary_node in bad_nodes:
5198
            val = "ERROR_nodedown"
5199
          else:
5200
            running = bool(live_data.get(instance.name))
5201
            if running:
5202
              if instance.admin_up:
5203
                val = "running"
5204
              else:
5205
                val = "ERROR_up"
5206
            else:
5207
              if instance.admin_up:
5208
                val = "ERROR_down"
5209
              else:
5210
                val = "ADMIN_down"
5211
        elif field == "oper_ram":
5212
          if instance.primary_node in bad_nodes:
5213
            val = None
5214
          elif instance.name in live_data:
5215
            val = live_data[instance.name].get("memory", "?")
5216
          else:
5217
            val = "-"
5218
        elif field == "oper_vcpus":
5219
          if instance.primary_node in bad_nodes:
5220
            val = None
5221
          elif instance.name in live_data:
5222
            val = live_data[instance.name].get("vcpus", "?")
5223
          else:
5224
            val = "-"
5225
        elif field == "vcpus":
5226
          val = i_be[constants.BE_VCPUS]
5227
        elif field == "disk_template":
5228
          val = instance.disk_template
5229
        elif field == "ip":
5230
          if instance.nics:
5231
            val = instance.nics[0].ip
5232
          else:
5233
            val = None
5234
        elif field == "nic_mode":
5235
          if instance.nics:
5236
            val = i_nicp[0][constants.NIC_MODE]
5237
          else:
5238
            val = None
5239
        elif field == "nic_link":
5240
          if instance.nics:
5241
            val = i_nicp[0][constants.NIC_LINK]
5242
          else:
5243
            val = None
5244
        elif field == "bridge":
5245
          if (instance.nics and
5246
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
5247
            val = i_nicp[0][constants.NIC_LINK]
5248
          else:
5249
            val = None
5250
        elif field == "mac":
5251
          if instance.nics:
5252
            val = instance.nics[0].mac
5253
          else:
5254
            val = None
5255
        elif field == "sda_size" or field == "sdb_size":
5256
          idx = ord(field[2]) - ord('a')
5257
          try:
5258
            val = instance.FindDisk(idx).size
5259
          except errors.OpPrereqError:
5260
            val = None
5261
        elif field == "disk_usage": # total disk usage per node
5262
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
5263
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
5264
        elif field == "tags":
5265
          val = list(instance.GetTags())
5266
        elif field == "hvparams":
5267
          val = i_hv
5268
        elif (field.startswith(HVPREFIX) and
5269
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS and
5270
              field[len(HVPREFIX):] not in constants.HVC_GLOBALS):
5271
          val = i_hv.get(field[len(HVPREFIX):], None)
5272
        elif field == "beparams":
5273
          val = i_be
5274
        elif (field.startswith(BEPREFIX) and
5275
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
5276
          val = i_be.get(field[len(BEPREFIX):], None)
5277
        elif st_match and st_match.groups():
5278
          # matches a variable list
5279
          st_groups = st_match.groups()
5280
          if st_groups and st_groups[0] == "disk":
5281
            if st_groups[1] == "count":
5282
              val = len(instance.disks)
5283
            elif st_groups[1] == "sizes":
5284
              val = [disk.size for disk in instance.disks]
5285
            elif st_groups[1] == "size":
5286
              try:
5287
                val = instance.FindDisk(st_groups[2]).size
5288
              except errors.OpPrereqError:
5289
                val = None
5290
            else:
5291
              assert False, "Unhandled disk parameter"
5292
          elif st_groups[0] == "nic":
5293
            if st_groups[1] == "count":
5294
              val = len(instance.nics)
5295
            elif st_groups[1] == "macs":
5296
              val = [nic.mac for nic in instance.nics]
5297
            elif st_groups[1] == "ips":
5298
              val = [nic.ip for nic in instance.nics]
5299
            elif st_groups[1] == "modes":
5300
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
5301
            elif st_groups[1] == "links":
5302
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
5303
            elif st_groups[1] == "bridges":
5304
              val = []
5305
              for nicp in i_nicp:
5306
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
5307
                  val.append(nicp[constants.NIC_LINK])
5308
                else:
5309
                  val.append(None)
5310
            else:
5311
              # index-based item
5312
              nic_idx = int(st_groups[2])
5313
              if nic_idx >= len(instance.nics):
5314
                val = None
5315
              else:
5316
                if st_groups[1] == "mac":
5317
                  val = instance.nics[nic_idx].mac
5318
                elif st_groups[1] == "ip":
5319
                  val = instance.nics[nic_idx].ip
5320
                elif st_groups[1] == "mode":
5321
                  val = i_nicp[nic_idx][constants.NIC_MODE]
5322
                elif st_groups[1] == "link":
5323
                  val = i_nicp[nic_idx][constants.NIC_LINK]
5324
                elif st_groups[1] == "bridge":
5325
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
5326
                  if nic_mode == constants.NIC_MODE_BRIDGED:
5327
                    val = i_nicp[nic_idx][constants.NIC_LINK]
5328
                  else:
5329
                    val = None
5330
                else:
5331
                  assert False, "Unhandled NIC parameter"
5332
          else:
5333
            assert False, ("Declared but unhandled variable parameter '%s'" %
5334
                           field)
5335
        else:
5336
          assert False, "Declared but unhandled parameter '%s'" % field
5337
        iout.append(val)
5338
      output.append(iout)
5339

    
5340
    return output
5341

    
5342

    
5343
class LUFailoverInstance(LogicalUnit):
5344
  """Failover an instance.
5345

5346
  """
5347
  HPATH = "instance-failover"
5348
  HTYPE = constants.HTYPE_INSTANCE
5349
  _OP_PARAMS = [
5350
    _PInstanceName,
5351
    ("ignore_consistency", False, _TBool),
5352
    _PShutdownTimeout,
5353
    ]
5354
  REQ_BGL = False
5355

    
5356
  def ExpandNames(self):
5357
    self._ExpandAndLockInstance()
5358
    self.needed_locks[locking.LEVEL_NODE] = []
5359
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5360

    
5361
  def DeclareLocks(self, level):
5362
    if level == locking.LEVEL_NODE:
5363
      self._LockInstancesNodes()
5364

    
5365
  def BuildHooksEnv(self):
5366
    """Build hooks env.
5367

5368
    This runs on master, primary and secondary nodes of the instance.
5369

5370
    """
5371
    instance = self.instance
5372
    source_node = instance.primary_node
5373
    target_node = instance.secondary_nodes[0]
5374
    env = {
5375
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5376
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5377
      "OLD_PRIMARY": source_node,
5378
      "OLD_SECONDARY": target_node,
5379
      "NEW_PRIMARY": target_node,
5380
      "NEW_SECONDARY": source_node,
5381
      }
5382
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5383
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5384
    nl_post = list(nl)
5385
    nl_post.append(source_node)
5386
    return env, nl, nl_post
5387

    
5388
  def CheckPrereq(self):
5389
    """Check prerequisites.
5390

5391
    This checks that the instance is in the cluster.
5392

5393
    """
5394
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5395
    assert self.instance is not None, \
5396
      "Cannot retrieve locked instance %s" % self.op.instance_name
5397

    
5398
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5399
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5400
      raise errors.OpPrereqError("Instance's disk layout is not"
5401
                                 " network mirrored, cannot failover.",
5402
                                 errors.ECODE_STATE)
5403

    
5404
    secondary_nodes = instance.secondary_nodes
5405
    if not secondary_nodes:
5406
      raise errors.ProgrammerError("no secondary node but using "
5407
                                   "a mirrored disk template")
5408

    
5409
    target_node = secondary_nodes[0]
5410
    _CheckNodeOnline(self, target_node)
5411
    _CheckNodeNotDrained(self, target_node)
5412
    if instance.admin_up:
5413
      # check memory requirements on the secondary node
5414
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5415
                           instance.name, bep[constants.BE_MEMORY],
5416
                           instance.hypervisor)
5417
    else:
5418
      self.LogInfo("Not checking memory on the secondary node as"
5419
                   " instance will not be started")
5420

    
5421
    # check bridge existance
5422
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5423

    
5424
  def Exec(self, feedback_fn):
5425
    """Failover an instance.
5426

5427
    The failover is done by shutting it down on its present node and
5428
    starting it on the secondary.
5429

5430
    """
5431
    instance = self.instance
5432

    
5433
    source_node = instance.primary_node
5434
    target_node = instance.secondary_nodes[0]
5435

    
5436
    if instance.admin_up:
5437
      feedback_fn("* checking disk consistency between source and target")
5438
      for dev in instance.disks:
5439
        # for drbd, these are drbd over lvm
5440
        if not _CheckDiskConsistency(self, dev, target_node, False):
5441
          if not self.op.ignore_consistency:
5442
            raise errors.OpExecError("Disk %s is degraded on target node,"
5443
                                     " aborting failover." % dev.iv_name)
5444
    else:
5445
      feedback_fn("* not checking disk consistency as instance is not running")
5446

    
5447
    feedback_fn("* shutting down instance on source node")
5448
    logging.info("Shutting down instance %s on node %s",
5449
                 instance.name, source_node)
5450

    
5451
    result = self.rpc.call_instance_shutdown(source_node, instance,
5452
                                             self.op.shutdown_timeout)
5453
    msg = result.fail_msg
5454
    if msg:
5455
      if self.op.ignore_consistency:
5456
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5457
                             " Proceeding anyway. Please make sure node"
5458
                             " %s is down. Error details: %s",
5459
                             instance.name, source_node, source_node, msg)
5460
      else:
5461
        raise errors.OpExecError("Could not shutdown instance %s on"
5462
                                 " node %s: %s" %
5463
                                 (instance.name, source_node, msg))
5464

    
5465
    feedback_fn("* deactivating the instance's disks on source node")
5466
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5467
      raise errors.OpExecError("Can't shut down the instance's disks.")
5468

    
5469
    instance.primary_node = target_node
5470
    # distribute new instance config to the other nodes
5471
    self.cfg.Update(instance, feedback_fn)
5472

    
5473
    # Only start the instance if it's marked as up
5474
    if instance.admin_up:
5475
      feedback_fn("* activating the instance's disks on target node")
5476
      logging.info("Starting instance %s on node %s",
5477
                   instance.name, target_node)
5478

    
5479
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5480
                                           ignore_secondaries=True)
5481
      if not disks_ok:
5482
        _ShutdownInstanceDisks(self, instance)
5483
        raise errors.OpExecError("Can't activate the instance's disks")
5484

    
5485
      feedback_fn("* starting the instance on the target node")
5486
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5487
      msg = result.fail_msg
5488
      if msg:
5489
        _ShutdownInstanceDisks(self, instance)
5490
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5491
                                 (instance.name, target_node, msg))
5492

    
5493

    
5494
class LUMigrateInstance(LogicalUnit):
5495
  """Migrate an instance.
5496

5497
  This is migration without shutting down, compared to the failover,
5498
  which is done with shutdown.
5499

5500
  """
5501
  HPATH = "instance-migrate"
5502
  HTYPE = constants.HTYPE_INSTANCE
5503
  _OP_PARAMS = [
5504
    _PInstanceName,
5505
    _PMigrationMode,
5506
    _PMigrationLive,
5507
    ("cleanup", False, _TBool),
5508
    ]
5509

    
5510
  REQ_BGL = False
5511

    
5512
  def ExpandNames(self):
5513
    self._ExpandAndLockInstance()
5514

    
5515
    self.needed_locks[locking.LEVEL_NODE] = []
5516
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5517

    
5518
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5519
                                       self.op.cleanup)
5520
    self.tasklets = [self._migrater]
5521

    
5522
  def DeclareLocks(self, level):
5523
    if level == locking.LEVEL_NODE:
5524
      self._LockInstancesNodes()
5525

    
5526
  def BuildHooksEnv(self):
5527
    """Build hooks env.
5528

5529
    This runs on master, primary and secondary nodes of the instance.
5530

5531
    """
5532
    instance = self._migrater.instance
5533
    source_node = instance.primary_node
5534
    target_node = instance.secondary_nodes[0]
5535
    env = _BuildInstanceHookEnvByObject(self, instance)
5536
    env["MIGRATE_LIVE"] = self._migrater.live
5537
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5538
    env.update({
5539
        "OLD_PRIMARY": source_node,
5540
        "OLD_SECONDARY": target_node,
5541
        "NEW_PRIMARY": target_node,
5542
        "NEW_SECONDARY": source_node,
5543
        })
5544
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5545
    nl_post = list(nl)
5546
    nl_post.append(source_node)
5547
    return env, nl, nl_post
5548

    
5549

    
5550
class LUMoveInstance(LogicalUnit):
5551
  """Move an instance by data-copying.
5552

5553
  """
5554
  HPATH = "instance-move"
5555
  HTYPE = constants.HTYPE_INSTANCE
5556
  _OP_PARAMS = [
5557
    _PInstanceName,
5558
    ("target_node", _NoDefault, _TNonEmptyString),
5559
    _PShutdownTimeout,
5560
    ]
5561
  REQ_BGL = False
5562

    
5563
  def ExpandNames(self):
5564
    self._ExpandAndLockInstance()
5565
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5566
    self.op.target_node = target_node
5567
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5568
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5569

    
5570
  def DeclareLocks(self, level):
5571
    if level == locking.LEVEL_NODE:
5572
      self._LockInstancesNodes(primary_only=True)
5573

    
5574
  def BuildHooksEnv(self):
5575
    """Build hooks env.
5576

5577
    This runs on master, primary and secondary nodes of the instance.
5578

5579
    """
5580
    env = {
5581
      "TARGET_NODE": self.op.target_node,
5582
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5583
      }
5584
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5585
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5586
                                       self.op.target_node]
5587
    return env, nl, nl
5588

    
5589
  def CheckPrereq(self):
5590
    """Check prerequisites.
5591

5592
    This checks that the instance is in the cluster.
5593

5594
    """
5595
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5596
    assert self.instance is not None, \
5597
      "Cannot retrieve locked instance %s" % self.op.instance_name
5598

    
5599
    node = self.cfg.GetNodeInfo(self.op.target_node)
5600
    assert node is not None, \
5601
      "Cannot retrieve locked node %s" % self.op.target_node
5602

    
5603
    self.target_node = target_node = node.name
5604

    
5605
    if target_node == instance.primary_node:
5606
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5607
                                 (instance.name, target_node),
5608
                                 errors.ECODE_STATE)
5609

    
5610
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5611

    
5612
    for idx, dsk in enumerate(instance.disks):
5613
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5614
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5615
                                   " cannot copy" % idx, errors.ECODE_STATE)
5616

    
5617
    _CheckNodeOnline(self, target_node)
5618
    _CheckNodeNotDrained(self, target_node)
5619

    
5620
    if instance.admin_up:
5621
      # check memory requirements on the secondary node
5622
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5623
                           instance.name, bep[constants.BE_MEMORY],
5624
                           instance.hypervisor)
5625
    else:
5626
      self.LogInfo("Not checking memory on the secondary node as"
5627
                   " instance will not be started")
5628

    
5629
    # check bridge existance
5630
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5631

    
5632
  def Exec(self, feedback_fn):
5633
    """Move an instance.
5634

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

5638
    """
5639
    instance = self.instance
5640

    
5641
    source_node = instance.primary_node
5642
    target_node = self.target_node
5643

    
5644
    self.LogInfo("Shutting down instance %s on source node %s",
5645
                 instance.name, source_node)
5646

    
5647
    result = self.rpc.call_instance_shutdown(source_node, instance,
5648
                                             self.op.shutdown_timeout)
5649
    msg = result.fail_msg
5650
    if msg:
5651
      if self.op.ignore_consistency:
5652
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5653
                             " Proceeding anyway. Please make sure node"
5654
                             " %s is down. Error details: %s",
5655
                             instance.name, source_node, source_node, msg)
5656
      else:
5657
        raise errors.OpExecError("Could not shutdown instance %s on"
5658
                                 " node %s: %s" %
5659
                                 (instance.name, source_node, msg))
5660

    
5661
    # create the target disks
5662
    try:
5663
      _CreateDisks(self, instance, target_node=target_node)
5664
    except errors.OpExecError:
5665
      self.LogWarning("Device creation failed, reverting...")
5666
      try:
5667
        _RemoveDisks(self, instance, target_node=target_node)
5668
      finally:
5669
        self.cfg.ReleaseDRBDMinors(instance.name)
5670
        raise
5671

    
5672
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5673

    
5674
    errs = []
5675
    # activate, get path, copy the data over
5676
    for idx, disk in enumerate(instance.disks):
5677
      self.LogInfo("Copying data for disk %d", idx)
5678
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5679
                                               instance.name, True)
5680
      if result.fail_msg:
5681
        self.LogWarning("Can't assemble newly created disk %d: %s",
5682
                        idx, result.fail_msg)
5683
        errs.append(result.fail_msg)
5684
        break
5685
      dev_path = result.payload
5686
      result = self.rpc.call_blockdev_export(source_node, disk,
5687
                                             target_node, dev_path,
5688
                                             cluster_name)
5689
      if result.fail_msg:
5690
        self.LogWarning("Can't copy data over for disk %d: %s",
5691
                        idx, result.fail_msg)
5692
        errs.append(result.fail_msg)
5693
        break
5694

    
5695
    if errs:
5696
      self.LogWarning("Some disks failed to copy, aborting")
5697
      try:
5698
        _RemoveDisks(self, instance, target_node=target_node)
5699
      finally:
5700
        self.cfg.ReleaseDRBDMinors(instance.name)
5701
        raise errors.OpExecError("Errors during disk copy: %s" %
5702
                                 (",".join(errs),))
5703

    
5704
    instance.primary_node = target_node
5705
    self.cfg.Update(instance, feedback_fn)
5706

    
5707
    self.LogInfo("Removing the disks on the original node")
5708
    _RemoveDisks(self, instance, target_node=source_node)
5709

    
5710
    # Only start the instance if it's marked as up
5711
    if instance.admin_up:
5712
      self.LogInfo("Starting instance %s on node %s",
5713
                   instance.name, target_node)
5714

    
5715
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5716
                                           ignore_secondaries=True)
5717
      if not disks_ok:
5718
        _ShutdownInstanceDisks(self, instance)
5719
        raise errors.OpExecError("Can't activate the instance's disks")
5720

    
5721
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5722
      msg = result.fail_msg
5723
      if msg:
5724
        _ShutdownInstanceDisks(self, instance)
5725
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5726
                                 (instance.name, target_node, msg))
5727

    
5728

    
5729
class LUMigrateNode(LogicalUnit):
5730
  """Migrate all instances from a node.
5731

5732
  """
5733
  HPATH = "node-migrate"
5734
  HTYPE = constants.HTYPE_NODE
5735
  _OP_PARAMS = [
5736
    _PNodeName,
5737
    _PMigrationMode,
5738
    _PMigrationLive,
5739
    ]
5740
  REQ_BGL = False
5741

    
5742
  def ExpandNames(self):
5743
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5744

    
5745
    self.needed_locks = {
5746
      locking.LEVEL_NODE: [self.op.node_name],
5747
      }
5748

    
5749
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5750

    
5751
    # Create tasklets for migrating instances for all instances on this node
5752
    names = []
5753
    tasklets = []
5754

    
5755
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5756
      logging.debug("Migrating instance %s", inst.name)
5757
      names.append(inst.name)
5758

    
5759
      tasklets.append(TLMigrateInstance(self, inst.name, False))
5760

    
5761
    self.tasklets = tasklets
5762

    
5763
    # Declare instance locks
5764
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5765

    
5766
  def DeclareLocks(self, level):
5767
    if level == locking.LEVEL_NODE:
5768
      self._LockInstancesNodes()
5769

    
5770
  def BuildHooksEnv(self):
5771
    """Build hooks env.
5772

5773
    This runs on the master, the primary and all the secondaries.
5774

5775
    """
5776
    env = {
5777
      "NODE_NAME": self.op.node_name,
5778
      }
5779

    
5780
    nl = [self.cfg.GetMasterNode()]
5781

    
5782
    return (env, nl, nl)
5783

    
5784

    
5785
class TLMigrateInstance(Tasklet):
5786
  """Tasklet class for instance migration.
5787

5788
  @type live: boolean
5789
  @ivar live: whether the migration will be done live or non-live;
5790
      this variable is initalized only after CheckPrereq has run
5791

5792
  """
5793
  def __init__(self, lu, instance_name, cleanup):
5794
    """Initializes this class.
5795

5796
    """
5797
    Tasklet.__init__(self, lu)
5798

    
5799
    # Parameters
5800
    self.instance_name = instance_name
5801
    self.cleanup = cleanup
5802
    self.live = False # will be overridden later
5803

    
5804
  def CheckPrereq(self):
5805
    """Check prerequisites.
5806

5807
    This checks that the instance is in the cluster.
5808

5809
    """
5810
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
5811
    instance = self.cfg.GetInstanceInfo(instance_name)
5812
    assert instance is not None
5813

    
5814
    if instance.disk_template != constants.DT_DRBD8:
5815
      raise errors.OpPrereqError("Instance's disk layout is not"
5816
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5817

    
5818
    secondary_nodes = instance.secondary_nodes
5819
    if not secondary_nodes:
5820
      raise errors.ConfigurationError("No secondary node but using"
5821
                                      " drbd8 disk template")
5822

    
5823
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5824

    
5825
    target_node = secondary_nodes[0]
5826
    # check memory requirements on the secondary node
5827
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
5828
                         instance.name, i_be[constants.BE_MEMORY],
5829
                         instance.hypervisor)
5830

    
5831
    # check bridge existance
5832
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
5833

    
5834
    if not self.cleanup:
5835
      _CheckNodeNotDrained(self.lu, target_node)
5836
      result = self.rpc.call_instance_migratable(instance.primary_node,
5837
                                                 instance)
5838
      result.Raise("Can't migrate, please use failover",
5839
                   prereq=True, ecode=errors.ECODE_STATE)
5840

    
5841
    self.instance = instance
5842

    
5843
    if self.lu.op.live is not None and self.lu.op.mode is not None:
5844
      raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
5845
                                 " parameters are accepted",
5846
                                 errors.ECODE_INVAL)
5847
    if self.lu.op.live is not None:
5848
      if self.lu.op.live:
5849
        self.lu.op.mode = constants.HT_MIGRATION_LIVE
5850
      else:
5851
        self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
5852
      # reset the 'live' parameter to None so that repeated
5853
      # invocations of CheckPrereq do not raise an exception
5854
      self.lu.op.live = None
5855
    elif self.lu.op.mode is None:
5856
      # read the default value from the hypervisor
5857
      i_hv = self.cfg.GetClusterInfo().FillHV(instance, skip_globals=False)
5858
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
5859

    
5860
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
5861

    
5862
  def _WaitUntilSync(self):
5863
    """Poll with custom rpc for disk sync.
5864

5865
    This uses our own step-based rpc call.
5866

5867
    """
5868
    self.feedback_fn("* wait until resync is done")
5869
    all_done = False
5870
    while not all_done:
5871
      all_done = True
5872
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
5873
                                            self.nodes_ip,
5874
                                            self.instance.disks)
5875
      min_percent = 100
5876
      for node, nres in result.items():
5877
        nres.Raise("Cannot resync disks on node %s" % node)
5878
        node_done, node_percent = nres.payload
5879
        all_done = all_done and node_done
5880
        if node_percent is not None:
5881
          min_percent = min(min_percent, node_percent)
5882
      if not all_done:
5883
        if min_percent < 100:
5884
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
5885
        time.sleep(2)
5886

    
5887
  def _EnsureSecondary(self, node):
5888
    """Demote a node to secondary.
5889

5890
    """
5891
    self.feedback_fn("* switching node %s to secondary mode" % node)
5892

    
5893
    for dev in self.instance.disks:
5894
      self.cfg.SetDiskID(dev, node)
5895

    
5896
    result = self.rpc.call_blockdev_close(node, self.instance.name,
5897
                                          self.instance.disks)
5898
    result.Raise("Cannot change disk to secondary on node %s" % node)
5899

    
5900
  def _GoStandalone(self):
5901
    """Disconnect from the network.
5902

5903
    """
5904
    self.feedback_fn("* changing into standalone mode")
5905
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
5906
                                               self.instance.disks)
5907
    for node, nres in result.items():
5908
      nres.Raise("Cannot disconnect disks node %s" % node)
5909

    
5910
  def _GoReconnect(self, multimaster):
5911
    """Reconnect to the network.
5912

5913
    """
5914
    if multimaster:
5915
      msg = "dual-master"
5916
    else:
5917
      msg = "single-master"
5918
    self.feedback_fn("* changing disks into %s mode" % msg)
5919
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
5920
                                           self.instance.disks,
5921
                                           self.instance.name, multimaster)
5922
    for node, nres in result.items():
5923
      nres.Raise("Cannot change disks config on node %s" % node)
5924

    
5925
  def _ExecCleanup(self):
5926
    """Try to cleanup after a failed migration.
5927

5928
    The cleanup is done by:
5929
      - check that the instance is running only on one node
5930
        (and update the config if needed)
5931
      - change disks on its secondary node to secondary
5932
      - wait until disks are fully synchronized
5933
      - disconnect from the network
5934
      - change disks into single-master mode
5935
      - wait again until disks are fully synchronized
5936

5937
    """
5938
    instance = self.instance
5939
    target_node = self.target_node
5940
    source_node = self.source_node
5941

    
5942
    # check running on only one node
5943
    self.feedback_fn("* checking where the instance actually runs"
5944
                     " (if this hangs, the hypervisor might be in"
5945
                     " a bad state)")
5946
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
5947
    for node, result in ins_l.items():
5948
      result.Raise("Can't contact node %s" % node)
5949

    
5950
    runningon_source = instance.name in ins_l[source_node].payload
5951
    runningon_target = instance.name in ins_l[target_node].payload
5952

    
5953
    if runningon_source and runningon_target:
5954
      raise errors.OpExecError("Instance seems to be running on two nodes,"
5955
                               " or the hypervisor is confused. You will have"
5956
                               " to ensure manually that it runs only on one"
5957
                               " and restart this operation.")
5958

    
5959
    if not (runningon_source or runningon_target):
5960
      raise errors.OpExecError("Instance does not seem to be running at all."
5961
                               " In this case, it's safer to repair by"
5962
                               " running 'gnt-instance stop' to ensure disk"
5963
                               " shutdown, and then restarting it.")
5964

    
5965
    if runningon_target:
5966
      # the migration has actually succeeded, we need to update the config
5967
      self.feedback_fn("* instance running on secondary node (%s),"
5968
                       " updating config" % target_node)
5969
      instance.primary_node = target_node
5970
      self.cfg.Update(instance, self.feedback_fn)
5971
      demoted_node = source_node
5972
    else:
5973
      self.feedback_fn("* instance confirmed to be running on its"
5974
                       " primary node (%s)" % source_node)
5975
      demoted_node = target_node
5976

    
5977
    self._EnsureSecondary(demoted_node)
5978
    try:
5979
      self._WaitUntilSync()
5980
    except errors.OpExecError:
5981
      # we ignore here errors, since if the device is standalone, it
5982
      # won't be able to sync
5983
      pass
5984
    self._GoStandalone()
5985
    self._GoReconnect(False)
5986
    self._WaitUntilSync()
5987

    
5988
    self.feedback_fn("* done")
5989

    
5990
  def _RevertDiskStatus(self):
5991
    """Try to revert the disk status after a failed migration.
5992

5993
    """
5994
    target_node = self.target_node
5995
    try:
5996
      self._EnsureSecondary(target_node)
5997
      self._GoStandalone()
5998
      self._GoReconnect(False)
5999
      self._WaitUntilSync()
6000
    except errors.OpExecError, err:
6001
      self.lu.LogWarning("Migration failed and I can't reconnect the"
6002
                         " drives: error '%s'\n"
6003
                         "Please look and recover the instance status" %
6004
                         str(err))
6005

    
6006
  def _AbortMigration(self):
6007
    """Call the hypervisor code to abort a started migration.
6008

6009
    """
6010
    instance = self.instance
6011
    target_node = self.target_node
6012
    migration_info = self.migration_info
6013

    
6014
    abort_result = self.rpc.call_finalize_migration(target_node,
6015
                                                    instance,
6016
                                                    migration_info,
6017
                                                    False)
6018
    abort_msg = abort_result.fail_msg
6019
    if abort_msg:
6020
      logging.error("Aborting migration failed on target node %s: %s",
6021
                    target_node, abort_msg)
6022
      # Don't raise an exception here, as we stil have to try to revert the
6023
      # disk status, even if this step failed.
6024

    
6025
  def _ExecMigration(self):
6026
    """Migrate an instance.
6027

6028
    The migrate is done by:
6029
      - change the disks into dual-master mode
6030
      - wait until disks are fully synchronized again
6031
      - migrate the instance
6032
      - change disks on the new secondary node (the old primary) to secondary
6033
      - wait until disks are fully synchronized
6034
      - change disks into single-master mode
6035

6036
    """
6037
    instance = self.instance
6038
    target_node = self.target_node
6039
    source_node = self.source_node
6040

    
6041
    self.feedback_fn("* checking disk consistency between source and target")
6042
    for dev in instance.disks:
6043
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6044
        raise errors.OpExecError("Disk %s is degraded or not fully"
6045
                                 " synchronized on target node,"
6046
                                 " aborting migrate." % dev.iv_name)
6047

    
6048
    # First get the migration information from the remote node
6049
    result = self.rpc.call_migration_info(source_node, instance)
6050
    msg = result.fail_msg
6051
    if msg:
6052
      log_err = ("Failed fetching source migration information from %s: %s" %
6053
                 (source_node, msg))
6054
      logging.error(log_err)
6055
      raise errors.OpExecError(log_err)
6056

    
6057
    self.migration_info = migration_info = result.payload
6058

    
6059
    # Then switch the disks to master/master mode
6060
    self._EnsureSecondary(target_node)
6061
    self._GoStandalone()
6062
    self._GoReconnect(True)
6063
    self._WaitUntilSync()
6064

    
6065
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6066
    result = self.rpc.call_accept_instance(target_node,
6067
                                           instance,
6068
                                           migration_info,
6069
                                           self.nodes_ip[target_node])
6070

    
6071
    msg = result.fail_msg
6072
    if msg:
6073
      logging.error("Instance pre-migration failed, trying to revert"
6074
                    " disk status: %s", msg)
6075
      self.feedback_fn("Pre-migration failed, aborting")
6076
      self._AbortMigration()
6077
      self._RevertDiskStatus()
6078
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6079
                               (instance.name, msg))
6080

    
6081
    self.feedback_fn("* migrating instance to %s" % target_node)
6082
    time.sleep(10)
6083
    result = self.rpc.call_instance_migrate(source_node, instance,
6084
                                            self.nodes_ip[target_node],
6085
                                            self.live)
6086
    msg = result.fail_msg
6087
    if msg:
6088
      logging.error("Instance migration failed, trying to revert"
6089
                    " disk status: %s", msg)
6090
      self.feedback_fn("Migration failed, aborting")
6091
      self._AbortMigration()
6092
      self._RevertDiskStatus()
6093
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6094
                               (instance.name, msg))
6095
    time.sleep(10)
6096

    
6097
    instance.primary_node = target_node
6098
    # distribute new instance config to the other nodes
6099
    self.cfg.Update(instance, self.feedback_fn)
6100

    
6101
    result = self.rpc.call_finalize_migration(target_node,
6102
                                              instance,
6103
                                              migration_info,
6104
                                              True)
6105
    msg = result.fail_msg
6106
    if msg:
6107
      logging.error("Instance migration succeeded, but finalization failed:"
6108
                    " %s", msg)
6109
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6110
                               msg)
6111

    
6112
    self._EnsureSecondary(source_node)
6113
    self._WaitUntilSync()
6114
    self._GoStandalone()
6115
    self._GoReconnect(False)
6116
    self._WaitUntilSync()
6117

    
6118
    self.feedback_fn("* done")
6119

    
6120
  def Exec(self, feedback_fn):
6121
    """Perform the migration.
6122

6123
    """
6124
    feedback_fn("Migrating instance %s" % self.instance.name)
6125

    
6126
    self.feedback_fn = feedback_fn
6127

    
6128
    self.source_node = self.instance.primary_node
6129
    self.target_node = self.instance.secondary_nodes[0]
6130
    self.all_nodes = [self.source_node, self.target_node]
6131
    self.nodes_ip = {
6132
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6133
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6134
      }
6135

    
6136
    if self.cleanup:
6137
      return self._ExecCleanup()
6138
    else:
6139
      return self._ExecMigration()
6140

    
6141

    
6142
def _CreateBlockDev(lu, node, instance, device, force_create,
6143
                    info, force_open):
6144
  """Create a tree of block devices on a given node.
6145

6146
  If this device type has to be created on secondaries, create it and
6147
  all its children.
6148

6149
  If not, just recurse to children keeping the same 'force' value.
6150

6151
  @param lu: the lu on whose behalf we execute
6152
  @param node: the node on which to create the device
6153
  @type instance: L{objects.Instance}
6154
  @param instance: the instance which owns the device
6155
  @type device: L{objects.Disk}
6156
  @param device: the device to create
6157
  @type force_create: boolean
6158
  @param force_create: whether to force creation of this device; this
6159
      will be change to True whenever we find a device which has
6160
      CreateOnSecondary() attribute
6161
  @param info: the extra 'metadata' we should attach to the device
6162
      (this will be represented as a LVM tag)
6163
  @type force_open: boolean
6164
  @param force_open: this parameter will be passes to the
6165
      L{backend.BlockdevCreate} function where it specifies
6166
      whether we run on primary or not, and it affects both
6167
      the child assembly and the device own Open() execution
6168

6169
  """
6170
  if device.CreateOnSecondary():
6171
    force_create = True
6172

    
6173
  if device.children:
6174
    for child in device.children:
6175
      _CreateBlockDev(lu, node, instance, child, force_create,
6176
                      info, force_open)
6177

    
6178
  if not force_create:
6179
    return
6180

    
6181
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6182

    
6183

    
6184
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6185
  """Create a single block device on a given node.
6186

6187
  This will not recurse over children of the device, so they must be
6188
  created in advance.
6189

6190
  @param lu: the lu on whose behalf we execute
6191
  @param node: the node on which to create the device
6192
  @type instance: L{objects.Instance}
6193
  @param instance: the instance which owns the device
6194
  @type device: L{objects.Disk}
6195
  @param device: the device to create
6196
  @param info: the extra 'metadata' we should attach to the device
6197
      (this will be represented as a LVM tag)
6198
  @type force_open: boolean
6199
  @param force_open: this parameter will be passes to the
6200
      L{backend.BlockdevCreate} function where it specifies
6201
      whether we run on primary or not, and it affects both
6202
      the child assembly and the device own Open() execution
6203

6204
  """
6205
  lu.cfg.SetDiskID(device, node)
6206
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6207
                                       instance.name, force_open, info)
6208
  result.Raise("Can't create block device %s on"
6209
               " node %s for instance %s" % (device, node, instance.name))
6210
  if device.physical_id is None:
6211
    device.physical_id = result.payload
6212

    
6213

    
6214
def _GenerateUniqueNames(lu, exts):
6215
  """Generate a suitable LV name.
6216

6217
  This will generate a logical volume name for the given instance.
6218

6219
  """
6220
  results = []
6221
  for val in exts:
6222
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6223
    results.append("%s%s" % (new_id, val))
6224
  return results
6225

    
6226

    
6227
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
6228
                         p_minor, s_minor):
6229
  """Generate a drbd8 device complete with its children.
6230

6231
  """
6232
  port = lu.cfg.AllocatePort()
6233
  vgname = lu.cfg.GetVGName()
6234
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6235
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6236
                          logical_id=(vgname, names[0]))
6237
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6238
                          logical_id=(vgname, names[1]))
6239
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6240
                          logical_id=(primary, secondary, port,
6241
                                      p_minor, s_minor,
6242
                                      shared_secret),
6243
                          children=[dev_data, dev_meta],
6244
                          iv_name=iv_name)
6245
  return drbd_dev
6246

    
6247

    
6248
def _GenerateDiskTemplate(lu, template_name,
6249
                          instance_name, primary_node,
6250
                          secondary_nodes, disk_info,
6251
                          file_storage_dir, file_driver,
6252
                          base_index):
6253
  """Generate the entire disk layout for a given template type.
6254

6255
  """
6256
  #TODO: compute space requirements
6257

    
6258
  vgname = lu.cfg.GetVGName()
6259
  disk_count = len(disk_info)
6260
  disks = []
6261
  if template_name == constants.DT_DISKLESS:
6262
    pass
6263
  elif template_name == constants.DT_PLAIN:
6264
    if len(secondary_nodes) != 0:
6265
      raise errors.ProgrammerError("Wrong template configuration")
6266

    
6267
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6268
                                      for i in range(disk_count)])
6269
    for idx, disk in enumerate(disk_info):
6270
      disk_index = idx + base_index
6271
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6272
                              logical_id=(vgname, names[idx]),
6273
                              iv_name="disk/%d" % disk_index,
6274
                              mode=disk["mode"])
6275
      disks.append(disk_dev)
6276
  elif template_name == constants.DT_DRBD8:
6277
    if len(secondary_nodes) != 1:
6278
      raise errors.ProgrammerError("Wrong template configuration")
6279
    remote_node = secondary_nodes[0]
6280
    minors = lu.cfg.AllocateDRBDMinor(
6281
      [primary_node, remote_node] * len(disk_info), instance_name)
6282

    
6283
    names = []
6284
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6285
                                               for i in range(disk_count)]):
6286
      names.append(lv_prefix + "_data")
6287
      names.append(lv_prefix + "_meta")
6288
    for idx, disk in enumerate(disk_info):
6289
      disk_index = idx + base_index
6290
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6291
                                      disk["size"], names[idx*2:idx*2+2],
6292
                                      "disk/%d" % disk_index,
6293
                                      minors[idx*2], minors[idx*2+1])
6294
      disk_dev.mode = disk["mode"]
6295
      disks.append(disk_dev)
6296
  elif template_name == constants.DT_FILE:
6297
    if len(secondary_nodes) != 0:
6298
      raise errors.ProgrammerError("Wrong template configuration")
6299

    
6300
    _RequireFileStorage()
6301

    
6302
    for idx, disk in enumerate(disk_info):
6303
      disk_index = idx + base_index
6304
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6305
                              iv_name="disk/%d" % disk_index,
6306
                              logical_id=(file_driver,
6307
                                          "%s/disk%d" % (file_storage_dir,
6308
                                                         disk_index)),
6309
                              mode=disk["mode"])
6310
      disks.append(disk_dev)
6311
  else:
6312
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6313
  return disks
6314

    
6315

    
6316
def _GetInstanceInfoText(instance):
6317
  """Compute that text that should be added to the disk's metadata.
6318

6319
  """
6320
  return "originstname+%s" % instance.name
6321

    
6322

    
6323
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6324
  """Create all disks for an instance.
6325

6326
  This abstracts away some work from AddInstance.
6327

6328
  @type lu: L{LogicalUnit}
6329
  @param lu: the logical unit on whose behalf we execute
6330
  @type instance: L{objects.Instance}
6331
  @param instance: the instance whose disks we should create
6332
  @type to_skip: list
6333
  @param to_skip: list of indices to skip
6334
  @type target_node: string
6335
  @param target_node: if passed, overrides the target node for creation
6336
  @rtype: boolean
6337
  @return: the success of the creation
6338

6339
  """
6340
  info = _GetInstanceInfoText(instance)
6341
  if target_node is None:
6342
    pnode = instance.primary_node
6343
    all_nodes = instance.all_nodes
6344
  else:
6345
    pnode = target_node
6346
    all_nodes = [pnode]
6347

    
6348
  if instance.disk_template == constants.DT_FILE:
6349
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6350
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6351

    
6352
    result.Raise("Failed to create directory '%s' on"
6353
                 " node %s" % (file_storage_dir, pnode))
6354

    
6355
  # Note: this needs to be kept in sync with adding of disks in
6356
  # LUSetInstanceParams
6357
  for idx, device in enumerate(instance.disks):
6358
    if to_skip and idx in to_skip:
6359
      continue
6360
    logging.info("Creating volume %s for instance %s",
6361
                 device.iv_name, instance.name)
6362
    #HARDCODE
6363
    for node in all_nodes:
6364
      f_create = node == pnode
6365
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6366

    
6367

    
6368
def _RemoveDisks(lu, instance, target_node=None):
6369
  """Remove all disks for an instance.
6370

6371
  This abstracts away some work from `AddInstance()` and
6372
  `RemoveInstance()`. Note that in case some of the devices couldn't
6373
  be removed, the removal will continue with the other ones (compare
6374
  with `_CreateDisks()`).
6375

6376
  @type lu: L{LogicalUnit}
6377
  @param lu: the logical unit on whose behalf we execute
6378
  @type instance: L{objects.Instance}
6379
  @param instance: the instance whose disks we should remove
6380
  @type target_node: string
6381
  @param target_node: used to override the node on which to remove the disks
6382
  @rtype: boolean
6383
  @return: the success of the removal
6384

6385
  """
6386
  logging.info("Removing block devices for instance %s", instance.name)
6387

    
6388
  all_result = True
6389
  for device in instance.disks:
6390
    if target_node:
6391
      edata = [(target_node, device)]
6392
    else:
6393
      edata = device.ComputeNodeTree(instance.primary_node)
6394
    for node, disk in edata:
6395
      lu.cfg.SetDiskID(disk, node)
6396
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6397
      if msg:
6398
        lu.LogWarning("Could not remove block device %s on node %s,"
6399
                      " continuing anyway: %s", device.iv_name, node, msg)
6400
        all_result = False
6401

    
6402
  if instance.disk_template == constants.DT_FILE:
6403
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6404
    if target_node:
6405
      tgt = target_node
6406
    else:
6407
      tgt = instance.primary_node
6408
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6409
    if result.fail_msg:
6410
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6411
                    file_storage_dir, instance.primary_node, result.fail_msg)
6412
      all_result = False
6413

    
6414
  return all_result
6415

    
6416

    
6417
def _ComputeDiskSize(disk_template, disks):
6418
  """Compute disk size requirements in the volume group
6419

6420
  """
6421
  # Required free disk space as a function of disk and swap space
6422
  req_size_dict = {
6423
    constants.DT_DISKLESS: None,
6424
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6425
    # 128 MB are added for drbd metadata for each disk
6426
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6427
    constants.DT_FILE: None,
6428
  }
6429

    
6430
  if disk_template not in req_size_dict:
6431
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6432
                                 " is unknown" %  disk_template)
6433

    
6434
  return req_size_dict[disk_template]
6435

    
6436

    
6437
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6438
  """Hypervisor parameter validation.
6439

6440
  This function abstract the hypervisor parameter validation to be
6441
  used in both instance create and instance modify.
6442

6443
  @type lu: L{LogicalUnit}
6444
  @param lu: the logical unit for which we check
6445
  @type nodenames: list
6446
  @param nodenames: the list of nodes on which we should check
6447
  @type hvname: string
6448
  @param hvname: the name of the hypervisor we should use
6449
  @type hvparams: dict
6450
  @param hvparams: the parameters which we need to check
6451
  @raise errors.OpPrereqError: if the parameters are not valid
6452

6453
  """
6454
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6455
                                                  hvname,
6456
                                                  hvparams)
6457
  for node in nodenames:
6458
    info = hvinfo[node]
6459
    if info.offline:
6460
      continue
6461
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6462

    
6463

    
6464
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6465
  """OS parameters validation.
6466

6467
  @type lu: L{LogicalUnit}
6468
  @param lu: the logical unit for which we check
6469
  @type required: boolean
6470
  @param required: whether the validation should fail if the OS is not
6471
      found
6472
  @type nodenames: list
6473
  @param nodenames: the list of nodes on which we should check
6474
  @type osname: string
6475
  @param osname: the name of the hypervisor we should use
6476
  @type osparams: dict
6477
  @param osparams: the parameters which we need to check
6478
  @raise errors.OpPrereqError: if the parameters are not valid
6479

6480
  """
6481
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6482
                                   [constants.OS_VALIDATE_PARAMETERS],
6483
                                   osparams)
6484
  for node, nres in result.items():
6485
    # we don't check for offline cases since this should be run only
6486
    # against the master node and/or an instance's nodes
6487
    nres.Raise("OS Parameters validation failed on node %s" % node)
6488
    if not nres.payload:
6489
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6490
                 osname, node)
6491

    
6492

    
6493
class LUCreateInstance(LogicalUnit):
6494
  """Create an instance.
6495

6496
  """
6497
  HPATH = "instance-add"
6498
  HTYPE = constants.HTYPE_INSTANCE
6499
  _OP_PARAMS = [
6500
    _PInstanceName,
6501
    ("mode", _NoDefault, _TElemOf(constants.INSTANCE_CREATE_MODES)),
6502
    ("start", True, _TBool),
6503
    ("wait_for_sync", True, _TBool),
6504
    ("ip_check", True, _TBool),
6505
    ("name_check", True, _TBool),
6506
    ("disks", _NoDefault, _TListOf(_TDict)),
6507
    ("nics", _NoDefault, _TListOf(_TDict)),
6508
    ("hvparams", _EmptyDict, _TDict),
6509
    ("beparams", _EmptyDict, _TDict),
6510
    ("osparams", _EmptyDict, _TDict),
6511
    ("no_install", None, _TMaybeBool),
6512
    ("os_type", None, _TMaybeString),
6513
    ("force_variant", False, _TBool),
6514
    ("source_handshake", None, _TOr(_TList, _TNone)),
6515
    ("source_x509_ca", None, _TMaybeString),
6516
    ("source_instance_name", None, _TMaybeString),
6517
    ("src_node", None, _TMaybeString),
6518
    ("src_path", None, _TMaybeString),
6519
    ("pnode", None, _TMaybeString),
6520
    ("snode", None, _TMaybeString),
6521
    ("iallocator", None, _TMaybeString),
6522
    ("hypervisor", None, _TMaybeString),
6523
    ("disk_template", _NoDefault, _CheckDiskTemplate),
6524
    ("identify_defaults", False, _TBool),
6525
    ("file_driver", None, _TOr(_TNone, _TElemOf(constants.FILE_DRIVER))),
6526
    ("file_storage_dir", None, _TMaybeString),
6527
    ("dry_run", False, _TBool),
6528
    ]
6529
  REQ_BGL = False
6530

    
6531
  def CheckArguments(self):
6532
    """Check arguments.
6533

6534
    """
6535
    # do not require name_check to ease forward/backward compatibility
6536
    # for tools
6537
    if self.op.no_install and self.op.start:
6538
      self.LogInfo("No-installation mode selected, disabling startup")
6539
      self.op.start = False
6540
    # validate/normalize the instance name
6541
    self.op.instance_name = \
6542
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
6543

    
6544
    if self.op.ip_check and not self.op.name_check:
6545
      # TODO: make the ip check more flexible and not depend on the name check
6546
      raise errors.OpPrereqError("Cannot do ip check without a name check",
6547
                                 errors.ECODE_INVAL)
6548

    
6549
    # check nics' parameter names
6550
    for nic in self.op.nics:
6551
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6552

    
6553
    # check disks. parameter names and consistent adopt/no-adopt strategy
6554
    has_adopt = has_no_adopt = False
6555
    for disk in self.op.disks:
6556
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6557
      if "adopt" in disk:
6558
        has_adopt = True
6559
      else:
6560
        has_no_adopt = True
6561
    if has_adopt and has_no_adopt:
6562
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6563
                                 errors.ECODE_INVAL)
6564
    if has_adopt:
6565
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6566
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6567
                                   " '%s' disk template" %
6568
                                   self.op.disk_template,
6569
                                   errors.ECODE_INVAL)
6570
      if self.op.iallocator is not None:
6571
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6572
                                   " iallocator script", errors.ECODE_INVAL)
6573
      if self.op.mode == constants.INSTANCE_IMPORT:
6574
        raise errors.OpPrereqError("Disk adoption not allowed for"
6575
                                   " instance import", errors.ECODE_INVAL)
6576

    
6577
    self.adopt_disks = has_adopt
6578

    
6579
    # instance name verification
6580
    if self.op.name_check:
6581
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
6582
      self.op.instance_name = self.hostname1.name
6583
      # used in CheckPrereq for ip ping check
6584
      self.check_ip = self.hostname1.ip
6585
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6586
      raise errors.OpPrereqError("Remote imports require names to be checked" %
6587
                                 errors.ECODE_INVAL)
6588
    else:
6589
      self.check_ip = None
6590

    
6591
    # file storage checks
6592
    if (self.op.file_driver and
6593
        not self.op.file_driver in constants.FILE_DRIVER):
6594
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6595
                                 self.op.file_driver, errors.ECODE_INVAL)
6596

    
6597
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6598
      raise errors.OpPrereqError("File storage directory path not absolute",
6599
                                 errors.ECODE_INVAL)
6600

    
6601
    ### Node/iallocator related checks
6602
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
6603

    
6604
    self._cds = _GetClusterDomainSecret()
6605

    
6606
    if self.op.mode == constants.INSTANCE_IMPORT:
6607
      # On import force_variant must be True, because if we forced it at
6608
      # initial install, our only chance when importing it back is that it
6609
      # works again!
6610
      self.op.force_variant = True
6611

    
6612
      if self.op.no_install:
6613
        self.LogInfo("No-installation mode has no effect during import")
6614

    
6615
    elif self.op.mode == constants.INSTANCE_CREATE:
6616
      if self.op.os_type is None:
6617
        raise errors.OpPrereqError("No guest OS specified",
6618
                                   errors.ECODE_INVAL)
6619
      if self.op.disk_template is None:
6620
        raise errors.OpPrereqError("No disk template specified",
6621
                                   errors.ECODE_INVAL)
6622

    
6623
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6624
      # Check handshake to ensure both clusters have the same domain secret
6625
      src_handshake = self.op.source_handshake
6626
      if not src_handshake:
6627
        raise errors.OpPrereqError("Missing source handshake",
6628
                                   errors.ECODE_INVAL)
6629

    
6630
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6631
                                                           src_handshake)
6632
      if errmsg:
6633
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6634
                                   errors.ECODE_INVAL)
6635

    
6636
      # Load and check source CA
6637
      self.source_x509_ca_pem = self.op.source_x509_ca
6638
      if not self.source_x509_ca_pem:
6639
        raise errors.OpPrereqError("Missing source X509 CA",
6640
                                   errors.ECODE_INVAL)
6641

    
6642
      try:
6643
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
6644
                                                    self._cds)
6645
      except OpenSSL.crypto.Error, err:
6646
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
6647
                                   (err, ), errors.ECODE_INVAL)
6648

    
6649
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
6650
      if errcode is not None:
6651
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
6652
                                   errors.ECODE_INVAL)
6653

    
6654
      self.source_x509_ca = cert
6655

    
6656
      src_instance_name = self.op.source_instance_name
6657
      if not src_instance_name:
6658
        raise errors.OpPrereqError("Missing source instance name",
6659
                                   errors.ECODE_INVAL)
6660

    
6661
      self.source_instance_name = \
6662
          netutils.GetHostname(name=src_instance_name).name
6663

    
6664
    else:
6665
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
6666
                                 self.op.mode, errors.ECODE_INVAL)
6667

    
6668
  def ExpandNames(self):
6669
    """ExpandNames for CreateInstance.
6670

6671
    Figure out the right locks for instance creation.
6672

6673
    """
6674
    self.needed_locks = {}
6675

    
6676
    instance_name = self.op.instance_name
6677
    # this is just a preventive check, but someone might still add this
6678
    # instance in the meantime, and creation will fail at lock-add time
6679
    if instance_name in self.cfg.GetInstanceList():
6680
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6681
                                 instance_name, errors.ECODE_EXISTS)
6682

    
6683
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
6684

    
6685
    if self.op.iallocator:
6686
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6687
    else:
6688
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
6689
      nodelist = [self.op.pnode]
6690
      if self.op.snode is not None:
6691
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
6692
        nodelist.append(self.op.snode)
6693
      self.needed_locks[locking.LEVEL_NODE] = nodelist
6694

    
6695
    # in case of import lock the source node too
6696
    if self.op.mode == constants.INSTANCE_IMPORT:
6697
      src_node = self.op.src_node
6698
      src_path = self.op.src_path
6699

    
6700
      if src_path is None:
6701
        self.op.src_path = src_path = self.op.instance_name
6702

    
6703
      if src_node is None:
6704
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6705
        self.op.src_node = None
6706
        if os.path.isabs(src_path):
6707
          raise errors.OpPrereqError("Importing an instance from an absolute"
6708
                                     " path requires a source node option.",
6709
                                     errors.ECODE_INVAL)
6710
      else:
6711
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
6712
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
6713
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
6714
        if not os.path.isabs(src_path):
6715
          self.op.src_path = src_path = \
6716
            utils.PathJoin(constants.EXPORT_DIR, src_path)
6717

    
6718
  def _RunAllocator(self):
6719
    """Run the allocator based on input opcode.
6720

6721
    """
6722
    nics = [n.ToDict() for n in self.nics]
6723
    ial = IAllocator(self.cfg, self.rpc,
6724
                     mode=constants.IALLOCATOR_MODE_ALLOC,
6725
                     name=self.op.instance_name,
6726
                     disk_template=self.op.disk_template,
6727
                     tags=[],
6728
                     os=self.op.os_type,
6729
                     vcpus=self.be_full[constants.BE_VCPUS],
6730
                     mem_size=self.be_full[constants.BE_MEMORY],
6731
                     disks=self.disks,
6732
                     nics=nics,
6733
                     hypervisor=self.op.hypervisor,
6734
                     )
6735

    
6736
    ial.Run(self.op.iallocator)
6737

    
6738
    if not ial.success:
6739
      raise errors.OpPrereqError("Can't compute nodes using"
6740
                                 " iallocator '%s': %s" %
6741
                                 (self.op.iallocator, ial.info),
6742
                                 errors.ECODE_NORES)
6743
    if len(ial.result) != ial.required_nodes:
6744
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6745
                                 " of nodes (%s), required %s" %
6746
                                 (self.op.iallocator, len(ial.result),
6747
                                  ial.required_nodes), errors.ECODE_FAULT)
6748
    self.op.pnode = ial.result[0]
6749
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6750
                 self.op.instance_name, self.op.iallocator,
6751
                 utils.CommaJoin(ial.result))
6752
    if ial.required_nodes == 2:
6753
      self.op.snode = ial.result[1]
6754

    
6755
  def BuildHooksEnv(self):
6756
    """Build hooks env.
6757

6758
    This runs on master, primary and secondary nodes of the instance.
6759

6760
    """
6761
    env = {
6762
      "ADD_MODE": self.op.mode,
6763
      }
6764
    if self.op.mode == constants.INSTANCE_IMPORT:
6765
      env["SRC_NODE"] = self.op.src_node
6766
      env["SRC_PATH"] = self.op.src_path
6767
      env["SRC_IMAGES"] = self.src_images
6768

    
6769
    env.update(_BuildInstanceHookEnv(
6770
      name=self.op.instance_name,
6771
      primary_node=self.op.pnode,
6772
      secondary_nodes=self.secondaries,
6773
      status=self.op.start,
6774
      os_type=self.op.os_type,
6775
      memory=self.be_full[constants.BE_MEMORY],
6776
      vcpus=self.be_full[constants.BE_VCPUS],
6777
      nics=_NICListToTuple(self, self.nics),
6778
      disk_template=self.op.disk_template,
6779
      disks=[(d["size"], d["mode"]) for d in self.disks],
6780
      bep=self.be_full,
6781
      hvp=self.hv_full,
6782
      hypervisor_name=self.op.hypervisor,
6783
    ))
6784

    
6785
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
6786
          self.secondaries)
6787
    return env, nl, nl
6788

    
6789
  def _ReadExportInfo(self):
6790
    """Reads the export information from disk.
6791

6792
    It will override the opcode source node and path with the actual
6793
    information, if these two were not specified before.
6794

6795
    @return: the export information
6796

6797
    """
6798
    assert self.op.mode == constants.INSTANCE_IMPORT
6799

    
6800
    src_node = self.op.src_node
6801
    src_path = self.op.src_path
6802

    
6803
    if src_node is None:
6804
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
6805
      exp_list = self.rpc.call_export_list(locked_nodes)
6806
      found = False
6807
      for node in exp_list:
6808
        if exp_list[node].fail_msg:
6809
          continue
6810
        if src_path in exp_list[node].payload:
6811
          found = True
6812
          self.op.src_node = src_node = node
6813
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
6814
                                                       src_path)
6815
          break
6816
      if not found:
6817
        raise errors.OpPrereqError("No export found for relative path %s" %
6818
                                    src_path, errors.ECODE_INVAL)
6819

    
6820
    _CheckNodeOnline(self, src_node)
6821
    result = self.rpc.call_export_info(src_node, src_path)
6822
    result.Raise("No export or invalid export found in dir %s" % src_path)
6823

    
6824
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
6825
    if not export_info.has_section(constants.INISECT_EXP):
6826
      raise errors.ProgrammerError("Corrupted export config",
6827
                                   errors.ECODE_ENVIRON)
6828

    
6829
    ei_version = export_info.get(constants.INISECT_EXP, "version")
6830
    if (int(ei_version) != constants.EXPORT_VERSION):
6831
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
6832
                                 (ei_version, constants.EXPORT_VERSION),
6833
                                 errors.ECODE_ENVIRON)
6834
    return export_info
6835

    
6836
  def _ReadExportParams(self, einfo):
6837
    """Use export parameters as defaults.
6838

6839
    In case the opcode doesn't specify (as in override) some instance
6840
    parameters, then try to use them from the export information, if
6841
    that declares them.
6842

6843
    """
6844
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
6845

    
6846
    if self.op.disk_template is None:
6847
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
6848
        self.op.disk_template = einfo.get(constants.INISECT_INS,
6849
                                          "disk_template")
6850
      else:
6851
        raise errors.OpPrereqError("No disk template specified and the export"
6852
                                   " is missing the disk_template information",
6853
                                   errors.ECODE_INVAL)
6854

    
6855
    if not self.op.disks:
6856
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
6857
        disks = []
6858
        # TODO: import the disk iv_name too
6859
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
6860
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
6861
          disks.append({"size": disk_sz})
6862
        self.op.disks = disks
6863
      else:
6864
        raise errors.OpPrereqError("No disk info specified and the export"
6865
                                   " is missing the disk information",
6866
                                   errors.ECODE_INVAL)
6867

    
6868
    if (not self.op.nics and
6869
        einfo.has_option(constants.INISECT_INS, "nic_count")):
6870
      nics = []
6871
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
6872
        ndict = {}
6873
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
6874
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
6875
          ndict[name] = v
6876
        nics.append(ndict)
6877
      self.op.nics = nics
6878

    
6879
    if (self.op.hypervisor is None and
6880
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
6881
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
6882
    if einfo.has_section(constants.INISECT_HYP):
6883
      # use the export parameters but do not override the ones
6884
      # specified by the user
6885
      for name, value in einfo.items(constants.INISECT_HYP):
6886
        if name not in self.op.hvparams:
6887
          self.op.hvparams[name] = value
6888

    
6889
    if einfo.has_section(constants.INISECT_BEP):
6890
      # use the parameters, without overriding
6891
      for name, value in einfo.items(constants.INISECT_BEP):
6892
        if name not in self.op.beparams:
6893
          self.op.beparams[name] = value
6894
    else:
6895
      # try to read the parameters old style, from the main section
6896
      for name in constants.BES_PARAMETERS:
6897
        if (name not in self.op.beparams and
6898
            einfo.has_option(constants.INISECT_INS, name)):
6899
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
6900

    
6901
    if einfo.has_section(constants.INISECT_OSP):
6902
      # use the parameters, without overriding
6903
      for name, value in einfo.items(constants.INISECT_OSP):
6904
        if name not in self.op.osparams:
6905
          self.op.osparams[name] = value
6906

    
6907
  def _RevertToDefaults(self, cluster):
6908
    """Revert the instance parameters to the default values.
6909

6910
    """
6911
    # hvparams
6912
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
6913
    for name in self.op.hvparams.keys():
6914
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
6915
        del self.op.hvparams[name]
6916
    # beparams
6917
    be_defs = cluster.SimpleFillBE({})
6918
    for name in self.op.beparams.keys():
6919
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
6920
        del self.op.beparams[name]
6921
    # nic params
6922
    nic_defs = cluster.SimpleFillNIC({})
6923
    for nic in self.op.nics:
6924
      for name in constants.NICS_PARAMETERS:
6925
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
6926
          del nic[name]
6927
    # osparams
6928
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
6929
    for name in self.op.osparams.keys():
6930
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
6931
        del self.op.osparams[name]
6932

    
6933
  def CheckPrereq(self):
6934
    """Check prerequisites.
6935

6936
    """
6937
    if self.op.mode == constants.INSTANCE_IMPORT:
6938
      export_info = self._ReadExportInfo()
6939
      self._ReadExportParams(export_info)
6940

    
6941
    _CheckDiskTemplate(self.op.disk_template)
6942

    
6943
    if (not self.cfg.GetVGName() and
6944
        self.op.disk_template not in constants.DTS_NOT_LVM):
6945
      raise errors.OpPrereqError("Cluster does not support lvm-based"
6946
                                 " instances", errors.ECODE_STATE)
6947

    
6948
    if self.op.hypervisor is None:
6949
      self.op.hypervisor = self.cfg.GetHypervisorType()
6950

    
6951
    cluster = self.cfg.GetClusterInfo()
6952
    enabled_hvs = cluster.enabled_hypervisors
6953
    if self.op.hypervisor not in enabled_hvs:
6954
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
6955
                                 " cluster (%s)" % (self.op.hypervisor,
6956
                                  ",".join(enabled_hvs)),
6957
                                 errors.ECODE_STATE)
6958

    
6959
    # check hypervisor parameter syntax (locally)
6960
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
6961
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
6962
                                      self.op.hvparams)
6963
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
6964
    hv_type.CheckParameterSyntax(filled_hvp)
6965
    self.hv_full = filled_hvp
6966
    # check that we don't specify global parameters on an instance
6967
    _CheckGlobalHvParams(self.op.hvparams)
6968

    
6969
    # fill and remember the beparams dict
6970
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
6971
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
6972

    
6973
    # build os parameters
6974
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
6975

    
6976
    # now that hvp/bep are in final format, let's reset to defaults,
6977
    # if told to do so
6978
    if self.op.identify_defaults:
6979
      self._RevertToDefaults(cluster)
6980

    
6981
    # NIC buildup
6982
    self.nics = []
6983
    for idx, nic in enumerate(self.op.nics):
6984
      nic_mode_req = nic.get("mode", None)
6985
      nic_mode = nic_mode_req
6986
      if nic_mode is None:
6987
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
6988

    
6989
      # in routed mode, for the first nic, the default ip is 'auto'
6990
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
6991
        default_ip_mode = constants.VALUE_AUTO
6992
      else:
6993
        default_ip_mode = constants.VALUE_NONE
6994

    
6995
      # ip validity checks
6996
      ip = nic.get("ip", default_ip_mode)
6997
      if ip is None or ip.lower() == constants.VALUE_NONE:
6998
        nic_ip = None
6999
      elif ip.lower() == constants.VALUE_AUTO:
7000
        if not self.op.name_check:
7001
          raise errors.OpPrereqError("IP address set to auto but name checks"
7002
                                     " have been skipped",
7003
                                     errors.ECODE_INVAL)
7004
        nic_ip = self.hostname1.ip
7005
      else:
7006
        if not netutils.IPAddress.IsValid(ip):
7007
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
7008
                                     errors.ECODE_INVAL)
7009
        nic_ip = ip
7010

    
7011
      # TODO: check the ip address for uniqueness
7012
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7013
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7014
                                   errors.ECODE_INVAL)
7015

    
7016
      # MAC address verification
7017
      mac = nic.get("mac", constants.VALUE_AUTO)
7018
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7019
        mac = utils.NormalizeAndValidateMac(mac)
7020

    
7021
        try:
7022
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7023
        except errors.ReservationError:
7024
          raise errors.OpPrereqError("MAC address %s already in use"
7025
                                     " in cluster" % mac,
7026
                                     errors.ECODE_NOTUNIQUE)
7027

    
7028
      # bridge verification
7029
      bridge = nic.get("bridge", None)
7030
      link = nic.get("link", None)
7031
      if bridge and link:
7032
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7033
                                   " at the same time", errors.ECODE_INVAL)
7034
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7035
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7036
                                   errors.ECODE_INVAL)
7037
      elif bridge:
7038
        link = bridge
7039

    
7040
      nicparams = {}
7041
      if nic_mode_req:
7042
        nicparams[constants.NIC_MODE] = nic_mode_req
7043
      if link:
7044
        nicparams[constants.NIC_LINK] = link
7045

    
7046
      check_params = cluster.SimpleFillNIC(nicparams)
7047
      objects.NIC.CheckParameterSyntax(check_params)
7048
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7049

    
7050
    # disk checks/pre-build
7051
    self.disks = []
7052
    for disk in self.op.disks:
7053
      mode = disk.get("mode", constants.DISK_RDWR)
7054
      if mode not in constants.DISK_ACCESS_SET:
7055
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7056
                                   mode, errors.ECODE_INVAL)
7057
      size = disk.get("size", None)
7058
      if size is None:
7059
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7060
      try:
7061
        size = int(size)
7062
      except (TypeError, ValueError):
7063
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7064
                                   errors.ECODE_INVAL)
7065
      new_disk = {"size": size, "mode": mode}
7066
      if "adopt" in disk:
7067
        new_disk["adopt"] = disk["adopt"]
7068
      self.disks.append(new_disk)
7069

    
7070
    if self.op.mode == constants.INSTANCE_IMPORT:
7071

    
7072
      # Check that the new instance doesn't have less disks than the export
7073
      instance_disks = len(self.disks)
7074
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7075
      if instance_disks < export_disks:
7076
        raise errors.OpPrereqError("Not enough disks to import."
7077
                                   " (instance: %d, export: %d)" %
7078
                                   (instance_disks, export_disks),
7079
                                   errors.ECODE_INVAL)
7080

    
7081
      disk_images = []
7082
      for idx in range(export_disks):
7083
        option = 'disk%d_dump' % idx
7084
        if export_info.has_option(constants.INISECT_INS, option):
7085
          # FIXME: are the old os-es, disk sizes, etc. useful?
7086
          export_name = export_info.get(constants.INISECT_INS, option)
7087
          image = utils.PathJoin(self.op.src_path, export_name)
7088
          disk_images.append(image)
7089
        else:
7090
          disk_images.append(False)
7091

    
7092
      self.src_images = disk_images
7093

    
7094
      old_name = export_info.get(constants.INISECT_INS, 'name')
7095
      try:
7096
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7097
      except (TypeError, ValueError), err:
7098
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7099
                                   " an integer: %s" % str(err),
7100
                                   errors.ECODE_STATE)
7101
      if self.op.instance_name == old_name:
7102
        for idx, nic in enumerate(self.nics):
7103
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7104
            nic_mac_ini = 'nic%d_mac' % idx
7105
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7106

    
7107
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7108

    
7109
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7110
    if self.op.ip_check:
7111
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7112
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7113
                                   (self.check_ip, self.op.instance_name),
7114
                                   errors.ECODE_NOTUNIQUE)
7115

    
7116
    #### mac address generation
7117
    # By generating here the mac address both the allocator and the hooks get
7118
    # the real final mac address rather than the 'auto' or 'generate' value.
7119
    # There is a race condition between the generation and the instance object
7120
    # creation, which means that we know the mac is valid now, but we're not
7121
    # sure it will be when we actually add the instance. If things go bad
7122
    # adding the instance will abort because of a duplicate mac, and the
7123
    # creation job will fail.
7124
    for nic in self.nics:
7125
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7126
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7127

    
7128
    #### allocator run
7129

    
7130
    if self.op.iallocator is not None:
7131
      self._RunAllocator()
7132

    
7133
    #### node related checks
7134

    
7135
    # check primary node
7136
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7137
    assert self.pnode is not None, \
7138
      "Cannot retrieve locked node %s" % self.op.pnode
7139
    if pnode.offline:
7140
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7141
                                 pnode.name, errors.ECODE_STATE)
7142
    if pnode.drained:
7143
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7144
                                 pnode.name, errors.ECODE_STATE)
7145

    
7146
    self.secondaries = []
7147

    
7148
    # mirror node verification
7149
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7150
      if self.op.snode is None:
7151
        raise errors.OpPrereqError("The networked disk templates need"
7152
                                   " a mirror node", errors.ECODE_INVAL)
7153
      if self.op.snode == pnode.name:
7154
        raise errors.OpPrereqError("The secondary node cannot be the"
7155
                                   " primary node.", errors.ECODE_INVAL)
7156
      _CheckNodeOnline(self, self.op.snode)
7157
      _CheckNodeNotDrained(self, self.op.snode)
7158
      self.secondaries.append(self.op.snode)
7159

    
7160
    nodenames = [pnode.name] + self.secondaries
7161

    
7162
    req_size = _ComputeDiskSize(self.op.disk_template,
7163
                                self.disks)
7164

    
7165
    # Check lv size requirements, if not adopting
7166
    if req_size is not None and not self.adopt_disks:
7167
      _CheckNodesFreeDisk(self, nodenames, req_size)
7168

    
7169
    if self.adopt_disks: # instead, we must check the adoption data
7170
      all_lvs = set([i["adopt"] for i in self.disks])
7171
      if len(all_lvs) != len(self.disks):
7172
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7173
                                   errors.ECODE_INVAL)
7174
      for lv_name in all_lvs:
7175
        try:
7176
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7177
        except errors.ReservationError:
7178
          raise errors.OpPrereqError("LV named %s used by another instance" %
7179
                                     lv_name, errors.ECODE_NOTUNIQUE)
7180

    
7181
      node_lvs = self.rpc.call_lv_list([pnode.name],
7182
                                       self.cfg.GetVGName())[pnode.name]
7183
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7184
      node_lvs = node_lvs.payload
7185
      delta = all_lvs.difference(node_lvs.keys())
7186
      if delta:
7187
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7188
                                   utils.CommaJoin(delta),
7189
                                   errors.ECODE_INVAL)
7190
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7191
      if online_lvs:
7192
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7193
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7194
                                   errors.ECODE_STATE)
7195
      # update the size of disk based on what is found
7196
      for dsk in self.disks:
7197
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
7198

    
7199
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7200

    
7201
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7202
    # check OS parameters (remotely)
7203
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7204

    
7205
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7206

    
7207
    # memory check on primary node
7208
    if self.op.start:
7209
      _CheckNodeFreeMemory(self, self.pnode.name,
7210
                           "creating instance %s" % self.op.instance_name,
7211
                           self.be_full[constants.BE_MEMORY],
7212
                           self.op.hypervisor)
7213

    
7214
    self.dry_run_result = list(nodenames)
7215

    
7216
  def Exec(self, feedback_fn):
7217
    """Create and add the instance to the cluster.
7218

7219
    """
7220
    instance = self.op.instance_name
7221
    pnode_name = self.pnode.name
7222

    
7223
    ht_kind = self.op.hypervisor
7224
    if ht_kind in constants.HTS_REQ_PORT:
7225
      network_port = self.cfg.AllocatePort()
7226
    else:
7227
      network_port = None
7228

    
7229
    if constants.ENABLE_FILE_STORAGE:
7230
      # this is needed because os.path.join does not accept None arguments
7231
      if self.op.file_storage_dir is None:
7232
        string_file_storage_dir = ""
7233
      else:
7234
        string_file_storage_dir = self.op.file_storage_dir
7235

    
7236
      # build the full file storage dir path
7237
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7238
                                        string_file_storage_dir, instance)
7239
    else:
7240
      file_storage_dir = ""
7241

    
7242
    disks = _GenerateDiskTemplate(self,
7243
                                  self.op.disk_template,
7244
                                  instance, pnode_name,
7245
                                  self.secondaries,
7246
                                  self.disks,
7247
                                  file_storage_dir,
7248
                                  self.op.file_driver,
7249
                                  0)
7250

    
7251
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7252
                            primary_node=pnode_name,
7253
                            nics=self.nics, disks=disks,
7254
                            disk_template=self.op.disk_template,
7255
                            admin_up=False,
7256
                            network_port=network_port,
7257
                            beparams=self.op.beparams,
7258
                            hvparams=self.op.hvparams,
7259
                            hypervisor=self.op.hypervisor,
7260
                            osparams=self.op.osparams,
7261
                            )
7262

    
7263
    if self.adopt_disks:
7264
      # rename LVs to the newly-generated names; we need to construct
7265
      # 'fake' LV disks with the old data, plus the new unique_id
7266
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7267
      rename_to = []
7268
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7269
        rename_to.append(t_dsk.logical_id)
7270
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7271
        self.cfg.SetDiskID(t_dsk, pnode_name)
7272
      result = self.rpc.call_blockdev_rename(pnode_name,
7273
                                             zip(tmp_disks, rename_to))
7274
      result.Raise("Failed to rename adoped LVs")
7275
    else:
7276
      feedback_fn("* creating instance disks...")
7277
      try:
7278
        _CreateDisks(self, iobj)
7279
      except errors.OpExecError:
7280
        self.LogWarning("Device creation failed, reverting...")
7281
        try:
7282
          _RemoveDisks(self, iobj)
7283
        finally:
7284
          self.cfg.ReleaseDRBDMinors(instance)
7285
          raise
7286

    
7287
    feedback_fn("adding instance %s to cluster config" % instance)
7288

    
7289
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7290

    
7291
    # Declare that we don't want to remove the instance lock anymore, as we've
7292
    # added the instance to the config
7293
    del self.remove_locks[locking.LEVEL_INSTANCE]
7294
    # Unlock all the nodes
7295
    if self.op.mode == constants.INSTANCE_IMPORT:
7296
      nodes_keep = [self.op.src_node]
7297
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7298
                       if node != self.op.src_node]
7299
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7300
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7301
    else:
7302
      self.context.glm.release(locking.LEVEL_NODE)
7303
      del self.acquired_locks[locking.LEVEL_NODE]
7304

    
7305
    if self.op.wait_for_sync:
7306
      disk_abort = not _WaitForSync(self, iobj)
7307
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7308
      # make sure the disks are not degraded (still sync-ing is ok)
7309
      time.sleep(15)
7310
      feedback_fn("* checking mirrors status")
7311
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7312
    else:
7313
      disk_abort = False
7314

    
7315
    if disk_abort:
7316
      _RemoveDisks(self, iobj)
7317
      self.cfg.RemoveInstance(iobj.name)
7318
      # Make sure the instance lock gets removed
7319
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7320
      raise errors.OpExecError("There are some degraded disks for"
7321
                               " this instance")
7322

    
7323
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7324
      if self.op.mode == constants.INSTANCE_CREATE:
7325
        if not self.op.no_install:
7326
          feedback_fn("* running the instance OS create scripts...")
7327
          # FIXME: pass debug option from opcode to backend
7328
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7329
                                                 self.op.debug_level)
7330
          result.Raise("Could not add os for instance %s"
7331
                       " on node %s" % (instance, pnode_name))
7332

    
7333
      elif self.op.mode == constants.INSTANCE_IMPORT:
7334
        feedback_fn("* running the instance OS import scripts...")
7335

    
7336
        transfers = []
7337

    
7338
        for idx, image in enumerate(self.src_images):
7339
          if not image:
7340
            continue
7341

    
7342
          # FIXME: pass debug option from opcode to backend
7343
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7344
                                             constants.IEIO_FILE, (image, ),
7345
                                             constants.IEIO_SCRIPT,
7346
                                             (iobj.disks[idx], idx),
7347
                                             None)
7348
          transfers.append(dt)
7349

    
7350
        import_result = \
7351
          masterd.instance.TransferInstanceData(self, feedback_fn,
7352
                                                self.op.src_node, pnode_name,
7353
                                                self.pnode.secondary_ip,
7354
                                                iobj, transfers)
7355
        if not compat.all(import_result):
7356
          self.LogWarning("Some disks for instance %s on node %s were not"
7357
                          " imported successfully" % (instance, pnode_name))
7358

    
7359
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7360
        feedback_fn("* preparing remote import...")
7361
        connect_timeout = constants.RIE_CONNECT_TIMEOUT
7362
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7363

    
7364
        disk_results = masterd.instance.RemoteImport(self, feedback_fn, iobj,
7365
                                                     self.source_x509_ca,
7366
                                                     self._cds, timeouts)
7367
        if not compat.all(disk_results):
7368
          # TODO: Should the instance still be started, even if some disks
7369
          # failed to import (valid for local imports, too)?
7370
          self.LogWarning("Some disks for instance %s on node %s were not"
7371
                          " imported successfully" % (instance, pnode_name))
7372

    
7373
        # Run rename script on newly imported instance
7374
        assert iobj.name == instance
7375
        feedback_fn("Running rename script for %s" % instance)
7376
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7377
                                                   self.source_instance_name,
7378
                                                   self.op.debug_level)
7379
        if result.fail_msg:
7380
          self.LogWarning("Failed to run rename script for %s on node"
7381
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7382

    
7383
      else:
7384
        # also checked in the prereq part
7385
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7386
                                     % self.op.mode)
7387

    
7388
    if self.op.start:
7389
      iobj.admin_up = True
7390
      self.cfg.Update(iobj, feedback_fn)
7391
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7392
      feedback_fn("* starting instance...")
7393
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7394
      result.Raise("Could not start instance")
7395

    
7396
    return list(iobj.all_nodes)
7397

    
7398

    
7399
class LUConnectConsole(NoHooksLU):
7400
  """Connect to an instance's console.
7401

7402
  This is somewhat special in that it returns the command line that
7403
  you need to run on the master node in order to connect to the
7404
  console.
7405

7406
  """
7407
  _OP_PARAMS = [
7408
    _PInstanceName
7409
    ]
7410
  REQ_BGL = False
7411

    
7412
  def ExpandNames(self):
7413
    self._ExpandAndLockInstance()
7414

    
7415
  def CheckPrereq(self):
7416
    """Check prerequisites.
7417

7418
    This checks that the instance is in the cluster.
7419

7420
    """
7421
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7422
    assert self.instance is not None, \
7423
      "Cannot retrieve locked instance %s" % self.op.instance_name
7424
    _CheckNodeOnline(self, self.instance.primary_node)
7425

    
7426
  def Exec(self, feedback_fn):
7427
    """Connect to the console of an instance
7428

7429
    """
7430
    instance = self.instance
7431
    node = instance.primary_node
7432

    
7433
    node_insts = self.rpc.call_instance_list([node],
7434
                                             [instance.hypervisor])[node]
7435
    node_insts.Raise("Can't get node information from %s" % node)
7436

    
7437
    if instance.name not in node_insts.payload:
7438
      raise errors.OpExecError("Instance %s is not running." % instance.name)
7439

    
7440
    logging.debug("Connecting to console of %s on %s", instance.name, node)
7441

    
7442
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
7443
    cluster = self.cfg.GetClusterInfo()
7444
    # beparams and hvparams are passed separately, to avoid editing the
7445
    # instance and then saving the defaults in the instance itself.
7446
    hvparams = cluster.FillHV(instance)
7447
    beparams = cluster.FillBE(instance)
7448
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
7449

    
7450
    # build ssh cmdline
7451
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
7452

    
7453

    
7454
class LUReplaceDisks(LogicalUnit):
7455
  """Replace the disks of an instance.
7456

7457
  """
7458
  HPATH = "mirrors-replace"
7459
  HTYPE = constants.HTYPE_INSTANCE
7460
  _OP_PARAMS = [
7461
    _PInstanceName,
7462
    ("mode", _NoDefault, _TElemOf(constants.REPLACE_MODES)),
7463
    ("disks", _EmptyList, _TListOf(_TPositiveInt)),
7464
    ("remote_node", None, _TMaybeString),
7465
    ("iallocator", None, _TMaybeString),
7466
    ("early_release", False, _TBool),
7467
    ]
7468
  REQ_BGL = False
7469

    
7470
  def CheckArguments(self):
7471
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7472
                                  self.op.iallocator)
7473

    
7474
  def ExpandNames(self):
7475
    self._ExpandAndLockInstance()
7476

    
7477
    if self.op.iallocator is not None:
7478
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7479

    
7480
    elif self.op.remote_node is not None:
7481
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7482
      self.op.remote_node = remote_node
7483

    
7484
      # Warning: do not remove the locking of the new secondary here
7485
      # unless DRBD8.AddChildren is changed to work in parallel;
7486
      # currently it doesn't since parallel invocations of
7487
      # FindUnusedMinor will conflict
7488
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7489
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7490

    
7491
    else:
7492
      self.needed_locks[locking.LEVEL_NODE] = []
7493
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7494

    
7495
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7496
                                   self.op.iallocator, self.op.remote_node,
7497
                                   self.op.disks, False, self.op.early_release)
7498

    
7499
    self.tasklets = [self.replacer]
7500

    
7501
  def DeclareLocks(self, level):
7502
    # If we're not already locking all nodes in the set we have to declare the
7503
    # instance's primary/secondary nodes.
7504
    if (level == locking.LEVEL_NODE and
7505
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7506
      self._LockInstancesNodes()
7507

    
7508
  def BuildHooksEnv(self):
7509
    """Build hooks env.
7510

7511
    This runs on the master, the primary and all the secondaries.
7512

7513
    """
7514
    instance = self.replacer.instance
7515
    env = {
7516
      "MODE": self.op.mode,
7517
      "NEW_SECONDARY": self.op.remote_node,
7518
      "OLD_SECONDARY": instance.secondary_nodes[0],
7519
      }
7520
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7521
    nl = [
7522
      self.cfg.GetMasterNode(),
7523
      instance.primary_node,
7524
      ]
7525
    if self.op.remote_node is not None:
7526
      nl.append(self.op.remote_node)
7527
    return env, nl, nl
7528

    
7529

    
7530
class TLReplaceDisks(Tasklet):
7531
  """Replaces disks for an instance.
7532

7533
  Note: Locking is not within the scope of this class.
7534

7535
  """
7536
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7537
               disks, delay_iallocator, early_release):
7538
    """Initializes this class.
7539

7540
    """
7541
    Tasklet.__init__(self, lu)
7542

    
7543
    # Parameters
7544
    self.instance_name = instance_name
7545
    self.mode = mode
7546
    self.iallocator_name = iallocator_name
7547
    self.remote_node = remote_node
7548
    self.disks = disks
7549
    self.delay_iallocator = delay_iallocator
7550
    self.early_release = early_release
7551

    
7552
    # Runtime data
7553
    self.instance = None
7554
    self.new_node = None
7555
    self.target_node = None
7556
    self.other_node = None
7557
    self.remote_node_info = None
7558
    self.node_secondary_ip = None
7559

    
7560
  @staticmethod
7561
  def CheckArguments(mode, remote_node, iallocator):
7562
    """Helper function for users of this class.
7563

7564
    """
7565
    # check for valid parameter combination
7566
    if mode == constants.REPLACE_DISK_CHG:
7567
      if remote_node is None and iallocator is None:
7568
        raise errors.OpPrereqError("When changing the secondary either an"
7569
                                   " iallocator script must be used or the"
7570
                                   " new node given", errors.ECODE_INVAL)
7571

    
7572
      if remote_node is not None and iallocator is not None:
7573
        raise errors.OpPrereqError("Give either the iallocator or the new"
7574
                                   " secondary, not both", errors.ECODE_INVAL)
7575

    
7576
    elif remote_node is not None or iallocator is not None:
7577
      # Not replacing the secondary
7578
      raise errors.OpPrereqError("The iallocator and new node options can"
7579
                                 " only be used when changing the"
7580
                                 " secondary node", errors.ECODE_INVAL)
7581

    
7582
  @staticmethod
7583
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7584
    """Compute a new secondary node using an IAllocator.
7585

7586
    """
7587
    ial = IAllocator(lu.cfg, lu.rpc,
7588
                     mode=constants.IALLOCATOR_MODE_RELOC,
7589
                     name=instance_name,
7590
                     relocate_from=relocate_from)
7591

    
7592
    ial.Run(iallocator_name)
7593

    
7594
    if not ial.success:
7595
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7596
                                 " %s" % (iallocator_name, ial.info),
7597
                                 errors.ECODE_NORES)
7598

    
7599
    if len(ial.result) != ial.required_nodes:
7600
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7601
                                 " of nodes (%s), required %s" %
7602
                                 (iallocator_name,
7603
                                  len(ial.result), ial.required_nodes),
7604
                                 errors.ECODE_FAULT)
7605

    
7606
    remote_node_name = ial.result[0]
7607

    
7608
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7609
               instance_name, remote_node_name)
7610

    
7611
    return remote_node_name
7612

    
7613
  def _FindFaultyDisks(self, node_name):
7614
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7615
                                    node_name, True)
7616

    
7617
  def CheckPrereq(self):
7618
    """Check prerequisites.
7619

7620
    This checks that the instance is in the cluster.
7621

7622
    """
7623
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7624
    assert instance is not None, \
7625
      "Cannot retrieve locked instance %s" % self.instance_name
7626

    
7627
    if instance.disk_template != constants.DT_DRBD8:
7628
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7629
                                 " instances", errors.ECODE_INVAL)
7630

    
7631
    if len(instance.secondary_nodes) != 1:
7632
      raise errors.OpPrereqError("The instance has a strange layout,"
7633
                                 " expected one secondary but found %d" %
7634
                                 len(instance.secondary_nodes),
7635
                                 errors.ECODE_FAULT)
7636

    
7637
    if not self.delay_iallocator:
7638
      self._CheckPrereq2()
7639

    
7640
  def _CheckPrereq2(self):
7641
    """Check prerequisites, second part.
7642

7643
    This function should always be part of CheckPrereq. It was separated and is
7644
    now called from Exec because during node evacuation iallocator was only
7645
    called with an unmodified cluster model, not taking planned changes into
7646
    account.
7647

7648
    """
7649
    instance = self.instance
7650
    secondary_node = instance.secondary_nodes[0]
7651

    
7652
    if self.iallocator_name is None:
7653
      remote_node = self.remote_node
7654
    else:
7655
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
7656
                                       instance.name, instance.secondary_nodes)
7657

    
7658
    if remote_node is not None:
7659
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
7660
      assert self.remote_node_info is not None, \
7661
        "Cannot retrieve locked node %s" % remote_node
7662
    else:
7663
      self.remote_node_info = None
7664

    
7665
    if remote_node == self.instance.primary_node:
7666
      raise errors.OpPrereqError("The specified node is the primary node of"
7667
                                 " the instance.", errors.ECODE_INVAL)
7668

    
7669
    if remote_node == secondary_node:
7670
      raise errors.OpPrereqError("The specified node is already the"
7671
                                 " secondary node of the instance.",
7672
                                 errors.ECODE_INVAL)
7673

    
7674
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
7675
                                    constants.REPLACE_DISK_CHG):
7676
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
7677
                                 errors.ECODE_INVAL)
7678

    
7679
    if self.mode == constants.REPLACE_DISK_AUTO:
7680
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
7681
      faulty_secondary = self._FindFaultyDisks(secondary_node)
7682

    
7683
      if faulty_primary and faulty_secondary:
7684
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
7685
                                   " one node and can not be repaired"
7686
                                   " automatically" % self.instance_name,
7687
                                   errors.ECODE_STATE)
7688

    
7689
      if faulty_primary:
7690
        self.disks = faulty_primary
7691
        self.target_node = instance.primary_node
7692
        self.other_node = secondary_node
7693
        check_nodes = [self.target_node, self.other_node]
7694
      elif faulty_secondary:
7695
        self.disks = faulty_secondary
7696
        self.target_node = secondary_node
7697
        self.other_node = instance.primary_node
7698
        check_nodes = [self.target_node, self.other_node]
7699
      else:
7700
        self.disks = []
7701
        check_nodes = []
7702

    
7703
    else:
7704
      # Non-automatic modes
7705
      if self.mode == constants.REPLACE_DISK_PRI:
7706
        self.target_node = instance.primary_node
7707
        self.other_node = secondary_node
7708
        check_nodes = [self.target_node, self.other_node]
7709

    
7710
      elif self.mode == constants.REPLACE_DISK_SEC:
7711
        self.target_node = secondary_node
7712
        self.other_node = instance.primary_node
7713
        check_nodes = [self.target_node, self.other_node]
7714

    
7715
      elif self.mode == constants.REPLACE_DISK_CHG:
7716
        self.new_node = remote_node
7717
        self.other_node = instance.primary_node
7718
        self.target_node = secondary_node
7719
        check_nodes = [self.new_node, self.other_node]
7720

    
7721
        _CheckNodeNotDrained(self.lu, remote_node)
7722

    
7723
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
7724
        assert old_node_info is not None
7725
        if old_node_info.offline and not self.early_release:
7726
          # doesn't make sense to delay the release
7727
          self.early_release = True
7728
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
7729
                          " early-release mode", secondary_node)
7730

    
7731
      else:
7732
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
7733
                                     self.mode)
7734

    
7735
      # If not specified all disks should be replaced
7736
      if not self.disks:
7737
        self.disks = range(len(self.instance.disks))
7738

    
7739
    for node in check_nodes:
7740
      _CheckNodeOnline(self.lu, node)
7741

    
7742
    # Check whether disks are valid
7743
    for disk_idx in self.disks:
7744
      instance.FindDisk(disk_idx)
7745

    
7746
    # Get secondary node IP addresses
7747
    node_2nd_ip = {}
7748

    
7749
    for node_name in [self.target_node, self.other_node, self.new_node]:
7750
      if node_name is not None:
7751
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
7752

    
7753
    self.node_secondary_ip = node_2nd_ip
7754

    
7755
  def Exec(self, feedback_fn):
7756
    """Execute disk replacement.
7757

7758
    This dispatches the disk replacement to the appropriate handler.
7759

7760
    """
7761
    if self.delay_iallocator:
7762
      self._CheckPrereq2()
7763

    
7764
    if not self.disks:
7765
      feedback_fn("No disks need replacement")
7766
      return
7767

    
7768
    feedback_fn("Replacing disk(s) %s for %s" %
7769
                (utils.CommaJoin(self.disks), self.instance.name))
7770

    
7771
    activate_disks = (not self.instance.admin_up)
7772

    
7773
    # Activate the instance disks if we're replacing them on a down instance
7774
    if activate_disks:
7775
      _StartInstanceDisks(self.lu, self.instance, True)
7776

    
7777
    try:
7778
      # Should we replace the secondary node?
7779
      if self.new_node is not None:
7780
        fn = self._ExecDrbd8Secondary
7781
      else:
7782
        fn = self._ExecDrbd8DiskOnly
7783

    
7784
      return fn(feedback_fn)
7785

    
7786
    finally:
7787
      # Deactivate the instance disks if we're replacing them on a
7788
      # down instance
7789
      if activate_disks:
7790
        _SafeShutdownInstanceDisks(self.lu, self.instance)
7791

    
7792
  def _CheckVolumeGroup(self, nodes):
7793
    self.lu.LogInfo("Checking volume groups")
7794

    
7795
    vgname = self.cfg.GetVGName()
7796

    
7797
    # Make sure volume group exists on all involved nodes
7798
    results = self.rpc.call_vg_list(nodes)
7799
    if not results:
7800
      raise errors.OpExecError("Can't list volume groups on the nodes")
7801

    
7802
    for node in nodes:
7803
      res = results[node]
7804
      res.Raise("Error checking node %s" % node)
7805
      if vgname not in res.payload:
7806
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
7807
                                 (vgname, node))
7808

    
7809
  def _CheckDisksExistence(self, nodes):
7810
    # Check disk existence
7811
    for idx, dev in enumerate(self.instance.disks):
7812
      if idx not in self.disks:
7813
        continue
7814

    
7815
      for node in nodes:
7816
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
7817
        self.cfg.SetDiskID(dev, node)
7818

    
7819
        result = self.rpc.call_blockdev_find(node, dev)
7820

    
7821
        msg = result.fail_msg
7822
        if msg or not result.payload:
7823
          if not msg:
7824
            msg = "disk not found"
7825
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
7826
                                   (idx, node, msg))
7827

    
7828
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
7829
    for idx, dev in enumerate(self.instance.disks):
7830
      if idx not in self.disks:
7831
        continue
7832

    
7833
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
7834
                      (idx, node_name))
7835

    
7836
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
7837
                                   ldisk=ldisk):
7838
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
7839
                                 " replace disks for instance %s" %
7840
                                 (node_name, self.instance.name))
7841

    
7842
  def _CreateNewStorage(self, node_name):
7843
    vgname = self.cfg.GetVGName()
7844
    iv_names = {}
7845

    
7846
    for idx, dev in enumerate(self.instance.disks):
7847
      if idx not in self.disks:
7848
        continue
7849

    
7850
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
7851

    
7852
      self.cfg.SetDiskID(dev, node_name)
7853

    
7854
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
7855
      names = _GenerateUniqueNames(self.lu, lv_names)
7856

    
7857
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
7858
                             logical_id=(vgname, names[0]))
7859
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7860
                             logical_id=(vgname, names[1]))
7861

    
7862
      new_lvs = [lv_data, lv_meta]
7863
      old_lvs = dev.children
7864
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
7865

    
7866
      # we pass force_create=True to force the LVM creation
7867
      for new_lv in new_lvs:
7868
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
7869
                        _GetInstanceInfoText(self.instance), False)
7870

    
7871
    return iv_names
7872

    
7873
  def _CheckDevices(self, node_name, iv_names):
7874
    for name, (dev, _, _) in iv_names.iteritems():
7875
      self.cfg.SetDiskID(dev, node_name)
7876

    
7877
      result = self.rpc.call_blockdev_find(node_name, dev)
7878

    
7879
      msg = result.fail_msg
7880
      if msg or not result.payload:
7881
        if not msg:
7882
          msg = "disk not found"
7883
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
7884
                                 (name, msg))
7885

    
7886
      if result.payload.is_degraded:
7887
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
7888

    
7889
  def _RemoveOldStorage(self, node_name, iv_names):
7890
    for name, (_, old_lvs, _) in iv_names.iteritems():
7891
      self.lu.LogInfo("Remove logical volumes for %s" % name)
7892

    
7893
      for lv in old_lvs:
7894
        self.cfg.SetDiskID(lv, node_name)
7895

    
7896
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
7897
        if msg:
7898
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
7899
                             hint="remove unused LVs manually")
7900

    
7901
  def _ReleaseNodeLock(self, node_name):
7902
    """Releases the lock for a given node."""
7903
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
7904

    
7905
  def _ExecDrbd8DiskOnly(self, feedback_fn):
7906
    """Replace a disk on the primary or secondary for DRBD 8.
7907

7908
    The algorithm for replace is quite complicated:
7909

7910
      1. for each disk to be replaced:
7911

7912
        1. create new LVs on the target node with unique names
7913
        1. detach old LVs from the drbd device
7914
        1. rename old LVs to name_replaced.<time_t>
7915
        1. rename new LVs to old LVs
7916
        1. attach the new LVs (with the old names now) to the drbd device
7917

7918
      1. wait for sync across all devices
7919

7920
      1. for each modified disk:
7921

7922
        1. remove old LVs (which have the name name_replaces.<time_t>)
7923

7924
    Failures are not very well handled.
7925

7926
    """
7927
    steps_total = 6
7928

    
7929
    # Step: check device activation
7930
    self.lu.LogStep(1, steps_total, "Check device existence")
7931
    self._CheckDisksExistence([self.other_node, self.target_node])
7932
    self._CheckVolumeGroup([self.target_node, self.other_node])
7933

    
7934
    # Step: check other node consistency
7935
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7936
    self._CheckDisksConsistency(self.other_node,
7937
                                self.other_node == self.instance.primary_node,
7938
                                False)
7939

    
7940
    # Step: create new storage
7941
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7942
    iv_names = self._CreateNewStorage(self.target_node)
7943

    
7944
    # Step: for each lv, detach+rename*2+attach
7945
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7946
    for dev, old_lvs, new_lvs in iv_names.itervalues():
7947
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
7948

    
7949
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
7950
                                                     old_lvs)
7951
      result.Raise("Can't detach drbd from local storage on node"
7952
                   " %s for device %s" % (self.target_node, dev.iv_name))
7953
      #dev.children = []
7954
      #cfg.Update(instance)
7955

    
7956
      # ok, we created the new LVs, so now we know we have the needed
7957
      # storage; as such, we proceed on the target node to rename
7958
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
7959
      # using the assumption that logical_id == physical_id (which in
7960
      # turn is the unique_id on that node)
7961

    
7962
      # FIXME(iustin): use a better name for the replaced LVs
7963
      temp_suffix = int(time.time())
7964
      ren_fn = lambda d, suff: (d.physical_id[0],
7965
                                d.physical_id[1] + "_replaced-%s" % suff)
7966

    
7967
      # Build the rename list based on what LVs exist on the node
7968
      rename_old_to_new = []
7969
      for to_ren in old_lvs:
7970
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
7971
        if not result.fail_msg and result.payload:
7972
          # device exists
7973
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
7974

    
7975
      self.lu.LogInfo("Renaming the old LVs on the target node")
7976
      result = self.rpc.call_blockdev_rename(self.target_node,
7977
                                             rename_old_to_new)
7978
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
7979

    
7980
      # Now we rename the new LVs to the old LVs
7981
      self.lu.LogInfo("Renaming the new LVs on the target node")
7982
      rename_new_to_old = [(new, old.physical_id)
7983
                           for old, new in zip(old_lvs, new_lvs)]
7984
      result = self.rpc.call_blockdev_rename(self.target_node,
7985
                                             rename_new_to_old)
7986
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
7987

    
7988
      for old, new in zip(old_lvs, new_lvs):
7989
        new.logical_id = old.logical_id
7990
        self.cfg.SetDiskID(new, self.target_node)
7991

    
7992
      for disk in old_lvs:
7993
        disk.logical_id = ren_fn(disk, temp_suffix)
7994
        self.cfg.SetDiskID(disk, self.target_node)
7995

    
7996
      # Now that the new lvs have the old name, we can add them to the device
7997
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
7998
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
7999
                                                  new_lvs)
8000
      msg = result.fail_msg
8001
      if msg:
8002
        for new_lv in new_lvs:
8003
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
8004
                                               new_lv).fail_msg
8005
          if msg2:
8006
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
8007
                               hint=("cleanup manually the unused logical"
8008
                                     "volumes"))
8009
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8010

    
8011
      dev.children = new_lvs
8012

    
8013
      self.cfg.Update(self.instance, feedback_fn)
8014

    
8015
    cstep = 5
8016
    if self.early_release:
8017
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8018
      cstep += 1
8019
      self._RemoveOldStorage(self.target_node, iv_names)
8020
      # WARNING: we release both node locks here, do not do other RPCs
8021
      # than WaitForSync to the primary node
8022
      self._ReleaseNodeLock([self.target_node, self.other_node])
8023

    
8024
    # Wait for sync
8025
    # This can fail as the old devices are degraded and _WaitForSync
8026
    # does a combined result over all disks, so we don't check its return value
8027
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8028
    cstep += 1
8029
    _WaitForSync(self.lu, self.instance)
8030

    
8031
    # Check all devices manually
8032
    self._CheckDevices(self.instance.primary_node, iv_names)
8033

    
8034
    # Step: remove old storage
8035
    if not self.early_release:
8036
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8037
      cstep += 1
8038
      self._RemoveOldStorage(self.target_node, iv_names)
8039

    
8040
  def _ExecDrbd8Secondary(self, feedback_fn):
8041
    """Replace the secondary node for DRBD 8.
8042

8043
    The algorithm for replace is quite complicated:
8044
      - for all disks of the instance:
8045
        - create new LVs on the new node with same names
8046
        - shutdown the drbd device on the old secondary
8047
        - disconnect the drbd network on the primary
8048
        - create the drbd device on the new secondary
8049
        - network attach the drbd on the primary, using an artifice:
8050
          the drbd code for Attach() will connect to the network if it
8051
          finds a device which is connected to the good local disks but
8052
          not network enabled
8053
      - wait for sync across all devices
8054
      - remove all disks from the old secondary
8055

8056
    Failures are not very well handled.
8057

8058
    """
8059
    steps_total = 6
8060

    
8061
    # Step: check device activation
8062
    self.lu.LogStep(1, steps_total, "Check device existence")
8063
    self._CheckDisksExistence([self.instance.primary_node])
8064
    self._CheckVolumeGroup([self.instance.primary_node])
8065

    
8066
    # Step: check other node consistency
8067
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8068
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8069

    
8070
    # Step: create new storage
8071
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8072
    for idx, dev in enumerate(self.instance.disks):
8073
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8074
                      (self.new_node, idx))
8075
      # we pass force_create=True to force LVM creation
8076
      for new_lv in dev.children:
8077
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8078
                        _GetInstanceInfoText(self.instance), False)
8079

    
8080
    # Step 4: dbrd minors and drbd setups changes
8081
    # after this, we must manually remove the drbd minors on both the
8082
    # error and the success paths
8083
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8084
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8085
                                         for dev in self.instance.disks],
8086
                                        self.instance.name)
8087
    logging.debug("Allocated minors %r", minors)
8088

    
8089
    iv_names = {}
8090
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8091
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8092
                      (self.new_node, idx))
8093
      # create new devices on new_node; note that we create two IDs:
8094
      # one without port, so the drbd will be activated without
8095
      # networking information on the new node at this stage, and one
8096
      # with network, for the latter activation in step 4
8097
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8098
      if self.instance.primary_node == o_node1:
8099
        p_minor = o_minor1
8100
      else:
8101
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8102
        p_minor = o_minor2
8103

    
8104
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8105
                      p_minor, new_minor, o_secret)
8106
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8107
                    p_minor, new_minor, o_secret)
8108

    
8109
      iv_names[idx] = (dev, dev.children, new_net_id)
8110
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8111
                    new_net_id)
8112
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8113
                              logical_id=new_alone_id,
8114
                              children=dev.children,
8115
                              size=dev.size)
8116
      try:
8117
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8118
                              _GetInstanceInfoText(self.instance), False)
8119
      except errors.GenericError:
8120
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8121
        raise
8122

    
8123
    # We have new devices, shutdown the drbd on the old secondary
8124
    for idx, dev in enumerate(self.instance.disks):
8125
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8126
      self.cfg.SetDiskID(dev, self.target_node)
8127
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8128
      if msg:
8129
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8130
                           "node: %s" % (idx, msg),
8131
                           hint=("Please cleanup this device manually as"
8132
                                 " soon as possible"))
8133

    
8134
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8135
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8136
                                               self.node_secondary_ip,
8137
                                               self.instance.disks)\
8138
                                              [self.instance.primary_node]
8139

    
8140
    msg = result.fail_msg
8141
    if msg:
8142
      # detaches didn't succeed (unlikely)
8143
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8144
      raise errors.OpExecError("Can't detach the disks from the network on"
8145
                               " old node: %s" % (msg,))
8146

    
8147
    # if we managed to detach at least one, we update all the disks of
8148
    # the instance to point to the new secondary
8149
    self.lu.LogInfo("Updating instance configuration")
8150
    for dev, _, new_logical_id in iv_names.itervalues():
8151
      dev.logical_id = new_logical_id
8152
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8153

    
8154
    self.cfg.Update(self.instance, feedback_fn)
8155

    
8156
    # and now perform the drbd attach
8157
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8158
                    " (standalone => connected)")
8159
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8160
                                            self.new_node],
8161
                                           self.node_secondary_ip,
8162
                                           self.instance.disks,
8163
                                           self.instance.name,
8164
                                           False)
8165
    for to_node, to_result in result.items():
8166
      msg = to_result.fail_msg
8167
      if msg:
8168
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8169
                           to_node, msg,
8170
                           hint=("please do a gnt-instance info to see the"
8171
                                 " status of disks"))
8172
    cstep = 5
8173
    if self.early_release:
8174
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8175
      cstep += 1
8176
      self._RemoveOldStorage(self.target_node, iv_names)
8177
      # WARNING: we release all node locks here, do not do other RPCs
8178
      # than WaitForSync to the primary node
8179
      self._ReleaseNodeLock([self.instance.primary_node,
8180
                             self.target_node,
8181
                             self.new_node])
8182

    
8183
    # Wait for sync
8184
    # This can fail as the old devices are degraded and _WaitForSync
8185
    # does a combined result over all disks, so we don't check its return value
8186
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8187
    cstep += 1
8188
    _WaitForSync(self.lu, self.instance)
8189

    
8190
    # Check all devices manually
8191
    self._CheckDevices(self.instance.primary_node, iv_names)
8192

    
8193
    # Step: remove old storage
8194
    if not self.early_release:
8195
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8196
      self._RemoveOldStorage(self.target_node, iv_names)
8197

    
8198

    
8199
class LURepairNodeStorage(NoHooksLU):
8200
  """Repairs the volume group on a node.
8201

8202
  """
8203
  _OP_PARAMS = [
8204
    _PNodeName,
8205
    ("storage_type", _NoDefault, _CheckStorageType),
8206
    ("name", _NoDefault, _TNonEmptyString),
8207
    ("ignore_consistency", False, _TBool),
8208
    ]
8209
  REQ_BGL = False
8210

    
8211
  def CheckArguments(self):
8212
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8213

    
8214
    storage_type = self.op.storage_type
8215

    
8216
    if (constants.SO_FIX_CONSISTENCY not in
8217
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8218
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8219
                                 " repaired" % storage_type,
8220
                                 errors.ECODE_INVAL)
8221

    
8222
  def ExpandNames(self):
8223
    self.needed_locks = {
8224
      locking.LEVEL_NODE: [self.op.node_name],
8225
      }
8226

    
8227
  def _CheckFaultyDisks(self, instance, node_name):
8228
    """Ensure faulty disks abort the opcode or at least warn."""
8229
    try:
8230
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8231
                                  node_name, True):
8232
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8233
                                   " node '%s'" % (instance.name, node_name),
8234
                                   errors.ECODE_STATE)
8235
    except errors.OpPrereqError, err:
8236
      if self.op.ignore_consistency:
8237
        self.proc.LogWarning(str(err.args[0]))
8238
      else:
8239
        raise
8240

    
8241
  def CheckPrereq(self):
8242
    """Check prerequisites.
8243

8244
    """
8245
    # Check whether any instance on this node has faulty disks
8246
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8247
      if not inst.admin_up:
8248
        continue
8249
      check_nodes = set(inst.all_nodes)
8250
      check_nodes.discard(self.op.node_name)
8251
      for inst_node_name in check_nodes:
8252
        self._CheckFaultyDisks(inst, inst_node_name)
8253

    
8254
  def Exec(self, feedback_fn):
8255
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8256
                (self.op.name, self.op.node_name))
8257

    
8258
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8259
    result = self.rpc.call_storage_execute(self.op.node_name,
8260
                                           self.op.storage_type, st_args,
8261
                                           self.op.name,
8262
                                           constants.SO_FIX_CONSISTENCY)
8263
    result.Raise("Failed to repair storage unit '%s' on %s" %
8264
                 (self.op.name, self.op.node_name))
8265

    
8266

    
8267
class LUNodeEvacuationStrategy(NoHooksLU):
8268
  """Computes the node evacuation strategy.
8269

8270
  """
8271
  _OP_PARAMS = [
8272
    ("nodes", _NoDefault, _TListOf(_TNonEmptyString)),
8273
    ("remote_node", None, _TMaybeString),
8274
    ("iallocator", None, _TMaybeString),
8275
    ]
8276
  REQ_BGL = False
8277

    
8278
  def CheckArguments(self):
8279
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8280

    
8281
  def ExpandNames(self):
8282
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8283
    self.needed_locks = locks = {}
8284
    if self.op.remote_node is None:
8285
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8286
    else:
8287
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8288
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8289

    
8290
  def Exec(self, feedback_fn):
8291
    if self.op.remote_node is not None:
8292
      instances = []
8293
      for node in self.op.nodes:
8294
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8295
      result = []
8296
      for i in instances:
8297
        if i.primary_node == self.op.remote_node:
8298
          raise errors.OpPrereqError("Node %s is the primary node of"
8299
                                     " instance %s, cannot use it as"
8300
                                     " secondary" %
8301
                                     (self.op.remote_node, i.name),
8302
                                     errors.ECODE_INVAL)
8303
        result.append([i.name, self.op.remote_node])
8304
    else:
8305
      ial = IAllocator(self.cfg, self.rpc,
8306
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8307
                       evac_nodes=self.op.nodes)
8308
      ial.Run(self.op.iallocator, validate=True)
8309
      if not ial.success:
8310
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8311
                                 errors.ECODE_NORES)
8312
      result = ial.result
8313
    return result
8314

    
8315

    
8316
class LUGrowDisk(LogicalUnit):
8317
  """Grow a disk of an instance.
8318

8319
  """
8320
  HPATH = "disk-grow"
8321
  HTYPE = constants.HTYPE_INSTANCE
8322
  _OP_PARAMS = [
8323
    _PInstanceName,
8324
    ("disk", _NoDefault, _TInt),
8325
    ("amount", _NoDefault, _TInt),
8326
    ("wait_for_sync", True, _TBool),
8327
    ]
8328
  REQ_BGL = False
8329

    
8330
  def ExpandNames(self):
8331
    self._ExpandAndLockInstance()
8332
    self.needed_locks[locking.LEVEL_NODE] = []
8333
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8334

    
8335
  def DeclareLocks(self, level):
8336
    if level == locking.LEVEL_NODE:
8337
      self._LockInstancesNodes()
8338

    
8339
  def BuildHooksEnv(self):
8340
    """Build hooks env.
8341

8342
    This runs on the master, the primary and all the secondaries.
8343

8344
    """
8345
    env = {
8346
      "DISK": self.op.disk,
8347
      "AMOUNT": self.op.amount,
8348
      }
8349
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8350
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8351
    return env, nl, nl
8352

    
8353
  def CheckPrereq(self):
8354
    """Check prerequisites.
8355

8356
    This checks that the instance is in the cluster.
8357

8358
    """
8359
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8360
    assert instance is not None, \
8361
      "Cannot retrieve locked instance %s" % self.op.instance_name
8362
    nodenames = list(instance.all_nodes)
8363
    for node in nodenames:
8364
      _CheckNodeOnline(self, node)
8365

    
8366
    self.instance = instance
8367

    
8368
    if instance.disk_template not in constants.DTS_GROWABLE:
8369
      raise errors.OpPrereqError("Instance's disk layout does not support"
8370
                                 " growing.", errors.ECODE_INVAL)
8371

    
8372
    self.disk = instance.FindDisk(self.op.disk)
8373

    
8374
    if instance.disk_template != constants.DT_FILE:
8375
      # TODO: check the free disk space for file, when that feature will be
8376
      # supported
8377
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
8378

    
8379
  def Exec(self, feedback_fn):
8380
    """Execute disk grow.
8381

8382
    """
8383
    instance = self.instance
8384
    disk = self.disk
8385

    
8386
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8387
    if not disks_ok:
8388
      raise errors.OpExecError("Cannot activate block device to grow")
8389

    
8390
    for node in instance.all_nodes:
8391
      self.cfg.SetDiskID(disk, node)
8392
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8393
      result.Raise("Grow request failed to node %s" % node)
8394

    
8395
      # TODO: Rewrite code to work properly
8396
      # DRBD goes into sync mode for a short amount of time after executing the
8397
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8398
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8399
      # time is a work-around.
8400
      time.sleep(5)
8401

    
8402
    disk.RecordGrow(self.op.amount)
8403
    self.cfg.Update(instance, feedback_fn)
8404
    if self.op.wait_for_sync:
8405
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8406
      if disk_abort:
8407
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8408
                             " status.\nPlease check the instance.")
8409
      if not instance.admin_up:
8410
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8411
    elif not instance.admin_up:
8412
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8413
                           " not supposed to be running because no wait for"
8414
                           " sync mode was requested.")
8415

    
8416

    
8417
class LUQueryInstanceData(NoHooksLU):
8418
  """Query runtime instance data.
8419

8420
  """
8421
  _OP_PARAMS = [
8422
    ("instances", _EmptyList, _TListOf(_TNonEmptyString)),
8423
    ("static", False, _TBool),
8424
    ]
8425
  REQ_BGL = False
8426

    
8427
  def ExpandNames(self):
8428
    self.needed_locks = {}
8429
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8430

    
8431
    if self.op.instances:
8432
      self.wanted_names = []
8433
      for name in self.op.instances:
8434
        full_name = _ExpandInstanceName(self.cfg, name)
8435
        self.wanted_names.append(full_name)
8436
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8437
    else:
8438
      self.wanted_names = None
8439
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8440

    
8441
    self.needed_locks[locking.LEVEL_NODE] = []
8442
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8443

    
8444
  def DeclareLocks(self, level):
8445
    if level == locking.LEVEL_NODE:
8446
      self._LockInstancesNodes()
8447

    
8448
  def CheckPrereq(self):
8449
    """Check prerequisites.
8450

8451
    This only checks the optional instance list against the existing names.
8452

8453
    """
8454
    if self.wanted_names is None:
8455
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8456

    
8457
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8458
                             in self.wanted_names]
8459

    
8460
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8461
    """Returns the status of a block device
8462

8463
    """
8464
    if self.op.static or not node:
8465
      return None
8466

    
8467
    self.cfg.SetDiskID(dev, node)
8468

    
8469
    result = self.rpc.call_blockdev_find(node, dev)
8470
    if result.offline:
8471
      return None
8472

    
8473
    result.Raise("Can't compute disk status for %s" % instance_name)
8474

    
8475
    status = result.payload
8476
    if status is None:
8477
      return None
8478

    
8479
    return (status.dev_path, status.major, status.minor,
8480
            status.sync_percent, status.estimated_time,
8481
            status.is_degraded, status.ldisk_status)
8482

    
8483
  def _ComputeDiskStatus(self, instance, snode, dev):
8484
    """Compute block device status.
8485

8486
    """
8487
    if dev.dev_type in constants.LDS_DRBD:
8488
      # we change the snode then (otherwise we use the one passed in)
8489
      if dev.logical_id[0] == instance.primary_node:
8490
        snode = dev.logical_id[1]
8491
      else:
8492
        snode = dev.logical_id[0]
8493

    
8494
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8495
                                              instance.name, dev)
8496
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8497

    
8498
    if dev.children:
8499
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8500
                      for child in dev.children]
8501
    else:
8502
      dev_children = []
8503

    
8504
    data = {
8505
      "iv_name": dev.iv_name,
8506
      "dev_type": dev.dev_type,
8507
      "logical_id": dev.logical_id,
8508
      "physical_id": dev.physical_id,
8509
      "pstatus": dev_pstatus,
8510
      "sstatus": dev_sstatus,
8511
      "children": dev_children,
8512
      "mode": dev.mode,
8513
      "size": dev.size,
8514
      }
8515

    
8516
    return data
8517

    
8518
  def Exec(self, feedback_fn):
8519
    """Gather and return data"""
8520
    result = {}
8521

    
8522
    cluster = self.cfg.GetClusterInfo()
8523

    
8524
    for instance in self.wanted_instances:
8525
      if not self.op.static:
8526
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8527
                                                  instance.name,
8528
                                                  instance.hypervisor)
8529
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8530
        remote_info = remote_info.payload
8531
        if remote_info and "state" in remote_info:
8532
          remote_state = "up"
8533
        else:
8534
          remote_state = "down"
8535
      else:
8536
        remote_state = None
8537
      if instance.admin_up:
8538
        config_state = "up"
8539
      else:
8540
        config_state = "down"
8541

    
8542
      disks = [self._ComputeDiskStatus(instance, None, device)
8543
               for device in instance.disks]
8544

    
8545
      idict = {
8546
        "name": instance.name,
8547
        "config_state": config_state,
8548
        "run_state": remote_state,
8549
        "pnode": instance.primary_node,
8550
        "snodes": instance.secondary_nodes,
8551
        "os": instance.os,
8552
        # this happens to be the same format used for hooks
8553
        "nics": _NICListToTuple(self, instance.nics),
8554
        "disk_template": instance.disk_template,
8555
        "disks": disks,
8556
        "hypervisor": instance.hypervisor,
8557
        "network_port": instance.network_port,
8558
        "hv_instance": instance.hvparams,
8559
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8560
        "be_instance": instance.beparams,
8561
        "be_actual": cluster.FillBE(instance),
8562
        "os_instance": instance.osparams,
8563
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8564
        "serial_no": instance.serial_no,
8565
        "mtime": instance.mtime,
8566
        "ctime": instance.ctime,
8567
        "uuid": instance.uuid,
8568
        }
8569

    
8570
      result[instance.name] = idict
8571

    
8572
    return result
8573

    
8574

    
8575
class LUSetInstanceParams(LogicalUnit):
8576
  """Modifies an instances's parameters.
8577

8578
  """
8579
  HPATH = "instance-modify"
8580
  HTYPE = constants.HTYPE_INSTANCE
8581
  _OP_PARAMS = [
8582
    _PInstanceName,
8583
    ("nics", _EmptyList, _TList),
8584
    ("disks", _EmptyList, _TList),
8585
    ("beparams", _EmptyDict, _TDict),
8586
    ("hvparams", _EmptyDict, _TDict),
8587
    ("disk_template", None, _TMaybeString),
8588
    ("remote_node", None, _TMaybeString),
8589
    ("os_name", None, _TMaybeString),
8590
    ("force_variant", False, _TBool),
8591
    ("osparams", None, _TOr(_TDict, _TNone)),
8592
    _PForce,
8593
    ]
8594
  REQ_BGL = False
8595

    
8596
  def CheckArguments(self):
8597
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8598
            self.op.hvparams or self.op.beparams or self.op.os_name):
8599
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8600

    
8601
    if self.op.hvparams:
8602
      _CheckGlobalHvParams(self.op.hvparams)
8603

    
8604
    # Disk validation
8605
    disk_addremove = 0
8606
    for disk_op, disk_dict in self.op.disks:
8607
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8608
      if disk_op == constants.DDM_REMOVE:
8609
        disk_addremove += 1
8610
        continue
8611
      elif disk_op == constants.DDM_ADD:
8612
        disk_addremove += 1
8613
      else:
8614
        if not isinstance(disk_op, int):
8615
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8616
        if not isinstance(disk_dict, dict):
8617
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8618
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8619

    
8620
      if disk_op == constants.DDM_ADD:
8621
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8622
        if mode not in constants.DISK_ACCESS_SET:
8623
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8624
                                     errors.ECODE_INVAL)
8625
        size = disk_dict.get('size', None)
8626
        if size is None:
8627
          raise errors.OpPrereqError("Required disk parameter size missing",
8628
                                     errors.ECODE_INVAL)
8629
        try:
8630
          size = int(size)
8631
        except (TypeError, ValueError), err:
8632
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8633
                                     str(err), errors.ECODE_INVAL)
8634
        disk_dict['size'] = size
8635
      else:
8636
        # modification of disk
8637
        if 'size' in disk_dict:
8638
          raise errors.OpPrereqError("Disk size change not possible, use"
8639
                                     " grow-disk", errors.ECODE_INVAL)
8640

    
8641
    if disk_addremove > 1:
8642
      raise errors.OpPrereqError("Only one disk add or remove operation"
8643
                                 " supported at a time", errors.ECODE_INVAL)
8644

    
8645
    if self.op.disks and self.op.disk_template is not None:
8646
      raise errors.OpPrereqError("Disk template conversion and other disk"
8647
                                 " changes not supported at the same time",
8648
                                 errors.ECODE_INVAL)
8649

    
8650
    if self.op.disk_template:
8651
      _CheckDiskTemplate(self.op.disk_template)
8652
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
8653
          self.op.remote_node is None):
8654
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
8655
                                   " one requires specifying a secondary node",
8656
                                   errors.ECODE_INVAL)
8657

    
8658
    # NIC validation
8659
    nic_addremove = 0
8660
    for nic_op, nic_dict in self.op.nics:
8661
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
8662
      if nic_op == constants.DDM_REMOVE:
8663
        nic_addremove += 1
8664
        continue
8665
      elif nic_op == constants.DDM_ADD:
8666
        nic_addremove += 1
8667
      else:
8668
        if not isinstance(nic_op, int):
8669
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
8670
        if not isinstance(nic_dict, dict):
8671
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
8672
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8673

    
8674
      # nic_dict should be a dict
8675
      nic_ip = nic_dict.get('ip', None)
8676
      if nic_ip is not None:
8677
        if nic_ip.lower() == constants.VALUE_NONE:
8678
          nic_dict['ip'] = None
8679
        else:
8680
          if not netutils.IPAddress.IsValid(nic_ip):
8681
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
8682
                                       errors.ECODE_INVAL)
8683

    
8684
      nic_bridge = nic_dict.get('bridge', None)
8685
      nic_link = nic_dict.get('link', None)
8686
      if nic_bridge and nic_link:
8687
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
8688
                                   " at the same time", errors.ECODE_INVAL)
8689
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
8690
        nic_dict['bridge'] = None
8691
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
8692
        nic_dict['link'] = None
8693

    
8694
      if nic_op == constants.DDM_ADD:
8695
        nic_mac = nic_dict.get('mac', None)
8696
        if nic_mac is None:
8697
          nic_dict['mac'] = constants.VALUE_AUTO
8698

    
8699
      if 'mac' in nic_dict:
8700
        nic_mac = nic_dict['mac']
8701
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8702
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
8703

    
8704
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
8705
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
8706
                                     " modifying an existing nic",
8707
                                     errors.ECODE_INVAL)
8708

    
8709
    if nic_addremove > 1:
8710
      raise errors.OpPrereqError("Only one NIC add or remove operation"
8711
                                 " supported at a time", errors.ECODE_INVAL)
8712

    
8713
  def ExpandNames(self):
8714
    self._ExpandAndLockInstance()
8715
    self.needed_locks[locking.LEVEL_NODE] = []
8716
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8717

    
8718
  def DeclareLocks(self, level):
8719
    if level == locking.LEVEL_NODE:
8720
      self._LockInstancesNodes()
8721
      if self.op.disk_template and self.op.remote_node:
8722
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8723
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
8724

    
8725
  def BuildHooksEnv(self):
8726
    """Build hooks env.
8727

8728
    This runs on the master, primary and secondaries.
8729

8730
    """
8731
    args = dict()
8732
    if constants.BE_MEMORY in self.be_new:
8733
      args['memory'] = self.be_new[constants.BE_MEMORY]
8734
    if constants.BE_VCPUS in self.be_new:
8735
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
8736
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
8737
    # information at all.
8738
    if self.op.nics:
8739
      args['nics'] = []
8740
      nic_override = dict(self.op.nics)
8741
      for idx, nic in enumerate(self.instance.nics):
8742
        if idx in nic_override:
8743
          this_nic_override = nic_override[idx]
8744
        else:
8745
          this_nic_override = {}
8746
        if 'ip' in this_nic_override:
8747
          ip = this_nic_override['ip']
8748
        else:
8749
          ip = nic.ip
8750
        if 'mac' in this_nic_override:
8751
          mac = this_nic_override['mac']
8752
        else:
8753
          mac = nic.mac
8754
        if idx in self.nic_pnew:
8755
          nicparams = self.nic_pnew[idx]
8756
        else:
8757
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
8758
        mode = nicparams[constants.NIC_MODE]
8759
        link = nicparams[constants.NIC_LINK]
8760
        args['nics'].append((ip, mac, mode, link))
8761
      if constants.DDM_ADD in nic_override:
8762
        ip = nic_override[constants.DDM_ADD].get('ip', None)
8763
        mac = nic_override[constants.DDM_ADD]['mac']
8764
        nicparams = self.nic_pnew[constants.DDM_ADD]
8765
        mode = nicparams[constants.NIC_MODE]
8766
        link = nicparams[constants.NIC_LINK]
8767
        args['nics'].append((ip, mac, mode, link))
8768
      elif constants.DDM_REMOVE in nic_override:
8769
        del args['nics'][-1]
8770

    
8771
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
8772
    if self.op.disk_template:
8773
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
8774
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8775
    return env, nl, nl
8776

    
8777
  def CheckPrereq(self):
8778
    """Check prerequisites.
8779

8780
    This only checks the instance list against the existing names.
8781

8782
    """
8783
    # checking the new params on the primary/secondary nodes
8784

    
8785
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8786
    cluster = self.cluster = self.cfg.GetClusterInfo()
8787
    assert self.instance is not None, \
8788
      "Cannot retrieve locked instance %s" % self.op.instance_name
8789
    pnode = instance.primary_node
8790
    nodelist = list(instance.all_nodes)
8791

    
8792
    # OS change
8793
    if self.op.os_name and not self.op.force:
8794
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
8795
                      self.op.force_variant)
8796
      instance_os = self.op.os_name
8797
    else:
8798
      instance_os = instance.os
8799

    
8800
    if self.op.disk_template:
8801
      if instance.disk_template == self.op.disk_template:
8802
        raise errors.OpPrereqError("Instance already has disk template %s" %
8803
                                   instance.disk_template, errors.ECODE_INVAL)
8804

    
8805
      if (instance.disk_template,
8806
          self.op.disk_template) not in self._DISK_CONVERSIONS:
8807
        raise errors.OpPrereqError("Unsupported disk template conversion from"
8808
                                   " %s to %s" % (instance.disk_template,
8809
                                                  self.op.disk_template),
8810
                                   errors.ECODE_INVAL)
8811
      _CheckInstanceDown(self, instance, "cannot change disk template")
8812
      if self.op.disk_template in constants.DTS_NET_MIRROR:
8813
        if self.op.remote_node == pnode:
8814
          raise errors.OpPrereqError("Given new secondary node %s is the same"
8815
                                     " as the primary node of the instance" %
8816
                                     self.op.remote_node, errors.ECODE_STATE)
8817
        _CheckNodeOnline(self, self.op.remote_node)
8818
        _CheckNodeNotDrained(self, self.op.remote_node)
8819
        disks = [{"size": d.size} for d in instance.disks]
8820
        required = _ComputeDiskSize(self.op.disk_template, disks)
8821
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
8822

    
8823
    # hvparams processing
8824
    if self.op.hvparams:
8825
      hv_type = instance.hypervisor
8826
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
8827
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
8828
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
8829

    
8830
      # local check
8831
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
8832
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
8833
      self.hv_new = hv_new # the new actual values
8834
      self.hv_inst = i_hvdict # the new dict (without defaults)
8835
    else:
8836
      self.hv_new = self.hv_inst = {}
8837

    
8838
    # beparams processing
8839
    if self.op.beparams:
8840
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
8841
                                   use_none=True)
8842
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
8843
      be_new = cluster.SimpleFillBE(i_bedict)
8844
      self.be_new = be_new # the new actual values
8845
      self.be_inst = i_bedict # the new dict (without defaults)
8846
    else:
8847
      self.be_new = self.be_inst = {}
8848

    
8849
    # osparams processing
8850
    if self.op.osparams:
8851
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
8852
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
8853
      self.os_new = cluster.SimpleFillOS(instance_os, i_osdict)
8854
      self.os_inst = i_osdict # the new dict (without defaults)
8855
    else:
8856
      self.os_new = self.os_inst = {}
8857

    
8858
    self.warn = []
8859

    
8860
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
8861
      mem_check_list = [pnode]
8862
      if be_new[constants.BE_AUTO_BALANCE]:
8863
        # either we changed auto_balance to yes or it was from before
8864
        mem_check_list.extend(instance.secondary_nodes)
8865
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
8866
                                                  instance.hypervisor)
8867
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
8868
                                         instance.hypervisor)
8869
      pninfo = nodeinfo[pnode]
8870
      msg = pninfo.fail_msg
8871
      if msg:
8872
        # Assume the primary node is unreachable and go ahead
8873
        self.warn.append("Can't get info from primary node %s: %s" %
8874
                         (pnode,  msg))
8875
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
8876
        self.warn.append("Node data from primary node %s doesn't contain"
8877
                         " free memory information" % pnode)
8878
      elif instance_info.fail_msg:
8879
        self.warn.append("Can't get instance runtime information: %s" %
8880
                        instance_info.fail_msg)
8881
      else:
8882
        if instance_info.payload:
8883
          current_mem = int(instance_info.payload['memory'])
8884
        else:
8885
          # Assume instance not running
8886
          # (there is a slight race condition here, but it's not very probable,
8887
          # and we have no other way to check)
8888
          current_mem = 0
8889
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
8890
                    pninfo.payload['memory_free'])
8891
        if miss_mem > 0:
8892
          raise errors.OpPrereqError("This change will prevent the instance"
8893
                                     " from starting, due to %d MB of memory"
8894
                                     " missing on its primary node" % miss_mem,
8895
                                     errors.ECODE_NORES)
8896

    
8897
      if be_new[constants.BE_AUTO_BALANCE]:
8898
        for node, nres in nodeinfo.items():
8899
          if node not in instance.secondary_nodes:
8900
            continue
8901
          msg = nres.fail_msg
8902
          if msg:
8903
            self.warn.append("Can't get info from secondary node %s: %s" %
8904
                             (node, msg))
8905
          elif not isinstance(nres.payload.get('memory_free', None), int):
8906
            self.warn.append("Secondary node %s didn't return free"
8907
                             " memory information" % node)
8908
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
8909
            self.warn.append("Not enough memory to failover instance to"
8910
                             " secondary node %s" % node)
8911

    
8912
    # NIC processing
8913
    self.nic_pnew = {}
8914
    self.nic_pinst = {}
8915
    for nic_op, nic_dict in self.op.nics:
8916
      if nic_op == constants.DDM_REMOVE:
8917
        if not instance.nics:
8918
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
8919
                                     errors.ECODE_INVAL)
8920
        continue
8921
      if nic_op != constants.DDM_ADD:
8922
        # an existing nic
8923
        if not instance.nics:
8924
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
8925
                                     " no NICs" % nic_op,
8926
                                     errors.ECODE_INVAL)
8927
        if nic_op < 0 or nic_op >= len(instance.nics):
8928
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
8929
                                     " are 0 to %d" %
8930
                                     (nic_op, len(instance.nics) - 1),
8931
                                     errors.ECODE_INVAL)
8932
        old_nic_params = instance.nics[nic_op].nicparams
8933
        old_nic_ip = instance.nics[nic_op].ip
8934
      else:
8935
        old_nic_params = {}
8936
        old_nic_ip = None
8937

    
8938
      update_params_dict = dict([(key, nic_dict[key])
8939
                                 for key in constants.NICS_PARAMETERS
8940
                                 if key in nic_dict])
8941

    
8942
      if 'bridge' in nic_dict:
8943
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
8944

    
8945
      new_nic_params = _GetUpdatedParams(old_nic_params,
8946
                                         update_params_dict)
8947
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
8948
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
8949
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
8950
      self.nic_pinst[nic_op] = new_nic_params
8951
      self.nic_pnew[nic_op] = new_filled_nic_params
8952
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
8953

    
8954
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
8955
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
8956
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
8957
        if msg:
8958
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
8959
          if self.op.force:
8960
            self.warn.append(msg)
8961
          else:
8962
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
8963
      if new_nic_mode == constants.NIC_MODE_ROUTED:
8964
        if 'ip' in nic_dict:
8965
          nic_ip = nic_dict['ip']
8966
        else:
8967
          nic_ip = old_nic_ip
8968
        if nic_ip is None:
8969
          raise errors.OpPrereqError('Cannot set the nic ip to None'
8970
                                     ' on a routed nic', errors.ECODE_INVAL)
8971
      if 'mac' in nic_dict:
8972
        nic_mac = nic_dict['mac']
8973
        if nic_mac is None:
8974
          raise errors.OpPrereqError('Cannot set the nic mac to None',
8975
                                     errors.ECODE_INVAL)
8976
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8977
          # otherwise generate the mac
8978
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
8979
        else:
8980
          # or validate/reserve the current one
8981
          try:
8982
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
8983
          except errors.ReservationError:
8984
            raise errors.OpPrereqError("MAC address %s already in use"
8985
                                       " in cluster" % nic_mac,
8986
                                       errors.ECODE_NOTUNIQUE)
8987

    
8988
    # DISK processing
8989
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
8990
      raise errors.OpPrereqError("Disk operations not supported for"
8991
                                 " diskless instances",
8992
                                 errors.ECODE_INVAL)
8993
    for disk_op, _ in self.op.disks:
8994
      if disk_op == constants.DDM_REMOVE:
8995
        if len(instance.disks) == 1:
8996
          raise errors.OpPrereqError("Cannot remove the last disk of"
8997
                                     " an instance", errors.ECODE_INVAL)
8998
        _CheckInstanceDown(self, instance, "cannot remove disks")
8999

    
9000
      if (disk_op == constants.DDM_ADD and
9001
          len(instance.nics) >= constants.MAX_DISKS):
9002
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
9003
                                   " add more" % constants.MAX_DISKS,
9004
                                   errors.ECODE_STATE)
9005
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
9006
        # an existing disk
9007
        if disk_op < 0 or disk_op >= len(instance.disks):
9008
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9009
                                     " are 0 to %d" %
9010
                                     (disk_op, len(instance.disks)),
9011
                                     errors.ECODE_INVAL)
9012

    
9013
    return
9014

    
9015
  def _ConvertPlainToDrbd(self, feedback_fn):
9016
    """Converts an instance from plain to drbd.
9017

9018
    """
9019
    feedback_fn("Converting template to drbd")
9020
    instance = self.instance
9021
    pnode = instance.primary_node
9022
    snode = self.op.remote_node
9023

    
9024
    # create a fake disk info for _GenerateDiskTemplate
9025
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
9026
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9027
                                      instance.name, pnode, [snode],
9028
                                      disk_info, None, None, 0)
9029
    info = _GetInstanceInfoText(instance)
9030
    feedback_fn("Creating aditional volumes...")
9031
    # first, create the missing data and meta devices
9032
    for disk in new_disks:
9033
      # unfortunately this is... not too nice
9034
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9035
                            info, True)
9036
      for child in disk.children:
9037
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9038
    # at this stage, all new LVs have been created, we can rename the
9039
    # old ones
9040
    feedback_fn("Renaming original volumes...")
9041
    rename_list = [(o, n.children[0].logical_id)
9042
                   for (o, n) in zip(instance.disks, new_disks)]
9043
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9044
    result.Raise("Failed to rename original LVs")
9045

    
9046
    feedback_fn("Initializing DRBD devices...")
9047
    # all child devices are in place, we can now create the DRBD devices
9048
    for disk in new_disks:
9049
      for node in [pnode, snode]:
9050
        f_create = node == pnode
9051
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9052

    
9053
    # at this point, the instance has been modified
9054
    instance.disk_template = constants.DT_DRBD8
9055
    instance.disks = new_disks
9056
    self.cfg.Update(instance, feedback_fn)
9057

    
9058
    # disks are created, waiting for sync
9059
    disk_abort = not _WaitForSync(self, instance)
9060
    if disk_abort:
9061
      raise errors.OpExecError("There are some degraded disks for"
9062
                               " this instance, please cleanup manually")
9063

    
9064
  def _ConvertDrbdToPlain(self, feedback_fn):
9065
    """Converts an instance from drbd to plain.
9066

9067
    """
9068
    instance = self.instance
9069
    assert len(instance.secondary_nodes) == 1
9070
    pnode = instance.primary_node
9071
    snode = instance.secondary_nodes[0]
9072
    feedback_fn("Converting template to plain")
9073

    
9074
    old_disks = instance.disks
9075
    new_disks = [d.children[0] for d in old_disks]
9076

    
9077
    # copy over size and mode
9078
    for parent, child in zip(old_disks, new_disks):
9079
      child.size = parent.size
9080
      child.mode = parent.mode
9081

    
9082
    # update instance structure
9083
    instance.disks = new_disks
9084
    instance.disk_template = constants.DT_PLAIN
9085
    self.cfg.Update(instance, feedback_fn)
9086

    
9087
    feedback_fn("Removing volumes on the secondary node...")
9088
    for disk in old_disks:
9089
      self.cfg.SetDiskID(disk, snode)
9090
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9091
      if msg:
9092
        self.LogWarning("Could not remove block device %s on node %s,"
9093
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9094

    
9095
    feedback_fn("Removing unneeded volumes on the primary node...")
9096
    for idx, disk in enumerate(old_disks):
9097
      meta = disk.children[1]
9098
      self.cfg.SetDiskID(meta, pnode)
9099
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9100
      if msg:
9101
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9102
                        " continuing anyway: %s", idx, pnode, msg)
9103

    
9104

    
9105
  def Exec(self, feedback_fn):
9106
    """Modifies an instance.
9107

9108
    All parameters take effect only at the next restart of the instance.
9109

9110
    """
9111
    # Process here the warnings from CheckPrereq, as we don't have a
9112
    # feedback_fn there.
9113
    for warn in self.warn:
9114
      feedback_fn("WARNING: %s" % warn)
9115

    
9116
    result = []
9117
    instance = self.instance
9118
    # disk changes
9119
    for disk_op, disk_dict in self.op.disks:
9120
      if disk_op == constants.DDM_REMOVE:
9121
        # remove the last disk
9122
        device = instance.disks.pop()
9123
        device_idx = len(instance.disks)
9124
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9125
          self.cfg.SetDiskID(disk, node)
9126
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9127
          if msg:
9128
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9129
                            " continuing anyway", device_idx, node, msg)
9130
        result.append(("disk/%d" % device_idx, "remove"))
9131
      elif disk_op == constants.DDM_ADD:
9132
        # add a new disk
9133
        if instance.disk_template == constants.DT_FILE:
9134
          file_driver, file_path = instance.disks[0].logical_id
9135
          file_path = os.path.dirname(file_path)
9136
        else:
9137
          file_driver = file_path = None
9138
        disk_idx_base = len(instance.disks)
9139
        new_disk = _GenerateDiskTemplate(self,
9140
                                         instance.disk_template,
9141
                                         instance.name, instance.primary_node,
9142
                                         instance.secondary_nodes,
9143
                                         [disk_dict],
9144
                                         file_path,
9145
                                         file_driver,
9146
                                         disk_idx_base)[0]
9147
        instance.disks.append(new_disk)
9148
        info = _GetInstanceInfoText(instance)
9149

    
9150
        logging.info("Creating volume %s for instance %s",
9151
                     new_disk.iv_name, instance.name)
9152
        # Note: this needs to be kept in sync with _CreateDisks
9153
        #HARDCODE
9154
        for node in instance.all_nodes:
9155
          f_create = node == instance.primary_node
9156
          try:
9157
            _CreateBlockDev(self, node, instance, new_disk,
9158
                            f_create, info, f_create)
9159
          except errors.OpExecError, err:
9160
            self.LogWarning("Failed to create volume %s (%s) on"
9161
                            " node %s: %s",
9162
                            new_disk.iv_name, new_disk, node, err)
9163
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9164
                       (new_disk.size, new_disk.mode)))
9165
      else:
9166
        # change a given disk
9167
        instance.disks[disk_op].mode = disk_dict['mode']
9168
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9169

    
9170
    if self.op.disk_template:
9171
      r_shut = _ShutdownInstanceDisks(self, instance)
9172
      if not r_shut:
9173
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
9174
                                 " proceed with disk template conversion")
9175
      mode = (instance.disk_template, self.op.disk_template)
9176
      try:
9177
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9178
      except:
9179
        self.cfg.ReleaseDRBDMinors(instance.name)
9180
        raise
9181
      result.append(("disk_template", self.op.disk_template))
9182

    
9183
    # NIC changes
9184
    for nic_op, nic_dict in self.op.nics:
9185
      if nic_op == constants.DDM_REMOVE:
9186
        # remove the last nic
9187
        del instance.nics[-1]
9188
        result.append(("nic.%d" % len(instance.nics), "remove"))
9189
      elif nic_op == constants.DDM_ADD:
9190
        # mac and bridge should be set, by now
9191
        mac = nic_dict['mac']
9192
        ip = nic_dict.get('ip', None)
9193
        nicparams = self.nic_pinst[constants.DDM_ADD]
9194
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9195
        instance.nics.append(new_nic)
9196
        result.append(("nic.%d" % (len(instance.nics) - 1),
9197
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9198
                       (new_nic.mac, new_nic.ip,
9199
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9200
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9201
                       )))
9202
      else:
9203
        for key in 'mac', 'ip':
9204
          if key in nic_dict:
9205
            setattr(instance.nics[nic_op], key, nic_dict[key])
9206
        if nic_op in self.nic_pinst:
9207
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9208
        for key, val in nic_dict.iteritems():
9209
          result.append(("nic.%s/%d" % (key, nic_op), val))
9210

    
9211
    # hvparams changes
9212
    if self.op.hvparams:
9213
      instance.hvparams = self.hv_inst
9214
      for key, val in self.op.hvparams.iteritems():
9215
        result.append(("hv/%s" % key, val))
9216

    
9217
    # beparams changes
9218
    if self.op.beparams:
9219
      instance.beparams = self.be_inst
9220
      for key, val in self.op.beparams.iteritems():
9221
        result.append(("be/%s" % key, val))
9222

    
9223
    # OS change
9224
    if self.op.os_name:
9225
      instance.os = self.op.os_name
9226

    
9227
    # osparams changes
9228
    if self.op.osparams:
9229
      instance.osparams = self.os_inst
9230
      for key, val in self.op.osparams.iteritems():
9231
        result.append(("os/%s" % key, val))
9232

    
9233
    self.cfg.Update(instance, feedback_fn)
9234

    
9235
    return result
9236

    
9237
  _DISK_CONVERSIONS = {
9238
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9239
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9240
    }
9241

    
9242

    
9243
class LUQueryExports(NoHooksLU):
9244
  """Query the exports list
9245

9246
  """
9247
  _OP_PARAMS = [
9248
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
9249
    ("use_locking", False, _TBool),
9250
    ]
9251
  REQ_BGL = False
9252

    
9253
  def ExpandNames(self):
9254
    self.needed_locks = {}
9255
    self.share_locks[locking.LEVEL_NODE] = 1
9256
    if not self.op.nodes:
9257
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9258
    else:
9259
      self.needed_locks[locking.LEVEL_NODE] = \
9260
        _GetWantedNodes(self, self.op.nodes)
9261

    
9262
  def Exec(self, feedback_fn):
9263
    """Compute the list of all the exported system images.
9264

9265
    @rtype: dict
9266
    @return: a dictionary with the structure node->(export-list)
9267
        where export-list is a list of the instances exported on
9268
        that node.
9269

9270
    """
9271
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9272
    rpcresult = self.rpc.call_export_list(self.nodes)
9273
    result = {}
9274
    for node in rpcresult:
9275
      if rpcresult[node].fail_msg:
9276
        result[node] = False
9277
      else:
9278
        result[node] = rpcresult[node].payload
9279

    
9280
    return result
9281

    
9282

    
9283
class LUPrepareExport(NoHooksLU):
9284
  """Prepares an instance for an export and returns useful information.
9285

9286
  """
9287
  _OP_PARAMS = [
9288
    _PInstanceName,
9289
    ("mode", _NoDefault, _TElemOf(constants.EXPORT_MODES)),
9290
    ]
9291
  REQ_BGL = False
9292

    
9293
  def ExpandNames(self):
9294
    self._ExpandAndLockInstance()
9295

    
9296
  def CheckPrereq(self):
9297
    """Check prerequisites.
9298

9299
    """
9300
    instance_name = self.op.instance_name
9301

    
9302
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9303
    assert self.instance is not None, \
9304
          "Cannot retrieve locked instance %s" % self.op.instance_name
9305
    _CheckNodeOnline(self, self.instance.primary_node)
9306

    
9307
    self._cds = _GetClusterDomainSecret()
9308

    
9309
  def Exec(self, feedback_fn):
9310
    """Prepares an instance for an export.
9311

9312
    """
9313
    instance = self.instance
9314

    
9315
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9316
      salt = utils.GenerateSecret(8)
9317

    
9318
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9319
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9320
                                              constants.RIE_CERT_VALIDITY)
9321
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9322

    
9323
      (name, cert_pem) = result.payload
9324

    
9325
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9326
                                             cert_pem)
9327

    
9328
      return {
9329
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9330
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9331
                          salt),
9332
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9333
        }
9334

    
9335
    return None
9336

    
9337

    
9338
class LUExportInstance(LogicalUnit):
9339
  """Export an instance to an image in the cluster.
9340

9341
  """
9342
  HPATH = "instance-export"
9343
  HTYPE = constants.HTYPE_INSTANCE
9344
  _OP_PARAMS = [
9345
    _PInstanceName,
9346
    ("target_node", _NoDefault, _TOr(_TNonEmptyString, _TList)),
9347
    ("shutdown", True, _TBool),
9348
    _PShutdownTimeout,
9349
    ("remove_instance", False, _TBool),
9350
    ("ignore_remove_failures", False, _TBool),
9351
    ("mode", constants.EXPORT_MODE_LOCAL, _TElemOf(constants.EXPORT_MODES)),
9352
    ("x509_key_name", None, _TOr(_TList, _TNone)),
9353
    ("destination_x509_ca", None, _TMaybeString),
9354
    ]
9355
  REQ_BGL = False
9356

    
9357
  def CheckArguments(self):
9358
    """Check the arguments.
9359

9360
    """
9361
    self.x509_key_name = self.op.x509_key_name
9362
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9363

    
9364
    if self.op.remove_instance and not self.op.shutdown:
9365
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9366
                                 " down before")
9367

    
9368
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9369
      if not self.x509_key_name:
9370
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9371
                                   errors.ECODE_INVAL)
9372

    
9373
      if not self.dest_x509_ca_pem:
9374
        raise errors.OpPrereqError("Missing destination X509 CA",
9375
                                   errors.ECODE_INVAL)
9376

    
9377
  def ExpandNames(self):
9378
    self._ExpandAndLockInstance()
9379

    
9380
    # Lock all nodes for local exports
9381
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9382
      # FIXME: lock only instance primary and destination node
9383
      #
9384
      # Sad but true, for now we have do lock all nodes, as we don't know where
9385
      # the previous export might be, and in this LU we search for it and
9386
      # remove it from its current node. In the future we could fix this by:
9387
      #  - making a tasklet to search (share-lock all), then create the
9388
      #    new one, then one to remove, after
9389
      #  - removing the removal operation altogether
9390
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9391

    
9392
  def DeclareLocks(self, level):
9393
    """Last minute lock declaration."""
9394
    # All nodes are locked anyway, so nothing to do here.
9395

    
9396
  def BuildHooksEnv(self):
9397
    """Build hooks env.
9398

9399
    This will run on the master, primary node and target node.
9400

9401
    """
9402
    env = {
9403
      "EXPORT_MODE": self.op.mode,
9404
      "EXPORT_NODE": self.op.target_node,
9405
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9406
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9407
      # TODO: Generic function for boolean env variables
9408
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9409
      }
9410

    
9411
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9412

    
9413
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9414

    
9415
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9416
      nl.append(self.op.target_node)
9417

    
9418
    return env, nl, nl
9419

    
9420
  def CheckPrereq(self):
9421
    """Check prerequisites.
9422

9423
    This checks that the instance and node names are valid.
9424

9425
    """
9426
    instance_name = self.op.instance_name
9427

    
9428
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9429
    assert self.instance is not None, \
9430
          "Cannot retrieve locked instance %s" % self.op.instance_name
9431
    _CheckNodeOnline(self, self.instance.primary_node)
9432

    
9433
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9434
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9435
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9436
      assert self.dst_node is not None
9437

    
9438
      _CheckNodeOnline(self, self.dst_node.name)
9439
      _CheckNodeNotDrained(self, self.dst_node.name)
9440

    
9441
      self._cds = None
9442
      self.dest_disk_info = None
9443
      self.dest_x509_ca = None
9444

    
9445
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9446
      self.dst_node = None
9447

    
9448
      if len(self.op.target_node) != len(self.instance.disks):
9449
        raise errors.OpPrereqError(("Received destination information for %s"
9450
                                    " disks, but instance %s has %s disks") %
9451
                                   (len(self.op.target_node), instance_name,
9452
                                    len(self.instance.disks)),
9453
                                   errors.ECODE_INVAL)
9454

    
9455
      cds = _GetClusterDomainSecret()
9456

    
9457
      # Check X509 key name
9458
      try:
9459
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9460
      except (TypeError, ValueError), err:
9461
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9462

    
9463
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9464
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9465
                                   errors.ECODE_INVAL)
9466

    
9467
      # Load and verify CA
9468
      try:
9469
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9470
      except OpenSSL.crypto.Error, err:
9471
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9472
                                   (err, ), errors.ECODE_INVAL)
9473

    
9474
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9475
      if errcode is not None:
9476
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9477
                                   (msg, ), errors.ECODE_INVAL)
9478

    
9479
      self.dest_x509_ca = cert
9480

    
9481
      # Verify target information
9482
      disk_info = []
9483
      for idx, disk_data in enumerate(self.op.target_node):
9484
        try:
9485
          (host, port, magic) = \
9486
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9487
        except errors.GenericError, err:
9488
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9489
                                     (idx, err), errors.ECODE_INVAL)
9490

    
9491
        disk_info.append((host, port, magic))
9492

    
9493
      assert len(disk_info) == len(self.op.target_node)
9494
      self.dest_disk_info = disk_info
9495

    
9496
    else:
9497
      raise errors.ProgrammerError("Unhandled export mode %r" %
9498
                                   self.op.mode)
9499

    
9500
    # instance disk type verification
9501
    # TODO: Implement export support for file-based disks
9502
    for disk in self.instance.disks:
9503
      if disk.dev_type == constants.LD_FILE:
9504
        raise errors.OpPrereqError("Export not supported for instances with"
9505
                                   " file-based disks", errors.ECODE_INVAL)
9506

    
9507
  def _CleanupExports(self, feedback_fn):
9508
    """Removes exports of current instance from all other nodes.
9509

9510
    If an instance in a cluster with nodes A..D was exported to node C, its
9511
    exports will be removed from the nodes A, B and D.
9512

9513
    """
9514
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9515

    
9516
    nodelist = self.cfg.GetNodeList()
9517
    nodelist.remove(self.dst_node.name)
9518

    
9519
    # on one-node clusters nodelist will be empty after the removal
9520
    # if we proceed the backup would be removed because OpQueryExports
9521
    # substitutes an empty list with the full cluster node list.
9522
    iname = self.instance.name
9523
    if nodelist:
9524
      feedback_fn("Removing old exports for instance %s" % iname)
9525
      exportlist = self.rpc.call_export_list(nodelist)
9526
      for node in exportlist:
9527
        if exportlist[node].fail_msg:
9528
          continue
9529
        if iname in exportlist[node].payload:
9530
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9531
          if msg:
9532
            self.LogWarning("Could not remove older export for instance %s"
9533
                            " on node %s: %s", iname, node, msg)
9534

    
9535
  def Exec(self, feedback_fn):
9536
    """Export an instance to an image in the cluster.
9537

9538
    """
9539
    assert self.op.mode in constants.EXPORT_MODES
9540

    
9541
    instance = self.instance
9542
    src_node = instance.primary_node
9543

    
9544
    if self.op.shutdown:
9545
      # shutdown the instance, but not the disks
9546
      feedback_fn("Shutting down instance %s" % instance.name)
9547
      result = self.rpc.call_instance_shutdown(src_node, instance,
9548
                                               self.op.shutdown_timeout)
9549
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9550
      result.Raise("Could not shutdown instance %s on"
9551
                   " node %s" % (instance.name, src_node))
9552

    
9553
    # set the disks ID correctly since call_instance_start needs the
9554
    # correct drbd minor to create the symlinks
9555
    for disk in instance.disks:
9556
      self.cfg.SetDiskID(disk, src_node)
9557

    
9558
    activate_disks = (not instance.admin_up)
9559

    
9560
    if activate_disks:
9561
      # Activate the instance disks if we'exporting a stopped instance
9562
      feedback_fn("Activating disks for %s" % instance.name)
9563
      _StartInstanceDisks(self, instance, None)
9564

    
9565
    try:
9566
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9567
                                                     instance)
9568

    
9569
      helper.CreateSnapshots()
9570
      try:
9571
        if (self.op.shutdown and instance.admin_up and
9572
            not self.op.remove_instance):
9573
          assert not activate_disks
9574
          feedback_fn("Starting instance %s" % instance.name)
9575
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9576
          msg = result.fail_msg
9577
          if msg:
9578
            feedback_fn("Failed to start instance: %s" % msg)
9579
            _ShutdownInstanceDisks(self, instance)
9580
            raise errors.OpExecError("Could not start instance: %s" % msg)
9581

    
9582
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9583
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9584
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9585
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9586
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9587

    
9588
          (key_name, _, _) = self.x509_key_name
9589

    
9590
          dest_ca_pem = \
9591
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9592
                                            self.dest_x509_ca)
9593

    
9594
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9595
                                                     key_name, dest_ca_pem,
9596
                                                     timeouts)
9597
      finally:
9598
        helper.Cleanup()
9599

    
9600
      # Check for backwards compatibility
9601
      assert len(dresults) == len(instance.disks)
9602
      assert compat.all(isinstance(i, bool) for i in dresults), \
9603
             "Not all results are boolean: %r" % dresults
9604

    
9605
    finally:
9606
      if activate_disks:
9607
        feedback_fn("Deactivating disks for %s" % instance.name)
9608
        _ShutdownInstanceDisks(self, instance)
9609

    
9610
    if not (compat.all(dresults) and fin_resu):
9611
      failures = []
9612
      if not fin_resu:
9613
        failures.append("export finalization")
9614
      if not compat.all(dresults):
9615
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
9616
                               if not dsk)
9617
        failures.append("disk export: disk(s) %s" % fdsk)
9618

    
9619
      raise errors.OpExecError("Export failed, errors in %s" %
9620
                               utils.CommaJoin(failures))
9621

    
9622
    # At this point, the export was successful, we can cleanup/finish
9623

    
9624
    # Remove instance if requested
9625
    if self.op.remove_instance:
9626
      feedback_fn("Removing instance %s" % instance.name)
9627
      _RemoveInstance(self, feedback_fn, instance,
9628
                      self.op.ignore_remove_failures)
9629

    
9630
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9631
      self._CleanupExports(feedback_fn)
9632

    
9633
    return fin_resu, dresults
9634

    
9635

    
9636
class LURemoveExport(NoHooksLU):
9637
  """Remove exports related to the named instance.
9638

9639
  """
9640
  _OP_PARAMS = [
9641
    _PInstanceName,
9642
    ]
9643
  REQ_BGL = False
9644

    
9645
  def ExpandNames(self):
9646
    self.needed_locks = {}
9647
    # We need all nodes to be locked in order for RemoveExport to work, but we
9648
    # don't need to lock the instance itself, as nothing will happen to it (and
9649
    # we can remove exports also for a removed instance)
9650
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9651

    
9652
  def Exec(self, feedback_fn):
9653
    """Remove any export.
9654

9655
    """
9656
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9657
    # If the instance was not found we'll try with the name that was passed in.
9658
    # This will only work if it was an FQDN, though.
9659
    fqdn_warn = False
9660
    if not instance_name:
9661
      fqdn_warn = True
9662
      instance_name = self.op.instance_name
9663

    
9664
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
9665
    exportlist = self.rpc.call_export_list(locked_nodes)
9666
    found = False
9667
    for node in exportlist:
9668
      msg = exportlist[node].fail_msg
9669
      if msg:
9670
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
9671
        continue
9672
      if instance_name in exportlist[node].payload:
9673
        found = True
9674
        result = self.rpc.call_export_remove(node, instance_name)
9675
        msg = result.fail_msg
9676
        if msg:
9677
          logging.error("Could not remove export for instance %s"
9678
                        " on node %s: %s", instance_name, node, msg)
9679

    
9680
    if fqdn_warn and not found:
9681
      feedback_fn("Export not found. If trying to remove an export belonging"
9682
                  " to a deleted instance please use its Fully Qualified"
9683
                  " Domain Name.")
9684

    
9685

    
9686
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
9687
  """Generic tags LU.
9688

9689
  This is an abstract class which is the parent of all the other tags LUs.
9690

9691
  """
9692

    
9693
  def ExpandNames(self):
9694
    self.needed_locks = {}
9695
    if self.op.kind == constants.TAG_NODE:
9696
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
9697
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
9698
    elif self.op.kind == constants.TAG_INSTANCE:
9699
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
9700
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
9701

    
9702
  def CheckPrereq(self):
9703
    """Check prerequisites.
9704

9705
    """
9706
    if self.op.kind == constants.TAG_CLUSTER:
9707
      self.target = self.cfg.GetClusterInfo()
9708
    elif self.op.kind == constants.TAG_NODE:
9709
      self.target = self.cfg.GetNodeInfo(self.op.name)
9710
    elif self.op.kind == constants.TAG_INSTANCE:
9711
      self.target = self.cfg.GetInstanceInfo(self.op.name)
9712
    else:
9713
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
9714
                                 str(self.op.kind), errors.ECODE_INVAL)
9715

    
9716

    
9717
class LUGetTags(TagsLU):
9718
  """Returns the tags of a given object.
9719

9720
  """
9721
  _OP_PARAMS = [
9722
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9723
    ("name", _NoDefault, _TNonEmptyString),
9724
    ]
9725
  REQ_BGL = False
9726

    
9727
  def Exec(self, feedback_fn):
9728
    """Returns the tag list.
9729

9730
    """
9731
    return list(self.target.GetTags())
9732

    
9733

    
9734
class LUSearchTags(NoHooksLU):
9735
  """Searches the tags for a given pattern.
9736

9737
  """
9738
  _OP_PARAMS = [
9739
    ("pattern", _NoDefault, _TNonEmptyString),
9740
    ]
9741
  REQ_BGL = False
9742

    
9743
  def ExpandNames(self):
9744
    self.needed_locks = {}
9745

    
9746
  def CheckPrereq(self):
9747
    """Check prerequisites.
9748

9749
    This checks the pattern passed for validity by compiling it.
9750

9751
    """
9752
    try:
9753
      self.re = re.compile(self.op.pattern)
9754
    except re.error, err:
9755
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
9756
                                 (self.op.pattern, err), errors.ECODE_INVAL)
9757

    
9758
  def Exec(self, feedback_fn):
9759
    """Returns the tag list.
9760

9761
    """
9762
    cfg = self.cfg
9763
    tgts = [("/cluster", cfg.GetClusterInfo())]
9764
    ilist = cfg.GetAllInstancesInfo().values()
9765
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
9766
    nlist = cfg.GetAllNodesInfo().values()
9767
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
9768
    results = []
9769
    for path, target in tgts:
9770
      for tag in target.GetTags():
9771
        if self.re.search(tag):
9772
          results.append((path, tag))
9773
    return results
9774

    
9775

    
9776
class LUAddTags(TagsLU):
9777
  """Sets a tag on a given object.
9778

9779
  """
9780
  _OP_PARAMS = [
9781
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9782
    ("name", _NoDefault, _TNonEmptyString),
9783
    ("tags", _NoDefault, _TListOf(_TNonEmptyString)),
9784
    ]
9785
  REQ_BGL = False
9786

    
9787
  def CheckPrereq(self):
9788
    """Check prerequisites.
9789

9790
    This checks the type and length of the tag name and value.
9791

9792
    """
9793
    TagsLU.CheckPrereq(self)
9794
    for tag in self.op.tags:
9795
      objects.TaggableObject.ValidateTag(tag)
9796

    
9797
  def Exec(self, feedback_fn):
9798
    """Sets the tag.
9799

9800
    """
9801
    try:
9802
      for tag in self.op.tags:
9803
        self.target.AddTag(tag)
9804
    except errors.TagError, err:
9805
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
9806
    self.cfg.Update(self.target, feedback_fn)
9807

    
9808

    
9809
class LUDelTags(TagsLU):
9810
  """Delete a list of tags from a given object.
9811

9812
  """
9813
  _OP_PARAMS = [
9814
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9815
    ("name", _NoDefault, _TNonEmptyString),
9816
    ("tags", _NoDefault, _TListOf(_TNonEmptyString)),
9817
    ]
9818
  REQ_BGL = False
9819

    
9820
  def CheckPrereq(self):
9821
    """Check prerequisites.
9822

9823
    This checks that we have the given tag.
9824

9825
    """
9826
    TagsLU.CheckPrereq(self)
9827
    for tag in self.op.tags:
9828
      objects.TaggableObject.ValidateTag(tag)
9829
    del_tags = frozenset(self.op.tags)
9830
    cur_tags = self.target.GetTags()
9831
    if not del_tags <= cur_tags:
9832
      diff_tags = del_tags - cur_tags
9833
      diff_names = ["'%s'" % tag for tag in diff_tags]
9834
      diff_names.sort()
9835
      raise errors.OpPrereqError("Tag(s) %s not found" %
9836
                                 (",".join(diff_names)), errors.ECODE_NOENT)
9837

    
9838
  def Exec(self, feedback_fn):
9839
    """Remove the tag from the object.
9840

9841
    """
9842
    for tag in self.op.tags:
9843
      self.target.RemoveTag(tag)
9844
    self.cfg.Update(self.target, feedback_fn)
9845

    
9846

    
9847
class LUTestDelay(NoHooksLU):
9848
  """Sleep for a specified amount of time.
9849

9850
  This LU sleeps on the master and/or nodes for a specified amount of
9851
  time.
9852

9853
  """
9854
  _OP_PARAMS = [
9855
    ("duration", _NoDefault, _TFloat),
9856
    ("on_master", True, _TBool),
9857
    ("on_nodes", _EmptyList, _TListOf(_TNonEmptyString)),
9858
    ("repeat", 0, _TPositiveInt)
9859
    ]
9860
  REQ_BGL = False
9861

    
9862
  def ExpandNames(self):
9863
    """Expand names and set required locks.
9864

9865
    This expands the node list, if any.
9866

9867
    """
9868
    self.needed_locks = {}
9869
    if self.op.on_nodes:
9870
      # _GetWantedNodes can be used here, but is not always appropriate to use
9871
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
9872
      # more information.
9873
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
9874
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
9875

    
9876
  def _TestDelay(self):
9877
    """Do the actual sleep.
9878

9879
    """
9880
    if self.op.on_master:
9881
      if not utils.TestDelay(self.op.duration):
9882
        raise errors.OpExecError("Error during master delay test")
9883
    if self.op.on_nodes:
9884
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
9885
      for node, node_result in result.items():
9886
        node_result.Raise("Failure during rpc call to node %s" % node)
9887

    
9888
  def Exec(self, feedback_fn):
9889
    """Execute the test delay opcode, with the wanted repetitions.
9890

9891
    """
9892
    if self.op.repeat == 0:
9893
      self._TestDelay()
9894
    else:
9895
      top_value = self.op.repeat - 1
9896
      for i in range(self.op.repeat):
9897
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
9898
        self._TestDelay()
9899

    
9900

    
9901
class LUTestJobqueue(NoHooksLU):
9902
  """Utility LU to test some aspects of the job queue.
9903

9904
  """
9905
  _OP_PARAMS = [
9906
    ("notify_waitlock", False, _TBool),
9907
    ("notify_exec", False, _TBool),
9908
    ("log_messages", _EmptyList, _TListOf(_TString)),
9909
    ("fail", False, _TBool),
9910
    ]
9911
  REQ_BGL = False
9912

    
9913
  # Must be lower than default timeout for WaitForJobChange to see whether it
9914
  # notices changed jobs
9915
  _CLIENT_CONNECT_TIMEOUT = 20.0
9916
  _CLIENT_CONFIRM_TIMEOUT = 60.0
9917

    
9918
  @classmethod
9919
  def _NotifyUsingSocket(cls, cb, errcls):
9920
    """Opens a Unix socket and waits for another program to connect.
9921

9922
    @type cb: callable
9923
    @param cb: Callback to send socket name to client
9924
    @type errcls: class
9925
    @param errcls: Exception class to use for errors
9926

9927
    """
9928
    # Using a temporary directory as there's no easy way to create temporary
9929
    # sockets without writing a custom loop around tempfile.mktemp and
9930
    # socket.bind
9931
    tmpdir = tempfile.mkdtemp()
9932
    try:
9933
      tmpsock = utils.PathJoin(tmpdir, "sock")
9934

    
9935
      logging.debug("Creating temporary socket at %s", tmpsock)
9936
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
9937
      try:
9938
        sock.bind(tmpsock)
9939
        sock.listen(1)
9940

    
9941
        # Send details to client
9942
        cb(tmpsock)
9943

    
9944
        # Wait for client to connect before continuing
9945
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
9946
        try:
9947
          (conn, _) = sock.accept()
9948
        except socket.error, err:
9949
          raise errcls("Client didn't connect in time (%s)" % err)
9950
      finally:
9951
        sock.close()
9952
    finally:
9953
      # Remove as soon as client is connected
9954
      shutil.rmtree(tmpdir)
9955

    
9956
    # Wait for client to close
9957
    try:
9958
      try:
9959
        # pylint: disable-msg=E1101
9960
        # Instance of '_socketobject' has no ... member
9961
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
9962
        conn.recv(1)
9963
      except socket.error, err:
9964
        raise errcls("Client failed to confirm notification (%s)" % err)
9965
    finally:
9966
      conn.close()
9967

    
9968
  def _SendNotification(self, test, arg, sockname):
9969
    """Sends a notification to the client.
9970

9971
    @type test: string
9972
    @param test: Test name
9973
    @param arg: Test argument (depends on test)
9974
    @type sockname: string
9975
    @param sockname: Socket path
9976

9977
    """
9978
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
9979

    
9980
  def _Notify(self, prereq, test, arg):
9981
    """Notifies the client of a test.
9982

9983
    @type prereq: bool
9984
    @param prereq: Whether this is a prereq-phase test
9985
    @type test: string
9986
    @param test: Test name
9987
    @param arg: Test argument (depends on test)
9988

9989
    """
9990
    if prereq:
9991
      errcls = errors.OpPrereqError
9992
    else:
9993
      errcls = errors.OpExecError
9994

    
9995
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
9996
                                                  test, arg),
9997
                                   errcls)
9998

    
9999
  def CheckArguments(self):
10000
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
10001
    self.expandnames_calls = 0
10002

    
10003
  def ExpandNames(self):
10004
    checkargs_calls = getattr(self, "checkargs_calls", 0)
10005
    if checkargs_calls < 1:
10006
      raise errors.ProgrammerError("CheckArguments was not called")
10007

    
10008
    self.expandnames_calls += 1
10009

    
10010
    if self.op.notify_waitlock:
10011
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
10012

    
10013
    self.LogInfo("Expanding names")
10014

    
10015
    # Get lock on master node (just to get a lock, not for a particular reason)
10016
    self.needed_locks = {
10017
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
10018
      }
10019

    
10020
  def Exec(self, feedback_fn):
10021
    if self.expandnames_calls < 1:
10022
      raise errors.ProgrammerError("ExpandNames was not called")
10023

    
10024
    if self.op.notify_exec:
10025
      self._Notify(False, constants.JQT_EXEC, None)
10026

    
10027
    self.LogInfo("Executing")
10028

    
10029
    if self.op.log_messages:
10030
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
10031
      for idx, msg in enumerate(self.op.log_messages):
10032
        self.LogInfo("Sending log message %s", idx + 1)
10033
        feedback_fn(constants.JQT_MSGPREFIX + msg)
10034
        # Report how many test messages have been sent
10035
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
10036

    
10037
    if self.op.fail:
10038
      raise errors.OpExecError("Opcode failure was requested")
10039

    
10040
    return True
10041

    
10042

    
10043
class IAllocator(object):
10044
  """IAllocator framework.
10045

10046
  An IAllocator instance has three sets of attributes:
10047
    - cfg that is needed to query the cluster
10048
    - input data (all members of the _KEYS class attribute are required)
10049
    - four buffer attributes (in|out_data|text), that represent the
10050
      input (to the external script) in text and data structure format,
10051
      and the output from it, again in two formats
10052
    - the result variables from the script (success, info, nodes) for
10053
      easy usage
10054

10055
  """
10056
  # pylint: disable-msg=R0902
10057
  # lots of instance attributes
10058
  _ALLO_KEYS = [
10059
    "name", "mem_size", "disks", "disk_template",
10060
    "os", "tags", "nics", "vcpus", "hypervisor",
10061
    ]
10062
  _RELO_KEYS = [
10063
    "name", "relocate_from",
10064
    ]
10065
  _EVAC_KEYS = [
10066
    "evac_nodes",
10067
    ]
10068

    
10069
  def __init__(self, cfg, rpc, mode, **kwargs):
10070
    self.cfg = cfg
10071
    self.rpc = rpc
10072
    # init buffer variables
10073
    self.in_text = self.out_text = self.in_data = self.out_data = None
10074
    # init all input fields so that pylint is happy
10075
    self.mode = mode
10076
    self.mem_size = self.disks = self.disk_template = None
10077
    self.os = self.tags = self.nics = self.vcpus = None
10078
    self.hypervisor = None
10079
    self.relocate_from = None
10080
    self.name = None
10081
    self.evac_nodes = None
10082
    # computed fields
10083
    self.required_nodes = None
10084
    # init result fields
10085
    self.success = self.info = self.result = None
10086
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10087
      keyset = self._ALLO_KEYS
10088
      fn = self._AddNewInstance
10089
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10090
      keyset = self._RELO_KEYS
10091
      fn = self._AddRelocateInstance
10092
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10093
      keyset = self._EVAC_KEYS
10094
      fn = self._AddEvacuateNodes
10095
    else:
10096
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
10097
                                   " IAllocator" % self.mode)
10098
    for key in kwargs:
10099
      if key not in keyset:
10100
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
10101
                                     " IAllocator" % key)
10102
      setattr(self, key, kwargs[key])
10103

    
10104
    for key in keyset:
10105
      if key not in kwargs:
10106
        raise errors.ProgrammerError("Missing input parameter '%s' to"
10107
                                     " IAllocator" % key)
10108
    self._BuildInputData(fn)
10109

    
10110
  def _ComputeClusterData(self):
10111
    """Compute the generic allocator input data.
10112

10113
    This is the data that is independent of the actual operation.
10114

10115
    """
10116
    cfg = self.cfg
10117
    cluster_info = cfg.GetClusterInfo()
10118
    # cluster data
10119
    data = {
10120
      "version": constants.IALLOCATOR_VERSION,
10121
      "cluster_name": cfg.GetClusterName(),
10122
      "cluster_tags": list(cluster_info.GetTags()),
10123
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
10124
      # we don't have job IDs
10125
      }
10126
    iinfo = cfg.GetAllInstancesInfo().values()
10127
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
10128

    
10129
    # node data
10130
    node_results = {}
10131
    node_list = cfg.GetNodeList()
10132

    
10133
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10134
      hypervisor_name = self.hypervisor
10135
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10136
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
10137
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10138
      hypervisor_name = cluster_info.enabled_hypervisors[0]
10139

    
10140
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
10141
                                        hypervisor_name)
10142
    node_iinfo = \
10143
      self.rpc.call_all_instances_info(node_list,
10144
                                       cluster_info.enabled_hypervisors)
10145
    for nname, nresult in node_data.items():
10146
      # first fill in static (config-based) values
10147
      ninfo = cfg.GetNodeInfo(nname)
10148
      pnr = {
10149
        "tags": list(ninfo.GetTags()),
10150
        "primary_ip": ninfo.primary_ip,
10151
        "secondary_ip": ninfo.secondary_ip,
10152
        "offline": ninfo.offline,
10153
        "drained": ninfo.drained,
10154
        "master_candidate": ninfo.master_candidate,
10155
        }
10156

    
10157
      if not (ninfo.offline or ninfo.drained):
10158
        nresult.Raise("Can't get data for node %s" % nname)
10159
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
10160
                                nname)
10161
        remote_info = nresult.payload
10162

    
10163
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
10164
                     'vg_size', 'vg_free', 'cpu_total']:
10165
          if attr not in remote_info:
10166
            raise errors.OpExecError("Node '%s' didn't return attribute"
10167
                                     " '%s'" % (nname, attr))
10168
          if not isinstance(remote_info[attr], int):
10169
            raise errors.OpExecError("Node '%s' returned invalid value"
10170
                                     " for '%s': %s" %
10171
                                     (nname, attr, remote_info[attr]))
10172
        # compute memory used by primary instances
10173
        i_p_mem = i_p_up_mem = 0
10174
        for iinfo, beinfo in i_list:
10175
          if iinfo.primary_node == nname:
10176
            i_p_mem += beinfo[constants.BE_MEMORY]
10177
            if iinfo.name not in node_iinfo[nname].payload:
10178
              i_used_mem = 0
10179
            else:
10180
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
10181
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
10182
            remote_info['memory_free'] -= max(0, i_mem_diff)
10183

    
10184
            if iinfo.admin_up:
10185
              i_p_up_mem += beinfo[constants.BE_MEMORY]
10186

    
10187
        # compute memory used by instances
10188
        pnr_dyn = {
10189
          "total_memory": remote_info['memory_total'],
10190
          "reserved_memory": remote_info['memory_dom0'],
10191
          "free_memory": remote_info['memory_free'],
10192
          "total_disk": remote_info['vg_size'],
10193
          "free_disk": remote_info['vg_free'],
10194
          "total_cpus": remote_info['cpu_total'],
10195
          "i_pri_memory": i_p_mem,
10196
          "i_pri_up_memory": i_p_up_mem,
10197
          }
10198
        pnr.update(pnr_dyn)
10199

    
10200
      node_results[nname] = pnr
10201
    data["nodes"] = node_results
10202

    
10203
    # instance data
10204
    instance_data = {}
10205
    for iinfo, beinfo in i_list:
10206
      nic_data = []
10207
      for nic in iinfo.nics:
10208
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
10209
        nic_dict = {"mac": nic.mac,
10210
                    "ip": nic.ip,
10211
                    "mode": filled_params[constants.NIC_MODE],
10212
                    "link": filled_params[constants.NIC_LINK],
10213
                   }
10214
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
10215
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
10216
        nic_data.append(nic_dict)
10217
      pir = {
10218
        "tags": list(iinfo.GetTags()),
10219
        "admin_up": iinfo.admin_up,
10220
        "vcpus": beinfo[constants.BE_VCPUS],
10221
        "memory": beinfo[constants.BE_MEMORY],
10222
        "os": iinfo.os,
10223
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
10224
        "nics": nic_data,
10225
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
10226
        "disk_template": iinfo.disk_template,
10227
        "hypervisor": iinfo.hypervisor,
10228
        }
10229
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
10230
                                                 pir["disks"])
10231
      instance_data[iinfo.name] = pir
10232

    
10233
    data["instances"] = instance_data
10234

    
10235
    self.in_data = data
10236

    
10237
  def _AddNewInstance(self):
10238
    """Add new instance data to allocator structure.
10239

10240
    This in combination with _AllocatorGetClusterData will create the
10241
    correct structure needed as input for the allocator.
10242

10243
    The checks for the completeness of the opcode must have already been
10244
    done.
10245

10246
    """
10247
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
10248

    
10249
    if self.disk_template in constants.DTS_NET_MIRROR:
10250
      self.required_nodes = 2
10251
    else:
10252
      self.required_nodes = 1
10253
    request = {
10254
      "name": self.name,
10255
      "disk_template": self.disk_template,
10256
      "tags": self.tags,
10257
      "os": self.os,
10258
      "vcpus": self.vcpus,
10259
      "memory": self.mem_size,
10260
      "disks": self.disks,
10261
      "disk_space_total": disk_space,
10262
      "nics": self.nics,
10263
      "required_nodes": self.required_nodes,
10264
      }
10265
    return request
10266

    
10267
  def _AddRelocateInstance(self):
10268
    """Add relocate instance data to allocator structure.
10269

10270
    This in combination with _IAllocatorGetClusterData will create the
10271
    correct structure needed as input for the allocator.
10272

10273
    The checks for the completeness of the opcode must have already been
10274
    done.
10275

10276
    """
10277
    instance = self.cfg.GetInstanceInfo(self.name)
10278
    if instance is None:
10279
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
10280
                                   " IAllocator" % self.name)
10281

    
10282
    if instance.disk_template not in constants.DTS_NET_MIRROR:
10283
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
10284
                                 errors.ECODE_INVAL)
10285

    
10286
    if len(instance.secondary_nodes) != 1:
10287
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
10288
                                 errors.ECODE_STATE)
10289

    
10290
    self.required_nodes = 1
10291
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
10292
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
10293

    
10294
    request = {
10295
      "name": self.name,
10296
      "disk_space_total": disk_space,
10297
      "required_nodes": self.required_nodes,
10298
      "relocate_from": self.relocate_from,
10299
      }
10300
    return request
10301

    
10302
  def _AddEvacuateNodes(self):
10303
    """Add evacuate nodes data to allocator structure.
10304

10305
    """
10306
    request = {
10307
      "evac_nodes": self.evac_nodes
10308
      }
10309
    return request
10310

    
10311
  def _BuildInputData(self, fn):
10312
    """Build input data structures.
10313

10314
    """
10315
    self._ComputeClusterData()
10316

    
10317
    request = fn()
10318
    request["type"] = self.mode
10319
    self.in_data["request"] = request
10320

    
10321
    self.in_text = serializer.Dump(self.in_data)
10322

    
10323
  def Run(self, name, validate=True, call_fn=None):
10324
    """Run an instance allocator and return the results.
10325

10326
    """
10327
    if call_fn is None:
10328
      call_fn = self.rpc.call_iallocator_runner
10329

    
10330
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
10331
    result.Raise("Failure while running the iallocator script")
10332

    
10333
    self.out_text = result.payload
10334
    if validate:
10335
      self._ValidateResult()
10336

    
10337
  def _ValidateResult(self):
10338
    """Process the allocator results.
10339

10340
    This will process and if successful save the result in
10341
    self.out_data and the other parameters.
10342

10343
    """
10344
    try:
10345
      rdict = serializer.Load(self.out_text)
10346
    except Exception, err:
10347
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
10348

    
10349
    if not isinstance(rdict, dict):
10350
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
10351

    
10352
    # TODO: remove backwards compatiblity in later versions
10353
    if "nodes" in rdict and "result" not in rdict:
10354
      rdict["result"] = rdict["nodes"]
10355
      del rdict["nodes"]
10356

    
10357
    for key in "success", "info", "result":
10358
      if key not in rdict:
10359
        raise errors.OpExecError("Can't parse iallocator results:"
10360
                                 " missing key '%s'" % key)
10361
      setattr(self, key, rdict[key])
10362

    
10363
    if not isinstance(rdict["result"], list):
10364
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
10365
                               " is not a list")
10366
    self.out_data = rdict
10367

    
10368

    
10369
class LUTestAllocator(NoHooksLU):
10370
  """Run allocator tests.
10371

10372
  This LU runs the allocator tests
10373

10374
  """
10375
  _OP_PARAMS = [
10376
    ("direction", _NoDefault, _TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS)),
10377
    ("mode", _NoDefault, _TElemOf(constants.VALID_IALLOCATOR_MODES)),
10378
    ("name", _NoDefault, _TNonEmptyString),
10379
    ("nics", _NoDefault, _TOr(_TNone, _TListOf(
10380
      _TDictOf(_TElemOf(["mac", "ip", "bridge"]),
10381
               _TOr(_TNone, _TNonEmptyString))))),
10382
    ("disks", _NoDefault, _TOr(_TNone, _TList)),
10383
    ("hypervisor", None, _TMaybeString),
10384
    ("allocator", None, _TMaybeString),
10385
    ("tags", _EmptyList, _TListOf(_TNonEmptyString)),
10386
    ("mem_size", None, _TOr(_TNone, _TPositiveInt)),
10387
    ("vcpus", None, _TOr(_TNone, _TPositiveInt)),
10388
    ("os", None, _TMaybeString),
10389
    ("disk_template", None, _TMaybeString),
10390
    ("evac_nodes", None, _TOr(_TNone, _TListOf(_TNonEmptyString))),
10391
    ]
10392

    
10393
  def CheckPrereq(self):
10394
    """Check prerequisites.
10395

10396
    This checks the opcode parameters depending on the director and mode test.
10397

10398
    """
10399
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10400
      for attr in ["mem_size", "disks", "disk_template",
10401
                   "os", "tags", "nics", "vcpus"]:
10402
        if not hasattr(self.op, attr):
10403
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
10404
                                     attr, errors.ECODE_INVAL)
10405
      iname = self.cfg.ExpandInstanceName(self.op.name)
10406
      if iname is not None:
10407
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
10408
                                   iname, errors.ECODE_EXISTS)
10409
      if not isinstance(self.op.nics, list):
10410
        raise errors.OpPrereqError("Invalid parameter 'nics'",
10411
                                   errors.ECODE_INVAL)
10412
      if not isinstance(self.op.disks, list):
10413
        raise errors.OpPrereqError("Invalid parameter 'disks'",
10414
                                   errors.ECODE_INVAL)
10415
      for row in self.op.disks:
10416
        if (not isinstance(row, dict) or
10417
            "size" not in row or
10418
            not isinstance(row["size"], int) or
10419
            "mode" not in row or
10420
            row["mode"] not in ['r', 'w']):
10421
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
10422
                                     " parameter", errors.ECODE_INVAL)
10423
      if self.op.hypervisor is None:
10424
        self.op.hypervisor = self.cfg.GetHypervisorType()
10425
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10426
      fname = _ExpandInstanceName(self.cfg, self.op.name)
10427
      self.op.name = fname
10428
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
10429
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10430
      if not hasattr(self.op, "evac_nodes"):
10431
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
10432
                                   " opcode input", errors.ECODE_INVAL)
10433
    else:
10434
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
10435
                                 self.op.mode, errors.ECODE_INVAL)
10436

    
10437
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
10438
      if self.op.allocator is None:
10439
        raise errors.OpPrereqError("Missing allocator name",
10440
                                   errors.ECODE_INVAL)
10441
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
10442
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
10443
                                 self.op.direction, errors.ECODE_INVAL)
10444

    
10445
  def Exec(self, feedback_fn):
10446
    """Run the allocator test.
10447

10448
    """
10449
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10450
      ial = IAllocator(self.cfg, self.rpc,
10451
                       mode=self.op.mode,
10452
                       name=self.op.name,
10453
                       mem_size=self.op.mem_size,
10454
                       disks=self.op.disks,
10455
                       disk_template=self.op.disk_template,
10456
                       os=self.op.os,
10457
                       tags=self.op.tags,
10458
                       nics=self.op.nics,
10459
                       vcpus=self.op.vcpus,
10460
                       hypervisor=self.op.hypervisor,
10461
                       )
10462
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10463
      ial = IAllocator(self.cfg, self.rpc,
10464
                       mode=self.op.mode,
10465
                       name=self.op.name,
10466
                       relocate_from=list(self.relocate_from),
10467
                       )
10468
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10469
      ial = IAllocator(self.cfg, self.rpc,
10470
                       mode=self.op.mode,
10471
                       evac_nodes=self.op.evac_nodes)
10472
    else:
10473
      raise errors.ProgrammerError("Uncatched mode %s in"
10474
                                   " LUTestAllocator.Exec", self.op.mode)
10475

    
10476
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
10477
      result = ial.in_text
10478
    else:
10479
      ial.Run(self.op.allocator, validate=False)
10480
      result = ial.out_text
10481
    return result