Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ ea8ac9c9

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

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

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

    
1264
    return master
1265

    
1266

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

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

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

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

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

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

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

    
1299

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1498

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

    
1504
    return True
1505

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1617

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1841
    nimg.os_fail = test
1842

    
1843
    if test:
1844
      return
1845

    
1846
    os_dict = {}
1847

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

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

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

    
1860
    nimg.oslist = os_dict
1861

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2018
    return env, [], all_nodes
2019

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

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

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

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

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

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

    
2064
    local_checksums = utils.FingerprintFiles(file_names)
2065

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

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

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

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

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

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

    
2108
      inst_config.MapLVsByNode(node_vol_should)
2109

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

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

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

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

    
2132
    all_drbd_map = self.cfg.ComputeDRBDMap()
2133

    
2134
    feedback_fn("* Verifying node status")
2135

    
2136
    refos_img = None
2137

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

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

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

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

    
2166
      nresult = all_nvinfo[node].payload
2167

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2261
    return not self.bad
2262

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

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

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

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

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

    
2307
      return lu_result
2308

    
2309

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

2313
  """
2314
  REQ_BGL = False
2315

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

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

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

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

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

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

    
2351
    if not nv_dict:
2352
      return result
2353

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

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

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

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

    
2381
    return result
2382

    
2383

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2499

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

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

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

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

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

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

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

    
2541
    self.op.name = new_name
2542

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

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

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

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

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

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

    
2584
    return clustername
2585

    
2586

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2885

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

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

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

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

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

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

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

    
2930

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

2934
  This is a very simple LU.
2935

2936
  """
2937
  REQ_BGL = False
2938

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

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

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

    
2952

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

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

    
2960
  disks = _ExpandCheckDisks(instance, disks)
2961

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

    
2965
  node = instance.primary_node
2966

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

    
2970
  # TODO: Convert to utils.Retry
2971

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

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

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

    
3018
    if done or oneshot:
3019
      break
3020

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

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

    
3027

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

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

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

    
3038
  result = True
3039

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

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

    
3059
  return result
3060

    
3061

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3181
    return output
3182

    
3183

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

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

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

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

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

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

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

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

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

    
3228
    instance_list = self.cfg.GetInstanceList()
3229

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

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

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

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

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

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

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

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

    
3273
    # Remove node from our /etc/hosts
3274
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3275
      master_node = self.cfg.GetMasterNode()
3276
      result = self.rpc.call_etc_hosts_modify(master_node,
3277
                                              constants.ETC_HOSTS_REMOVE,
3278
                                              node.name, None)
3279
      result.Raise("Can't update hosts file with new host data")
3280
      _RedistributeAncillaryFiles(self)
3281

    
3282

    
3283
class LUQueryNodes(NoHooksLU):
3284
  """Logical unit for querying nodes.
3285

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

    
3295
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
3296
                    "master_candidate", "offline", "drained"]
3297

    
3298
  _FIELDS_DYNAMIC = utils.FieldSet(
3299
    "dtotal", "dfree",
3300
    "mtotal", "mnode", "mfree",
3301
    "bootid",
3302
    "ctotal", "cnodes", "csockets",
3303
    )
3304

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

    
3313
  def CheckArguments(self):
3314
    _CheckOutputFields(static=self._FIELDS_STATIC,
3315
                       dynamic=self._FIELDS_DYNAMIC,
3316
                       selected=self.op.output_fields)
3317

    
3318
  def ExpandNames(self):
3319
    self.needed_locks = {}
3320
    self.share_locks[locking.LEVEL_NODE] = 1
3321

    
3322
    if self.op.names:
3323
      self.wanted = _GetWantedNodes(self, self.op.names)
3324
    else:
3325
      self.wanted = locking.ALL_SET
3326

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

    
3333
  def Exec(self, feedback_fn):
3334
    """Computes the list of nodes and their attributes.
3335

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

    
3349
    nodenames = utils.NiceSort(nodenames)
3350
    nodelist = [all_info[name] for name in nodenames]
3351

    
3352
    # begin data gathering
3353

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

    
3379
    node_to_primary = dict([(name, set()) for name in nodenames])
3380
    node_to_secondary = dict([(name, set()) for name in nodenames])
3381

    
3382
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
3383
                             "sinst_cnt", "sinst_list"))
3384
    if inst_fields & frozenset(self.op.output_fields):
3385
      inst_data = self.cfg.GetAllInstancesInfo()
3386

    
3387
      for inst in inst_data.values():
3388
        if inst.primary_node in node_to_primary:
3389
          node_to_primary[inst.primary_node].add(inst.name)
3390
        for secnode in inst.secondary_nodes:
3391
          if secnode in node_to_secondary:
3392
            node_to_secondary[secnode].add(inst.name)
3393

    
3394
    master_node = self.cfg.GetMasterNode()
3395

    
3396
    # end data gathering
3397

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

    
3438
    return output
3439

    
3440

    
3441
class LUQueryNodeVolumes(NoHooksLU):
3442
  """Logical unit for getting volumes on node(s).
3443

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

    
3453
  def CheckArguments(self):
3454
    _CheckOutputFields(static=self._FIELDS_STATIC,
3455
                       dynamic=self._FIELDS_DYNAMIC,
3456
                       selected=self.op.output_fields)
3457

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

    
3467
  def Exec(self, feedback_fn):
3468
    """Computes the list of nodes and their attributes.
3469

3470
    """
3471
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3472
    volumes = self.rpc.call_node_volumes(nodenames)
3473

    
3474
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3475
             in self.cfg.GetInstanceList()]
3476

    
3477
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3478

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

    
3489
      node_vols = nresult.payload[:]
3490
      node_vols.sort(key=lambda vol: vol['dev'])
3491

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

    
3518
        output.append(node_output)
3519

    
3520
    return output
3521

    
3522

    
3523
class LUQueryNodeStorage(NoHooksLU):
3524
  """Logical unit for getting information on storage units on node(s).
3525

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

    
3536
  def CheckArguments(self):
3537
    _CheckOutputFields(static=self._FIELDS_STATIC,
3538
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3539
                       selected=self.op.output_fields)
3540

    
3541
  def ExpandNames(self):
3542
    self.needed_locks = {}
3543
    self.share_locks[locking.LEVEL_NODE] = 1
3544

    
3545
    if self.op.nodes:
3546
      self.needed_locks[locking.LEVEL_NODE] = \
3547
        _GetWantedNodes(self, self.op.nodes)
3548
    else:
3549
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3550

    
3551
  def Exec(self, feedback_fn):
3552
    """Computes the list of nodes and their attributes.
3553

3554
    """
3555
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3556

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

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

    
3568
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3569
    name_idx = field_idx[constants.SF_NAME]
3570

    
3571
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3572
    data = self.rpc.call_storage_list(self.nodes,
3573
                                      self.op.storage_type, st_args,
3574
                                      self.op.name, fields)
3575

    
3576
    result = []
3577

    
3578
    for node in utils.NiceSort(self.nodes):
3579
      nresult = data[node]
3580
      if nresult.offline:
3581
        continue
3582

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

    
3588
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3589

    
3590
      for name in utils.NiceSort(rows.keys()):
3591
        row = rows[name]
3592

    
3593
        out = []
3594

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

    
3605
          out.append(val)
3606

    
3607
        result.append(out)
3608

    
3609
    return result
3610

    
3611

    
3612
class LUModifyNodeStorage(NoHooksLU):
3613
  """Logical unit for modifying a storage volume on a node.
3614

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

    
3624
  def CheckArguments(self):
3625
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3626

    
3627
    storage_type = self.op.storage_type
3628

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

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

    
3643
  def ExpandNames(self):
3644
    self.needed_locks = {
3645
      locking.LEVEL_NODE: self.op.node_name,
3646
      }
3647

    
3648
  def Exec(self, feedback_fn):
3649
    """Computes the list of nodes and their attributes.
3650

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

    
3659

    
3660
class LUAddNode(LogicalUnit):
3661
  """Logical unit for adding node to the cluster.
3662

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

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

    
3680
  def BuildHooksEnv(self):
3681
    """Build hooks env.
3682

3683
    This will run on all nodes before, and on all nodes + the new node after.
3684

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

    
3696
  def CheckPrereq(self):
3697
    """Check prerequisites.
3698

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

3704
    Any errors are signaled by raising errors.OpPrereqError.
3705

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

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

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

    
3731
    self.changed_primary_ip = False
3732

    
3733
    for existing_node_name in node_list:
3734
      existing_node = cfg.GetNodeInfo(existing_node_name)
3735

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

    
3744
        continue
3745

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

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

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

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

    
3782
    if self.op.readd:
3783
      exceptions = [node]
3784
    else:
3785
      exceptions = []
3786

    
3787
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3788

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

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

3802
    """
3803
    new_node = self.new_node
3804
    node = new_node.name
3805

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

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

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

    
3833
    # Add node to our /etc/hosts, and add key to known_hosts
3834
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3835
      master_node = self.cfg.GetMasterNode()
3836
      result = self.rpc.call_etc_hosts_modify(master_node,
3837
                                              constants.ETC_HOSTS_ADD,
3838
                                              self.hostname.name,
3839
                                              self.hostname.ip)
3840
      result.Raise("Can't update hosts file with new host data")
3841

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

    
3852
    node_verify_list = [self.cfg.GetMasterNode()]
3853
    node_verify_param = {
3854
      constants.NV_NODELIST: [node],
3855
      # TODO: do a node-net-test as well?
3856
    }
3857

    
3858
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3859
                                       self.cfg.GetClusterName())
3860
    for verifier in node_verify_list:
3861
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3862
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3863
      if nl_payload:
3864
        for failed in nl_payload:
3865
          feedback_fn("ssh/hostname verification failed"
3866
                      " (checking from %s): %s" %
3867
                      (verifier, nl_payload[failed]))
3868
        raise errors.OpExecError("ssh/hostname verification failed.")
3869

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

    
3886

    
3887
class LUSetNodeParams(LogicalUnit):
3888
  """Modifies the parameters of a node.
3889

3890
  """
3891
  HPATH = "node-modify"
3892
  HTYPE = constants.HTYPE_NODE
3893
  _OP_PARAMS = [
3894
    _PNodeName,
3895
    ("master_candidate", None, _TMaybeBool),
3896
    ("offline", None, _TMaybeBool),
3897
    ("drained", None, _TMaybeBool),
3898
    ("auto_promote", False, _TBool),
3899
    _PForce,
3900
    ]
3901
  REQ_BGL = False
3902

    
3903
  def CheckArguments(self):
3904
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3905
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
3906
    if all_mods.count(None) == 3:
3907
      raise errors.OpPrereqError("Please pass at least one modification",
3908
                                 errors.ECODE_INVAL)
3909
    if all_mods.count(True) > 1:
3910
      raise errors.OpPrereqError("Can't set the node into more than one"
3911
                                 " state at the same time",
3912
                                 errors.ECODE_INVAL)
3913

    
3914
    # Boolean value that tells us whether we're offlining or draining the node
3915
    self.offline_or_drain = (self.op.offline == True or
3916
                             self.op.drained == True)
3917
    self.deoffline_or_drain = (self.op.offline == False or
3918
                               self.op.drained == False)
3919
    self.might_demote = (self.op.master_candidate == False or
3920
                         self.offline_or_drain)
3921

    
3922
    self.lock_all = self.op.auto_promote and self.might_demote
3923

    
3924

    
3925
  def ExpandNames(self):
3926
    if self.lock_all:
3927
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
3928
    else:
3929
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3930

    
3931
  def BuildHooksEnv(self):
3932
    """Build hooks env.
3933

3934
    This runs on the master node.
3935

3936
    """
3937
    env = {
3938
      "OP_TARGET": self.op.node_name,
3939
      "MASTER_CANDIDATE": str(self.op.master_candidate),
3940
      "OFFLINE": str(self.op.offline),
3941
      "DRAINED": str(self.op.drained),
3942
      }
3943
    nl = [self.cfg.GetMasterNode(),
3944
          self.op.node_name]
3945
    return env, nl, nl
3946

    
3947
  def CheckPrereq(self):
3948
    """Check prerequisites.
3949

3950
    This only checks the instance list against the existing names.
3951

3952
    """
3953
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3954

    
3955
    if (self.op.master_candidate is not None or
3956
        self.op.drained is not None or
3957
        self.op.offline is not None):
3958
      # we can't change the master's node flags
3959
      if self.op.node_name == self.cfg.GetMasterNode():
3960
        raise errors.OpPrereqError("The master role can be changed"
3961
                                   " only via master-failover",
3962
                                   errors.ECODE_INVAL)
3963

    
3964

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

    
3976
    if (self.op.master_candidate == True and
3977
        ((node.offline and not self.op.offline == False) or
3978
         (node.drained and not self.op.drained == False))):
3979
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
3980
                                 " to master_candidate" % node.name,
3981
                                 errors.ECODE_INVAL)
3982

    
3983
    # If we're being deofflined/drained, we'll MC ourself if needed
3984
    if (self.deoffline_or_drain and not self.offline_or_drain and not
3985
        self.op.master_candidate == True and not node.master_candidate):
3986
      self.op.master_candidate = _DecideSelfPromotion(self)
3987
      if self.op.master_candidate:
3988
        self.LogInfo("Autopromoting node to master candidate")
3989

    
3990
    return
3991

    
3992
  def Exec(self, feedback_fn):
3993
    """Modifies a node.
3994

3995
    """
3996
    node = self.node
3997

    
3998
    result = []
3999
    changed_mc = False
4000

    
4001
    if self.op.offline is not None:
4002
      node.offline = self.op.offline
4003
      result.append(("offline", str(self.op.offline)))
4004
      if self.op.offline == True:
4005
        if node.master_candidate:
4006
          node.master_candidate = False
4007
          changed_mc = True
4008
          result.append(("master_candidate", "auto-demotion due to offline"))
4009
        if node.drained:
4010
          node.drained = False
4011
          result.append(("drained", "clear drained status due to offline"))
4012

    
4013
    if self.op.master_candidate is not None:
4014
      node.master_candidate = self.op.master_candidate
4015
      changed_mc = True
4016
      result.append(("master_candidate", str(self.op.master_candidate)))
4017
      if self.op.master_candidate == False:
4018
        rrc = self.rpc.call_node_demote_from_mc(node.name)
4019
        msg = rrc.fail_msg
4020
        if msg:
4021
          self.LogWarning("Node failed to demote itself: %s" % msg)
4022

    
4023
    if self.op.drained is not None:
4024
      node.drained = self.op.drained
4025
      result.append(("drained", str(self.op.drained)))
4026
      if self.op.drained == True:
4027
        if node.master_candidate:
4028
          node.master_candidate = False
4029
          changed_mc = True
4030
          result.append(("master_candidate", "auto-demotion due to drain"))
4031
          rrc = self.rpc.call_node_demote_from_mc(node.name)
4032
          msg = rrc.fail_msg
4033
          if msg:
4034
            self.LogWarning("Node failed to demote itself: %s" % msg)
4035
        if node.offline:
4036
          node.offline = False
4037
          result.append(("offline", "clear offline status due to drain"))
4038

    
4039
    # we locked all nodes, we adjust the CP before updating this node
4040
    if self.lock_all:
4041
      _AdjustCandidatePool(self, [node.name])
4042

    
4043
    # this will trigger configuration file update, if needed
4044
    self.cfg.Update(node, feedback_fn)
4045

    
4046
    # this will trigger job queue propagation or cleanup
4047
    if changed_mc:
4048
      self.context.ReaddNode(node)
4049

    
4050
    return result
4051

    
4052

    
4053
class LUPowercycleNode(NoHooksLU):
4054
  """Powercycles a node.
4055

4056
  """
4057
  _OP_PARAMS = [
4058
    _PNodeName,
4059
    _PForce,
4060
    ]
4061
  REQ_BGL = False
4062

    
4063
  def CheckArguments(self):
4064
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4065
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4066
      raise errors.OpPrereqError("The node is the master and the force"
4067
                                 " parameter was not set",
4068
                                 errors.ECODE_INVAL)
4069

    
4070
  def ExpandNames(self):
4071
    """Locking for PowercycleNode.
4072

4073
    This is a last-resort option and shouldn't block on other
4074
    jobs. Therefore, we grab no locks.
4075

4076
    """
4077
    self.needed_locks = {}
4078

    
4079
  def Exec(self, feedback_fn):
4080
    """Reboots a node.
4081

4082
    """
4083
    result = self.rpc.call_node_powercycle(self.op.node_name,
4084
                                           self.cfg.GetHypervisorType())
4085
    result.Raise("Failed to schedule the reboot")
4086
    return result.payload
4087

    
4088

    
4089
class LUQueryClusterInfo(NoHooksLU):
4090
  """Query cluster configuration.
4091

4092
  """
4093
  REQ_BGL = False
4094

    
4095
  def ExpandNames(self):
4096
    self.needed_locks = {}
4097

    
4098
  def Exec(self, feedback_fn):
4099
    """Return cluster config.
4100

4101
    """
4102
    cluster = self.cfg.GetClusterInfo()
4103
    os_hvp = {}
4104

    
4105
    # Filter just for enabled hypervisors
4106
    for os_name, hv_dict in cluster.os_hvp.items():
4107
      os_hvp[os_name] = {}
4108
      for hv_name, hv_params in hv_dict.items():
4109
        if hv_name in cluster.enabled_hypervisors:
4110
          os_hvp[os_name][hv_name] = hv_params
4111

    
4112
    # Convert ip_family to ip_version
4113
    primary_ip_version = constants.IP4_VERSION
4114
    if cluster.primary_ip_family == netutils.IP6Address.family:
4115
      primary_ip_version = constants.IP6_VERSION
4116

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

    
4150
    return result
4151

    
4152

    
4153
class LUQueryConfigValues(NoHooksLU):
4154
  """Return configuration values.
4155

4156
  """
4157
  _OP_PARAMS = [_POutputFields]
4158
  REQ_BGL = False
4159
  _FIELDS_DYNAMIC = utils.FieldSet()
4160
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4161
                                  "watcher_pause")
4162

    
4163
  def CheckArguments(self):
4164
    _CheckOutputFields(static=self._FIELDS_STATIC,
4165
                       dynamic=self._FIELDS_DYNAMIC,
4166
                       selected=self.op.output_fields)
4167

    
4168
  def ExpandNames(self):
4169
    self.needed_locks = {}
4170

    
4171
  def Exec(self, feedback_fn):
4172
    """Dump a representation of the cluster config to the standard output.
4173

4174
    """
4175
    values = []
4176
    for field in self.op.output_fields:
4177
      if field == "cluster_name":
4178
        entry = self.cfg.GetClusterName()
4179
      elif field == "master_node":
4180
        entry = self.cfg.GetMasterNode()
4181
      elif field == "drain_flag":
4182
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4183
      elif field == "watcher_pause":
4184
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4185
      else:
4186
        raise errors.ParameterError(field)
4187
      values.append(entry)
4188
    return values
4189

    
4190

    
4191
class LUActivateInstanceDisks(NoHooksLU):
4192
  """Bring up an instance's disks.
4193

4194
  """
4195
  _OP_PARAMS = [
4196
    _PInstanceName,
4197
    ("ignore_size", False, _TBool),
4198
    ]
4199
  REQ_BGL = False
4200

    
4201
  def ExpandNames(self):
4202
    self._ExpandAndLockInstance()
4203
    self.needed_locks[locking.LEVEL_NODE] = []
4204
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4205

    
4206
  def DeclareLocks(self, level):
4207
    if level == locking.LEVEL_NODE:
4208
      self._LockInstancesNodes()
4209

    
4210
  def CheckPrereq(self):
4211
    """Check prerequisites.
4212

4213
    This checks that the instance is in the cluster.
4214

4215
    """
4216
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4217
    assert self.instance is not None, \
4218
      "Cannot retrieve locked instance %s" % self.op.instance_name
4219
    _CheckNodeOnline(self, self.instance.primary_node)
4220

    
4221
  def Exec(self, feedback_fn):
4222
    """Activate the disks.
4223

4224
    """
4225
    disks_ok, disks_info = \
4226
              _AssembleInstanceDisks(self, self.instance,
4227
                                     ignore_size=self.op.ignore_size)
4228
    if not disks_ok:
4229
      raise errors.OpExecError("Cannot activate block devices")
4230

    
4231
    return disks_info
4232

    
4233

    
4234
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4235
                           ignore_size=False):
4236
  """Prepare the block devices for an instance.
4237

4238
  This sets up the block devices on all nodes.
4239

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

4257
  """
4258
  device_info = []
4259
  disks_ok = True
4260
  iname = instance.name
4261
  disks = _ExpandCheckDisks(instance, disks)
4262

    
4263
  # With the two passes mechanism we try to reduce the window of
4264
  # opportunity for the race condition of switching DRBD to primary
4265
  # before handshaking occured, but we do not eliminate it
4266

    
4267
  # The proper fix would be to wait (with some limits) until the
4268
  # connection has been made and drbd transitions from WFConnection
4269
  # into any other network-connected state (Connected, SyncTarget,
4270
  # SyncSource, etc.)
4271

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

    
4288
  # FIXME: race condition on drbd migration to primary
4289

    
4290
  # 2nd pass, do only the primary node
4291
  for inst_disk in disks:
4292
    dev_path = None
4293

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

    
4311
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4312

    
4313
  # leave the disks configured for the primary node
4314
  # this is a workaround that would be fixed better by
4315
  # improving the logical/physical id handling
4316
  for disk in disks:
4317
    lu.cfg.SetDiskID(disk, instance.primary_node)
4318

    
4319
  return disks_ok, device_info
4320

    
4321

    
4322
def _StartInstanceDisks(lu, instance, force):
4323
  """Start the disks of an instance.
4324

4325
  """
4326
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4327
                                           ignore_secondaries=force)
4328
  if not disks_ok:
4329
    _ShutdownInstanceDisks(lu, instance)
4330
    if force is not None and not force:
4331
      lu.proc.LogWarning("", hint="If the message above refers to a"
4332
                         " secondary node,"
4333
                         " you can retry the operation using '--force'.")
4334
    raise errors.OpExecError("Disk consistency error")
4335

    
4336

    
4337
class LUDeactivateInstanceDisks(NoHooksLU):
4338
  """Shutdown an instance's disks.
4339

4340
  """
4341
  _OP_PARAMS = [
4342
    _PInstanceName,
4343
    ]
4344
  REQ_BGL = False
4345

    
4346
  def ExpandNames(self):
4347
    self._ExpandAndLockInstance()
4348
    self.needed_locks[locking.LEVEL_NODE] = []
4349
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4350

    
4351
  def DeclareLocks(self, level):
4352
    if level == locking.LEVEL_NODE:
4353
      self._LockInstancesNodes()
4354

    
4355
  def CheckPrereq(self):
4356
    """Check prerequisites.
4357

4358
    This checks that the instance is in the cluster.
4359

4360
    """
4361
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4362
    assert self.instance is not None, \
4363
      "Cannot retrieve locked instance %s" % self.op.instance_name
4364

    
4365
  def Exec(self, feedback_fn):
4366
    """Deactivate the disks
4367

4368
    """
4369
    instance = self.instance
4370
    _SafeShutdownInstanceDisks(self, instance)
4371

    
4372

    
4373
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4374
  """Shutdown block devices of an instance.
4375

4376
  This function checks if an instance is running, before calling
4377
  _ShutdownInstanceDisks.
4378

4379
  """
4380
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4381
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4382

    
4383

    
4384
def _ExpandCheckDisks(instance, disks):
4385
  """Return the instance disks selected by the disks list
4386

4387
  @type disks: list of L{objects.Disk} or None
4388
  @param disks: selected disks
4389
  @rtype: list of L{objects.Disk}
4390
  @return: selected instance disks to act on
4391

4392
  """
4393
  if disks is None:
4394
    return instance.disks
4395
  else:
4396
    if not set(disks).issubset(instance.disks):
4397
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4398
                                   " target instance")
4399
    return disks
4400

    
4401

    
4402
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4403
  """Shutdown block devices of an instance.
4404

4405
  This does the shutdown on all nodes of the instance.
4406

4407
  If the ignore_primary is false, errors on the primary node are
4408
  ignored.
4409

4410
  """
4411
  all_result = True
4412
  disks = _ExpandCheckDisks(instance, disks)
4413

    
4414
  for disk in disks:
4415
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4416
      lu.cfg.SetDiskID(top_disk, node)
4417
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4418
      msg = result.fail_msg
4419
      if msg:
4420
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4421
                      disk.iv_name, node, msg)
4422
        if not ignore_primary or node != instance.primary_node:
4423
          all_result = False
4424
  return all_result
4425

    
4426

    
4427
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4428
  """Checks if a node has enough free memory.
4429

4430
  This function check if a given node has the needed amount of free
4431
  memory. In case the node has less memory or we cannot get the
4432
  information from the node, this function raise an OpPrereqError
4433
  exception.
4434

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

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

    
4463

    
4464
def _CheckNodesFreeDisk(lu, nodenames, requested):
4465
  """Checks if nodes have enough free disk space in the default VG.
4466

4467
  This function check if all given nodes have the needed amount of
4468
  free disk. In case any node has less disk or we cannot get the
4469
  information from the node, this function raise an OpPrereqError
4470
  exception.
4471

4472
  @type lu: C{LogicalUnit}
4473
  @param lu: a logical unit from which we get configuration data
4474
  @type nodenames: C{list}
4475
  @param nodenames: the list of node names to check
4476
  @type requested: C{int}
4477
  @param requested: the amount of disk in MiB to check for
4478
  @raise errors.OpPrereqError: if the node doesn't have enough disk, or
4479
      we cannot check the node
4480

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

    
4499

    
4500
class LUStartupInstance(LogicalUnit):
4501
  """Starts an instance.
4502

4503
  """
4504
  HPATH = "instance-start"
4505
  HTYPE = constants.HTYPE_INSTANCE
4506
  _OP_PARAMS = [
4507
    _PInstanceName,
4508
    _PForce,
4509
    ("hvparams", _EmptyDict, _TDict),
4510
    ("beparams", _EmptyDict, _TDict),
4511
    ]
4512
  REQ_BGL = False
4513

    
4514
  def CheckArguments(self):
4515
    # extra beparams
4516
    if self.op.beparams:
4517
      # fill the beparams dict
4518
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
4519

    
4520
  def ExpandNames(self):
4521
    self._ExpandAndLockInstance()
4522

    
4523
  def BuildHooksEnv(self):
4524
    """Build hooks env.
4525

4526
    This runs on master, primary and secondary nodes of the instance.
4527

4528
    """
4529
    env = {
4530
      "FORCE": self.op.force,
4531
      }
4532
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4533
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4534
    return env, nl, nl
4535

    
4536
  def CheckPrereq(self):
4537
    """Check prerequisites.
4538

4539
    This checks that the instance is in the cluster.
4540

4541
    """
4542
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4543
    assert self.instance is not None, \
4544
      "Cannot retrieve locked instance %s" % self.op.instance_name
4545

    
4546
    # extra hvparams
4547
    if self.op.hvparams:
4548
      # check hypervisor parameter syntax (locally)
4549
      cluster = self.cfg.GetClusterInfo()
4550
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
4551
      filled_hvp = cluster.FillHV(instance)
4552
      filled_hvp.update(self.op.hvparams)
4553
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
4554
      hv_type.CheckParameterSyntax(filled_hvp)
4555
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
4556

    
4557
    _CheckNodeOnline(self, instance.primary_node)
4558

    
4559
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4560
    # check bridges existence
4561
    _CheckInstanceBridgesExist(self, instance)
4562

    
4563
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4564
                                              instance.name,
4565
                                              instance.hypervisor)
4566
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4567
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4568
    if not remote_info.payload: # not running already
4569
      _CheckNodeFreeMemory(self, instance.primary_node,
4570
                           "starting instance %s" % instance.name,
4571
                           bep[constants.BE_MEMORY], instance.hypervisor)
4572

    
4573
  def Exec(self, feedback_fn):
4574
    """Start the instance.
4575

4576
    """
4577
    instance = self.instance
4578
    force = self.op.force
4579

    
4580
    self.cfg.MarkInstanceUp(instance.name)
4581

    
4582
    node_current = instance.primary_node
4583

    
4584
    _StartInstanceDisks(self, instance, force)
4585

    
4586
    result = self.rpc.call_instance_start(node_current, instance,
4587
                                          self.op.hvparams, self.op.beparams)
4588
    msg = result.fail_msg
4589
    if msg:
4590
      _ShutdownInstanceDisks(self, instance)
4591
      raise errors.OpExecError("Could not start instance: %s" % msg)
4592

    
4593

    
4594
class LURebootInstance(LogicalUnit):
4595
  """Reboot an instance.
4596

4597
  """
4598
  HPATH = "instance-reboot"
4599
  HTYPE = constants.HTYPE_INSTANCE
4600
  _OP_PARAMS = [
4601
    _PInstanceName,
4602
    ("ignore_secondaries", False, _TBool),
4603
    ("reboot_type", _NoDefault, _TElemOf(constants.REBOOT_TYPES)),
4604
    _PShutdownTimeout,
4605
    ]
4606
  REQ_BGL = False
4607

    
4608
  def ExpandNames(self):
4609
    self._ExpandAndLockInstance()
4610

    
4611
  def BuildHooksEnv(self):
4612
    """Build hooks env.
4613

4614
    This runs on master, primary and secondary nodes of the instance.
4615

4616
    """
4617
    env = {
4618
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
4619
      "REBOOT_TYPE": self.op.reboot_type,
4620
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
4621
      }
4622
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4623
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4624
    return env, nl, nl
4625

    
4626
  def CheckPrereq(self):
4627
    """Check prerequisites.
4628

4629
    This checks that the instance is in the cluster.
4630

4631
    """
4632
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4633
    assert self.instance is not None, \
4634
      "Cannot retrieve locked instance %s" % self.op.instance_name
4635

    
4636
    _CheckNodeOnline(self, instance.primary_node)
4637

    
4638
    # check bridges existence
4639
    _CheckInstanceBridgesExist(self, instance)
4640

    
4641
  def Exec(self, feedback_fn):
4642
    """Reboot the instance.
4643

4644
    """
4645
    instance = self.instance
4646
    ignore_secondaries = self.op.ignore_secondaries
4647
    reboot_type = self.op.reboot_type
4648

    
4649
    node_current = instance.primary_node
4650

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

    
4672
    self.cfg.MarkInstanceUp(instance.name)
4673

    
4674

    
4675
class LUShutdownInstance(LogicalUnit):
4676
  """Shutdown an instance.
4677

4678
  """
4679
  HPATH = "instance-stop"
4680
  HTYPE = constants.HTYPE_INSTANCE
4681
  _OP_PARAMS = [
4682
    _PInstanceName,
4683
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, _TPositiveInt),
4684
    ]
4685
  REQ_BGL = False
4686

    
4687
  def ExpandNames(self):
4688
    self._ExpandAndLockInstance()
4689

    
4690
  def BuildHooksEnv(self):
4691
    """Build hooks env.
4692

4693
    This runs on master, primary and secondary nodes of the instance.
4694

4695
    """
4696
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4697
    env["TIMEOUT"] = self.op.timeout
4698
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4699
    return env, nl, nl
4700

    
4701
  def CheckPrereq(self):
4702
    """Check prerequisites.
4703

4704
    This checks that the instance is in the cluster.
4705

4706
    """
4707
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4708
    assert self.instance is not None, \
4709
      "Cannot retrieve locked instance %s" % self.op.instance_name
4710
    _CheckNodeOnline(self, self.instance.primary_node)
4711

    
4712
  def Exec(self, feedback_fn):
4713
    """Shutdown the instance.
4714

4715
    """
4716
    instance = self.instance
4717
    node_current = instance.primary_node
4718
    timeout = self.op.timeout
4719
    self.cfg.MarkInstanceDown(instance.name)
4720
    result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
4721
    msg = result.fail_msg
4722
    if msg:
4723
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
4724

    
4725
    _ShutdownInstanceDisks(self, instance)
4726

    
4727

    
4728
class LUReinstallInstance(LogicalUnit):
4729
  """Reinstall an instance.
4730

4731
  """
4732
  HPATH = "instance-reinstall"
4733
  HTYPE = constants.HTYPE_INSTANCE
4734
  _OP_PARAMS = [
4735
    _PInstanceName,
4736
    ("os_type", None, _TMaybeString),
4737
    ("force_variant", False, _TBool),
4738
    ]
4739
  REQ_BGL = False
4740

    
4741
  def ExpandNames(self):
4742
    self._ExpandAndLockInstance()
4743

    
4744
  def BuildHooksEnv(self):
4745
    """Build hooks env.
4746

4747
    This runs on master, primary and secondary nodes of the instance.
4748

4749
    """
4750
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4751
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4752
    return env, nl, nl
4753

    
4754
  def CheckPrereq(self):
4755
    """Check prerequisites.
4756

4757
    This checks that the instance is in the cluster and is not running.
4758

4759
    """
4760
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4761
    assert instance is not None, \
4762
      "Cannot retrieve locked instance %s" % self.op.instance_name
4763
    _CheckNodeOnline(self, instance.primary_node)
4764

    
4765
    if instance.disk_template == constants.DT_DISKLESS:
4766
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4767
                                 self.op.instance_name,
4768
                                 errors.ECODE_INVAL)
4769
    _CheckInstanceDown(self, instance, "cannot reinstall")
4770

    
4771
    if self.op.os_type is not None:
4772
      # OS verification
4773
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
4774
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
4775

    
4776
    self.instance = instance
4777

    
4778
  def Exec(self, feedback_fn):
4779
    """Reinstall the instance.
4780

4781
    """
4782
    inst = self.instance
4783

    
4784
    if self.op.os_type is not None:
4785
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
4786
      inst.os = self.op.os_type
4787
      self.cfg.Update(inst, feedback_fn)
4788

    
4789
    _StartInstanceDisks(self, inst, None)
4790
    try:
4791
      feedback_fn("Running the instance OS create scripts...")
4792
      # FIXME: pass debug option from opcode to backend
4793
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
4794
                                             self.op.debug_level)
4795
      result.Raise("Could not install OS for instance %s on node %s" %
4796
                   (inst.name, inst.primary_node))
4797
    finally:
4798
      _ShutdownInstanceDisks(self, inst)
4799

    
4800

    
4801
class LURecreateInstanceDisks(LogicalUnit):
4802
  """Recreate an instance's missing disks.
4803

4804
  """
4805
  HPATH = "instance-recreate-disks"
4806
  HTYPE = constants.HTYPE_INSTANCE
4807
  _OP_PARAMS = [
4808
    _PInstanceName,
4809
    ("disks", _EmptyList, _TListOf(_TPositiveInt)),
4810
    ]
4811
  REQ_BGL = False
4812

    
4813
  def ExpandNames(self):
4814
    self._ExpandAndLockInstance()
4815

    
4816
  def BuildHooksEnv(self):
4817
    """Build hooks env.
4818

4819
    This runs on master, primary and secondary nodes of the instance.
4820

4821
    """
4822
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4823
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4824
    return env, nl, nl
4825

    
4826
  def CheckPrereq(self):
4827
    """Check prerequisites.
4828

4829
    This checks that the instance is in the cluster and is not running.
4830

4831
    """
4832
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4833
    assert instance is not None, \
4834
      "Cannot retrieve locked instance %s" % self.op.instance_name
4835
    _CheckNodeOnline(self, instance.primary_node)
4836

    
4837
    if instance.disk_template == constants.DT_DISKLESS:
4838
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4839
                                 self.op.instance_name, errors.ECODE_INVAL)
4840
    _CheckInstanceDown(self, instance, "cannot recreate disks")
4841

    
4842
    if not self.op.disks:
4843
      self.op.disks = range(len(instance.disks))
4844
    else:
4845
      for idx in self.op.disks:
4846
        if idx >= len(instance.disks):
4847
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
4848
                                     errors.ECODE_INVAL)
4849

    
4850
    self.instance = instance
4851

    
4852
  def Exec(self, feedback_fn):
4853
    """Recreate the disks.
4854

4855
    """
4856
    to_skip = []
4857
    for idx, _ in enumerate(self.instance.disks):
4858
      if idx not in self.op.disks: # disk idx has not been passed in
4859
        to_skip.append(idx)
4860
        continue
4861

    
4862
    _CreateDisks(self, self.instance, to_skip=to_skip)
4863

    
4864

    
4865
class LURenameInstance(LogicalUnit):
4866
  """Rename an instance.
4867

4868
  """
4869
  HPATH = "instance-rename"
4870
  HTYPE = constants.HTYPE_INSTANCE
4871
  _OP_PARAMS = [
4872
    _PInstanceName,
4873
    ("new_name", _NoDefault, _TNonEmptyString),
4874
    ("ip_check", False, _TBool),
4875
    ("name_check", True, _TBool),
4876
    ]
4877

    
4878
  def CheckArguments(self):
4879
    """Check arguments.
4880

4881
    """
4882
    if self.op.ip_check and not self.op.name_check:
4883
      # TODO: make the ip check more flexible and not depend on the name check
4884
      raise errors.OpPrereqError("Cannot do ip check without a name check",
4885
                                 errors.ECODE_INVAL)
4886

    
4887
  def BuildHooksEnv(self):
4888
    """Build hooks env.
4889

4890
    This runs on master, primary and secondary nodes of the instance.
4891

4892
    """
4893
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4894
    env["INSTANCE_NEW_NAME"] = self.op.new_name
4895
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4896
    return env, nl, nl
4897

    
4898
  def CheckPrereq(self):
4899
    """Check prerequisites.
4900

4901
    This checks that the instance is in the cluster and is not running.
4902

4903
    """
4904
    self.op.instance_name = _ExpandInstanceName(self.cfg,
4905
                                                self.op.instance_name)
4906
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4907
    assert instance is not None
4908
    _CheckNodeOnline(self, instance.primary_node)
4909
    _CheckInstanceDown(self, instance, "cannot rename")
4910
    self.instance = instance
4911

    
4912
    new_name = self.op.new_name
4913
    if self.op.name_check:
4914
      hostname = netutils.GetHostname(name=new_name)
4915
      new_name = hostname.name
4916
      if (self.op.ip_check and
4917
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
4918
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4919
                                   (hostname.ip, new_name),
4920
                                   errors.ECODE_NOTUNIQUE)
4921

    
4922
    instance_list = self.cfg.GetInstanceList()
4923
    if new_name in instance_list:
4924
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4925
                                 new_name, errors.ECODE_EXISTS)
4926

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

4930
    """
4931
    inst = self.instance
4932
    old_name = inst.name
4933

    
4934
    if inst.disk_template == constants.DT_FILE:
4935
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4936

    
4937
    self.cfg.RenameInstance(inst.name, self.op.new_name)
4938
    # Change the instance lock. This is definitely safe while we hold the BGL
4939
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
4940
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
4941

    
4942
    # re-read the instance from the configuration after rename
4943
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
4944

    
4945
    if inst.disk_template == constants.DT_FILE:
4946
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4947
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
4948
                                                     old_file_storage_dir,
4949
                                                     new_file_storage_dir)
4950
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
4951
                   " (but the instance has been renamed in Ganeti)" %
4952
                   (inst.primary_node, old_file_storage_dir,
4953
                    new_file_storage_dir))
4954

    
4955
    _StartInstanceDisks(self, inst, None)
4956
    try:
4957
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
4958
                                                 old_name, self.op.debug_level)
4959
      msg = result.fail_msg
4960
      if msg:
4961
        msg = ("Could not run OS rename script for instance %s on node %s"
4962
               " (but the instance has been renamed in Ganeti): %s" %
4963
               (inst.name, inst.primary_node, msg))
4964
        self.proc.LogWarning(msg)
4965
    finally:
4966
      _ShutdownInstanceDisks(self, inst)
4967

    
4968
    return inst.name
4969

    
4970

    
4971
class LURemoveInstance(LogicalUnit):
4972
  """Remove an instance.
4973

4974
  """
4975
  HPATH = "instance-remove"
4976
  HTYPE = constants.HTYPE_INSTANCE
4977
  _OP_PARAMS = [
4978
    _PInstanceName,
4979
    ("ignore_failures", False, _TBool),
4980
    _PShutdownTimeout,
4981
    ]
4982
  REQ_BGL = False
4983

    
4984
  def ExpandNames(self):
4985
    self._ExpandAndLockInstance()
4986
    self.needed_locks[locking.LEVEL_NODE] = []
4987
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4988

    
4989
  def DeclareLocks(self, level):
4990
    if level == locking.LEVEL_NODE:
4991
      self._LockInstancesNodes()
4992

    
4993
  def BuildHooksEnv(self):
4994
    """Build hooks env.
4995

4996
    This runs on master, primary and secondary nodes of the instance.
4997

4998
    """
4999
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5000
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
5001
    nl = [self.cfg.GetMasterNode()]
5002
    nl_post = list(self.instance.all_nodes) + nl
5003
    return env, nl, nl_post
5004

    
5005
  def CheckPrereq(self):
5006
    """Check prerequisites.
5007

5008
    This checks that the instance is in the cluster.
5009

5010
    """
5011
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5012
    assert self.instance is not None, \
5013
      "Cannot retrieve locked instance %s" % self.op.instance_name
5014

    
5015
  def Exec(self, feedback_fn):
5016
    """Remove the instance.
5017

5018
    """
5019
    instance = self.instance
5020
    logging.info("Shutting down instance %s on node %s",
5021
                 instance.name, instance.primary_node)
5022

    
5023
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5024
                                             self.op.shutdown_timeout)
5025
    msg = result.fail_msg
5026
    if msg:
5027
      if self.op.ignore_failures:
5028
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5029
      else:
5030
        raise errors.OpExecError("Could not shutdown instance %s on"
5031
                                 " node %s: %s" %
5032
                                 (instance.name, instance.primary_node, msg))
5033

    
5034
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5035

    
5036

    
5037
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5038
  """Utility function to remove an instance.
5039

5040
  """
5041
  logging.info("Removing block devices for instance %s", instance.name)
5042

    
5043
  if not _RemoveDisks(lu, instance):
5044
    if not ignore_failures:
5045
      raise errors.OpExecError("Can't remove instance's disks")
5046
    feedback_fn("Warning: can't remove instance's disks")
5047

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

    
5050
  lu.cfg.RemoveInstance(instance.name)
5051

    
5052
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5053
    "Instance lock removal conflict"
5054

    
5055
  # Remove lock for the instance
5056
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5057

    
5058

    
5059
class LUQueryInstances(NoHooksLU):
5060
  """Logical unit for querying instances.
5061

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

    
5096

    
5097
  def CheckArguments(self):
5098
    _CheckOutputFields(static=self._FIELDS_STATIC,
5099
                       dynamic=self._FIELDS_DYNAMIC,
5100
                       selected=self.op.output_fields)
5101

    
5102
  def ExpandNames(self):
5103
    self.needed_locks = {}
5104
    self.share_locks[locking.LEVEL_INSTANCE] = 1
5105
    self.share_locks[locking.LEVEL_NODE] = 1
5106

    
5107
    if self.op.names:
5108
      self.wanted = _GetWantedInstances(self, self.op.names)
5109
    else:
5110
      self.wanted = locking.ALL_SET
5111

    
5112
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
5113
    self.do_locking = self.do_node_query and self.op.use_locking
5114
    if self.do_locking:
5115
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
5116
      self.needed_locks[locking.LEVEL_NODE] = []
5117
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5118

    
5119
  def DeclareLocks(self, level):
5120
    if level == locking.LEVEL_NODE and self.do_locking:
5121
      self._LockInstancesNodes()
5122

    
5123
  def Exec(self, feedback_fn):
5124
    """Computes the list of nodes and their attributes.
5125

5126
    """
5127
    # pylint: disable-msg=R0912
5128
    # way too many branches here
5129
    all_info = self.cfg.GetAllInstancesInfo()
5130
    if self.wanted == locking.ALL_SET:
5131
      # caller didn't specify instance names, so ordering is not important
5132
      if self.do_locking:
5133
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5134
      else:
5135
        instance_names = all_info.keys()
5136
      instance_names = utils.NiceSort(instance_names)
5137
    else:
5138
      # caller did specify names, so we must keep the ordering
5139
      if self.do_locking:
5140
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
5141
      else:
5142
        tgt_set = all_info.keys()
5143
      missing = set(self.wanted).difference(tgt_set)
5144
      if missing:
5145
        raise errors.OpExecError("Some instances were removed before"
5146
                                 " retrieving their data: %s" % missing)
5147
      instance_names = self.wanted
5148

    
5149
    instance_list = [all_info[iname] for iname in instance_names]
5150

    
5151
    # begin data gathering
5152

    
5153
    nodes = frozenset([inst.primary_node for inst in instance_list])
5154
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
5155

    
5156
    bad_nodes = []
5157
    off_nodes = []
5158
    if self.do_node_query:
5159
      live_data = {}
5160
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
5161
      for name in nodes:
5162
        result = node_data[name]
5163
        if result.offline:
5164
          # offline nodes will be in both lists
5165
          off_nodes.append(name)
5166
        if result.fail_msg:
5167
          bad_nodes.append(name)
5168
        else:
5169
          if result.payload:
5170
            live_data.update(result.payload)
5171
          # else no instance is alive
5172
    else:
5173
      live_data = dict([(name, {}) for name in instance_names])
5174

    
5175
    # end data gathering
5176

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

    
5347
    return output
5348

    
5349

    
5350
class LUFailoverInstance(LogicalUnit):
5351
  """Failover an instance.
5352

5353
  """
5354
  HPATH = "instance-failover"
5355
  HTYPE = constants.HTYPE_INSTANCE
5356
  _OP_PARAMS = [
5357
    _PInstanceName,
5358
    ("ignore_consistency", False, _TBool),
5359
    _PShutdownTimeout,
5360
    ]
5361
  REQ_BGL = False
5362

    
5363
  def ExpandNames(self):
5364
    self._ExpandAndLockInstance()
5365
    self.needed_locks[locking.LEVEL_NODE] = []
5366
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5367

    
5368
  def DeclareLocks(self, level):
5369
    if level == locking.LEVEL_NODE:
5370
      self._LockInstancesNodes()
5371

    
5372
  def BuildHooksEnv(self):
5373
    """Build hooks env.
5374

5375
    This runs on master, primary and secondary nodes of the instance.
5376

5377
    """
5378
    instance = self.instance
5379
    source_node = instance.primary_node
5380
    target_node = instance.secondary_nodes[0]
5381
    env = {
5382
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5383
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5384
      "OLD_PRIMARY": source_node,
5385
      "OLD_SECONDARY": target_node,
5386
      "NEW_PRIMARY": target_node,
5387
      "NEW_SECONDARY": source_node,
5388
      }
5389
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5390
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5391
    nl_post = list(nl)
5392
    nl_post.append(source_node)
5393
    return env, nl, nl_post
5394

    
5395
  def CheckPrereq(self):
5396
    """Check prerequisites.
5397

5398
    This checks that the instance is in the cluster.
5399

5400
    """
5401
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5402
    assert self.instance is not None, \
5403
      "Cannot retrieve locked instance %s" % self.op.instance_name
5404

    
5405
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5406
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5407
      raise errors.OpPrereqError("Instance's disk layout is not"
5408
                                 " network mirrored, cannot failover.",
5409
                                 errors.ECODE_STATE)
5410

    
5411
    secondary_nodes = instance.secondary_nodes
5412
    if not secondary_nodes:
5413
      raise errors.ProgrammerError("no secondary node but using "
5414
                                   "a mirrored disk template")
5415

    
5416
    target_node = secondary_nodes[0]
5417
    _CheckNodeOnline(self, target_node)
5418
    _CheckNodeNotDrained(self, target_node)
5419
    if instance.admin_up:
5420
      # check memory requirements on the secondary node
5421
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5422
                           instance.name, bep[constants.BE_MEMORY],
5423
                           instance.hypervisor)
5424
    else:
5425
      self.LogInfo("Not checking memory on the secondary node as"
5426
                   " instance will not be started")
5427

    
5428
    # check bridge existance
5429
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5430

    
5431
  def Exec(self, feedback_fn):
5432
    """Failover an instance.
5433

5434
    The failover is done by shutting it down on its present node and
5435
    starting it on the secondary.
5436

5437
    """
5438
    instance = self.instance
5439

    
5440
    source_node = instance.primary_node
5441
    target_node = instance.secondary_nodes[0]
5442

    
5443
    if instance.admin_up:
5444
      feedback_fn("* checking disk consistency between source and target")
5445
      for dev in instance.disks:
5446
        # for drbd, these are drbd over lvm
5447
        if not _CheckDiskConsistency(self, dev, target_node, False):
5448
          if not self.op.ignore_consistency:
5449
            raise errors.OpExecError("Disk %s is degraded on target node,"
5450
                                     " aborting failover." % dev.iv_name)
5451
    else:
5452
      feedback_fn("* not checking disk consistency as instance is not running")
5453

    
5454
    feedback_fn("* shutting down instance on source node")
5455
    logging.info("Shutting down instance %s on node %s",
5456
                 instance.name, source_node)
5457

    
5458
    result = self.rpc.call_instance_shutdown(source_node, instance,
5459
                                             self.op.shutdown_timeout)
5460
    msg = result.fail_msg
5461
    if msg:
5462
      if self.op.ignore_consistency:
5463
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5464
                             " Proceeding anyway. Please make sure node"
5465
                             " %s is down. Error details: %s",
5466
                             instance.name, source_node, source_node, msg)
5467
      else:
5468
        raise errors.OpExecError("Could not shutdown instance %s on"
5469
                                 " node %s: %s" %
5470
                                 (instance.name, source_node, msg))
5471

    
5472
    feedback_fn("* deactivating the instance's disks on source node")
5473
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5474
      raise errors.OpExecError("Can't shut down the instance's disks.")
5475

    
5476
    instance.primary_node = target_node
5477
    # distribute new instance config to the other nodes
5478
    self.cfg.Update(instance, feedback_fn)
5479

    
5480
    # Only start the instance if it's marked as up
5481
    if instance.admin_up:
5482
      feedback_fn("* activating the instance's disks on target node")
5483
      logging.info("Starting instance %s on node %s",
5484
                   instance.name, target_node)
5485

    
5486
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5487
                                           ignore_secondaries=True)
5488
      if not disks_ok:
5489
        _ShutdownInstanceDisks(self, instance)
5490
        raise errors.OpExecError("Can't activate the instance's disks")
5491

    
5492
      feedback_fn("* starting the instance on the target node")
5493
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5494
      msg = result.fail_msg
5495
      if msg:
5496
        _ShutdownInstanceDisks(self, instance)
5497
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5498
                                 (instance.name, target_node, msg))
5499

    
5500

    
5501
class LUMigrateInstance(LogicalUnit):
5502
  """Migrate an instance.
5503

5504
  This is migration without shutting down, compared to the failover,
5505
  which is done with shutdown.
5506

5507
  """
5508
  HPATH = "instance-migrate"
5509
  HTYPE = constants.HTYPE_INSTANCE
5510
  _OP_PARAMS = [
5511
    _PInstanceName,
5512
    _PMigrationMode,
5513
    _PMigrationLive,
5514
    ("cleanup", False, _TBool),
5515
    ]
5516

    
5517
  REQ_BGL = False
5518

    
5519
  def ExpandNames(self):
5520
    self._ExpandAndLockInstance()
5521

    
5522
    self.needed_locks[locking.LEVEL_NODE] = []
5523
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5524

    
5525
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5526
                                       self.op.cleanup)
5527
    self.tasklets = [self._migrater]
5528

    
5529
  def DeclareLocks(self, level):
5530
    if level == locking.LEVEL_NODE:
5531
      self._LockInstancesNodes()
5532

    
5533
  def BuildHooksEnv(self):
5534
    """Build hooks env.
5535

5536
    This runs on master, primary and secondary nodes of the instance.
5537

5538
    """
5539
    instance = self._migrater.instance
5540
    source_node = instance.primary_node
5541
    target_node = instance.secondary_nodes[0]
5542
    env = _BuildInstanceHookEnvByObject(self, instance)
5543
    env["MIGRATE_LIVE"] = self._migrater.live
5544
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5545
    env.update({
5546
        "OLD_PRIMARY": source_node,
5547
        "OLD_SECONDARY": target_node,
5548
        "NEW_PRIMARY": target_node,
5549
        "NEW_SECONDARY": source_node,
5550
        })
5551
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5552
    nl_post = list(nl)
5553
    nl_post.append(source_node)
5554
    return env, nl, nl_post
5555

    
5556

    
5557
class LUMoveInstance(LogicalUnit):
5558
  """Move an instance by data-copying.
5559

5560
  """
5561
  HPATH = "instance-move"
5562
  HTYPE = constants.HTYPE_INSTANCE
5563
  _OP_PARAMS = [
5564
    _PInstanceName,
5565
    ("target_node", _NoDefault, _TNonEmptyString),
5566
    _PShutdownTimeout,
5567
    ]
5568
  REQ_BGL = False
5569

    
5570
  def ExpandNames(self):
5571
    self._ExpandAndLockInstance()
5572
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5573
    self.op.target_node = target_node
5574
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5575
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5576

    
5577
  def DeclareLocks(self, level):
5578
    if level == locking.LEVEL_NODE:
5579
      self._LockInstancesNodes(primary_only=True)
5580

    
5581
  def BuildHooksEnv(self):
5582
    """Build hooks env.
5583

5584
    This runs on master, primary and secondary nodes of the instance.
5585

5586
    """
5587
    env = {
5588
      "TARGET_NODE": self.op.target_node,
5589
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5590
      }
5591
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5592
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5593
                                       self.op.target_node]
5594
    return env, nl, nl
5595

    
5596
  def CheckPrereq(self):
5597
    """Check prerequisites.
5598

5599
    This checks that the instance is in the cluster.
5600

5601
    """
5602
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5603
    assert self.instance is not None, \
5604
      "Cannot retrieve locked instance %s" % self.op.instance_name
5605

    
5606
    node = self.cfg.GetNodeInfo(self.op.target_node)
5607
    assert node is not None, \
5608
      "Cannot retrieve locked node %s" % self.op.target_node
5609

    
5610
    self.target_node = target_node = node.name
5611

    
5612
    if target_node == instance.primary_node:
5613
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5614
                                 (instance.name, target_node),
5615
                                 errors.ECODE_STATE)
5616

    
5617
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5618

    
5619
    for idx, dsk in enumerate(instance.disks):
5620
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5621
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5622
                                   " cannot copy" % idx, errors.ECODE_STATE)
5623

    
5624
    _CheckNodeOnline(self, target_node)
5625
    _CheckNodeNotDrained(self, target_node)
5626

    
5627
    if instance.admin_up:
5628
      # check memory requirements on the secondary node
5629
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5630
                           instance.name, bep[constants.BE_MEMORY],
5631
                           instance.hypervisor)
5632
    else:
5633
      self.LogInfo("Not checking memory on the secondary node as"
5634
                   " instance will not be started")
5635

    
5636
    # check bridge existance
5637
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5638

    
5639
  def Exec(self, feedback_fn):
5640
    """Move an instance.
5641

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

5645
    """
5646
    instance = self.instance
5647

    
5648
    source_node = instance.primary_node
5649
    target_node = self.target_node
5650

    
5651
    self.LogInfo("Shutting down instance %s on source node %s",
5652
                 instance.name, source_node)
5653

    
5654
    result = self.rpc.call_instance_shutdown(source_node, instance,
5655
                                             self.op.shutdown_timeout)
5656
    msg = result.fail_msg
5657
    if msg:
5658
      if self.op.ignore_consistency:
5659
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5660
                             " Proceeding anyway. Please make sure node"
5661
                             " %s is down. Error details: %s",
5662
                             instance.name, source_node, source_node, msg)
5663
      else:
5664
        raise errors.OpExecError("Could not shutdown instance %s on"
5665
                                 " node %s: %s" %
5666
                                 (instance.name, source_node, msg))
5667

    
5668
    # create the target disks
5669
    try:
5670
      _CreateDisks(self, instance, target_node=target_node)
5671
    except errors.OpExecError:
5672
      self.LogWarning("Device creation failed, reverting...")
5673
      try:
5674
        _RemoveDisks(self, instance, target_node=target_node)
5675
      finally:
5676
        self.cfg.ReleaseDRBDMinors(instance.name)
5677
        raise
5678

    
5679
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5680

    
5681
    errs = []
5682
    # activate, get path, copy the data over
5683
    for idx, disk in enumerate(instance.disks):
5684
      self.LogInfo("Copying data for disk %d", idx)
5685
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5686
                                               instance.name, True)
5687
      if result.fail_msg:
5688
        self.LogWarning("Can't assemble newly created disk %d: %s",
5689
                        idx, result.fail_msg)
5690
        errs.append(result.fail_msg)
5691
        break
5692
      dev_path = result.payload
5693
      result = self.rpc.call_blockdev_export(source_node, disk,
5694
                                             target_node, dev_path,
5695
                                             cluster_name)
5696
      if result.fail_msg:
5697
        self.LogWarning("Can't copy data over for disk %d: %s",
5698
                        idx, result.fail_msg)
5699
        errs.append(result.fail_msg)
5700
        break
5701

    
5702
    if errs:
5703
      self.LogWarning("Some disks failed to copy, aborting")
5704
      try:
5705
        _RemoveDisks(self, instance, target_node=target_node)
5706
      finally:
5707
        self.cfg.ReleaseDRBDMinors(instance.name)
5708
        raise errors.OpExecError("Errors during disk copy: %s" %
5709
                                 (",".join(errs),))
5710

    
5711
    instance.primary_node = target_node
5712
    self.cfg.Update(instance, feedback_fn)
5713

    
5714
    self.LogInfo("Removing the disks on the original node")
5715
    _RemoveDisks(self, instance, target_node=source_node)
5716

    
5717
    # Only start the instance if it's marked as up
5718
    if instance.admin_up:
5719
      self.LogInfo("Starting instance %s on node %s",
5720
                   instance.name, target_node)
5721

    
5722
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5723
                                           ignore_secondaries=True)
5724
      if not disks_ok:
5725
        _ShutdownInstanceDisks(self, instance)
5726
        raise errors.OpExecError("Can't activate the instance's disks")
5727

    
5728
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5729
      msg = result.fail_msg
5730
      if msg:
5731
        _ShutdownInstanceDisks(self, instance)
5732
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5733
                                 (instance.name, target_node, msg))
5734

    
5735

    
5736
class LUMigrateNode(LogicalUnit):
5737
  """Migrate all instances from a node.
5738

5739
  """
5740
  HPATH = "node-migrate"
5741
  HTYPE = constants.HTYPE_NODE
5742
  _OP_PARAMS = [
5743
    _PNodeName,
5744
    _PMigrationMode,
5745
    _PMigrationLive,
5746
    ]
5747
  REQ_BGL = False
5748

    
5749
  def ExpandNames(self):
5750
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5751

    
5752
    self.needed_locks = {
5753
      locking.LEVEL_NODE: [self.op.node_name],
5754
      }
5755

    
5756
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5757

    
5758
    # Create tasklets for migrating instances for all instances on this node
5759
    names = []
5760
    tasklets = []
5761

    
5762
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5763
      logging.debug("Migrating instance %s", inst.name)
5764
      names.append(inst.name)
5765

    
5766
      tasklets.append(TLMigrateInstance(self, inst.name, False))
5767

    
5768
    self.tasklets = tasklets
5769

    
5770
    # Declare instance locks
5771
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5772

    
5773
  def DeclareLocks(self, level):
5774
    if level == locking.LEVEL_NODE:
5775
      self._LockInstancesNodes()
5776

    
5777
  def BuildHooksEnv(self):
5778
    """Build hooks env.
5779

5780
    This runs on the master, the primary and all the secondaries.
5781

5782
    """
5783
    env = {
5784
      "NODE_NAME": self.op.node_name,
5785
      }
5786

    
5787
    nl = [self.cfg.GetMasterNode()]
5788

    
5789
    return (env, nl, nl)
5790

    
5791

    
5792
class TLMigrateInstance(Tasklet):
5793
  """Tasklet class for instance migration.
5794

5795
  @type live: boolean
5796
  @ivar live: whether the migration will be done live or non-live;
5797
      this variable is initalized only after CheckPrereq has run
5798

5799
  """
5800
  def __init__(self, lu, instance_name, cleanup):
5801
    """Initializes this class.
5802

5803
    """
5804
    Tasklet.__init__(self, lu)
5805

    
5806
    # Parameters
5807
    self.instance_name = instance_name
5808
    self.cleanup = cleanup
5809
    self.live = False # will be overridden later
5810

    
5811
  def CheckPrereq(self):
5812
    """Check prerequisites.
5813

5814
    This checks that the instance is in the cluster.
5815

5816
    """
5817
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
5818
    instance = self.cfg.GetInstanceInfo(instance_name)
5819
    assert instance is not None
5820

    
5821
    if instance.disk_template != constants.DT_DRBD8:
5822
      raise errors.OpPrereqError("Instance's disk layout is not"
5823
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5824

    
5825
    secondary_nodes = instance.secondary_nodes
5826
    if not secondary_nodes:
5827
      raise errors.ConfigurationError("No secondary node but using"
5828
                                      " drbd8 disk template")
5829

    
5830
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5831

    
5832
    target_node = secondary_nodes[0]
5833
    # check memory requirements on the secondary node
5834
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
5835
                         instance.name, i_be[constants.BE_MEMORY],
5836
                         instance.hypervisor)
5837

    
5838
    # check bridge existance
5839
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
5840

    
5841
    if not self.cleanup:
5842
      _CheckNodeNotDrained(self.lu, target_node)
5843
      result = self.rpc.call_instance_migratable(instance.primary_node,
5844
                                                 instance)
5845
      result.Raise("Can't migrate, please use failover",
5846
                   prereq=True, ecode=errors.ECODE_STATE)
5847

    
5848
    self.instance = instance
5849

    
5850
    if self.lu.op.live is not None and self.lu.op.mode is not None:
5851
      raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
5852
                                 " parameters are accepted",
5853
                                 errors.ECODE_INVAL)
5854
    if self.lu.op.live is not None:
5855
      if self.lu.op.live:
5856
        self.lu.op.mode = constants.HT_MIGRATION_LIVE
5857
      else:
5858
        self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
5859
      # reset the 'live' parameter to None so that repeated
5860
      # invocations of CheckPrereq do not raise an exception
5861
      self.lu.op.live = None
5862
    elif self.lu.op.mode is None:
5863
      # read the default value from the hypervisor
5864
      i_hv = self.cfg.GetClusterInfo().FillHV(instance, skip_globals=False)
5865
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
5866

    
5867
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
5868

    
5869
  def _WaitUntilSync(self):
5870
    """Poll with custom rpc for disk sync.
5871

5872
    This uses our own step-based rpc call.
5873

5874
    """
5875
    self.feedback_fn("* wait until resync is done")
5876
    all_done = False
5877
    while not all_done:
5878
      all_done = True
5879
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
5880
                                            self.nodes_ip,
5881
                                            self.instance.disks)
5882
      min_percent = 100
5883
      for node, nres in result.items():
5884
        nres.Raise("Cannot resync disks on node %s" % node)
5885
        node_done, node_percent = nres.payload
5886
        all_done = all_done and node_done
5887
        if node_percent is not None:
5888
          min_percent = min(min_percent, node_percent)
5889
      if not all_done:
5890
        if min_percent < 100:
5891
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
5892
        time.sleep(2)
5893

    
5894
  def _EnsureSecondary(self, node):
5895
    """Demote a node to secondary.
5896

5897
    """
5898
    self.feedback_fn("* switching node %s to secondary mode" % node)
5899

    
5900
    for dev in self.instance.disks:
5901
      self.cfg.SetDiskID(dev, node)
5902

    
5903
    result = self.rpc.call_blockdev_close(node, self.instance.name,
5904
                                          self.instance.disks)
5905
    result.Raise("Cannot change disk to secondary on node %s" % node)
5906

    
5907
  def _GoStandalone(self):
5908
    """Disconnect from the network.
5909

5910
    """
5911
    self.feedback_fn("* changing into standalone mode")
5912
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
5913
                                               self.instance.disks)
5914
    for node, nres in result.items():
5915
      nres.Raise("Cannot disconnect disks node %s" % node)
5916

    
5917
  def _GoReconnect(self, multimaster):
5918
    """Reconnect to the network.
5919

5920
    """
5921
    if multimaster:
5922
      msg = "dual-master"
5923
    else:
5924
      msg = "single-master"
5925
    self.feedback_fn("* changing disks into %s mode" % msg)
5926
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
5927
                                           self.instance.disks,
5928
                                           self.instance.name, multimaster)
5929
    for node, nres in result.items():
5930
      nres.Raise("Cannot change disks config on node %s" % node)
5931

    
5932
  def _ExecCleanup(self):
5933
    """Try to cleanup after a failed migration.
5934

5935
    The cleanup is done by:
5936
      - check that the instance is running only on one node
5937
        (and update the config if needed)
5938
      - change disks on its secondary node to secondary
5939
      - wait until disks are fully synchronized
5940
      - disconnect from the network
5941
      - change disks into single-master mode
5942
      - wait again until disks are fully synchronized
5943

5944
    """
5945
    instance = self.instance
5946
    target_node = self.target_node
5947
    source_node = self.source_node
5948

    
5949
    # check running on only one node
5950
    self.feedback_fn("* checking where the instance actually runs"
5951
                     " (if this hangs, the hypervisor might be in"
5952
                     " a bad state)")
5953
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
5954
    for node, result in ins_l.items():
5955
      result.Raise("Can't contact node %s" % node)
5956

    
5957
    runningon_source = instance.name in ins_l[source_node].payload
5958
    runningon_target = instance.name in ins_l[target_node].payload
5959

    
5960
    if runningon_source and runningon_target:
5961
      raise errors.OpExecError("Instance seems to be running on two nodes,"
5962
                               " or the hypervisor is confused. You will have"
5963
                               " to ensure manually that it runs only on one"
5964
                               " and restart this operation.")
5965

    
5966
    if not (runningon_source or runningon_target):
5967
      raise errors.OpExecError("Instance does not seem to be running at all."
5968
                               " In this case, it's safer to repair by"
5969
                               " running 'gnt-instance stop' to ensure disk"
5970
                               " shutdown, and then restarting it.")
5971

    
5972
    if runningon_target:
5973
      # the migration has actually succeeded, we need to update the config
5974
      self.feedback_fn("* instance running on secondary node (%s),"
5975
                       " updating config" % target_node)
5976
      instance.primary_node = target_node
5977
      self.cfg.Update(instance, self.feedback_fn)
5978
      demoted_node = source_node
5979
    else:
5980
      self.feedback_fn("* instance confirmed to be running on its"
5981
                       " primary node (%s)" % source_node)
5982
      demoted_node = target_node
5983

    
5984
    self._EnsureSecondary(demoted_node)
5985
    try:
5986
      self._WaitUntilSync()
5987
    except errors.OpExecError:
5988
      # we ignore here errors, since if the device is standalone, it
5989
      # won't be able to sync
5990
      pass
5991
    self._GoStandalone()
5992
    self._GoReconnect(False)
5993
    self._WaitUntilSync()
5994

    
5995
    self.feedback_fn("* done")
5996

    
5997
  def _RevertDiskStatus(self):
5998
    """Try to revert the disk status after a failed migration.
5999

6000
    """
6001
    target_node = self.target_node
6002
    try:
6003
      self._EnsureSecondary(target_node)
6004
      self._GoStandalone()
6005
      self._GoReconnect(False)
6006
      self._WaitUntilSync()
6007
    except errors.OpExecError, err:
6008
      self.lu.LogWarning("Migration failed and I can't reconnect the"
6009
                         " drives: error '%s'\n"
6010
                         "Please look and recover the instance status" %
6011
                         str(err))
6012

    
6013
  def _AbortMigration(self):
6014
    """Call the hypervisor code to abort a started migration.
6015

6016
    """
6017
    instance = self.instance
6018
    target_node = self.target_node
6019
    migration_info = self.migration_info
6020

    
6021
    abort_result = self.rpc.call_finalize_migration(target_node,
6022
                                                    instance,
6023
                                                    migration_info,
6024
                                                    False)
6025
    abort_msg = abort_result.fail_msg
6026
    if abort_msg:
6027
      logging.error("Aborting migration failed on target node %s: %s",
6028
                    target_node, abort_msg)
6029
      # Don't raise an exception here, as we stil have to try to revert the
6030
      # disk status, even if this step failed.
6031

    
6032
  def _ExecMigration(self):
6033
    """Migrate an instance.
6034

6035
    The migrate is done by:
6036
      - change the disks into dual-master mode
6037
      - wait until disks are fully synchronized again
6038
      - migrate the instance
6039
      - change disks on the new secondary node (the old primary) to secondary
6040
      - wait until disks are fully synchronized
6041
      - change disks into single-master mode
6042

6043
    """
6044
    instance = self.instance
6045
    target_node = self.target_node
6046
    source_node = self.source_node
6047

    
6048
    self.feedback_fn("* checking disk consistency between source and target")
6049
    for dev in instance.disks:
6050
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6051
        raise errors.OpExecError("Disk %s is degraded or not fully"
6052
                                 " synchronized on target node,"
6053
                                 " aborting migrate." % dev.iv_name)
6054

    
6055
    # First get the migration information from the remote node
6056
    result = self.rpc.call_migration_info(source_node, instance)
6057
    msg = result.fail_msg
6058
    if msg:
6059
      log_err = ("Failed fetching source migration information from %s: %s" %
6060
                 (source_node, msg))
6061
      logging.error(log_err)
6062
      raise errors.OpExecError(log_err)
6063

    
6064
    self.migration_info = migration_info = result.payload
6065

    
6066
    # Then switch the disks to master/master mode
6067
    self._EnsureSecondary(target_node)
6068
    self._GoStandalone()
6069
    self._GoReconnect(True)
6070
    self._WaitUntilSync()
6071

    
6072
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6073
    result = self.rpc.call_accept_instance(target_node,
6074
                                           instance,
6075
                                           migration_info,
6076
                                           self.nodes_ip[target_node])
6077

    
6078
    msg = result.fail_msg
6079
    if msg:
6080
      logging.error("Instance pre-migration failed, trying to revert"
6081
                    " disk status: %s", msg)
6082
      self.feedback_fn("Pre-migration failed, aborting")
6083
      self._AbortMigration()
6084
      self._RevertDiskStatus()
6085
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6086
                               (instance.name, msg))
6087

    
6088
    self.feedback_fn("* migrating instance to %s" % target_node)
6089
    time.sleep(10)
6090
    result = self.rpc.call_instance_migrate(source_node, instance,
6091
                                            self.nodes_ip[target_node],
6092
                                            self.live)
6093
    msg = result.fail_msg
6094
    if msg:
6095
      logging.error("Instance migration failed, trying to revert"
6096
                    " disk status: %s", msg)
6097
      self.feedback_fn("Migration failed, aborting")
6098
      self._AbortMigration()
6099
      self._RevertDiskStatus()
6100
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6101
                               (instance.name, msg))
6102
    time.sleep(10)
6103

    
6104
    instance.primary_node = target_node
6105
    # distribute new instance config to the other nodes
6106
    self.cfg.Update(instance, self.feedback_fn)
6107

    
6108
    result = self.rpc.call_finalize_migration(target_node,
6109
                                              instance,
6110
                                              migration_info,
6111
                                              True)
6112
    msg = result.fail_msg
6113
    if msg:
6114
      logging.error("Instance migration succeeded, but finalization failed:"
6115
                    " %s", msg)
6116
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6117
                               msg)
6118

    
6119
    self._EnsureSecondary(source_node)
6120
    self._WaitUntilSync()
6121
    self._GoStandalone()
6122
    self._GoReconnect(False)
6123
    self._WaitUntilSync()
6124

    
6125
    self.feedback_fn("* done")
6126

    
6127
  def Exec(self, feedback_fn):
6128
    """Perform the migration.
6129

6130
    """
6131
    feedback_fn("Migrating instance %s" % self.instance.name)
6132

    
6133
    self.feedback_fn = feedback_fn
6134

    
6135
    self.source_node = self.instance.primary_node
6136
    self.target_node = self.instance.secondary_nodes[0]
6137
    self.all_nodes = [self.source_node, self.target_node]
6138
    self.nodes_ip = {
6139
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6140
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6141
      }
6142

    
6143
    if self.cleanup:
6144
      return self._ExecCleanup()
6145
    else:
6146
      return self._ExecMigration()
6147

    
6148

    
6149
def _CreateBlockDev(lu, node, instance, device, force_create,
6150
                    info, force_open):
6151
  """Create a tree of block devices on a given node.
6152

6153
  If this device type has to be created on secondaries, create it and
6154
  all its children.
6155

6156
  If not, just recurse to children keeping the same 'force' value.
6157

6158
  @param lu: the lu on whose behalf we execute
6159
  @param node: the node on which to create the device
6160
  @type instance: L{objects.Instance}
6161
  @param instance: the instance which owns the device
6162
  @type device: L{objects.Disk}
6163
  @param device: the device to create
6164
  @type force_create: boolean
6165
  @param force_create: whether to force creation of this device; this
6166
      will be change to True whenever we find a device which has
6167
      CreateOnSecondary() attribute
6168
  @param info: the extra 'metadata' we should attach to the device
6169
      (this will be represented as a LVM tag)
6170
  @type force_open: boolean
6171
  @param force_open: this parameter will be passes to the
6172
      L{backend.BlockdevCreate} function where it specifies
6173
      whether we run on primary or not, and it affects both
6174
      the child assembly and the device own Open() execution
6175

6176
  """
6177
  if device.CreateOnSecondary():
6178
    force_create = True
6179

    
6180
  if device.children:
6181
    for child in device.children:
6182
      _CreateBlockDev(lu, node, instance, child, force_create,
6183
                      info, force_open)
6184

    
6185
  if not force_create:
6186
    return
6187

    
6188
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6189

    
6190

    
6191
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6192
  """Create a single block device on a given node.
6193

6194
  This will not recurse over children of the device, so they must be
6195
  created in advance.
6196

6197
  @param lu: the lu on whose behalf we execute
6198
  @param node: the node on which to create the device
6199
  @type instance: L{objects.Instance}
6200
  @param instance: the instance which owns the device
6201
  @type device: L{objects.Disk}
6202
  @param device: the device to create
6203
  @param info: the extra 'metadata' we should attach to the device
6204
      (this will be represented as a LVM tag)
6205
  @type force_open: boolean
6206
  @param force_open: this parameter will be passes to the
6207
      L{backend.BlockdevCreate} function where it specifies
6208
      whether we run on primary or not, and it affects both
6209
      the child assembly and the device own Open() execution
6210

6211
  """
6212
  lu.cfg.SetDiskID(device, node)
6213
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6214
                                       instance.name, force_open, info)
6215
  result.Raise("Can't create block device %s on"
6216
               " node %s for instance %s" % (device, node, instance.name))
6217
  if device.physical_id is None:
6218
    device.physical_id = result.payload
6219

    
6220

    
6221
def _GenerateUniqueNames(lu, exts):
6222
  """Generate a suitable LV name.
6223

6224
  This will generate a logical volume name for the given instance.
6225

6226
  """
6227
  results = []
6228
  for val in exts:
6229
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6230
    results.append("%s%s" % (new_id, val))
6231
  return results
6232

    
6233

    
6234
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
6235
                         p_minor, s_minor):
6236
  """Generate a drbd8 device complete with its children.
6237

6238
  """
6239
  port = lu.cfg.AllocatePort()
6240
  vgname = lu.cfg.GetVGName()
6241
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6242
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6243
                          logical_id=(vgname, names[0]))
6244
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6245
                          logical_id=(vgname, names[1]))
6246
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6247
                          logical_id=(primary, secondary, port,
6248
                                      p_minor, s_minor,
6249
                                      shared_secret),
6250
                          children=[dev_data, dev_meta],
6251
                          iv_name=iv_name)
6252
  return drbd_dev
6253

    
6254

    
6255
def _GenerateDiskTemplate(lu, template_name,
6256
                          instance_name, primary_node,
6257
                          secondary_nodes, disk_info,
6258
                          file_storage_dir, file_driver,
6259
                          base_index):
6260
  """Generate the entire disk layout for a given template type.
6261

6262
  """
6263
  #TODO: compute space requirements
6264

    
6265
  vgname = lu.cfg.GetVGName()
6266
  disk_count = len(disk_info)
6267
  disks = []
6268
  if template_name == constants.DT_DISKLESS:
6269
    pass
6270
  elif template_name == constants.DT_PLAIN:
6271
    if len(secondary_nodes) != 0:
6272
      raise errors.ProgrammerError("Wrong template configuration")
6273

    
6274
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6275
                                      for i in range(disk_count)])
6276
    for idx, disk in enumerate(disk_info):
6277
      disk_index = idx + base_index
6278
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6279
                              logical_id=(vgname, names[idx]),
6280
                              iv_name="disk/%d" % disk_index,
6281
                              mode=disk["mode"])
6282
      disks.append(disk_dev)
6283
  elif template_name == constants.DT_DRBD8:
6284
    if len(secondary_nodes) != 1:
6285
      raise errors.ProgrammerError("Wrong template configuration")
6286
    remote_node = secondary_nodes[0]
6287
    minors = lu.cfg.AllocateDRBDMinor(
6288
      [primary_node, remote_node] * len(disk_info), instance_name)
6289

    
6290
    names = []
6291
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6292
                                               for i in range(disk_count)]):
6293
      names.append(lv_prefix + "_data")
6294
      names.append(lv_prefix + "_meta")
6295
    for idx, disk in enumerate(disk_info):
6296
      disk_index = idx + base_index
6297
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6298
                                      disk["size"], names[idx*2:idx*2+2],
6299
                                      "disk/%d" % disk_index,
6300
                                      minors[idx*2], minors[idx*2+1])
6301
      disk_dev.mode = disk["mode"]
6302
      disks.append(disk_dev)
6303
  elif template_name == constants.DT_FILE:
6304
    if len(secondary_nodes) != 0:
6305
      raise errors.ProgrammerError("Wrong template configuration")
6306

    
6307
    _RequireFileStorage()
6308

    
6309
    for idx, disk in enumerate(disk_info):
6310
      disk_index = idx + base_index
6311
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6312
                              iv_name="disk/%d" % disk_index,
6313
                              logical_id=(file_driver,
6314
                                          "%s/disk%d" % (file_storage_dir,
6315
                                                         disk_index)),
6316
                              mode=disk["mode"])
6317
      disks.append(disk_dev)
6318
  else:
6319
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6320
  return disks
6321

    
6322

    
6323
def _GetInstanceInfoText(instance):
6324
  """Compute that text that should be added to the disk's metadata.
6325

6326
  """
6327
  return "originstname+%s" % instance.name
6328

    
6329

    
6330
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6331
  """Create all disks for an instance.
6332

6333
  This abstracts away some work from AddInstance.
6334

6335
  @type lu: L{LogicalUnit}
6336
  @param lu: the logical unit on whose behalf we execute
6337
  @type instance: L{objects.Instance}
6338
  @param instance: the instance whose disks we should create
6339
  @type to_skip: list
6340
  @param to_skip: list of indices to skip
6341
  @type target_node: string
6342
  @param target_node: if passed, overrides the target node for creation
6343
  @rtype: boolean
6344
  @return: the success of the creation
6345

6346
  """
6347
  info = _GetInstanceInfoText(instance)
6348
  if target_node is None:
6349
    pnode = instance.primary_node
6350
    all_nodes = instance.all_nodes
6351
  else:
6352
    pnode = target_node
6353
    all_nodes = [pnode]
6354

    
6355
  if instance.disk_template == constants.DT_FILE:
6356
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6357
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6358

    
6359
    result.Raise("Failed to create directory '%s' on"
6360
                 " node %s" % (file_storage_dir, pnode))
6361

    
6362
  # Note: this needs to be kept in sync with adding of disks in
6363
  # LUSetInstanceParams
6364
  for idx, device in enumerate(instance.disks):
6365
    if to_skip and idx in to_skip:
6366
      continue
6367
    logging.info("Creating volume %s for instance %s",
6368
                 device.iv_name, instance.name)
6369
    #HARDCODE
6370
    for node in all_nodes:
6371
      f_create = node == pnode
6372
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6373

    
6374

    
6375
def _RemoveDisks(lu, instance, target_node=None):
6376
  """Remove all disks for an instance.
6377

6378
  This abstracts away some work from `AddInstance()` and
6379
  `RemoveInstance()`. Note that in case some of the devices couldn't
6380
  be removed, the removal will continue with the other ones (compare
6381
  with `_CreateDisks()`).
6382

6383
  @type lu: L{LogicalUnit}
6384
  @param lu: the logical unit on whose behalf we execute
6385
  @type instance: L{objects.Instance}
6386
  @param instance: the instance whose disks we should remove
6387
  @type target_node: string
6388
  @param target_node: used to override the node on which to remove the disks
6389
  @rtype: boolean
6390
  @return: the success of the removal
6391

6392
  """
6393
  logging.info("Removing block devices for instance %s", instance.name)
6394

    
6395
  all_result = True
6396
  for device in instance.disks:
6397
    if target_node:
6398
      edata = [(target_node, device)]
6399
    else:
6400
      edata = device.ComputeNodeTree(instance.primary_node)
6401
    for node, disk in edata:
6402
      lu.cfg.SetDiskID(disk, node)
6403
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6404
      if msg:
6405
        lu.LogWarning("Could not remove block device %s on node %s,"
6406
                      " continuing anyway: %s", device.iv_name, node, msg)
6407
        all_result = False
6408

    
6409
  if instance.disk_template == constants.DT_FILE:
6410
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6411
    if target_node:
6412
      tgt = target_node
6413
    else:
6414
      tgt = instance.primary_node
6415
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6416
    if result.fail_msg:
6417
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6418
                    file_storage_dir, instance.primary_node, result.fail_msg)
6419
      all_result = False
6420

    
6421
  return all_result
6422

    
6423

    
6424
def _ComputeDiskSize(disk_template, disks):
6425
  """Compute disk size requirements in the volume group
6426

6427
  """
6428
  # Required free disk space as a function of disk and swap space
6429
  req_size_dict = {
6430
    constants.DT_DISKLESS: None,
6431
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6432
    # 128 MB are added for drbd metadata for each disk
6433
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6434
    constants.DT_FILE: None,
6435
  }
6436

    
6437
  if disk_template not in req_size_dict:
6438
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6439
                                 " is unknown" %  disk_template)
6440

    
6441
  return req_size_dict[disk_template]
6442

    
6443

    
6444
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6445
  """Hypervisor parameter validation.
6446

6447
  This function abstract the hypervisor parameter validation to be
6448
  used in both instance create and instance modify.
6449

6450
  @type lu: L{LogicalUnit}
6451
  @param lu: the logical unit for which we check
6452
  @type nodenames: list
6453
  @param nodenames: the list of nodes on which we should check
6454
  @type hvname: string
6455
  @param hvname: the name of the hypervisor we should use
6456
  @type hvparams: dict
6457
  @param hvparams: the parameters which we need to check
6458
  @raise errors.OpPrereqError: if the parameters are not valid
6459

6460
  """
6461
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6462
                                                  hvname,
6463
                                                  hvparams)
6464
  for node in nodenames:
6465
    info = hvinfo[node]
6466
    if info.offline:
6467
      continue
6468
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6469

    
6470

    
6471
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6472
  """OS parameters validation.
6473

6474
  @type lu: L{LogicalUnit}
6475
  @param lu: the logical unit for which we check
6476
  @type required: boolean
6477
  @param required: whether the validation should fail if the OS is not
6478
      found
6479
  @type nodenames: list
6480
  @param nodenames: the list of nodes on which we should check
6481
  @type osname: string
6482
  @param osname: the name of the hypervisor we should use
6483
  @type osparams: dict
6484
  @param osparams: the parameters which we need to check
6485
  @raise errors.OpPrereqError: if the parameters are not valid
6486

6487
  """
6488
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6489
                                   [constants.OS_VALIDATE_PARAMETERS],
6490
                                   osparams)
6491
  for node, nres in result.items():
6492
    # we don't check for offline cases since this should be run only
6493
    # against the master node and/or an instance's nodes
6494
    nres.Raise("OS Parameters validation failed on node %s" % node)
6495
    if not nres.payload:
6496
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6497
                 osname, node)
6498

    
6499

    
6500
class LUCreateInstance(LogicalUnit):
6501
  """Create an instance.
6502

6503
  """
6504
  HPATH = "instance-add"
6505
  HTYPE = constants.HTYPE_INSTANCE
6506
  _OP_PARAMS = [
6507
    _PInstanceName,
6508
    ("mode", _NoDefault, _TElemOf(constants.INSTANCE_CREATE_MODES)),
6509
    ("start", True, _TBool),
6510
    ("wait_for_sync", True, _TBool),
6511
    ("ip_check", True, _TBool),
6512
    ("name_check", True, _TBool),
6513
    ("disks", _NoDefault, _TListOf(_TDict)),
6514
    ("nics", _NoDefault, _TListOf(_TDict)),
6515
    ("hvparams", _EmptyDict, _TDict),
6516
    ("beparams", _EmptyDict, _TDict),
6517
    ("osparams", _EmptyDict, _TDict),
6518
    ("no_install", None, _TMaybeBool),
6519
    ("os_type", None, _TMaybeString),
6520
    ("force_variant", False, _TBool),
6521
    ("source_handshake", None, _TOr(_TList, _TNone)),
6522
    ("source_x509_ca", None, _TMaybeString),
6523
    ("source_instance_name", None, _TMaybeString),
6524
    ("src_node", None, _TMaybeString),
6525
    ("src_path", None, _TMaybeString),
6526
    ("pnode", None, _TMaybeString),
6527
    ("snode", None, _TMaybeString),
6528
    ("iallocator", None, _TMaybeString),
6529
    ("hypervisor", None, _TMaybeString),
6530
    ("disk_template", _NoDefault, _CheckDiskTemplate),
6531
    ("identify_defaults", False, _TBool),
6532
    ("file_driver", None, _TOr(_TNone, _TElemOf(constants.FILE_DRIVER))),
6533
    ("file_storage_dir", None, _TMaybeString),
6534
    ("dry_run", False, _TBool),
6535
    ]
6536
  REQ_BGL = False
6537

    
6538
  def CheckArguments(self):
6539
    """Check arguments.
6540

6541
    """
6542
    # do not require name_check to ease forward/backward compatibility
6543
    # for tools
6544
    if self.op.no_install and self.op.start:
6545
      self.LogInfo("No-installation mode selected, disabling startup")
6546
      self.op.start = False
6547
    # validate/normalize the instance name
6548
    self.op.instance_name = \
6549
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
6550

    
6551
    if self.op.ip_check and not self.op.name_check:
6552
      # TODO: make the ip check more flexible and not depend on the name check
6553
      raise errors.OpPrereqError("Cannot do ip check without a name check",
6554
                                 errors.ECODE_INVAL)
6555

    
6556
    # check nics' parameter names
6557
    for nic in self.op.nics:
6558
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6559

    
6560
    # check disks. parameter names and consistent adopt/no-adopt strategy
6561
    has_adopt = has_no_adopt = False
6562
    for disk in self.op.disks:
6563
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6564
      if "adopt" in disk:
6565
        has_adopt = True
6566
      else:
6567
        has_no_adopt = True
6568
    if has_adopt and has_no_adopt:
6569
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6570
                                 errors.ECODE_INVAL)
6571
    if has_adopt:
6572
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6573
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6574
                                   " '%s' disk template" %
6575
                                   self.op.disk_template,
6576
                                   errors.ECODE_INVAL)
6577
      if self.op.iallocator is not None:
6578
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6579
                                   " iallocator script", errors.ECODE_INVAL)
6580
      if self.op.mode == constants.INSTANCE_IMPORT:
6581
        raise errors.OpPrereqError("Disk adoption not allowed for"
6582
                                   " instance import", errors.ECODE_INVAL)
6583

    
6584
    self.adopt_disks = has_adopt
6585

    
6586
    # instance name verification
6587
    if self.op.name_check:
6588
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
6589
      self.op.instance_name = self.hostname1.name
6590
      # used in CheckPrereq for ip ping check
6591
      self.check_ip = self.hostname1.ip
6592
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6593
      raise errors.OpPrereqError("Remote imports require names to be checked" %
6594
                                 errors.ECODE_INVAL)
6595
    else:
6596
      self.check_ip = None
6597

    
6598
    # file storage checks
6599
    if (self.op.file_driver and
6600
        not self.op.file_driver in constants.FILE_DRIVER):
6601
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6602
                                 self.op.file_driver, errors.ECODE_INVAL)
6603

    
6604
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6605
      raise errors.OpPrereqError("File storage directory path not absolute",
6606
                                 errors.ECODE_INVAL)
6607

    
6608
    ### Node/iallocator related checks
6609
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
6610

    
6611
    if self.op.pnode is not None:
6612
      if self.op.disk_template in constants.DTS_NET_MIRROR:
6613
        if self.op.snode is None:
6614
          raise errors.OpPrereqError("The networked disk templates need"
6615
                                     " a mirror node", errors.ECODE_INVAL)
6616
      elif self.op.snode:
6617
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
6618
                        " template")
6619
        self.op.snode = None
6620

    
6621
    self._cds = _GetClusterDomainSecret()
6622

    
6623
    if self.op.mode == constants.INSTANCE_IMPORT:
6624
      # On import force_variant must be True, because if we forced it at
6625
      # initial install, our only chance when importing it back is that it
6626
      # works again!
6627
      self.op.force_variant = True
6628

    
6629
      if self.op.no_install:
6630
        self.LogInfo("No-installation mode has no effect during import")
6631

    
6632
    elif self.op.mode == constants.INSTANCE_CREATE:
6633
      if self.op.os_type is None:
6634
        raise errors.OpPrereqError("No guest OS specified",
6635
                                   errors.ECODE_INVAL)
6636
      if self.op.disk_template is None:
6637
        raise errors.OpPrereqError("No disk template specified",
6638
                                   errors.ECODE_INVAL)
6639

    
6640
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6641
      # Check handshake to ensure both clusters have the same domain secret
6642
      src_handshake = self.op.source_handshake
6643
      if not src_handshake:
6644
        raise errors.OpPrereqError("Missing source handshake",
6645
                                   errors.ECODE_INVAL)
6646

    
6647
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6648
                                                           src_handshake)
6649
      if errmsg:
6650
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6651
                                   errors.ECODE_INVAL)
6652

    
6653
      # Load and check source CA
6654
      self.source_x509_ca_pem = self.op.source_x509_ca
6655
      if not self.source_x509_ca_pem:
6656
        raise errors.OpPrereqError("Missing source X509 CA",
6657
                                   errors.ECODE_INVAL)
6658

    
6659
      try:
6660
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
6661
                                                    self._cds)
6662
      except OpenSSL.crypto.Error, err:
6663
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
6664
                                   (err, ), errors.ECODE_INVAL)
6665

    
6666
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
6667
      if errcode is not None:
6668
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
6669
                                   errors.ECODE_INVAL)
6670

    
6671
      self.source_x509_ca = cert
6672

    
6673
      src_instance_name = self.op.source_instance_name
6674
      if not src_instance_name:
6675
        raise errors.OpPrereqError("Missing source instance name",
6676
                                   errors.ECODE_INVAL)
6677

    
6678
      self.source_instance_name = \
6679
          netutils.GetHostname(name=src_instance_name).name
6680

    
6681
    else:
6682
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
6683
                                 self.op.mode, errors.ECODE_INVAL)
6684

    
6685
  def ExpandNames(self):
6686
    """ExpandNames for CreateInstance.
6687

6688
    Figure out the right locks for instance creation.
6689

6690
    """
6691
    self.needed_locks = {}
6692

    
6693
    instance_name = self.op.instance_name
6694
    # this is just a preventive check, but someone might still add this
6695
    # instance in the meantime, and creation will fail at lock-add time
6696
    if instance_name in self.cfg.GetInstanceList():
6697
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6698
                                 instance_name, errors.ECODE_EXISTS)
6699

    
6700
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
6701

    
6702
    if self.op.iallocator:
6703
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6704
    else:
6705
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
6706
      nodelist = [self.op.pnode]
6707
      if self.op.snode is not None:
6708
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
6709
        nodelist.append(self.op.snode)
6710
      self.needed_locks[locking.LEVEL_NODE] = nodelist
6711

    
6712
    # in case of import lock the source node too
6713
    if self.op.mode == constants.INSTANCE_IMPORT:
6714
      src_node = self.op.src_node
6715
      src_path = self.op.src_path
6716

    
6717
      if src_path is None:
6718
        self.op.src_path = src_path = self.op.instance_name
6719

    
6720
      if src_node is None:
6721
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6722
        self.op.src_node = None
6723
        if os.path.isabs(src_path):
6724
          raise errors.OpPrereqError("Importing an instance from an absolute"
6725
                                     " path requires a source node option.",
6726
                                     errors.ECODE_INVAL)
6727
      else:
6728
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
6729
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
6730
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
6731
        if not os.path.isabs(src_path):
6732
          self.op.src_path = src_path = \
6733
            utils.PathJoin(constants.EXPORT_DIR, src_path)
6734

    
6735
  def _RunAllocator(self):
6736
    """Run the allocator based on input opcode.
6737

6738
    """
6739
    nics = [n.ToDict() for n in self.nics]
6740
    ial = IAllocator(self.cfg, self.rpc,
6741
                     mode=constants.IALLOCATOR_MODE_ALLOC,
6742
                     name=self.op.instance_name,
6743
                     disk_template=self.op.disk_template,
6744
                     tags=[],
6745
                     os=self.op.os_type,
6746
                     vcpus=self.be_full[constants.BE_VCPUS],
6747
                     mem_size=self.be_full[constants.BE_MEMORY],
6748
                     disks=self.disks,
6749
                     nics=nics,
6750
                     hypervisor=self.op.hypervisor,
6751
                     )
6752

    
6753
    ial.Run(self.op.iallocator)
6754

    
6755
    if not ial.success:
6756
      raise errors.OpPrereqError("Can't compute nodes using"
6757
                                 " iallocator '%s': %s" %
6758
                                 (self.op.iallocator, ial.info),
6759
                                 errors.ECODE_NORES)
6760
    if len(ial.result) != ial.required_nodes:
6761
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6762
                                 " of nodes (%s), required %s" %
6763
                                 (self.op.iallocator, len(ial.result),
6764
                                  ial.required_nodes), errors.ECODE_FAULT)
6765
    self.op.pnode = ial.result[0]
6766
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6767
                 self.op.instance_name, self.op.iallocator,
6768
                 utils.CommaJoin(ial.result))
6769
    if ial.required_nodes == 2:
6770
      self.op.snode = ial.result[1]
6771

    
6772
  def BuildHooksEnv(self):
6773
    """Build hooks env.
6774

6775
    This runs on master, primary and secondary nodes of the instance.
6776

6777
    """
6778
    env = {
6779
      "ADD_MODE": self.op.mode,
6780
      }
6781
    if self.op.mode == constants.INSTANCE_IMPORT:
6782
      env["SRC_NODE"] = self.op.src_node
6783
      env["SRC_PATH"] = self.op.src_path
6784
      env["SRC_IMAGES"] = self.src_images
6785

    
6786
    env.update(_BuildInstanceHookEnv(
6787
      name=self.op.instance_name,
6788
      primary_node=self.op.pnode,
6789
      secondary_nodes=self.secondaries,
6790
      status=self.op.start,
6791
      os_type=self.op.os_type,
6792
      memory=self.be_full[constants.BE_MEMORY],
6793
      vcpus=self.be_full[constants.BE_VCPUS],
6794
      nics=_NICListToTuple(self, self.nics),
6795
      disk_template=self.op.disk_template,
6796
      disks=[(d["size"], d["mode"]) for d in self.disks],
6797
      bep=self.be_full,
6798
      hvp=self.hv_full,
6799
      hypervisor_name=self.op.hypervisor,
6800
    ))
6801

    
6802
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
6803
          self.secondaries)
6804
    return env, nl, nl
6805

    
6806
  def _ReadExportInfo(self):
6807
    """Reads the export information from disk.
6808

6809
    It will override the opcode source node and path with the actual
6810
    information, if these two were not specified before.
6811

6812
    @return: the export information
6813

6814
    """
6815
    assert self.op.mode == constants.INSTANCE_IMPORT
6816

    
6817
    src_node = self.op.src_node
6818
    src_path = self.op.src_path
6819

    
6820
    if src_node is None:
6821
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
6822
      exp_list = self.rpc.call_export_list(locked_nodes)
6823
      found = False
6824
      for node in exp_list:
6825
        if exp_list[node].fail_msg:
6826
          continue
6827
        if src_path in exp_list[node].payload:
6828
          found = True
6829
          self.op.src_node = src_node = node
6830
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
6831
                                                       src_path)
6832
          break
6833
      if not found:
6834
        raise errors.OpPrereqError("No export found for relative path %s" %
6835
                                    src_path, errors.ECODE_INVAL)
6836

    
6837
    _CheckNodeOnline(self, src_node)
6838
    result = self.rpc.call_export_info(src_node, src_path)
6839
    result.Raise("No export or invalid export found in dir %s" % src_path)
6840

    
6841
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
6842
    if not export_info.has_section(constants.INISECT_EXP):
6843
      raise errors.ProgrammerError("Corrupted export config",
6844
                                   errors.ECODE_ENVIRON)
6845

    
6846
    ei_version = export_info.get(constants.INISECT_EXP, "version")
6847
    if (int(ei_version) != constants.EXPORT_VERSION):
6848
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
6849
                                 (ei_version, constants.EXPORT_VERSION),
6850
                                 errors.ECODE_ENVIRON)
6851
    return export_info
6852

    
6853
  def _ReadExportParams(self, einfo):
6854
    """Use export parameters as defaults.
6855

6856
    In case the opcode doesn't specify (as in override) some instance
6857
    parameters, then try to use them from the export information, if
6858
    that declares them.
6859

6860
    """
6861
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
6862

    
6863
    if self.op.disk_template is None:
6864
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
6865
        self.op.disk_template = einfo.get(constants.INISECT_INS,
6866
                                          "disk_template")
6867
      else:
6868
        raise errors.OpPrereqError("No disk template specified and the export"
6869
                                   " is missing the disk_template information",
6870
                                   errors.ECODE_INVAL)
6871

    
6872
    if not self.op.disks:
6873
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
6874
        disks = []
6875
        # TODO: import the disk iv_name too
6876
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
6877
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
6878
          disks.append({"size": disk_sz})
6879
        self.op.disks = disks
6880
      else:
6881
        raise errors.OpPrereqError("No disk info specified and the export"
6882
                                   " is missing the disk information",
6883
                                   errors.ECODE_INVAL)
6884

    
6885
    if (not self.op.nics and
6886
        einfo.has_option(constants.INISECT_INS, "nic_count")):
6887
      nics = []
6888
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
6889
        ndict = {}
6890
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
6891
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
6892
          ndict[name] = v
6893
        nics.append(ndict)
6894
      self.op.nics = nics
6895

    
6896
    if (self.op.hypervisor is None and
6897
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
6898
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
6899
    if einfo.has_section(constants.INISECT_HYP):
6900
      # use the export parameters but do not override the ones
6901
      # specified by the user
6902
      for name, value in einfo.items(constants.INISECT_HYP):
6903
        if name not in self.op.hvparams:
6904
          self.op.hvparams[name] = value
6905

    
6906
    if einfo.has_section(constants.INISECT_BEP):
6907
      # use the parameters, without overriding
6908
      for name, value in einfo.items(constants.INISECT_BEP):
6909
        if name not in self.op.beparams:
6910
          self.op.beparams[name] = value
6911
    else:
6912
      # try to read the parameters old style, from the main section
6913
      for name in constants.BES_PARAMETERS:
6914
        if (name not in self.op.beparams and
6915
            einfo.has_option(constants.INISECT_INS, name)):
6916
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
6917

    
6918
    if einfo.has_section(constants.INISECT_OSP):
6919
      # use the parameters, without overriding
6920
      for name, value in einfo.items(constants.INISECT_OSP):
6921
        if name not in self.op.osparams:
6922
          self.op.osparams[name] = value
6923

    
6924
  def _RevertToDefaults(self, cluster):
6925
    """Revert the instance parameters to the default values.
6926

6927
    """
6928
    # hvparams
6929
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
6930
    for name in self.op.hvparams.keys():
6931
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
6932
        del self.op.hvparams[name]
6933
    # beparams
6934
    be_defs = cluster.SimpleFillBE({})
6935
    for name in self.op.beparams.keys():
6936
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
6937
        del self.op.beparams[name]
6938
    # nic params
6939
    nic_defs = cluster.SimpleFillNIC({})
6940
    for nic in self.op.nics:
6941
      for name in constants.NICS_PARAMETERS:
6942
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
6943
          del nic[name]
6944
    # osparams
6945
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
6946
    for name in self.op.osparams.keys():
6947
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
6948
        del self.op.osparams[name]
6949

    
6950
  def CheckPrereq(self):
6951
    """Check prerequisites.
6952

6953
    """
6954
    if self.op.mode == constants.INSTANCE_IMPORT:
6955
      export_info = self._ReadExportInfo()
6956
      self._ReadExportParams(export_info)
6957

    
6958
    _CheckDiskTemplate(self.op.disk_template)
6959

    
6960
    if (not self.cfg.GetVGName() and
6961
        self.op.disk_template not in constants.DTS_NOT_LVM):
6962
      raise errors.OpPrereqError("Cluster does not support lvm-based"
6963
                                 " instances", errors.ECODE_STATE)
6964

    
6965
    if self.op.hypervisor is None:
6966
      self.op.hypervisor = self.cfg.GetHypervisorType()
6967

    
6968
    cluster = self.cfg.GetClusterInfo()
6969
    enabled_hvs = cluster.enabled_hypervisors
6970
    if self.op.hypervisor not in enabled_hvs:
6971
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
6972
                                 " cluster (%s)" % (self.op.hypervisor,
6973
                                  ",".join(enabled_hvs)),
6974
                                 errors.ECODE_STATE)
6975

    
6976
    # check hypervisor parameter syntax (locally)
6977
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
6978
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
6979
                                      self.op.hvparams)
6980
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
6981
    hv_type.CheckParameterSyntax(filled_hvp)
6982
    self.hv_full = filled_hvp
6983
    # check that we don't specify global parameters on an instance
6984
    _CheckGlobalHvParams(self.op.hvparams)
6985

    
6986
    # fill and remember the beparams dict
6987
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
6988
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
6989

    
6990
    # build os parameters
6991
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
6992

    
6993
    # now that hvp/bep are in final format, let's reset to defaults,
6994
    # if told to do so
6995
    if self.op.identify_defaults:
6996
      self._RevertToDefaults(cluster)
6997

    
6998
    # NIC buildup
6999
    self.nics = []
7000
    for idx, nic in enumerate(self.op.nics):
7001
      nic_mode_req = nic.get("mode", None)
7002
      nic_mode = nic_mode_req
7003
      if nic_mode is None:
7004
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
7005

    
7006
      # in routed mode, for the first nic, the default ip is 'auto'
7007
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
7008
        default_ip_mode = constants.VALUE_AUTO
7009
      else:
7010
        default_ip_mode = constants.VALUE_NONE
7011

    
7012
      # ip validity checks
7013
      ip = nic.get("ip", default_ip_mode)
7014
      if ip is None or ip.lower() == constants.VALUE_NONE:
7015
        nic_ip = None
7016
      elif ip.lower() == constants.VALUE_AUTO:
7017
        if not self.op.name_check:
7018
          raise errors.OpPrereqError("IP address set to auto but name checks"
7019
                                     " have been skipped",
7020
                                     errors.ECODE_INVAL)
7021
        nic_ip = self.hostname1.ip
7022
      else:
7023
        if not netutils.IPAddress.IsValid(ip):
7024
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
7025
                                     errors.ECODE_INVAL)
7026
        nic_ip = ip
7027

    
7028
      # TODO: check the ip address for uniqueness
7029
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7030
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7031
                                   errors.ECODE_INVAL)
7032

    
7033
      # MAC address verification
7034
      mac = nic.get("mac", constants.VALUE_AUTO)
7035
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7036
        mac = utils.NormalizeAndValidateMac(mac)
7037

    
7038
        try:
7039
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7040
        except errors.ReservationError:
7041
          raise errors.OpPrereqError("MAC address %s already in use"
7042
                                     " in cluster" % mac,
7043
                                     errors.ECODE_NOTUNIQUE)
7044

    
7045
      # bridge verification
7046
      bridge = nic.get("bridge", None)
7047
      link = nic.get("link", None)
7048
      if bridge and link:
7049
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7050
                                   " at the same time", errors.ECODE_INVAL)
7051
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7052
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7053
                                   errors.ECODE_INVAL)
7054
      elif bridge:
7055
        link = bridge
7056

    
7057
      nicparams = {}
7058
      if nic_mode_req:
7059
        nicparams[constants.NIC_MODE] = nic_mode_req
7060
      if link:
7061
        nicparams[constants.NIC_LINK] = link
7062

    
7063
      check_params = cluster.SimpleFillNIC(nicparams)
7064
      objects.NIC.CheckParameterSyntax(check_params)
7065
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7066

    
7067
    # disk checks/pre-build
7068
    self.disks = []
7069
    for disk in self.op.disks:
7070
      mode = disk.get("mode", constants.DISK_RDWR)
7071
      if mode not in constants.DISK_ACCESS_SET:
7072
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7073
                                   mode, errors.ECODE_INVAL)
7074
      size = disk.get("size", None)
7075
      if size is None:
7076
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7077
      try:
7078
        size = int(size)
7079
      except (TypeError, ValueError):
7080
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7081
                                   errors.ECODE_INVAL)
7082
      new_disk = {"size": size, "mode": mode}
7083
      if "adopt" in disk:
7084
        new_disk["adopt"] = disk["adopt"]
7085
      self.disks.append(new_disk)
7086

    
7087
    if self.op.mode == constants.INSTANCE_IMPORT:
7088

    
7089
      # Check that the new instance doesn't have less disks than the export
7090
      instance_disks = len(self.disks)
7091
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7092
      if instance_disks < export_disks:
7093
        raise errors.OpPrereqError("Not enough disks to import."
7094
                                   " (instance: %d, export: %d)" %
7095
                                   (instance_disks, export_disks),
7096
                                   errors.ECODE_INVAL)
7097

    
7098
      disk_images = []
7099
      for idx in range(export_disks):
7100
        option = 'disk%d_dump' % idx
7101
        if export_info.has_option(constants.INISECT_INS, option):
7102
          # FIXME: are the old os-es, disk sizes, etc. useful?
7103
          export_name = export_info.get(constants.INISECT_INS, option)
7104
          image = utils.PathJoin(self.op.src_path, export_name)
7105
          disk_images.append(image)
7106
        else:
7107
          disk_images.append(False)
7108

    
7109
      self.src_images = disk_images
7110

    
7111
      old_name = export_info.get(constants.INISECT_INS, 'name')
7112
      try:
7113
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7114
      except (TypeError, ValueError), err:
7115
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7116
                                   " an integer: %s" % str(err),
7117
                                   errors.ECODE_STATE)
7118
      if self.op.instance_name == old_name:
7119
        for idx, nic in enumerate(self.nics):
7120
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7121
            nic_mac_ini = 'nic%d_mac' % idx
7122
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7123

    
7124
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7125

    
7126
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7127
    if self.op.ip_check:
7128
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7129
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7130
                                   (self.check_ip, self.op.instance_name),
7131
                                   errors.ECODE_NOTUNIQUE)
7132

    
7133
    #### mac address generation
7134
    # By generating here the mac address both the allocator and the hooks get
7135
    # the real final mac address rather than the 'auto' or 'generate' value.
7136
    # There is a race condition between the generation and the instance object
7137
    # creation, which means that we know the mac is valid now, but we're not
7138
    # sure it will be when we actually add the instance. If things go bad
7139
    # adding the instance will abort because of a duplicate mac, and the
7140
    # creation job will fail.
7141
    for nic in self.nics:
7142
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7143
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7144

    
7145
    #### allocator run
7146

    
7147
    if self.op.iallocator is not None:
7148
      self._RunAllocator()
7149

    
7150
    #### node related checks
7151

    
7152
    # check primary node
7153
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7154
    assert self.pnode is not None, \
7155
      "Cannot retrieve locked node %s" % self.op.pnode
7156
    if pnode.offline:
7157
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7158
                                 pnode.name, errors.ECODE_STATE)
7159
    if pnode.drained:
7160
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7161
                                 pnode.name, errors.ECODE_STATE)
7162

    
7163
    self.secondaries = []
7164

    
7165
    # mirror node verification
7166
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7167
      if self.op.snode == pnode.name:
7168
        raise errors.OpPrereqError("The secondary node cannot be the"
7169
                                   " primary node.", errors.ECODE_INVAL)
7170
      _CheckNodeOnline(self, self.op.snode)
7171
      _CheckNodeNotDrained(self, self.op.snode)
7172
      self.secondaries.append(self.op.snode)
7173

    
7174
    nodenames = [pnode.name] + self.secondaries
7175

    
7176
    req_size = _ComputeDiskSize(self.op.disk_template,
7177
                                self.disks)
7178

    
7179
    # Check lv size requirements, if not adopting
7180
    if req_size is not None and not self.adopt_disks:
7181
      _CheckNodesFreeDisk(self, nodenames, req_size)
7182

    
7183
    if self.adopt_disks: # instead, we must check the adoption data
7184
      all_lvs = set([i["adopt"] for i in self.disks])
7185
      if len(all_lvs) != len(self.disks):
7186
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7187
                                   errors.ECODE_INVAL)
7188
      for lv_name in all_lvs:
7189
        try:
7190
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7191
        except errors.ReservationError:
7192
          raise errors.OpPrereqError("LV named %s used by another instance" %
7193
                                     lv_name, errors.ECODE_NOTUNIQUE)
7194

    
7195
      node_lvs = self.rpc.call_lv_list([pnode.name],
7196
                                       self.cfg.GetVGName())[pnode.name]
7197
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7198
      node_lvs = node_lvs.payload
7199
      delta = all_lvs.difference(node_lvs.keys())
7200
      if delta:
7201
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7202
                                   utils.CommaJoin(delta),
7203
                                   errors.ECODE_INVAL)
7204
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7205
      if online_lvs:
7206
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7207
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7208
                                   errors.ECODE_STATE)
7209
      # update the size of disk based on what is found
7210
      for dsk in self.disks:
7211
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
7212

    
7213
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7214

    
7215
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7216
    # check OS parameters (remotely)
7217
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7218

    
7219
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7220

    
7221
    # memory check on primary node
7222
    if self.op.start:
7223
      _CheckNodeFreeMemory(self, self.pnode.name,
7224
                           "creating instance %s" % self.op.instance_name,
7225
                           self.be_full[constants.BE_MEMORY],
7226
                           self.op.hypervisor)
7227

    
7228
    self.dry_run_result = list(nodenames)
7229

    
7230
  def Exec(self, feedback_fn):
7231
    """Create and add the instance to the cluster.
7232

7233
    """
7234
    instance = self.op.instance_name
7235
    pnode_name = self.pnode.name
7236

    
7237
    ht_kind = self.op.hypervisor
7238
    if ht_kind in constants.HTS_REQ_PORT:
7239
      network_port = self.cfg.AllocatePort()
7240
    else:
7241
      network_port = None
7242

    
7243
    if constants.ENABLE_FILE_STORAGE:
7244
      # this is needed because os.path.join does not accept None arguments
7245
      if self.op.file_storage_dir is None:
7246
        string_file_storage_dir = ""
7247
      else:
7248
        string_file_storage_dir = self.op.file_storage_dir
7249

    
7250
      # build the full file storage dir path
7251
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7252
                                        string_file_storage_dir, instance)
7253
    else:
7254
      file_storage_dir = ""
7255

    
7256
    disks = _GenerateDiskTemplate(self,
7257
                                  self.op.disk_template,
7258
                                  instance, pnode_name,
7259
                                  self.secondaries,
7260
                                  self.disks,
7261
                                  file_storage_dir,
7262
                                  self.op.file_driver,
7263
                                  0)
7264

    
7265
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7266
                            primary_node=pnode_name,
7267
                            nics=self.nics, disks=disks,
7268
                            disk_template=self.op.disk_template,
7269
                            admin_up=False,
7270
                            network_port=network_port,
7271
                            beparams=self.op.beparams,
7272
                            hvparams=self.op.hvparams,
7273
                            hypervisor=self.op.hypervisor,
7274
                            osparams=self.op.osparams,
7275
                            )
7276

    
7277
    if self.adopt_disks:
7278
      # rename LVs to the newly-generated names; we need to construct
7279
      # 'fake' LV disks with the old data, plus the new unique_id
7280
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7281
      rename_to = []
7282
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7283
        rename_to.append(t_dsk.logical_id)
7284
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7285
        self.cfg.SetDiskID(t_dsk, pnode_name)
7286
      result = self.rpc.call_blockdev_rename(pnode_name,
7287
                                             zip(tmp_disks, rename_to))
7288
      result.Raise("Failed to rename adoped LVs")
7289
    else:
7290
      feedback_fn("* creating instance disks...")
7291
      try:
7292
        _CreateDisks(self, iobj)
7293
      except errors.OpExecError:
7294
        self.LogWarning("Device creation failed, reverting...")
7295
        try:
7296
          _RemoveDisks(self, iobj)
7297
        finally:
7298
          self.cfg.ReleaseDRBDMinors(instance)
7299
          raise
7300

    
7301
    feedback_fn("adding instance %s to cluster config" % instance)
7302

    
7303
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7304

    
7305
    # Declare that we don't want to remove the instance lock anymore, as we've
7306
    # added the instance to the config
7307
    del self.remove_locks[locking.LEVEL_INSTANCE]
7308
    # Unlock all the nodes
7309
    if self.op.mode == constants.INSTANCE_IMPORT:
7310
      nodes_keep = [self.op.src_node]
7311
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7312
                       if node != self.op.src_node]
7313
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7314
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7315
    else:
7316
      self.context.glm.release(locking.LEVEL_NODE)
7317
      del self.acquired_locks[locking.LEVEL_NODE]
7318

    
7319
    if self.op.wait_for_sync:
7320
      disk_abort = not _WaitForSync(self, iobj)
7321
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7322
      # make sure the disks are not degraded (still sync-ing is ok)
7323
      time.sleep(15)
7324
      feedback_fn("* checking mirrors status")
7325
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7326
    else:
7327
      disk_abort = False
7328

    
7329
    if disk_abort:
7330
      _RemoveDisks(self, iobj)
7331
      self.cfg.RemoveInstance(iobj.name)
7332
      # Make sure the instance lock gets removed
7333
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7334
      raise errors.OpExecError("There are some degraded disks for"
7335
                               " this instance")
7336

    
7337
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7338
      if self.op.mode == constants.INSTANCE_CREATE:
7339
        if not self.op.no_install:
7340
          feedback_fn("* running the instance OS create scripts...")
7341
          # FIXME: pass debug option from opcode to backend
7342
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7343
                                                 self.op.debug_level)
7344
          result.Raise("Could not add os for instance %s"
7345
                       " on node %s" % (instance, pnode_name))
7346

    
7347
      elif self.op.mode == constants.INSTANCE_IMPORT:
7348
        feedback_fn("* running the instance OS import scripts...")
7349

    
7350
        transfers = []
7351

    
7352
        for idx, image in enumerate(self.src_images):
7353
          if not image:
7354
            continue
7355

    
7356
          # FIXME: pass debug option from opcode to backend
7357
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7358
                                             constants.IEIO_FILE, (image, ),
7359
                                             constants.IEIO_SCRIPT,
7360
                                             (iobj.disks[idx], idx),
7361
                                             None)
7362
          transfers.append(dt)
7363

    
7364
        import_result = \
7365
          masterd.instance.TransferInstanceData(self, feedback_fn,
7366
                                                self.op.src_node, pnode_name,
7367
                                                self.pnode.secondary_ip,
7368
                                                iobj, transfers)
7369
        if not compat.all(import_result):
7370
          self.LogWarning("Some disks for instance %s on node %s were not"
7371
                          " imported successfully" % (instance, pnode_name))
7372

    
7373
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7374
        feedback_fn("* preparing remote import...")
7375
        connect_timeout = constants.RIE_CONNECT_TIMEOUT
7376
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7377

    
7378
        disk_results = masterd.instance.RemoteImport(self, feedback_fn, iobj,
7379
                                                     self.source_x509_ca,
7380
                                                     self._cds, timeouts)
7381
        if not compat.all(disk_results):
7382
          # TODO: Should the instance still be started, even if some disks
7383
          # failed to import (valid for local imports, too)?
7384
          self.LogWarning("Some disks for instance %s on node %s were not"
7385
                          " imported successfully" % (instance, pnode_name))
7386

    
7387
        # Run rename script on newly imported instance
7388
        assert iobj.name == instance
7389
        feedback_fn("Running rename script for %s" % instance)
7390
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7391
                                                   self.source_instance_name,
7392
                                                   self.op.debug_level)
7393
        if result.fail_msg:
7394
          self.LogWarning("Failed to run rename script for %s on node"
7395
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7396

    
7397
      else:
7398
        # also checked in the prereq part
7399
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7400
                                     % self.op.mode)
7401

    
7402
    if self.op.start:
7403
      iobj.admin_up = True
7404
      self.cfg.Update(iobj, feedback_fn)
7405
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7406
      feedback_fn("* starting instance...")
7407
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7408
      result.Raise("Could not start instance")
7409

    
7410
    return list(iobj.all_nodes)
7411

    
7412

    
7413
class LUConnectConsole(NoHooksLU):
7414
  """Connect to an instance's console.
7415

7416
  This is somewhat special in that it returns the command line that
7417
  you need to run on the master node in order to connect to the
7418
  console.
7419

7420
  """
7421
  _OP_PARAMS = [
7422
    _PInstanceName
7423
    ]
7424
  REQ_BGL = False
7425

    
7426
  def ExpandNames(self):
7427
    self._ExpandAndLockInstance()
7428

    
7429
  def CheckPrereq(self):
7430
    """Check prerequisites.
7431

7432
    This checks that the instance is in the cluster.
7433

7434
    """
7435
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7436
    assert self.instance is not None, \
7437
      "Cannot retrieve locked instance %s" % self.op.instance_name
7438
    _CheckNodeOnline(self, self.instance.primary_node)
7439

    
7440
  def Exec(self, feedback_fn):
7441
    """Connect to the console of an instance
7442

7443
    """
7444
    instance = self.instance
7445
    node = instance.primary_node
7446

    
7447
    node_insts = self.rpc.call_instance_list([node],
7448
                                             [instance.hypervisor])[node]
7449
    node_insts.Raise("Can't get node information from %s" % node)
7450

    
7451
    if instance.name not in node_insts.payload:
7452
      raise errors.OpExecError("Instance %s is not running." % instance.name)
7453

    
7454
    logging.debug("Connecting to console of %s on %s", instance.name, node)
7455

    
7456
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
7457
    cluster = self.cfg.GetClusterInfo()
7458
    # beparams and hvparams are passed separately, to avoid editing the
7459
    # instance and then saving the defaults in the instance itself.
7460
    hvparams = cluster.FillHV(instance)
7461
    beparams = cluster.FillBE(instance)
7462
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
7463

    
7464
    # build ssh cmdline
7465
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
7466

    
7467

    
7468
class LUReplaceDisks(LogicalUnit):
7469
  """Replace the disks of an instance.
7470

7471
  """
7472
  HPATH = "mirrors-replace"
7473
  HTYPE = constants.HTYPE_INSTANCE
7474
  _OP_PARAMS = [
7475
    _PInstanceName,
7476
    ("mode", _NoDefault, _TElemOf(constants.REPLACE_MODES)),
7477
    ("disks", _EmptyList, _TListOf(_TPositiveInt)),
7478
    ("remote_node", None, _TMaybeString),
7479
    ("iallocator", None, _TMaybeString),
7480
    ("early_release", False, _TBool),
7481
    ]
7482
  REQ_BGL = False
7483

    
7484
  def CheckArguments(self):
7485
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7486
                                  self.op.iallocator)
7487

    
7488
  def ExpandNames(self):
7489
    self._ExpandAndLockInstance()
7490

    
7491
    if self.op.iallocator is not None:
7492
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7493

    
7494
    elif self.op.remote_node is not None:
7495
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7496
      self.op.remote_node = remote_node
7497

    
7498
      # Warning: do not remove the locking of the new secondary here
7499
      # unless DRBD8.AddChildren is changed to work in parallel;
7500
      # currently it doesn't since parallel invocations of
7501
      # FindUnusedMinor will conflict
7502
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7503
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7504

    
7505
    else:
7506
      self.needed_locks[locking.LEVEL_NODE] = []
7507
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7508

    
7509
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7510
                                   self.op.iallocator, self.op.remote_node,
7511
                                   self.op.disks, False, self.op.early_release)
7512

    
7513
    self.tasklets = [self.replacer]
7514

    
7515
  def DeclareLocks(self, level):
7516
    # If we're not already locking all nodes in the set we have to declare the
7517
    # instance's primary/secondary nodes.
7518
    if (level == locking.LEVEL_NODE and
7519
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7520
      self._LockInstancesNodes()
7521

    
7522
  def BuildHooksEnv(self):
7523
    """Build hooks env.
7524

7525
    This runs on the master, the primary and all the secondaries.
7526

7527
    """
7528
    instance = self.replacer.instance
7529
    env = {
7530
      "MODE": self.op.mode,
7531
      "NEW_SECONDARY": self.op.remote_node,
7532
      "OLD_SECONDARY": instance.secondary_nodes[0],
7533
      }
7534
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7535
    nl = [
7536
      self.cfg.GetMasterNode(),
7537
      instance.primary_node,
7538
      ]
7539
    if self.op.remote_node is not None:
7540
      nl.append(self.op.remote_node)
7541
    return env, nl, nl
7542

    
7543

    
7544
class TLReplaceDisks(Tasklet):
7545
  """Replaces disks for an instance.
7546

7547
  Note: Locking is not within the scope of this class.
7548

7549
  """
7550
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7551
               disks, delay_iallocator, early_release):
7552
    """Initializes this class.
7553

7554
    """
7555
    Tasklet.__init__(self, lu)
7556

    
7557
    # Parameters
7558
    self.instance_name = instance_name
7559
    self.mode = mode
7560
    self.iallocator_name = iallocator_name
7561
    self.remote_node = remote_node
7562
    self.disks = disks
7563
    self.delay_iallocator = delay_iallocator
7564
    self.early_release = early_release
7565

    
7566
    # Runtime data
7567
    self.instance = None
7568
    self.new_node = None
7569
    self.target_node = None
7570
    self.other_node = None
7571
    self.remote_node_info = None
7572
    self.node_secondary_ip = None
7573

    
7574
  @staticmethod
7575
  def CheckArguments(mode, remote_node, iallocator):
7576
    """Helper function for users of this class.
7577

7578
    """
7579
    # check for valid parameter combination
7580
    if mode == constants.REPLACE_DISK_CHG:
7581
      if remote_node is None and iallocator is None:
7582
        raise errors.OpPrereqError("When changing the secondary either an"
7583
                                   " iallocator script must be used or the"
7584
                                   " new node given", errors.ECODE_INVAL)
7585

    
7586
      if remote_node is not None and iallocator is not None:
7587
        raise errors.OpPrereqError("Give either the iallocator or the new"
7588
                                   " secondary, not both", errors.ECODE_INVAL)
7589

    
7590
    elif remote_node is not None or iallocator is not None:
7591
      # Not replacing the secondary
7592
      raise errors.OpPrereqError("The iallocator and new node options can"
7593
                                 " only be used when changing the"
7594
                                 " secondary node", errors.ECODE_INVAL)
7595

    
7596
  @staticmethod
7597
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7598
    """Compute a new secondary node using an IAllocator.
7599

7600
    """
7601
    ial = IAllocator(lu.cfg, lu.rpc,
7602
                     mode=constants.IALLOCATOR_MODE_RELOC,
7603
                     name=instance_name,
7604
                     relocate_from=relocate_from)
7605

    
7606
    ial.Run(iallocator_name)
7607

    
7608
    if not ial.success:
7609
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7610
                                 " %s" % (iallocator_name, ial.info),
7611
                                 errors.ECODE_NORES)
7612

    
7613
    if len(ial.result) != ial.required_nodes:
7614
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7615
                                 " of nodes (%s), required %s" %
7616
                                 (iallocator_name,
7617
                                  len(ial.result), ial.required_nodes),
7618
                                 errors.ECODE_FAULT)
7619

    
7620
    remote_node_name = ial.result[0]
7621

    
7622
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7623
               instance_name, remote_node_name)
7624

    
7625
    return remote_node_name
7626

    
7627
  def _FindFaultyDisks(self, node_name):
7628
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7629
                                    node_name, True)
7630

    
7631
  def CheckPrereq(self):
7632
    """Check prerequisites.
7633

7634
    This checks that the instance is in the cluster.
7635

7636
    """
7637
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7638
    assert instance is not None, \
7639
      "Cannot retrieve locked instance %s" % self.instance_name
7640

    
7641
    if instance.disk_template != constants.DT_DRBD8:
7642
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7643
                                 " instances", errors.ECODE_INVAL)
7644

    
7645
    if len(instance.secondary_nodes) != 1:
7646
      raise errors.OpPrereqError("The instance has a strange layout,"
7647
                                 " expected one secondary but found %d" %
7648
                                 len(instance.secondary_nodes),
7649
                                 errors.ECODE_FAULT)
7650

    
7651
    if not self.delay_iallocator:
7652
      self._CheckPrereq2()
7653

    
7654
  def _CheckPrereq2(self):
7655
    """Check prerequisites, second part.
7656

7657
    This function should always be part of CheckPrereq. It was separated and is
7658
    now called from Exec because during node evacuation iallocator was only
7659
    called with an unmodified cluster model, not taking planned changes into
7660
    account.
7661

7662
    """
7663
    instance = self.instance
7664
    secondary_node = instance.secondary_nodes[0]
7665

    
7666
    if self.iallocator_name is None:
7667
      remote_node = self.remote_node
7668
    else:
7669
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
7670
                                       instance.name, instance.secondary_nodes)
7671

    
7672
    if remote_node is not None:
7673
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
7674
      assert self.remote_node_info is not None, \
7675
        "Cannot retrieve locked node %s" % remote_node
7676
    else:
7677
      self.remote_node_info = None
7678

    
7679
    if remote_node == self.instance.primary_node:
7680
      raise errors.OpPrereqError("The specified node is the primary node of"
7681
                                 " the instance.", errors.ECODE_INVAL)
7682

    
7683
    if remote_node == secondary_node:
7684
      raise errors.OpPrereqError("The specified node is already the"
7685
                                 " secondary node of the instance.",
7686
                                 errors.ECODE_INVAL)
7687

    
7688
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
7689
                                    constants.REPLACE_DISK_CHG):
7690
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
7691
                                 errors.ECODE_INVAL)
7692

    
7693
    if self.mode == constants.REPLACE_DISK_AUTO:
7694
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
7695
      faulty_secondary = self._FindFaultyDisks(secondary_node)
7696

    
7697
      if faulty_primary and faulty_secondary:
7698
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
7699
                                   " one node and can not be repaired"
7700
                                   " automatically" % self.instance_name,
7701
                                   errors.ECODE_STATE)
7702

    
7703
      if faulty_primary:
7704
        self.disks = faulty_primary
7705
        self.target_node = instance.primary_node
7706
        self.other_node = secondary_node
7707
        check_nodes = [self.target_node, self.other_node]
7708
      elif faulty_secondary:
7709
        self.disks = faulty_secondary
7710
        self.target_node = secondary_node
7711
        self.other_node = instance.primary_node
7712
        check_nodes = [self.target_node, self.other_node]
7713
      else:
7714
        self.disks = []
7715
        check_nodes = []
7716

    
7717
    else:
7718
      # Non-automatic modes
7719
      if self.mode == constants.REPLACE_DISK_PRI:
7720
        self.target_node = instance.primary_node
7721
        self.other_node = secondary_node
7722
        check_nodes = [self.target_node, self.other_node]
7723

    
7724
      elif self.mode == constants.REPLACE_DISK_SEC:
7725
        self.target_node = secondary_node
7726
        self.other_node = instance.primary_node
7727
        check_nodes = [self.target_node, self.other_node]
7728

    
7729
      elif self.mode == constants.REPLACE_DISK_CHG:
7730
        self.new_node = remote_node
7731
        self.other_node = instance.primary_node
7732
        self.target_node = secondary_node
7733
        check_nodes = [self.new_node, self.other_node]
7734

    
7735
        _CheckNodeNotDrained(self.lu, remote_node)
7736

    
7737
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
7738
        assert old_node_info is not None
7739
        if old_node_info.offline and not self.early_release:
7740
          # doesn't make sense to delay the release
7741
          self.early_release = True
7742
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
7743
                          " early-release mode", secondary_node)
7744

    
7745
      else:
7746
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
7747
                                     self.mode)
7748

    
7749
      # If not specified all disks should be replaced
7750
      if not self.disks:
7751
        self.disks = range(len(self.instance.disks))
7752

    
7753
    for node in check_nodes:
7754
      _CheckNodeOnline(self.lu, node)
7755

    
7756
    # Check whether disks are valid
7757
    for disk_idx in self.disks:
7758
      instance.FindDisk(disk_idx)
7759

    
7760
    # Get secondary node IP addresses
7761
    node_2nd_ip = {}
7762

    
7763
    for node_name in [self.target_node, self.other_node, self.new_node]:
7764
      if node_name is not None:
7765
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
7766

    
7767
    self.node_secondary_ip = node_2nd_ip
7768

    
7769
  def Exec(self, feedback_fn):
7770
    """Execute disk replacement.
7771

7772
    This dispatches the disk replacement to the appropriate handler.
7773

7774
    """
7775
    if self.delay_iallocator:
7776
      self._CheckPrereq2()
7777

    
7778
    if not self.disks:
7779
      feedback_fn("No disks need replacement")
7780
      return
7781

    
7782
    feedback_fn("Replacing disk(s) %s for %s" %
7783
                (utils.CommaJoin(self.disks), self.instance.name))
7784

    
7785
    activate_disks = (not self.instance.admin_up)
7786

    
7787
    # Activate the instance disks if we're replacing them on a down instance
7788
    if activate_disks:
7789
      _StartInstanceDisks(self.lu, self.instance, True)
7790

    
7791
    try:
7792
      # Should we replace the secondary node?
7793
      if self.new_node is not None:
7794
        fn = self._ExecDrbd8Secondary
7795
      else:
7796
        fn = self._ExecDrbd8DiskOnly
7797

    
7798
      return fn(feedback_fn)
7799

    
7800
    finally:
7801
      # Deactivate the instance disks if we're replacing them on a
7802
      # down instance
7803
      if activate_disks:
7804
        _SafeShutdownInstanceDisks(self.lu, self.instance)
7805

    
7806
  def _CheckVolumeGroup(self, nodes):
7807
    self.lu.LogInfo("Checking volume groups")
7808

    
7809
    vgname = self.cfg.GetVGName()
7810

    
7811
    # Make sure volume group exists on all involved nodes
7812
    results = self.rpc.call_vg_list(nodes)
7813
    if not results:
7814
      raise errors.OpExecError("Can't list volume groups on the nodes")
7815

    
7816
    for node in nodes:
7817
      res = results[node]
7818
      res.Raise("Error checking node %s" % node)
7819
      if vgname not in res.payload:
7820
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
7821
                                 (vgname, node))
7822

    
7823
  def _CheckDisksExistence(self, nodes):
7824
    # Check disk existence
7825
    for idx, dev in enumerate(self.instance.disks):
7826
      if idx not in self.disks:
7827
        continue
7828

    
7829
      for node in nodes:
7830
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
7831
        self.cfg.SetDiskID(dev, node)
7832

    
7833
        result = self.rpc.call_blockdev_find(node, dev)
7834

    
7835
        msg = result.fail_msg
7836
        if msg or not result.payload:
7837
          if not msg:
7838
            msg = "disk not found"
7839
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
7840
                                   (idx, node, msg))
7841

    
7842
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
7843
    for idx, dev in enumerate(self.instance.disks):
7844
      if idx not in self.disks:
7845
        continue
7846

    
7847
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
7848
                      (idx, node_name))
7849

    
7850
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
7851
                                   ldisk=ldisk):
7852
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
7853
                                 " replace disks for instance %s" %
7854
                                 (node_name, self.instance.name))
7855

    
7856
  def _CreateNewStorage(self, node_name):
7857
    vgname = self.cfg.GetVGName()
7858
    iv_names = {}
7859

    
7860
    for idx, dev in enumerate(self.instance.disks):
7861
      if idx not in self.disks:
7862
        continue
7863

    
7864
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
7865

    
7866
      self.cfg.SetDiskID(dev, node_name)
7867

    
7868
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
7869
      names = _GenerateUniqueNames(self.lu, lv_names)
7870

    
7871
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
7872
                             logical_id=(vgname, names[0]))
7873
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7874
                             logical_id=(vgname, names[1]))
7875

    
7876
      new_lvs = [lv_data, lv_meta]
7877
      old_lvs = dev.children
7878
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
7879

    
7880
      # we pass force_create=True to force the LVM creation
7881
      for new_lv in new_lvs:
7882
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
7883
                        _GetInstanceInfoText(self.instance), False)
7884

    
7885
    return iv_names
7886

    
7887
  def _CheckDevices(self, node_name, iv_names):
7888
    for name, (dev, _, _) in iv_names.iteritems():
7889
      self.cfg.SetDiskID(dev, node_name)
7890

    
7891
      result = self.rpc.call_blockdev_find(node_name, dev)
7892

    
7893
      msg = result.fail_msg
7894
      if msg or not result.payload:
7895
        if not msg:
7896
          msg = "disk not found"
7897
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
7898
                                 (name, msg))
7899

    
7900
      if result.payload.is_degraded:
7901
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
7902

    
7903
  def _RemoveOldStorage(self, node_name, iv_names):
7904
    for name, (_, old_lvs, _) in iv_names.iteritems():
7905
      self.lu.LogInfo("Remove logical volumes for %s" % name)
7906

    
7907
      for lv in old_lvs:
7908
        self.cfg.SetDiskID(lv, node_name)
7909

    
7910
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
7911
        if msg:
7912
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
7913
                             hint="remove unused LVs manually")
7914

    
7915
  def _ReleaseNodeLock(self, node_name):
7916
    """Releases the lock for a given node."""
7917
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
7918

    
7919
  def _ExecDrbd8DiskOnly(self, feedback_fn):
7920
    """Replace a disk on the primary or secondary for DRBD 8.
7921

7922
    The algorithm for replace is quite complicated:
7923

7924
      1. for each disk to be replaced:
7925

7926
        1. create new LVs on the target node with unique names
7927
        1. detach old LVs from the drbd device
7928
        1. rename old LVs to name_replaced.<time_t>
7929
        1. rename new LVs to old LVs
7930
        1. attach the new LVs (with the old names now) to the drbd device
7931

7932
      1. wait for sync across all devices
7933

7934
      1. for each modified disk:
7935

7936
        1. remove old LVs (which have the name name_replaces.<time_t>)
7937

7938
    Failures are not very well handled.
7939

7940
    """
7941
    steps_total = 6
7942

    
7943
    # Step: check device activation
7944
    self.lu.LogStep(1, steps_total, "Check device existence")
7945
    self._CheckDisksExistence([self.other_node, self.target_node])
7946
    self._CheckVolumeGroup([self.target_node, self.other_node])
7947

    
7948
    # Step: check other node consistency
7949
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7950
    self._CheckDisksConsistency(self.other_node,
7951
                                self.other_node == self.instance.primary_node,
7952
                                False)
7953

    
7954
    # Step: create new storage
7955
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7956
    iv_names = self._CreateNewStorage(self.target_node)
7957

    
7958
    # Step: for each lv, detach+rename*2+attach
7959
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7960
    for dev, old_lvs, new_lvs in iv_names.itervalues():
7961
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
7962

    
7963
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
7964
                                                     old_lvs)
7965
      result.Raise("Can't detach drbd from local storage on node"
7966
                   " %s for device %s" % (self.target_node, dev.iv_name))
7967
      #dev.children = []
7968
      #cfg.Update(instance)
7969

    
7970
      # ok, we created the new LVs, so now we know we have the needed
7971
      # storage; as such, we proceed on the target node to rename
7972
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
7973
      # using the assumption that logical_id == physical_id (which in
7974
      # turn is the unique_id on that node)
7975

    
7976
      # FIXME(iustin): use a better name for the replaced LVs
7977
      temp_suffix = int(time.time())
7978
      ren_fn = lambda d, suff: (d.physical_id[0],
7979
                                d.physical_id[1] + "_replaced-%s" % suff)
7980

    
7981
      # Build the rename list based on what LVs exist on the node
7982
      rename_old_to_new = []
7983
      for to_ren in old_lvs:
7984
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
7985
        if not result.fail_msg and result.payload:
7986
          # device exists
7987
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
7988

    
7989
      self.lu.LogInfo("Renaming the old LVs on the target node")
7990
      result = self.rpc.call_blockdev_rename(self.target_node,
7991
                                             rename_old_to_new)
7992
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
7993

    
7994
      # Now we rename the new LVs to the old LVs
7995
      self.lu.LogInfo("Renaming the new LVs on the target node")
7996
      rename_new_to_old = [(new, old.physical_id)
7997
                           for old, new in zip(old_lvs, new_lvs)]
7998
      result = self.rpc.call_blockdev_rename(self.target_node,
7999
                                             rename_new_to_old)
8000
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
8001

    
8002
      for old, new in zip(old_lvs, new_lvs):
8003
        new.logical_id = old.logical_id
8004
        self.cfg.SetDiskID(new, self.target_node)
8005

    
8006
      for disk in old_lvs:
8007
        disk.logical_id = ren_fn(disk, temp_suffix)
8008
        self.cfg.SetDiskID(disk, self.target_node)
8009

    
8010
      # Now that the new lvs have the old name, we can add them to the device
8011
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
8012
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
8013
                                                  new_lvs)
8014
      msg = result.fail_msg
8015
      if msg:
8016
        for new_lv in new_lvs:
8017
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
8018
                                               new_lv).fail_msg
8019
          if msg2:
8020
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
8021
                               hint=("cleanup manually the unused logical"
8022
                                     "volumes"))
8023
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8024

    
8025
      dev.children = new_lvs
8026

    
8027
      self.cfg.Update(self.instance, feedback_fn)
8028

    
8029
    cstep = 5
8030
    if self.early_release:
8031
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8032
      cstep += 1
8033
      self._RemoveOldStorage(self.target_node, iv_names)
8034
      # WARNING: we release both node locks here, do not do other RPCs
8035
      # than WaitForSync to the primary node
8036
      self._ReleaseNodeLock([self.target_node, self.other_node])
8037

    
8038
    # Wait for sync
8039
    # This can fail as the old devices are degraded and _WaitForSync
8040
    # does a combined result over all disks, so we don't check its return value
8041
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8042
    cstep += 1
8043
    _WaitForSync(self.lu, self.instance)
8044

    
8045
    # Check all devices manually
8046
    self._CheckDevices(self.instance.primary_node, iv_names)
8047

    
8048
    # Step: remove old storage
8049
    if not self.early_release:
8050
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8051
      cstep += 1
8052
      self._RemoveOldStorage(self.target_node, iv_names)
8053

    
8054
  def _ExecDrbd8Secondary(self, feedback_fn):
8055
    """Replace the secondary node for DRBD 8.
8056

8057
    The algorithm for replace is quite complicated:
8058
      - for all disks of the instance:
8059
        - create new LVs on the new node with same names
8060
        - shutdown the drbd device on the old secondary
8061
        - disconnect the drbd network on the primary
8062
        - create the drbd device on the new secondary
8063
        - network attach the drbd on the primary, using an artifice:
8064
          the drbd code for Attach() will connect to the network if it
8065
          finds a device which is connected to the good local disks but
8066
          not network enabled
8067
      - wait for sync across all devices
8068
      - remove all disks from the old secondary
8069

8070
    Failures are not very well handled.
8071

8072
    """
8073
    steps_total = 6
8074

    
8075
    # Step: check device activation
8076
    self.lu.LogStep(1, steps_total, "Check device existence")
8077
    self._CheckDisksExistence([self.instance.primary_node])
8078
    self._CheckVolumeGroup([self.instance.primary_node])
8079

    
8080
    # Step: check other node consistency
8081
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8082
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8083

    
8084
    # Step: create new storage
8085
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8086
    for idx, dev in enumerate(self.instance.disks):
8087
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8088
                      (self.new_node, idx))
8089
      # we pass force_create=True to force LVM creation
8090
      for new_lv in dev.children:
8091
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8092
                        _GetInstanceInfoText(self.instance), False)
8093

    
8094
    # Step 4: dbrd minors and drbd setups changes
8095
    # after this, we must manually remove the drbd minors on both the
8096
    # error and the success paths
8097
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8098
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8099
                                         for dev in self.instance.disks],
8100
                                        self.instance.name)
8101
    logging.debug("Allocated minors %r", minors)
8102

    
8103
    iv_names = {}
8104
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8105
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8106
                      (self.new_node, idx))
8107
      # create new devices on new_node; note that we create two IDs:
8108
      # one without port, so the drbd will be activated without
8109
      # networking information on the new node at this stage, and one
8110
      # with network, for the latter activation in step 4
8111
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8112
      if self.instance.primary_node == o_node1:
8113
        p_minor = o_minor1
8114
      else:
8115
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8116
        p_minor = o_minor2
8117

    
8118
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8119
                      p_minor, new_minor, o_secret)
8120
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8121
                    p_minor, new_minor, o_secret)
8122

    
8123
      iv_names[idx] = (dev, dev.children, new_net_id)
8124
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8125
                    new_net_id)
8126
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8127
                              logical_id=new_alone_id,
8128
                              children=dev.children,
8129
                              size=dev.size)
8130
      try:
8131
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8132
                              _GetInstanceInfoText(self.instance), False)
8133
      except errors.GenericError:
8134
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8135
        raise
8136

    
8137
    # We have new devices, shutdown the drbd on the old secondary
8138
    for idx, dev in enumerate(self.instance.disks):
8139
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8140
      self.cfg.SetDiskID(dev, self.target_node)
8141
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8142
      if msg:
8143
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8144
                           "node: %s" % (idx, msg),
8145
                           hint=("Please cleanup this device manually as"
8146
                                 " soon as possible"))
8147

    
8148
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8149
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8150
                                               self.node_secondary_ip,
8151
                                               self.instance.disks)\
8152
                                              [self.instance.primary_node]
8153

    
8154
    msg = result.fail_msg
8155
    if msg:
8156
      # detaches didn't succeed (unlikely)
8157
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8158
      raise errors.OpExecError("Can't detach the disks from the network on"
8159
                               " old node: %s" % (msg,))
8160

    
8161
    # if we managed to detach at least one, we update all the disks of
8162
    # the instance to point to the new secondary
8163
    self.lu.LogInfo("Updating instance configuration")
8164
    for dev, _, new_logical_id in iv_names.itervalues():
8165
      dev.logical_id = new_logical_id
8166
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8167

    
8168
    self.cfg.Update(self.instance, feedback_fn)
8169

    
8170
    # and now perform the drbd attach
8171
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8172
                    " (standalone => connected)")
8173
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8174
                                            self.new_node],
8175
                                           self.node_secondary_ip,
8176
                                           self.instance.disks,
8177
                                           self.instance.name,
8178
                                           False)
8179
    for to_node, to_result in result.items():
8180
      msg = to_result.fail_msg
8181
      if msg:
8182
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8183
                           to_node, msg,
8184
                           hint=("please do a gnt-instance info to see the"
8185
                                 " status of disks"))
8186
    cstep = 5
8187
    if self.early_release:
8188
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8189
      cstep += 1
8190
      self._RemoveOldStorage(self.target_node, iv_names)
8191
      # WARNING: we release all node locks here, do not do other RPCs
8192
      # than WaitForSync to the primary node
8193
      self._ReleaseNodeLock([self.instance.primary_node,
8194
                             self.target_node,
8195
                             self.new_node])
8196

    
8197
    # Wait for sync
8198
    # This can fail as the old devices are degraded and _WaitForSync
8199
    # does a combined result over all disks, so we don't check its return value
8200
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8201
    cstep += 1
8202
    _WaitForSync(self.lu, self.instance)
8203

    
8204
    # Check all devices manually
8205
    self._CheckDevices(self.instance.primary_node, iv_names)
8206

    
8207
    # Step: remove old storage
8208
    if not self.early_release:
8209
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8210
      self._RemoveOldStorage(self.target_node, iv_names)
8211

    
8212

    
8213
class LURepairNodeStorage(NoHooksLU):
8214
  """Repairs the volume group on a node.
8215

8216
  """
8217
  _OP_PARAMS = [
8218
    _PNodeName,
8219
    ("storage_type", _NoDefault, _CheckStorageType),
8220
    ("name", _NoDefault, _TNonEmptyString),
8221
    ("ignore_consistency", False, _TBool),
8222
    ]
8223
  REQ_BGL = False
8224

    
8225
  def CheckArguments(self):
8226
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8227

    
8228
    storage_type = self.op.storage_type
8229

    
8230
    if (constants.SO_FIX_CONSISTENCY not in
8231
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8232
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8233
                                 " repaired" % storage_type,
8234
                                 errors.ECODE_INVAL)
8235

    
8236
  def ExpandNames(self):
8237
    self.needed_locks = {
8238
      locking.LEVEL_NODE: [self.op.node_name],
8239
      }
8240

    
8241
  def _CheckFaultyDisks(self, instance, node_name):
8242
    """Ensure faulty disks abort the opcode or at least warn."""
8243
    try:
8244
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8245
                                  node_name, True):
8246
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8247
                                   " node '%s'" % (instance.name, node_name),
8248
                                   errors.ECODE_STATE)
8249
    except errors.OpPrereqError, err:
8250
      if self.op.ignore_consistency:
8251
        self.proc.LogWarning(str(err.args[0]))
8252
      else:
8253
        raise
8254

    
8255
  def CheckPrereq(self):
8256
    """Check prerequisites.
8257

8258
    """
8259
    # Check whether any instance on this node has faulty disks
8260
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8261
      if not inst.admin_up:
8262
        continue
8263
      check_nodes = set(inst.all_nodes)
8264
      check_nodes.discard(self.op.node_name)
8265
      for inst_node_name in check_nodes:
8266
        self._CheckFaultyDisks(inst, inst_node_name)
8267

    
8268
  def Exec(self, feedback_fn):
8269
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8270
                (self.op.name, self.op.node_name))
8271

    
8272
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8273
    result = self.rpc.call_storage_execute(self.op.node_name,
8274
                                           self.op.storage_type, st_args,
8275
                                           self.op.name,
8276
                                           constants.SO_FIX_CONSISTENCY)
8277
    result.Raise("Failed to repair storage unit '%s' on %s" %
8278
                 (self.op.name, self.op.node_name))
8279

    
8280

    
8281
class LUNodeEvacuationStrategy(NoHooksLU):
8282
  """Computes the node evacuation strategy.
8283

8284
  """
8285
  _OP_PARAMS = [
8286
    ("nodes", _NoDefault, _TListOf(_TNonEmptyString)),
8287
    ("remote_node", None, _TMaybeString),
8288
    ("iallocator", None, _TMaybeString),
8289
    ]
8290
  REQ_BGL = False
8291

    
8292
  def CheckArguments(self):
8293
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8294

    
8295
  def ExpandNames(self):
8296
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8297
    self.needed_locks = locks = {}
8298
    if self.op.remote_node is None:
8299
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8300
    else:
8301
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8302
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8303

    
8304
  def Exec(self, feedback_fn):
8305
    if self.op.remote_node is not None:
8306
      instances = []
8307
      for node in self.op.nodes:
8308
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8309
      result = []
8310
      for i in instances:
8311
        if i.primary_node == self.op.remote_node:
8312
          raise errors.OpPrereqError("Node %s is the primary node of"
8313
                                     " instance %s, cannot use it as"
8314
                                     " secondary" %
8315
                                     (self.op.remote_node, i.name),
8316
                                     errors.ECODE_INVAL)
8317
        result.append([i.name, self.op.remote_node])
8318
    else:
8319
      ial = IAllocator(self.cfg, self.rpc,
8320
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8321
                       evac_nodes=self.op.nodes)
8322
      ial.Run(self.op.iallocator, validate=True)
8323
      if not ial.success:
8324
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8325
                                 errors.ECODE_NORES)
8326
      result = ial.result
8327
    return result
8328

    
8329

    
8330
class LUGrowDisk(LogicalUnit):
8331
  """Grow a disk of an instance.
8332

8333
  """
8334
  HPATH = "disk-grow"
8335
  HTYPE = constants.HTYPE_INSTANCE
8336
  _OP_PARAMS = [
8337
    _PInstanceName,
8338
    ("disk", _NoDefault, _TInt),
8339
    ("amount", _NoDefault, _TInt),
8340
    ("wait_for_sync", True, _TBool),
8341
    ]
8342
  REQ_BGL = False
8343

    
8344
  def ExpandNames(self):
8345
    self._ExpandAndLockInstance()
8346
    self.needed_locks[locking.LEVEL_NODE] = []
8347
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8348

    
8349
  def DeclareLocks(self, level):
8350
    if level == locking.LEVEL_NODE:
8351
      self._LockInstancesNodes()
8352

    
8353
  def BuildHooksEnv(self):
8354
    """Build hooks env.
8355

8356
    This runs on the master, the primary and all the secondaries.
8357

8358
    """
8359
    env = {
8360
      "DISK": self.op.disk,
8361
      "AMOUNT": self.op.amount,
8362
      }
8363
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8364
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8365
    return env, nl, nl
8366

    
8367
  def CheckPrereq(self):
8368
    """Check prerequisites.
8369

8370
    This checks that the instance is in the cluster.
8371

8372
    """
8373
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8374
    assert instance is not None, \
8375
      "Cannot retrieve locked instance %s" % self.op.instance_name
8376
    nodenames = list(instance.all_nodes)
8377
    for node in nodenames:
8378
      _CheckNodeOnline(self, node)
8379

    
8380
    self.instance = instance
8381

    
8382
    if instance.disk_template not in constants.DTS_GROWABLE:
8383
      raise errors.OpPrereqError("Instance's disk layout does not support"
8384
                                 " growing.", errors.ECODE_INVAL)
8385

    
8386
    self.disk = instance.FindDisk(self.op.disk)
8387

    
8388
    if instance.disk_template != constants.DT_FILE:
8389
      # TODO: check the free disk space for file, when that feature will be
8390
      # supported
8391
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
8392

    
8393
  def Exec(self, feedback_fn):
8394
    """Execute disk grow.
8395

8396
    """
8397
    instance = self.instance
8398
    disk = self.disk
8399

    
8400
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8401
    if not disks_ok:
8402
      raise errors.OpExecError("Cannot activate block device to grow")
8403

    
8404
    for node in instance.all_nodes:
8405
      self.cfg.SetDiskID(disk, node)
8406
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8407
      result.Raise("Grow request failed to node %s" % node)
8408

    
8409
      # TODO: Rewrite code to work properly
8410
      # DRBD goes into sync mode for a short amount of time after executing the
8411
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8412
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8413
      # time is a work-around.
8414
      time.sleep(5)
8415

    
8416
    disk.RecordGrow(self.op.amount)
8417
    self.cfg.Update(instance, feedback_fn)
8418
    if self.op.wait_for_sync:
8419
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8420
      if disk_abort:
8421
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8422
                             " status.\nPlease check the instance.")
8423
      if not instance.admin_up:
8424
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8425
    elif not instance.admin_up:
8426
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8427
                           " not supposed to be running because no wait for"
8428
                           " sync mode was requested.")
8429

    
8430

    
8431
class LUQueryInstanceData(NoHooksLU):
8432
  """Query runtime instance data.
8433

8434
  """
8435
  _OP_PARAMS = [
8436
    ("instances", _EmptyList, _TListOf(_TNonEmptyString)),
8437
    ("static", False, _TBool),
8438
    ]
8439
  REQ_BGL = False
8440

    
8441
  def ExpandNames(self):
8442
    self.needed_locks = {}
8443
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8444

    
8445
    if self.op.instances:
8446
      self.wanted_names = []
8447
      for name in self.op.instances:
8448
        full_name = _ExpandInstanceName(self.cfg, name)
8449
        self.wanted_names.append(full_name)
8450
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8451
    else:
8452
      self.wanted_names = None
8453
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8454

    
8455
    self.needed_locks[locking.LEVEL_NODE] = []
8456
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8457

    
8458
  def DeclareLocks(self, level):
8459
    if level == locking.LEVEL_NODE:
8460
      self._LockInstancesNodes()
8461

    
8462
  def CheckPrereq(self):
8463
    """Check prerequisites.
8464

8465
    This only checks the optional instance list against the existing names.
8466

8467
    """
8468
    if self.wanted_names is None:
8469
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8470

    
8471
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8472
                             in self.wanted_names]
8473

    
8474
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8475
    """Returns the status of a block device
8476

8477
    """
8478
    if self.op.static or not node:
8479
      return None
8480

    
8481
    self.cfg.SetDiskID(dev, node)
8482

    
8483
    result = self.rpc.call_blockdev_find(node, dev)
8484
    if result.offline:
8485
      return None
8486

    
8487
    result.Raise("Can't compute disk status for %s" % instance_name)
8488

    
8489
    status = result.payload
8490
    if status is None:
8491
      return None
8492

    
8493
    return (status.dev_path, status.major, status.minor,
8494
            status.sync_percent, status.estimated_time,
8495
            status.is_degraded, status.ldisk_status)
8496

    
8497
  def _ComputeDiskStatus(self, instance, snode, dev):
8498
    """Compute block device status.
8499

8500
    """
8501
    if dev.dev_type in constants.LDS_DRBD:
8502
      # we change the snode then (otherwise we use the one passed in)
8503
      if dev.logical_id[0] == instance.primary_node:
8504
        snode = dev.logical_id[1]
8505
      else:
8506
        snode = dev.logical_id[0]
8507

    
8508
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8509
                                              instance.name, dev)
8510
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8511

    
8512
    if dev.children:
8513
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8514
                      for child in dev.children]
8515
    else:
8516
      dev_children = []
8517

    
8518
    data = {
8519
      "iv_name": dev.iv_name,
8520
      "dev_type": dev.dev_type,
8521
      "logical_id": dev.logical_id,
8522
      "physical_id": dev.physical_id,
8523
      "pstatus": dev_pstatus,
8524
      "sstatus": dev_sstatus,
8525
      "children": dev_children,
8526
      "mode": dev.mode,
8527
      "size": dev.size,
8528
      }
8529

    
8530
    return data
8531

    
8532
  def Exec(self, feedback_fn):
8533
    """Gather and return data"""
8534
    result = {}
8535

    
8536
    cluster = self.cfg.GetClusterInfo()
8537

    
8538
    for instance in self.wanted_instances:
8539
      if not self.op.static:
8540
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8541
                                                  instance.name,
8542
                                                  instance.hypervisor)
8543
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8544
        remote_info = remote_info.payload
8545
        if remote_info and "state" in remote_info:
8546
          remote_state = "up"
8547
        else:
8548
          remote_state = "down"
8549
      else:
8550
        remote_state = None
8551
      if instance.admin_up:
8552
        config_state = "up"
8553
      else:
8554
        config_state = "down"
8555

    
8556
      disks = [self._ComputeDiskStatus(instance, None, device)
8557
               for device in instance.disks]
8558

    
8559
      idict = {
8560
        "name": instance.name,
8561
        "config_state": config_state,
8562
        "run_state": remote_state,
8563
        "pnode": instance.primary_node,
8564
        "snodes": instance.secondary_nodes,
8565
        "os": instance.os,
8566
        # this happens to be the same format used for hooks
8567
        "nics": _NICListToTuple(self, instance.nics),
8568
        "disk_template": instance.disk_template,
8569
        "disks": disks,
8570
        "hypervisor": instance.hypervisor,
8571
        "network_port": instance.network_port,
8572
        "hv_instance": instance.hvparams,
8573
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8574
        "be_instance": instance.beparams,
8575
        "be_actual": cluster.FillBE(instance),
8576
        "os_instance": instance.osparams,
8577
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8578
        "serial_no": instance.serial_no,
8579
        "mtime": instance.mtime,
8580
        "ctime": instance.ctime,
8581
        "uuid": instance.uuid,
8582
        }
8583

    
8584
      result[instance.name] = idict
8585

    
8586
    return result
8587

    
8588

    
8589
class LUSetInstanceParams(LogicalUnit):
8590
  """Modifies an instances's parameters.
8591

8592
  """
8593
  HPATH = "instance-modify"
8594
  HTYPE = constants.HTYPE_INSTANCE
8595
  _OP_PARAMS = [
8596
    _PInstanceName,
8597
    ("nics", _EmptyList, _TList),
8598
    ("disks", _EmptyList, _TList),
8599
    ("beparams", _EmptyDict, _TDict),
8600
    ("hvparams", _EmptyDict, _TDict),
8601
    ("disk_template", None, _TMaybeString),
8602
    ("remote_node", None, _TMaybeString),
8603
    ("os_name", None, _TMaybeString),
8604
    ("force_variant", False, _TBool),
8605
    ("osparams", None, _TOr(_TDict, _TNone)),
8606
    _PForce,
8607
    ]
8608
  REQ_BGL = False
8609

    
8610
  def CheckArguments(self):
8611
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8612
            self.op.hvparams or self.op.beparams or self.op.os_name):
8613
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8614

    
8615
    if self.op.hvparams:
8616
      _CheckGlobalHvParams(self.op.hvparams)
8617

    
8618
    # Disk validation
8619
    disk_addremove = 0
8620
    for disk_op, disk_dict in self.op.disks:
8621
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8622
      if disk_op == constants.DDM_REMOVE:
8623
        disk_addremove += 1
8624
        continue
8625
      elif disk_op == constants.DDM_ADD:
8626
        disk_addremove += 1
8627
      else:
8628
        if not isinstance(disk_op, int):
8629
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8630
        if not isinstance(disk_dict, dict):
8631
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8632
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8633

    
8634
      if disk_op == constants.DDM_ADD:
8635
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8636
        if mode not in constants.DISK_ACCESS_SET:
8637
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8638
                                     errors.ECODE_INVAL)
8639
        size = disk_dict.get('size', None)
8640
        if size is None:
8641
          raise errors.OpPrereqError("Required disk parameter size missing",
8642
                                     errors.ECODE_INVAL)
8643
        try:
8644
          size = int(size)
8645
        except (TypeError, ValueError), err:
8646
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8647
                                     str(err), errors.ECODE_INVAL)
8648
        disk_dict['size'] = size
8649
      else:
8650
        # modification of disk
8651
        if 'size' in disk_dict:
8652
          raise errors.OpPrereqError("Disk size change not possible, use"
8653
                                     " grow-disk", errors.ECODE_INVAL)
8654

    
8655
    if disk_addremove > 1:
8656
      raise errors.OpPrereqError("Only one disk add or remove operation"
8657
                                 " supported at a time", errors.ECODE_INVAL)
8658

    
8659
    if self.op.disks and self.op.disk_template is not None:
8660
      raise errors.OpPrereqError("Disk template conversion and other disk"
8661
                                 " changes not supported at the same time",
8662
                                 errors.ECODE_INVAL)
8663

    
8664
    if self.op.disk_template:
8665
      _CheckDiskTemplate(self.op.disk_template)
8666
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
8667
          self.op.remote_node is None):
8668
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
8669
                                   " one requires specifying a secondary node",
8670
                                   errors.ECODE_INVAL)
8671

    
8672
    # NIC validation
8673
    nic_addremove = 0
8674
    for nic_op, nic_dict in self.op.nics:
8675
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
8676
      if nic_op == constants.DDM_REMOVE:
8677
        nic_addremove += 1
8678
        continue
8679
      elif nic_op == constants.DDM_ADD:
8680
        nic_addremove += 1
8681
      else:
8682
        if not isinstance(nic_op, int):
8683
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
8684
        if not isinstance(nic_dict, dict):
8685
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
8686
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8687

    
8688
      # nic_dict should be a dict
8689
      nic_ip = nic_dict.get('ip', None)
8690
      if nic_ip is not None:
8691
        if nic_ip.lower() == constants.VALUE_NONE:
8692
          nic_dict['ip'] = None
8693
        else:
8694
          if not netutils.IPAddress.IsValid(nic_ip):
8695
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
8696
                                       errors.ECODE_INVAL)
8697

    
8698
      nic_bridge = nic_dict.get('bridge', None)
8699
      nic_link = nic_dict.get('link', None)
8700
      if nic_bridge and nic_link:
8701
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
8702
                                   " at the same time", errors.ECODE_INVAL)
8703
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
8704
        nic_dict['bridge'] = None
8705
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
8706
        nic_dict['link'] = None
8707

    
8708
      if nic_op == constants.DDM_ADD:
8709
        nic_mac = nic_dict.get('mac', None)
8710
        if nic_mac is None:
8711
          nic_dict['mac'] = constants.VALUE_AUTO
8712

    
8713
      if 'mac' in nic_dict:
8714
        nic_mac = nic_dict['mac']
8715
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8716
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
8717

    
8718
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
8719
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
8720
                                     " modifying an existing nic",
8721
                                     errors.ECODE_INVAL)
8722

    
8723
    if nic_addremove > 1:
8724
      raise errors.OpPrereqError("Only one NIC add or remove operation"
8725
                                 " supported at a time", errors.ECODE_INVAL)
8726

    
8727
  def ExpandNames(self):
8728
    self._ExpandAndLockInstance()
8729
    self.needed_locks[locking.LEVEL_NODE] = []
8730
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8731

    
8732
  def DeclareLocks(self, level):
8733
    if level == locking.LEVEL_NODE:
8734
      self._LockInstancesNodes()
8735
      if self.op.disk_template and self.op.remote_node:
8736
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8737
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
8738

    
8739
  def BuildHooksEnv(self):
8740
    """Build hooks env.
8741

8742
    This runs on the master, primary and secondaries.
8743

8744
    """
8745
    args = dict()
8746
    if constants.BE_MEMORY in self.be_new:
8747
      args['memory'] = self.be_new[constants.BE_MEMORY]
8748
    if constants.BE_VCPUS in self.be_new:
8749
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
8750
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
8751
    # information at all.
8752
    if self.op.nics:
8753
      args['nics'] = []
8754
      nic_override = dict(self.op.nics)
8755
      for idx, nic in enumerate(self.instance.nics):
8756
        if idx in nic_override:
8757
          this_nic_override = nic_override[idx]
8758
        else:
8759
          this_nic_override = {}
8760
        if 'ip' in this_nic_override:
8761
          ip = this_nic_override['ip']
8762
        else:
8763
          ip = nic.ip
8764
        if 'mac' in this_nic_override:
8765
          mac = this_nic_override['mac']
8766
        else:
8767
          mac = nic.mac
8768
        if idx in self.nic_pnew:
8769
          nicparams = self.nic_pnew[idx]
8770
        else:
8771
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
8772
        mode = nicparams[constants.NIC_MODE]
8773
        link = nicparams[constants.NIC_LINK]
8774
        args['nics'].append((ip, mac, mode, link))
8775
      if constants.DDM_ADD in nic_override:
8776
        ip = nic_override[constants.DDM_ADD].get('ip', None)
8777
        mac = nic_override[constants.DDM_ADD]['mac']
8778
        nicparams = self.nic_pnew[constants.DDM_ADD]
8779
        mode = nicparams[constants.NIC_MODE]
8780
        link = nicparams[constants.NIC_LINK]
8781
        args['nics'].append((ip, mac, mode, link))
8782
      elif constants.DDM_REMOVE in nic_override:
8783
        del args['nics'][-1]
8784

    
8785
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
8786
    if self.op.disk_template:
8787
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
8788
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8789
    return env, nl, nl
8790

    
8791
  def CheckPrereq(self):
8792
    """Check prerequisites.
8793

8794
    This only checks the instance list against the existing names.
8795

8796
    """
8797
    # checking the new params on the primary/secondary nodes
8798

    
8799
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8800
    cluster = self.cluster = self.cfg.GetClusterInfo()
8801
    assert self.instance is not None, \
8802
      "Cannot retrieve locked instance %s" % self.op.instance_name
8803
    pnode = instance.primary_node
8804
    nodelist = list(instance.all_nodes)
8805

    
8806
    # OS change
8807
    if self.op.os_name and not self.op.force:
8808
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
8809
                      self.op.force_variant)
8810
      instance_os = self.op.os_name
8811
    else:
8812
      instance_os = instance.os
8813

    
8814
    if self.op.disk_template:
8815
      if instance.disk_template == self.op.disk_template:
8816
        raise errors.OpPrereqError("Instance already has disk template %s" %
8817
                                   instance.disk_template, errors.ECODE_INVAL)
8818

    
8819
      if (instance.disk_template,
8820
          self.op.disk_template) not in self._DISK_CONVERSIONS:
8821
        raise errors.OpPrereqError("Unsupported disk template conversion from"
8822
                                   " %s to %s" % (instance.disk_template,
8823
                                                  self.op.disk_template),
8824
                                   errors.ECODE_INVAL)
8825
      _CheckInstanceDown(self, instance, "cannot change disk template")
8826
      if self.op.disk_template in constants.DTS_NET_MIRROR:
8827
        if self.op.remote_node == pnode:
8828
          raise errors.OpPrereqError("Given new secondary node %s is the same"
8829
                                     " as the primary node of the instance" %
8830
                                     self.op.remote_node, errors.ECODE_STATE)
8831
        _CheckNodeOnline(self, self.op.remote_node)
8832
        _CheckNodeNotDrained(self, self.op.remote_node)
8833
        disks = [{"size": d.size} for d in instance.disks]
8834
        required = _ComputeDiskSize(self.op.disk_template, disks)
8835
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
8836

    
8837
    # hvparams processing
8838
    if self.op.hvparams:
8839
      hv_type = instance.hypervisor
8840
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
8841
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
8842
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
8843

    
8844
      # local check
8845
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
8846
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
8847
      self.hv_new = hv_new # the new actual values
8848
      self.hv_inst = i_hvdict # the new dict (without defaults)
8849
    else:
8850
      self.hv_new = self.hv_inst = {}
8851

    
8852
    # beparams processing
8853
    if self.op.beparams:
8854
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
8855
                                   use_none=True)
8856
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
8857
      be_new = cluster.SimpleFillBE(i_bedict)
8858
      self.be_new = be_new # the new actual values
8859
      self.be_inst = i_bedict # the new dict (without defaults)
8860
    else:
8861
      self.be_new = self.be_inst = {}
8862

    
8863
    # osparams processing
8864
    if self.op.osparams:
8865
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
8866
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
8867
      self.os_new = cluster.SimpleFillOS(instance_os, i_osdict)
8868
      self.os_inst = i_osdict # the new dict (without defaults)
8869
    else:
8870
      self.os_new = self.os_inst = {}
8871

    
8872
    self.warn = []
8873

    
8874
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
8875
      mem_check_list = [pnode]
8876
      if be_new[constants.BE_AUTO_BALANCE]:
8877
        # either we changed auto_balance to yes or it was from before
8878
        mem_check_list.extend(instance.secondary_nodes)
8879
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
8880
                                                  instance.hypervisor)
8881
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
8882
                                         instance.hypervisor)
8883
      pninfo = nodeinfo[pnode]
8884
      msg = pninfo.fail_msg
8885
      if msg:
8886
        # Assume the primary node is unreachable and go ahead
8887
        self.warn.append("Can't get info from primary node %s: %s" %
8888
                         (pnode,  msg))
8889
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
8890
        self.warn.append("Node data from primary node %s doesn't contain"
8891
                         " free memory information" % pnode)
8892
      elif instance_info.fail_msg:
8893
        self.warn.append("Can't get instance runtime information: %s" %
8894
                        instance_info.fail_msg)
8895
      else:
8896
        if instance_info.payload:
8897
          current_mem = int(instance_info.payload['memory'])
8898
        else:
8899
          # Assume instance not running
8900
          # (there is a slight race condition here, but it's not very probable,
8901
          # and we have no other way to check)
8902
          current_mem = 0
8903
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
8904
                    pninfo.payload['memory_free'])
8905
        if miss_mem > 0:
8906
          raise errors.OpPrereqError("This change will prevent the instance"
8907
                                     " from starting, due to %d MB of memory"
8908
                                     " missing on its primary node" % miss_mem,
8909
                                     errors.ECODE_NORES)
8910

    
8911
      if be_new[constants.BE_AUTO_BALANCE]:
8912
        for node, nres in nodeinfo.items():
8913
          if node not in instance.secondary_nodes:
8914
            continue
8915
          msg = nres.fail_msg
8916
          if msg:
8917
            self.warn.append("Can't get info from secondary node %s: %s" %
8918
                             (node, msg))
8919
          elif not isinstance(nres.payload.get('memory_free', None), int):
8920
            self.warn.append("Secondary node %s didn't return free"
8921
                             " memory information" % node)
8922
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
8923
            self.warn.append("Not enough memory to failover instance to"
8924
                             " secondary node %s" % node)
8925

    
8926
    # NIC processing
8927
    self.nic_pnew = {}
8928
    self.nic_pinst = {}
8929
    for nic_op, nic_dict in self.op.nics:
8930
      if nic_op == constants.DDM_REMOVE:
8931
        if not instance.nics:
8932
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
8933
                                     errors.ECODE_INVAL)
8934
        continue
8935
      if nic_op != constants.DDM_ADD:
8936
        # an existing nic
8937
        if not instance.nics:
8938
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
8939
                                     " no NICs" % nic_op,
8940
                                     errors.ECODE_INVAL)
8941
        if nic_op < 0 or nic_op >= len(instance.nics):
8942
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
8943
                                     " are 0 to %d" %
8944
                                     (nic_op, len(instance.nics) - 1),
8945
                                     errors.ECODE_INVAL)
8946
        old_nic_params = instance.nics[nic_op].nicparams
8947
        old_nic_ip = instance.nics[nic_op].ip
8948
      else:
8949
        old_nic_params = {}
8950
        old_nic_ip = None
8951

    
8952
      update_params_dict = dict([(key, nic_dict[key])
8953
                                 for key in constants.NICS_PARAMETERS
8954
                                 if key in nic_dict])
8955

    
8956
      if 'bridge' in nic_dict:
8957
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
8958

    
8959
      new_nic_params = _GetUpdatedParams(old_nic_params,
8960
                                         update_params_dict)
8961
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
8962
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
8963
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
8964
      self.nic_pinst[nic_op] = new_nic_params
8965
      self.nic_pnew[nic_op] = new_filled_nic_params
8966
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
8967

    
8968
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
8969
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
8970
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
8971
        if msg:
8972
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
8973
          if self.op.force:
8974
            self.warn.append(msg)
8975
          else:
8976
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
8977
      if new_nic_mode == constants.NIC_MODE_ROUTED:
8978
        if 'ip' in nic_dict:
8979
          nic_ip = nic_dict['ip']
8980
        else:
8981
          nic_ip = old_nic_ip
8982
        if nic_ip is None:
8983
          raise errors.OpPrereqError('Cannot set the nic ip to None'
8984
                                     ' on a routed nic', errors.ECODE_INVAL)
8985
      if 'mac' in nic_dict:
8986
        nic_mac = nic_dict['mac']
8987
        if nic_mac is None:
8988
          raise errors.OpPrereqError('Cannot set the nic mac to None',
8989
                                     errors.ECODE_INVAL)
8990
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8991
          # otherwise generate the mac
8992
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
8993
        else:
8994
          # or validate/reserve the current one
8995
          try:
8996
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
8997
          except errors.ReservationError:
8998
            raise errors.OpPrereqError("MAC address %s already in use"
8999
                                       " in cluster" % nic_mac,
9000
                                       errors.ECODE_NOTUNIQUE)
9001

    
9002
    # DISK processing
9003
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
9004
      raise errors.OpPrereqError("Disk operations not supported for"
9005
                                 " diskless instances",
9006
                                 errors.ECODE_INVAL)
9007
    for disk_op, _ in self.op.disks:
9008
      if disk_op == constants.DDM_REMOVE:
9009
        if len(instance.disks) == 1:
9010
          raise errors.OpPrereqError("Cannot remove the last disk of"
9011
                                     " an instance", errors.ECODE_INVAL)
9012
        _CheckInstanceDown(self, instance, "cannot remove disks")
9013

    
9014
      if (disk_op == constants.DDM_ADD and
9015
          len(instance.nics) >= constants.MAX_DISKS):
9016
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
9017
                                   " add more" % constants.MAX_DISKS,
9018
                                   errors.ECODE_STATE)
9019
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
9020
        # an existing disk
9021
        if disk_op < 0 or disk_op >= len(instance.disks):
9022
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9023
                                     " are 0 to %d" %
9024
                                     (disk_op, len(instance.disks)),
9025
                                     errors.ECODE_INVAL)
9026

    
9027
    return
9028

    
9029
  def _ConvertPlainToDrbd(self, feedback_fn):
9030
    """Converts an instance from plain to drbd.
9031

9032
    """
9033
    feedback_fn("Converting template to drbd")
9034
    instance = self.instance
9035
    pnode = instance.primary_node
9036
    snode = self.op.remote_node
9037

    
9038
    # create a fake disk info for _GenerateDiskTemplate
9039
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
9040
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9041
                                      instance.name, pnode, [snode],
9042
                                      disk_info, None, None, 0)
9043
    info = _GetInstanceInfoText(instance)
9044
    feedback_fn("Creating aditional volumes...")
9045
    # first, create the missing data and meta devices
9046
    for disk in new_disks:
9047
      # unfortunately this is... not too nice
9048
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9049
                            info, True)
9050
      for child in disk.children:
9051
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9052
    # at this stage, all new LVs have been created, we can rename the
9053
    # old ones
9054
    feedback_fn("Renaming original volumes...")
9055
    rename_list = [(o, n.children[0].logical_id)
9056
                   for (o, n) in zip(instance.disks, new_disks)]
9057
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9058
    result.Raise("Failed to rename original LVs")
9059

    
9060
    feedback_fn("Initializing DRBD devices...")
9061
    # all child devices are in place, we can now create the DRBD devices
9062
    for disk in new_disks:
9063
      for node in [pnode, snode]:
9064
        f_create = node == pnode
9065
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9066

    
9067
    # at this point, the instance has been modified
9068
    instance.disk_template = constants.DT_DRBD8
9069
    instance.disks = new_disks
9070
    self.cfg.Update(instance, feedback_fn)
9071

    
9072
    # disks are created, waiting for sync
9073
    disk_abort = not _WaitForSync(self, instance)
9074
    if disk_abort:
9075
      raise errors.OpExecError("There are some degraded disks for"
9076
                               " this instance, please cleanup manually")
9077

    
9078
  def _ConvertDrbdToPlain(self, feedback_fn):
9079
    """Converts an instance from drbd to plain.
9080

9081
    """
9082
    instance = self.instance
9083
    assert len(instance.secondary_nodes) == 1
9084
    pnode = instance.primary_node
9085
    snode = instance.secondary_nodes[0]
9086
    feedback_fn("Converting template to plain")
9087

    
9088
    old_disks = instance.disks
9089
    new_disks = [d.children[0] for d in old_disks]
9090

    
9091
    # copy over size and mode
9092
    for parent, child in zip(old_disks, new_disks):
9093
      child.size = parent.size
9094
      child.mode = parent.mode
9095

    
9096
    # update instance structure
9097
    instance.disks = new_disks
9098
    instance.disk_template = constants.DT_PLAIN
9099
    self.cfg.Update(instance, feedback_fn)
9100

    
9101
    feedback_fn("Removing volumes on the secondary node...")
9102
    for disk in old_disks:
9103
      self.cfg.SetDiskID(disk, snode)
9104
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9105
      if msg:
9106
        self.LogWarning("Could not remove block device %s on node %s,"
9107
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9108

    
9109
    feedback_fn("Removing unneeded volumes on the primary node...")
9110
    for idx, disk in enumerate(old_disks):
9111
      meta = disk.children[1]
9112
      self.cfg.SetDiskID(meta, pnode)
9113
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9114
      if msg:
9115
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9116
                        " continuing anyway: %s", idx, pnode, msg)
9117

    
9118

    
9119
  def Exec(self, feedback_fn):
9120
    """Modifies an instance.
9121

9122
    All parameters take effect only at the next restart of the instance.
9123

9124
    """
9125
    # Process here the warnings from CheckPrereq, as we don't have a
9126
    # feedback_fn there.
9127
    for warn in self.warn:
9128
      feedback_fn("WARNING: %s" % warn)
9129

    
9130
    result = []
9131
    instance = self.instance
9132
    # disk changes
9133
    for disk_op, disk_dict in self.op.disks:
9134
      if disk_op == constants.DDM_REMOVE:
9135
        # remove the last disk
9136
        device = instance.disks.pop()
9137
        device_idx = len(instance.disks)
9138
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9139
          self.cfg.SetDiskID(disk, node)
9140
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9141
          if msg:
9142
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9143
                            " continuing anyway", device_idx, node, msg)
9144
        result.append(("disk/%d" % device_idx, "remove"))
9145
      elif disk_op == constants.DDM_ADD:
9146
        # add a new disk
9147
        if instance.disk_template == constants.DT_FILE:
9148
          file_driver, file_path = instance.disks[0].logical_id
9149
          file_path = os.path.dirname(file_path)
9150
        else:
9151
          file_driver = file_path = None
9152
        disk_idx_base = len(instance.disks)
9153
        new_disk = _GenerateDiskTemplate(self,
9154
                                         instance.disk_template,
9155
                                         instance.name, instance.primary_node,
9156
                                         instance.secondary_nodes,
9157
                                         [disk_dict],
9158
                                         file_path,
9159
                                         file_driver,
9160
                                         disk_idx_base)[0]
9161
        instance.disks.append(new_disk)
9162
        info = _GetInstanceInfoText(instance)
9163

    
9164
        logging.info("Creating volume %s for instance %s",
9165
                     new_disk.iv_name, instance.name)
9166
        # Note: this needs to be kept in sync with _CreateDisks
9167
        #HARDCODE
9168
        for node in instance.all_nodes:
9169
          f_create = node == instance.primary_node
9170
          try:
9171
            _CreateBlockDev(self, node, instance, new_disk,
9172
                            f_create, info, f_create)
9173
          except errors.OpExecError, err:
9174
            self.LogWarning("Failed to create volume %s (%s) on"
9175
                            " node %s: %s",
9176
                            new_disk.iv_name, new_disk, node, err)
9177
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9178
                       (new_disk.size, new_disk.mode)))
9179
      else:
9180
        # change a given disk
9181
        instance.disks[disk_op].mode = disk_dict['mode']
9182
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9183

    
9184
    if self.op.disk_template:
9185
      r_shut = _ShutdownInstanceDisks(self, instance)
9186
      if not r_shut:
9187
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
9188
                                 " proceed with disk template conversion")
9189
      mode = (instance.disk_template, self.op.disk_template)
9190
      try:
9191
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9192
      except:
9193
        self.cfg.ReleaseDRBDMinors(instance.name)
9194
        raise
9195
      result.append(("disk_template", self.op.disk_template))
9196

    
9197
    # NIC changes
9198
    for nic_op, nic_dict in self.op.nics:
9199
      if nic_op == constants.DDM_REMOVE:
9200
        # remove the last nic
9201
        del instance.nics[-1]
9202
        result.append(("nic.%d" % len(instance.nics), "remove"))
9203
      elif nic_op == constants.DDM_ADD:
9204
        # mac and bridge should be set, by now
9205
        mac = nic_dict['mac']
9206
        ip = nic_dict.get('ip', None)
9207
        nicparams = self.nic_pinst[constants.DDM_ADD]
9208
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9209
        instance.nics.append(new_nic)
9210
        result.append(("nic.%d" % (len(instance.nics) - 1),
9211
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9212
                       (new_nic.mac, new_nic.ip,
9213
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9214
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9215
                       )))
9216
      else:
9217
        for key in 'mac', 'ip':
9218
          if key in nic_dict:
9219
            setattr(instance.nics[nic_op], key, nic_dict[key])
9220
        if nic_op in self.nic_pinst:
9221
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9222
        for key, val in nic_dict.iteritems():
9223
          result.append(("nic.%s/%d" % (key, nic_op), val))
9224

    
9225
    # hvparams changes
9226
    if self.op.hvparams:
9227
      instance.hvparams = self.hv_inst
9228
      for key, val in self.op.hvparams.iteritems():
9229
        result.append(("hv/%s" % key, val))
9230

    
9231
    # beparams changes
9232
    if self.op.beparams:
9233
      instance.beparams = self.be_inst
9234
      for key, val in self.op.beparams.iteritems():
9235
        result.append(("be/%s" % key, val))
9236

    
9237
    # OS change
9238
    if self.op.os_name:
9239
      instance.os = self.op.os_name
9240

    
9241
    # osparams changes
9242
    if self.op.osparams:
9243
      instance.osparams = self.os_inst
9244
      for key, val in self.op.osparams.iteritems():
9245
        result.append(("os/%s" % key, val))
9246

    
9247
    self.cfg.Update(instance, feedback_fn)
9248

    
9249
    return result
9250

    
9251
  _DISK_CONVERSIONS = {
9252
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9253
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9254
    }
9255

    
9256

    
9257
class LUQueryExports(NoHooksLU):
9258
  """Query the exports list
9259

9260
  """
9261
  _OP_PARAMS = [
9262
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
9263
    ("use_locking", False, _TBool),
9264
    ]
9265
  REQ_BGL = False
9266

    
9267
  def ExpandNames(self):
9268
    self.needed_locks = {}
9269
    self.share_locks[locking.LEVEL_NODE] = 1
9270
    if not self.op.nodes:
9271
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9272
    else:
9273
      self.needed_locks[locking.LEVEL_NODE] = \
9274
        _GetWantedNodes(self, self.op.nodes)
9275

    
9276
  def Exec(self, feedback_fn):
9277
    """Compute the list of all the exported system images.
9278

9279
    @rtype: dict
9280
    @return: a dictionary with the structure node->(export-list)
9281
        where export-list is a list of the instances exported on
9282
        that node.
9283

9284
    """
9285
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9286
    rpcresult = self.rpc.call_export_list(self.nodes)
9287
    result = {}
9288
    for node in rpcresult:
9289
      if rpcresult[node].fail_msg:
9290
        result[node] = False
9291
      else:
9292
        result[node] = rpcresult[node].payload
9293

    
9294
    return result
9295

    
9296

    
9297
class LUPrepareExport(NoHooksLU):
9298
  """Prepares an instance for an export and returns useful information.
9299

9300
  """
9301
  _OP_PARAMS = [
9302
    _PInstanceName,
9303
    ("mode", _NoDefault, _TElemOf(constants.EXPORT_MODES)),
9304
    ]
9305
  REQ_BGL = False
9306

    
9307
  def ExpandNames(self):
9308
    self._ExpandAndLockInstance()
9309

    
9310
  def CheckPrereq(self):
9311
    """Check prerequisites.
9312

9313
    """
9314
    instance_name = self.op.instance_name
9315

    
9316
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9317
    assert self.instance is not None, \
9318
          "Cannot retrieve locked instance %s" % self.op.instance_name
9319
    _CheckNodeOnline(self, self.instance.primary_node)
9320

    
9321
    self._cds = _GetClusterDomainSecret()
9322

    
9323
  def Exec(self, feedback_fn):
9324
    """Prepares an instance for an export.
9325

9326
    """
9327
    instance = self.instance
9328

    
9329
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9330
      salt = utils.GenerateSecret(8)
9331

    
9332
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9333
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9334
                                              constants.RIE_CERT_VALIDITY)
9335
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9336

    
9337
      (name, cert_pem) = result.payload
9338

    
9339
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9340
                                             cert_pem)
9341

    
9342
      return {
9343
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9344
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9345
                          salt),
9346
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9347
        }
9348

    
9349
    return None
9350

    
9351

    
9352
class LUExportInstance(LogicalUnit):
9353
  """Export an instance to an image in the cluster.
9354

9355
  """
9356
  HPATH = "instance-export"
9357
  HTYPE = constants.HTYPE_INSTANCE
9358
  _OP_PARAMS = [
9359
    _PInstanceName,
9360
    ("target_node", _NoDefault, _TOr(_TNonEmptyString, _TList)),
9361
    ("shutdown", True, _TBool),
9362
    _PShutdownTimeout,
9363
    ("remove_instance", False, _TBool),
9364
    ("ignore_remove_failures", False, _TBool),
9365
    ("mode", constants.EXPORT_MODE_LOCAL, _TElemOf(constants.EXPORT_MODES)),
9366
    ("x509_key_name", None, _TOr(_TList, _TNone)),
9367
    ("destination_x509_ca", None, _TMaybeString),
9368
    ]
9369
  REQ_BGL = False
9370

    
9371
  def CheckArguments(self):
9372
    """Check the arguments.
9373

9374
    """
9375
    self.x509_key_name = self.op.x509_key_name
9376
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9377

    
9378
    if self.op.remove_instance and not self.op.shutdown:
9379
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9380
                                 " down before")
9381

    
9382
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9383
      if not self.x509_key_name:
9384
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9385
                                   errors.ECODE_INVAL)
9386

    
9387
      if not self.dest_x509_ca_pem:
9388
        raise errors.OpPrereqError("Missing destination X509 CA",
9389
                                   errors.ECODE_INVAL)
9390

    
9391
  def ExpandNames(self):
9392
    self._ExpandAndLockInstance()
9393

    
9394
    # Lock all nodes for local exports
9395
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9396
      # FIXME: lock only instance primary and destination node
9397
      #
9398
      # Sad but true, for now we have do lock all nodes, as we don't know where
9399
      # the previous export might be, and in this LU we search for it and
9400
      # remove it from its current node. In the future we could fix this by:
9401
      #  - making a tasklet to search (share-lock all), then create the
9402
      #    new one, then one to remove, after
9403
      #  - removing the removal operation altogether
9404
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9405

    
9406
  def DeclareLocks(self, level):
9407
    """Last minute lock declaration."""
9408
    # All nodes are locked anyway, so nothing to do here.
9409

    
9410
  def BuildHooksEnv(self):
9411
    """Build hooks env.
9412

9413
    This will run on the master, primary node and target node.
9414

9415
    """
9416
    env = {
9417
      "EXPORT_MODE": self.op.mode,
9418
      "EXPORT_NODE": self.op.target_node,
9419
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9420
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9421
      # TODO: Generic function for boolean env variables
9422
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9423
      }
9424

    
9425
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9426

    
9427
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9428

    
9429
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9430
      nl.append(self.op.target_node)
9431

    
9432
    return env, nl, nl
9433

    
9434
  def CheckPrereq(self):
9435
    """Check prerequisites.
9436

9437
    This checks that the instance and node names are valid.
9438

9439
    """
9440
    instance_name = self.op.instance_name
9441

    
9442
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9443
    assert self.instance is not None, \
9444
          "Cannot retrieve locked instance %s" % self.op.instance_name
9445
    _CheckNodeOnline(self, self.instance.primary_node)
9446

    
9447
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9448
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9449
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9450
      assert self.dst_node is not None
9451

    
9452
      _CheckNodeOnline(self, self.dst_node.name)
9453
      _CheckNodeNotDrained(self, self.dst_node.name)
9454

    
9455
      self._cds = None
9456
      self.dest_disk_info = None
9457
      self.dest_x509_ca = None
9458

    
9459
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9460
      self.dst_node = None
9461

    
9462
      if len(self.op.target_node) != len(self.instance.disks):
9463
        raise errors.OpPrereqError(("Received destination information for %s"
9464
                                    " disks, but instance %s has %s disks") %
9465
                                   (len(self.op.target_node), instance_name,
9466
                                    len(self.instance.disks)),
9467
                                   errors.ECODE_INVAL)
9468

    
9469
      cds = _GetClusterDomainSecret()
9470

    
9471
      # Check X509 key name
9472
      try:
9473
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9474
      except (TypeError, ValueError), err:
9475
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9476

    
9477
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9478
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9479
                                   errors.ECODE_INVAL)
9480

    
9481
      # Load and verify CA
9482
      try:
9483
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9484
      except OpenSSL.crypto.Error, err:
9485
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9486
                                   (err, ), errors.ECODE_INVAL)
9487

    
9488
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9489
      if errcode is not None:
9490
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9491
                                   (msg, ), errors.ECODE_INVAL)
9492

    
9493
      self.dest_x509_ca = cert
9494

    
9495
      # Verify target information
9496
      disk_info = []
9497
      for idx, disk_data in enumerate(self.op.target_node):
9498
        try:
9499
          (host, port, magic) = \
9500
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9501
        except errors.GenericError, err:
9502
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9503
                                     (idx, err), errors.ECODE_INVAL)
9504

    
9505
        disk_info.append((host, port, magic))
9506

    
9507
      assert len(disk_info) == len(self.op.target_node)
9508
      self.dest_disk_info = disk_info
9509

    
9510
    else:
9511
      raise errors.ProgrammerError("Unhandled export mode %r" %
9512
                                   self.op.mode)
9513

    
9514
    # instance disk type verification
9515
    # TODO: Implement export support for file-based disks
9516
    for disk in self.instance.disks:
9517
      if disk.dev_type == constants.LD_FILE:
9518
        raise errors.OpPrereqError("Export not supported for instances with"
9519
                                   " file-based disks", errors.ECODE_INVAL)
9520

    
9521
  def _CleanupExports(self, feedback_fn):
9522
    """Removes exports of current instance from all other nodes.
9523

9524
    If an instance in a cluster with nodes A..D was exported to node C, its
9525
    exports will be removed from the nodes A, B and D.
9526

9527
    """
9528
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9529

    
9530
    nodelist = self.cfg.GetNodeList()
9531
    nodelist.remove(self.dst_node.name)
9532

    
9533
    # on one-node clusters nodelist will be empty after the removal
9534
    # if we proceed the backup would be removed because OpQueryExports
9535
    # substitutes an empty list with the full cluster node list.
9536
    iname = self.instance.name
9537
    if nodelist:
9538
      feedback_fn("Removing old exports for instance %s" % iname)
9539
      exportlist = self.rpc.call_export_list(nodelist)
9540
      for node in exportlist:
9541
        if exportlist[node].fail_msg:
9542
          continue
9543
        if iname in exportlist[node].payload:
9544
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9545
          if msg:
9546
            self.LogWarning("Could not remove older export for instance %s"
9547
                            " on node %s: %s", iname, node, msg)
9548

    
9549
  def Exec(self, feedback_fn):
9550
    """Export an instance to an image in the cluster.
9551

9552
    """
9553
    assert self.op.mode in constants.EXPORT_MODES
9554

    
9555
    instance = self.instance
9556
    src_node = instance.primary_node
9557

    
9558
    if self.op.shutdown:
9559
      # shutdown the instance, but not the disks
9560
      feedback_fn("Shutting down instance %s" % instance.name)
9561
      result = self.rpc.call_instance_shutdown(src_node, instance,
9562
                                               self.op.shutdown_timeout)
9563
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9564
      result.Raise("Could not shutdown instance %s on"
9565
                   " node %s" % (instance.name, src_node))
9566

    
9567
    # set the disks ID correctly since call_instance_start needs the
9568
    # correct drbd minor to create the symlinks
9569
    for disk in instance.disks:
9570
      self.cfg.SetDiskID(disk, src_node)
9571

    
9572
    activate_disks = (not instance.admin_up)
9573

    
9574
    if activate_disks:
9575
      # Activate the instance disks if we'exporting a stopped instance
9576
      feedback_fn("Activating disks for %s" % instance.name)
9577
      _StartInstanceDisks(self, instance, None)
9578

    
9579
    try:
9580
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9581
                                                     instance)
9582

    
9583
      helper.CreateSnapshots()
9584
      try:
9585
        if (self.op.shutdown and instance.admin_up and
9586
            not self.op.remove_instance):
9587
          assert not activate_disks
9588
          feedback_fn("Starting instance %s" % instance.name)
9589
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9590
          msg = result.fail_msg
9591
          if msg:
9592
            feedback_fn("Failed to start instance: %s" % msg)
9593
            _ShutdownInstanceDisks(self, instance)
9594
            raise errors.OpExecError("Could not start instance: %s" % msg)
9595

    
9596
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9597
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9598
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9599
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9600
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9601

    
9602
          (key_name, _, _) = self.x509_key_name
9603

    
9604
          dest_ca_pem = \
9605
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9606
                                            self.dest_x509_ca)
9607

    
9608
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9609
                                                     key_name, dest_ca_pem,
9610
                                                     timeouts)
9611
      finally:
9612
        helper.Cleanup()
9613

    
9614
      # Check for backwards compatibility
9615
      assert len(dresults) == len(instance.disks)
9616
      assert compat.all(isinstance(i, bool) for i in dresults), \
9617
             "Not all results are boolean: %r" % dresults
9618

    
9619
    finally:
9620
      if activate_disks:
9621
        feedback_fn("Deactivating disks for %s" % instance.name)
9622
        _ShutdownInstanceDisks(self, instance)
9623

    
9624
    if not (compat.all(dresults) and fin_resu):
9625
      failures = []
9626
      if not fin_resu:
9627
        failures.append("export finalization")
9628
      if not compat.all(dresults):
9629
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
9630
                               if not dsk)
9631
        failures.append("disk export: disk(s) %s" % fdsk)
9632

    
9633
      raise errors.OpExecError("Export failed, errors in %s" %
9634
                               utils.CommaJoin(failures))
9635

    
9636
    # At this point, the export was successful, we can cleanup/finish
9637

    
9638
    # Remove instance if requested
9639
    if self.op.remove_instance:
9640
      feedback_fn("Removing instance %s" % instance.name)
9641
      _RemoveInstance(self, feedback_fn, instance,
9642
                      self.op.ignore_remove_failures)
9643

    
9644
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9645
      self._CleanupExports(feedback_fn)
9646

    
9647
    return fin_resu, dresults
9648

    
9649

    
9650
class LURemoveExport(NoHooksLU):
9651
  """Remove exports related to the named instance.
9652

9653
  """
9654
  _OP_PARAMS = [
9655
    _PInstanceName,
9656
    ]
9657
  REQ_BGL = False
9658

    
9659
  def ExpandNames(self):
9660
    self.needed_locks = {}
9661
    # We need all nodes to be locked in order for RemoveExport to work, but we
9662
    # don't need to lock the instance itself, as nothing will happen to it (and
9663
    # we can remove exports also for a removed instance)
9664
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9665

    
9666
  def Exec(self, feedback_fn):
9667
    """Remove any export.
9668

9669
    """
9670
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9671
    # If the instance was not found we'll try with the name that was passed in.
9672
    # This will only work if it was an FQDN, though.
9673
    fqdn_warn = False
9674
    if not instance_name:
9675
      fqdn_warn = True
9676
      instance_name = self.op.instance_name
9677

    
9678
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
9679
    exportlist = self.rpc.call_export_list(locked_nodes)
9680
    found = False
9681
    for node in exportlist:
9682
      msg = exportlist[node].fail_msg
9683
      if msg:
9684
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
9685
        continue
9686
      if instance_name in exportlist[node].payload:
9687
        found = True
9688
        result = self.rpc.call_export_remove(node, instance_name)
9689
        msg = result.fail_msg
9690
        if msg:
9691
          logging.error("Could not remove export for instance %s"
9692
                        " on node %s: %s", instance_name, node, msg)
9693

    
9694
    if fqdn_warn and not found:
9695
      feedback_fn("Export not found. If trying to remove an export belonging"
9696
                  " to a deleted instance please use its Fully Qualified"
9697
                  " Domain Name.")
9698

    
9699

    
9700
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
9701
  """Generic tags LU.
9702

9703
  This is an abstract class which is the parent of all the other tags LUs.
9704

9705
  """
9706

    
9707
  def ExpandNames(self):
9708
    self.needed_locks = {}
9709
    if self.op.kind == constants.TAG_NODE:
9710
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
9711
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
9712
    elif self.op.kind == constants.TAG_INSTANCE:
9713
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
9714
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
9715

    
9716
  def CheckPrereq(self):
9717
    """Check prerequisites.
9718

9719
    """
9720
    if self.op.kind == constants.TAG_CLUSTER:
9721
      self.target = self.cfg.GetClusterInfo()
9722
    elif self.op.kind == constants.TAG_NODE:
9723
      self.target = self.cfg.GetNodeInfo(self.op.name)
9724
    elif self.op.kind == constants.TAG_INSTANCE:
9725
      self.target = self.cfg.GetInstanceInfo(self.op.name)
9726
    else:
9727
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
9728
                                 str(self.op.kind), errors.ECODE_INVAL)
9729

    
9730

    
9731
class LUGetTags(TagsLU):
9732
  """Returns the tags of a given object.
9733

9734
  """
9735
  _OP_PARAMS = [
9736
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9737
    ("name", _NoDefault, _TNonEmptyString),
9738
    ]
9739
  REQ_BGL = False
9740

    
9741
  def Exec(self, feedback_fn):
9742
    """Returns the tag list.
9743

9744
    """
9745
    return list(self.target.GetTags())
9746

    
9747

    
9748
class LUSearchTags(NoHooksLU):
9749
  """Searches the tags for a given pattern.
9750

9751
  """
9752
  _OP_PARAMS = [
9753
    ("pattern", _NoDefault, _TNonEmptyString),
9754
    ]
9755
  REQ_BGL = False
9756

    
9757
  def ExpandNames(self):
9758
    self.needed_locks = {}
9759

    
9760
  def CheckPrereq(self):
9761
    """Check prerequisites.
9762

9763
    This checks the pattern passed for validity by compiling it.
9764

9765
    """
9766
    try:
9767
      self.re = re.compile(self.op.pattern)
9768
    except re.error, err:
9769
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
9770
                                 (self.op.pattern, err), errors.ECODE_INVAL)
9771

    
9772
  def Exec(self, feedback_fn):
9773
    """Returns the tag list.
9774

9775
    """
9776
    cfg = self.cfg
9777
    tgts = [("/cluster", cfg.GetClusterInfo())]
9778
    ilist = cfg.GetAllInstancesInfo().values()
9779
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
9780
    nlist = cfg.GetAllNodesInfo().values()
9781
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
9782
    results = []
9783
    for path, target in tgts:
9784
      for tag in target.GetTags():
9785
        if self.re.search(tag):
9786
          results.append((path, tag))
9787
    return results
9788

    
9789

    
9790
class LUAddTags(TagsLU):
9791
  """Sets a tag on a given object.
9792

9793
  """
9794
  _OP_PARAMS = [
9795
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9796
    ("name", _NoDefault, _TNonEmptyString),
9797
    ("tags", _NoDefault, _TListOf(_TNonEmptyString)),
9798
    ]
9799
  REQ_BGL = False
9800

    
9801
  def CheckPrereq(self):
9802
    """Check prerequisites.
9803

9804
    This checks the type and length of the tag name and value.
9805

9806
    """
9807
    TagsLU.CheckPrereq(self)
9808
    for tag in self.op.tags:
9809
      objects.TaggableObject.ValidateTag(tag)
9810

    
9811
  def Exec(self, feedback_fn):
9812
    """Sets the tag.
9813

9814
    """
9815
    try:
9816
      for tag in self.op.tags:
9817
        self.target.AddTag(tag)
9818
    except errors.TagError, err:
9819
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
9820
    self.cfg.Update(self.target, feedback_fn)
9821

    
9822

    
9823
class LUDelTags(TagsLU):
9824
  """Delete a list of tags from a given object.
9825

9826
  """
9827
  _OP_PARAMS = [
9828
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9829
    ("name", _NoDefault, _TNonEmptyString),
9830
    ("tags", _NoDefault, _TListOf(_TNonEmptyString)),
9831
    ]
9832
  REQ_BGL = False
9833

    
9834
  def CheckPrereq(self):
9835
    """Check prerequisites.
9836

9837
    This checks that we have the given tag.
9838

9839
    """
9840
    TagsLU.CheckPrereq(self)
9841
    for tag in self.op.tags:
9842
      objects.TaggableObject.ValidateTag(tag)
9843
    del_tags = frozenset(self.op.tags)
9844
    cur_tags = self.target.GetTags()
9845
    if not del_tags <= cur_tags:
9846
      diff_tags = del_tags - cur_tags
9847
      diff_names = ["'%s'" % tag for tag in diff_tags]
9848
      diff_names.sort()
9849
      raise errors.OpPrereqError("Tag(s) %s not found" %
9850
                                 (",".join(diff_names)), errors.ECODE_NOENT)
9851

    
9852
  def Exec(self, feedback_fn):
9853
    """Remove the tag from the object.
9854

9855
    """
9856
    for tag in self.op.tags:
9857
      self.target.RemoveTag(tag)
9858
    self.cfg.Update(self.target, feedback_fn)
9859

    
9860

    
9861
class LUTestDelay(NoHooksLU):
9862
  """Sleep for a specified amount of time.
9863

9864
  This LU sleeps on the master and/or nodes for a specified amount of
9865
  time.
9866

9867
  """
9868
  _OP_PARAMS = [
9869
    ("duration", _NoDefault, _TFloat),
9870
    ("on_master", True, _TBool),
9871
    ("on_nodes", _EmptyList, _TListOf(_TNonEmptyString)),
9872
    ("repeat", 0, _TPositiveInt)
9873
    ]
9874
  REQ_BGL = False
9875

    
9876
  def ExpandNames(self):
9877
    """Expand names and set required locks.
9878

9879
    This expands the node list, if any.
9880

9881
    """
9882
    self.needed_locks = {}
9883
    if self.op.on_nodes:
9884
      # _GetWantedNodes can be used here, but is not always appropriate to use
9885
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
9886
      # more information.
9887
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
9888
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
9889

    
9890
  def _TestDelay(self):
9891
    """Do the actual sleep.
9892

9893
    """
9894
    if self.op.on_master:
9895
      if not utils.TestDelay(self.op.duration):
9896
        raise errors.OpExecError("Error during master delay test")
9897
    if self.op.on_nodes:
9898
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
9899
      for node, node_result in result.items():
9900
        node_result.Raise("Failure during rpc call to node %s" % node)
9901

    
9902
  def Exec(self, feedback_fn):
9903
    """Execute the test delay opcode, with the wanted repetitions.
9904

9905
    """
9906
    if self.op.repeat == 0:
9907
      self._TestDelay()
9908
    else:
9909
      top_value = self.op.repeat - 1
9910
      for i in range(self.op.repeat):
9911
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
9912
        self._TestDelay()
9913

    
9914

    
9915
class LUTestJobqueue(NoHooksLU):
9916
  """Utility LU to test some aspects of the job queue.
9917

9918
  """
9919
  _OP_PARAMS = [
9920
    ("notify_waitlock", False, _TBool),
9921
    ("notify_exec", False, _TBool),
9922
    ("log_messages", _EmptyList, _TListOf(_TString)),
9923
    ("fail", False, _TBool),
9924
    ]
9925
  REQ_BGL = False
9926

    
9927
  # Must be lower than default timeout for WaitForJobChange to see whether it
9928
  # notices changed jobs
9929
  _CLIENT_CONNECT_TIMEOUT = 20.0
9930
  _CLIENT_CONFIRM_TIMEOUT = 60.0
9931

    
9932
  @classmethod
9933
  def _NotifyUsingSocket(cls, cb, errcls):
9934
    """Opens a Unix socket and waits for another program to connect.
9935

9936
    @type cb: callable
9937
    @param cb: Callback to send socket name to client
9938
    @type errcls: class
9939
    @param errcls: Exception class to use for errors
9940

9941
    """
9942
    # Using a temporary directory as there's no easy way to create temporary
9943
    # sockets without writing a custom loop around tempfile.mktemp and
9944
    # socket.bind
9945
    tmpdir = tempfile.mkdtemp()
9946
    try:
9947
      tmpsock = utils.PathJoin(tmpdir, "sock")
9948

    
9949
      logging.debug("Creating temporary socket at %s", tmpsock)
9950
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
9951
      try:
9952
        sock.bind(tmpsock)
9953
        sock.listen(1)
9954

    
9955
        # Send details to client
9956
        cb(tmpsock)
9957

    
9958
        # Wait for client to connect before continuing
9959
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
9960
        try:
9961
          (conn, _) = sock.accept()
9962
        except socket.error, err:
9963
          raise errcls("Client didn't connect in time (%s)" % err)
9964
      finally:
9965
        sock.close()
9966
    finally:
9967
      # Remove as soon as client is connected
9968
      shutil.rmtree(tmpdir)
9969

    
9970
    # Wait for client to close
9971
    try:
9972
      try:
9973
        # pylint: disable-msg=E1101
9974
        # Instance of '_socketobject' has no ... member
9975
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
9976
        conn.recv(1)
9977
      except socket.error, err:
9978
        raise errcls("Client failed to confirm notification (%s)" % err)
9979
    finally:
9980
      conn.close()
9981

    
9982
  def _SendNotification(self, test, arg, sockname):
9983
    """Sends a notification to the client.
9984

9985
    @type test: string
9986
    @param test: Test name
9987
    @param arg: Test argument (depends on test)
9988
    @type sockname: string
9989
    @param sockname: Socket path
9990

9991
    """
9992
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
9993

    
9994
  def _Notify(self, prereq, test, arg):
9995
    """Notifies the client of a test.
9996

9997
    @type prereq: bool
9998
    @param prereq: Whether this is a prereq-phase test
9999
    @type test: string
10000
    @param test: Test name
10001
    @param arg: Test argument (depends on test)
10002

10003
    """
10004
    if prereq:
10005
      errcls = errors.OpPrereqError
10006
    else:
10007
      errcls = errors.OpExecError
10008

    
10009
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
10010
                                                  test, arg),
10011
                                   errcls)
10012

    
10013
  def CheckArguments(self):
10014
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
10015
    self.expandnames_calls = 0
10016

    
10017
  def ExpandNames(self):
10018
    checkargs_calls = getattr(self, "checkargs_calls", 0)
10019
    if checkargs_calls < 1:
10020
      raise errors.ProgrammerError("CheckArguments was not called")
10021

    
10022
    self.expandnames_calls += 1
10023

    
10024
    if self.op.notify_waitlock:
10025
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
10026

    
10027
    self.LogInfo("Expanding names")
10028

    
10029
    # Get lock on master node (just to get a lock, not for a particular reason)
10030
    self.needed_locks = {
10031
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
10032
      }
10033

    
10034
  def Exec(self, feedback_fn):
10035
    if self.expandnames_calls < 1:
10036
      raise errors.ProgrammerError("ExpandNames was not called")
10037

    
10038
    if self.op.notify_exec:
10039
      self._Notify(False, constants.JQT_EXEC, None)
10040

    
10041
    self.LogInfo("Executing")
10042

    
10043
    if self.op.log_messages:
10044
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
10045
      for idx, msg in enumerate(self.op.log_messages):
10046
        self.LogInfo("Sending log message %s", idx + 1)
10047
        feedback_fn(constants.JQT_MSGPREFIX + msg)
10048
        # Report how many test messages have been sent
10049
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
10050

    
10051
    if self.op.fail:
10052
      raise errors.OpExecError("Opcode failure was requested")
10053

    
10054
    return True
10055

    
10056

    
10057
class IAllocator(object):
10058
  """IAllocator framework.
10059

10060
  An IAllocator instance has three sets of attributes:
10061
    - cfg that is needed to query the cluster
10062
    - input data (all members of the _KEYS class attribute are required)
10063
    - four buffer attributes (in|out_data|text), that represent the
10064
      input (to the external script) in text and data structure format,
10065
      and the output from it, again in two formats
10066
    - the result variables from the script (success, info, nodes) for
10067
      easy usage
10068

10069
  """
10070
  # pylint: disable-msg=R0902
10071
  # lots of instance attributes
10072
  _ALLO_KEYS = [
10073
    "name", "mem_size", "disks", "disk_template",
10074
    "os", "tags", "nics", "vcpus", "hypervisor",
10075
    ]
10076
  _RELO_KEYS = [
10077
    "name", "relocate_from",
10078
    ]
10079
  _EVAC_KEYS = [
10080
    "evac_nodes",
10081
    ]
10082

    
10083
  def __init__(self, cfg, rpc, mode, **kwargs):
10084
    self.cfg = cfg
10085
    self.rpc = rpc
10086
    # init buffer variables
10087
    self.in_text = self.out_text = self.in_data = self.out_data = None
10088
    # init all input fields so that pylint is happy
10089
    self.mode = mode
10090
    self.mem_size = self.disks = self.disk_template = None
10091
    self.os = self.tags = self.nics = self.vcpus = None
10092
    self.hypervisor = None
10093
    self.relocate_from = None
10094
    self.name = None
10095
    self.evac_nodes = None
10096
    # computed fields
10097
    self.required_nodes = None
10098
    # init result fields
10099
    self.success = self.info = self.result = None
10100
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10101
      keyset = self._ALLO_KEYS
10102
      fn = self._AddNewInstance
10103
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10104
      keyset = self._RELO_KEYS
10105
      fn = self._AddRelocateInstance
10106
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10107
      keyset = self._EVAC_KEYS
10108
      fn = self._AddEvacuateNodes
10109
    else:
10110
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
10111
                                   " IAllocator" % self.mode)
10112
    for key in kwargs:
10113
      if key not in keyset:
10114
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
10115
                                     " IAllocator" % key)
10116
      setattr(self, key, kwargs[key])
10117

    
10118
    for key in keyset:
10119
      if key not in kwargs:
10120
        raise errors.ProgrammerError("Missing input parameter '%s' to"
10121
                                     " IAllocator" % key)
10122
    self._BuildInputData(fn)
10123

    
10124
  def _ComputeClusterData(self):
10125
    """Compute the generic allocator input data.
10126

10127
    This is the data that is independent of the actual operation.
10128

10129
    """
10130
    cfg = self.cfg
10131
    cluster_info = cfg.GetClusterInfo()
10132
    # cluster data
10133
    data = {
10134
      "version": constants.IALLOCATOR_VERSION,
10135
      "cluster_name": cfg.GetClusterName(),
10136
      "cluster_tags": list(cluster_info.GetTags()),
10137
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
10138
      # we don't have job IDs
10139
      }
10140
    iinfo = cfg.GetAllInstancesInfo().values()
10141
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
10142

    
10143
    # node data
10144
    node_results = {}
10145
    node_list = cfg.GetNodeList()
10146

    
10147
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10148
      hypervisor_name = self.hypervisor
10149
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10150
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
10151
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10152
      hypervisor_name = cluster_info.enabled_hypervisors[0]
10153

    
10154
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
10155
                                        hypervisor_name)
10156
    node_iinfo = \
10157
      self.rpc.call_all_instances_info(node_list,
10158
                                       cluster_info.enabled_hypervisors)
10159
    for nname, nresult in node_data.items():
10160
      # first fill in static (config-based) values
10161
      ninfo = cfg.GetNodeInfo(nname)
10162
      pnr = {
10163
        "tags": list(ninfo.GetTags()),
10164
        "primary_ip": ninfo.primary_ip,
10165
        "secondary_ip": ninfo.secondary_ip,
10166
        "offline": ninfo.offline,
10167
        "drained": ninfo.drained,
10168
        "master_candidate": ninfo.master_candidate,
10169
        }
10170

    
10171
      if not (ninfo.offline or ninfo.drained):
10172
        nresult.Raise("Can't get data for node %s" % nname)
10173
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
10174
                                nname)
10175
        remote_info = nresult.payload
10176

    
10177
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
10178
                     'vg_size', 'vg_free', 'cpu_total']:
10179
          if attr not in remote_info:
10180
            raise errors.OpExecError("Node '%s' didn't return attribute"
10181
                                     " '%s'" % (nname, attr))
10182
          if not isinstance(remote_info[attr], int):
10183
            raise errors.OpExecError("Node '%s' returned invalid value"
10184
                                     " for '%s': %s" %
10185
                                     (nname, attr, remote_info[attr]))
10186
        # compute memory used by primary instances
10187
        i_p_mem = i_p_up_mem = 0
10188
        for iinfo, beinfo in i_list:
10189
          if iinfo.primary_node == nname:
10190
            i_p_mem += beinfo[constants.BE_MEMORY]
10191
            if iinfo.name not in node_iinfo[nname].payload:
10192
              i_used_mem = 0
10193
            else:
10194
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
10195
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
10196
            remote_info['memory_free'] -= max(0, i_mem_diff)
10197

    
10198
            if iinfo.admin_up:
10199
              i_p_up_mem += beinfo[constants.BE_MEMORY]
10200

    
10201
        # compute memory used by instances
10202
        pnr_dyn = {
10203
          "total_memory": remote_info['memory_total'],
10204
          "reserved_memory": remote_info['memory_dom0'],
10205
          "free_memory": remote_info['memory_free'],
10206
          "total_disk": remote_info['vg_size'],
10207
          "free_disk": remote_info['vg_free'],
10208
          "total_cpus": remote_info['cpu_total'],
10209
          "i_pri_memory": i_p_mem,
10210
          "i_pri_up_memory": i_p_up_mem,
10211
          }
10212
        pnr.update(pnr_dyn)
10213

    
10214
      node_results[nname] = pnr
10215
    data["nodes"] = node_results
10216

    
10217
    # instance data
10218
    instance_data = {}
10219
    for iinfo, beinfo in i_list:
10220
      nic_data = []
10221
      for nic in iinfo.nics:
10222
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
10223
        nic_dict = {"mac": nic.mac,
10224
                    "ip": nic.ip,
10225
                    "mode": filled_params[constants.NIC_MODE],
10226
                    "link": filled_params[constants.NIC_LINK],
10227
                   }
10228
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
10229
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
10230
        nic_data.append(nic_dict)
10231
      pir = {
10232
        "tags": list(iinfo.GetTags()),
10233
        "admin_up": iinfo.admin_up,
10234
        "vcpus": beinfo[constants.BE_VCPUS],
10235
        "memory": beinfo[constants.BE_MEMORY],
10236
        "os": iinfo.os,
10237
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
10238
        "nics": nic_data,
10239
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
10240
        "disk_template": iinfo.disk_template,
10241
        "hypervisor": iinfo.hypervisor,
10242
        }
10243
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
10244
                                                 pir["disks"])
10245
      instance_data[iinfo.name] = pir
10246

    
10247
    data["instances"] = instance_data
10248

    
10249
    self.in_data = data
10250

    
10251
  def _AddNewInstance(self):
10252
    """Add new instance data to allocator structure.
10253

10254
    This in combination with _AllocatorGetClusterData will create the
10255
    correct structure needed as input for the allocator.
10256

10257
    The checks for the completeness of the opcode must have already been
10258
    done.
10259

10260
    """
10261
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
10262

    
10263
    if self.disk_template in constants.DTS_NET_MIRROR:
10264
      self.required_nodes = 2
10265
    else:
10266
      self.required_nodes = 1
10267
    request = {
10268
      "name": self.name,
10269
      "disk_template": self.disk_template,
10270
      "tags": self.tags,
10271
      "os": self.os,
10272
      "vcpus": self.vcpus,
10273
      "memory": self.mem_size,
10274
      "disks": self.disks,
10275
      "disk_space_total": disk_space,
10276
      "nics": self.nics,
10277
      "required_nodes": self.required_nodes,
10278
      }
10279
    return request
10280

    
10281
  def _AddRelocateInstance(self):
10282
    """Add relocate instance data to allocator structure.
10283

10284
    This in combination with _IAllocatorGetClusterData will create the
10285
    correct structure needed as input for the allocator.
10286

10287
    The checks for the completeness of the opcode must have already been
10288
    done.
10289

10290
    """
10291
    instance = self.cfg.GetInstanceInfo(self.name)
10292
    if instance is None:
10293
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
10294
                                   " IAllocator" % self.name)
10295

    
10296
    if instance.disk_template not in constants.DTS_NET_MIRROR:
10297
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
10298
                                 errors.ECODE_INVAL)
10299

    
10300
    if len(instance.secondary_nodes) != 1:
10301
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
10302
                                 errors.ECODE_STATE)
10303

    
10304
    self.required_nodes = 1
10305
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
10306
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
10307

    
10308
    request = {
10309
      "name": self.name,
10310
      "disk_space_total": disk_space,
10311
      "required_nodes": self.required_nodes,
10312
      "relocate_from": self.relocate_from,
10313
      }
10314
    return request
10315

    
10316
  def _AddEvacuateNodes(self):
10317
    """Add evacuate nodes data to allocator structure.
10318

10319
    """
10320
    request = {
10321
      "evac_nodes": self.evac_nodes
10322
      }
10323
    return request
10324

    
10325
  def _BuildInputData(self, fn):
10326
    """Build input data structures.
10327

10328
    """
10329
    self._ComputeClusterData()
10330

    
10331
    request = fn()
10332
    request["type"] = self.mode
10333
    self.in_data["request"] = request
10334

    
10335
    self.in_text = serializer.Dump(self.in_data)
10336

    
10337
  def Run(self, name, validate=True, call_fn=None):
10338
    """Run an instance allocator and return the results.
10339

10340
    """
10341
    if call_fn is None:
10342
      call_fn = self.rpc.call_iallocator_runner
10343

    
10344
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
10345
    result.Raise("Failure while running the iallocator script")
10346

    
10347
    self.out_text = result.payload
10348
    if validate:
10349
      self._ValidateResult()
10350

    
10351
  def _ValidateResult(self):
10352
    """Process the allocator results.
10353

10354
    This will process and if successful save the result in
10355
    self.out_data and the other parameters.
10356

10357
    """
10358
    try:
10359
      rdict = serializer.Load(self.out_text)
10360
    except Exception, err:
10361
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
10362

    
10363
    if not isinstance(rdict, dict):
10364
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
10365

    
10366
    # TODO: remove backwards compatiblity in later versions
10367
    if "nodes" in rdict and "result" not in rdict:
10368
      rdict["result"] = rdict["nodes"]
10369
      del rdict["nodes"]
10370

    
10371
    for key in "success", "info", "result":
10372
      if key not in rdict:
10373
        raise errors.OpExecError("Can't parse iallocator results:"
10374
                                 " missing key '%s'" % key)
10375
      setattr(self, key, rdict[key])
10376

    
10377
    if not isinstance(rdict["result"], list):
10378
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
10379
                               " is not a list")
10380
    self.out_data = rdict
10381

    
10382

    
10383
class LUTestAllocator(NoHooksLU):
10384
  """Run allocator tests.
10385

10386
  This LU runs the allocator tests
10387

10388
  """
10389
  _OP_PARAMS = [
10390
    ("direction", _NoDefault, _TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS)),
10391
    ("mode", _NoDefault, _TElemOf(constants.VALID_IALLOCATOR_MODES)),
10392
    ("name", _NoDefault, _TNonEmptyString),
10393
    ("nics", _NoDefault, _TOr(_TNone, _TListOf(
10394
      _TDictOf(_TElemOf(["mac", "ip", "bridge"]),
10395
               _TOr(_TNone, _TNonEmptyString))))),
10396
    ("disks", _NoDefault, _TOr(_TNone, _TList)),
10397
    ("hypervisor", None, _TMaybeString),
10398
    ("allocator", None, _TMaybeString),
10399
    ("tags", _EmptyList, _TListOf(_TNonEmptyString)),
10400
    ("mem_size", None, _TOr(_TNone, _TPositiveInt)),
10401
    ("vcpus", None, _TOr(_TNone, _TPositiveInt)),
10402
    ("os", None, _TMaybeString),
10403
    ("disk_template", None, _TMaybeString),
10404
    ("evac_nodes", None, _TOr(_TNone, _TListOf(_TNonEmptyString))),
10405
    ]
10406

    
10407
  def CheckPrereq(self):
10408
    """Check prerequisites.
10409

10410
    This checks the opcode parameters depending on the director and mode test.
10411

10412
    """
10413
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10414
      for attr in ["mem_size", "disks", "disk_template",
10415
                   "os", "tags", "nics", "vcpus"]:
10416
        if not hasattr(self.op, attr):
10417
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
10418
                                     attr, errors.ECODE_INVAL)
10419
      iname = self.cfg.ExpandInstanceName(self.op.name)
10420
      if iname is not None:
10421
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
10422
                                   iname, errors.ECODE_EXISTS)
10423
      if not isinstance(self.op.nics, list):
10424
        raise errors.OpPrereqError("Invalid parameter 'nics'",
10425
                                   errors.ECODE_INVAL)
10426
      if not isinstance(self.op.disks, list):
10427
        raise errors.OpPrereqError("Invalid parameter 'disks'",
10428
                                   errors.ECODE_INVAL)
10429
      for row in self.op.disks:
10430
        if (not isinstance(row, dict) or
10431
            "size" not in row or
10432
            not isinstance(row["size"], int) or
10433
            "mode" not in row or
10434
            row["mode"] not in ['r', 'w']):
10435
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
10436
                                     " parameter", errors.ECODE_INVAL)
10437
      if self.op.hypervisor is None:
10438
        self.op.hypervisor = self.cfg.GetHypervisorType()
10439
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10440
      fname = _ExpandInstanceName(self.cfg, self.op.name)
10441
      self.op.name = fname
10442
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
10443
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10444
      if not hasattr(self.op, "evac_nodes"):
10445
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
10446
                                   " opcode input", errors.ECODE_INVAL)
10447
    else:
10448
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
10449
                                 self.op.mode, errors.ECODE_INVAL)
10450

    
10451
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
10452
      if self.op.allocator is None:
10453
        raise errors.OpPrereqError("Missing allocator name",
10454
                                   errors.ECODE_INVAL)
10455
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
10456
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
10457
                                 self.op.direction, errors.ECODE_INVAL)
10458

    
10459
  def Exec(self, feedback_fn):
10460
    """Run the allocator test.
10461

10462
    """
10463
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10464
      ial = IAllocator(self.cfg, self.rpc,
10465
                       mode=self.op.mode,
10466
                       name=self.op.name,
10467
                       mem_size=self.op.mem_size,
10468
                       disks=self.op.disks,
10469
                       disk_template=self.op.disk_template,
10470
                       os=self.op.os,
10471
                       tags=self.op.tags,
10472
                       nics=self.op.nics,
10473
                       vcpus=self.op.vcpus,
10474
                       hypervisor=self.op.hypervisor,
10475
                       )
10476
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10477
      ial = IAllocator(self.cfg, self.rpc,
10478
                       mode=self.op.mode,
10479
                       name=self.op.name,
10480
                       relocate_from=list(self.relocate_from),
10481
                       )
10482
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10483
      ial = IAllocator(self.cfg, self.rpc,
10484
                       mode=self.op.mode,
10485
                       evac_nodes=self.op.evac_nodes)
10486
    else:
10487
      raise errors.ProgrammerError("Uncatched mode %s in"
10488
                                   " LUTestAllocator.Exec", self.op.mode)
10489

    
10490
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
10491
      result = ial.in_text
10492
    else:
10493
      ial.Run(self.op.allocator, validate=False)
10494
      result = ial.out_text
10495
    return result