Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ b43dcc5a

History | View | Annotate | Download (365.8 kB)

1
#
2
#
3

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

    
21

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

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

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

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

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

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

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

    
59

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

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

66
  """
67
  return []
68

    
69

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

73
  """
74
  return {}
75

    
76

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

    
80

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

    
84

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

89
  """
90
  return val is not None
91

    
92

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

96
  """
97
  return val is None
98

    
99

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

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

    
106

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

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

    
113

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

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

    
120

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

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

    
127

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

131
  """
132
  return bool(val)
133

    
134

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

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

    
141

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

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

    
149

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

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

    
156

    
157
# 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
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
1253

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

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

    
1265
    if modify_ssh_setup:
1266
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
1267
      utils.CreateBackup(priv_key)
1268
      utils.CreateBackup(pub_key)
1269

    
1270
    return master
1271

    
1272

    
1273
def _VerifyCertificate(filename):
1274
  """Verifies a certificate for LUVerifyCluster.
1275

1276
  @type filename: string
1277
  @param filename: Path to PEM file
1278

1279
  """
1280
  try:
1281
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1282
                                           utils.ReadFile(filename))
1283
  except Exception, err: # pylint: disable-msg=W0703
1284
    return (LUVerifyCluster.ETYPE_ERROR,
1285
            "Failed to load X509 certificate %s: %s" % (filename, err))
1286

    
1287
  (errcode, msg) = \
1288
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1289
                                constants.SSL_CERT_EXPIRATION_ERROR)
1290

    
1291
  if msg:
1292
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1293
  else:
1294
    fnamemsg = None
1295

    
1296
  if errcode is None:
1297
    return (None, fnamemsg)
1298
  elif errcode == utils.CERT_WARNING:
1299
    return (LUVerifyCluster.ETYPE_WARNING, fnamemsg)
1300
  elif errcode == utils.CERT_ERROR:
1301
    return (LUVerifyCluster.ETYPE_ERROR, fnamemsg)
1302

    
1303
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1304

    
1305

    
1306
class LUVerifyCluster(LogicalUnit):
1307
  """Verifies the cluster status.
1308

1309
  """
1310
  HPATH = "cluster-verify"
1311
  HTYPE = constants.HTYPE_CLUSTER
1312
  _OP_PARAMS = [
1313
    ("skip_checks", _EmptyList,
1314
     _TListOf(_TElemOf(constants.VERIFY_OPTIONAL_CHECKS))),
1315
    ("verbose", False, _TBool),
1316
    ("error_codes", False, _TBool),
1317
    ("debug_simulate_errors", False, _TBool),
1318
    ]
1319
  REQ_BGL = False
1320

    
1321
  TCLUSTER = "cluster"
1322
  TNODE = "node"
1323
  TINSTANCE = "instance"
1324

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

    
1350
  ETYPE_FIELD = "code"
1351
  ETYPE_ERROR = "ERROR"
1352
  ETYPE_WARNING = "WARNING"
1353

    
1354
  class NodeImage(object):
1355
    """A class representing the logical and physical status of a node.
1356

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

1383
    """
1384
    def __init__(self, offline=False, name=None):
1385
      self.name = name
1386
      self.volumes = {}
1387
      self.instances = []
1388
      self.pinst = []
1389
      self.sinst = []
1390
      self.sbp = {}
1391
      self.mfree = 0
1392
      self.dfree = 0
1393
      self.offline = offline
1394
      self.rpc_fail = False
1395
      self.lvm_fail = False
1396
      self.hyp_fail = False
1397
      self.ghost = False
1398
      self.os_fail = False
1399
      self.oslist = {}
1400

    
1401
  def ExpandNames(self):
1402
    self.needed_locks = {
1403
      locking.LEVEL_NODE: locking.ALL_SET,
1404
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1405
    }
1406
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1407

    
1408
  def _Error(self, ecode, item, msg, *args, **kwargs):
1409
    """Format an error message.
1410

1411
    Based on the opcode's error_codes parameter, either format a
1412
    parseable error code, or a simpler error string.
1413

1414
    This must be called only from Exec and functions called from Exec.
1415

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

    
1434
  def _ErrorIf(self, cond, *args, **kwargs):
1435
    """Log an error message if the passed condition is True.
1436

1437
    """
1438
    cond = bool(cond) or self.op.debug_simulate_errors
1439
    if cond:
1440
      self._Error(*args, **kwargs)
1441
    # do not mark the operation as failed for WARN cases only
1442
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1443
      self.bad = self.bad or cond
1444

    
1445
  def _VerifyNode(self, ninfo, nresult):
1446
    """Perform some basic validation on data returned from a node.
1447

1448
      - check the result data structure is well formed and has all the
1449
        mandatory fields
1450
      - check ganeti version
1451

1452
    @type ninfo: L{objects.Node}
1453
    @param ninfo: the node to check
1454
    @param nresult: the results from the node
1455
    @rtype: boolean
1456
    @return: whether overall this call was successful (and we can expect
1457
         reasonable values in the respose)
1458

1459
    """
1460
    node = ninfo.name
1461
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1462

    
1463
    # main result, nresult should be a non-empty dict
1464
    test = not nresult or not isinstance(nresult, dict)
1465
    _ErrorIf(test, self.ENODERPC, node,
1466
                  "unable to verify node: no data returned")
1467
    if test:
1468
      return False
1469

    
1470
    # compares ganeti version
1471
    local_version = constants.PROTOCOL_VERSION
1472
    remote_version = nresult.get("version", None)
1473
    test = not (remote_version and
1474
                isinstance(remote_version, (list, tuple)) and
1475
                len(remote_version) == 2)
1476
    _ErrorIf(test, self.ENODERPC, node,
1477
             "connection to node returned invalid data")
1478
    if test:
1479
      return False
1480

    
1481
    test = local_version != remote_version[0]
1482
    _ErrorIf(test, self.ENODEVERSION, node,
1483
             "incompatible protocol versions: master %s,"
1484
             " node %s", local_version, remote_version[0])
1485
    if test:
1486
      return False
1487

    
1488
    # node seems compatible, we can actually try to look into its results
1489

    
1490
    # full package version
1491
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1492
                  self.ENODEVERSION, node,
1493
                  "software version mismatch: master %s, node %s",
1494
                  constants.RELEASE_VERSION, remote_version[1],
1495
                  code=self.ETYPE_WARNING)
1496

    
1497
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1498
    if isinstance(hyp_result, dict):
1499
      for hv_name, hv_result in hyp_result.iteritems():
1500
        test = hv_result is not None
1501
        _ErrorIf(test, self.ENODEHV, node,
1502
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1503

    
1504

    
1505
    test = nresult.get(constants.NV_NODESETUP,
1506
                           ["Missing NODESETUP results"])
1507
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1508
             "; ".join(test))
1509

    
1510
    return True
1511

    
1512
  def _VerifyNodeTime(self, ninfo, nresult,
1513
                      nvinfo_starttime, nvinfo_endtime):
1514
    """Check the node time.
1515

1516
    @type ninfo: L{objects.Node}
1517
    @param ninfo: the node to check
1518
    @param nresult: the remote results for the node
1519
    @param nvinfo_starttime: the start time of the RPC call
1520
    @param nvinfo_endtime: the end time of the RPC call
1521

1522
    """
1523
    node = ninfo.name
1524
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1525

    
1526
    ntime = nresult.get(constants.NV_TIME, None)
1527
    try:
1528
      ntime_merged = utils.MergeTime(ntime)
1529
    except (ValueError, TypeError):
1530
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1531
      return
1532

    
1533
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1534
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1535
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1536
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1537
    else:
1538
      ntime_diff = None
1539

    
1540
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1541
             "Node time diverges by at least %s from master node time",
1542
             ntime_diff)
1543

    
1544
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1545
    """Check the node time.
1546

1547
    @type ninfo: L{objects.Node}
1548
    @param ninfo: the node to check
1549
    @param nresult: the remote results for the node
1550
    @param vg_name: the configured VG name
1551

1552
    """
1553
    if vg_name is None:
1554
      return
1555

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

    
1559
    # checks vg existence and size > 20G
1560
    vglist = nresult.get(constants.NV_VGLIST, None)
1561
    test = not vglist
1562
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1563
    if not test:
1564
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1565
                                            constants.MIN_VG_SIZE)
1566
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1567

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

    
1581
  def _VerifyNodeNetwork(self, ninfo, nresult):
1582
    """Check the node time.
1583

1584
    @type ninfo: L{objects.Node}
1585
    @param ninfo: the node to check
1586
    @param nresult: the remote results for the node
1587

1588
    """
1589
    node = ninfo.name
1590
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1591

    
1592
    test = constants.NV_NODELIST not in nresult
1593
    _ErrorIf(test, self.ENODESSH, node,
1594
             "node hasn't returned node ssh connectivity data")
1595
    if not test:
1596
      if nresult[constants.NV_NODELIST]:
1597
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1598
          _ErrorIf(True, self.ENODESSH, node,
1599
                   "ssh communication with node '%s': %s", a_node, a_msg)
1600

    
1601
    test = constants.NV_NODENETTEST not in nresult
1602
    _ErrorIf(test, self.ENODENET, node,
1603
             "node hasn't returned node tcp connectivity data")
1604
    if not test:
1605
      if nresult[constants.NV_NODENETTEST]:
1606
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1607
        for anode in nlist:
1608
          _ErrorIf(True, self.ENODENET, node,
1609
                   "tcp communication with node '%s': %s",
1610
                   anode, nresult[constants.NV_NODENETTEST][anode])
1611

    
1612
    test = constants.NV_MASTERIP not in nresult
1613
    _ErrorIf(test, self.ENODENET, node,
1614
             "node hasn't returned node master IP reachability data")
1615
    if not test:
1616
      if not nresult[constants.NV_MASTERIP]:
1617
        if node == self.master_node:
1618
          msg = "the master node cannot reach the master IP (not configured?)"
1619
        else:
1620
          msg = "cannot reach the master IP"
1621
        _ErrorIf(True, self.ENODENET, node, msg)
1622

    
1623

    
1624
  def _VerifyInstance(self, instance, instanceconfig, node_image):
1625
    """Verify an instance.
1626

1627
    This function checks to see if the required block devices are
1628
    available on the instance's node.
1629

1630
    """
1631
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1632
    node_current = instanceconfig.primary_node
1633

    
1634
    node_vol_should = {}
1635
    instanceconfig.MapLVsByNode(node_vol_should)
1636

    
1637
    for node in node_vol_should:
1638
      n_img = node_image[node]
1639
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1640
        # ignore missing volumes on offline or broken nodes
1641
        continue
1642
      for volume in node_vol_should[node]:
1643
        test = volume not in n_img.volumes
1644
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1645
                 "volume %s missing on node %s", volume, node)
1646

    
1647
    if instanceconfig.admin_up:
1648
      pri_img = node_image[node_current]
1649
      test = instance not in pri_img.instances and not pri_img.offline
1650
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1651
               "instance not running on its primary node %s",
1652
               node_current)
1653

    
1654
    for node, n_img in node_image.items():
1655
      if (not node == node_current):
1656
        test = instance in n_img.instances
1657
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1658
                 "instance should not run on node %s", node)
1659

    
1660
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1661
    """Verify if there are any unknown volumes in the cluster.
1662

1663
    The .os, .swap and backup volumes are ignored. All other volumes are
1664
    reported as unknown.
1665

1666
    @type reserved: L{ganeti.utils.FieldSet}
1667
    @param reserved: a FieldSet of reserved volume names
1668

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

    
1681
  def _VerifyOrphanInstances(self, instancelist, node_image):
1682
    """Verify the list of running instances.
1683

1684
    This checks what instances are running but unknown to the cluster.
1685

1686
    """
1687
    for node, n_img in node_image.items():
1688
      for o_inst in n_img.instances:
1689
        test = o_inst not in instancelist
1690
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1691
                      "instance %s on node %s should not exist", o_inst, node)
1692

    
1693
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1694
    """Verify N+1 Memory Resilience.
1695

1696
    Check that if one single node dies we can still start all the
1697
    instances it was primary for.
1698

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

    
1720
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1721
                       master_files):
1722
    """Verifies and computes the node required file checksums.
1723

1724
    @type ninfo: L{objects.Node}
1725
    @param ninfo: the node to check
1726
    @param nresult: the remote results for the node
1727
    @param file_list: required list of files
1728
    @param local_cksum: dictionary of local files and their checksums
1729
    @param master_files: list of files that only masters should have
1730

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

    
1735
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1736
    test = not isinstance(remote_cksum, dict)
1737
    _ErrorIf(test, self.ENODEFILECHECK, node,
1738
             "node hasn't returned file checksum data")
1739
    if test:
1740
      return
1741

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

    
1764
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1765
                      drbd_map):
1766
    """Verifies and the node DRBD status.
1767

1768
    @type ninfo: L{objects.Node}
1769
    @param ninfo: the node to check
1770
    @param nresult: the remote results for the node
1771
    @param instanceinfo: the dict of instances
1772
    @param drbd_helper: the configured DRBD usermode helper
1773
    @param drbd_map: the DRBD map as returned by
1774
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1775

1776
    """
1777
    node = ninfo.name
1778
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1779

    
1780
    if drbd_helper:
1781
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1782
      test = (helper_result == None)
1783
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1784
               "no drbd usermode helper returned")
1785
      if helper_result:
1786
        status, payload = helper_result
1787
        test = not status
1788
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1789
                 "drbd usermode helper check unsuccessful: %s", payload)
1790
        test = status and (payload != drbd_helper)
1791
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1792
                 "wrong drbd usermode helper: %s", payload)
1793

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

    
1809
    # and now check them
1810
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1811
    test = not isinstance(used_minors, (tuple, list))
1812
    _ErrorIf(test, self.ENODEDRBD, node,
1813
             "cannot parse drbd status file: %s", str(used_minors))
1814
    if test:
1815
      # we cannot check drbd status
1816
      return
1817

    
1818
    for minor, (iname, must_exist) in node_drbd.items():
1819
      test = minor not in used_minors and must_exist
1820
      _ErrorIf(test, self.ENODEDRBD, node,
1821
               "drbd minor %d of instance %s is not active", minor, iname)
1822
    for minor in used_minors:
1823
      test = minor not in node_drbd
1824
      _ErrorIf(test, self.ENODEDRBD, node,
1825
               "unallocated drbd minor %d is in use", minor)
1826

    
1827
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1828
    """Builds the node OS structures.
1829

1830
    @type ninfo: L{objects.Node}
1831
    @param ninfo: the node to check
1832
    @param nresult: the remote results for the node
1833
    @param nimg: the node image object
1834

1835
    """
1836
    node = ninfo.name
1837
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1838

    
1839
    remote_os = nresult.get(constants.NV_OSLIST, None)
1840
    test = (not isinstance(remote_os, list) or
1841
            not compat.all(isinstance(v, list) and len(v) == 7
1842
                           for v in remote_os))
1843

    
1844
    _ErrorIf(test, self.ENODEOS, node,
1845
             "node hasn't returned valid OS data")
1846

    
1847
    nimg.os_fail = test
1848

    
1849
    if test:
1850
      return
1851

    
1852
    os_dict = {}
1853

    
1854
    for (name, os_path, status, diagnose,
1855
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1856

    
1857
      if name not in os_dict:
1858
        os_dict[name] = []
1859

    
1860
      # parameters is a list of lists instead of list of tuples due to
1861
      # JSON lacking a real tuple type, fix it:
1862
      parameters = [tuple(v) for v in parameters]
1863
      os_dict[name].append((os_path, status, diagnose,
1864
                            set(variants), set(parameters), set(api_ver)))
1865

    
1866
    nimg.oslist = os_dict
1867

    
1868
  def _VerifyNodeOS(self, ninfo, nimg, base):
1869
    """Verifies the node OS list.
1870

1871
    @type ninfo: L{objects.Node}
1872
    @param ninfo: the node to check
1873
    @param nimg: the node image object
1874
    @param base: the 'template' node we match against (e.g. from the master)
1875

1876
    """
1877
    node = ninfo.name
1878
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1879

    
1880
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1881

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

    
1915
    # check any missing OSes
1916
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
1917
    _ErrorIf(missing, self.ENODEOS, node,
1918
             "OSes present on reference node %s but missing on this node: %s",
1919
             base.name, utils.CommaJoin(missing))
1920

    
1921
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1922
    """Verifies and updates the node volume data.
1923

1924
    This function will update a L{NodeImage}'s internal structures
1925
    with data from the remote call.
1926

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

1933
    """
1934
    node = ninfo.name
1935
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1936

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

    
1950
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1951
    """Verifies and updates the node instance list.
1952

1953
    If the listing was successful, then updates this node's instance
1954
    list. Otherwise, it marks the RPC call as failed for the instance
1955
    list key.
1956

1957
    @type ninfo: L{objects.Node}
1958
    @param ninfo: the node to check
1959
    @param nresult: the remote results for the node
1960
    @param nimg: the node image object
1961

1962
    """
1963
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1964
    test = not isinstance(idata, list)
1965
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1966
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1967
    if test:
1968
      nimg.hyp_fail = True
1969
    else:
1970
      nimg.instances = idata
1971

    
1972
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1973
    """Verifies and computes a node information map
1974

1975
    @type ninfo: L{objects.Node}
1976
    @param ninfo: the node to check
1977
    @param nresult: the remote results for the node
1978
    @param nimg: the node image object
1979
    @param vg_name: the configured VG name
1980

1981
    """
1982
    node = ninfo.name
1983
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1984

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

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

    
2010
  def BuildHooksEnv(self):
2011
    """Build hooks env.
2012

2013
    Cluster-Verify hooks just ran in the post phase and their failure makes
2014
    the output be logged in the verify output and the verification to fail.
2015

2016
    """
2017
    all_nodes = self.cfg.GetNodeList()
2018
    env = {
2019
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2020
      }
2021
    for node in self.cfg.GetAllNodesInfo().values():
2022
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
2023

    
2024
    return env, [], all_nodes
2025

    
2026
  def Exec(self, feedback_fn):
2027
    """Verify integrity of cluster, performing various test on nodes.
2028

2029
    """
2030
    self.bad = False
2031
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2032
    verbose = self.op.verbose
2033
    self._feedback_fn = feedback_fn
2034
    feedback_fn("* Verifying global settings")
2035
    for msg in self.cfg.VerifyConfig():
2036
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
2037

    
2038
    # Check the cluster certificates
2039
    for cert_filename in constants.ALL_CERT_FILES:
2040
      (errcode, msg) = _VerifyCertificate(cert_filename)
2041
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
2042

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

    
2058
    # FIXME: verify OS list
2059
    # do local checksums
2060
    master_files = [constants.CLUSTER_CONF_FILE]
2061
    master_node = self.master_node = self.cfg.GetMasterNode()
2062
    master_ip = self.cfg.GetMasterIP()
2063

    
2064
    file_names = ssconf.SimpleStore().GetFileList()
2065
    file_names.extend(constants.ALL_CERT_FILES)
2066
    file_names.extend(master_files)
2067
    if cluster.modify_etc_hosts:
2068
      file_names.append(constants.ETC_HOSTS)
2069

    
2070
    local_checksums = utils.FingerprintFiles(file_names)
2071

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

    
2090
    if vg_name is not None:
2091
      node_verify_param[constants.NV_VGLIST] = None
2092
      node_verify_param[constants.NV_LVLIST] = vg_name
2093
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2094
      node_verify_param[constants.NV_DRBDLIST] = None
2095

    
2096
    if drbd_helper:
2097
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2098

    
2099
    # Build our expected cluster state
2100
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2101
                                                 name=node.name))
2102
                      for node in nodeinfo)
2103

    
2104
    for instance in instancelist:
2105
      inst_config = instanceinfo[instance]
2106

    
2107
      for nname in inst_config.all_nodes:
2108
        if nname not in node_image:
2109
          # ghost node
2110
          gnode = self.NodeImage(name=nname)
2111
          gnode.ghost = True
2112
          node_image[nname] = gnode
2113

    
2114
      inst_config.MapLVsByNode(node_vol_should)
2115

    
2116
      pnode = inst_config.primary_node
2117
      node_image[pnode].pinst.append(instance)
2118

    
2119
      for snode in inst_config.secondary_nodes:
2120
        nimg = node_image[snode]
2121
        nimg.sinst.append(instance)
2122
        if pnode not in nimg.sbp:
2123
          nimg.sbp[pnode] = []
2124
        nimg.sbp[pnode].append(instance)
2125

    
2126
    # At this point, we have the in-memory data structures complete,
2127
    # except for the runtime information, which we'll gather next
2128

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

    
2138
    all_drbd_map = self.cfg.ComputeDRBDMap()
2139

    
2140
    feedback_fn("* Verifying node status")
2141

    
2142
    refos_img = None
2143

    
2144
    for node_i in nodeinfo:
2145
      node = node_i.name
2146
      nimg = node_image[node]
2147

    
2148
      if node_i.offline:
2149
        if verbose:
2150
          feedback_fn("* Skipping offline node %s" % (node,))
2151
        n_offline += 1
2152
        continue
2153

    
2154
      if node == master_node:
2155
        ntype = "master"
2156
      elif node_i.master_candidate:
2157
        ntype = "master candidate"
2158
      elif node_i.drained:
2159
        ntype = "drained"
2160
        n_drained += 1
2161
      else:
2162
        ntype = "regular"
2163
      if verbose:
2164
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2165

    
2166
      msg = all_nvinfo[node].fail_msg
2167
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2168
      if msg:
2169
        nimg.rpc_fail = True
2170
        continue
2171

    
2172
      nresult = all_nvinfo[node].payload
2173

    
2174
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2175
      self._VerifyNodeNetwork(node_i, nresult)
2176
      self._VerifyNodeLVM(node_i, nresult, vg_name)
2177
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2178
                            master_files)
2179
      self._VerifyNodeDrbd(node_i, nresult, instanceinfo, drbd_helper,
2180
                           all_drbd_map)
2181
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2182

    
2183
      self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2184
      self._UpdateNodeInstances(node_i, nresult, nimg)
2185
      self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2186
      self._UpdateNodeOS(node_i, nresult, nimg)
2187
      if not nimg.os_fail:
2188
        if refos_img is None:
2189
          refos_img = nimg
2190
        self._VerifyNodeOS(node_i, nimg, refos_img)
2191

    
2192
    feedback_fn("* Verifying instance status")
2193
    for instance in instancelist:
2194
      if verbose:
2195
        feedback_fn("* Verifying instance %s" % instance)
2196
      inst_config = instanceinfo[instance]
2197
      self._VerifyInstance(instance, inst_config, node_image)
2198
      inst_nodes_offline = []
2199

    
2200
      pnode = inst_config.primary_node
2201
      pnode_img = node_image[pnode]
2202
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2203
               self.ENODERPC, pnode, "instance %s, connection to"
2204
               " primary node failed", instance)
2205

    
2206
      if pnode_img.offline:
2207
        inst_nodes_offline.append(pnode)
2208

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

    
2221
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2222
        i_non_a_balanced.append(instance)
2223

    
2224
      for snode in inst_config.secondary_nodes:
2225
        s_img = node_image[snode]
2226
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2227
                 "instance %s, connection to secondary node failed", instance)
2228

    
2229
        if s_img.offline:
2230
          inst_nodes_offline.append(snode)
2231

    
2232
      # warn that the instance lives on offline nodes
2233
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2234
               "instance lives on offline node(s) %s",
2235
               utils.CommaJoin(inst_nodes_offline))
2236
      # ... or ghost nodes
2237
      for node in inst_config.all_nodes:
2238
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2239
                 "instance lives on ghost node %s", node)
2240

    
2241
    feedback_fn("* Verifying orphan volumes")
2242
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2243
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2244

    
2245
    feedback_fn("* Verifying orphan instances")
2246
    self._VerifyOrphanInstances(instancelist, node_image)
2247

    
2248
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2249
      feedback_fn("* Verifying N+1 Memory redundancy")
2250
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2251

    
2252
    feedback_fn("* Other Notes")
2253
    if i_non_redundant:
2254
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2255
                  % len(i_non_redundant))
2256

    
2257
    if i_non_a_balanced:
2258
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2259
                  % len(i_non_a_balanced))
2260

    
2261
    if n_offline:
2262
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2263

    
2264
    if n_drained:
2265
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2266

    
2267
    return not self.bad
2268

    
2269
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2270
    """Analyze the post-hooks' result
2271

2272
    This method analyses the hook result, handles it, and sends some
2273
    nicely-formatted feedback back to the user.
2274

2275
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2276
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2277
    @param hooks_results: the results of the multi-node hooks rpc call
2278
    @param feedback_fn: function used send feedback back to the caller
2279
    @param lu_result: previous Exec result
2280
    @return: the new Exec result, based on the previous result
2281
        and hook results
2282

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

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

    
2313
      return lu_result
2314

    
2315

    
2316
class LUVerifyDisks(NoHooksLU):
2317
  """Verifies the cluster disks status.
2318

2319
  """
2320
  REQ_BGL = False
2321

    
2322
  def ExpandNames(self):
2323
    self.needed_locks = {
2324
      locking.LEVEL_NODE: locking.ALL_SET,
2325
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2326
    }
2327
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2328

    
2329
  def Exec(self, feedback_fn):
2330
    """Verify integrity of cluster disks.
2331

2332
    @rtype: tuple of three items
2333
    @return: a tuple of (dict of node-to-node_error, list of instances
2334
        which need activate-disks, dict of instance: (node, volume) for
2335
        missing volumes
2336

2337
    """
2338
    result = res_nodes, res_instances, res_missing = {}, [], {}
2339

    
2340
    vg_name = self.cfg.GetVGName()
2341
    nodes = utils.NiceSort(self.cfg.GetNodeList())
2342
    instances = [self.cfg.GetInstanceInfo(name)
2343
                 for name in self.cfg.GetInstanceList()]
2344

    
2345
    nv_dict = {}
2346
    for inst in instances:
2347
      inst_lvs = {}
2348
      if (not inst.admin_up or
2349
          inst.disk_template not in constants.DTS_NET_MIRROR):
2350
        continue
2351
      inst.MapLVsByNode(inst_lvs)
2352
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2353
      for node, vol_list in inst_lvs.iteritems():
2354
        for vol in vol_list:
2355
          nv_dict[(node, vol)] = inst
2356

    
2357
    if not nv_dict:
2358
      return result
2359

    
2360
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
2361

    
2362
    for node in nodes:
2363
      # node_volume
2364
      node_res = node_lvs[node]
2365
      if node_res.offline:
2366
        continue
2367
      msg = node_res.fail_msg
2368
      if msg:
2369
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2370
        res_nodes[node] = msg
2371
        continue
2372

    
2373
      lvs = node_res.payload
2374
      for lv_name, (_, _, lv_online) in lvs.items():
2375
        inst = nv_dict.pop((node, lv_name), None)
2376
        if (not lv_online and inst is not None
2377
            and inst.name not in res_instances):
2378
          res_instances.append(inst.name)
2379

    
2380
    # any leftover items in nv_dict are missing LVs, let's arrange the
2381
    # data better
2382
    for key, inst in nv_dict.iteritems():
2383
      if inst.name not in res_missing:
2384
        res_missing[inst.name] = []
2385
      res_missing[inst.name].append(key)
2386

    
2387
    return result
2388

    
2389

    
2390
class LURepairDiskSizes(NoHooksLU):
2391
  """Verifies the cluster disks sizes.
2392

2393
  """
2394
  _OP_PARAMS = [("instances", _EmptyList, _TListOf(_TNonEmptyString))]
2395
  REQ_BGL = False
2396

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

    
2416
  def DeclareLocks(self, level):
2417
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2418
      self._LockInstancesNodes(primary_only=True)
2419

    
2420
  def CheckPrereq(self):
2421
    """Check prerequisites.
2422

2423
    This only checks the optional instance list against the existing names.
2424

2425
    """
2426
    if self.wanted_names is None:
2427
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2428

    
2429
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2430
                             in self.wanted_names]
2431

    
2432
  def _EnsureChildSizes(self, disk):
2433
    """Ensure children of the disk have the needed disk size.
2434

2435
    This is valid mainly for DRBD8 and fixes an issue where the
2436
    children have smaller disk size.
2437

2438
    @param disk: an L{ganeti.objects.Disk} object
2439

2440
    """
2441
    if disk.dev_type == constants.LD_DRBD8:
2442
      assert disk.children, "Empty children for DRBD8?"
2443
      fchild = disk.children[0]
2444
      mismatch = fchild.size < disk.size
2445
      if mismatch:
2446
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2447
                     fchild.size, disk.size)
2448
        fchild.size = disk.size
2449

    
2450
      # and we recurse on this child only, not on the metadev
2451
      return self._EnsureChildSizes(fchild) or mismatch
2452
    else:
2453
      return False
2454

    
2455
  def Exec(self, feedback_fn):
2456
    """Verify the size of cluster disks.
2457

2458
    """
2459
    # TODO: check child disks too
2460
    # TODO: check differences in size between primary/secondary nodes
2461
    per_node_disks = {}
2462
    for instance in self.wanted_instances:
2463
      pnode = instance.primary_node
2464
      if pnode not in per_node_disks:
2465
        per_node_disks[pnode] = []
2466
      for idx, disk in enumerate(instance.disks):
2467
        per_node_disks[pnode].append((instance, idx, disk))
2468

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

    
2505

    
2506
class LURenameCluster(LogicalUnit):
2507
  """Rename the cluster.
2508

2509
  """
2510
  HPATH = "cluster-rename"
2511
  HTYPE = constants.HTYPE_CLUSTER
2512
  _OP_PARAMS = [("name", _NoDefault, _TNonEmptyString)]
2513

    
2514
  def BuildHooksEnv(self):
2515
    """Build hooks env.
2516

2517
    """
2518
    env = {
2519
      "OP_TARGET": self.cfg.GetClusterName(),
2520
      "NEW_NAME": self.op.name,
2521
      }
2522
    mn = self.cfg.GetMasterNode()
2523
    all_nodes = self.cfg.GetNodeList()
2524
    return env, [mn], all_nodes
2525

    
2526
  def CheckPrereq(self):
2527
    """Verify that the passed name is a valid one.
2528

2529
    """
2530
    hostname = netutils.GetHostname(name=self.op.name,
2531
                                    family=self.cfg.GetPrimaryIPFamily())
2532

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

    
2547
    self.op.name = new_name
2548

    
2549
  def Exec(self, feedback_fn):
2550
    """Rename the cluster.
2551

2552
    """
2553
    clustername = self.op.name
2554
    ip = self.ip
2555

    
2556
    # shutdown the master IP
2557
    master = self.cfg.GetMasterNode()
2558
    result = self.rpc.call_node_stop_master(master, False)
2559
    result.Raise("Could not disable the master role")
2560

    
2561
    try:
2562
      cluster = self.cfg.GetClusterInfo()
2563
      cluster.cluster_name = clustername
2564
      cluster.master_ip = ip
2565
      self.cfg.Update(cluster, feedback_fn)
2566

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

    
2583
    finally:
2584
      result = self.rpc.call_node_start_master(master, False, False)
2585
      msg = result.fail_msg
2586
      if msg:
2587
        self.LogWarning("Could not re-enable the master role on"
2588
                        " the master, please restart manually: %s", msg)
2589

    
2590
    return clustername
2591

    
2592

    
2593
class LUSetClusterParams(LogicalUnit):
2594
  """Change the parameters of the cluster.
2595

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

    
2619
  def CheckArguments(self):
2620
    """Check parameters
2621

2622
    """
2623
    if self.op.uid_pool:
2624
      uidpool.CheckUidPool(self.op.uid_pool)
2625

    
2626
    if self.op.add_uids:
2627
      uidpool.CheckUidPool(self.op.add_uids)
2628

    
2629
    if self.op.remove_uids:
2630
      uidpool.CheckUidPool(self.op.remove_uids)
2631

    
2632
  def ExpandNames(self):
2633
    # FIXME: in the future maybe other cluster params won't require checking on
2634
    # all nodes to be modified.
2635
    self.needed_locks = {
2636
      locking.LEVEL_NODE: locking.ALL_SET,
2637
    }
2638
    self.share_locks[locking.LEVEL_NODE] = 1
2639

    
2640
  def BuildHooksEnv(self):
2641
    """Build hooks env.
2642

2643
    """
2644
    env = {
2645
      "OP_TARGET": self.cfg.GetClusterName(),
2646
      "NEW_VG_NAME": self.op.vg_name,
2647
      }
2648
    mn = self.cfg.GetMasterNode()
2649
    return env, [mn], [mn]
2650

    
2651
  def CheckPrereq(self):
2652
    """Check prerequisites.
2653

2654
    This checks whether the given params don't conflict and
2655
    if the given volume group is valid.
2656

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

    
2663
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
2664
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
2665
        raise errors.OpPrereqError("Cannot disable drbd helper while"
2666
                                   " drbd-based instances exist",
2667
                                   errors.ECODE_INVAL)
2668

    
2669
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2670

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

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

    
2706
    self.cluster = cluster = self.cfg.GetClusterInfo()
2707
    # validate params changes
2708
    if self.op.beparams:
2709
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2710
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2711

    
2712
    if self.op.nicparams:
2713
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2714
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2715
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2716
      nic_errors = []
2717

    
2718
      # check all instances for consistency
2719
      for instance in self.cfg.GetAllInstancesInfo().values():
2720
        for nic_idx, nic in enumerate(instance.nics):
2721
          params_copy = copy.deepcopy(nic.nicparams)
2722
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2723

    
2724
          # check parameter syntax
2725
          try:
2726
            objects.NIC.CheckParameterSyntax(params_filled)
2727
          except errors.ConfigurationError, err:
2728
            nic_errors.append("Instance %s, nic/%d: %s" %
2729
                              (instance.name, nic_idx, err))
2730

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

    
2740
    # hypervisor list/parameters
2741
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2742
    if self.op.hvparams:
2743
      for hv_name, hv_dict in self.op.hvparams.items():
2744
        if hv_name not in self.new_hvparams:
2745
          self.new_hvparams[hv_name] = hv_dict
2746
        else:
2747
          self.new_hvparams[hv_name].update(hv_dict)
2748

    
2749
    # os hypervisor parameters
2750
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2751
    if self.op.os_hvp:
2752
      for os_name, hvs in self.op.os_hvp.items():
2753
        if os_name not in self.new_os_hvp:
2754
          self.new_os_hvp[os_name] = hvs
2755
        else:
2756
          for hv_name, hv_dict in hvs.items():
2757
            if hv_name not in self.new_os_hvp[os_name]:
2758
              self.new_os_hvp[os_name][hv_name] = hv_dict
2759
            else:
2760
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2761

    
2762
    # os parameters
2763
    self.new_osp = objects.FillDict(cluster.osparams, {})
2764
    if self.op.osparams:
2765
      for os_name, osp in self.op.osparams.items():
2766
        if os_name not in self.new_osp:
2767
          self.new_osp[os_name] = {}
2768

    
2769
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2770
                                                  use_none=True)
2771

    
2772
        if not self.new_osp[os_name]:
2773
          # we removed all parameters
2774
          del self.new_osp[os_name]
2775
        else:
2776
          # check the parameter validity (remote check)
2777
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
2778
                         os_name, self.new_osp[os_name])
2779

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

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

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

    
2821
    if self.op.default_iallocator:
2822
      alloc_script = utils.FindFile(self.op.default_iallocator,
2823
                                    constants.IALLOCATOR_SEARCH_PATH,
2824
                                    os.path.isfile)
2825
      if alloc_script is None:
2826
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
2827
                                   " specified" % self.op.default_iallocator,
2828
                                   errors.ECODE_INVAL)
2829

    
2830
  def Exec(self, feedback_fn):
2831
    """Change the parameters of the cluster.
2832

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

    
2866
    if self.op.candidate_pool_size is not None:
2867
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2868
      # we need to update the pool size here, otherwise the save will fail
2869
      _AdjustCandidatePool(self, [])
2870

    
2871
    if self.op.maintain_node_health is not None:
2872
      self.cluster.maintain_node_health = self.op.maintain_node_health
2873

    
2874
    if self.op.add_uids is not None:
2875
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2876

    
2877
    if self.op.remove_uids is not None:
2878
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2879

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

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

    
2886
    if self.op.reserved_lvs is not None:
2887
      self.cluster.reserved_lvs = self.op.reserved_lvs
2888

    
2889
    self.cfg.Update(self.cluster, feedback_fn)
2890

    
2891

    
2892
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
2893
  """Distribute additional files which are part of the cluster configuration.
2894

2895
  ConfigWriter takes care of distributing the config and ssconf files, but
2896
  there are more files which should be distributed to all nodes. This function
2897
  makes sure those are copied.
2898

2899
  @param lu: calling logical unit
2900
  @param additional_nodes: list of nodes not in the config to distribute to
2901

2902
  """
2903
  # 1. Gather target nodes
2904
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2905
  dist_nodes = lu.cfg.GetOnlineNodeList()
2906
  if additional_nodes is not None:
2907
    dist_nodes.extend(additional_nodes)
2908
  if myself.name in dist_nodes:
2909
    dist_nodes.remove(myself.name)
2910

    
2911
  # 2. Gather files to distribute
2912
  dist_files = set([constants.ETC_HOSTS,
2913
                    constants.SSH_KNOWN_HOSTS_FILE,
2914
                    constants.RAPI_CERT_FILE,
2915
                    constants.RAPI_USERS_FILE,
2916
                    constants.CONFD_HMAC_KEY,
2917
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
2918
                   ])
2919

    
2920
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2921
  for hv_name in enabled_hypervisors:
2922
    hv_class = hypervisor.GetHypervisor(hv_name)
2923
    dist_files.update(hv_class.GetAncillaryFiles())
2924

    
2925
  # 3. Perform the files upload
2926
  for fname in dist_files:
2927
    if os.path.exists(fname):
2928
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2929
      for to_node, to_result in result.items():
2930
        msg = to_result.fail_msg
2931
        if msg:
2932
          msg = ("Copy of file %s to node %s failed: %s" %
2933
                 (fname, to_node, msg))
2934
          lu.proc.LogWarning(msg)
2935

    
2936

    
2937
class LURedistributeConfig(NoHooksLU):
2938
  """Force the redistribution of cluster configuration.
2939

2940
  This is a very simple LU.
2941

2942
  """
2943
  REQ_BGL = False
2944

    
2945
  def ExpandNames(self):
2946
    self.needed_locks = {
2947
      locking.LEVEL_NODE: locking.ALL_SET,
2948
    }
2949
    self.share_locks[locking.LEVEL_NODE] = 1
2950

    
2951
  def Exec(self, feedback_fn):
2952
    """Redistribute the configuration.
2953

2954
    """
2955
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2956
    _RedistributeAncillaryFiles(self)
2957

    
2958

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

2962
  """
2963
  if not instance.disks or disks is not None and not disks:
2964
    return True
2965

    
2966
  disks = _ExpandCheckDisks(instance, disks)
2967

    
2968
  if not oneshot:
2969
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2970

    
2971
  node = instance.primary_node
2972

    
2973
  for dev in disks:
2974
    lu.cfg.SetDiskID(dev, node)
2975

    
2976
  # TODO: Convert to utils.Retry
2977

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

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

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

    
3024
    if done or oneshot:
3025
      break
3026

    
3027
    time.sleep(min(60, max_time))
3028

    
3029
  if done:
3030
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3031
  return not cumul_degraded
3032

    
3033

    
3034
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3035
  """Check that mirrors are not degraded.
3036

3037
  The ldisk parameter, if True, will change the test from the
3038
  is_degraded attribute (which represents overall non-ok status for
3039
  the device(s)) to the ldisk (representing the local storage status).
3040

3041
  """
3042
  lu.cfg.SetDiskID(dev, node)
3043

    
3044
  result = True
3045

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

    
3061
  if dev.children:
3062
    for child in dev.children:
3063
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3064

    
3065
  return result
3066

    
3067

    
3068
class LUDiagnoseOS(NoHooksLU):
3069
  """Logical unit for OS diagnose/query.
3070

3071
  """
3072
  _OP_PARAMS = [
3073
    _POutputFields,
3074
    ("names", _EmptyList, _TListOf(_TNonEmptyString)),
3075
    ]
3076
  REQ_BGL = False
3077
  _FIELDS_STATIC = utils.FieldSet()
3078
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status", "variants",
3079
                                   "parameters", "api_versions")
3080

    
3081
  def CheckArguments(self):
3082
    if self.op.names:
3083
      raise errors.OpPrereqError("Selective OS query not supported",
3084
                                 errors.ECODE_INVAL)
3085

    
3086
    _CheckOutputFields(static=self._FIELDS_STATIC,
3087
                       dynamic=self._FIELDS_DYNAMIC,
3088
                       selected=self.op.output_fields)
3089

    
3090
  def ExpandNames(self):
3091
    # Lock all nodes, in shared mode
3092
    # Temporary removal of locks, should be reverted later
3093
    # TODO: reintroduce locks when they are lighter-weight
3094
    self.needed_locks = {}
3095
    #self.share_locks[locking.LEVEL_NODE] = 1
3096
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3097

    
3098
  @staticmethod
3099
  def _DiagnoseByOS(rlist):
3100
    """Remaps a per-node return list into an a per-os per-node dictionary
3101

3102
    @param rlist: a map with node names as keys and OS objects as values
3103

3104
    @rtype: dict
3105
    @return: a dictionary with osnames as keys and as value another
3106
        map, with nodes as keys and tuples of (path, status, diagnose,
3107
        variants, parameters, api_versions) as values, eg::
3108

3109
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3110
                                     (/srv/..., False, "invalid api")],
3111
                           "node2": [(/srv/..., True, "", [], [])]}
3112
          }
3113

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

    
3138
  def Exec(self, feedback_fn):
3139
    """Compute the list of OSes.
3140

3141
    """
3142
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
3143
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3144
    pol = self._DiagnoseByOS(node_data)
3145
    output = []
3146

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

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

    
3187
    return output
3188

    
3189

    
3190
class LURemoveNode(LogicalUnit):
3191
  """Logical unit for removing a node.
3192

3193
  """
3194
  HPATH = "node-remove"
3195
  HTYPE = constants.HTYPE_NODE
3196
  _OP_PARAMS = [
3197
    _PNodeName,
3198
    ]
3199

    
3200
  def BuildHooksEnv(self):
3201
    """Build hooks env.
3202

3203
    This doesn't run on the target node in the pre phase as a failed
3204
    node would then be impossible to remove.
3205

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

    
3219
  def CheckPrereq(self):
3220
    """Check prerequisites.
3221

3222
    This checks:
3223
     - the node exists in the configuration
3224
     - it does not have primary or secondary instances
3225
     - it's not the master
3226

3227
    Any errors are signaled by raising errors.OpPrereqError.
3228

3229
    """
3230
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3231
    node = self.cfg.GetNodeInfo(self.op.node_name)
3232
    assert node is not None
3233

    
3234
    instance_list = self.cfg.GetInstanceList()
3235

    
3236
    masternode = self.cfg.GetMasterNode()
3237
    if node.name == masternode:
3238
      raise errors.OpPrereqError("Node is the master node,"
3239
                                 " you need to failover first.",
3240
                                 errors.ECODE_INVAL)
3241

    
3242
    for instance_name in instance_list:
3243
      instance = self.cfg.GetInstanceInfo(instance_name)
3244
      if node.name in instance.all_nodes:
3245
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3246
                                   " please remove first." % instance_name,
3247
                                   errors.ECODE_INVAL)
3248
    self.op.node_name = node.name
3249
    self.node = node
3250

    
3251
  def Exec(self, feedback_fn):
3252
    """Removes the node from the cluster.
3253

3254
    """
3255
    node = self.node
3256
    logging.info("Stopping the node daemon and removing configs from node %s",
3257
                 node.name)
3258

    
3259
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3260

    
3261
    # Promote nodes to master candidate as needed
3262
    _AdjustCandidatePool(self, exceptions=[node.name])
3263
    self.context.RemoveNode(node.name)
3264

    
3265
    # Run post hooks on the node before it's removed
3266
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3267
    try:
3268
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3269
    except:
3270
      # pylint: disable-msg=W0702
3271
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3272

    
3273
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3274
    msg = result.fail_msg
3275
    if msg:
3276
      self.LogWarning("Errors encountered on the remote node while leaving"
3277
                      " the cluster: %s", msg)
3278

    
3279
    # Remove node from our /etc/hosts
3280
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3281
      # FIXME: this should be done via an rpc call to node daemon
3282
      utils.RemoveHostFromEtcHosts(node.name)
3283
      _RedistributeAncillaryFiles(self)
3284

    
3285

    
3286
class LUQueryNodes(NoHooksLU):
3287
  """Logical unit for querying nodes.
3288

3289
  """
3290
  # pylint: disable-msg=W0142
3291
  _OP_PARAMS = [
3292
    _POutputFields,
3293
    ("names", _EmptyList, _TListOf(_TNonEmptyString)),
3294
    ("use_locking", False, _TBool),
3295
    ]
3296
  REQ_BGL = False
3297

    
3298
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
3299
                    "master_candidate", "offline", "drained"]
3300

    
3301
  _FIELDS_DYNAMIC = utils.FieldSet(
3302
    "dtotal", "dfree",
3303
    "mtotal", "mnode", "mfree",
3304
    "bootid",
3305
    "ctotal", "cnodes", "csockets",
3306
    )
3307

    
3308
  _FIELDS_STATIC = utils.FieldSet(*[
3309
    "pinst_cnt", "sinst_cnt",
3310
    "pinst_list", "sinst_list",
3311
    "pip", "sip", "tags",
3312
    "master",
3313
    "role"] + _SIMPLE_FIELDS
3314
    )
3315

    
3316
  def CheckArguments(self):
3317
    _CheckOutputFields(static=self._FIELDS_STATIC,
3318
                       dynamic=self._FIELDS_DYNAMIC,
3319
                       selected=self.op.output_fields)
3320

    
3321
  def ExpandNames(self):
3322
    self.needed_locks = {}
3323
    self.share_locks[locking.LEVEL_NODE] = 1
3324

    
3325
    if self.op.names:
3326
      self.wanted = _GetWantedNodes(self, self.op.names)
3327
    else:
3328
      self.wanted = locking.ALL_SET
3329

    
3330
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3331
    self.do_locking = self.do_node_query and self.op.use_locking
3332
    if self.do_locking:
3333
      # if we don't request only static fields, we need to lock the nodes
3334
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
3335

    
3336
  def Exec(self, feedback_fn):
3337
    """Computes the list of nodes and their attributes.
3338

3339
    """
3340
    all_info = self.cfg.GetAllNodesInfo()
3341
    if self.do_locking:
3342
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
3343
    elif self.wanted != locking.ALL_SET:
3344
      nodenames = self.wanted
3345
      missing = set(nodenames).difference(all_info.keys())
3346
      if missing:
3347
        raise errors.OpExecError(
3348
          "Some nodes were removed before retrieving their data: %s" % missing)
3349
    else:
3350
      nodenames = all_info.keys()
3351

    
3352
    nodenames = utils.NiceSort(nodenames)
3353
    nodelist = [all_info[name] for name in nodenames]
3354

    
3355
    # begin data gathering
3356

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

    
3382
    node_to_primary = dict([(name, set()) for name in nodenames])
3383
    node_to_secondary = dict([(name, set()) for name in nodenames])
3384

    
3385
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
3386
                             "sinst_cnt", "sinst_list"))
3387
    if inst_fields & frozenset(self.op.output_fields):
3388
      inst_data = self.cfg.GetAllInstancesInfo()
3389

    
3390
      for inst in inst_data.values():
3391
        if inst.primary_node in node_to_primary:
3392
          node_to_primary[inst.primary_node].add(inst.name)
3393
        for secnode in inst.secondary_nodes:
3394
          if secnode in node_to_secondary:
3395
            node_to_secondary[secnode].add(inst.name)
3396

    
3397
    master_node = self.cfg.GetMasterNode()
3398

    
3399
    # end data gathering
3400

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

    
3441
    return output
3442

    
3443

    
3444
class LUQueryNodeVolumes(NoHooksLU):
3445
  """Logical unit for getting volumes on node(s).
3446

3447
  """
3448
  _OP_PARAMS = [
3449
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
3450
    ("output_fields", _NoDefault, _TListOf(_TNonEmptyString)),
3451
    ]
3452
  REQ_BGL = False
3453
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3454
  _FIELDS_STATIC = utils.FieldSet("node")
3455

    
3456
  def CheckArguments(self):
3457
    _CheckOutputFields(static=self._FIELDS_STATIC,
3458
                       dynamic=self._FIELDS_DYNAMIC,
3459
                       selected=self.op.output_fields)
3460

    
3461
  def ExpandNames(self):
3462
    self.needed_locks = {}
3463
    self.share_locks[locking.LEVEL_NODE] = 1
3464
    if not self.op.nodes:
3465
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3466
    else:
3467
      self.needed_locks[locking.LEVEL_NODE] = \
3468
        _GetWantedNodes(self, self.op.nodes)
3469

    
3470
  def Exec(self, feedback_fn):
3471
    """Computes the list of nodes and their attributes.
3472

3473
    """
3474
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3475
    volumes = self.rpc.call_node_volumes(nodenames)
3476

    
3477
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3478
             in self.cfg.GetInstanceList()]
3479

    
3480
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3481

    
3482
    output = []
3483
    for node in nodenames:
3484
      nresult = volumes[node]
3485
      if nresult.offline:
3486
        continue
3487
      msg = nresult.fail_msg
3488
      if msg:
3489
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3490
        continue
3491

    
3492
      node_vols = nresult.payload[:]
3493
      node_vols.sort(key=lambda vol: vol['dev'])
3494

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

    
3521
        output.append(node_output)
3522

    
3523
    return output
3524

    
3525

    
3526
class LUQueryNodeStorage(NoHooksLU):
3527
  """Logical unit for getting information on storage units on node(s).
3528

3529
  """
3530
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3531
  _OP_PARAMS = [
3532
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
3533
    ("storage_type", _NoDefault, _CheckStorageType),
3534
    ("output_fields", _NoDefault, _TListOf(_TNonEmptyString)),
3535
    ("name", None, _TMaybeString),
3536
    ]
3537
  REQ_BGL = False
3538

    
3539
  def CheckArguments(self):
3540
    _CheckOutputFields(static=self._FIELDS_STATIC,
3541
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3542
                       selected=self.op.output_fields)
3543

    
3544
  def ExpandNames(self):
3545
    self.needed_locks = {}
3546
    self.share_locks[locking.LEVEL_NODE] = 1
3547

    
3548
    if self.op.nodes:
3549
      self.needed_locks[locking.LEVEL_NODE] = \
3550
        _GetWantedNodes(self, self.op.nodes)
3551
    else:
3552
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3553

    
3554
  def Exec(self, feedback_fn):
3555
    """Computes the list of nodes and their attributes.
3556

3557
    """
3558
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3559

    
3560
    # Always get name to sort by
3561
    if constants.SF_NAME in self.op.output_fields:
3562
      fields = self.op.output_fields[:]
3563
    else:
3564
      fields = [constants.SF_NAME] + self.op.output_fields
3565

    
3566
    # Never ask for node or type as it's only known to the LU
3567
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3568
      while extra in fields:
3569
        fields.remove(extra)
3570

    
3571
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3572
    name_idx = field_idx[constants.SF_NAME]
3573

    
3574
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3575
    data = self.rpc.call_storage_list(self.nodes,
3576
                                      self.op.storage_type, st_args,
3577
                                      self.op.name, fields)
3578

    
3579
    result = []
3580

    
3581
    for node in utils.NiceSort(self.nodes):
3582
      nresult = data[node]
3583
      if nresult.offline:
3584
        continue
3585

    
3586
      msg = nresult.fail_msg
3587
      if msg:
3588
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3589
        continue
3590

    
3591
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3592

    
3593
      for name in utils.NiceSort(rows.keys()):
3594
        row = rows[name]
3595

    
3596
        out = []
3597

    
3598
        for field in self.op.output_fields:
3599
          if field == constants.SF_NODE:
3600
            val = node
3601
          elif field == constants.SF_TYPE:
3602
            val = self.op.storage_type
3603
          elif field in field_idx:
3604
            val = row[field_idx[field]]
3605
          else:
3606
            raise errors.ParameterError(field)
3607

    
3608
          out.append(val)
3609

    
3610
        result.append(out)
3611

    
3612
    return result
3613

    
3614

    
3615
class LUModifyNodeStorage(NoHooksLU):
3616
  """Logical unit for modifying a storage volume on a node.
3617

3618
  """
3619
  _OP_PARAMS = [
3620
    _PNodeName,
3621
    ("storage_type", _NoDefault, _CheckStorageType),
3622
    ("name", _NoDefault, _TNonEmptyString),
3623
    ("changes", _NoDefault, _TDict),
3624
    ]
3625
  REQ_BGL = False
3626

    
3627
  def CheckArguments(self):
3628
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3629

    
3630
    storage_type = self.op.storage_type
3631

    
3632
    try:
3633
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3634
    except KeyError:
3635
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3636
                                 " modified" % storage_type,
3637
                                 errors.ECODE_INVAL)
3638

    
3639
    diff = set(self.op.changes.keys()) - modifiable
3640
    if diff:
3641
      raise errors.OpPrereqError("The following fields can not be modified for"
3642
                                 " storage units of type '%s': %r" %
3643
                                 (storage_type, list(diff)),
3644
                                 errors.ECODE_INVAL)
3645

    
3646
  def ExpandNames(self):
3647
    self.needed_locks = {
3648
      locking.LEVEL_NODE: self.op.node_name,
3649
      }
3650

    
3651
  def Exec(self, feedback_fn):
3652
    """Computes the list of nodes and their attributes.
3653

3654
    """
3655
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3656
    result = self.rpc.call_storage_modify(self.op.node_name,
3657
                                          self.op.storage_type, st_args,
3658
                                          self.op.name, self.op.changes)
3659
    result.Raise("Failed to modify storage unit '%s' on %s" %
3660
                 (self.op.name, self.op.node_name))
3661

    
3662

    
3663
class LUAddNode(LogicalUnit):
3664
  """Logical unit for adding node to the cluster.
3665

3666
  """
3667
  HPATH = "node-add"
3668
  HTYPE = constants.HTYPE_NODE
3669
  _OP_PARAMS = [
3670
    _PNodeName,
3671
    ("primary_ip", None, _NoType),
3672
    ("secondary_ip", None, _TMaybeString),
3673
    ("readd", False, _TBool),
3674
    ]
3675

    
3676
  def CheckArguments(self):
3677
    # validate/normalize the node name
3678
    self.hostname = netutils.GetHostname(name=self.op.node_name,
3679
                                         family=self.cfg.GetPrimaryIPFamily())
3680
    self.op.node_name = self.hostname.name
3681

    
3682
  def BuildHooksEnv(self):
3683
    """Build hooks env.
3684

3685
    This will run on all nodes before, and on all nodes + the new node after.
3686

3687
    """
3688
    env = {
3689
      "OP_TARGET": self.op.node_name,
3690
      "NODE_NAME": self.op.node_name,
3691
      "NODE_PIP": self.op.primary_ip,
3692
      "NODE_SIP": self.op.secondary_ip,
3693
      }
3694
    nodes_0 = self.cfg.GetNodeList()
3695
    nodes_1 = nodes_0 + [self.op.node_name, ]
3696
    return env, nodes_0, nodes_1
3697

    
3698
  def CheckPrereq(self):
3699
    """Check prerequisites.
3700

3701
    This checks:
3702
     - the new node is not already in the config
3703
     - it is resolvable
3704
     - its parameters (single/dual homed) matches the cluster
3705

3706
    Any errors are signaled by raising errors.OpPrereqError.
3707

3708
    """
3709
    cfg = self.cfg
3710
    hostname = self.hostname
3711
    node = hostname.name
3712
    primary_ip = self.op.primary_ip = hostname.ip
3713
    if self.op.secondary_ip is None:
3714
      self.op.secondary_ip = primary_ip
3715

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

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

    
3729
    self.changed_primary_ip = False
3730

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

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

    
3742
        continue
3743

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

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

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

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

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

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

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

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

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

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

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

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

    
3831
    # setup ssh on node
3832
    if self.cfg.GetClusterInfo().modify_ssh_setup:
3833
      logging.info("Copy ssh key to node %s", node)
3834
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
3835
      keyarray = []
3836
      keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
3837
                  constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
3838
                  priv_key, pub_key]
3839

    
3840
      for i in keyfiles:
3841
        keyarray.append(utils.ReadFile(i))
3842

    
3843
      result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
3844
                                      keyarray[2], keyarray[3], keyarray[4],
3845
                                      keyarray[5])
3846
      result.Raise("Cannot transfer ssh keys to the new node")
3847

    
3848
    # Add node to our /etc/hosts, and add key to known_hosts
3849
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3850
      # FIXME: this should be done via an rpc call to node daemon
3851
      utils.AddHostToEtcHosts(self.hostname)
3852

    
3853
    if new_node.secondary_ip != new_node.primary_ip:
3854
      result = self.rpc.call_node_has_ip_address(new_node.name,
3855
                                                 new_node.secondary_ip)
3856
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
3857
                   prereq=True, ecode=errors.ECODE_ENVIRON)
3858
      if not result.payload:
3859
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
3860
                                 " you gave (%s). Please fix and re-run this"
3861
                                 " command." % new_node.secondary_ip)
3862

    
3863
    node_verify_list = [self.cfg.GetMasterNode()]
3864
    node_verify_param = {
3865
      constants.NV_NODELIST: [node],
3866
      # TODO: do a node-net-test as well?
3867
    }
3868

    
3869
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3870
                                       self.cfg.GetClusterName())
3871
    for verifier in node_verify_list:
3872
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3873
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3874
      if nl_payload:
3875
        for failed in nl_payload:
3876
          feedback_fn("ssh/hostname verification failed"
3877
                      " (checking from %s): %s" %
3878
                      (verifier, nl_payload[failed]))
3879
        raise errors.OpExecError("ssh/hostname verification failed.")
3880

    
3881
    if self.op.readd:
3882
      _RedistributeAncillaryFiles(self)
3883
      self.context.ReaddNode(new_node)
3884
      # make sure we redistribute the config
3885
      self.cfg.Update(new_node, feedback_fn)
3886
      # and make sure the new node will not have old files around
3887
      if not new_node.master_candidate:
3888
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3889
        msg = result.fail_msg
3890
        if msg:
3891
          self.LogWarning("Node failed to demote itself from master"
3892
                          " candidate status: %s" % msg)
3893
    else:
3894
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
3895
      self.context.AddNode(new_node, self.proc.GetECId())
3896

    
3897

    
3898
class LUSetNodeParams(LogicalUnit):
3899
  """Modifies the parameters of a node.
3900

3901
  """
3902
  HPATH = "node-modify"
3903
  HTYPE = constants.HTYPE_NODE
3904
  _OP_PARAMS = [
3905
    _PNodeName,
3906
    ("master_candidate", None, _TMaybeBool),
3907
    ("offline", None, _TMaybeBool),
3908
    ("drained", None, _TMaybeBool),
3909
    ("auto_promote", False, _TBool),
3910
    _PForce,
3911
    ]
3912
  REQ_BGL = False
3913

    
3914
  def CheckArguments(self):
3915
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3916
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
3917
    if all_mods.count(None) == 3:
3918
      raise errors.OpPrereqError("Please pass at least one modification",
3919
                                 errors.ECODE_INVAL)
3920
    if all_mods.count(True) > 1:
3921
      raise errors.OpPrereqError("Can't set the node into more than one"
3922
                                 " state at the same time",
3923
                                 errors.ECODE_INVAL)
3924

    
3925
    # Boolean value that tells us whether we're offlining or draining the node
3926
    self.offline_or_drain = (self.op.offline == True or
3927
                             self.op.drained == True)
3928
    self.deoffline_or_drain = (self.op.offline == False or
3929
                               self.op.drained == False)
3930
    self.might_demote = (self.op.master_candidate == False or
3931
                         self.offline_or_drain)
3932

    
3933
    self.lock_all = self.op.auto_promote and self.might_demote
3934

    
3935

    
3936
  def ExpandNames(self):
3937
    if self.lock_all:
3938
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
3939
    else:
3940
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3941

    
3942
  def BuildHooksEnv(self):
3943
    """Build hooks env.
3944

3945
    This runs on the master node.
3946

3947
    """
3948
    env = {
3949
      "OP_TARGET": self.op.node_name,
3950
      "MASTER_CANDIDATE": str(self.op.master_candidate),
3951
      "OFFLINE": str(self.op.offline),
3952
      "DRAINED": str(self.op.drained),
3953
      }
3954
    nl = [self.cfg.GetMasterNode(),
3955
          self.op.node_name]
3956
    return env, nl, nl
3957

    
3958
  def CheckPrereq(self):
3959
    """Check prerequisites.
3960

3961
    This only checks the instance list against the existing names.
3962

3963
    """
3964
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3965

    
3966
    if (self.op.master_candidate is not None or
3967
        self.op.drained is not None or
3968
        self.op.offline is not None):
3969
      # we can't change the master's node flags
3970
      if self.op.node_name == self.cfg.GetMasterNode():
3971
        raise errors.OpPrereqError("The master role can be changed"
3972
                                   " only via master-failover",
3973
                                   errors.ECODE_INVAL)
3974

    
3975

    
3976
    if node.master_candidate and self.might_demote and not self.lock_all:
3977
      assert not self.op.auto_promote, "auto-promote set but lock_all not"
3978
      # check if after removing the current node, we're missing master
3979
      # candidates
3980
      (mc_remaining, mc_should, _) = \
3981
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
3982
      if mc_remaining < mc_should:
3983
        raise errors.OpPrereqError("Not enough master candidates, please"
3984
                                   " pass auto_promote to allow promotion",
3985
                                   errors.ECODE_INVAL)
3986

    
3987
    if (self.op.master_candidate == True and
3988
        ((node.offline and not self.op.offline == False) or
3989
         (node.drained and not self.op.drained == False))):
3990
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
3991
                                 " to master_candidate" % node.name,
3992
                                 errors.ECODE_INVAL)
3993

    
3994
    # If we're being deofflined/drained, we'll MC ourself if needed
3995
    if (self.deoffline_or_drain and not self.offline_or_drain and not
3996
        self.op.master_candidate == True and not node.master_candidate):
3997
      self.op.master_candidate = _DecideSelfPromotion(self)
3998
      if self.op.master_candidate:
3999
        self.LogInfo("Autopromoting node to master candidate")
4000

    
4001
    return
4002

    
4003
  def Exec(self, feedback_fn):
4004
    """Modifies a node.
4005

4006
    """
4007
    node = self.node
4008

    
4009
    result = []
4010
    changed_mc = False
4011

    
4012
    if self.op.offline is not None:
4013
      node.offline = self.op.offline
4014
      result.append(("offline", str(self.op.offline)))
4015
      if self.op.offline == True:
4016
        if node.master_candidate:
4017
          node.master_candidate = False
4018
          changed_mc = True
4019
          result.append(("master_candidate", "auto-demotion due to offline"))
4020
        if node.drained:
4021
          node.drained = False
4022
          result.append(("drained", "clear drained status due to offline"))
4023

    
4024
    if self.op.master_candidate is not None:
4025
      node.master_candidate = self.op.master_candidate
4026
      changed_mc = True
4027
      result.append(("master_candidate", str(self.op.master_candidate)))
4028
      if self.op.master_candidate == False:
4029
        rrc = self.rpc.call_node_demote_from_mc(node.name)
4030
        msg = rrc.fail_msg
4031
        if msg:
4032
          self.LogWarning("Node failed to demote itself: %s" % msg)
4033

    
4034
    if self.op.drained is not None:
4035
      node.drained = self.op.drained
4036
      result.append(("drained", str(self.op.drained)))
4037
      if self.op.drained == True:
4038
        if node.master_candidate:
4039
          node.master_candidate = False
4040
          changed_mc = True
4041
          result.append(("master_candidate", "auto-demotion due to drain"))
4042
          rrc = self.rpc.call_node_demote_from_mc(node.name)
4043
          msg = rrc.fail_msg
4044
          if msg:
4045
            self.LogWarning("Node failed to demote itself: %s" % msg)
4046
        if node.offline:
4047
          node.offline = False
4048
          result.append(("offline", "clear offline status due to drain"))
4049

    
4050
    # we locked all nodes, we adjust the CP before updating this node
4051
    if self.lock_all:
4052
      _AdjustCandidatePool(self, [node.name])
4053

    
4054
    # this will trigger configuration file update, if needed
4055
    self.cfg.Update(node, feedback_fn)
4056

    
4057
    # this will trigger job queue propagation or cleanup
4058
    if changed_mc:
4059
      self.context.ReaddNode(node)
4060

    
4061
    return result
4062

    
4063

    
4064
class LUPowercycleNode(NoHooksLU):
4065
  """Powercycles a node.
4066

4067
  """
4068
  _OP_PARAMS = [
4069
    _PNodeName,
4070
    _PForce,
4071
    ]
4072
  REQ_BGL = False
4073

    
4074
  def CheckArguments(self):
4075
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4076
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4077
      raise errors.OpPrereqError("The node is the master and the force"
4078
                                 " parameter was not set",
4079
                                 errors.ECODE_INVAL)
4080

    
4081
  def ExpandNames(self):
4082
    """Locking for PowercycleNode.
4083

4084
    This is a last-resort option and shouldn't block on other
4085
    jobs. Therefore, we grab no locks.
4086

4087
    """
4088
    self.needed_locks = {}
4089

    
4090
  def Exec(self, feedback_fn):
4091
    """Reboots a node.
4092

4093
    """
4094
    result = self.rpc.call_node_powercycle(self.op.node_name,
4095
                                           self.cfg.GetHypervisorType())
4096
    result.Raise("Failed to schedule the reboot")
4097
    return result.payload
4098

    
4099

    
4100
class LUQueryClusterInfo(NoHooksLU):
4101
  """Query cluster configuration.
4102

4103
  """
4104
  REQ_BGL = False
4105

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

    
4109
  def Exec(self, feedback_fn):
4110
    """Return cluster config.
4111

4112
    """
4113
    cluster = self.cfg.GetClusterInfo()
4114
    os_hvp = {}
4115

    
4116
    # Filter just for enabled hypervisors
4117
    for os_name, hv_dict in cluster.os_hvp.items():
4118
      os_hvp[os_name] = {}
4119
      for hv_name, hv_params in hv_dict.items():
4120
        if hv_name in cluster.enabled_hypervisors:
4121
          os_hvp[os_name][hv_name] = hv_params
4122

    
4123
    # Convert ip_family to ip_version
4124
    primary_ip_version = constants.IP4_VERSION
4125
    if cluster.primary_ip_family == netutils.IP6Address.family:
4126
      primary_ip_version = constants.IP6_VERSION
4127

    
4128
    result = {
4129
      "software_version": constants.RELEASE_VERSION,
4130
      "protocol_version": constants.PROTOCOL_VERSION,
4131
      "config_version": constants.CONFIG_VERSION,
4132
      "os_api_version": max(constants.OS_API_VERSIONS),
4133
      "export_version": constants.EXPORT_VERSION,
4134
      "architecture": (platform.architecture()[0], platform.machine()),
4135
      "name": cluster.cluster_name,
4136
      "master": cluster.master_node,
4137
      "default_hypervisor": cluster.enabled_hypervisors[0],
4138
      "enabled_hypervisors": cluster.enabled_hypervisors,
4139
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4140
                        for hypervisor_name in cluster.enabled_hypervisors]),
4141
      "os_hvp": os_hvp,
4142
      "beparams": cluster.beparams,
4143
      "osparams": cluster.osparams,
4144
      "nicparams": cluster.nicparams,
4145
      "candidate_pool_size": cluster.candidate_pool_size,
4146
      "master_netdev": cluster.master_netdev,
4147
      "volume_group_name": cluster.volume_group_name,
4148
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
4149
      "file_storage_dir": cluster.file_storage_dir,
4150
      "maintain_node_health": cluster.maintain_node_health,
4151
      "ctime": cluster.ctime,
4152
      "mtime": cluster.mtime,
4153
      "uuid": cluster.uuid,
4154
      "tags": list(cluster.GetTags()),
4155
      "uid_pool": cluster.uid_pool,
4156
      "default_iallocator": cluster.default_iallocator,
4157
      "reserved_lvs": cluster.reserved_lvs,
4158
      "primary_ip_version": primary_ip_version,
4159
      }
4160

    
4161
    return result
4162

    
4163

    
4164
class LUQueryConfigValues(NoHooksLU):
4165
  """Return configuration values.
4166

4167
  """
4168
  _OP_PARAMS = [_POutputFields]
4169
  REQ_BGL = False
4170
  _FIELDS_DYNAMIC = utils.FieldSet()
4171
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4172
                                  "watcher_pause")
4173

    
4174
  def CheckArguments(self):
4175
    _CheckOutputFields(static=self._FIELDS_STATIC,
4176
                       dynamic=self._FIELDS_DYNAMIC,
4177
                       selected=self.op.output_fields)
4178

    
4179
  def ExpandNames(self):
4180
    self.needed_locks = {}
4181

    
4182
  def Exec(self, feedback_fn):
4183
    """Dump a representation of the cluster config to the standard output.
4184

4185
    """
4186
    values = []
4187
    for field in self.op.output_fields:
4188
      if field == "cluster_name":
4189
        entry = self.cfg.GetClusterName()
4190
      elif field == "master_node":
4191
        entry = self.cfg.GetMasterNode()
4192
      elif field == "drain_flag":
4193
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4194
      elif field == "watcher_pause":
4195
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4196
      else:
4197
        raise errors.ParameterError(field)
4198
      values.append(entry)
4199
    return values
4200

    
4201

    
4202
class LUActivateInstanceDisks(NoHooksLU):
4203
  """Bring up an instance's disks.
4204

4205
  """
4206
  _OP_PARAMS = [
4207
    _PInstanceName,
4208
    ("ignore_size", False, _TBool),
4209
    ]
4210
  REQ_BGL = False
4211

    
4212
  def ExpandNames(self):
4213
    self._ExpandAndLockInstance()
4214
    self.needed_locks[locking.LEVEL_NODE] = []
4215
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4216

    
4217
  def DeclareLocks(self, level):
4218
    if level == locking.LEVEL_NODE:
4219
      self._LockInstancesNodes()
4220

    
4221
  def CheckPrereq(self):
4222
    """Check prerequisites.
4223

4224
    This checks that the instance is in the cluster.
4225

4226
    """
4227
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4228
    assert self.instance is not None, \
4229
      "Cannot retrieve locked instance %s" % self.op.instance_name
4230
    _CheckNodeOnline(self, self.instance.primary_node)
4231

    
4232
  def Exec(self, feedback_fn):
4233
    """Activate the disks.
4234

4235
    """
4236
    disks_ok, disks_info = \
4237
              _AssembleInstanceDisks(self, self.instance,
4238
                                     ignore_size=self.op.ignore_size)
4239
    if not disks_ok:
4240
      raise errors.OpExecError("Cannot activate block devices")
4241

    
4242
    return disks_info
4243

    
4244

    
4245
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4246
                           ignore_size=False):
4247
  """Prepare the block devices for an instance.
4248

4249
  This sets up the block devices on all nodes.
4250

4251
  @type lu: L{LogicalUnit}
4252
  @param lu: the logical unit on whose behalf we execute
4253
  @type instance: L{objects.Instance}
4254
  @param instance: the instance for whose disks we assemble
4255
  @type disks: list of L{objects.Disk} or None
4256
  @param disks: which disks to assemble (or all, if None)
4257
  @type ignore_secondaries: boolean
4258
  @param ignore_secondaries: if true, errors on secondary nodes
4259
      won't result in an error return from the function
4260
  @type ignore_size: boolean
4261
  @param ignore_size: if true, the current known size of the disk
4262
      will not be used during the disk activation, useful for cases
4263
      when the size is wrong
4264
  @return: False if the operation failed, otherwise a list of
4265
      (host, instance_visible_name, node_visible_name)
4266
      with the mapping from node devices to instance devices
4267

4268
  """
4269
  device_info = []
4270
  disks_ok = True
4271
  iname = instance.name
4272
  disks = _ExpandCheckDisks(instance, disks)
4273

    
4274
  # With the two passes mechanism we try to reduce the window of
4275
  # opportunity for the race condition of switching DRBD to primary
4276
  # before handshaking occured, but we do not eliminate it
4277

    
4278
  # The proper fix would be to wait (with some limits) until the
4279
  # connection has been made and drbd transitions from WFConnection
4280
  # into any other network-connected state (Connected, SyncTarget,
4281
  # SyncSource, etc.)
4282

    
4283
  # 1st pass, assemble on all nodes in secondary mode
4284
  for inst_disk in disks:
4285
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4286
      if ignore_size:
4287
        node_disk = node_disk.Copy()
4288
        node_disk.UnsetSize()
4289
      lu.cfg.SetDiskID(node_disk, node)
4290
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
4291
      msg = result.fail_msg
4292
      if msg:
4293
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4294
                           " (is_primary=False, pass=1): %s",
4295
                           inst_disk.iv_name, node, msg)
4296
        if not ignore_secondaries:
4297
          disks_ok = False
4298

    
4299
  # FIXME: race condition on drbd migration to primary
4300

    
4301
  # 2nd pass, do only the primary node
4302
  for inst_disk in disks:
4303
    dev_path = None
4304

    
4305
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4306
      if node != instance.primary_node:
4307
        continue
4308
      if ignore_size:
4309
        node_disk = node_disk.Copy()
4310
        node_disk.UnsetSize()
4311
      lu.cfg.SetDiskID(node_disk, node)
4312
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
4313
      msg = result.fail_msg
4314
      if msg:
4315
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4316
                           " (is_primary=True, pass=2): %s",
4317
                           inst_disk.iv_name, node, msg)
4318
        disks_ok = False
4319
      else:
4320
        dev_path = result.payload
4321

    
4322
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4323

    
4324
  # leave the disks configured for the primary node
4325
  # this is a workaround that would be fixed better by
4326
  # improving the logical/physical id handling
4327
  for disk in disks:
4328
    lu.cfg.SetDiskID(disk, instance.primary_node)
4329

    
4330
  return disks_ok, device_info
4331

    
4332

    
4333
def _StartInstanceDisks(lu, instance, force):
4334
  """Start the disks of an instance.
4335

4336
  """
4337
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4338
                                           ignore_secondaries=force)
4339
  if not disks_ok:
4340
    _ShutdownInstanceDisks(lu, instance)
4341
    if force is not None and not force:
4342
      lu.proc.LogWarning("", hint="If the message above refers to a"
4343
                         " secondary node,"
4344
                         " you can retry the operation using '--force'.")
4345
    raise errors.OpExecError("Disk consistency error")
4346

    
4347

    
4348
class LUDeactivateInstanceDisks(NoHooksLU):
4349
  """Shutdown an instance's disks.
4350

4351
  """
4352
  _OP_PARAMS = [
4353
    _PInstanceName,
4354
    ]
4355
  REQ_BGL = False
4356

    
4357
  def ExpandNames(self):
4358
    self._ExpandAndLockInstance()
4359
    self.needed_locks[locking.LEVEL_NODE] = []
4360
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4361

    
4362
  def DeclareLocks(self, level):
4363
    if level == locking.LEVEL_NODE:
4364
      self._LockInstancesNodes()
4365

    
4366
  def CheckPrereq(self):
4367
    """Check prerequisites.
4368

4369
    This checks that the instance is in the cluster.
4370

4371
    """
4372
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4373
    assert self.instance is not None, \
4374
      "Cannot retrieve locked instance %s" % self.op.instance_name
4375

    
4376
  def Exec(self, feedback_fn):
4377
    """Deactivate the disks
4378

4379
    """
4380
    instance = self.instance
4381
    _SafeShutdownInstanceDisks(self, instance)
4382

    
4383

    
4384
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4385
  """Shutdown block devices of an instance.
4386

4387
  This function checks if an instance is running, before calling
4388
  _ShutdownInstanceDisks.
4389

4390
  """
4391
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4392
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4393

    
4394

    
4395
def _ExpandCheckDisks(instance, disks):
4396
  """Return the instance disks selected by the disks list
4397

4398
  @type disks: list of L{objects.Disk} or None
4399
  @param disks: selected disks
4400
  @rtype: list of L{objects.Disk}
4401
  @return: selected instance disks to act on
4402

4403
  """
4404
  if disks is None:
4405
    return instance.disks
4406
  else:
4407
    if not set(disks).issubset(instance.disks):
4408
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4409
                                   " target instance")
4410
    return disks
4411

    
4412

    
4413
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4414
  """Shutdown block devices of an instance.
4415

4416
  This does the shutdown on all nodes of the instance.
4417

4418
  If the ignore_primary is false, errors on the primary node are
4419
  ignored.
4420

4421
  """
4422
  all_result = True
4423
  disks = _ExpandCheckDisks(instance, disks)
4424

    
4425
  for disk in disks:
4426
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4427
      lu.cfg.SetDiskID(top_disk, node)
4428
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4429
      msg = result.fail_msg
4430
      if msg:
4431
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4432
                      disk.iv_name, node, msg)
4433
        if not ignore_primary or node != instance.primary_node:
4434
          all_result = False
4435
  return all_result
4436

    
4437

    
4438
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4439
  """Checks if a node has enough free memory.
4440

4441
  This function check if a given node has the needed amount of free
4442
  memory. In case the node has less memory or we cannot get the
4443
  information from the node, this function raise an OpPrereqError
4444
  exception.
4445

4446
  @type lu: C{LogicalUnit}
4447
  @param lu: a logical unit from which we get configuration data
4448
  @type node: C{str}
4449
  @param node: the node to check
4450
  @type reason: C{str}
4451
  @param reason: string to use in the error message
4452
  @type requested: C{int}
4453
  @param requested: the amount of memory in MiB to check for
4454
  @type hypervisor_name: C{str}
4455
  @param hypervisor_name: the hypervisor to ask for memory stats
4456
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4457
      we cannot check the node
4458

4459
  """
4460
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
4461
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4462
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4463
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4464
  if not isinstance(free_mem, int):
4465
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4466
                               " was '%s'" % (node, free_mem),
4467
                               errors.ECODE_ENVIRON)
4468
  if requested > free_mem:
4469
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
4470
                               " needed %s MiB, available %s MiB" %
4471
                               (node, reason, requested, free_mem),
4472
                               errors.ECODE_NORES)
4473

    
4474

    
4475
def _CheckNodesFreeDisk(lu, nodenames, requested):
4476
  """Checks if nodes have enough free disk space in the default VG.
4477

4478
  This function check if all given nodes have the needed amount of
4479
  free disk. In case any node has less disk or we cannot get the
4480
  information from the node, this function raise an OpPrereqError
4481
  exception.
4482

4483
  @type lu: C{LogicalUnit}
4484
  @param lu: a logical unit from which we get configuration data
4485
  @type nodenames: C{list}
4486
  @param nodenames: the list of node names to check
4487
  @type requested: C{int}
4488
  @param requested: the amount of disk in MiB to check for
4489
  @raise errors.OpPrereqError: if the node doesn't have enough disk, or
4490
      we cannot check the node
4491

4492
  """
4493
  nodeinfo = lu.rpc.call_node_info(nodenames, lu.cfg.GetVGName(),
4494
                                   lu.cfg.GetHypervisorType())
4495
  for node in nodenames:
4496
    info = nodeinfo[node]
4497
    info.Raise("Cannot get current information from node %s" % node,
4498
               prereq=True, ecode=errors.ECODE_ENVIRON)
4499
    vg_free = info.payload.get("vg_free", None)
4500
    if not isinstance(vg_free, int):
4501
      raise errors.OpPrereqError("Can't compute free disk space on node %s,"
4502
                                 " result was '%s'" % (node, vg_free),
4503
                                 errors.ECODE_ENVIRON)
4504
    if requested > vg_free:
4505
      raise errors.OpPrereqError("Not enough disk space on target node %s:"
4506
                                 " required %d MiB, available %d MiB" %
4507
                                 (node, requested, vg_free),
4508
                                 errors.ECODE_NORES)
4509

    
4510

    
4511
class LUStartupInstance(LogicalUnit):
4512
  """Starts an instance.
4513

4514
  """
4515
  HPATH = "instance-start"
4516
  HTYPE = constants.HTYPE_INSTANCE
4517
  _OP_PARAMS = [
4518
    _PInstanceName,
4519
    _PForce,
4520
    ("hvparams", _EmptyDict, _TDict),
4521
    ("beparams", _EmptyDict, _TDict),
4522
    ]
4523
  REQ_BGL = False
4524

    
4525
  def CheckArguments(self):
4526
    # extra beparams
4527
    if self.op.beparams:
4528
      # fill the beparams dict
4529
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
4530

    
4531
  def ExpandNames(self):
4532
    self._ExpandAndLockInstance()
4533

    
4534
  def BuildHooksEnv(self):
4535
    """Build hooks env.
4536

4537
    This runs on master, primary and secondary nodes of the instance.
4538

4539
    """
4540
    env = {
4541
      "FORCE": self.op.force,
4542
      }
4543
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4544
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4545
    return env, nl, nl
4546

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

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

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

    
4557
    # extra hvparams
4558
    if self.op.hvparams:
4559
      # check hypervisor parameter syntax (locally)
4560
      cluster = self.cfg.GetClusterInfo()
4561
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
4562
      filled_hvp = cluster.FillHV(instance)
4563
      filled_hvp.update(self.op.hvparams)
4564
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
4565
      hv_type.CheckParameterSyntax(filled_hvp)
4566
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
4567

    
4568
    _CheckNodeOnline(self, instance.primary_node)
4569

    
4570
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4571
    # check bridges existence
4572
    _CheckInstanceBridgesExist(self, instance)
4573

    
4574
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4575
                                              instance.name,
4576
                                              instance.hypervisor)
4577
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4578
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4579
    if not remote_info.payload: # not running already
4580
      _CheckNodeFreeMemory(self, instance.primary_node,
4581
                           "starting instance %s" % instance.name,
4582
                           bep[constants.BE_MEMORY], instance.hypervisor)
4583

    
4584
  def Exec(self, feedback_fn):
4585
    """Start the instance.
4586

4587
    """
4588
    instance = self.instance
4589
    force = self.op.force
4590

    
4591
    self.cfg.MarkInstanceUp(instance.name)
4592

    
4593
    node_current = instance.primary_node
4594

    
4595
    _StartInstanceDisks(self, instance, force)
4596

    
4597
    result = self.rpc.call_instance_start(node_current, instance,
4598
                                          self.op.hvparams, self.op.beparams)
4599
    msg = result.fail_msg
4600
    if msg:
4601
      _ShutdownInstanceDisks(self, instance)
4602
      raise errors.OpExecError("Could not start instance: %s" % msg)
4603

    
4604

    
4605
class LURebootInstance(LogicalUnit):
4606
  """Reboot an instance.
4607

4608
  """
4609
  HPATH = "instance-reboot"
4610
  HTYPE = constants.HTYPE_INSTANCE
4611
  _OP_PARAMS = [
4612
    _PInstanceName,
4613
    ("ignore_secondaries", False, _TBool),
4614
    ("reboot_type", _NoDefault, _TElemOf(constants.REBOOT_TYPES)),
4615
    _PShutdownTimeout,
4616
    ]
4617
  REQ_BGL = False
4618

    
4619
  def ExpandNames(self):
4620
    self._ExpandAndLockInstance()
4621

    
4622
  def BuildHooksEnv(self):
4623
    """Build hooks env.
4624

4625
    This runs on master, primary and secondary nodes of the instance.
4626

4627
    """
4628
    env = {
4629
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
4630
      "REBOOT_TYPE": self.op.reboot_type,
4631
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
4632
      }
4633
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4634
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4635
    return env, nl, nl
4636

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

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

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

    
4647
    _CheckNodeOnline(self, instance.primary_node)
4648

    
4649
    # check bridges existence
4650
    _CheckInstanceBridgesExist(self, instance)
4651

    
4652
  def Exec(self, feedback_fn):
4653
    """Reboot the instance.
4654

4655
    """
4656
    instance = self.instance
4657
    ignore_secondaries = self.op.ignore_secondaries
4658
    reboot_type = self.op.reboot_type
4659

    
4660
    node_current = instance.primary_node
4661

    
4662
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
4663
                       constants.INSTANCE_REBOOT_HARD]:
4664
      for disk in instance.disks:
4665
        self.cfg.SetDiskID(disk, node_current)
4666
      result = self.rpc.call_instance_reboot(node_current, instance,
4667
                                             reboot_type,
4668
                                             self.op.shutdown_timeout)
4669
      result.Raise("Could not reboot instance")
4670
    else:
4671
      result = self.rpc.call_instance_shutdown(node_current, instance,
4672
                                               self.op.shutdown_timeout)
4673
      result.Raise("Could not shutdown instance for full reboot")
4674
      _ShutdownInstanceDisks(self, instance)
4675
      _StartInstanceDisks(self, instance, ignore_secondaries)
4676
      result = self.rpc.call_instance_start(node_current, instance, None, None)
4677
      msg = result.fail_msg
4678
      if msg:
4679
        _ShutdownInstanceDisks(self, instance)
4680
        raise errors.OpExecError("Could not start instance for"
4681
                                 " full reboot: %s" % msg)
4682

    
4683
    self.cfg.MarkInstanceUp(instance.name)
4684

    
4685

    
4686
class LUShutdownInstance(LogicalUnit):
4687
  """Shutdown an instance.
4688

4689
  """
4690
  HPATH = "instance-stop"
4691
  HTYPE = constants.HTYPE_INSTANCE
4692
  _OP_PARAMS = [
4693
    _PInstanceName,
4694
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, _TPositiveInt),
4695
    ]
4696
  REQ_BGL = False
4697

    
4698
  def ExpandNames(self):
4699
    self._ExpandAndLockInstance()
4700

    
4701
  def BuildHooksEnv(self):
4702
    """Build hooks env.
4703

4704
    This runs on master, primary and secondary nodes of the instance.
4705

4706
    """
4707
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4708
    env["TIMEOUT"] = self.op.timeout
4709
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4710
    return env, nl, nl
4711

    
4712
  def CheckPrereq(self):
4713
    """Check prerequisites.
4714

4715
    This checks that the instance is in the cluster.
4716

4717
    """
4718
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4719
    assert self.instance is not None, \
4720
      "Cannot retrieve locked instance %s" % self.op.instance_name
4721
    _CheckNodeOnline(self, self.instance.primary_node)
4722

    
4723
  def Exec(self, feedback_fn):
4724
    """Shutdown the instance.
4725

4726
    """
4727
    instance = self.instance
4728
    node_current = instance.primary_node
4729
    timeout = self.op.timeout
4730
    self.cfg.MarkInstanceDown(instance.name)
4731
    result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
4732
    msg = result.fail_msg
4733
    if msg:
4734
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
4735

    
4736
    _ShutdownInstanceDisks(self, instance)
4737

    
4738

    
4739
class LUReinstallInstance(LogicalUnit):
4740
  """Reinstall an instance.
4741

4742
  """
4743
  HPATH = "instance-reinstall"
4744
  HTYPE = constants.HTYPE_INSTANCE
4745
  _OP_PARAMS = [
4746
    _PInstanceName,
4747
    ("os_type", None, _TMaybeString),
4748
    ("force_variant", False, _TBool),
4749
    ]
4750
  REQ_BGL = False
4751

    
4752
  def ExpandNames(self):
4753
    self._ExpandAndLockInstance()
4754

    
4755
  def BuildHooksEnv(self):
4756
    """Build hooks env.
4757

4758
    This runs on master, primary and secondary nodes of the instance.
4759

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

    
4765
  def CheckPrereq(self):
4766
    """Check prerequisites.
4767

4768
    This checks that the instance is in the cluster and is not running.
4769

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

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

    
4782
    if self.op.os_type is not None:
4783
      # OS verification
4784
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
4785
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
4786

    
4787
    self.instance = instance
4788

    
4789
  def Exec(self, feedback_fn):
4790
    """Reinstall the instance.
4791

4792
    """
4793
    inst = self.instance
4794

    
4795
    if self.op.os_type is not None:
4796
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
4797
      inst.os = self.op.os_type
4798
      self.cfg.Update(inst, feedback_fn)
4799

    
4800
    _StartInstanceDisks(self, inst, None)
4801
    try:
4802
      feedback_fn("Running the instance OS create scripts...")
4803
      # FIXME: pass debug option from opcode to backend
4804
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
4805
                                             self.op.debug_level)
4806
      result.Raise("Could not install OS for instance %s on node %s" %
4807
                   (inst.name, inst.primary_node))
4808
    finally:
4809
      _ShutdownInstanceDisks(self, inst)
4810

    
4811

    
4812
class LURecreateInstanceDisks(LogicalUnit):
4813
  """Recreate an instance's missing disks.
4814

4815
  """
4816
  HPATH = "instance-recreate-disks"
4817
  HTYPE = constants.HTYPE_INSTANCE
4818
  _OP_PARAMS = [
4819
    _PInstanceName,
4820
    ("disks", _EmptyList, _TListOf(_TPositiveInt)),
4821
    ]
4822
  REQ_BGL = False
4823

    
4824
  def ExpandNames(self):
4825
    self._ExpandAndLockInstance()
4826

    
4827
  def BuildHooksEnv(self):
4828
    """Build hooks env.
4829

4830
    This runs on master, primary and secondary nodes of the instance.
4831

4832
    """
4833
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4834
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4835
    return env, nl, nl
4836

    
4837
  def CheckPrereq(self):
4838
    """Check prerequisites.
4839

4840
    This checks that the instance is in the cluster and is not running.
4841

4842
    """
4843
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4844
    assert instance is not None, \
4845
      "Cannot retrieve locked instance %s" % self.op.instance_name
4846
    _CheckNodeOnline(self, instance.primary_node)
4847

    
4848
    if instance.disk_template == constants.DT_DISKLESS:
4849
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4850
                                 self.op.instance_name, errors.ECODE_INVAL)
4851
    _CheckInstanceDown(self, instance, "cannot recreate disks")
4852

    
4853
    if not self.op.disks:
4854
      self.op.disks = range(len(instance.disks))
4855
    else:
4856
      for idx in self.op.disks:
4857
        if idx >= len(instance.disks):
4858
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
4859
                                     errors.ECODE_INVAL)
4860

    
4861
    self.instance = instance
4862

    
4863
  def Exec(self, feedback_fn):
4864
    """Recreate the disks.
4865

4866
    """
4867
    to_skip = []
4868
    for idx, _ in enumerate(self.instance.disks):
4869
      if idx not in self.op.disks: # disk idx has not been passed in
4870
        to_skip.append(idx)
4871
        continue
4872

    
4873
    _CreateDisks(self, self.instance, to_skip=to_skip)
4874

    
4875

    
4876
class LURenameInstance(LogicalUnit):
4877
  """Rename an instance.
4878

4879
  """
4880
  HPATH = "instance-rename"
4881
  HTYPE = constants.HTYPE_INSTANCE
4882
  _OP_PARAMS = [
4883
    _PInstanceName,
4884
    ("new_name", _NoDefault, _TNonEmptyString),
4885
    ("ip_check", False, _TBool),
4886
    ("name_check", True, _TBool),
4887
    ]
4888

    
4889
  def CheckArguments(self):
4890
    """Check arguments.
4891

4892
    """
4893
    if self.op.ip_check and not self.op.name_check:
4894
      # TODO: make the ip check more flexible and not depend on the name check
4895
      raise errors.OpPrereqError("Cannot do ip check without a name check",
4896
                                 errors.ECODE_INVAL)
4897

    
4898
  def BuildHooksEnv(self):
4899
    """Build hooks env.
4900

4901
    This runs on master, primary and secondary nodes of the instance.
4902

4903
    """
4904
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4905
    env["INSTANCE_NEW_NAME"] = self.op.new_name
4906
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4907
    return env, nl, nl
4908

    
4909
  def CheckPrereq(self):
4910
    """Check prerequisites.
4911

4912
    This checks that the instance is in the cluster and is not running.
4913

4914
    """
4915
    self.op.instance_name = _ExpandInstanceName(self.cfg,
4916
                                                self.op.instance_name)
4917
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4918
    assert instance is not None
4919
    _CheckNodeOnline(self, instance.primary_node)
4920
    _CheckInstanceDown(self, instance, "cannot rename")
4921
    self.instance = instance
4922

    
4923
    new_name = self.op.new_name
4924
    if self.op.name_check:
4925
      hostname = netutils.GetHostname(name=new_name)
4926
      new_name = hostname.name
4927
      if (self.op.ip_check and
4928
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
4929
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4930
                                   (hostname.ip, new_name),
4931
                                   errors.ECODE_NOTUNIQUE)
4932

    
4933
    instance_list = self.cfg.GetInstanceList()
4934
    if new_name in instance_list:
4935
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4936
                                 new_name, errors.ECODE_EXISTS)
4937

    
4938
  def Exec(self, feedback_fn):
4939
    """Reinstall the instance.
4940

4941
    """
4942
    inst = self.instance
4943
    old_name = inst.name
4944

    
4945
    if inst.disk_template == constants.DT_FILE:
4946
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4947

    
4948
    self.cfg.RenameInstance(inst.name, self.op.new_name)
4949
    # Change the instance lock. This is definitely safe while we hold the BGL
4950
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
4951
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
4952

    
4953
    # re-read the instance from the configuration after rename
4954
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
4955

    
4956
    if inst.disk_template == constants.DT_FILE:
4957
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4958
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
4959
                                                     old_file_storage_dir,
4960
                                                     new_file_storage_dir)
4961
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
4962
                   " (but the instance has been renamed in Ganeti)" %
4963
                   (inst.primary_node, old_file_storage_dir,
4964
                    new_file_storage_dir))
4965

    
4966
    _StartInstanceDisks(self, inst, None)
4967
    try:
4968
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
4969
                                                 old_name, self.op.debug_level)
4970
      msg = result.fail_msg
4971
      if msg:
4972
        msg = ("Could not run OS rename script for instance %s on node %s"
4973
               " (but the instance has been renamed in Ganeti): %s" %
4974
               (inst.name, inst.primary_node, msg))
4975
        self.proc.LogWarning(msg)
4976
    finally:
4977
      _ShutdownInstanceDisks(self, inst)
4978

    
4979
    return inst.name
4980

    
4981

    
4982
class LURemoveInstance(LogicalUnit):
4983
  """Remove an instance.
4984

4985
  """
4986
  HPATH = "instance-remove"
4987
  HTYPE = constants.HTYPE_INSTANCE
4988
  _OP_PARAMS = [
4989
    _PInstanceName,
4990
    ("ignore_failures", False, _TBool),
4991
    _PShutdownTimeout,
4992
    ]
4993
  REQ_BGL = False
4994

    
4995
  def ExpandNames(self):
4996
    self._ExpandAndLockInstance()
4997
    self.needed_locks[locking.LEVEL_NODE] = []
4998
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4999

    
5000
  def DeclareLocks(self, level):
5001
    if level == locking.LEVEL_NODE:
5002
      self._LockInstancesNodes()
5003

    
5004
  def BuildHooksEnv(self):
5005
    """Build hooks env.
5006

5007
    This runs on master, primary and secondary nodes of the instance.
5008

5009
    """
5010
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5011
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
5012
    nl = [self.cfg.GetMasterNode()]
5013
    nl_post = list(self.instance.all_nodes) + nl
5014
    return env, nl, nl_post
5015

    
5016
  def CheckPrereq(self):
5017
    """Check prerequisites.
5018

5019
    This checks that the instance is in the cluster.
5020

5021
    """
5022
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5023
    assert self.instance is not None, \
5024
      "Cannot retrieve locked instance %s" % self.op.instance_name
5025

    
5026
  def Exec(self, feedback_fn):
5027
    """Remove the instance.
5028

5029
    """
5030
    instance = self.instance
5031
    logging.info("Shutting down instance %s on node %s",
5032
                 instance.name, instance.primary_node)
5033

    
5034
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5035
                                             self.op.shutdown_timeout)
5036
    msg = result.fail_msg
5037
    if msg:
5038
      if self.op.ignore_failures:
5039
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5040
      else:
5041
        raise errors.OpExecError("Could not shutdown instance %s on"
5042
                                 " node %s: %s" %
5043
                                 (instance.name, instance.primary_node, msg))
5044

    
5045
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5046

    
5047

    
5048
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5049
  """Utility function to remove an instance.
5050

5051
  """
5052
  logging.info("Removing block devices for instance %s", instance.name)
5053

    
5054
  if not _RemoveDisks(lu, instance):
5055
    if not ignore_failures:
5056
      raise errors.OpExecError("Can't remove instance's disks")
5057
    feedback_fn("Warning: can't remove instance's disks")
5058

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

    
5061
  lu.cfg.RemoveInstance(instance.name)
5062

    
5063
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5064
    "Instance lock removal conflict"
5065

    
5066
  # Remove lock for the instance
5067
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5068

    
5069

    
5070
class LUQueryInstances(NoHooksLU):
5071
  """Logical unit for querying instances.
5072

5073
  """
5074
  # pylint: disable-msg=W0142
5075
  _OP_PARAMS = [
5076
    ("output_fields", _NoDefault, _TListOf(_TNonEmptyString)),
5077
    ("names", _EmptyList, _TListOf(_TNonEmptyString)),
5078
    ("use_locking", False, _TBool),
5079
    ]
5080
  REQ_BGL = False
5081
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
5082
                    "serial_no", "ctime", "mtime", "uuid"]
5083
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
5084
                                    "admin_state",
5085
                                    "disk_template", "ip", "mac", "bridge",
5086
                                    "nic_mode", "nic_link",
5087
                                    "sda_size", "sdb_size", "vcpus", "tags",
5088
                                    "network_port", "beparams",
5089
                                    r"(disk)\.(size)/([0-9]+)",
5090
                                    r"(disk)\.(sizes)", "disk_usage",
5091
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
5092
                                    r"(nic)\.(bridge)/([0-9]+)",
5093
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
5094
                                    r"(disk|nic)\.(count)",
5095
                                    "hvparams",
5096
                                    ] + _SIMPLE_FIELDS +
5097
                                  ["hv/%s" % name
5098
                                   for name in constants.HVS_PARAMETERS
5099
                                   if name not in constants.HVC_GLOBALS] +
5100
                                  ["be/%s" % name
5101
                                   for name in constants.BES_PARAMETERS])
5102
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state",
5103
                                   "oper_ram",
5104
                                   "oper_vcpus",
5105
                                   "status")
5106

    
5107

    
5108
  def CheckArguments(self):
5109
    _CheckOutputFields(static=self._FIELDS_STATIC,
5110
                       dynamic=self._FIELDS_DYNAMIC,
5111
                       selected=self.op.output_fields)
5112

    
5113
  def ExpandNames(self):
5114
    self.needed_locks = {}
5115
    self.share_locks[locking.LEVEL_INSTANCE] = 1
5116
    self.share_locks[locking.LEVEL_NODE] = 1
5117

    
5118
    if self.op.names:
5119
      self.wanted = _GetWantedInstances(self, self.op.names)
5120
    else:
5121
      self.wanted = locking.ALL_SET
5122

    
5123
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
5124
    self.do_locking = self.do_node_query and self.op.use_locking
5125
    if self.do_locking:
5126
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
5127
      self.needed_locks[locking.LEVEL_NODE] = []
5128
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5129

    
5130
  def DeclareLocks(self, level):
5131
    if level == locking.LEVEL_NODE and self.do_locking:
5132
      self._LockInstancesNodes()
5133

    
5134
  def Exec(self, feedback_fn):
5135
    """Computes the list of nodes and their attributes.
5136

5137
    """
5138
    # pylint: disable-msg=R0912
5139
    # way too many branches here
5140
    all_info = self.cfg.GetAllInstancesInfo()
5141
    if self.wanted == locking.ALL_SET:
5142
      # caller didn't specify instance names, so ordering is not important
5143
      if self.do_locking:
5144
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5145
      else:
5146
        instance_names = all_info.keys()
5147
      instance_names = utils.NiceSort(instance_names)
5148
    else:
5149
      # caller did specify names, so we must keep the ordering
5150
      if self.do_locking:
5151
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
5152
      else:
5153
        tgt_set = all_info.keys()
5154
      missing = set(self.wanted).difference(tgt_set)
5155
      if missing:
5156
        raise errors.OpExecError("Some instances were removed before"
5157
                                 " retrieving their data: %s" % missing)
5158
      instance_names = self.wanted
5159

    
5160
    instance_list = [all_info[iname] for iname in instance_names]
5161

    
5162
    # begin data gathering
5163

    
5164
    nodes = frozenset([inst.primary_node for inst in instance_list])
5165
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
5166

    
5167
    bad_nodes = []
5168
    off_nodes = []
5169
    if self.do_node_query:
5170
      live_data = {}
5171
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
5172
      for name in nodes:
5173
        result = node_data[name]
5174
        if result.offline:
5175
          # offline nodes will be in both lists
5176
          off_nodes.append(name)
5177
        if result.fail_msg:
5178
          bad_nodes.append(name)
5179
        else:
5180
          if result.payload:
5181
            live_data.update(result.payload)
5182
          # else no instance is alive
5183
    else:
5184
      live_data = dict([(name, {}) for name in instance_names])
5185

    
5186
    # end data gathering
5187

    
5188
    HVPREFIX = "hv/"
5189
    BEPREFIX = "be/"
5190
    output = []
5191
    cluster = self.cfg.GetClusterInfo()
5192
    for instance in instance_list:
5193
      iout = []
5194
      i_hv = cluster.FillHV(instance, skip_globals=True)
5195
      i_be = cluster.FillBE(instance)
5196
      i_nicp = [cluster.SimpleFillNIC(nic.nicparams) for nic in instance.nics]
5197
      for field in self.op.output_fields:
5198
        st_match = self._FIELDS_STATIC.Matches(field)
5199
        if field in self._SIMPLE_FIELDS:
5200
          val = getattr(instance, field)
5201
        elif field == "pnode":
5202
          val = instance.primary_node
5203
        elif field == "snodes":
5204
          val = list(instance.secondary_nodes)
5205
        elif field == "admin_state":
5206
          val = instance.admin_up
5207
        elif field == "oper_state":
5208
          if instance.primary_node in bad_nodes:
5209
            val = None
5210
          else:
5211
            val = bool(live_data.get(instance.name))
5212
        elif field == "status":
5213
          if instance.primary_node in off_nodes:
5214
            val = "ERROR_nodeoffline"
5215
          elif instance.primary_node in bad_nodes:
5216
            val = "ERROR_nodedown"
5217
          else:
5218
            running = bool(live_data.get(instance.name))
5219
            if running:
5220
              if instance.admin_up:
5221
                val = "running"
5222
              else:
5223
                val = "ERROR_up"
5224
            else:
5225
              if instance.admin_up:
5226
                val = "ERROR_down"
5227
              else:
5228
                val = "ADMIN_down"
5229
        elif field == "oper_ram":
5230
          if instance.primary_node in bad_nodes:
5231
            val = None
5232
          elif instance.name in live_data:
5233
            val = live_data[instance.name].get("memory", "?")
5234
          else:
5235
            val = "-"
5236
        elif field == "oper_vcpus":
5237
          if instance.primary_node in bad_nodes:
5238
            val = None
5239
          elif instance.name in live_data:
5240
            val = live_data[instance.name].get("vcpus", "?")
5241
          else:
5242
            val = "-"
5243
        elif field == "vcpus":
5244
          val = i_be[constants.BE_VCPUS]
5245
        elif field == "disk_template":
5246
          val = instance.disk_template
5247
        elif field == "ip":
5248
          if instance.nics:
5249
            val = instance.nics[0].ip
5250
          else:
5251
            val = None
5252
        elif field == "nic_mode":
5253
          if instance.nics:
5254
            val = i_nicp[0][constants.NIC_MODE]
5255
          else:
5256
            val = None
5257
        elif field == "nic_link":
5258
          if instance.nics:
5259
            val = i_nicp[0][constants.NIC_LINK]
5260
          else:
5261
            val = None
5262
        elif field == "bridge":
5263
          if (instance.nics and
5264
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
5265
            val = i_nicp[0][constants.NIC_LINK]
5266
          else:
5267
            val = None
5268
        elif field == "mac":
5269
          if instance.nics:
5270
            val = instance.nics[0].mac
5271
          else:
5272
            val = None
5273
        elif field == "sda_size" or field == "sdb_size":
5274
          idx = ord(field[2]) - ord('a')
5275
          try:
5276
            val = instance.FindDisk(idx).size
5277
          except errors.OpPrereqError:
5278
            val = None
5279
        elif field == "disk_usage": # total disk usage per node
5280
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
5281
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
5282
        elif field == "tags":
5283
          val = list(instance.GetTags())
5284
        elif field == "hvparams":
5285
          val = i_hv
5286
        elif (field.startswith(HVPREFIX) and
5287
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS and
5288
              field[len(HVPREFIX):] not in constants.HVC_GLOBALS):
5289
          val = i_hv.get(field[len(HVPREFIX):], None)
5290
        elif field == "beparams":
5291
          val = i_be
5292
        elif (field.startswith(BEPREFIX) and
5293
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
5294
          val = i_be.get(field[len(BEPREFIX):], None)
5295
        elif st_match and st_match.groups():
5296
          # matches a variable list
5297
          st_groups = st_match.groups()
5298
          if st_groups and st_groups[0] == "disk":
5299
            if st_groups[1] == "count":
5300
              val = len(instance.disks)
5301
            elif st_groups[1] == "sizes":
5302
              val = [disk.size for disk in instance.disks]
5303
            elif st_groups[1] == "size":
5304
              try:
5305
                val = instance.FindDisk(st_groups[2]).size
5306
              except errors.OpPrereqError:
5307
                val = None
5308
            else:
5309
              assert False, "Unhandled disk parameter"
5310
          elif st_groups[0] == "nic":
5311
            if st_groups[1] == "count":
5312
              val = len(instance.nics)
5313
            elif st_groups[1] == "macs":
5314
              val = [nic.mac for nic in instance.nics]
5315
            elif st_groups[1] == "ips":
5316
              val = [nic.ip for nic in instance.nics]
5317
            elif st_groups[1] == "modes":
5318
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
5319
            elif st_groups[1] == "links":
5320
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
5321
            elif st_groups[1] == "bridges":
5322
              val = []
5323
              for nicp in i_nicp:
5324
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
5325
                  val.append(nicp[constants.NIC_LINK])
5326
                else:
5327
                  val.append(None)
5328
            else:
5329
              # index-based item
5330
              nic_idx = int(st_groups[2])
5331
              if nic_idx >= len(instance.nics):
5332
                val = None
5333
              else:
5334
                if st_groups[1] == "mac":
5335
                  val = instance.nics[nic_idx].mac
5336
                elif st_groups[1] == "ip":
5337
                  val = instance.nics[nic_idx].ip
5338
                elif st_groups[1] == "mode":
5339
                  val = i_nicp[nic_idx][constants.NIC_MODE]
5340
                elif st_groups[1] == "link":
5341
                  val = i_nicp[nic_idx][constants.NIC_LINK]
5342
                elif st_groups[1] == "bridge":
5343
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
5344
                  if nic_mode == constants.NIC_MODE_BRIDGED:
5345
                    val = i_nicp[nic_idx][constants.NIC_LINK]
5346
                  else:
5347
                    val = None
5348
                else:
5349
                  assert False, "Unhandled NIC parameter"
5350
          else:
5351
            assert False, ("Declared but unhandled variable parameter '%s'" %
5352
                           field)
5353
        else:
5354
          assert False, "Declared but unhandled parameter '%s'" % field
5355
        iout.append(val)
5356
      output.append(iout)
5357

    
5358
    return output
5359

    
5360

    
5361
class LUFailoverInstance(LogicalUnit):
5362
  """Failover an instance.
5363

5364
  """
5365
  HPATH = "instance-failover"
5366
  HTYPE = constants.HTYPE_INSTANCE
5367
  _OP_PARAMS = [
5368
    _PInstanceName,
5369
    ("ignore_consistency", False, _TBool),
5370
    _PShutdownTimeout,
5371
    ]
5372
  REQ_BGL = False
5373

    
5374
  def ExpandNames(self):
5375
    self._ExpandAndLockInstance()
5376
    self.needed_locks[locking.LEVEL_NODE] = []
5377
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5378

    
5379
  def DeclareLocks(self, level):
5380
    if level == locking.LEVEL_NODE:
5381
      self._LockInstancesNodes()
5382

    
5383
  def BuildHooksEnv(self):
5384
    """Build hooks env.
5385

5386
    This runs on master, primary and secondary nodes of the instance.
5387

5388
    """
5389
    instance = self.instance
5390
    source_node = instance.primary_node
5391
    target_node = instance.secondary_nodes[0]
5392
    env = {
5393
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5394
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5395
      "OLD_PRIMARY": source_node,
5396
      "OLD_SECONDARY": target_node,
5397
      "NEW_PRIMARY": target_node,
5398
      "NEW_SECONDARY": source_node,
5399
      }
5400
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5401
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5402
    nl_post = list(nl)
5403
    nl_post.append(source_node)
5404
    return env, nl, nl_post
5405

    
5406
  def CheckPrereq(self):
5407
    """Check prerequisites.
5408

5409
    This checks that the instance is in the cluster.
5410

5411
    """
5412
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5413
    assert self.instance is not None, \
5414
      "Cannot retrieve locked instance %s" % self.op.instance_name
5415

    
5416
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5417
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5418
      raise errors.OpPrereqError("Instance's disk layout is not"
5419
                                 " network mirrored, cannot failover.",
5420
                                 errors.ECODE_STATE)
5421

    
5422
    secondary_nodes = instance.secondary_nodes
5423
    if not secondary_nodes:
5424
      raise errors.ProgrammerError("no secondary node but using "
5425
                                   "a mirrored disk template")
5426

    
5427
    target_node = secondary_nodes[0]
5428
    _CheckNodeOnline(self, target_node)
5429
    _CheckNodeNotDrained(self, target_node)
5430
    if instance.admin_up:
5431
      # check memory requirements on the secondary node
5432
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5433
                           instance.name, bep[constants.BE_MEMORY],
5434
                           instance.hypervisor)
5435
    else:
5436
      self.LogInfo("Not checking memory on the secondary node as"
5437
                   " instance will not be started")
5438

    
5439
    # check bridge existance
5440
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5441

    
5442
  def Exec(self, feedback_fn):
5443
    """Failover an instance.
5444

5445
    The failover is done by shutting it down on its present node and
5446
    starting it on the secondary.
5447

5448
    """
5449
    instance = self.instance
5450

    
5451
    source_node = instance.primary_node
5452
    target_node = instance.secondary_nodes[0]
5453

    
5454
    if instance.admin_up:
5455
      feedback_fn("* checking disk consistency between source and target")
5456
      for dev in instance.disks:
5457
        # for drbd, these are drbd over lvm
5458
        if not _CheckDiskConsistency(self, dev, target_node, False):
5459
          if not self.op.ignore_consistency:
5460
            raise errors.OpExecError("Disk %s is degraded on target node,"
5461
                                     " aborting failover." % dev.iv_name)
5462
    else:
5463
      feedback_fn("* not checking disk consistency as instance is not running")
5464

    
5465
    feedback_fn("* shutting down instance on source node")
5466
    logging.info("Shutting down instance %s on node %s",
5467
                 instance.name, source_node)
5468

    
5469
    result = self.rpc.call_instance_shutdown(source_node, instance,
5470
                                             self.op.shutdown_timeout)
5471
    msg = result.fail_msg
5472
    if msg:
5473
      if self.op.ignore_consistency:
5474
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5475
                             " Proceeding anyway. Please make sure node"
5476
                             " %s is down. Error details: %s",
5477
                             instance.name, source_node, source_node, msg)
5478
      else:
5479
        raise errors.OpExecError("Could not shutdown instance %s on"
5480
                                 " node %s: %s" %
5481
                                 (instance.name, source_node, msg))
5482

    
5483
    feedback_fn("* deactivating the instance's disks on source node")
5484
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5485
      raise errors.OpExecError("Can't shut down the instance's disks.")
5486

    
5487
    instance.primary_node = target_node
5488
    # distribute new instance config to the other nodes
5489
    self.cfg.Update(instance, feedback_fn)
5490

    
5491
    # Only start the instance if it's marked as up
5492
    if instance.admin_up:
5493
      feedback_fn("* activating the instance's disks on target node")
5494
      logging.info("Starting instance %s on node %s",
5495
                   instance.name, target_node)
5496

    
5497
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5498
                                           ignore_secondaries=True)
5499
      if not disks_ok:
5500
        _ShutdownInstanceDisks(self, instance)
5501
        raise errors.OpExecError("Can't activate the instance's disks")
5502

    
5503
      feedback_fn("* starting the instance on the target node")
5504
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5505
      msg = result.fail_msg
5506
      if msg:
5507
        _ShutdownInstanceDisks(self, instance)
5508
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5509
                                 (instance.name, target_node, msg))
5510

    
5511

    
5512
class LUMigrateInstance(LogicalUnit):
5513
  """Migrate an instance.
5514

5515
  This is migration without shutting down, compared to the failover,
5516
  which is done with shutdown.
5517

5518
  """
5519
  HPATH = "instance-migrate"
5520
  HTYPE = constants.HTYPE_INSTANCE
5521
  _OP_PARAMS = [
5522
    _PInstanceName,
5523
    _PMigrationMode,
5524
    _PMigrationLive,
5525
    ("cleanup", False, _TBool),
5526
    ]
5527

    
5528
  REQ_BGL = False
5529

    
5530
  def ExpandNames(self):
5531
    self._ExpandAndLockInstance()
5532

    
5533
    self.needed_locks[locking.LEVEL_NODE] = []
5534
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5535

    
5536
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5537
                                       self.op.cleanup)
5538
    self.tasklets = [self._migrater]
5539

    
5540
  def DeclareLocks(self, level):
5541
    if level == locking.LEVEL_NODE:
5542
      self._LockInstancesNodes()
5543

    
5544
  def BuildHooksEnv(self):
5545
    """Build hooks env.
5546

5547
    This runs on master, primary and secondary nodes of the instance.
5548

5549
    """
5550
    instance = self._migrater.instance
5551
    source_node = instance.primary_node
5552
    target_node = instance.secondary_nodes[0]
5553
    env = _BuildInstanceHookEnvByObject(self, instance)
5554
    env["MIGRATE_LIVE"] = self._migrater.live
5555
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5556
    env.update({
5557
        "OLD_PRIMARY": source_node,
5558
        "OLD_SECONDARY": target_node,
5559
        "NEW_PRIMARY": target_node,
5560
        "NEW_SECONDARY": source_node,
5561
        })
5562
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5563
    nl_post = list(nl)
5564
    nl_post.append(source_node)
5565
    return env, nl, nl_post
5566

    
5567

    
5568
class LUMoveInstance(LogicalUnit):
5569
  """Move an instance by data-copying.
5570

5571
  """
5572
  HPATH = "instance-move"
5573
  HTYPE = constants.HTYPE_INSTANCE
5574
  _OP_PARAMS = [
5575
    _PInstanceName,
5576
    ("target_node", _NoDefault, _TNonEmptyString),
5577
    _PShutdownTimeout,
5578
    ]
5579
  REQ_BGL = False
5580

    
5581
  def ExpandNames(self):
5582
    self._ExpandAndLockInstance()
5583
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5584
    self.op.target_node = target_node
5585
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5586
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5587

    
5588
  def DeclareLocks(self, level):
5589
    if level == locking.LEVEL_NODE:
5590
      self._LockInstancesNodes(primary_only=True)
5591

    
5592
  def BuildHooksEnv(self):
5593
    """Build hooks env.
5594

5595
    This runs on master, primary and secondary nodes of the instance.
5596

5597
    """
5598
    env = {
5599
      "TARGET_NODE": self.op.target_node,
5600
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5601
      }
5602
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5603
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5604
                                       self.op.target_node]
5605
    return env, nl, nl
5606

    
5607
  def CheckPrereq(self):
5608
    """Check prerequisites.
5609

5610
    This checks that the instance is in the cluster.
5611

5612
    """
5613
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5614
    assert self.instance is not None, \
5615
      "Cannot retrieve locked instance %s" % self.op.instance_name
5616

    
5617
    node = self.cfg.GetNodeInfo(self.op.target_node)
5618
    assert node is not None, \
5619
      "Cannot retrieve locked node %s" % self.op.target_node
5620

    
5621
    self.target_node = target_node = node.name
5622

    
5623
    if target_node == instance.primary_node:
5624
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5625
                                 (instance.name, target_node),
5626
                                 errors.ECODE_STATE)
5627

    
5628
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5629

    
5630
    for idx, dsk in enumerate(instance.disks):
5631
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5632
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5633
                                   " cannot copy" % idx, errors.ECODE_STATE)
5634

    
5635
    _CheckNodeOnline(self, target_node)
5636
    _CheckNodeNotDrained(self, target_node)
5637

    
5638
    if instance.admin_up:
5639
      # check memory requirements on the secondary node
5640
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5641
                           instance.name, bep[constants.BE_MEMORY],
5642
                           instance.hypervisor)
5643
    else:
5644
      self.LogInfo("Not checking memory on the secondary node as"
5645
                   " instance will not be started")
5646

    
5647
    # check bridge existance
5648
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5649

    
5650
  def Exec(self, feedback_fn):
5651
    """Move an instance.
5652

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

5656
    """
5657
    instance = self.instance
5658

    
5659
    source_node = instance.primary_node
5660
    target_node = self.target_node
5661

    
5662
    self.LogInfo("Shutting down instance %s on source node %s",
5663
                 instance.name, source_node)
5664

    
5665
    result = self.rpc.call_instance_shutdown(source_node, instance,
5666
                                             self.op.shutdown_timeout)
5667
    msg = result.fail_msg
5668
    if msg:
5669
      if self.op.ignore_consistency:
5670
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5671
                             " Proceeding anyway. Please make sure node"
5672
                             " %s is down. Error details: %s",
5673
                             instance.name, source_node, source_node, msg)
5674
      else:
5675
        raise errors.OpExecError("Could not shutdown instance %s on"
5676
                                 " node %s: %s" %
5677
                                 (instance.name, source_node, msg))
5678

    
5679
    # create the target disks
5680
    try:
5681
      _CreateDisks(self, instance, target_node=target_node)
5682
    except errors.OpExecError:
5683
      self.LogWarning("Device creation failed, reverting...")
5684
      try:
5685
        _RemoveDisks(self, instance, target_node=target_node)
5686
      finally:
5687
        self.cfg.ReleaseDRBDMinors(instance.name)
5688
        raise
5689

    
5690
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5691

    
5692
    errs = []
5693
    # activate, get path, copy the data over
5694
    for idx, disk in enumerate(instance.disks):
5695
      self.LogInfo("Copying data for disk %d", idx)
5696
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5697
                                               instance.name, True)
5698
      if result.fail_msg:
5699
        self.LogWarning("Can't assemble newly created disk %d: %s",
5700
                        idx, result.fail_msg)
5701
        errs.append(result.fail_msg)
5702
        break
5703
      dev_path = result.payload
5704
      result = self.rpc.call_blockdev_export(source_node, disk,
5705
                                             target_node, dev_path,
5706
                                             cluster_name)
5707
      if result.fail_msg:
5708
        self.LogWarning("Can't copy data over for disk %d: %s",
5709
                        idx, result.fail_msg)
5710
        errs.append(result.fail_msg)
5711
        break
5712

    
5713
    if errs:
5714
      self.LogWarning("Some disks failed to copy, aborting")
5715
      try:
5716
        _RemoveDisks(self, instance, target_node=target_node)
5717
      finally:
5718
        self.cfg.ReleaseDRBDMinors(instance.name)
5719
        raise errors.OpExecError("Errors during disk copy: %s" %
5720
                                 (",".join(errs),))
5721

    
5722
    instance.primary_node = target_node
5723
    self.cfg.Update(instance, feedback_fn)
5724

    
5725
    self.LogInfo("Removing the disks on the original node")
5726
    _RemoveDisks(self, instance, target_node=source_node)
5727

    
5728
    # Only start the instance if it's marked as up
5729
    if instance.admin_up:
5730
      self.LogInfo("Starting instance %s on node %s",
5731
                   instance.name, target_node)
5732

    
5733
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5734
                                           ignore_secondaries=True)
5735
      if not disks_ok:
5736
        _ShutdownInstanceDisks(self, instance)
5737
        raise errors.OpExecError("Can't activate the instance's disks")
5738

    
5739
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5740
      msg = result.fail_msg
5741
      if msg:
5742
        _ShutdownInstanceDisks(self, instance)
5743
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5744
                                 (instance.name, target_node, msg))
5745

    
5746

    
5747
class LUMigrateNode(LogicalUnit):
5748
  """Migrate all instances from a node.
5749

5750
  """
5751
  HPATH = "node-migrate"
5752
  HTYPE = constants.HTYPE_NODE
5753
  _OP_PARAMS = [
5754
    _PNodeName,
5755
    _PMigrationMode,
5756
    _PMigrationLive,
5757
    ]
5758
  REQ_BGL = False
5759

    
5760
  def ExpandNames(self):
5761
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5762

    
5763
    self.needed_locks = {
5764
      locking.LEVEL_NODE: [self.op.node_name],
5765
      }
5766

    
5767
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5768

    
5769
    # Create tasklets for migrating instances for all instances on this node
5770
    names = []
5771
    tasklets = []
5772

    
5773
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5774
      logging.debug("Migrating instance %s", inst.name)
5775
      names.append(inst.name)
5776

    
5777
      tasklets.append(TLMigrateInstance(self, inst.name, False))
5778

    
5779
    self.tasklets = tasklets
5780

    
5781
    # Declare instance locks
5782
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5783

    
5784
  def DeclareLocks(self, level):
5785
    if level == locking.LEVEL_NODE:
5786
      self._LockInstancesNodes()
5787

    
5788
  def BuildHooksEnv(self):
5789
    """Build hooks env.
5790

5791
    This runs on the master, the primary and all the secondaries.
5792

5793
    """
5794
    env = {
5795
      "NODE_NAME": self.op.node_name,
5796
      }
5797

    
5798
    nl = [self.cfg.GetMasterNode()]
5799

    
5800
    return (env, nl, nl)
5801

    
5802

    
5803
class TLMigrateInstance(Tasklet):
5804
  """Tasklet class for instance migration.
5805

5806
  @type live: boolean
5807
  @ivar live: whether the migration will be done live or non-live;
5808
      this variable is initalized only after CheckPrereq has run
5809

5810
  """
5811
  def __init__(self, lu, instance_name, cleanup):
5812
    """Initializes this class.
5813

5814
    """
5815
    Tasklet.__init__(self, lu)
5816

    
5817
    # Parameters
5818
    self.instance_name = instance_name
5819
    self.cleanup = cleanup
5820
    self.live = False # will be overridden later
5821

    
5822
  def CheckPrereq(self):
5823
    """Check prerequisites.
5824

5825
    This checks that the instance is in the cluster.
5826

5827
    """
5828
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
5829
    instance = self.cfg.GetInstanceInfo(instance_name)
5830
    assert instance is not None
5831

    
5832
    if instance.disk_template != constants.DT_DRBD8:
5833
      raise errors.OpPrereqError("Instance's disk layout is not"
5834
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5835

    
5836
    secondary_nodes = instance.secondary_nodes
5837
    if not secondary_nodes:
5838
      raise errors.ConfigurationError("No secondary node but using"
5839
                                      " drbd8 disk template")
5840

    
5841
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5842

    
5843
    target_node = secondary_nodes[0]
5844
    # check memory requirements on the secondary node
5845
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
5846
                         instance.name, i_be[constants.BE_MEMORY],
5847
                         instance.hypervisor)
5848

    
5849
    # check bridge existance
5850
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
5851

    
5852
    if not self.cleanup:
5853
      _CheckNodeNotDrained(self.lu, target_node)
5854
      result = self.rpc.call_instance_migratable(instance.primary_node,
5855
                                                 instance)
5856
      result.Raise("Can't migrate, please use failover",
5857
                   prereq=True, ecode=errors.ECODE_STATE)
5858

    
5859
    self.instance = instance
5860

    
5861
    if self.lu.op.live is not None and self.lu.op.mode is not None:
5862
      raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
5863
                                 " parameters are accepted",
5864
                                 errors.ECODE_INVAL)
5865
    if self.lu.op.live is not None:
5866
      if self.lu.op.live:
5867
        self.lu.op.mode = constants.HT_MIGRATION_LIVE
5868
      else:
5869
        self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
5870
      # reset the 'live' parameter to None so that repeated
5871
      # invocations of CheckPrereq do not raise an exception
5872
      self.lu.op.live = None
5873
    elif self.lu.op.mode is None:
5874
      # read the default value from the hypervisor
5875
      i_hv = self.cfg.GetClusterInfo().FillHV(instance, skip_globals=False)
5876
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
5877

    
5878
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
5879

    
5880
  def _WaitUntilSync(self):
5881
    """Poll with custom rpc for disk sync.
5882

5883
    This uses our own step-based rpc call.
5884

5885
    """
5886
    self.feedback_fn("* wait until resync is done")
5887
    all_done = False
5888
    while not all_done:
5889
      all_done = True
5890
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
5891
                                            self.nodes_ip,
5892
                                            self.instance.disks)
5893
      min_percent = 100
5894
      for node, nres in result.items():
5895
        nres.Raise("Cannot resync disks on node %s" % node)
5896
        node_done, node_percent = nres.payload
5897
        all_done = all_done and node_done
5898
        if node_percent is not None:
5899
          min_percent = min(min_percent, node_percent)
5900
      if not all_done:
5901
        if min_percent < 100:
5902
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
5903
        time.sleep(2)
5904

    
5905
  def _EnsureSecondary(self, node):
5906
    """Demote a node to secondary.
5907

5908
    """
5909
    self.feedback_fn("* switching node %s to secondary mode" % node)
5910

    
5911
    for dev in self.instance.disks:
5912
      self.cfg.SetDiskID(dev, node)
5913

    
5914
    result = self.rpc.call_blockdev_close(node, self.instance.name,
5915
                                          self.instance.disks)
5916
    result.Raise("Cannot change disk to secondary on node %s" % node)
5917

    
5918
  def _GoStandalone(self):
5919
    """Disconnect from the network.
5920

5921
    """
5922
    self.feedback_fn("* changing into standalone mode")
5923
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
5924
                                               self.instance.disks)
5925
    for node, nres in result.items():
5926
      nres.Raise("Cannot disconnect disks node %s" % node)
5927

    
5928
  def _GoReconnect(self, multimaster):
5929
    """Reconnect to the network.
5930

5931
    """
5932
    if multimaster:
5933
      msg = "dual-master"
5934
    else:
5935
      msg = "single-master"
5936
    self.feedback_fn("* changing disks into %s mode" % msg)
5937
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
5938
                                           self.instance.disks,
5939
                                           self.instance.name, multimaster)
5940
    for node, nres in result.items():
5941
      nres.Raise("Cannot change disks config on node %s" % node)
5942

    
5943
  def _ExecCleanup(self):
5944
    """Try to cleanup after a failed migration.
5945

5946
    The cleanup is done by:
5947
      - check that the instance is running only on one node
5948
        (and update the config if needed)
5949
      - change disks on its secondary node to secondary
5950
      - wait until disks are fully synchronized
5951
      - disconnect from the network
5952
      - change disks into single-master mode
5953
      - wait again until disks are fully synchronized
5954

5955
    """
5956
    instance = self.instance
5957
    target_node = self.target_node
5958
    source_node = self.source_node
5959

    
5960
    # check running on only one node
5961
    self.feedback_fn("* checking where the instance actually runs"
5962
                     " (if this hangs, the hypervisor might be in"
5963
                     " a bad state)")
5964
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
5965
    for node, result in ins_l.items():
5966
      result.Raise("Can't contact node %s" % node)
5967

    
5968
    runningon_source = instance.name in ins_l[source_node].payload
5969
    runningon_target = instance.name in ins_l[target_node].payload
5970

    
5971
    if runningon_source and runningon_target:
5972
      raise errors.OpExecError("Instance seems to be running on two nodes,"
5973
                               " or the hypervisor is confused. You will have"
5974
                               " to ensure manually that it runs only on one"
5975
                               " and restart this operation.")
5976

    
5977
    if not (runningon_source or runningon_target):
5978
      raise errors.OpExecError("Instance does not seem to be running at all."
5979
                               " In this case, it's safer to repair by"
5980
                               " running 'gnt-instance stop' to ensure disk"
5981
                               " shutdown, and then restarting it.")
5982

    
5983
    if runningon_target:
5984
      # the migration has actually succeeded, we need to update the config
5985
      self.feedback_fn("* instance running on secondary node (%s),"
5986
                       " updating config" % target_node)
5987
      instance.primary_node = target_node
5988
      self.cfg.Update(instance, self.feedback_fn)
5989
      demoted_node = source_node
5990
    else:
5991
      self.feedback_fn("* instance confirmed to be running on its"
5992
                       " primary node (%s)" % source_node)
5993
      demoted_node = target_node
5994

    
5995
    self._EnsureSecondary(demoted_node)
5996
    try:
5997
      self._WaitUntilSync()
5998
    except errors.OpExecError:
5999
      # we ignore here errors, since if the device is standalone, it
6000
      # won't be able to sync
6001
      pass
6002
    self._GoStandalone()
6003
    self._GoReconnect(False)
6004
    self._WaitUntilSync()
6005

    
6006
    self.feedback_fn("* done")
6007

    
6008
  def _RevertDiskStatus(self):
6009
    """Try to revert the disk status after a failed migration.
6010

6011
    """
6012
    target_node = self.target_node
6013
    try:
6014
      self._EnsureSecondary(target_node)
6015
      self._GoStandalone()
6016
      self._GoReconnect(False)
6017
      self._WaitUntilSync()
6018
    except errors.OpExecError, err:
6019
      self.lu.LogWarning("Migration failed and I can't reconnect the"
6020
                         " drives: error '%s'\n"
6021
                         "Please look and recover the instance status" %
6022
                         str(err))
6023

    
6024
  def _AbortMigration(self):
6025
    """Call the hypervisor code to abort a started migration.
6026

6027
    """
6028
    instance = self.instance
6029
    target_node = self.target_node
6030
    migration_info = self.migration_info
6031

    
6032
    abort_result = self.rpc.call_finalize_migration(target_node,
6033
                                                    instance,
6034
                                                    migration_info,
6035
                                                    False)
6036
    abort_msg = abort_result.fail_msg
6037
    if abort_msg:
6038
      logging.error("Aborting migration failed on target node %s: %s",
6039
                    target_node, abort_msg)
6040
      # Don't raise an exception here, as we stil have to try to revert the
6041
      # disk status, even if this step failed.
6042

    
6043
  def _ExecMigration(self):
6044
    """Migrate an instance.
6045

6046
    The migrate is done by:
6047
      - change the disks into dual-master mode
6048
      - wait until disks are fully synchronized again
6049
      - migrate the instance
6050
      - change disks on the new secondary node (the old primary) to secondary
6051
      - wait until disks are fully synchronized
6052
      - change disks into single-master mode
6053

6054
    """
6055
    instance = self.instance
6056
    target_node = self.target_node
6057
    source_node = self.source_node
6058

    
6059
    self.feedback_fn("* checking disk consistency between source and target")
6060
    for dev in instance.disks:
6061
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6062
        raise errors.OpExecError("Disk %s is degraded or not fully"
6063
                                 " synchronized on target node,"
6064
                                 " aborting migrate." % dev.iv_name)
6065

    
6066
    # First get the migration information from the remote node
6067
    result = self.rpc.call_migration_info(source_node, instance)
6068
    msg = result.fail_msg
6069
    if msg:
6070
      log_err = ("Failed fetching source migration information from %s: %s" %
6071
                 (source_node, msg))
6072
      logging.error(log_err)
6073
      raise errors.OpExecError(log_err)
6074

    
6075
    self.migration_info = migration_info = result.payload
6076

    
6077
    # Then switch the disks to master/master mode
6078
    self._EnsureSecondary(target_node)
6079
    self._GoStandalone()
6080
    self._GoReconnect(True)
6081
    self._WaitUntilSync()
6082

    
6083
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6084
    result = self.rpc.call_accept_instance(target_node,
6085
                                           instance,
6086
                                           migration_info,
6087
                                           self.nodes_ip[target_node])
6088

    
6089
    msg = result.fail_msg
6090
    if msg:
6091
      logging.error("Instance pre-migration failed, trying to revert"
6092
                    " disk status: %s", msg)
6093
      self.feedback_fn("Pre-migration failed, aborting")
6094
      self._AbortMigration()
6095
      self._RevertDiskStatus()
6096
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6097
                               (instance.name, msg))
6098

    
6099
    self.feedback_fn("* migrating instance to %s" % target_node)
6100
    time.sleep(10)
6101
    result = self.rpc.call_instance_migrate(source_node, instance,
6102
                                            self.nodes_ip[target_node],
6103
                                            self.live)
6104
    msg = result.fail_msg
6105
    if msg:
6106
      logging.error("Instance migration failed, trying to revert"
6107
                    " disk status: %s", msg)
6108
      self.feedback_fn("Migration failed, aborting")
6109
      self._AbortMigration()
6110
      self._RevertDiskStatus()
6111
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6112
                               (instance.name, msg))
6113
    time.sleep(10)
6114

    
6115
    instance.primary_node = target_node
6116
    # distribute new instance config to the other nodes
6117
    self.cfg.Update(instance, self.feedback_fn)
6118

    
6119
    result = self.rpc.call_finalize_migration(target_node,
6120
                                              instance,
6121
                                              migration_info,
6122
                                              True)
6123
    msg = result.fail_msg
6124
    if msg:
6125
      logging.error("Instance migration succeeded, but finalization failed:"
6126
                    " %s", msg)
6127
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6128
                               msg)
6129

    
6130
    self._EnsureSecondary(source_node)
6131
    self._WaitUntilSync()
6132
    self._GoStandalone()
6133
    self._GoReconnect(False)
6134
    self._WaitUntilSync()
6135

    
6136
    self.feedback_fn("* done")
6137

    
6138
  def Exec(self, feedback_fn):
6139
    """Perform the migration.
6140

6141
    """
6142
    feedback_fn("Migrating instance %s" % self.instance.name)
6143

    
6144
    self.feedback_fn = feedback_fn
6145

    
6146
    self.source_node = self.instance.primary_node
6147
    self.target_node = self.instance.secondary_nodes[0]
6148
    self.all_nodes = [self.source_node, self.target_node]
6149
    self.nodes_ip = {
6150
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6151
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6152
      }
6153

    
6154
    if self.cleanup:
6155
      return self._ExecCleanup()
6156
    else:
6157
      return self._ExecMigration()
6158

    
6159

    
6160
def _CreateBlockDev(lu, node, instance, device, force_create,
6161
                    info, force_open):
6162
  """Create a tree of block devices on a given node.
6163

6164
  If this device type has to be created on secondaries, create it and
6165
  all its children.
6166

6167
  If not, just recurse to children keeping the same 'force' value.
6168

6169
  @param lu: the lu on whose behalf we execute
6170
  @param node: the node on which to create the device
6171
  @type instance: L{objects.Instance}
6172
  @param instance: the instance which owns the device
6173
  @type device: L{objects.Disk}
6174
  @param device: the device to create
6175
  @type force_create: boolean
6176
  @param force_create: whether to force creation of this device; this
6177
      will be change to True whenever we find a device which has
6178
      CreateOnSecondary() attribute
6179
  @param info: the extra 'metadata' we should attach to the device
6180
      (this will be represented as a LVM tag)
6181
  @type force_open: boolean
6182
  @param force_open: this parameter will be passes to the
6183
      L{backend.BlockdevCreate} function where it specifies
6184
      whether we run on primary or not, and it affects both
6185
      the child assembly and the device own Open() execution
6186

6187
  """
6188
  if device.CreateOnSecondary():
6189
    force_create = True
6190

    
6191
  if device.children:
6192
    for child in device.children:
6193
      _CreateBlockDev(lu, node, instance, child, force_create,
6194
                      info, force_open)
6195

    
6196
  if not force_create:
6197
    return
6198

    
6199
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6200

    
6201

    
6202
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6203
  """Create a single block device on a given node.
6204

6205
  This will not recurse over children of the device, so they must be
6206
  created in advance.
6207

6208
  @param lu: the lu on whose behalf we execute
6209
  @param node: the node on which to create the device
6210
  @type instance: L{objects.Instance}
6211
  @param instance: the instance which owns the device
6212
  @type device: L{objects.Disk}
6213
  @param device: the device to create
6214
  @param info: the extra 'metadata' we should attach to the device
6215
      (this will be represented as a LVM tag)
6216
  @type force_open: boolean
6217
  @param force_open: this parameter will be passes to the
6218
      L{backend.BlockdevCreate} function where it specifies
6219
      whether we run on primary or not, and it affects both
6220
      the child assembly and the device own Open() execution
6221

6222
  """
6223
  lu.cfg.SetDiskID(device, node)
6224
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6225
                                       instance.name, force_open, info)
6226
  result.Raise("Can't create block device %s on"
6227
               " node %s for instance %s" % (device, node, instance.name))
6228
  if device.physical_id is None:
6229
    device.physical_id = result.payload
6230

    
6231

    
6232
def _GenerateUniqueNames(lu, exts):
6233
  """Generate a suitable LV name.
6234

6235
  This will generate a logical volume name for the given instance.
6236

6237
  """
6238
  results = []
6239
  for val in exts:
6240
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6241
    results.append("%s%s" % (new_id, val))
6242
  return results
6243

    
6244

    
6245
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
6246
                         p_minor, s_minor):
6247
  """Generate a drbd8 device complete with its children.
6248

6249
  """
6250
  port = lu.cfg.AllocatePort()
6251
  vgname = lu.cfg.GetVGName()
6252
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6253
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6254
                          logical_id=(vgname, names[0]))
6255
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6256
                          logical_id=(vgname, names[1]))
6257
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6258
                          logical_id=(primary, secondary, port,
6259
                                      p_minor, s_minor,
6260
                                      shared_secret),
6261
                          children=[dev_data, dev_meta],
6262
                          iv_name=iv_name)
6263
  return drbd_dev
6264

    
6265

    
6266
def _GenerateDiskTemplate(lu, template_name,
6267
                          instance_name, primary_node,
6268
                          secondary_nodes, disk_info,
6269
                          file_storage_dir, file_driver,
6270
                          base_index):
6271
  """Generate the entire disk layout for a given template type.
6272

6273
  """
6274
  #TODO: compute space requirements
6275

    
6276
  vgname = lu.cfg.GetVGName()
6277
  disk_count = len(disk_info)
6278
  disks = []
6279
  if template_name == constants.DT_DISKLESS:
6280
    pass
6281
  elif template_name == constants.DT_PLAIN:
6282
    if len(secondary_nodes) != 0:
6283
      raise errors.ProgrammerError("Wrong template configuration")
6284

    
6285
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6286
                                      for i in range(disk_count)])
6287
    for idx, disk in enumerate(disk_info):
6288
      disk_index = idx + base_index
6289
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6290
                              logical_id=(vgname, names[idx]),
6291
                              iv_name="disk/%d" % disk_index,
6292
                              mode=disk["mode"])
6293
      disks.append(disk_dev)
6294
  elif template_name == constants.DT_DRBD8:
6295
    if len(secondary_nodes) != 1:
6296
      raise errors.ProgrammerError("Wrong template configuration")
6297
    remote_node = secondary_nodes[0]
6298
    minors = lu.cfg.AllocateDRBDMinor(
6299
      [primary_node, remote_node] * len(disk_info), instance_name)
6300

    
6301
    names = []
6302
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6303
                                               for i in range(disk_count)]):
6304
      names.append(lv_prefix + "_data")
6305
      names.append(lv_prefix + "_meta")
6306
    for idx, disk in enumerate(disk_info):
6307
      disk_index = idx + base_index
6308
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6309
                                      disk["size"], names[idx*2:idx*2+2],
6310
                                      "disk/%d" % disk_index,
6311
                                      minors[idx*2], minors[idx*2+1])
6312
      disk_dev.mode = disk["mode"]
6313
      disks.append(disk_dev)
6314
  elif template_name == constants.DT_FILE:
6315
    if len(secondary_nodes) != 0:
6316
      raise errors.ProgrammerError("Wrong template configuration")
6317

    
6318
    _RequireFileStorage()
6319

    
6320
    for idx, disk in enumerate(disk_info):
6321
      disk_index = idx + base_index
6322
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6323
                              iv_name="disk/%d" % disk_index,
6324
                              logical_id=(file_driver,
6325
                                          "%s/disk%d" % (file_storage_dir,
6326
                                                         disk_index)),
6327
                              mode=disk["mode"])
6328
      disks.append(disk_dev)
6329
  else:
6330
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6331
  return disks
6332

    
6333

    
6334
def _GetInstanceInfoText(instance):
6335
  """Compute that text that should be added to the disk's metadata.
6336

6337
  """
6338
  return "originstname+%s" % instance.name
6339

    
6340

    
6341
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6342
  """Create all disks for an instance.
6343

6344
  This abstracts away some work from AddInstance.
6345

6346
  @type lu: L{LogicalUnit}
6347
  @param lu: the logical unit on whose behalf we execute
6348
  @type instance: L{objects.Instance}
6349
  @param instance: the instance whose disks we should create
6350
  @type to_skip: list
6351
  @param to_skip: list of indices to skip
6352
  @type target_node: string
6353
  @param target_node: if passed, overrides the target node for creation
6354
  @rtype: boolean
6355
  @return: the success of the creation
6356

6357
  """
6358
  info = _GetInstanceInfoText(instance)
6359
  if target_node is None:
6360
    pnode = instance.primary_node
6361
    all_nodes = instance.all_nodes
6362
  else:
6363
    pnode = target_node
6364
    all_nodes = [pnode]
6365

    
6366
  if instance.disk_template == constants.DT_FILE:
6367
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6368
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6369

    
6370
    result.Raise("Failed to create directory '%s' on"
6371
                 " node %s" % (file_storage_dir, pnode))
6372

    
6373
  # Note: this needs to be kept in sync with adding of disks in
6374
  # LUSetInstanceParams
6375
  for idx, device in enumerate(instance.disks):
6376
    if to_skip and idx in to_skip:
6377
      continue
6378
    logging.info("Creating volume %s for instance %s",
6379
                 device.iv_name, instance.name)
6380
    #HARDCODE
6381
    for node in all_nodes:
6382
      f_create = node == pnode
6383
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6384

    
6385

    
6386
def _RemoveDisks(lu, instance, target_node=None):
6387
  """Remove all disks for an instance.
6388

6389
  This abstracts away some work from `AddInstance()` and
6390
  `RemoveInstance()`. Note that in case some of the devices couldn't
6391
  be removed, the removal will continue with the other ones (compare
6392
  with `_CreateDisks()`).
6393

6394
  @type lu: L{LogicalUnit}
6395
  @param lu: the logical unit on whose behalf we execute
6396
  @type instance: L{objects.Instance}
6397
  @param instance: the instance whose disks we should remove
6398
  @type target_node: string
6399
  @param target_node: used to override the node on which to remove the disks
6400
  @rtype: boolean
6401
  @return: the success of the removal
6402

6403
  """
6404
  logging.info("Removing block devices for instance %s", instance.name)
6405

    
6406
  all_result = True
6407
  for device in instance.disks:
6408
    if target_node:
6409
      edata = [(target_node, device)]
6410
    else:
6411
      edata = device.ComputeNodeTree(instance.primary_node)
6412
    for node, disk in edata:
6413
      lu.cfg.SetDiskID(disk, node)
6414
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6415
      if msg:
6416
        lu.LogWarning("Could not remove block device %s on node %s,"
6417
                      " continuing anyway: %s", device.iv_name, node, msg)
6418
        all_result = False
6419

    
6420
  if instance.disk_template == constants.DT_FILE:
6421
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6422
    if target_node:
6423
      tgt = target_node
6424
    else:
6425
      tgt = instance.primary_node
6426
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6427
    if result.fail_msg:
6428
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6429
                    file_storage_dir, instance.primary_node, result.fail_msg)
6430
      all_result = False
6431

    
6432
  return all_result
6433

    
6434

    
6435
def _ComputeDiskSize(disk_template, disks):
6436
  """Compute disk size requirements in the volume group
6437

6438
  """
6439
  # Required free disk space as a function of disk and swap space
6440
  req_size_dict = {
6441
    constants.DT_DISKLESS: None,
6442
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6443
    # 128 MB are added for drbd metadata for each disk
6444
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6445
    constants.DT_FILE: None,
6446
  }
6447

    
6448
  if disk_template not in req_size_dict:
6449
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6450
                                 " is unknown" %  disk_template)
6451

    
6452
  return req_size_dict[disk_template]
6453

    
6454

    
6455
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6456
  """Hypervisor parameter validation.
6457

6458
  This function abstract the hypervisor parameter validation to be
6459
  used in both instance create and instance modify.
6460

6461
  @type lu: L{LogicalUnit}
6462
  @param lu: the logical unit for which we check
6463
  @type nodenames: list
6464
  @param nodenames: the list of nodes on which we should check
6465
  @type hvname: string
6466
  @param hvname: the name of the hypervisor we should use
6467
  @type hvparams: dict
6468
  @param hvparams: the parameters which we need to check
6469
  @raise errors.OpPrereqError: if the parameters are not valid
6470

6471
  """
6472
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6473
                                                  hvname,
6474
                                                  hvparams)
6475
  for node in nodenames:
6476
    info = hvinfo[node]
6477
    if info.offline:
6478
      continue
6479
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6480

    
6481

    
6482
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6483
  """OS parameters validation.
6484

6485
  @type lu: L{LogicalUnit}
6486
  @param lu: the logical unit for which we check
6487
  @type required: boolean
6488
  @param required: whether the validation should fail if the OS is not
6489
      found
6490
  @type nodenames: list
6491
  @param nodenames: the list of nodes on which we should check
6492
  @type osname: string
6493
  @param osname: the name of the hypervisor we should use
6494
  @type osparams: dict
6495
  @param osparams: the parameters which we need to check
6496
  @raise errors.OpPrereqError: if the parameters are not valid
6497

6498
  """
6499
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6500
                                   [constants.OS_VALIDATE_PARAMETERS],
6501
                                   osparams)
6502
  for node, nres in result.items():
6503
    # we don't check for offline cases since this should be run only
6504
    # against the master node and/or an instance's nodes
6505
    nres.Raise("OS Parameters validation failed on node %s" % node)
6506
    if not nres.payload:
6507
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6508
                 osname, node)
6509

    
6510

    
6511
class LUCreateInstance(LogicalUnit):
6512
  """Create an instance.
6513

6514
  """
6515
  HPATH = "instance-add"
6516
  HTYPE = constants.HTYPE_INSTANCE
6517
  _OP_PARAMS = [
6518
    _PInstanceName,
6519
    ("mode", _NoDefault, _TElemOf(constants.INSTANCE_CREATE_MODES)),
6520
    ("start", True, _TBool),
6521
    ("wait_for_sync", True, _TBool),
6522
    ("ip_check", True, _TBool),
6523
    ("name_check", True, _TBool),
6524
    ("disks", _NoDefault, _TListOf(_TDict)),
6525
    ("nics", _NoDefault, _TListOf(_TDict)),
6526
    ("hvparams", _EmptyDict, _TDict),
6527
    ("beparams", _EmptyDict, _TDict),
6528
    ("osparams", _EmptyDict, _TDict),
6529
    ("no_install", None, _TMaybeBool),
6530
    ("os_type", None, _TMaybeString),
6531
    ("force_variant", False, _TBool),
6532
    ("source_handshake", None, _TOr(_TList, _TNone)),
6533
    ("source_x509_ca", None, _TMaybeString),
6534
    ("source_instance_name", None, _TMaybeString),
6535
    ("src_node", None, _TMaybeString),
6536
    ("src_path", None, _TMaybeString),
6537
    ("pnode", None, _TMaybeString),
6538
    ("snode", None, _TMaybeString),
6539
    ("iallocator", None, _TMaybeString),
6540
    ("hypervisor", None, _TMaybeString),
6541
    ("disk_template", _NoDefault, _CheckDiskTemplate),
6542
    ("identify_defaults", False, _TBool),
6543
    ("file_driver", None, _TOr(_TNone, _TElemOf(constants.FILE_DRIVER))),
6544
    ("file_storage_dir", None, _TMaybeString),
6545
    ("dry_run", False, _TBool),
6546
    ]
6547
  REQ_BGL = False
6548

    
6549
  def CheckArguments(self):
6550
    """Check arguments.
6551

6552
    """
6553
    # do not require name_check to ease forward/backward compatibility
6554
    # for tools
6555
    if self.op.no_install and self.op.start:
6556
      self.LogInfo("No-installation mode selected, disabling startup")
6557
      self.op.start = False
6558
    # validate/normalize the instance name
6559
    self.op.instance_name = \
6560
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
6561

    
6562
    if self.op.ip_check and not self.op.name_check:
6563
      # TODO: make the ip check more flexible and not depend on the name check
6564
      raise errors.OpPrereqError("Cannot do ip check without a name check",
6565
                                 errors.ECODE_INVAL)
6566

    
6567
    # check nics' parameter names
6568
    for nic in self.op.nics:
6569
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6570

    
6571
    # check disks. parameter names and consistent adopt/no-adopt strategy
6572
    has_adopt = has_no_adopt = False
6573
    for disk in self.op.disks:
6574
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6575
      if "adopt" in disk:
6576
        has_adopt = True
6577
      else:
6578
        has_no_adopt = True
6579
    if has_adopt and has_no_adopt:
6580
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6581
                                 errors.ECODE_INVAL)
6582
    if has_adopt:
6583
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6584
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6585
                                   " '%s' disk template" %
6586
                                   self.op.disk_template,
6587
                                   errors.ECODE_INVAL)
6588
      if self.op.iallocator is not None:
6589
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6590
                                   " iallocator script", errors.ECODE_INVAL)
6591
      if self.op.mode == constants.INSTANCE_IMPORT:
6592
        raise errors.OpPrereqError("Disk adoption not allowed for"
6593
                                   " instance import", errors.ECODE_INVAL)
6594

    
6595
    self.adopt_disks = has_adopt
6596

    
6597
    # instance name verification
6598
    if self.op.name_check:
6599
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
6600
      self.op.instance_name = self.hostname1.name
6601
      # used in CheckPrereq for ip ping check
6602
      self.check_ip = self.hostname1.ip
6603
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6604
      raise errors.OpPrereqError("Remote imports require names to be checked" %
6605
                                 errors.ECODE_INVAL)
6606
    else:
6607
      self.check_ip = None
6608

    
6609
    # file storage checks
6610
    if (self.op.file_driver and
6611
        not self.op.file_driver in constants.FILE_DRIVER):
6612
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6613
                                 self.op.file_driver, errors.ECODE_INVAL)
6614

    
6615
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6616
      raise errors.OpPrereqError("File storage directory path not absolute",
6617
                                 errors.ECODE_INVAL)
6618

    
6619
    ### Node/iallocator related checks
6620
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
6621

    
6622
    self._cds = _GetClusterDomainSecret()
6623

    
6624
    if self.op.mode == constants.INSTANCE_IMPORT:
6625
      # On import force_variant must be True, because if we forced it at
6626
      # initial install, our only chance when importing it back is that it
6627
      # works again!
6628
      self.op.force_variant = True
6629

    
6630
      if self.op.no_install:
6631
        self.LogInfo("No-installation mode has no effect during import")
6632

    
6633
    elif self.op.mode == constants.INSTANCE_CREATE:
6634
      if self.op.os_type is None:
6635
        raise errors.OpPrereqError("No guest OS specified",
6636
                                   errors.ECODE_INVAL)
6637
      if self.op.disk_template is None:
6638
        raise errors.OpPrereqError("No disk template specified",
6639
                                   errors.ECODE_INVAL)
6640

    
6641
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6642
      # Check handshake to ensure both clusters have the same domain secret
6643
      src_handshake = self.op.source_handshake
6644
      if not src_handshake:
6645
        raise errors.OpPrereqError("Missing source handshake",
6646
                                   errors.ECODE_INVAL)
6647

    
6648
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6649
                                                           src_handshake)
6650
      if errmsg:
6651
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6652
                                   errors.ECODE_INVAL)
6653

    
6654
      # Load and check source CA
6655
      self.source_x509_ca_pem = self.op.source_x509_ca
6656
      if not self.source_x509_ca_pem:
6657
        raise errors.OpPrereqError("Missing source X509 CA",
6658
                                   errors.ECODE_INVAL)
6659

    
6660
      try:
6661
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
6662
                                                    self._cds)
6663
      except OpenSSL.crypto.Error, err:
6664
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
6665
                                   (err, ), errors.ECODE_INVAL)
6666

    
6667
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
6668
      if errcode is not None:
6669
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
6670
                                   errors.ECODE_INVAL)
6671

    
6672
      self.source_x509_ca = cert
6673

    
6674
      src_instance_name = self.op.source_instance_name
6675
      if not src_instance_name:
6676
        raise errors.OpPrereqError("Missing source instance name",
6677
                                   errors.ECODE_INVAL)
6678

    
6679
      self.source_instance_name = \
6680
          netutils.GetHostname(name=src_instance_name).name
6681

    
6682
    else:
6683
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
6684
                                 self.op.mode, errors.ECODE_INVAL)
6685

    
6686
  def ExpandNames(self):
6687
    """ExpandNames for CreateInstance.
6688

6689
    Figure out the right locks for instance creation.
6690

6691
    """
6692
    self.needed_locks = {}
6693

    
6694
    instance_name = self.op.instance_name
6695
    # this is just a preventive check, but someone might still add this
6696
    # instance in the meantime, and creation will fail at lock-add time
6697
    if instance_name in self.cfg.GetInstanceList():
6698
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6699
                                 instance_name, errors.ECODE_EXISTS)
6700

    
6701
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
6702

    
6703
    if self.op.iallocator:
6704
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6705
    else:
6706
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
6707
      nodelist = [self.op.pnode]
6708
      if self.op.snode is not None:
6709
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
6710
        nodelist.append(self.op.snode)
6711
      self.needed_locks[locking.LEVEL_NODE] = nodelist
6712

    
6713
    # in case of import lock the source node too
6714
    if self.op.mode == constants.INSTANCE_IMPORT:
6715
      src_node = self.op.src_node
6716
      src_path = self.op.src_path
6717

    
6718
      if src_path is None:
6719
        self.op.src_path = src_path = self.op.instance_name
6720

    
6721
      if src_node is None:
6722
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6723
        self.op.src_node = None
6724
        if os.path.isabs(src_path):
6725
          raise errors.OpPrereqError("Importing an instance from an absolute"
6726
                                     " path requires a source node option.",
6727
                                     errors.ECODE_INVAL)
6728
      else:
6729
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
6730
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
6731
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
6732
        if not os.path.isabs(src_path):
6733
          self.op.src_path = src_path = \
6734
            utils.PathJoin(constants.EXPORT_DIR, src_path)
6735

    
6736
  def _RunAllocator(self):
6737
    """Run the allocator based on input opcode.
6738

6739
    """
6740
    nics = [n.ToDict() for n in self.nics]
6741
    ial = IAllocator(self.cfg, self.rpc,
6742
                     mode=constants.IALLOCATOR_MODE_ALLOC,
6743
                     name=self.op.instance_name,
6744
                     disk_template=self.op.disk_template,
6745
                     tags=[],
6746
                     os=self.op.os_type,
6747
                     vcpus=self.be_full[constants.BE_VCPUS],
6748
                     mem_size=self.be_full[constants.BE_MEMORY],
6749
                     disks=self.disks,
6750
                     nics=nics,
6751
                     hypervisor=self.op.hypervisor,
6752
                     )
6753

    
6754
    ial.Run(self.op.iallocator)
6755

    
6756
    if not ial.success:
6757
      raise errors.OpPrereqError("Can't compute nodes using"
6758
                                 " iallocator '%s': %s" %
6759
                                 (self.op.iallocator, ial.info),
6760
                                 errors.ECODE_NORES)
6761
    if len(ial.result) != ial.required_nodes:
6762
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6763
                                 " of nodes (%s), required %s" %
6764
                                 (self.op.iallocator, len(ial.result),
6765
                                  ial.required_nodes), errors.ECODE_FAULT)
6766
    self.op.pnode = ial.result[0]
6767
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6768
                 self.op.instance_name, self.op.iallocator,
6769
                 utils.CommaJoin(ial.result))
6770
    if ial.required_nodes == 2:
6771
      self.op.snode = ial.result[1]
6772

    
6773
  def BuildHooksEnv(self):
6774
    """Build hooks env.
6775

6776
    This runs on master, primary and secondary nodes of the instance.
6777

6778
    """
6779
    env = {
6780
      "ADD_MODE": self.op.mode,
6781
      }
6782
    if self.op.mode == constants.INSTANCE_IMPORT:
6783
      env["SRC_NODE"] = self.op.src_node
6784
      env["SRC_PATH"] = self.op.src_path
6785
      env["SRC_IMAGES"] = self.src_images
6786

    
6787
    env.update(_BuildInstanceHookEnv(
6788
      name=self.op.instance_name,
6789
      primary_node=self.op.pnode,
6790
      secondary_nodes=self.secondaries,
6791
      status=self.op.start,
6792
      os_type=self.op.os_type,
6793
      memory=self.be_full[constants.BE_MEMORY],
6794
      vcpus=self.be_full[constants.BE_VCPUS],
6795
      nics=_NICListToTuple(self, self.nics),
6796
      disk_template=self.op.disk_template,
6797
      disks=[(d["size"], d["mode"]) for d in self.disks],
6798
      bep=self.be_full,
6799
      hvp=self.hv_full,
6800
      hypervisor_name=self.op.hypervisor,
6801
    ))
6802

    
6803
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
6804
          self.secondaries)
6805
    return env, nl, nl
6806

    
6807
  def _ReadExportInfo(self):
6808
    """Reads the export information from disk.
6809

6810
    It will override the opcode source node and path with the actual
6811
    information, if these two were not specified before.
6812

6813
    @return: the export information
6814

6815
    """
6816
    assert self.op.mode == constants.INSTANCE_IMPORT
6817

    
6818
    src_node = self.op.src_node
6819
    src_path = self.op.src_path
6820

    
6821
    if src_node is None:
6822
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
6823
      exp_list = self.rpc.call_export_list(locked_nodes)
6824
      found = False
6825
      for node in exp_list:
6826
        if exp_list[node].fail_msg:
6827
          continue
6828
        if src_path in exp_list[node].payload:
6829
          found = True
6830
          self.op.src_node = src_node = node
6831
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
6832
                                                       src_path)
6833
          break
6834
      if not found:
6835
        raise errors.OpPrereqError("No export found for relative path %s" %
6836
                                    src_path, errors.ECODE_INVAL)
6837

    
6838
    _CheckNodeOnline(self, src_node)
6839
    result = self.rpc.call_export_info(src_node, src_path)
6840
    result.Raise("No export or invalid export found in dir %s" % src_path)
6841

    
6842
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
6843
    if not export_info.has_section(constants.INISECT_EXP):
6844
      raise errors.ProgrammerError("Corrupted export config",
6845
                                   errors.ECODE_ENVIRON)
6846

    
6847
    ei_version = export_info.get(constants.INISECT_EXP, "version")
6848
    if (int(ei_version) != constants.EXPORT_VERSION):
6849
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
6850
                                 (ei_version, constants.EXPORT_VERSION),
6851
                                 errors.ECODE_ENVIRON)
6852
    return export_info
6853

    
6854
  def _ReadExportParams(self, einfo):
6855
    """Use export parameters as defaults.
6856

6857
    In case the opcode doesn't specify (as in override) some instance
6858
    parameters, then try to use them from the export information, if
6859
    that declares them.
6860

6861
    """
6862
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
6863

    
6864
    if self.op.disk_template is None:
6865
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
6866
        self.op.disk_template = einfo.get(constants.INISECT_INS,
6867
                                          "disk_template")
6868
      else:
6869
        raise errors.OpPrereqError("No disk template specified and the export"
6870
                                   " is missing the disk_template information",
6871
                                   errors.ECODE_INVAL)
6872

    
6873
    if not self.op.disks:
6874
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
6875
        disks = []
6876
        # TODO: import the disk iv_name too
6877
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
6878
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
6879
          disks.append({"size": disk_sz})
6880
        self.op.disks = disks
6881
      else:
6882
        raise errors.OpPrereqError("No disk info specified and the export"
6883
                                   " is missing the disk information",
6884
                                   errors.ECODE_INVAL)
6885

    
6886
    if (not self.op.nics and
6887
        einfo.has_option(constants.INISECT_INS, "nic_count")):
6888
      nics = []
6889
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
6890
        ndict = {}
6891
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
6892
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
6893
          ndict[name] = v
6894
        nics.append(ndict)
6895
      self.op.nics = nics
6896

    
6897
    if (self.op.hypervisor is None and
6898
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
6899
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
6900
    if einfo.has_section(constants.INISECT_HYP):
6901
      # use the export parameters but do not override the ones
6902
      # specified by the user
6903
      for name, value in einfo.items(constants.INISECT_HYP):
6904
        if name not in self.op.hvparams:
6905
          self.op.hvparams[name] = value
6906

    
6907
    if einfo.has_section(constants.INISECT_BEP):
6908
      # use the parameters, without overriding
6909
      for name, value in einfo.items(constants.INISECT_BEP):
6910
        if name not in self.op.beparams:
6911
          self.op.beparams[name] = value
6912
    else:
6913
      # try to read the parameters old style, from the main section
6914
      for name in constants.BES_PARAMETERS:
6915
        if (name not in self.op.beparams and
6916
            einfo.has_option(constants.INISECT_INS, name)):
6917
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
6918

    
6919
    if einfo.has_section(constants.INISECT_OSP):
6920
      # use the parameters, without overriding
6921
      for name, value in einfo.items(constants.INISECT_OSP):
6922
        if name not in self.op.osparams:
6923
          self.op.osparams[name] = value
6924

    
6925
  def _RevertToDefaults(self, cluster):
6926
    """Revert the instance parameters to the default values.
6927

6928
    """
6929
    # hvparams
6930
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
6931
    for name in self.op.hvparams.keys():
6932
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
6933
        del self.op.hvparams[name]
6934
    # beparams
6935
    be_defs = cluster.SimpleFillBE({})
6936
    for name in self.op.beparams.keys():
6937
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
6938
        del self.op.beparams[name]
6939
    # nic params
6940
    nic_defs = cluster.SimpleFillNIC({})
6941
    for nic in self.op.nics:
6942
      for name in constants.NICS_PARAMETERS:
6943
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
6944
          del nic[name]
6945
    # osparams
6946
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
6947
    for name in self.op.osparams.keys():
6948
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
6949
        del self.op.osparams[name]
6950

    
6951
  def CheckPrereq(self):
6952
    """Check prerequisites.
6953

6954
    """
6955
    if self.op.mode == constants.INSTANCE_IMPORT:
6956
      export_info = self._ReadExportInfo()
6957
      self._ReadExportParams(export_info)
6958

    
6959
    _CheckDiskTemplate(self.op.disk_template)
6960

    
6961
    if (not self.cfg.GetVGName() and
6962
        self.op.disk_template not in constants.DTS_NOT_LVM):
6963
      raise errors.OpPrereqError("Cluster does not support lvm-based"
6964
                                 " instances", errors.ECODE_STATE)
6965

    
6966
    if self.op.hypervisor is None:
6967
      self.op.hypervisor = self.cfg.GetHypervisorType()
6968

    
6969
    cluster = self.cfg.GetClusterInfo()
6970
    enabled_hvs = cluster.enabled_hypervisors
6971
    if self.op.hypervisor not in enabled_hvs:
6972
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
6973
                                 " cluster (%s)" % (self.op.hypervisor,
6974
                                  ",".join(enabled_hvs)),
6975
                                 errors.ECODE_STATE)
6976

    
6977
    # check hypervisor parameter syntax (locally)
6978
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
6979
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
6980
                                      self.op.hvparams)
6981
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
6982
    hv_type.CheckParameterSyntax(filled_hvp)
6983
    self.hv_full = filled_hvp
6984
    # check that we don't specify global parameters on an instance
6985
    _CheckGlobalHvParams(self.op.hvparams)
6986

    
6987
    # fill and remember the beparams dict
6988
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
6989
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
6990

    
6991
    # build os parameters
6992
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
6993

    
6994
    # now that hvp/bep are in final format, let's reset to defaults,
6995
    # if told to do so
6996
    if self.op.identify_defaults:
6997
      self._RevertToDefaults(cluster)
6998

    
6999
    # NIC buildup
7000
    self.nics = []
7001
    for idx, nic in enumerate(self.op.nics):
7002
      nic_mode_req = nic.get("mode", None)
7003
      nic_mode = nic_mode_req
7004
      if nic_mode is None:
7005
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
7006

    
7007
      # in routed mode, for the first nic, the default ip is 'auto'
7008
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
7009
        default_ip_mode = constants.VALUE_AUTO
7010
      else:
7011
        default_ip_mode = constants.VALUE_NONE
7012

    
7013
      # ip validity checks
7014
      ip = nic.get("ip", default_ip_mode)
7015
      if ip is None or ip.lower() == constants.VALUE_NONE:
7016
        nic_ip = None
7017
      elif ip.lower() == constants.VALUE_AUTO:
7018
        if not self.op.name_check:
7019
          raise errors.OpPrereqError("IP address set to auto but name checks"
7020
                                     " have been skipped. Aborting.",
7021
                                     errors.ECODE_INVAL)
7022
        nic_ip = self.hostname1.ip
7023
      else:
7024
        if not netutils.IP4Address.IsValid(ip):
7025
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
7026
                                     " like a valid IP" % ip,
7027
                                     errors.ECODE_INVAL)
7028
        nic_ip = ip
7029

    
7030
      # TODO: check the ip address for uniqueness
7031
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7032
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7033
                                   errors.ECODE_INVAL)
7034

    
7035
      # MAC address verification
7036
      mac = nic.get("mac", constants.VALUE_AUTO)
7037
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7038
        mac = utils.NormalizeAndValidateMac(mac)
7039

    
7040
        try:
7041
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7042
        except errors.ReservationError:
7043
          raise errors.OpPrereqError("MAC address %s already in use"
7044
                                     " in cluster" % mac,
7045
                                     errors.ECODE_NOTUNIQUE)
7046

    
7047
      # bridge verification
7048
      bridge = nic.get("bridge", None)
7049
      link = nic.get("link", None)
7050
      if bridge and link:
7051
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7052
                                   " at the same time", errors.ECODE_INVAL)
7053
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7054
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7055
                                   errors.ECODE_INVAL)
7056
      elif bridge:
7057
        link = bridge
7058

    
7059
      nicparams = {}
7060
      if nic_mode_req:
7061
        nicparams[constants.NIC_MODE] = nic_mode_req
7062
      if link:
7063
        nicparams[constants.NIC_LINK] = link
7064

    
7065
      check_params = cluster.SimpleFillNIC(nicparams)
7066
      objects.NIC.CheckParameterSyntax(check_params)
7067
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7068

    
7069
    # disk checks/pre-build
7070
    self.disks = []
7071
    for disk in self.op.disks:
7072
      mode = disk.get("mode", constants.DISK_RDWR)
7073
      if mode not in constants.DISK_ACCESS_SET:
7074
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7075
                                   mode, errors.ECODE_INVAL)
7076
      size = disk.get("size", None)
7077
      if size is None:
7078
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7079
      try:
7080
        size = int(size)
7081
      except (TypeError, ValueError):
7082
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7083
                                   errors.ECODE_INVAL)
7084
      new_disk = {"size": size, "mode": mode}
7085
      if "adopt" in disk:
7086
        new_disk["adopt"] = disk["adopt"]
7087
      self.disks.append(new_disk)
7088

    
7089
    if self.op.mode == constants.INSTANCE_IMPORT:
7090

    
7091
      # Check that the new instance doesn't have less disks than the export
7092
      instance_disks = len(self.disks)
7093
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7094
      if instance_disks < export_disks:
7095
        raise errors.OpPrereqError("Not enough disks to import."
7096
                                   " (instance: %d, export: %d)" %
7097
                                   (instance_disks, export_disks),
7098
                                   errors.ECODE_INVAL)
7099

    
7100
      disk_images = []
7101
      for idx in range(export_disks):
7102
        option = 'disk%d_dump' % idx
7103
        if export_info.has_option(constants.INISECT_INS, option):
7104
          # FIXME: are the old os-es, disk sizes, etc. useful?
7105
          export_name = export_info.get(constants.INISECT_INS, option)
7106
          image = utils.PathJoin(self.op.src_path, export_name)
7107
          disk_images.append(image)
7108
        else:
7109
          disk_images.append(False)
7110

    
7111
      self.src_images = disk_images
7112

    
7113
      old_name = export_info.get(constants.INISECT_INS, 'name')
7114
      try:
7115
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7116
      except (TypeError, ValueError), err:
7117
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7118
                                   " an integer: %s" % str(err),
7119
                                   errors.ECODE_STATE)
7120
      if self.op.instance_name == old_name:
7121
        for idx, nic in enumerate(self.nics):
7122
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7123
            nic_mac_ini = 'nic%d_mac' % idx
7124
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7125

    
7126
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7127

    
7128
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7129
    if self.op.ip_check:
7130
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7131
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7132
                                   (self.check_ip, self.op.instance_name),
7133
                                   errors.ECODE_NOTUNIQUE)
7134

    
7135
    #### mac address generation
7136
    # By generating here the mac address both the allocator and the hooks get
7137
    # the real final mac address rather than the 'auto' or 'generate' value.
7138
    # There is a race condition between the generation and the instance object
7139
    # creation, which means that we know the mac is valid now, but we're not
7140
    # sure it will be when we actually add the instance. If things go bad
7141
    # adding the instance will abort because of a duplicate mac, and the
7142
    # creation job will fail.
7143
    for nic in self.nics:
7144
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7145
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7146

    
7147
    #### allocator run
7148

    
7149
    if self.op.iallocator is not None:
7150
      self._RunAllocator()
7151

    
7152
    #### node related checks
7153

    
7154
    # check primary node
7155
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7156
    assert self.pnode is not None, \
7157
      "Cannot retrieve locked node %s" % self.op.pnode
7158
    if pnode.offline:
7159
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7160
                                 pnode.name, errors.ECODE_STATE)
7161
    if pnode.drained:
7162
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7163
                                 pnode.name, errors.ECODE_STATE)
7164

    
7165
    self.secondaries = []
7166

    
7167
    # mirror node verification
7168
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7169
      if self.op.snode is None:
7170
        raise errors.OpPrereqError("The networked disk templates need"
7171
                                   " a mirror node", errors.ECODE_INVAL)
7172
      if self.op.snode == pnode.name:
7173
        raise errors.OpPrereqError("The secondary node cannot be the"
7174
                                   " primary node.", errors.ECODE_INVAL)
7175
      _CheckNodeOnline(self, self.op.snode)
7176
      _CheckNodeNotDrained(self, self.op.snode)
7177
      self.secondaries.append(self.op.snode)
7178

    
7179
    nodenames = [pnode.name] + self.secondaries
7180

    
7181
    req_size = _ComputeDiskSize(self.op.disk_template,
7182
                                self.disks)
7183

    
7184
    # Check lv size requirements, if not adopting
7185
    if req_size is not None and not self.adopt_disks:
7186
      _CheckNodesFreeDisk(self, nodenames, req_size)
7187

    
7188
    if self.adopt_disks: # instead, we must check the adoption data
7189
      all_lvs = set([i["adopt"] for i in self.disks])
7190
      if len(all_lvs) != len(self.disks):
7191
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7192
                                   errors.ECODE_INVAL)
7193
      for lv_name in all_lvs:
7194
        try:
7195
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7196
        except errors.ReservationError:
7197
          raise errors.OpPrereqError("LV named %s used by another instance" %
7198
                                     lv_name, errors.ECODE_NOTUNIQUE)
7199

    
7200
      node_lvs = self.rpc.call_lv_list([pnode.name],
7201
                                       self.cfg.GetVGName())[pnode.name]
7202
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7203
      node_lvs = node_lvs.payload
7204
      delta = all_lvs.difference(node_lvs.keys())
7205
      if delta:
7206
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7207
                                   utils.CommaJoin(delta),
7208
                                   errors.ECODE_INVAL)
7209
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7210
      if online_lvs:
7211
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7212
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7213
                                   errors.ECODE_STATE)
7214
      # update the size of disk based on what is found
7215
      for dsk in self.disks:
7216
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
7217

    
7218
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7219

    
7220
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7221
    # check OS parameters (remotely)
7222
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7223

    
7224
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7225

    
7226
    # memory check on primary node
7227
    if self.op.start:
7228
      _CheckNodeFreeMemory(self, self.pnode.name,
7229
                           "creating instance %s" % self.op.instance_name,
7230
                           self.be_full[constants.BE_MEMORY],
7231
                           self.op.hypervisor)
7232

    
7233
    self.dry_run_result = list(nodenames)
7234

    
7235
  def Exec(self, feedback_fn):
7236
    """Create and add the instance to the cluster.
7237

7238
    """
7239
    instance = self.op.instance_name
7240
    pnode_name = self.pnode.name
7241

    
7242
    ht_kind = self.op.hypervisor
7243
    if ht_kind in constants.HTS_REQ_PORT:
7244
      network_port = self.cfg.AllocatePort()
7245
    else:
7246
      network_port = None
7247

    
7248
    if constants.ENABLE_FILE_STORAGE:
7249
      # this is needed because os.path.join does not accept None arguments
7250
      if self.op.file_storage_dir is None:
7251
        string_file_storage_dir = ""
7252
      else:
7253
        string_file_storage_dir = self.op.file_storage_dir
7254

    
7255
      # build the full file storage dir path
7256
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7257
                                        string_file_storage_dir, instance)
7258
    else:
7259
      file_storage_dir = ""
7260

    
7261
    disks = _GenerateDiskTemplate(self,
7262
                                  self.op.disk_template,
7263
                                  instance, pnode_name,
7264
                                  self.secondaries,
7265
                                  self.disks,
7266
                                  file_storage_dir,
7267
                                  self.op.file_driver,
7268
                                  0)
7269

    
7270
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7271
                            primary_node=pnode_name,
7272
                            nics=self.nics, disks=disks,
7273
                            disk_template=self.op.disk_template,
7274
                            admin_up=False,
7275
                            network_port=network_port,
7276
                            beparams=self.op.beparams,
7277
                            hvparams=self.op.hvparams,
7278
                            hypervisor=self.op.hypervisor,
7279
                            osparams=self.op.osparams,
7280
                            )
7281

    
7282
    if self.adopt_disks:
7283
      # rename LVs to the newly-generated names; we need to construct
7284
      # 'fake' LV disks with the old data, plus the new unique_id
7285
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7286
      rename_to = []
7287
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7288
        rename_to.append(t_dsk.logical_id)
7289
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7290
        self.cfg.SetDiskID(t_dsk, pnode_name)
7291
      result = self.rpc.call_blockdev_rename(pnode_name,
7292
                                             zip(tmp_disks, rename_to))
7293
      result.Raise("Failed to rename adoped LVs")
7294
    else:
7295
      feedback_fn("* creating instance disks...")
7296
      try:
7297
        _CreateDisks(self, iobj)
7298
      except errors.OpExecError:
7299
        self.LogWarning("Device creation failed, reverting...")
7300
        try:
7301
          _RemoveDisks(self, iobj)
7302
        finally:
7303
          self.cfg.ReleaseDRBDMinors(instance)
7304
          raise
7305

    
7306
    feedback_fn("adding instance %s to cluster config" % instance)
7307

    
7308
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7309

    
7310
    # Declare that we don't want to remove the instance lock anymore, as we've
7311
    # added the instance to the config
7312
    del self.remove_locks[locking.LEVEL_INSTANCE]
7313
    # Unlock all the nodes
7314
    if self.op.mode == constants.INSTANCE_IMPORT:
7315
      nodes_keep = [self.op.src_node]
7316
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7317
                       if node != self.op.src_node]
7318
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7319
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7320
    else:
7321
      self.context.glm.release(locking.LEVEL_NODE)
7322
      del self.acquired_locks[locking.LEVEL_NODE]
7323

    
7324
    if self.op.wait_for_sync:
7325
      disk_abort = not _WaitForSync(self, iobj)
7326
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7327
      # make sure the disks are not degraded (still sync-ing is ok)
7328
      time.sleep(15)
7329
      feedback_fn("* checking mirrors status")
7330
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7331
    else:
7332
      disk_abort = False
7333

    
7334
    if disk_abort:
7335
      _RemoveDisks(self, iobj)
7336
      self.cfg.RemoveInstance(iobj.name)
7337
      # Make sure the instance lock gets removed
7338
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7339
      raise errors.OpExecError("There are some degraded disks for"
7340
                               " this instance")
7341

    
7342
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7343
      if self.op.mode == constants.INSTANCE_CREATE:
7344
        if not self.op.no_install:
7345
          feedback_fn("* running the instance OS create scripts...")
7346
          # FIXME: pass debug option from opcode to backend
7347
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7348
                                                 self.op.debug_level)
7349
          result.Raise("Could not add os for instance %s"
7350
                       " on node %s" % (instance, pnode_name))
7351

    
7352
      elif self.op.mode == constants.INSTANCE_IMPORT:
7353
        feedback_fn("* running the instance OS import scripts...")
7354

    
7355
        transfers = []
7356

    
7357
        for idx, image in enumerate(self.src_images):
7358
          if not image:
7359
            continue
7360

    
7361
          # FIXME: pass debug option from opcode to backend
7362
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7363
                                             constants.IEIO_FILE, (image, ),
7364
                                             constants.IEIO_SCRIPT,
7365
                                             (iobj.disks[idx], idx),
7366
                                             None)
7367
          transfers.append(dt)
7368

    
7369
        import_result = \
7370
          masterd.instance.TransferInstanceData(self, feedback_fn,
7371
                                                self.op.src_node, pnode_name,
7372
                                                self.pnode.secondary_ip,
7373
                                                iobj, transfers)
7374
        if not compat.all(import_result):
7375
          self.LogWarning("Some disks for instance %s on node %s were not"
7376
                          " imported successfully" % (instance, pnode_name))
7377

    
7378
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7379
        feedback_fn("* preparing remote import...")
7380
        connect_timeout = constants.RIE_CONNECT_TIMEOUT
7381
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7382

    
7383
        disk_results = masterd.instance.RemoteImport(self, feedback_fn, iobj,
7384
                                                     self.source_x509_ca,
7385
                                                     self._cds, timeouts)
7386
        if not compat.all(disk_results):
7387
          # TODO: Should the instance still be started, even if some disks
7388
          # failed to import (valid for local imports, too)?
7389
          self.LogWarning("Some disks for instance %s on node %s were not"
7390
                          " imported successfully" % (instance, pnode_name))
7391

    
7392
        # Run rename script on newly imported instance
7393
        assert iobj.name == instance
7394
        feedback_fn("Running rename script for %s" % instance)
7395
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7396
                                                   self.source_instance_name,
7397
                                                   self.op.debug_level)
7398
        if result.fail_msg:
7399
          self.LogWarning("Failed to run rename script for %s on node"
7400
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7401

    
7402
      else:
7403
        # also checked in the prereq part
7404
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7405
                                     % self.op.mode)
7406

    
7407
    if self.op.start:
7408
      iobj.admin_up = True
7409
      self.cfg.Update(iobj, feedback_fn)
7410
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7411
      feedback_fn("* starting instance...")
7412
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7413
      result.Raise("Could not start instance")
7414

    
7415
    return list(iobj.all_nodes)
7416

    
7417

    
7418
class LUConnectConsole(NoHooksLU):
7419
  """Connect to an instance's console.
7420

7421
  This is somewhat special in that it returns the command line that
7422
  you need to run on the master node in order to connect to the
7423
  console.
7424

7425
  """
7426
  _OP_PARAMS = [
7427
    _PInstanceName
7428
    ]
7429
  REQ_BGL = False
7430

    
7431
  def ExpandNames(self):
7432
    self._ExpandAndLockInstance()
7433

    
7434
  def CheckPrereq(self):
7435
    """Check prerequisites.
7436

7437
    This checks that the instance is in the cluster.
7438

7439
    """
7440
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7441
    assert self.instance is not None, \
7442
      "Cannot retrieve locked instance %s" % self.op.instance_name
7443
    _CheckNodeOnline(self, self.instance.primary_node)
7444

    
7445
  def Exec(self, feedback_fn):
7446
    """Connect to the console of an instance
7447

7448
    """
7449
    instance = self.instance
7450
    node = instance.primary_node
7451

    
7452
    node_insts = self.rpc.call_instance_list([node],
7453
                                             [instance.hypervisor])[node]
7454
    node_insts.Raise("Can't get node information from %s" % node)
7455

    
7456
    if instance.name not in node_insts.payload:
7457
      raise errors.OpExecError("Instance %s is not running." % instance.name)
7458

    
7459
    logging.debug("Connecting to console of %s on %s", instance.name, node)
7460

    
7461
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
7462
    cluster = self.cfg.GetClusterInfo()
7463
    # beparams and hvparams are passed separately, to avoid editing the
7464
    # instance and then saving the defaults in the instance itself.
7465
    hvparams = cluster.FillHV(instance)
7466
    beparams = cluster.FillBE(instance)
7467
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
7468

    
7469
    # build ssh cmdline
7470
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
7471

    
7472

    
7473
class LUReplaceDisks(LogicalUnit):
7474
  """Replace the disks of an instance.
7475

7476
  """
7477
  HPATH = "mirrors-replace"
7478
  HTYPE = constants.HTYPE_INSTANCE
7479
  _OP_PARAMS = [
7480
    _PInstanceName,
7481
    ("mode", _NoDefault, _TElemOf(constants.REPLACE_MODES)),
7482
    ("disks", _EmptyList, _TListOf(_TPositiveInt)),
7483
    ("remote_node", None, _TMaybeString),
7484
    ("iallocator", None, _TMaybeString),
7485
    ("early_release", False, _TBool),
7486
    ]
7487
  REQ_BGL = False
7488

    
7489
  def CheckArguments(self):
7490
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7491
                                  self.op.iallocator)
7492

    
7493
  def ExpandNames(self):
7494
    self._ExpandAndLockInstance()
7495

    
7496
    if self.op.iallocator is not None:
7497
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7498

    
7499
    elif self.op.remote_node is not None:
7500
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7501
      self.op.remote_node = remote_node
7502

    
7503
      # Warning: do not remove the locking of the new secondary here
7504
      # unless DRBD8.AddChildren is changed to work in parallel;
7505
      # currently it doesn't since parallel invocations of
7506
      # FindUnusedMinor will conflict
7507
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7508
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7509

    
7510
    else:
7511
      self.needed_locks[locking.LEVEL_NODE] = []
7512
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7513

    
7514
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7515
                                   self.op.iallocator, self.op.remote_node,
7516
                                   self.op.disks, False, self.op.early_release)
7517

    
7518
    self.tasklets = [self.replacer]
7519

    
7520
  def DeclareLocks(self, level):
7521
    # If we're not already locking all nodes in the set we have to declare the
7522
    # instance's primary/secondary nodes.
7523
    if (level == locking.LEVEL_NODE and
7524
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7525
      self._LockInstancesNodes()
7526

    
7527
  def BuildHooksEnv(self):
7528
    """Build hooks env.
7529

7530
    This runs on the master, the primary and all the secondaries.
7531

7532
    """
7533
    instance = self.replacer.instance
7534
    env = {
7535
      "MODE": self.op.mode,
7536
      "NEW_SECONDARY": self.op.remote_node,
7537
      "OLD_SECONDARY": instance.secondary_nodes[0],
7538
      }
7539
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7540
    nl = [
7541
      self.cfg.GetMasterNode(),
7542
      instance.primary_node,
7543
      ]
7544
    if self.op.remote_node is not None:
7545
      nl.append(self.op.remote_node)
7546
    return env, nl, nl
7547

    
7548

    
7549
class TLReplaceDisks(Tasklet):
7550
  """Replaces disks for an instance.
7551

7552
  Note: Locking is not within the scope of this class.
7553

7554
  """
7555
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7556
               disks, delay_iallocator, early_release):
7557
    """Initializes this class.
7558

7559
    """
7560
    Tasklet.__init__(self, lu)
7561

    
7562
    # Parameters
7563
    self.instance_name = instance_name
7564
    self.mode = mode
7565
    self.iallocator_name = iallocator_name
7566
    self.remote_node = remote_node
7567
    self.disks = disks
7568
    self.delay_iallocator = delay_iallocator
7569
    self.early_release = early_release
7570

    
7571
    # Runtime data
7572
    self.instance = None
7573
    self.new_node = None
7574
    self.target_node = None
7575
    self.other_node = None
7576
    self.remote_node_info = None
7577
    self.node_secondary_ip = None
7578

    
7579
  @staticmethod
7580
  def CheckArguments(mode, remote_node, iallocator):
7581
    """Helper function for users of this class.
7582

7583
    """
7584
    # check for valid parameter combination
7585
    if mode == constants.REPLACE_DISK_CHG:
7586
      if remote_node is None and iallocator is None:
7587
        raise errors.OpPrereqError("When changing the secondary either an"
7588
                                   " iallocator script must be used or the"
7589
                                   " new node given", errors.ECODE_INVAL)
7590

    
7591
      if remote_node is not None and iallocator is not None:
7592
        raise errors.OpPrereqError("Give either the iallocator or the new"
7593
                                   " secondary, not both", errors.ECODE_INVAL)
7594

    
7595
    elif remote_node is not None or iallocator is not None:
7596
      # Not replacing the secondary
7597
      raise errors.OpPrereqError("The iallocator and new node options can"
7598
                                 " only be used when changing the"
7599
                                 " secondary node", errors.ECODE_INVAL)
7600

    
7601
  @staticmethod
7602
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7603
    """Compute a new secondary node using an IAllocator.
7604

7605
    """
7606
    ial = IAllocator(lu.cfg, lu.rpc,
7607
                     mode=constants.IALLOCATOR_MODE_RELOC,
7608
                     name=instance_name,
7609
                     relocate_from=relocate_from)
7610

    
7611
    ial.Run(iallocator_name)
7612

    
7613
    if not ial.success:
7614
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7615
                                 " %s" % (iallocator_name, ial.info),
7616
                                 errors.ECODE_NORES)
7617

    
7618
    if len(ial.result) != ial.required_nodes:
7619
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7620
                                 " of nodes (%s), required %s" %
7621
                                 (iallocator_name,
7622
                                  len(ial.result), ial.required_nodes),
7623
                                 errors.ECODE_FAULT)
7624

    
7625
    remote_node_name = ial.result[0]
7626

    
7627
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7628
               instance_name, remote_node_name)
7629

    
7630
    return remote_node_name
7631

    
7632
  def _FindFaultyDisks(self, node_name):
7633
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7634
                                    node_name, True)
7635

    
7636
  def CheckPrereq(self):
7637
    """Check prerequisites.
7638

7639
    This checks that the instance is in the cluster.
7640

7641
    """
7642
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7643
    assert instance is not None, \
7644
      "Cannot retrieve locked instance %s" % self.instance_name
7645

    
7646
    if instance.disk_template != constants.DT_DRBD8:
7647
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7648
                                 " instances", errors.ECODE_INVAL)
7649

    
7650
    if len(instance.secondary_nodes) != 1:
7651
      raise errors.OpPrereqError("The instance has a strange layout,"
7652
                                 " expected one secondary but found %d" %
7653
                                 len(instance.secondary_nodes),
7654
                                 errors.ECODE_FAULT)
7655

    
7656
    if not self.delay_iallocator:
7657
      self._CheckPrereq2()
7658

    
7659
  def _CheckPrereq2(self):
7660
    """Check prerequisites, second part.
7661

7662
    This function should always be part of CheckPrereq. It was separated and is
7663
    now called from Exec because during node evacuation iallocator was only
7664
    called with an unmodified cluster model, not taking planned changes into
7665
    account.
7666

7667
    """
7668
    instance = self.instance
7669
    secondary_node = instance.secondary_nodes[0]
7670

    
7671
    if self.iallocator_name is None:
7672
      remote_node = self.remote_node
7673
    else:
7674
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
7675
                                       instance.name, instance.secondary_nodes)
7676

    
7677
    if remote_node is not None:
7678
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
7679
      assert self.remote_node_info is not None, \
7680
        "Cannot retrieve locked node %s" % remote_node
7681
    else:
7682
      self.remote_node_info = None
7683

    
7684
    if remote_node == self.instance.primary_node:
7685
      raise errors.OpPrereqError("The specified node is the primary node of"
7686
                                 " the instance.", errors.ECODE_INVAL)
7687

    
7688
    if remote_node == secondary_node:
7689
      raise errors.OpPrereqError("The specified node is already the"
7690
                                 " secondary node of the instance.",
7691
                                 errors.ECODE_INVAL)
7692

    
7693
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
7694
                                    constants.REPLACE_DISK_CHG):
7695
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
7696
                                 errors.ECODE_INVAL)
7697

    
7698
    if self.mode == constants.REPLACE_DISK_AUTO:
7699
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
7700
      faulty_secondary = self._FindFaultyDisks(secondary_node)
7701

    
7702
      if faulty_primary and faulty_secondary:
7703
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
7704
                                   " one node and can not be repaired"
7705
                                   " automatically" % self.instance_name,
7706
                                   errors.ECODE_STATE)
7707

    
7708
      if faulty_primary:
7709
        self.disks = faulty_primary
7710
        self.target_node = instance.primary_node
7711
        self.other_node = secondary_node
7712
        check_nodes = [self.target_node, self.other_node]
7713
      elif faulty_secondary:
7714
        self.disks = faulty_secondary
7715
        self.target_node = secondary_node
7716
        self.other_node = instance.primary_node
7717
        check_nodes = [self.target_node, self.other_node]
7718
      else:
7719
        self.disks = []
7720
        check_nodes = []
7721

    
7722
    else:
7723
      # Non-automatic modes
7724
      if self.mode == constants.REPLACE_DISK_PRI:
7725
        self.target_node = instance.primary_node
7726
        self.other_node = secondary_node
7727
        check_nodes = [self.target_node, self.other_node]
7728

    
7729
      elif self.mode == constants.REPLACE_DISK_SEC:
7730
        self.target_node = secondary_node
7731
        self.other_node = instance.primary_node
7732
        check_nodes = [self.target_node, self.other_node]
7733

    
7734
      elif self.mode == constants.REPLACE_DISK_CHG:
7735
        self.new_node = remote_node
7736
        self.other_node = instance.primary_node
7737
        self.target_node = secondary_node
7738
        check_nodes = [self.new_node, self.other_node]
7739

    
7740
        _CheckNodeNotDrained(self.lu, remote_node)
7741

    
7742
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
7743
        assert old_node_info is not None
7744
        if old_node_info.offline and not self.early_release:
7745
          # doesn't make sense to delay the release
7746
          self.early_release = True
7747
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
7748
                          " early-release mode", secondary_node)
7749

    
7750
      else:
7751
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
7752
                                     self.mode)
7753

    
7754
      # If not specified all disks should be replaced
7755
      if not self.disks:
7756
        self.disks = range(len(self.instance.disks))
7757

    
7758
    for node in check_nodes:
7759
      _CheckNodeOnline(self.lu, node)
7760

    
7761
    # Check whether disks are valid
7762
    for disk_idx in self.disks:
7763
      instance.FindDisk(disk_idx)
7764

    
7765
    # Get secondary node IP addresses
7766
    node_2nd_ip = {}
7767

    
7768
    for node_name in [self.target_node, self.other_node, self.new_node]:
7769
      if node_name is not None:
7770
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
7771

    
7772
    self.node_secondary_ip = node_2nd_ip
7773

    
7774
  def Exec(self, feedback_fn):
7775
    """Execute disk replacement.
7776

7777
    This dispatches the disk replacement to the appropriate handler.
7778

7779
    """
7780
    if self.delay_iallocator:
7781
      self._CheckPrereq2()
7782

    
7783
    if not self.disks:
7784
      feedback_fn("No disks need replacement")
7785
      return
7786

    
7787
    feedback_fn("Replacing disk(s) %s for %s" %
7788
                (utils.CommaJoin(self.disks), self.instance.name))
7789

    
7790
    activate_disks = (not self.instance.admin_up)
7791

    
7792
    # Activate the instance disks if we're replacing them on a down instance
7793
    if activate_disks:
7794
      _StartInstanceDisks(self.lu, self.instance, True)
7795

    
7796
    try:
7797
      # Should we replace the secondary node?
7798
      if self.new_node is not None:
7799
        fn = self._ExecDrbd8Secondary
7800
      else:
7801
        fn = self._ExecDrbd8DiskOnly
7802

    
7803
      return fn(feedback_fn)
7804

    
7805
    finally:
7806
      # Deactivate the instance disks if we're replacing them on a
7807
      # down instance
7808
      if activate_disks:
7809
        _SafeShutdownInstanceDisks(self.lu, self.instance)
7810

    
7811
  def _CheckVolumeGroup(self, nodes):
7812
    self.lu.LogInfo("Checking volume groups")
7813

    
7814
    vgname = self.cfg.GetVGName()
7815

    
7816
    # Make sure volume group exists on all involved nodes
7817
    results = self.rpc.call_vg_list(nodes)
7818
    if not results:
7819
      raise errors.OpExecError("Can't list volume groups on the nodes")
7820

    
7821
    for node in nodes:
7822
      res = results[node]
7823
      res.Raise("Error checking node %s" % node)
7824
      if vgname not in res.payload:
7825
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
7826
                                 (vgname, node))
7827

    
7828
  def _CheckDisksExistence(self, nodes):
7829
    # Check disk existence
7830
    for idx, dev in enumerate(self.instance.disks):
7831
      if idx not in self.disks:
7832
        continue
7833

    
7834
      for node in nodes:
7835
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
7836
        self.cfg.SetDiskID(dev, node)
7837

    
7838
        result = self.rpc.call_blockdev_find(node, dev)
7839

    
7840
        msg = result.fail_msg
7841
        if msg or not result.payload:
7842
          if not msg:
7843
            msg = "disk not found"
7844
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
7845
                                   (idx, node, msg))
7846

    
7847
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
7848
    for idx, dev in enumerate(self.instance.disks):
7849
      if idx not in self.disks:
7850
        continue
7851

    
7852
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
7853
                      (idx, node_name))
7854

    
7855
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
7856
                                   ldisk=ldisk):
7857
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
7858
                                 " replace disks for instance %s" %
7859
                                 (node_name, self.instance.name))
7860

    
7861
  def _CreateNewStorage(self, node_name):
7862
    vgname = self.cfg.GetVGName()
7863
    iv_names = {}
7864

    
7865
    for idx, dev in enumerate(self.instance.disks):
7866
      if idx not in self.disks:
7867
        continue
7868

    
7869
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
7870

    
7871
      self.cfg.SetDiskID(dev, node_name)
7872

    
7873
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
7874
      names = _GenerateUniqueNames(self.lu, lv_names)
7875

    
7876
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
7877
                             logical_id=(vgname, names[0]))
7878
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7879
                             logical_id=(vgname, names[1]))
7880

    
7881
      new_lvs = [lv_data, lv_meta]
7882
      old_lvs = dev.children
7883
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
7884

    
7885
      # we pass force_create=True to force the LVM creation
7886
      for new_lv in new_lvs:
7887
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
7888
                        _GetInstanceInfoText(self.instance), False)
7889

    
7890
    return iv_names
7891

    
7892
  def _CheckDevices(self, node_name, iv_names):
7893
    for name, (dev, _, _) in iv_names.iteritems():
7894
      self.cfg.SetDiskID(dev, node_name)
7895

    
7896
      result = self.rpc.call_blockdev_find(node_name, dev)
7897

    
7898
      msg = result.fail_msg
7899
      if msg or not result.payload:
7900
        if not msg:
7901
          msg = "disk not found"
7902
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
7903
                                 (name, msg))
7904

    
7905
      if result.payload.is_degraded:
7906
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
7907

    
7908
  def _RemoveOldStorage(self, node_name, iv_names):
7909
    for name, (_, old_lvs, _) in iv_names.iteritems():
7910
      self.lu.LogInfo("Remove logical volumes for %s" % name)
7911

    
7912
      for lv in old_lvs:
7913
        self.cfg.SetDiskID(lv, node_name)
7914

    
7915
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
7916
        if msg:
7917
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
7918
                             hint="remove unused LVs manually")
7919

    
7920
  def _ReleaseNodeLock(self, node_name):
7921
    """Releases the lock for a given node."""
7922
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
7923

    
7924
  def _ExecDrbd8DiskOnly(self, feedback_fn):
7925
    """Replace a disk on the primary or secondary for DRBD 8.
7926

7927
    The algorithm for replace is quite complicated:
7928

7929
      1. for each disk to be replaced:
7930

7931
        1. create new LVs on the target node with unique names
7932
        1. detach old LVs from the drbd device
7933
        1. rename old LVs to name_replaced.<time_t>
7934
        1. rename new LVs to old LVs
7935
        1. attach the new LVs (with the old names now) to the drbd device
7936

7937
      1. wait for sync across all devices
7938

7939
      1. for each modified disk:
7940

7941
        1. remove old LVs (which have the name name_replaces.<time_t>)
7942

7943
    Failures are not very well handled.
7944

7945
    """
7946
    steps_total = 6
7947

    
7948
    # Step: check device activation
7949
    self.lu.LogStep(1, steps_total, "Check device existence")
7950
    self._CheckDisksExistence([self.other_node, self.target_node])
7951
    self._CheckVolumeGroup([self.target_node, self.other_node])
7952

    
7953
    # Step: check other node consistency
7954
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7955
    self._CheckDisksConsistency(self.other_node,
7956
                                self.other_node == self.instance.primary_node,
7957
                                False)
7958

    
7959
    # Step: create new storage
7960
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7961
    iv_names = self._CreateNewStorage(self.target_node)
7962

    
7963
    # Step: for each lv, detach+rename*2+attach
7964
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7965
    for dev, old_lvs, new_lvs in iv_names.itervalues():
7966
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
7967

    
7968
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
7969
                                                     old_lvs)
7970
      result.Raise("Can't detach drbd from local storage on node"
7971
                   " %s for device %s" % (self.target_node, dev.iv_name))
7972
      #dev.children = []
7973
      #cfg.Update(instance)
7974

    
7975
      # ok, we created the new LVs, so now we know we have the needed
7976
      # storage; as such, we proceed on the target node to rename
7977
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
7978
      # using the assumption that logical_id == physical_id (which in
7979
      # turn is the unique_id on that node)
7980

    
7981
      # FIXME(iustin): use a better name for the replaced LVs
7982
      temp_suffix = int(time.time())
7983
      ren_fn = lambda d, suff: (d.physical_id[0],
7984
                                d.physical_id[1] + "_replaced-%s" % suff)
7985

    
7986
      # Build the rename list based on what LVs exist on the node
7987
      rename_old_to_new = []
7988
      for to_ren in old_lvs:
7989
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
7990
        if not result.fail_msg and result.payload:
7991
          # device exists
7992
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
7993

    
7994
      self.lu.LogInfo("Renaming the old LVs on the target node")
7995
      result = self.rpc.call_blockdev_rename(self.target_node,
7996
                                             rename_old_to_new)
7997
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
7998

    
7999
      # Now we rename the new LVs to the old LVs
8000
      self.lu.LogInfo("Renaming the new LVs on the target node")
8001
      rename_new_to_old = [(new, old.physical_id)
8002
                           for old, new in zip(old_lvs, new_lvs)]
8003
      result = self.rpc.call_blockdev_rename(self.target_node,
8004
                                             rename_new_to_old)
8005
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
8006

    
8007
      for old, new in zip(old_lvs, new_lvs):
8008
        new.logical_id = old.logical_id
8009
        self.cfg.SetDiskID(new, self.target_node)
8010

    
8011
      for disk in old_lvs:
8012
        disk.logical_id = ren_fn(disk, temp_suffix)
8013
        self.cfg.SetDiskID(disk, self.target_node)
8014

    
8015
      # Now that the new lvs have the old name, we can add them to the device
8016
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
8017
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
8018
                                                  new_lvs)
8019
      msg = result.fail_msg
8020
      if msg:
8021
        for new_lv in new_lvs:
8022
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
8023
                                               new_lv).fail_msg
8024
          if msg2:
8025
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
8026
                               hint=("cleanup manually the unused logical"
8027
                                     "volumes"))
8028
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8029

    
8030
      dev.children = new_lvs
8031

    
8032
      self.cfg.Update(self.instance, feedback_fn)
8033

    
8034
    cstep = 5
8035
    if 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
      # WARNING: we release both node locks here, do not do other RPCs
8040
      # than WaitForSync to the primary node
8041
      self._ReleaseNodeLock([self.target_node, self.other_node])
8042

    
8043
    # Wait for sync
8044
    # This can fail as the old devices are degraded and _WaitForSync
8045
    # does a combined result over all disks, so we don't check its return value
8046
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8047
    cstep += 1
8048
    _WaitForSync(self.lu, self.instance)
8049

    
8050
    # Check all devices manually
8051
    self._CheckDevices(self.instance.primary_node, iv_names)
8052

    
8053
    # Step: remove old storage
8054
    if not self.early_release:
8055
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8056
      cstep += 1
8057
      self._RemoveOldStorage(self.target_node, iv_names)
8058

    
8059
  def _ExecDrbd8Secondary(self, feedback_fn):
8060
    """Replace the secondary node for DRBD 8.
8061

8062
    The algorithm for replace is quite complicated:
8063
      - for all disks of the instance:
8064
        - create new LVs on the new node with same names
8065
        - shutdown the drbd device on the old secondary
8066
        - disconnect the drbd network on the primary
8067
        - create the drbd device on the new secondary
8068
        - network attach the drbd on the primary, using an artifice:
8069
          the drbd code for Attach() will connect to the network if it
8070
          finds a device which is connected to the good local disks but
8071
          not network enabled
8072
      - wait for sync across all devices
8073
      - remove all disks from the old secondary
8074

8075
    Failures are not very well handled.
8076

8077
    """
8078
    steps_total = 6
8079

    
8080
    # Step: check device activation
8081
    self.lu.LogStep(1, steps_total, "Check device existence")
8082
    self._CheckDisksExistence([self.instance.primary_node])
8083
    self._CheckVolumeGroup([self.instance.primary_node])
8084

    
8085
    # Step: check other node consistency
8086
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8087
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8088

    
8089
    # Step: create new storage
8090
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8091
    for idx, dev in enumerate(self.instance.disks):
8092
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8093
                      (self.new_node, idx))
8094
      # we pass force_create=True to force LVM creation
8095
      for new_lv in dev.children:
8096
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8097
                        _GetInstanceInfoText(self.instance), False)
8098

    
8099
    # Step 4: dbrd minors and drbd setups changes
8100
    # after this, we must manually remove the drbd minors on both the
8101
    # error and the success paths
8102
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8103
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8104
                                         for dev in self.instance.disks],
8105
                                        self.instance.name)
8106
    logging.debug("Allocated minors %r", minors)
8107

    
8108
    iv_names = {}
8109
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8110
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8111
                      (self.new_node, idx))
8112
      # create new devices on new_node; note that we create two IDs:
8113
      # one without port, so the drbd will be activated without
8114
      # networking information on the new node at this stage, and one
8115
      # with network, for the latter activation in step 4
8116
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8117
      if self.instance.primary_node == o_node1:
8118
        p_minor = o_minor1
8119
      else:
8120
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8121
        p_minor = o_minor2
8122

    
8123
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8124
                      p_minor, new_minor, o_secret)
8125
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8126
                    p_minor, new_minor, o_secret)
8127

    
8128
      iv_names[idx] = (dev, dev.children, new_net_id)
8129
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8130
                    new_net_id)
8131
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8132
                              logical_id=new_alone_id,
8133
                              children=dev.children,
8134
                              size=dev.size)
8135
      try:
8136
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8137
                              _GetInstanceInfoText(self.instance), False)
8138
      except errors.GenericError:
8139
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8140
        raise
8141

    
8142
    # We have new devices, shutdown the drbd on the old secondary
8143
    for idx, dev in enumerate(self.instance.disks):
8144
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8145
      self.cfg.SetDiskID(dev, self.target_node)
8146
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8147
      if msg:
8148
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8149
                           "node: %s" % (idx, msg),
8150
                           hint=("Please cleanup this device manually as"
8151
                                 " soon as possible"))
8152

    
8153
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8154
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8155
                                               self.node_secondary_ip,
8156
                                               self.instance.disks)\
8157
                                              [self.instance.primary_node]
8158

    
8159
    msg = result.fail_msg
8160
    if msg:
8161
      # detaches didn't succeed (unlikely)
8162
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8163
      raise errors.OpExecError("Can't detach the disks from the network on"
8164
                               " old node: %s" % (msg,))
8165

    
8166
    # if we managed to detach at least one, we update all the disks of
8167
    # the instance to point to the new secondary
8168
    self.lu.LogInfo("Updating instance configuration")
8169
    for dev, _, new_logical_id in iv_names.itervalues():
8170
      dev.logical_id = new_logical_id
8171
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8172

    
8173
    self.cfg.Update(self.instance, feedback_fn)
8174

    
8175
    # and now perform the drbd attach
8176
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8177
                    " (standalone => connected)")
8178
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8179
                                            self.new_node],
8180
                                           self.node_secondary_ip,
8181
                                           self.instance.disks,
8182
                                           self.instance.name,
8183
                                           False)
8184
    for to_node, to_result in result.items():
8185
      msg = to_result.fail_msg
8186
      if msg:
8187
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8188
                           to_node, msg,
8189
                           hint=("please do a gnt-instance info to see the"
8190
                                 " status of disks"))
8191
    cstep = 5
8192
    if self.early_release:
8193
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8194
      cstep += 1
8195
      self._RemoveOldStorage(self.target_node, iv_names)
8196
      # WARNING: we release all node locks here, do not do other RPCs
8197
      # than WaitForSync to the primary node
8198
      self._ReleaseNodeLock([self.instance.primary_node,
8199
                             self.target_node,
8200
                             self.new_node])
8201

    
8202
    # Wait for sync
8203
    # This can fail as the old devices are degraded and _WaitForSync
8204
    # does a combined result over all disks, so we don't check its return value
8205
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8206
    cstep += 1
8207
    _WaitForSync(self.lu, self.instance)
8208

    
8209
    # Check all devices manually
8210
    self._CheckDevices(self.instance.primary_node, iv_names)
8211

    
8212
    # Step: remove old storage
8213
    if not self.early_release:
8214
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8215
      self._RemoveOldStorage(self.target_node, iv_names)
8216

    
8217

    
8218
class LURepairNodeStorage(NoHooksLU):
8219
  """Repairs the volume group on a node.
8220

8221
  """
8222
  _OP_PARAMS = [
8223
    _PNodeName,
8224
    ("storage_type", _NoDefault, _CheckStorageType),
8225
    ("name", _NoDefault, _TNonEmptyString),
8226
    ("ignore_consistency", False, _TBool),
8227
    ]
8228
  REQ_BGL = False
8229

    
8230
  def CheckArguments(self):
8231
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8232

    
8233
    storage_type = self.op.storage_type
8234

    
8235
    if (constants.SO_FIX_CONSISTENCY not in
8236
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8237
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8238
                                 " repaired" % storage_type,
8239
                                 errors.ECODE_INVAL)
8240

    
8241
  def ExpandNames(self):
8242
    self.needed_locks = {
8243
      locking.LEVEL_NODE: [self.op.node_name],
8244
      }
8245

    
8246
  def _CheckFaultyDisks(self, instance, node_name):
8247
    """Ensure faulty disks abort the opcode or at least warn."""
8248
    try:
8249
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8250
                                  node_name, True):
8251
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8252
                                   " node '%s'" % (instance.name, node_name),
8253
                                   errors.ECODE_STATE)
8254
    except errors.OpPrereqError, err:
8255
      if self.op.ignore_consistency:
8256
        self.proc.LogWarning(str(err.args[0]))
8257
      else:
8258
        raise
8259

    
8260
  def CheckPrereq(self):
8261
    """Check prerequisites.
8262

8263
    """
8264
    # Check whether any instance on this node has faulty disks
8265
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8266
      if not inst.admin_up:
8267
        continue
8268
      check_nodes = set(inst.all_nodes)
8269
      check_nodes.discard(self.op.node_name)
8270
      for inst_node_name in check_nodes:
8271
        self._CheckFaultyDisks(inst, inst_node_name)
8272

    
8273
  def Exec(self, feedback_fn):
8274
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8275
                (self.op.name, self.op.node_name))
8276

    
8277
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8278
    result = self.rpc.call_storage_execute(self.op.node_name,
8279
                                           self.op.storage_type, st_args,
8280
                                           self.op.name,
8281
                                           constants.SO_FIX_CONSISTENCY)
8282
    result.Raise("Failed to repair storage unit '%s' on %s" %
8283
                 (self.op.name, self.op.node_name))
8284

    
8285

    
8286
class LUNodeEvacuationStrategy(NoHooksLU):
8287
  """Computes the node evacuation strategy.
8288

8289
  """
8290
  _OP_PARAMS = [
8291
    ("nodes", _NoDefault, _TListOf(_TNonEmptyString)),
8292
    ("remote_node", None, _TMaybeString),
8293
    ("iallocator", None, _TMaybeString),
8294
    ]
8295
  REQ_BGL = False
8296

    
8297
  def CheckArguments(self):
8298
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8299

    
8300
  def ExpandNames(self):
8301
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8302
    self.needed_locks = locks = {}
8303
    if self.op.remote_node is None:
8304
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8305
    else:
8306
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8307
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8308

    
8309
  def Exec(self, feedback_fn):
8310
    if self.op.remote_node is not None:
8311
      instances = []
8312
      for node in self.op.nodes:
8313
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8314
      result = []
8315
      for i in instances:
8316
        if i.primary_node == self.op.remote_node:
8317
          raise errors.OpPrereqError("Node %s is the primary node of"
8318
                                     " instance %s, cannot use it as"
8319
                                     " secondary" %
8320
                                     (self.op.remote_node, i.name),
8321
                                     errors.ECODE_INVAL)
8322
        result.append([i.name, self.op.remote_node])
8323
    else:
8324
      ial = IAllocator(self.cfg, self.rpc,
8325
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8326
                       evac_nodes=self.op.nodes)
8327
      ial.Run(self.op.iallocator, validate=True)
8328
      if not ial.success:
8329
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8330
                                 errors.ECODE_NORES)
8331
      result = ial.result
8332
    return result
8333

    
8334

    
8335
class LUGrowDisk(LogicalUnit):
8336
  """Grow a disk of an instance.
8337

8338
  """
8339
  HPATH = "disk-grow"
8340
  HTYPE = constants.HTYPE_INSTANCE
8341
  _OP_PARAMS = [
8342
    _PInstanceName,
8343
    ("disk", _NoDefault, _TInt),
8344
    ("amount", _NoDefault, _TInt),
8345
    ("wait_for_sync", True, _TBool),
8346
    ]
8347
  REQ_BGL = False
8348

    
8349
  def ExpandNames(self):
8350
    self._ExpandAndLockInstance()
8351
    self.needed_locks[locking.LEVEL_NODE] = []
8352
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8353

    
8354
  def DeclareLocks(self, level):
8355
    if level == locking.LEVEL_NODE:
8356
      self._LockInstancesNodes()
8357

    
8358
  def BuildHooksEnv(self):
8359
    """Build hooks env.
8360

8361
    This runs on the master, the primary and all the secondaries.
8362

8363
    """
8364
    env = {
8365
      "DISK": self.op.disk,
8366
      "AMOUNT": self.op.amount,
8367
      }
8368
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8369
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8370
    return env, nl, nl
8371

    
8372
  def CheckPrereq(self):
8373
    """Check prerequisites.
8374

8375
    This checks that the instance is in the cluster.
8376

8377
    """
8378
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8379
    assert instance is not None, \
8380
      "Cannot retrieve locked instance %s" % self.op.instance_name
8381
    nodenames = list(instance.all_nodes)
8382
    for node in nodenames:
8383
      _CheckNodeOnline(self, node)
8384

    
8385
    self.instance = instance
8386

    
8387
    if instance.disk_template not in constants.DTS_GROWABLE:
8388
      raise errors.OpPrereqError("Instance's disk layout does not support"
8389
                                 " growing.", errors.ECODE_INVAL)
8390

    
8391
    self.disk = instance.FindDisk(self.op.disk)
8392

    
8393
    if instance.disk_template != constants.DT_FILE:
8394
      # TODO: check the free disk space for file, when that feature will be
8395
      # supported
8396
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
8397

    
8398
  def Exec(self, feedback_fn):
8399
    """Execute disk grow.
8400

8401
    """
8402
    instance = self.instance
8403
    disk = self.disk
8404

    
8405
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8406
    if not disks_ok:
8407
      raise errors.OpExecError("Cannot activate block device to grow")
8408

    
8409
    for node in instance.all_nodes:
8410
      self.cfg.SetDiskID(disk, node)
8411
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8412
      result.Raise("Grow request failed to node %s" % node)
8413

    
8414
      # TODO: Rewrite code to work properly
8415
      # DRBD goes into sync mode for a short amount of time after executing the
8416
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8417
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8418
      # time is a work-around.
8419
      time.sleep(5)
8420

    
8421
    disk.RecordGrow(self.op.amount)
8422
    self.cfg.Update(instance, feedback_fn)
8423
    if self.op.wait_for_sync:
8424
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8425
      if disk_abort:
8426
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8427
                             " status.\nPlease check the instance.")
8428
      if not instance.admin_up:
8429
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8430
    elif not instance.admin_up:
8431
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8432
                           " not supposed to be running because no wait for"
8433
                           " sync mode was requested.")
8434

    
8435

    
8436
class LUQueryInstanceData(NoHooksLU):
8437
  """Query runtime instance data.
8438

8439
  """
8440
  _OP_PARAMS = [
8441
    ("instances", _EmptyList, _TListOf(_TNonEmptyString)),
8442
    ("static", False, _TBool),
8443
    ]
8444
  REQ_BGL = False
8445

    
8446
  def ExpandNames(self):
8447
    self.needed_locks = {}
8448
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8449

    
8450
    if self.op.instances:
8451
      self.wanted_names = []
8452
      for name in self.op.instances:
8453
        full_name = _ExpandInstanceName(self.cfg, name)
8454
        self.wanted_names.append(full_name)
8455
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8456
    else:
8457
      self.wanted_names = None
8458
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8459

    
8460
    self.needed_locks[locking.LEVEL_NODE] = []
8461
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8462

    
8463
  def DeclareLocks(self, level):
8464
    if level == locking.LEVEL_NODE:
8465
      self._LockInstancesNodes()
8466

    
8467
  def CheckPrereq(self):
8468
    """Check prerequisites.
8469

8470
    This only checks the optional instance list against the existing names.
8471

8472
    """
8473
    if self.wanted_names is None:
8474
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8475

    
8476
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8477
                             in self.wanted_names]
8478

    
8479
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8480
    """Returns the status of a block device
8481

8482
    """
8483
    if self.op.static or not node:
8484
      return None
8485

    
8486
    self.cfg.SetDiskID(dev, node)
8487

    
8488
    result = self.rpc.call_blockdev_find(node, dev)
8489
    if result.offline:
8490
      return None
8491

    
8492
    result.Raise("Can't compute disk status for %s" % instance_name)
8493

    
8494
    status = result.payload
8495
    if status is None:
8496
      return None
8497

    
8498
    return (status.dev_path, status.major, status.minor,
8499
            status.sync_percent, status.estimated_time,
8500
            status.is_degraded, status.ldisk_status)
8501

    
8502
  def _ComputeDiskStatus(self, instance, snode, dev):
8503
    """Compute block device status.
8504

8505
    """
8506
    if dev.dev_type in constants.LDS_DRBD:
8507
      # we change the snode then (otherwise we use the one passed in)
8508
      if dev.logical_id[0] == instance.primary_node:
8509
        snode = dev.logical_id[1]
8510
      else:
8511
        snode = dev.logical_id[0]
8512

    
8513
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8514
                                              instance.name, dev)
8515
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8516

    
8517
    if dev.children:
8518
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8519
                      for child in dev.children]
8520
    else:
8521
      dev_children = []
8522

    
8523
    data = {
8524
      "iv_name": dev.iv_name,
8525
      "dev_type": dev.dev_type,
8526
      "logical_id": dev.logical_id,
8527
      "physical_id": dev.physical_id,
8528
      "pstatus": dev_pstatus,
8529
      "sstatus": dev_sstatus,
8530
      "children": dev_children,
8531
      "mode": dev.mode,
8532
      "size": dev.size,
8533
      }
8534

    
8535
    return data
8536

    
8537
  def Exec(self, feedback_fn):
8538
    """Gather and return data"""
8539
    result = {}
8540

    
8541
    cluster = self.cfg.GetClusterInfo()
8542

    
8543
    for instance in self.wanted_instances:
8544
      if not self.op.static:
8545
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8546
                                                  instance.name,
8547
                                                  instance.hypervisor)
8548
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8549
        remote_info = remote_info.payload
8550
        if remote_info and "state" in remote_info:
8551
          remote_state = "up"
8552
        else:
8553
          remote_state = "down"
8554
      else:
8555
        remote_state = None
8556
      if instance.admin_up:
8557
        config_state = "up"
8558
      else:
8559
        config_state = "down"
8560

    
8561
      disks = [self._ComputeDiskStatus(instance, None, device)
8562
               for device in instance.disks]
8563

    
8564
      idict = {
8565
        "name": instance.name,
8566
        "config_state": config_state,
8567
        "run_state": remote_state,
8568
        "pnode": instance.primary_node,
8569
        "snodes": instance.secondary_nodes,
8570
        "os": instance.os,
8571
        # this happens to be the same format used for hooks
8572
        "nics": _NICListToTuple(self, instance.nics),
8573
        "disk_template": instance.disk_template,
8574
        "disks": disks,
8575
        "hypervisor": instance.hypervisor,
8576
        "network_port": instance.network_port,
8577
        "hv_instance": instance.hvparams,
8578
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8579
        "be_instance": instance.beparams,
8580
        "be_actual": cluster.FillBE(instance),
8581
        "os_instance": instance.osparams,
8582
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8583
        "serial_no": instance.serial_no,
8584
        "mtime": instance.mtime,
8585
        "ctime": instance.ctime,
8586
        "uuid": instance.uuid,
8587
        }
8588

    
8589
      result[instance.name] = idict
8590

    
8591
    return result
8592

    
8593

    
8594
class LUSetInstanceParams(LogicalUnit):
8595
  """Modifies an instances's parameters.
8596

8597
  """
8598
  HPATH = "instance-modify"
8599
  HTYPE = constants.HTYPE_INSTANCE
8600
  _OP_PARAMS = [
8601
    _PInstanceName,
8602
    ("nics", _EmptyList, _TList),
8603
    ("disks", _EmptyList, _TList),
8604
    ("beparams", _EmptyDict, _TDict),
8605
    ("hvparams", _EmptyDict, _TDict),
8606
    ("disk_template", None, _TMaybeString),
8607
    ("remote_node", None, _TMaybeString),
8608
    ("os_name", None, _TMaybeString),
8609
    ("force_variant", False, _TBool),
8610
    ("osparams", None, _TOr(_TDict, _TNone)),
8611
    _PForce,
8612
    ]
8613
  REQ_BGL = False
8614

    
8615
  def CheckArguments(self):
8616
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8617
            self.op.hvparams or self.op.beparams or self.op.os_name):
8618
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8619

    
8620
    if self.op.hvparams:
8621
      _CheckGlobalHvParams(self.op.hvparams)
8622

    
8623
    # Disk validation
8624
    disk_addremove = 0
8625
    for disk_op, disk_dict in self.op.disks:
8626
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8627
      if disk_op == constants.DDM_REMOVE:
8628
        disk_addremove += 1
8629
        continue
8630
      elif disk_op == constants.DDM_ADD:
8631
        disk_addremove += 1
8632
      else:
8633
        if not isinstance(disk_op, int):
8634
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8635
        if not isinstance(disk_dict, dict):
8636
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8637
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8638

    
8639
      if disk_op == constants.DDM_ADD:
8640
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8641
        if mode not in constants.DISK_ACCESS_SET:
8642
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8643
                                     errors.ECODE_INVAL)
8644
        size = disk_dict.get('size', None)
8645
        if size is None:
8646
          raise errors.OpPrereqError("Required disk parameter size missing",
8647
                                     errors.ECODE_INVAL)
8648
        try:
8649
          size = int(size)
8650
        except (TypeError, ValueError), err:
8651
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8652
                                     str(err), errors.ECODE_INVAL)
8653
        disk_dict['size'] = size
8654
      else:
8655
        # modification of disk
8656
        if 'size' in disk_dict:
8657
          raise errors.OpPrereqError("Disk size change not possible, use"
8658
                                     " grow-disk", errors.ECODE_INVAL)
8659

    
8660
    if disk_addremove > 1:
8661
      raise errors.OpPrereqError("Only one disk add or remove operation"
8662
                                 " supported at a time", errors.ECODE_INVAL)
8663

    
8664
    if self.op.disks and self.op.disk_template is not None:
8665
      raise errors.OpPrereqError("Disk template conversion and other disk"
8666
                                 " changes not supported at the same time",
8667
                                 errors.ECODE_INVAL)
8668

    
8669
    if self.op.disk_template:
8670
      _CheckDiskTemplate(self.op.disk_template)
8671
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
8672
          self.op.remote_node is None):
8673
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
8674
                                   " one requires specifying a secondary node",
8675
                                   errors.ECODE_INVAL)
8676

    
8677
    # NIC validation
8678
    nic_addremove = 0
8679
    for nic_op, nic_dict in self.op.nics:
8680
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
8681
      if nic_op == constants.DDM_REMOVE:
8682
        nic_addremove += 1
8683
        continue
8684
      elif nic_op == constants.DDM_ADD:
8685
        nic_addremove += 1
8686
      else:
8687
        if not isinstance(nic_op, int):
8688
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
8689
        if not isinstance(nic_dict, dict):
8690
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
8691
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8692

    
8693
      # nic_dict should be a dict
8694
      nic_ip = nic_dict.get('ip', None)
8695
      if nic_ip is not None:
8696
        if nic_ip.lower() == constants.VALUE_NONE:
8697
          nic_dict['ip'] = None
8698
        else:
8699
          if not netutils.IP4Address.IsValid(nic_ip):
8700
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
8701
                                       errors.ECODE_INVAL)
8702

    
8703
      nic_bridge = nic_dict.get('bridge', None)
8704
      nic_link = nic_dict.get('link', None)
8705
      if nic_bridge and nic_link:
8706
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
8707
                                   " at the same time", errors.ECODE_INVAL)
8708
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
8709
        nic_dict['bridge'] = None
8710
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
8711
        nic_dict['link'] = None
8712

    
8713
      if nic_op == constants.DDM_ADD:
8714
        nic_mac = nic_dict.get('mac', None)
8715
        if nic_mac is None:
8716
          nic_dict['mac'] = constants.VALUE_AUTO
8717

    
8718
      if 'mac' in nic_dict:
8719
        nic_mac = nic_dict['mac']
8720
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8721
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
8722

    
8723
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
8724
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
8725
                                     " modifying an existing nic",
8726
                                     errors.ECODE_INVAL)
8727

    
8728
    if nic_addremove > 1:
8729
      raise errors.OpPrereqError("Only one NIC add or remove operation"
8730
                                 " supported at a time", errors.ECODE_INVAL)
8731

    
8732
  def ExpandNames(self):
8733
    self._ExpandAndLockInstance()
8734
    self.needed_locks[locking.LEVEL_NODE] = []
8735
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8736

    
8737
  def DeclareLocks(self, level):
8738
    if level == locking.LEVEL_NODE:
8739
      self._LockInstancesNodes()
8740
      if self.op.disk_template and self.op.remote_node:
8741
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8742
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
8743

    
8744
  def BuildHooksEnv(self):
8745
    """Build hooks env.
8746

8747
    This runs on the master, primary and secondaries.
8748

8749
    """
8750
    args = dict()
8751
    if constants.BE_MEMORY in self.be_new:
8752
      args['memory'] = self.be_new[constants.BE_MEMORY]
8753
    if constants.BE_VCPUS in self.be_new:
8754
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
8755
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
8756
    # information at all.
8757
    if self.op.nics:
8758
      args['nics'] = []
8759
      nic_override = dict(self.op.nics)
8760
      for idx, nic in enumerate(self.instance.nics):
8761
        if idx in nic_override:
8762
          this_nic_override = nic_override[idx]
8763
        else:
8764
          this_nic_override = {}
8765
        if 'ip' in this_nic_override:
8766
          ip = this_nic_override['ip']
8767
        else:
8768
          ip = nic.ip
8769
        if 'mac' in this_nic_override:
8770
          mac = this_nic_override['mac']
8771
        else:
8772
          mac = nic.mac
8773
        if idx in self.nic_pnew:
8774
          nicparams = self.nic_pnew[idx]
8775
        else:
8776
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
8777
        mode = nicparams[constants.NIC_MODE]
8778
        link = nicparams[constants.NIC_LINK]
8779
        args['nics'].append((ip, mac, mode, link))
8780
      if constants.DDM_ADD in nic_override:
8781
        ip = nic_override[constants.DDM_ADD].get('ip', None)
8782
        mac = nic_override[constants.DDM_ADD]['mac']
8783
        nicparams = self.nic_pnew[constants.DDM_ADD]
8784
        mode = nicparams[constants.NIC_MODE]
8785
        link = nicparams[constants.NIC_LINK]
8786
        args['nics'].append((ip, mac, mode, link))
8787
      elif constants.DDM_REMOVE in nic_override:
8788
        del args['nics'][-1]
8789

    
8790
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
8791
    if self.op.disk_template:
8792
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
8793
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8794
    return env, nl, nl
8795

    
8796
  def CheckPrereq(self):
8797
    """Check prerequisites.
8798

8799
    This only checks the instance list against the existing names.
8800

8801
    """
8802
    # checking the new params on the primary/secondary nodes
8803

    
8804
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8805
    cluster = self.cluster = self.cfg.GetClusterInfo()
8806
    assert self.instance is not None, \
8807
      "Cannot retrieve locked instance %s" % self.op.instance_name
8808
    pnode = instance.primary_node
8809
    nodelist = list(instance.all_nodes)
8810

    
8811
    # OS change
8812
    if self.op.os_name and not self.op.force:
8813
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
8814
                      self.op.force_variant)
8815
      instance_os = self.op.os_name
8816
    else:
8817
      instance_os = instance.os
8818

    
8819
    if self.op.disk_template:
8820
      if instance.disk_template == self.op.disk_template:
8821
        raise errors.OpPrereqError("Instance already has disk template %s" %
8822
                                   instance.disk_template, errors.ECODE_INVAL)
8823

    
8824
      if (instance.disk_template,
8825
          self.op.disk_template) not in self._DISK_CONVERSIONS:
8826
        raise errors.OpPrereqError("Unsupported disk template conversion from"
8827
                                   " %s to %s" % (instance.disk_template,
8828
                                                  self.op.disk_template),
8829
                                   errors.ECODE_INVAL)
8830
      _CheckInstanceDown(self, instance, "cannot change disk template")
8831
      if self.op.disk_template in constants.DTS_NET_MIRROR:
8832
        if self.op.remote_node == pnode:
8833
          raise errors.OpPrereqError("Given new secondary node %s is the same"
8834
                                     " as the primary node of the instance" %
8835
                                     self.op.remote_node, errors.ECODE_STATE)
8836
        _CheckNodeOnline(self, self.op.remote_node)
8837
        _CheckNodeNotDrained(self, self.op.remote_node)
8838
        disks = [{"size": d.size} for d in instance.disks]
8839
        required = _ComputeDiskSize(self.op.disk_template, disks)
8840
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
8841

    
8842
    # hvparams processing
8843
    if self.op.hvparams:
8844
      hv_type = instance.hypervisor
8845
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
8846
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
8847
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
8848

    
8849
      # local check
8850
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
8851
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
8852
      self.hv_new = hv_new # the new actual values
8853
      self.hv_inst = i_hvdict # the new dict (without defaults)
8854
    else:
8855
      self.hv_new = self.hv_inst = {}
8856

    
8857
    # beparams processing
8858
    if self.op.beparams:
8859
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
8860
                                   use_none=True)
8861
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
8862
      be_new = cluster.SimpleFillBE(i_bedict)
8863
      self.be_new = be_new # the new actual values
8864
      self.be_inst = i_bedict # the new dict (without defaults)
8865
    else:
8866
      self.be_new = self.be_inst = {}
8867

    
8868
    # osparams processing
8869
    if self.op.osparams:
8870
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
8871
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
8872
      self.os_new = cluster.SimpleFillOS(instance_os, i_osdict)
8873
      self.os_inst = i_osdict # the new dict (without defaults)
8874
    else:
8875
      self.os_new = self.os_inst = {}
8876

    
8877
    self.warn = []
8878

    
8879
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
8880
      mem_check_list = [pnode]
8881
      if be_new[constants.BE_AUTO_BALANCE]:
8882
        # either we changed auto_balance to yes or it was from before
8883
        mem_check_list.extend(instance.secondary_nodes)
8884
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
8885
                                                  instance.hypervisor)
8886
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
8887
                                         instance.hypervisor)
8888
      pninfo = nodeinfo[pnode]
8889
      msg = pninfo.fail_msg
8890
      if msg:
8891
        # Assume the primary node is unreachable and go ahead
8892
        self.warn.append("Can't get info from primary node %s: %s" %
8893
                         (pnode,  msg))
8894
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
8895
        self.warn.append("Node data from primary node %s doesn't contain"
8896
                         " free memory information" % pnode)
8897
      elif instance_info.fail_msg:
8898
        self.warn.append("Can't get instance runtime information: %s" %
8899
                        instance_info.fail_msg)
8900
      else:
8901
        if instance_info.payload:
8902
          current_mem = int(instance_info.payload['memory'])
8903
        else:
8904
          # Assume instance not running
8905
          # (there is a slight race condition here, but it's not very probable,
8906
          # and we have no other way to check)
8907
          current_mem = 0
8908
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
8909
                    pninfo.payload['memory_free'])
8910
        if miss_mem > 0:
8911
          raise errors.OpPrereqError("This change will prevent the instance"
8912
                                     " from starting, due to %d MB of memory"
8913
                                     " missing on its primary node" % miss_mem,
8914
                                     errors.ECODE_NORES)
8915

    
8916
      if be_new[constants.BE_AUTO_BALANCE]:
8917
        for node, nres in nodeinfo.items():
8918
          if node not in instance.secondary_nodes:
8919
            continue
8920
          msg = nres.fail_msg
8921
          if msg:
8922
            self.warn.append("Can't get info from secondary node %s: %s" %
8923
                             (node, msg))
8924
          elif not isinstance(nres.payload.get('memory_free', None), int):
8925
            self.warn.append("Secondary node %s didn't return free"
8926
                             " memory information" % node)
8927
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
8928
            self.warn.append("Not enough memory to failover instance to"
8929
                             " secondary node %s" % node)
8930

    
8931
    # NIC processing
8932
    self.nic_pnew = {}
8933
    self.nic_pinst = {}
8934
    for nic_op, nic_dict in self.op.nics:
8935
      if nic_op == constants.DDM_REMOVE:
8936
        if not instance.nics:
8937
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
8938
                                     errors.ECODE_INVAL)
8939
        continue
8940
      if nic_op != constants.DDM_ADD:
8941
        # an existing nic
8942
        if not instance.nics:
8943
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
8944
                                     " no NICs" % nic_op,
8945
                                     errors.ECODE_INVAL)
8946
        if nic_op < 0 or nic_op >= len(instance.nics):
8947
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
8948
                                     " are 0 to %d" %
8949
                                     (nic_op, len(instance.nics) - 1),
8950
                                     errors.ECODE_INVAL)
8951
        old_nic_params = instance.nics[nic_op].nicparams
8952
        old_nic_ip = instance.nics[nic_op].ip
8953
      else:
8954
        old_nic_params = {}
8955
        old_nic_ip = None
8956

    
8957
      update_params_dict = dict([(key, nic_dict[key])
8958
                                 for key in constants.NICS_PARAMETERS
8959
                                 if key in nic_dict])
8960

    
8961
      if 'bridge' in nic_dict:
8962
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
8963

    
8964
      new_nic_params = _GetUpdatedParams(old_nic_params,
8965
                                         update_params_dict)
8966
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
8967
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
8968
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
8969
      self.nic_pinst[nic_op] = new_nic_params
8970
      self.nic_pnew[nic_op] = new_filled_nic_params
8971
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
8972

    
8973
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
8974
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
8975
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
8976
        if msg:
8977
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
8978
          if self.op.force:
8979
            self.warn.append(msg)
8980
          else:
8981
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
8982
      if new_nic_mode == constants.NIC_MODE_ROUTED:
8983
        if 'ip' in nic_dict:
8984
          nic_ip = nic_dict['ip']
8985
        else:
8986
          nic_ip = old_nic_ip
8987
        if nic_ip is None:
8988
          raise errors.OpPrereqError('Cannot set the nic ip to None'
8989
                                     ' on a routed nic', errors.ECODE_INVAL)
8990
      if 'mac' in nic_dict:
8991
        nic_mac = nic_dict['mac']
8992
        if nic_mac is None:
8993
          raise errors.OpPrereqError('Cannot set the nic mac to None',
8994
                                     errors.ECODE_INVAL)
8995
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8996
          # otherwise generate the mac
8997
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
8998
        else:
8999
          # or validate/reserve the current one
9000
          try:
9001
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
9002
          except errors.ReservationError:
9003
            raise errors.OpPrereqError("MAC address %s already in use"
9004
                                       " in cluster" % nic_mac,
9005
                                       errors.ECODE_NOTUNIQUE)
9006

    
9007
    # DISK processing
9008
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
9009
      raise errors.OpPrereqError("Disk operations not supported for"
9010
                                 " diskless instances",
9011
                                 errors.ECODE_INVAL)
9012
    for disk_op, _ in self.op.disks:
9013
      if disk_op == constants.DDM_REMOVE:
9014
        if len(instance.disks) == 1:
9015
          raise errors.OpPrereqError("Cannot remove the last disk of"
9016
                                     " an instance", errors.ECODE_INVAL)
9017
        _CheckInstanceDown(self, instance, "cannot remove disks")
9018

    
9019
      if (disk_op == constants.DDM_ADD and
9020
          len(instance.nics) >= constants.MAX_DISKS):
9021
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
9022
                                   " add more" % constants.MAX_DISKS,
9023
                                   errors.ECODE_STATE)
9024
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
9025
        # an existing disk
9026
        if disk_op < 0 or disk_op >= len(instance.disks):
9027
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9028
                                     " are 0 to %d" %
9029
                                     (disk_op, len(instance.disks)),
9030
                                     errors.ECODE_INVAL)
9031

    
9032
    return
9033

    
9034
  def _ConvertPlainToDrbd(self, feedback_fn):
9035
    """Converts an instance from plain to drbd.
9036

9037
    """
9038
    feedback_fn("Converting template to drbd")
9039
    instance = self.instance
9040
    pnode = instance.primary_node
9041
    snode = self.op.remote_node
9042

    
9043
    # create a fake disk info for _GenerateDiskTemplate
9044
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
9045
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9046
                                      instance.name, pnode, [snode],
9047
                                      disk_info, None, None, 0)
9048
    info = _GetInstanceInfoText(instance)
9049
    feedback_fn("Creating aditional volumes...")
9050
    # first, create the missing data and meta devices
9051
    for disk in new_disks:
9052
      # unfortunately this is... not too nice
9053
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9054
                            info, True)
9055
      for child in disk.children:
9056
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9057
    # at this stage, all new LVs have been created, we can rename the
9058
    # old ones
9059
    feedback_fn("Renaming original volumes...")
9060
    rename_list = [(o, n.children[0].logical_id)
9061
                   for (o, n) in zip(instance.disks, new_disks)]
9062
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9063
    result.Raise("Failed to rename original LVs")
9064

    
9065
    feedback_fn("Initializing DRBD devices...")
9066
    # all child devices are in place, we can now create the DRBD devices
9067
    for disk in new_disks:
9068
      for node in [pnode, snode]:
9069
        f_create = node == pnode
9070
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9071

    
9072
    # at this point, the instance has been modified
9073
    instance.disk_template = constants.DT_DRBD8
9074
    instance.disks = new_disks
9075
    self.cfg.Update(instance, feedback_fn)
9076

    
9077
    # disks are created, waiting for sync
9078
    disk_abort = not _WaitForSync(self, instance)
9079
    if disk_abort:
9080
      raise errors.OpExecError("There are some degraded disks for"
9081
                               " this instance, please cleanup manually")
9082

    
9083
  def _ConvertDrbdToPlain(self, feedback_fn):
9084
    """Converts an instance from drbd to plain.
9085

9086
    """
9087
    instance = self.instance
9088
    assert len(instance.secondary_nodes) == 1
9089
    pnode = instance.primary_node
9090
    snode = instance.secondary_nodes[0]
9091
    feedback_fn("Converting template to plain")
9092

    
9093
    old_disks = instance.disks
9094
    new_disks = [d.children[0] for d in old_disks]
9095

    
9096
    # copy over size and mode
9097
    for parent, child in zip(old_disks, new_disks):
9098
      child.size = parent.size
9099
      child.mode = parent.mode
9100

    
9101
    # update instance structure
9102
    instance.disks = new_disks
9103
    instance.disk_template = constants.DT_PLAIN
9104
    self.cfg.Update(instance, feedback_fn)
9105

    
9106
    feedback_fn("Removing volumes on the secondary node...")
9107
    for disk in old_disks:
9108
      self.cfg.SetDiskID(disk, snode)
9109
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9110
      if msg:
9111
        self.LogWarning("Could not remove block device %s on node %s,"
9112
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9113

    
9114
    feedback_fn("Removing unneeded volumes on the primary node...")
9115
    for idx, disk in enumerate(old_disks):
9116
      meta = disk.children[1]
9117
      self.cfg.SetDiskID(meta, pnode)
9118
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9119
      if msg:
9120
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9121
                        " continuing anyway: %s", idx, pnode, msg)
9122

    
9123

    
9124
  def Exec(self, feedback_fn):
9125
    """Modifies an instance.
9126

9127
    All parameters take effect only at the next restart of the instance.
9128

9129
    """
9130
    # Process here the warnings from CheckPrereq, as we don't have a
9131
    # feedback_fn there.
9132
    for warn in self.warn:
9133
      feedback_fn("WARNING: %s" % warn)
9134

    
9135
    result = []
9136
    instance = self.instance
9137
    # disk changes
9138
    for disk_op, disk_dict in self.op.disks:
9139
      if disk_op == constants.DDM_REMOVE:
9140
        # remove the last disk
9141
        device = instance.disks.pop()
9142
        device_idx = len(instance.disks)
9143
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9144
          self.cfg.SetDiskID(disk, node)
9145
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9146
          if msg:
9147
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9148
                            " continuing anyway", device_idx, node, msg)
9149
        result.append(("disk/%d" % device_idx, "remove"))
9150
      elif disk_op == constants.DDM_ADD:
9151
        # add a new disk
9152
        if instance.disk_template == constants.DT_FILE:
9153
          file_driver, file_path = instance.disks[0].logical_id
9154
          file_path = os.path.dirname(file_path)
9155
        else:
9156
          file_driver = file_path = None
9157
        disk_idx_base = len(instance.disks)
9158
        new_disk = _GenerateDiskTemplate(self,
9159
                                         instance.disk_template,
9160
                                         instance.name, instance.primary_node,
9161
                                         instance.secondary_nodes,
9162
                                         [disk_dict],
9163
                                         file_path,
9164
                                         file_driver,
9165
                                         disk_idx_base)[0]
9166
        instance.disks.append(new_disk)
9167
        info = _GetInstanceInfoText(instance)
9168

    
9169
        logging.info("Creating volume %s for instance %s",
9170
                     new_disk.iv_name, instance.name)
9171
        # Note: this needs to be kept in sync with _CreateDisks
9172
        #HARDCODE
9173
        for node in instance.all_nodes:
9174
          f_create = node == instance.primary_node
9175
          try:
9176
            _CreateBlockDev(self, node, instance, new_disk,
9177
                            f_create, info, f_create)
9178
          except errors.OpExecError, err:
9179
            self.LogWarning("Failed to create volume %s (%s) on"
9180
                            " node %s: %s",
9181
                            new_disk.iv_name, new_disk, node, err)
9182
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9183
                       (new_disk.size, new_disk.mode)))
9184
      else:
9185
        # change a given disk
9186
        instance.disks[disk_op].mode = disk_dict['mode']
9187
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9188

    
9189
    if self.op.disk_template:
9190
      r_shut = _ShutdownInstanceDisks(self, instance)
9191
      if not r_shut:
9192
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
9193
                                 " proceed with disk template conversion")
9194
      mode = (instance.disk_template, self.op.disk_template)
9195
      try:
9196
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9197
      except:
9198
        self.cfg.ReleaseDRBDMinors(instance.name)
9199
        raise
9200
      result.append(("disk_template", self.op.disk_template))
9201

    
9202
    # NIC changes
9203
    for nic_op, nic_dict in self.op.nics:
9204
      if nic_op == constants.DDM_REMOVE:
9205
        # remove the last nic
9206
        del instance.nics[-1]
9207
        result.append(("nic.%d" % len(instance.nics), "remove"))
9208
      elif nic_op == constants.DDM_ADD:
9209
        # mac and bridge should be set, by now
9210
        mac = nic_dict['mac']
9211
        ip = nic_dict.get('ip', None)
9212
        nicparams = self.nic_pinst[constants.DDM_ADD]
9213
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9214
        instance.nics.append(new_nic)
9215
        result.append(("nic.%d" % (len(instance.nics) - 1),
9216
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9217
                       (new_nic.mac, new_nic.ip,
9218
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9219
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9220
                       )))
9221
      else:
9222
        for key in 'mac', 'ip':
9223
          if key in nic_dict:
9224
            setattr(instance.nics[nic_op], key, nic_dict[key])
9225
        if nic_op in self.nic_pinst:
9226
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9227
        for key, val in nic_dict.iteritems():
9228
          result.append(("nic.%s/%d" % (key, nic_op), val))
9229

    
9230
    # hvparams changes
9231
    if self.op.hvparams:
9232
      instance.hvparams = self.hv_inst
9233
      for key, val in self.op.hvparams.iteritems():
9234
        result.append(("hv/%s" % key, val))
9235

    
9236
    # beparams changes
9237
    if self.op.beparams:
9238
      instance.beparams = self.be_inst
9239
      for key, val in self.op.beparams.iteritems():
9240
        result.append(("be/%s" % key, val))
9241

    
9242
    # OS change
9243
    if self.op.os_name:
9244
      instance.os = self.op.os_name
9245

    
9246
    # osparams changes
9247
    if self.op.osparams:
9248
      instance.osparams = self.os_inst
9249
      for key, val in self.op.osparams.iteritems():
9250
        result.append(("os/%s" % key, val))
9251

    
9252
    self.cfg.Update(instance, feedback_fn)
9253

    
9254
    return result
9255

    
9256
  _DISK_CONVERSIONS = {
9257
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9258
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9259
    }
9260

    
9261

    
9262
class LUQueryExports(NoHooksLU):
9263
  """Query the exports list
9264

9265
  """
9266
  _OP_PARAMS = [
9267
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
9268
    ("use_locking", False, _TBool),
9269
    ]
9270
  REQ_BGL = False
9271

    
9272
  def ExpandNames(self):
9273
    self.needed_locks = {}
9274
    self.share_locks[locking.LEVEL_NODE] = 1
9275
    if not self.op.nodes:
9276
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9277
    else:
9278
      self.needed_locks[locking.LEVEL_NODE] = \
9279
        _GetWantedNodes(self, self.op.nodes)
9280

    
9281
  def Exec(self, feedback_fn):
9282
    """Compute the list of all the exported system images.
9283

9284
    @rtype: dict
9285
    @return: a dictionary with the structure node->(export-list)
9286
        where export-list is a list of the instances exported on
9287
        that node.
9288

9289
    """
9290
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9291
    rpcresult = self.rpc.call_export_list(self.nodes)
9292
    result = {}
9293
    for node in rpcresult:
9294
      if rpcresult[node].fail_msg:
9295
        result[node] = False
9296
      else:
9297
        result[node] = rpcresult[node].payload
9298

    
9299
    return result
9300

    
9301

    
9302
class LUPrepareExport(NoHooksLU):
9303
  """Prepares an instance for an export and returns useful information.
9304

9305
  """
9306
  _OP_PARAMS = [
9307
    _PInstanceName,
9308
    ("mode", _NoDefault, _TElemOf(constants.EXPORT_MODES)),
9309
    ]
9310
  REQ_BGL = False
9311

    
9312
  def ExpandNames(self):
9313
    self._ExpandAndLockInstance()
9314

    
9315
  def CheckPrereq(self):
9316
    """Check prerequisites.
9317

9318
    """
9319
    instance_name = self.op.instance_name
9320

    
9321
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9322
    assert self.instance is not None, \
9323
          "Cannot retrieve locked instance %s" % self.op.instance_name
9324
    _CheckNodeOnline(self, self.instance.primary_node)
9325

    
9326
    self._cds = _GetClusterDomainSecret()
9327

    
9328
  def Exec(self, feedback_fn):
9329
    """Prepares an instance for an export.
9330

9331
    """
9332
    instance = self.instance
9333

    
9334
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9335
      salt = utils.GenerateSecret(8)
9336

    
9337
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9338
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9339
                                              constants.RIE_CERT_VALIDITY)
9340
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9341

    
9342
      (name, cert_pem) = result.payload
9343

    
9344
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9345
                                             cert_pem)
9346

    
9347
      return {
9348
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9349
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9350
                          salt),
9351
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9352
        }
9353

    
9354
    return None
9355

    
9356

    
9357
class LUExportInstance(LogicalUnit):
9358
  """Export an instance to an image in the cluster.
9359

9360
  """
9361
  HPATH = "instance-export"
9362
  HTYPE = constants.HTYPE_INSTANCE
9363
  _OP_PARAMS = [
9364
    _PInstanceName,
9365
    ("target_node", _NoDefault, _TOr(_TNonEmptyString, _TList)),
9366
    ("shutdown", True, _TBool),
9367
    _PShutdownTimeout,
9368
    ("remove_instance", False, _TBool),
9369
    ("ignore_remove_failures", False, _TBool),
9370
    ("mode", constants.EXPORT_MODE_LOCAL, _TElemOf(constants.EXPORT_MODES)),
9371
    ("x509_key_name", None, _TOr(_TList, _TNone)),
9372
    ("destination_x509_ca", None, _TMaybeString),
9373
    ]
9374
  REQ_BGL = False
9375

    
9376
  def CheckArguments(self):
9377
    """Check the arguments.
9378

9379
    """
9380
    self.x509_key_name = self.op.x509_key_name
9381
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9382

    
9383
    if self.op.remove_instance and not self.op.shutdown:
9384
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9385
                                 " down before")
9386

    
9387
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9388
      if not self.x509_key_name:
9389
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9390
                                   errors.ECODE_INVAL)
9391

    
9392
      if not self.dest_x509_ca_pem:
9393
        raise errors.OpPrereqError("Missing destination X509 CA",
9394
                                   errors.ECODE_INVAL)
9395

    
9396
  def ExpandNames(self):
9397
    self._ExpandAndLockInstance()
9398

    
9399
    # Lock all nodes for local exports
9400
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9401
      # FIXME: lock only instance primary and destination node
9402
      #
9403
      # Sad but true, for now we have do lock all nodes, as we don't know where
9404
      # the previous export might be, and in this LU we search for it and
9405
      # remove it from its current node. In the future we could fix this by:
9406
      #  - making a tasklet to search (share-lock all), then create the
9407
      #    new one, then one to remove, after
9408
      #  - removing the removal operation altogether
9409
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9410

    
9411
  def DeclareLocks(self, level):
9412
    """Last minute lock declaration."""
9413
    # All nodes are locked anyway, so nothing to do here.
9414

    
9415
  def BuildHooksEnv(self):
9416
    """Build hooks env.
9417

9418
    This will run on the master, primary node and target node.
9419

9420
    """
9421
    env = {
9422
      "EXPORT_MODE": self.op.mode,
9423
      "EXPORT_NODE": self.op.target_node,
9424
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9425
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9426
      # TODO: Generic function for boolean env variables
9427
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9428
      }
9429

    
9430
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9431

    
9432
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9433

    
9434
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9435
      nl.append(self.op.target_node)
9436

    
9437
    return env, nl, nl
9438

    
9439
  def CheckPrereq(self):
9440
    """Check prerequisites.
9441

9442
    This checks that the instance and node names are valid.
9443

9444
    """
9445
    instance_name = self.op.instance_name
9446

    
9447
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9448
    assert self.instance is not None, \
9449
          "Cannot retrieve locked instance %s" % self.op.instance_name
9450
    _CheckNodeOnline(self, self.instance.primary_node)
9451

    
9452
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9453
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9454
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9455
      assert self.dst_node is not None
9456

    
9457
      _CheckNodeOnline(self, self.dst_node.name)
9458
      _CheckNodeNotDrained(self, self.dst_node.name)
9459

    
9460
      self._cds = None
9461
      self.dest_disk_info = None
9462
      self.dest_x509_ca = None
9463

    
9464
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9465
      self.dst_node = None
9466

    
9467
      if len(self.op.target_node) != len(self.instance.disks):
9468
        raise errors.OpPrereqError(("Received destination information for %s"
9469
                                    " disks, but instance %s has %s disks") %
9470
                                   (len(self.op.target_node), instance_name,
9471
                                    len(self.instance.disks)),
9472
                                   errors.ECODE_INVAL)
9473

    
9474
      cds = _GetClusterDomainSecret()
9475

    
9476
      # Check X509 key name
9477
      try:
9478
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9479
      except (TypeError, ValueError), err:
9480
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9481

    
9482
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9483
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9484
                                   errors.ECODE_INVAL)
9485

    
9486
      # Load and verify CA
9487
      try:
9488
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9489
      except OpenSSL.crypto.Error, err:
9490
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9491
                                   (err, ), errors.ECODE_INVAL)
9492

    
9493
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9494
      if errcode is not None:
9495
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9496
                                   (msg, ), errors.ECODE_INVAL)
9497

    
9498
      self.dest_x509_ca = cert
9499

    
9500
      # Verify target information
9501
      disk_info = []
9502
      for idx, disk_data in enumerate(self.op.target_node):
9503
        try:
9504
          (host, port, magic) = \
9505
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9506
        except errors.GenericError, err:
9507
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9508
                                     (idx, err), errors.ECODE_INVAL)
9509

    
9510
        disk_info.append((host, port, magic))
9511

    
9512
      assert len(disk_info) == len(self.op.target_node)
9513
      self.dest_disk_info = disk_info
9514

    
9515
    else:
9516
      raise errors.ProgrammerError("Unhandled export mode %r" %
9517
                                   self.op.mode)
9518

    
9519
    # instance disk type verification
9520
    # TODO: Implement export support for file-based disks
9521
    for disk in self.instance.disks:
9522
      if disk.dev_type == constants.LD_FILE:
9523
        raise errors.OpPrereqError("Export not supported for instances with"
9524
                                   " file-based disks", errors.ECODE_INVAL)
9525

    
9526
  def _CleanupExports(self, feedback_fn):
9527
    """Removes exports of current instance from all other nodes.
9528

9529
    If an instance in a cluster with nodes A..D was exported to node C, its
9530
    exports will be removed from the nodes A, B and D.
9531

9532
    """
9533
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9534

    
9535
    nodelist = self.cfg.GetNodeList()
9536
    nodelist.remove(self.dst_node.name)
9537

    
9538
    # on one-node clusters nodelist will be empty after the removal
9539
    # if we proceed the backup would be removed because OpQueryExports
9540
    # substitutes an empty list with the full cluster node list.
9541
    iname = self.instance.name
9542
    if nodelist:
9543
      feedback_fn("Removing old exports for instance %s" % iname)
9544
      exportlist = self.rpc.call_export_list(nodelist)
9545
      for node in exportlist:
9546
        if exportlist[node].fail_msg:
9547
          continue
9548
        if iname in exportlist[node].payload:
9549
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9550
          if msg:
9551
            self.LogWarning("Could not remove older export for instance %s"
9552
                            " on node %s: %s", iname, node, msg)
9553

    
9554
  def Exec(self, feedback_fn):
9555
    """Export an instance to an image in the cluster.
9556

9557
    """
9558
    assert self.op.mode in constants.EXPORT_MODES
9559

    
9560
    instance = self.instance
9561
    src_node = instance.primary_node
9562

    
9563
    if self.op.shutdown:
9564
      # shutdown the instance, but not the disks
9565
      feedback_fn("Shutting down instance %s" % instance.name)
9566
      result = self.rpc.call_instance_shutdown(src_node, instance,
9567
                                               self.op.shutdown_timeout)
9568
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9569
      result.Raise("Could not shutdown instance %s on"
9570
                   " node %s" % (instance.name, src_node))
9571

    
9572
    # set the disks ID correctly since call_instance_start needs the
9573
    # correct drbd minor to create the symlinks
9574
    for disk in instance.disks:
9575
      self.cfg.SetDiskID(disk, src_node)
9576

    
9577
    activate_disks = (not instance.admin_up)
9578

    
9579
    if activate_disks:
9580
      # Activate the instance disks if we'exporting a stopped instance
9581
      feedback_fn("Activating disks for %s" % instance.name)
9582
      _StartInstanceDisks(self, instance, None)
9583

    
9584
    try:
9585
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9586
                                                     instance)
9587

    
9588
      helper.CreateSnapshots()
9589
      try:
9590
        if (self.op.shutdown and instance.admin_up and
9591
            not self.op.remove_instance):
9592
          assert not activate_disks
9593
          feedback_fn("Starting instance %s" % instance.name)
9594
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9595
          msg = result.fail_msg
9596
          if msg:
9597
            feedback_fn("Failed to start instance: %s" % msg)
9598
            _ShutdownInstanceDisks(self, instance)
9599
            raise errors.OpExecError("Could not start instance: %s" % msg)
9600

    
9601
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9602
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9603
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9604
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9605
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9606

    
9607
          (key_name, _, _) = self.x509_key_name
9608

    
9609
          dest_ca_pem = \
9610
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9611
                                            self.dest_x509_ca)
9612

    
9613
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9614
                                                     key_name, dest_ca_pem,
9615
                                                     timeouts)
9616
      finally:
9617
        helper.Cleanup()
9618

    
9619
      # Check for backwards compatibility
9620
      assert len(dresults) == len(instance.disks)
9621
      assert compat.all(isinstance(i, bool) for i in dresults), \
9622
             "Not all results are boolean: %r" % dresults
9623

    
9624
    finally:
9625
      if activate_disks:
9626
        feedback_fn("Deactivating disks for %s" % instance.name)
9627
        _ShutdownInstanceDisks(self, instance)
9628

    
9629
    if not (compat.all(dresults) and fin_resu):
9630
      failures = []
9631
      if not fin_resu:
9632
        failures.append("export finalization")
9633
      if not compat.all(dresults):
9634
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
9635
                               if not dsk)
9636
        failures.append("disk export: disk(s) %s" % fdsk)
9637

    
9638
      raise errors.OpExecError("Export failed, errors in %s" %
9639
                               utils.CommaJoin(failures))
9640

    
9641
    # At this point, the export was successful, we can cleanup/finish
9642

    
9643
    # Remove instance if requested
9644
    if self.op.remove_instance:
9645
      feedback_fn("Removing instance %s" % instance.name)
9646
      _RemoveInstance(self, feedback_fn, instance,
9647
                      self.op.ignore_remove_failures)
9648

    
9649
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9650
      self._CleanupExports(feedback_fn)
9651

    
9652
    return fin_resu, dresults
9653

    
9654

    
9655
class LURemoveExport(NoHooksLU):
9656
  """Remove exports related to the named instance.
9657

9658
  """
9659
  _OP_PARAMS = [
9660
    _PInstanceName,
9661
    ]
9662
  REQ_BGL = False
9663

    
9664
  def ExpandNames(self):
9665
    self.needed_locks = {}
9666
    # We need all nodes to be locked in order for RemoveExport to work, but we
9667
    # don't need to lock the instance itself, as nothing will happen to it (and
9668
    # we can remove exports also for a removed instance)
9669
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9670

    
9671
  def Exec(self, feedback_fn):
9672
    """Remove any export.
9673

9674
    """
9675
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9676
    # If the instance was not found we'll try with the name that was passed in.
9677
    # This will only work if it was an FQDN, though.
9678
    fqdn_warn = False
9679
    if not instance_name:
9680
      fqdn_warn = True
9681
      instance_name = self.op.instance_name
9682

    
9683
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
9684
    exportlist = self.rpc.call_export_list(locked_nodes)
9685
    found = False
9686
    for node in exportlist:
9687
      msg = exportlist[node].fail_msg
9688
      if msg:
9689
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
9690
        continue
9691
      if instance_name in exportlist[node].payload:
9692
        found = True
9693
        result = self.rpc.call_export_remove(node, instance_name)
9694
        msg = result.fail_msg
9695
        if msg:
9696
          logging.error("Could not remove export for instance %s"
9697
                        " on node %s: %s", instance_name, node, msg)
9698

    
9699
    if fqdn_warn and not found:
9700
      feedback_fn("Export not found. If trying to remove an export belonging"
9701
                  " to a deleted instance please use its Fully Qualified"
9702
                  " Domain Name.")
9703

    
9704

    
9705
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
9706
  """Generic tags LU.
9707

9708
  This is an abstract class which is the parent of all the other tags LUs.
9709

9710
  """
9711

    
9712
  def ExpandNames(self):
9713
    self.needed_locks = {}
9714
    if self.op.kind == constants.TAG_NODE:
9715
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
9716
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
9717
    elif self.op.kind == constants.TAG_INSTANCE:
9718
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
9719
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
9720

    
9721
  def CheckPrereq(self):
9722
    """Check prerequisites.
9723

9724
    """
9725
    if self.op.kind == constants.TAG_CLUSTER:
9726
      self.target = self.cfg.GetClusterInfo()
9727
    elif self.op.kind == constants.TAG_NODE:
9728
      self.target = self.cfg.GetNodeInfo(self.op.name)
9729
    elif self.op.kind == constants.TAG_INSTANCE:
9730
      self.target = self.cfg.GetInstanceInfo(self.op.name)
9731
    else:
9732
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
9733
                                 str(self.op.kind), errors.ECODE_INVAL)
9734

    
9735

    
9736
class LUGetTags(TagsLU):
9737
  """Returns the tags of a given object.
9738

9739
  """
9740
  _OP_PARAMS = [
9741
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9742
    ("name", _NoDefault, _TNonEmptyString),
9743
    ]
9744
  REQ_BGL = False
9745

    
9746
  def Exec(self, feedback_fn):
9747
    """Returns the tag list.
9748

9749
    """
9750
    return list(self.target.GetTags())
9751

    
9752

    
9753
class LUSearchTags(NoHooksLU):
9754
  """Searches the tags for a given pattern.
9755

9756
  """
9757
  _OP_PARAMS = [
9758
    ("pattern", _NoDefault, _TNonEmptyString),
9759
    ]
9760
  REQ_BGL = False
9761

    
9762
  def ExpandNames(self):
9763
    self.needed_locks = {}
9764

    
9765
  def CheckPrereq(self):
9766
    """Check prerequisites.
9767

9768
    This checks the pattern passed for validity by compiling it.
9769

9770
    """
9771
    try:
9772
      self.re = re.compile(self.op.pattern)
9773
    except re.error, err:
9774
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
9775
                                 (self.op.pattern, err), errors.ECODE_INVAL)
9776

    
9777
  def Exec(self, feedback_fn):
9778
    """Returns the tag list.
9779

9780
    """
9781
    cfg = self.cfg
9782
    tgts = [("/cluster", cfg.GetClusterInfo())]
9783
    ilist = cfg.GetAllInstancesInfo().values()
9784
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
9785
    nlist = cfg.GetAllNodesInfo().values()
9786
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
9787
    results = []
9788
    for path, target in tgts:
9789
      for tag in target.GetTags():
9790
        if self.re.search(tag):
9791
          results.append((path, tag))
9792
    return results
9793

    
9794

    
9795
class LUAddTags(TagsLU):
9796
  """Sets a tag on a given object.
9797

9798
  """
9799
  _OP_PARAMS = [
9800
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9801
    ("name", _NoDefault, _TNonEmptyString),
9802
    ("tags", _NoDefault, _TListOf(_TNonEmptyString)),
9803
    ]
9804
  REQ_BGL = False
9805

    
9806
  def CheckPrereq(self):
9807
    """Check prerequisites.
9808

9809
    This checks the type and length of the tag name and value.
9810

9811
    """
9812
    TagsLU.CheckPrereq(self)
9813
    for tag in self.op.tags:
9814
      objects.TaggableObject.ValidateTag(tag)
9815

    
9816
  def Exec(self, feedback_fn):
9817
    """Sets the tag.
9818

9819
    """
9820
    try:
9821
      for tag in self.op.tags:
9822
        self.target.AddTag(tag)
9823
    except errors.TagError, err:
9824
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
9825
    self.cfg.Update(self.target, feedback_fn)
9826

    
9827

    
9828
class LUDelTags(TagsLU):
9829
  """Delete a list of tags from a given object.
9830

9831
  """
9832
  _OP_PARAMS = [
9833
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9834
    ("name", _NoDefault, _TNonEmptyString),
9835
    ("tags", _NoDefault, _TListOf(_TNonEmptyString)),
9836
    ]
9837
  REQ_BGL = False
9838

    
9839
  def CheckPrereq(self):
9840
    """Check prerequisites.
9841

9842
    This checks that we have the given tag.
9843

9844
    """
9845
    TagsLU.CheckPrereq(self)
9846
    for tag in self.op.tags:
9847
      objects.TaggableObject.ValidateTag(tag)
9848
    del_tags = frozenset(self.op.tags)
9849
    cur_tags = self.target.GetTags()
9850
    if not del_tags <= cur_tags:
9851
      diff_tags = del_tags - cur_tags
9852
      diff_names = ["'%s'" % tag for tag in diff_tags]
9853
      diff_names.sort()
9854
      raise errors.OpPrereqError("Tag(s) %s not found" %
9855
                                 (",".join(diff_names)), errors.ECODE_NOENT)
9856

    
9857
  def Exec(self, feedback_fn):
9858
    """Remove the tag from the object.
9859

9860
    """
9861
    for tag in self.op.tags:
9862
      self.target.RemoveTag(tag)
9863
    self.cfg.Update(self.target, feedback_fn)
9864

    
9865

    
9866
class LUTestDelay(NoHooksLU):
9867
  """Sleep for a specified amount of time.
9868

9869
  This LU sleeps on the master and/or nodes for a specified amount of
9870
  time.
9871

9872
  """
9873
  _OP_PARAMS = [
9874
    ("duration", _NoDefault, _TFloat),
9875
    ("on_master", True, _TBool),
9876
    ("on_nodes", _EmptyList, _TListOf(_TNonEmptyString)),
9877
    ("repeat", 0, _TPositiveInt)
9878
    ]
9879
  REQ_BGL = False
9880

    
9881
  def ExpandNames(self):
9882
    """Expand names and set required locks.
9883

9884
    This expands the node list, if any.
9885

9886
    """
9887
    self.needed_locks = {}
9888
    if self.op.on_nodes:
9889
      # _GetWantedNodes can be used here, but is not always appropriate to use
9890
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
9891
      # more information.
9892
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
9893
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
9894

    
9895
  def _TestDelay(self):
9896
    """Do the actual sleep.
9897

9898
    """
9899
    if self.op.on_master:
9900
      if not utils.TestDelay(self.op.duration):
9901
        raise errors.OpExecError("Error during master delay test")
9902
    if self.op.on_nodes:
9903
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
9904
      for node, node_result in result.items():
9905
        node_result.Raise("Failure during rpc call to node %s" % node)
9906

    
9907
  def Exec(self, feedback_fn):
9908
    """Execute the test delay opcode, with the wanted repetitions.
9909

9910
    """
9911
    if self.op.repeat == 0:
9912
      self._TestDelay()
9913
    else:
9914
      top_value = self.op.repeat - 1
9915
      for i in range(self.op.repeat):
9916
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
9917
        self._TestDelay()
9918

    
9919

    
9920
class LUTestJobqueue(NoHooksLU):
9921
  """Utility LU to test some aspects of the job queue.
9922

9923
  """
9924
  _OP_PARAMS = [
9925
    ("notify_waitlock", False, _TBool),
9926
    ("notify_exec", False, _TBool),
9927
    ("log_messages", _EmptyList, _TListOf(_TString)),
9928
    ("fail", False, _TBool),
9929
    ]
9930
  REQ_BGL = False
9931

    
9932
  # Must be lower than default timeout for WaitForJobChange to see whether it
9933
  # notices changed jobs
9934
  _CLIENT_CONNECT_TIMEOUT = 20.0
9935
  _CLIENT_CONFIRM_TIMEOUT = 60.0
9936

    
9937
  @classmethod
9938
  def _NotifyUsingSocket(cls, cb, errcls):
9939
    """Opens a Unix socket and waits for another program to connect.
9940

9941
    @type cb: callable
9942
    @param cb: Callback to send socket name to client
9943
    @type errcls: class
9944
    @param errcls: Exception class to use for errors
9945

9946
    """
9947
    # Using a temporary directory as there's no easy way to create temporary
9948
    # sockets without writing a custom loop around tempfile.mktemp and
9949
    # socket.bind
9950
    tmpdir = tempfile.mkdtemp()
9951
    try:
9952
      tmpsock = utils.PathJoin(tmpdir, "sock")
9953

    
9954
      logging.debug("Creating temporary socket at %s", tmpsock)
9955
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
9956
      try:
9957
        sock.bind(tmpsock)
9958
        sock.listen(1)
9959

    
9960
        # Send details to client
9961
        cb(tmpsock)
9962

    
9963
        # Wait for client to connect before continuing
9964
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
9965
        try:
9966
          (conn, _) = sock.accept()
9967
        except socket.error, err:
9968
          raise errcls("Client didn't connect in time (%s)" % err)
9969
      finally:
9970
        sock.close()
9971
    finally:
9972
      # Remove as soon as client is connected
9973
      shutil.rmtree(tmpdir)
9974

    
9975
    # Wait for client to close
9976
    try:
9977
      try:
9978
        # pylint: disable-msg=E1101
9979
        # Instance of '_socketobject' has no ... member
9980
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
9981
        conn.recv(1)
9982
      except socket.error, err:
9983
        raise errcls("Client failed to confirm notification (%s)" % err)
9984
    finally:
9985
      conn.close()
9986

    
9987
  def _SendNotification(self, test, arg, sockname):
9988
    """Sends a notification to the client.
9989

9990
    @type test: string
9991
    @param test: Test name
9992
    @param arg: Test argument (depends on test)
9993
    @type sockname: string
9994
    @param sockname: Socket path
9995

9996
    """
9997
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
9998

    
9999
  def _Notify(self, prereq, test, arg):
10000
    """Notifies the client of a test.
10001

10002
    @type prereq: bool
10003
    @param prereq: Whether this is a prereq-phase test
10004
    @type test: string
10005
    @param test: Test name
10006
    @param arg: Test argument (depends on test)
10007

10008
    """
10009
    if prereq:
10010
      errcls = errors.OpPrereqError
10011
    else:
10012
      errcls = errors.OpExecError
10013

    
10014
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
10015
                                                  test, arg),
10016
                                   errcls)
10017

    
10018
  def CheckArguments(self):
10019
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
10020
    self.expandnames_calls = 0
10021

    
10022
  def ExpandNames(self):
10023
    checkargs_calls = getattr(self, "checkargs_calls", 0)
10024
    if checkargs_calls < 1:
10025
      raise errors.ProgrammerError("CheckArguments was not called")
10026

    
10027
    self.expandnames_calls += 1
10028

    
10029
    if self.op.notify_waitlock:
10030
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
10031

    
10032
    self.LogInfo("Expanding names")
10033

    
10034
    # Get lock on master node (just to get a lock, not for a particular reason)
10035
    self.needed_locks = {
10036
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
10037
      }
10038

    
10039
  def Exec(self, feedback_fn):
10040
    if self.expandnames_calls < 1:
10041
      raise errors.ProgrammerError("ExpandNames was not called")
10042

    
10043
    if self.op.notify_exec:
10044
      self._Notify(False, constants.JQT_EXEC, None)
10045

    
10046
    self.LogInfo("Executing")
10047

    
10048
    if self.op.log_messages:
10049
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
10050
      for idx, msg in enumerate(self.op.log_messages):
10051
        self.LogInfo("Sending log message %s", idx + 1)
10052
        feedback_fn(constants.JQT_MSGPREFIX + msg)
10053
        # Report how many test messages have been sent
10054
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
10055

    
10056
    if self.op.fail:
10057
      raise errors.OpExecError("Opcode failure was requested")
10058

    
10059
    return True
10060

    
10061

    
10062
class IAllocator(object):
10063
  """IAllocator framework.
10064

10065
  An IAllocator instance has three sets of attributes:
10066
    - cfg that is needed to query the cluster
10067
    - input data (all members of the _KEYS class attribute are required)
10068
    - four buffer attributes (in|out_data|text), that represent the
10069
      input (to the external script) in text and data structure format,
10070
      and the output from it, again in two formats
10071
    - the result variables from the script (success, info, nodes) for
10072
      easy usage
10073

10074
  """
10075
  # pylint: disable-msg=R0902
10076
  # lots of instance attributes
10077
  _ALLO_KEYS = [
10078
    "name", "mem_size", "disks", "disk_template",
10079
    "os", "tags", "nics", "vcpus", "hypervisor",
10080
    ]
10081
  _RELO_KEYS = [
10082
    "name", "relocate_from",
10083
    ]
10084
  _EVAC_KEYS = [
10085
    "evac_nodes",
10086
    ]
10087

    
10088
  def __init__(self, cfg, rpc, mode, **kwargs):
10089
    self.cfg = cfg
10090
    self.rpc = rpc
10091
    # init buffer variables
10092
    self.in_text = self.out_text = self.in_data = self.out_data = None
10093
    # init all input fields so that pylint is happy
10094
    self.mode = mode
10095
    self.mem_size = self.disks = self.disk_template = None
10096
    self.os = self.tags = self.nics = self.vcpus = None
10097
    self.hypervisor = None
10098
    self.relocate_from = None
10099
    self.name = None
10100
    self.evac_nodes = None
10101
    # computed fields
10102
    self.required_nodes = None
10103
    # init result fields
10104
    self.success = self.info = self.result = None
10105
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10106
      keyset = self._ALLO_KEYS
10107
      fn = self._AddNewInstance
10108
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10109
      keyset = self._RELO_KEYS
10110
      fn = self._AddRelocateInstance
10111
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10112
      keyset = self._EVAC_KEYS
10113
      fn = self._AddEvacuateNodes
10114
    else:
10115
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
10116
                                   " IAllocator" % self.mode)
10117
    for key in kwargs:
10118
      if key not in keyset:
10119
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
10120
                                     " IAllocator" % key)
10121
      setattr(self, key, kwargs[key])
10122

    
10123
    for key in keyset:
10124
      if key not in kwargs:
10125
        raise errors.ProgrammerError("Missing input parameter '%s' to"
10126
                                     " IAllocator" % key)
10127
    self._BuildInputData(fn)
10128

    
10129
  def _ComputeClusterData(self):
10130
    """Compute the generic allocator input data.
10131

10132
    This is the data that is independent of the actual operation.
10133

10134
    """
10135
    cfg = self.cfg
10136
    cluster_info = cfg.GetClusterInfo()
10137
    # cluster data
10138
    data = {
10139
      "version": constants.IALLOCATOR_VERSION,
10140
      "cluster_name": cfg.GetClusterName(),
10141
      "cluster_tags": list(cluster_info.GetTags()),
10142
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
10143
      # we don't have job IDs
10144
      }
10145
    iinfo = cfg.GetAllInstancesInfo().values()
10146
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
10147

    
10148
    # node data
10149
    node_results = {}
10150
    node_list = cfg.GetNodeList()
10151

    
10152
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10153
      hypervisor_name = self.hypervisor
10154
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10155
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
10156
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10157
      hypervisor_name = cluster_info.enabled_hypervisors[0]
10158

    
10159
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
10160
                                        hypervisor_name)
10161
    node_iinfo = \
10162
      self.rpc.call_all_instances_info(node_list,
10163
                                       cluster_info.enabled_hypervisors)
10164
    for nname, nresult in node_data.items():
10165
      # first fill in static (config-based) values
10166
      ninfo = cfg.GetNodeInfo(nname)
10167
      pnr = {
10168
        "tags": list(ninfo.GetTags()),
10169
        "primary_ip": ninfo.primary_ip,
10170
        "secondary_ip": ninfo.secondary_ip,
10171
        "offline": ninfo.offline,
10172
        "drained": ninfo.drained,
10173
        "master_candidate": ninfo.master_candidate,
10174
        }
10175

    
10176
      if not (ninfo.offline or ninfo.drained):
10177
        nresult.Raise("Can't get data for node %s" % nname)
10178
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
10179
                                nname)
10180
        remote_info = nresult.payload
10181

    
10182
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
10183
                     'vg_size', 'vg_free', 'cpu_total']:
10184
          if attr not in remote_info:
10185
            raise errors.OpExecError("Node '%s' didn't return attribute"
10186
                                     " '%s'" % (nname, attr))
10187
          if not isinstance(remote_info[attr], int):
10188
            raise errors.OpExecError("Node '%s' returned invalid value"
10189
                                     " for '%s': %s" %
10190
                                     (nname, attr, remote_info[attr]))
10191
        # compute memory used by primary instances
10192
        i_p_mem = i_p_up_mem = 0
10193
        for iinfo, beinfo in i_list:
10194
          if iinfo.primary_node == nname:
10195
            i_p_mem += beinfo[constants.BE_MEMORY]
10196
            if iinfo.name not in node_iinfo[nname].payload:
10197
              i_used_mem = 0
10198
            else:
10199
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
10200
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
10201
            remote_info['memory_free'] -= max(0, i_mem_diff)
10202

    
10203
            if iinfo.admin_up:
10204
              i_p_up_mem += beinfo[constants.BE_MEMORY]
10205

    
10206
        # compute memory used by instances
10207
        pnr_dyn = {
10208
          "total_memory": remote_info['memory_total'],
10209
          "reserved_memory": remote_info['memory_dom0'],
10210
          "free_memory": remote_info['memory_free'],
10211
          "total_disk": remote_info['vg_size'],
10212
          "free_disk": remote_info['vg_free'],
10213
          "total_cpus": remote_info['cpu_total'],
10214
          "i_pri_memory": i_p_mem,
10215
          "i_pri_up_memory": i_p_up_mem,
10216
          }
10217
        pnr.update(pnr_dyn)
10218

    
10219
      node_results[nname] = pnr
10220
    data["nodes"] = node_results
10221

    
10222
    # instance data
10223
    instance_data = {}
10224
    for iinfo, beinfo in i_list:
10225
      nic_data = []
10226
      for nic in iinfo.nics:
10227
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
10228
        nic_dict = {"mac": nic.mac,
10229
                    "ip": nic.ip,
10230
                    "mode": filled_params[constants.NIC_MODE],
10231
                    "link": filled_params[constants.NIC_LINK],
10232
                   }
10233
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
10234
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
10235
        nic_data.append(nic_dict)
10236
      pir = {
10237
        "tags": list(iinfo.GetTags()),
10238
        "admin_up": iinfo.admin_up,
10239
        "vcpus": beinfo[constants.BE_VCPUS],
10240
        "memory": beinfo[constants.BE_MEMORY],
10241
        "os": iinfo.os,
10242
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
10243
        "nics": nic_data,
10244
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
10245
        "disk_template": iinfo.disk_template,
10246
        "hypervisor": iinfo.hypervisor,
10247
        }
10248
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
10249
                                                 pir["disks"])
10250
      instance_data[iinfo.name] = pir
10251

    
10252
    data["instances"] = instance_data
10253

    
10254
    self.in_data = data
10255

    
10256
  def _AddNewInstance(self):
10257
    """Add new instance data to allocator structure.
10258

10259
    This in combination with _AllocatorGetClusterData will create the
10260
    correct structure needed as input for the allocator.
10261

10262
    The checks for the completeness of the opcode must have already been
10263
    done.
10264

10265
    """
10266
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
10267

    
10268
    if self.disk_template in constants.DTS_NET_MIRROR:
10269
      self.required_nodes = 2
10270
    else:
10271
      self.required_nodes = 1
10272
    request = {
10273
      "name": self.name,
10274
      "disk_template": self.disk_template,
10275
      "tags": self.tags,
10276
      "os": self.os,
10277
      "vcpus": self.vcpus,
10278
      "memory": self.mem_size,
10279
      "disks": self.disks,
10280
      "disk_space_total": disk_space,
10281
      "nics": self.nics,
10282
      "required_nodes": self.required_nodes,
10283
      }
10284
    return request
10285

    
10286
  def _AddRelocateInstance(self):
10287
    """Add relocate instance data to allocator structure.
10288

10289
    This in combination with _IAllocatorGetClusterData will create the
10290
    correct structure needed as input for the allocator.
10291

10292
    The checks for the completeness of the opcode must have already been
10293
    done.
10294

10295
    """
10296
    instance = self.cfg.GetInstanceInfo(self.name)
10297
    if instance is None:
10298
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
10299
                                   " IAllocator" % self.name)
10300

    
10301
    if instance.disk_template not in constants.DTS_NET_MIRROR:
10302
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
10303
                                 errors.ECODE_INVAL)
10304

    
10305
    if len(instance.secondary_nodes) != 1:
10306
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
10307
                                 errors.ECODE_STATE)
10308

    
10309
    self.required_nodes = 1
10310
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
10311
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
10312

    
10313
    request = {
10314
      "name": self.name,
10315
      "disk_space_total": disk_space,
10316
      "required_nodes": self.required_nodes,
10317
      "relocate_from": self.relocate_from,
10318
      }
10319
    return request
10320

    
10321
  def _AddEvacuateNodes(self):
10322
    """Add evacuate nodes data to allocator structure.
10323

10324
    """
10325
    request = {
10326
      "evac_nodes": self.evac_nodes
10327
      }
10328
    return request
10329

    
10330
  def _BuildInputData(self, fn):
10331
    """Build input data structures.
10332

10333
    """
10334
    self._ComputeClusterData()
10335

    
10336
    request = fn()
10337
    request["type"] = self.mode
10338
    self.in_data["request"] = request
10339

    
10340
    self.in_text = serializer.Dump(self.in_data)
10341

    
10342
  def Run(self, name, validate=True, call_fn=None):
10343
    """Run an instance allocator and return the results.
10344

10345
    """
10346
    if call_fn is None:
10347
      call_fn = self.rpc.call_iallocator_runner
10348

    
10349
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
10350
    result.Raise("Failure while running the iallocator script")
10351

    
10352
    self.out_text = result.payload
10353
    if validate:
10354
      self._ValidateResult()
10355

    
10356
  def _ValidateResult(self):
10357
    """Process the allocator results.
10358

10359
    This will process and if successful save the result in
10360
    self.out_data and the other parameters.
10361

10362
    """
10363
    try:
10364
      rdict = serializer.Load(self.out_text)
10365
    except Exception, err:
10366
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
10367

    
10368
    if not isinstance(rdict, dict):
10369
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
10370

    
10371
    # TODO: remove backwards compatiblity in later versions
10372
    if "nodes" in rdict and "result" not in rdict:
10373
      rdict["result"] = rdict["nodes"]
10374
      del rdict["nodes"]
10375

    
10376
    for key in "success", "info", "result":
10377
      if key not in rdict:
10378
        raise errors.OpExecError("Can't parse iallocator results:"
10379
                                 " missing key '%s'" % key)
10380
      setattr(self, key, rdict[key])
10381

    
10382
    if not isinstance(rdict["result"], list):
10383
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
10384
                               " is not a list")
10385
    self.out_data = rdict
10386

    
10387

    
10388
class LUTestAllocator(NoHooksLU):
10389
  """Run allocator tests.
10390

10391
  This LU runs the allocator tests
10392

10393
  """
10394
  _OP_PARAMS = [
10395
    ("direction", _NoDefault, _TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS)),
10396
    ("mode", _NoDefault, _TElemOf(constants.VALID_IALLOCATOR_MODES)),
10397
    ("name", _NoDefault, _TNonEmptyString),
10398
    ("nics", _NoDefault, _TOr(_TNone, _TListOf(
10399
      _TDictOf(_TElemOf(["mac", "ip", "bridge"]),
10400
               _TOr(_TNone, _TNonEmptyString))))),
10401
    ("disks", _NoDefault, _TOr(_TNone, _TList)),
10402
    ("hypervisor", None, _TMaybeString),
10403
    ("allocator", None, _TMaybeString),
10404
    ("tags", _EmptyList, _TListOf(_TNonEmptyString)),
10405
    ("mem_size", None, _TOr(_TNone, _TPositiveInt)),
10406
    ("vcpus", None, _TOr(_TNone, _TPositiveInt)),
10407
    ("os", None, _TMaybeString),
10408
    ("disk_template", None, _TMaybeString),
10409
    ("evac_nodes", None, _TOr(_TNone, _TListOf(_TNonEmptyString))),
10410
    ]
10411

    
10412
  def CheckPrereq(self):
10413
    """Check prerequisites.
10414

10415
    This checks the opcode parameters depending on the director and mode test.
10416

10417
    """
10418
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10419
      for attr in ["mem_size", "disks", "disk_template",
10420
                   "os", "tags", "nics", "vcpus"]:
10421
        if not hasattr(self.op, attr):
10422
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
10423
                                     attr, errors.ECODE_INVAL)
10424
      iname = self.cfg.ExpandInstanceName(self.op.name)
10425
      if iname is not None:
10426
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
10427
                                   iname, errors.ECODE_EXISTS)
10428
      if not isinstance(self.op.nics, list):
10429
        raise errors.OpPrereqError("Invalid parameter 'nics'",
10430
                                   errors.ECODE_INVAL)
10431
      if not isinstance(self.op.disks, list):
10432
        raise errors.OpPrereqError("Invalid parameter 'disks'",
10433
                                   errors.ECODE_INVAL)
10434
      for row in self.op.disks:
10435
        if (not isinstance(row, dict) or
10436
            "size" not in row or
10437
            not isinstance(row["size"], int) or
10438
            "mode" not in row or
10439
            row["mode"] not in ['r', 'w']):
10440
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
10441
                                     " parameter", errors.ECODE_INVAL)
10442
      if self.op.hypervisor is None:
10443
        self.op.hypervisor = self.cfg.GetHypervisorType()
10444
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10445
      fname = _ExpandInstanceName(self.cfg, self.op.name)
10446
      self.op.name = fname
10447
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
10448
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10449
      if not hasattr(self.op, "evac_nodes"):
10450
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
10451
                                   " opcode input", errors.ECODE_INVAL)
10452
    else:
10453
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
10454
                                 self.op.mode, errors.ECODE_INVAL)
10455

    
10456
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
10457
      if self.op.allocator is None:
10458
        raise errors.OpPrereqError("Missing allocator name",
10459
                                   errors.ECODE_INVAL)
10460
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
10461
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
10462
                                 self.op.direction, errors.ECODE_INVAL)
10463

    
10464
  def Exec(self, feedback_fn):
10465
    """Run the allocator test.
10466

10467
    """
10468
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10469
      ial = IAllocator(self.cfg, self.rpc,
10470
                       mode=self.op.mode,
10471
                       name=self.op.name,
10472
                       mem_size=self.op.mem_size,
10473
                       disks=self.op.disks,
10474
                       disk_template=self.op.disk_template,
10475
                       os=self.op.os,
10476
                       tags=self.op.tags,
10477
                       nics=self.op.nics,
10478
                       vcpus=self.op.vcpus,
10479
                       hypervisor=self.op.hypervisor,
10480
                       )
10481
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10482
      ial = IAllocator(self.cfg, self.rpc,
10483
                       mode=self.op.mode,
10484
                       name=self.op.name,
10485
                       relocate_from=list(self.relocate_from),
10486
                       )
10487
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10488
      ial = IAllocator(self.cfg, self.rpc,
10489
                       mode=self.op.mode,
10490
                       evac_nodes=self.op.evac_nodes)
10491
    else:
10492
      raise errors.ProgrammerError("Uncatched mode %s in"
10493
                                   " LUTestAllocator.Exec", self.op.mode)
10494

    
10495
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
10496
      result = ial.in_text
10497
    else:
10498
      ial.Run(self.op.allocator, validate=False)
10499
      result = ial.out_text
10500
    return result