Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 5a3ab484

History | View | Annotate | Download (364.2 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

    
240
# End types
241
class LogicalUnit(object):
242
  """Logical Unit base class.
243

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

253
  Note that all commands require root permissions.
254

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

260
  """
261
  HPATH = None
262
  HTYPE = None
263
  _OP_PARAMS = []
264
  REQ_BGL = True
265

    
266
  def __init__(self, processor, op, context, rpc):
267
    """Constructor for LogicalUnit.
268

269
    This needs to be overridden in derived classes in order to check op
270
    validity.
271

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

    
299
    # Tasklets
300
    self.tasklets = None
301

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

    
329
    self.CheckArguments()
330

    
331
  def __GetSSH(self):
332
    """Returns the SshRunner object
333

334
    """
335
    if not self.__ssh:
336
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
337
    return self.__ssh
338

    
339
  ssh = property(fget=__GetSSH)
340

    
341
  def CheckArguments(self):
342
    """Check syntactic validity for the opcode arguments.
343

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

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

353
    The function is allowed to change the self.op attribute so that
354
    later methods can no longer worry about missing parameters.
355

356
    """
357
    pass
358

    
359
  def ExpandNames(self):
360
    """Expand names for this LU.
361

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

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

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

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

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

384
    Examples::
385

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

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

    
407
  def DeclareLocks(self, level):
408
    """Declare LU locking needs for a level
409

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

417
    This function is only called if you have something already set in
418
    self.needed_locks for the level.
419

420
    @param level: Locking level which is going to be locked
421
    @type level: member of ganeti.locking.LEVELS
422

423
    """
424

    
425
  def CheckPrereq(self):
426
    """Check prerequisites for this LU.
427

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

433
    The method should raise errors.OpPrereqError in case something is
434
    not fulfilled. Its return value is ignored.
435

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

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

    
448
  def Exec(self, feedback_fn):
449
    """Execute the LU.
450

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

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

    
463
  def BuildHooksEnv(self):
464
    """Build hooks environment for this LU.
465

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

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

477
    No nodes should be returned as an empty list (and not None).
478

479
    Note that if the HPATH for a LU class is None, this function will
480
    not be called.
481

482
    """
483
    raise NotImplementedError
484

    
485
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
486
    """Notify the LU about the results of its hooks.
487

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

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

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

    
509
  def _ExpandAndLockInstance(self):
510
    """Helper function to expand and lock an instance.
511

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

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

    
528
  def _LockInstancesNodes(self, primary_only=False):
529
    """Helper function to declare instances' nodes for locking.
530

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

536
    It should be called from DeclareLocks, and for safety only works if
537
    self.recalculate_locks[locking.LEVEL_NODE] is set.
538

539
    In the future it may grow parameters to just lock some instance's nodes, or
540
    to just lock primaries or secondary nodes, if needed.
541

542
    If should be called in DeclareLocks in a way similar to::
543

544
      if level == locking.LEVEL_NODE:
545
        self._LockInstancesNodes()
546

547
    @type primary_only: boolean
548
    @param primary_only: only lock primary nodes of locked instances
549

550
    """
551
    assert locking.LEVEL_NODE in self.recalculate_locks, \
552
      "_LockInstancesNodes helper function called with no nodes to recalculate"
553

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

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

    
566
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
567
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
568
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
569
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
570

    
571
    del self.recalculate_locks[locking.LEVEL_NODE]
572

    
573

    
574
class NoHooksLU(LogicalUnit): # pylint: disable-msg=W0223
575
  """Simple LU which runs no hooks.
576

577
  This LU is intended as a parent for other LogicalUnits which will
578
  run no hooks, in order to reduce duplicate code.
579

580
  """
581
  HPATH = None
582
  HTYPE = None
583

    
584
  def BuildHooksEnv(self):
585
    """Empty BuildHooksEnv for NoHooksLu.
586

587
    This just raises an error.
588

589
    """
590
    assert False, "BuildHooksEnv called for NoHooksLUs"
591

    
592

    
593
class Tasklet:
594
  """Tasklet base class.
595

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

600
  Subclasses must follow these rules:
601
    - Implement CheckPrereq
602
    - Implement Exec
603

604
  """
605
  def __init__(self, lu):
606
    self.lu = lu
607

    
608
    # Shortcuts
609
    self.cfg = lu.cfg
610
    self.rpc = lu.rpc
611

    
612
  def CheckPrereq(self):
613
    """Check prerequisites for this tasklets.
614

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

619
    The method should raise errors.OpPrereqError in case something is not
620
    fulfilled. Its return value is ignored.
621

622
    This method should also update all parameters to their canonical form if it
623
    hasn't been done before.
624

625
    """
626
    pass
627

    
628
  def Exec(self, feedback_fn):
629
    """Execute the tasklet.
630

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

635
    """
636
    raise NotImplementedError
637

    
638

    
639
def _GetWantedNodes(lu, nodes):
640
  """Returns list of checked and expanded node names.
641

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

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

    
655
  wanted = [_ExpandNodeName(lu.cfg, name) for name in nodes]
656
  return utils.NiceSort(wanted)
657

    
658

    
659
def _GetWantedInstances(lu, instances):
660
  """Returns list of checked and expanded instance names.
661

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

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

    
678

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

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

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

    
711

    
712
def _CheckOutputFields(static, dynamic, selected):
713
  """Checks whether all selected fields are valid.
714

715
  @type static: L{utils.FieldSet}
716
  @param static: static fields set
717
  @type dynamic: L{utils.FieldSet}
718
  @param dynamic: dynamic fields set
719

720
  """
721
  f = utils.FieldSet()
722
  f.Extend(static)
723
  f.Extend(dynamic)
724

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

    
730

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

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

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

    
745

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

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

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

    
758

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

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

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

    
771

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

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

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

    
789

    
790
def _RequireFileStorage():
791
  """Checks that file storage is enabled.
792

793
  @raise errors.OpPrereqError: when file storage is disabled
794

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

    
800

    
801
def _CheckDiskTemplate(template):
802
  """Ensure a given disk template is valid.
803

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

    
813

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

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

    
825

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

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

    
833

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

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

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

    
849

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

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

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

    
866

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

    
871

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

    
876

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

882
  This builds the hook environment from individual variables.
883

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

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

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

    
946
  env["INSTANCE_NIC_COUNT"] = nic_count
947

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

    
956
  env["INSTANCE_DISK_COUNT"] = disk_count
957

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

    
962
  return env
963

    
964

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

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

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

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

    
988

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

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

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

    
1026

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

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

    
1042

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

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

    
1053

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

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

    
1067

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

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

    
1076

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

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

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

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

    
1097

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

    
1101

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

1105
  """
1106

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

    
1109

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

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

    
1117

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

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

    
1125

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

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

    
1135
  return []
1136

    
1137

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

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

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

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

    
1152
  return faulty
1153

    
1154

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

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

1163
  @type iallocator_slot: string
1164
  @param iallocator_slot: the name of the opcode iallocator slot
1165
  @type node_slot: string
1166
  @param node_slot: the name of the opcode target node slot
1167

1168
  """
1169
  node = getattr(lu.op, node_slot, None)
1170
  iallocator = getattr(lu.op, iallocator_slot, None)
1171

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

    
1186

    
1187
class LUPostInitCluster(LogicalUnit):
1188
  """Logical unit for running hooks after cluster initialization.
1189

1190
  """
1191
  HPATH = "cluster-init"
1192
  HTYPE = constants.HTYPE_CLUSTER
1193

    
1194
  def BuildHooksEnv(self):
1195
    """Build hooks env.
1196

1197
    """
1198
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1199
    mn = self.cfg.GetMasterNode()
1200
    return env, [], [mn]
1201

    
1202
  def Exec(self, feedback_fn):
1203
    """Nothing to do.
1204

1205
    """
1206
    return True
1207

    
1208

    
1209
class LUDestroyCluster(LogicalUnit):
1210
  """Logical unit for destroying the cluster.
1211

1212
  """
1213
  HPATH = "cluster-destroy"
1214
  HTYPE = constants.HTYPE_CLUSTER
1215

    
1216
  def BuildHooksEnv(self):
1217
    """Build hooks env.
1218

1219
    """
1220
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1221
    return env, [], []
1222

    
1223
  def CheckPrereq(self):
1224
    """Check prerequisites.
1225

1226
    This checks whether the cluster is empty.
1227

1228
    Any errors are signaled by raising errors.OpPrereqError.
1229

1230
    """
1231
    master = self.cfg.GetMasterNode()
1232

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

    
1244
  def Exec(self, feedback_fn):
1245
    """Destroys the cluster.
1246

1247
    """
1248
    master = self.cfg.GetMasterNode()
1249
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
1250

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

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

    
1262
    if modify_ssh_setup:
1263
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
1264
      utils.CreateBackup(priv_key)
1265
      utils.CreateBackup(pub_key)
1266

    
1267
    return master
1268

    
1269

    
1270
def _VerifyCertificate(filename):
1271
  """Verifies a certificate for LUVerifyCluster.
1272

1273
  @type filename: string
1274
  @param filename: Path to PEM file
1275

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

    
1284
  (errcode, msg) = \
1285
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1286
                                constants.SSL_CERT_EXPIRATION_ERROR)
1287

    
1288
  if msg:
1289
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1290
  else:
1291
    fnamemsg = None
1292

    
1293
  if errcode is None:
1294
    return (None, fnamemsg)
1295
  elif errcode == utils.CERT_WARNING:
1296
    return (LUVerifyCluster.ETYPE_WARNING, fnamemsg)
1297
  elif errcode == utils.CERT_ERROR:
1298
    return (LUVerifyCluster.ETYPE_ERROR, fnamemsg)
1299

    
1300
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1301

    
1302

    
1303
class LUVerifyCluster(LogicalUnit):
1304
  """Verifies the cluster status.
1305

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

    
1318
  TCLUSTER = "cluster"
1319
  TNODE = "node"
1320
  TINSTANCE = "instance"
1321

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

    
1347
  ETYPE_FIELD = "code"
1348
  ETYPE_ERROR = "ERROR"
1349
  ETYPE_WARNING = "WARNING"
1350

    
1351
  class NodeImage(object):
1352
    """A class representing the logical and physical status of a node.
1353

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

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

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

    
1405
  def _Error(self, ecode, item, msg, *args, **kwargs):
1406
    """Format an error message.
1407

1408
    Based on the opcode's error_codes parameter, either format a
1409
    parseable error code, or a simpler error string.
1410

1411
    This must be called only from Exec and functions called from Exec.
1412

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

    
1431
  def _ErrorIf(self, cond, *args, **kwargs):
1432
    """Log an error message if the passed condition is True.
1433

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

    
1442
  def _VerifyNode(self, ninfo, nresult):
1443
    """Perform some basic validation on data returned from a node.
1444

1445
      - check the result data structure is well formed and has all the
1446
        mandatory fields
1447
      - check ganeti version
1448

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

1456
    """
1457
    node = ninfo.name
1458
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1459

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

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

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

    
1485
    # node seems compatible, we can actually try to look into its results
1486

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

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

    
1501

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

    
1507
    return True
1508

    
1509
  def _VerifyNodeTime(self, ninfo, nresult,
1510
                      nvinfo_starttime, nvinfo_endtime):
1511
    """Check the node time.
1512

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

1519
    """
1520
    node = ninfo.name
1521
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1522

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

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

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

    
1541
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1542
    """Check the node time.
1543

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

1549
    """
1550
    if vg_name is None:
1551
      return
1552

    
1553
    node = ninfo.name
1554
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1555

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

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

    
1578
  def _VerifyNodeNetwork(self, ninfo, nresult):
1579
    """Check the node time.
1580

1581
    @type ninfo: L{objects.Node}
1582
    @param ninfo: the node to check
1583
    @param nresult: the remote results for the node
1584

1585
    """
1586
    node = ninfo.name
1587
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1588

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

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

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

    
1620

    
1621
  def _VerifyInstance(self, instance, instanceconfig, node_image):
1622
    """Verify an instance.
1623

1624
    This function checks to see if the required block devices are
1625
    available on the instance's node.
1626

1627
    """
1628
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1629
    node_current = instanceconfig.primary_node
1630

    
1631
    node_vol_should = {}
1632
    instanceconfig.MapLVsByNode(node_vol_should)
1633

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

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

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

    
1657
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1658
    """Verify if there are any unknown volumes in the cluster.
1659

1660
    The .os, .swap and backup volumes are ignored. All other volumes are
1661
    reported as unknown.
1662

1663
    @type reserved: L{ganeti.utils.FieldSet}
1664
    @param reserved: a FieldSet of reserved volume names
1665

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

    
1678
  def _VerifyOrphanInstances(self, instancelist, node_image):
1679
    """Verify the list of running instances.
1680

1681
    This checks what instances are running but unknown to the cluster.
1682

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

    
1690
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1691
    """Verify N+1 Memory Resilience.
1692

1693
    Check that if one single node dies we can still start all the
1694
    instances it was primary for.
1695

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

    
1717
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1718
                       master_files):
1719
    """Verifies and computes the node required file checksums.
1720

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

1728
    """
1729
    node = ninfo.name
1730
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1731

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

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

    
1761
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1762
                      drbd_map):
1763
    """Verifies and the node DRBD status.
1764

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

1773
    """
1774
    node = ninfo.name
1775
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1776

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

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

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

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

    
1824
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1825
    """Builds the node OS structures.
1826

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

1832
    """
1833
    node = ninfo.name
1834
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1835

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

    
1841
    _ErrorIf(test, self.ENODEOS, node,
1842
             "node hasn't returned valid OS data")
1843

    
1844
    nimg.os_fail = test
1845

    
1846
    if test:
1847
      return
1848

    
1849
    os_dict = {}
1850

    
1851
    for (name, os_path, status, diagnose,
1852
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1853

    
1854
      if name not in os_dict:
1855
        os_dict[name] = []
1856

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

    
1863
    nimg.oslist = os_dict
1864

    
1865
  def _VerifyNodeOS(self, ninfo, nimg, base):
1866
    """Verifies the node OS list.
1867

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

1873
    """
1874
    node = ninfo.name
1875
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1876

    
1877
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1878

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

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

    
1918
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1919
    """Verifies and updates the node volume data.
1920

1921
    This function will update a L{NodeImage}'s internal structures
1922
    with data from the remote call.
1923

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

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

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

    
1947
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1948
    """Verifies and updates the node instance list.
1949

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

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

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

    
1969
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1970
    """Verifies and computes a node information map
1971

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

1978
    """
1979
    node = ninfo.name
1980
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1981

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

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

    
2007
  def BuildHooksEnv(self):
2008
    """Build hooks env.
2009

2010
    Cluster-Verify hooks just ran in the post phase and their failure makes
2011
    the output be logged in the verify output and the verification to fail.
2012

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

    
2021
    return env, [], all_nodes
2022

    
2023
  def Exec(self, feedback_fn):
2024
    """Verify integrity of cluster, performing various test on nodes.
2025

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

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

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

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

    
2061
    file_names = ssconf.SimpleStore().GetFileList()
2062
    file_names.extend(constants.ALL_CERT_FILES)
2063
    file_names.extend(master_files)
2064
    if cluster.modify_etc_hosts:
2065
      file_names.append(constants.ETC_HOSTS)
2066

    
2067
    local_checksums = utils.FingerprintFiles(file_names)
2068

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

    
2087
    if vg_name is not None:
2088
      node_verify_param[constants.NV_VGLIST] = None
2089
      node_verify_param[constants.NV_LVLIST] = vg_name
2090
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2091
      node_verify_param[constants.NV_DRBDLIST] = None
2092

    
2093
    if drbd_helper:
2094
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2095

    
2096
    # Build our expected cluster state
2097
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2098
                                                 name=node.name))
2099
                      for node in nodeinfo)
2100

    
2101
    for instance in instancelist:
2102
      inst_config = instanceinfo[instance]
2103

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

    
2111
      inst_config.MapLVsByNode(node_vol_should)
2112

    
2113
      pnode = inst_config.primary_node
2114
      node_image[pnode].pinst.append(instance)
2115

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

    
2123
    # At this point, we have the in-memory data structures complete,
2124
    # except for the runtime information, which we'll gather next
2125

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

    
2135
    all_drbd_map = self.cfg.ComputeDRBDMap()
2136

    
2137
    feedback_fn("* Verifying node status")
2138

    
2139
    refos_img = None
2140

    
2141
    for node_i in nodeinfo:
2142
      node = node_i.name
2143
      nimg = node_image[node]
2144

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

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

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

    
2169
      nresult = all_nvinfo[node].payload
2170

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

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

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

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

    
2203
      if pnode_img.offline:
2204
        inst_nodes_offline.append(pnode)
2205

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

    
2218
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2219
        i_non_a_balanced.append(instance)
2220

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

    
2226
        if s_img.offline:
2227
          inst_nodes_offline.append(snode)
2228

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

    
2238
    feedback_fn("* Verifying orphan volumes")
2239
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2240
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2241

    
2242
    feedback_fn("* Verifying orphan instances")
2243
    self._VerifyOrphanInstances(instancelist, node_image)
2244

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

    
2249
    feedback_fn("* Other Notes")
2250
    if i_non_redundant:
2251
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2252
                  % len(i_non_redundant))
2253

    
2254
    if i_non_a_balanced:
2255
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2256
                  % len(i_non_a_balanced))
2257

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

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

    
2264
    return not self.bad
2265

    
2266
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2267
    """Analyze the post-hooks' result
2268

2269
    This method analyses the hook result, handles it, and sends some
2270
    nicely-formatted feedback back to the user.
2271

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

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

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

    
2310
      return lu_result
2311

    
2312

    
2313
class LUVerifyDisks(NoHooksLU):
2314
  """Verifies the cluster disks status.
2315

2316
  """
2317
  REQ_BGL = False
2318

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

    
2326
  def Exec(self, feedback_fn):
2327
    """Verify integrity of cluster disks.
2328

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

2334
    """
2335
    result = res_nodes, res_instances, res_missing = {}, [], {}
2336

    
2337
    vg_name = self.cfg.GetVGName()
2338
    nodes = utils.NiceSort(self.cfg.GetNodeList())
2339
    instances = [self.cfg.GetInstanceInfo(name)
2340
                 for name in self.cfg.GetInstanceList()]
2341

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

    
2354
    if not nv_dict:
2355
      return result
2356

    
2357
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
2358

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

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

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

    
2384
    return result
2385

    
2386

    
2387
class LURepairDiskSizes(NoHooksLU):
2388
  """Verifies the cluster disks sizes.
2389

2390
  """
2391
  _OP_PARAMS = [("instances", _EmptyList, _TListOf(_TNonEmptyString))]
2392
  REQ_BGL = False
2393

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

    
2413
  def DeclareLocks(self, level):
2414
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2415
      self._LockInstancesNodes(primary_only=True)
2416

    
2417
  def CheckPrereq(self):
2418
    """Check prerequisites.
2419

2420
    This only checks the optional instance list against the existing names.
2421

2422
    """
2423
    if self.wanted_names is None:
2424
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2425

    
2426
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2427
                             in self.wanted_names]
2428

    
2429
  def _EnsureChildSizes(self, disk):
2430
    """Ensure children of the disk have the needed disk size.
2431

2432
    This is valid mainly for DRBD8 and fixes an issue where the
2433
    children have smaller disk size.
2434

2435
    @param disk: an L{ganeti.objects.Disk} object
2436

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

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

    
2452
  def Exec(self, feedback_fn):
2453
    """Verify the size of cluster disks.
2454

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

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

    
2502

    
2503
class LURenameCluster(LogicalUnit):
2504
  """Rename the cluster.
2505

2506
  """
2507
  HPATH = "cluster-rename"
2508
  HTYPE = constants.HTYPE_CLUSTER
2509
  _OP_PARAMS = [("name", _NoDefault, _TNonEmptyString)]
2510

    
2511
  def BuildHooksEnv(self):
2512
    """Build hooks env.
2513

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

    
2523
  def CheckPrereq(self):
2524
    """Verify that the passed name is a valid one.
2525

2526
    """
2527
    hostname = netutils.GetHostInfo(self.op.name)
2528

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

    
2543
    self.op.name = new_name
2544

    
2545
  def Exec(self, feedback_fn):
2546
    """Rename the cluster.
2547

2548
    """
2549
    clustername = self.op.name
2550
    ip = self.ip
2551

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

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

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

    
2579
    finally:
2580
      result = self.rpc.call_node_start_master(master, False, False)
2581
      msg = result.fail_msg
2582
      if msg:
2583
        self.LogWarning("Could not re-enable the master role on"
2584
                        " the master, please restart manually: %s", msg)
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
    ]
2610
  REQ_BGL = False
2611

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2879
    self.cfg.Update(self.cluster, feedback_fn)
2880

    
2881

    
2882
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
2883
  """Distribute additional files which are part of the cluster configuration.
2884

2885
  ConfigWriter takes care of distributing the config and ssconf files, but
2886
  there are more files which should be distributed to all nodes. This function
2887
  makes sure those are copied.
2888

2889
  @param lu: calling logical unit
2890
  @param additional_nodes: list of nodes not in the config to distribute to
2891

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

    
2901
  # 2. Gather files to distribute
2902
  dist_files = set([constants.ETC_HOSTS,
2903
                    constants.SSH_KNOWN_HOSTS_FILE,
2904
                    constants.RAPI_CERT_FILE,
2905
                    constants.RAPI_USERS_FILE,
2906
                    constants.CONFD_HMAC_KEY,
2907
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
2908
                   ])
2909

    
2910
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2911
  for hv_name in enabled_hypervisors:
2912
    hv_class = hypervisor.GetHypervisor(hv_name)
2913
    dist_files.update(hv_class.GetAncillaryFiles())
2914

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

    
2926

    
2927
class LURedistributeConfig(NoHooksLU):
2928
  """Force the redistribution of cluster configuration.
2929

2930
  This is a very simple LU.
2931

2932
  """
2933
  REQ_BGL = False
2934

    
2935
  def ExpandNames(self):
2936
    self.needed_locks = {
2937
      locking.LEVEL_NODE: locking.ALL_SET,
2938
    }
2939
    self.share_locks[locking.LEVEL_NODE] = 1
2940

    
2941
  def Exec(self, feedback_fn):
2942
    """Redistribute the configuration.
2943

2944
    """
2945
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2946
    _RedistributeAncillaryFiles(self)
2947

    
2948

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

2952
  """
2953
  if not instance.disks or disks is not None and not disks:
2954
    return True
2955

    
2956
  disks = _ExpandCheckDisks(instance, disks)
2957

    
2958
  if not oneshot:
2959
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2960

    
2961
  node = instance.primary_node
2962

    
2963
  for dev in disks:
2964
    lu.cfg.SetDiskID(dev, node)
2965

    
2966
  # TODO: Convert to utils.Retry
2967

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

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

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

    
3014
    if done or oneshot:
3015
      break
3016

    
3017
    time.sleep(min(60, max_time))
3018

    
3019
  if done:
3020
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3021
  return not cumul_degraded
3022

    
3023

    
3024
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3025
  """Check that mirrors are not degraded.
3026

3027
  The ldisk parameter, if True, will change the test from the
3028
  is_degraded attribute (which represents overall non-ok status for
3029
  the device(s)) to the ldisk (representing the local storage status).
3030

3031
  """
3032
  lu.cfg.SetDiskID(dev, node)
3033

    
3034
  result = True
3035

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

    
3051
  if dev.children:
3052
    for child in dev.children:
3053
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3054

    
3055
  return result
3056

    
3057

    
3058
class LUDiagnoseOS(NoHooksLU):
3059
  """Logical unit for OS diagnose/query.
3060

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

    
3071
  def CheckArguments(self):
3072
    if self.op.names:
3073
      raise errors.OpPrereqError("Selective OS query not supported",
3074
                                 errors.ECODE_INVAL)
3075

    
3076
    _CheckOutputFields(static=self._FIELDS_STATIC,
3077
                       dynamic=self._FIELDS_DYNAMIC,
3078
                       selected=self.op.output_fields)
3079

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

    
3088
  @staticmethod
3089
  def _DiagnoseByOS(rlist):
3090
    """Remaps a per-node return list into an a per-os per-node dictionary
3091

3092
    @param rlist: a map with node names as keys and OS objects as values
3093

3094
    @rtype: dict
3095
    @return: a dictionary with osnames as keys and as value another
3096
        map, with nodes as keys and tuples of (path, status, diagnose,
3097
        variants, parameters, api_versions) as values, eg::
3098

3099
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3100
                                     (/srv/..., False, "invalid api")],
3101
                           "node2": [(/srv/..., True, "", [], [])]}
3102
          }
3103

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

    
3128
  def Exec(self, feedback_fn):
3129
    """Compute the list of OSes.
3130

3131
    """
3132
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
3133
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3134
    pol = self._DiagnoseByOS(node_data)
3135
    output = []
3136

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

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

    
3177
    return output
3178

    
3179

    
3180
class LURemoveNode(LogicalUnit):
3181
  """Logical unit for removing a node.
3182

3183
  """
3184
  HPATH = "node-remove"
3185
  HTYPE = constants.HTYPE_NODE
3186
  _OP_PARAMS = [
3187
    _PNodeName,
3188
    ]
3189

    
3190
  def BuildHooksEnv(self):
3191
    """Build hooks env.
3192

3193
    This doesn't run on the target node in the pre phase as a failed
3194
    node would then be impossible to remove.
3195

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

    
3209
  def CheckPrereq(self):
3210
    """Check prerequisites.
3211

3212
    This checks:
3213
     - the node exists in the configuration
3214
     - it does not have primary or secondary instances
3215
     - it's not the master
3216

3217
    Any errors are signaled by raising errors.OpPrereqError.
3218

3219
    """
3220
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3221
    node = self.cfg.GetNodeInfo(self.op.node_name)
3222
    assert node is not None
3223

    
3224
    instance_list = self.cfg.GetInstanceList()
3225

    
3226
    masternode = self.cfg.GetMasterNode()
3227
    if node.name == masternode:
3228
      raise errors.OpPrereqError("Node is the master node,"
3229
                                 " you need to failover first.",
3230
                                 errors.ECODE_INVAL)
3231

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

    
3241
  def Exec(self, feedback_fn):
3242
    """Removes the node from the cluster.
3243

3244
    """
3245
    node = self.node
3246
    logging.info("Stopping the node daemon and removing configs from node %s",
3247
                 node.name)
3248

    
3249
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3250

    
3251
    # Promote nodes to master candidate as needed
3252
    _AdjustCandidatePool(self, exceptions=[node.name])
3253
    self.context.RemoveNode(node.name)
3254

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

    
3263
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3264
    msg = result.fail_msg
3265
    if msg:
3266
      self.LogWarning("Errors encountered on the remote node while leaving"
3267
                      " the cluster: %s", msg)
3268

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

    
3275

    
3276
class LUQueryNodes(NoHooksLU):
3277
  """Logical unit for querying nodes.
3278

3279
  """
3280
  # pylint: disable-msg=W0142
3281
  _OP_PARAMS = [
3282
    _POutputFields,
3283
    ("names", _EmptyList, _TListOf(_TNonEmptyString)),
3284
    ("use_locking", False, _TBool),
3285
    ]
3286
  REQ_BGL = False
3287

    
3288
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
3289
                    "master_candidate", "offline", "drained"]
3290

    
3291
  _FIELDS_DYNAMIC = utils.FieldSet(
3292
    "dtotal", "dfree",
3293
    "mtotal", "mnode", "mfree",
3294
    "bootid",
3295
    "ctotal", "cnodes", "csockets",
3296
    )
3297

    
3298
  _FIELDS_STATIC = utils.FieldSet(*[
3299
    "pinst_cnt", "sinst_cnt",
3300
    "pinst_list", "sinst_list",
3301
    "pip", "sip", "tags",
3302
    "master",
3303
    "role"] + _SIMPLE_FIELDS
3304
    )
3305

    
3306
  def CheckArguments(self):
3307
    _CheckOutputFields(static=self._FIELDS_STATIC,
3308
                       dynamic=self._FIELDS_DYNAMIC,
3309
                       selected=self.op.output_fields)
3310

    
3311
  def ExpandNames(self):
3312
    self.needed_locks = {}
3313
    self.share_locks[locking.LEVEL_NODE] = 1
3314

    
3315
    if self.op.names:
3316
      self.wanted = _GetWantedNodes(self, self.op.names)
3317
    else:
3318
      self.wanted = locking.ALL_SET
3319

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

    
3326
  def Exec(self, feedback_fn):
3327
    """Computes the list of nodes and their attributes.
3328

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

    
3342
    nodenames = utils.NiceSort(nodenames)
3343
    nodelist = [all_info[name] for name in nodenames]
3344

    
3345
    # begin data gathering
3346

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

    
3372
    node_to_primary = dict([(name, set()) for name in nodenames])
3373
    node_to_secondary = dict([(name, set()) for name in nodenames])
3374

    
3375
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
3376
                             "sinst_cnt", "sinst_list"))
3377
    if inst_fields & frozenset(self.op.output_fields):
3378
      inst_data = self.cfg.GetAllInstancesInfo()
3379

    
3380
      for inst in inst_data.values():
3381
        if inst.primary_node in node_to_primary:
3382
          node_to_primary[inst.primary_node].add(inst.name)
3383
        for secnode in inst.secondary_nodes:
3384
          if secnode in node_to_secondary:
3385
            node_to_secondary[secnode].add(inst.name)
3386

    
3387
    master_node = self.cfg.GetMasterNode()
3388

    
3389
    # end data gathering
3390

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

    
3431
    return output
3432

    
3433

    
3434
class LUQueryNodeVolumes(NoHooksLU):
3435
  """Logical unit for getting volumes on node(s).
3436

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

    
3446
  def CheckArguments(self):
3447
    _CheckOutputFields(static=self._FIELDS_STATIC,
3448
                       dynamic=self._FIELDS_DYNAMIC,
3449
                       selected=self.op.output_fields)
3450

    
3451
  def ExpandNames(self):
3452
    self.needed_locks = {}
3453
    self.share_locks[locking.LEVEL_NODE] = 1
3454
    if not self.op.nodes:
3455
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3456
    else:
3457
      self.needed_locks[locking.LEVEL_NODE] = \
3458
        _GetWantedNodes(self, self.op.nodes)
3459

    
3460
  def Exec(self, feedback_fn):
3461
    """Computes the list of nodes and their attributes.
3462

3463
    """
3464
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3465
    volumes = self.rpc.call_node_volumes(nodenames)
3466

    
3467
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3468
             in self.cfg.GetInstanceList()]
3469

    
3470
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3471

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

    
3482
      node_vols = nresult.payload[:]
3483
      node_vols.sort(key=lambda vol: vol['dev'])
3484

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

    
3511
        output.append(node_output)
3512

    
3513
    return output
3514

    
3515

    
3516
class LUQueryNodeStorage(NoHooksLU):
3517
  """Logical unit for getting information on storage units on node(s).
3518

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

    
3529
  def CheckArguments(self):
3530
    _CheckOutputFields(static=self._FIELDS_STATIC,
3531
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3532
                       selected=self.op.output_fields)
3533

    
3534
  def ExpandNames(self):
3535
    self.needed_locks = {}
3536
    self.share_locks[locking.LEVEL_NODE] = 1
3537

    
3538
    if self.op.nodes:
3539
      self.needed_locks[locking.LEVEL_NODE] = \
3540
        _GetWantedNodes(self, self.op.nodes)
3541
    else:
3542
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3543

    
3544
  def Exec(self, feedback_fn):
3545
    """Computes the list of nodes and their attributes.
3546

3547
    """
3548
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3549

    
3550
    # Always get name to sort by
3551
    if constants.SF_NAME in self.op.output_fields:
3552
      fields = self.op.output_fields[:]
3553
    else:
3554
      fields = [constants.SF_NAME] + self.op.output_fields
3555

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

    
3561
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3562
    name_idx = field_idx[constants.SF_NAME]
3563

    
3564
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3565
    data = self.rpc.call_storage_list(self.nodes,
3566
                                      self.op.storage_type, st_args,
3567
                                      self.op.name, fields)
3568

    
3569
    result = []
3570

    
3571
    for node in utils.NiceSort(self.nodes):
3572
      nresult = data[node]
3573
      if nresult.offline:
3574
        continue
3575

    
3576
      msg = nresult.fail_msg
3577
      if msg:
3578
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3579
        continue
3580

    
3581
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3582

    
3583
      for name in utils.NiceSort(rows.keys()):
3584
        row = rows[name]
3585

    
3586
        out = []
3587

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

    
3598
          out.append(val)
3599

    
3600
        result.append(out)
3601

    
3602
    return result
3603

    
3604

    
3605
class LUModifyNodeStorage(NoHooksLU):
3606
  """Logical unit for modifying a storage volume on a node.
3607

3608
  """
3609
  _OP_PARAMS = [
3610
    _PNodeName,
3611
    ("storage_type", _NoDefault, _CheckStorageType),
3612
    ("name", _NoDefault, _TNonEmptyString),
3613
    ("changes", _NoDefault, _TDict),
3614
    ]
3615
  REQ_BGL = False
3616

    
3617
  def CheckArguments(self):
3618
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3619

    
3620
    storage_type = self.op.storage_type
3621

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

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

    
3636
  def ExpandNames(self):
3637
    self.needed_locks = {
3638
      locking.LEVEL_NODE: self.op.node_name,
3639
      }
3640

    
3641
  def Exec(self, feedback_fn):
3642
    """Computes the list of nodes and their attributes.
3643

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

    
3652

    
3653
class LUAddNode(LogicalUnit):
3654
  """Logical unit for adding node to the cluster.
3655

3656
  """
3657
  HPATH = "node-add"
3658
  HTYPE = constants.HTYPE_NODE
3659
  _OP_PARAMS = [
3660
    _PNodeName,
3661
    ("primary_ip", None, _NoType),
3662
    ("secondary_ip", None, _TMaybeString),
3663
    ("readd", False, _TBool),
3664
    ]
3665

    
3666
  def CheckArguments(self):
3667
    # validate/normalize the node name
3668
    self.op.node_name = netutils.HostInfo.NormalizeName(self.op.node_name)
3669

    
3670
  def BuildHooksEnv(self):
3671
    """Build hooks env.
3672

3673
    This will run on all nodes before, and on all nodes + the new node after.
3674

3675
    """
3676
    env = {
3677
      "OP_TARGET": self.op.node_name,
3678
      "NODE_NAME": self.op.node_name,
3679
      "NODE_PIP": self.op.primary_ip,
3680
      "NODE_SIP": self.op.secondary_ip,
3681
      }
3682
    nodes_0 = self.cfg.GetNodeList()
3683
    nodes_1 = nodes_0 + [self.op.node_name, ]
3684
    return env, nodes_0, nodes_1
3685

    
3686
  def CheckPrereq(self):
3687
    """Check prerequisites.
3688

3689
    This checks:
3690
     - the new node is not already in the config
3691
     - it is resolvable
3692
     - its parameters (single/dual homed) matches the cluster
3693

3694
    Any errors are signaled by raising errors.OpPrereqError.
3695

3696
    """
3697
    node_name = self.op.node_name
3698
    cfg = self.cfg
3699

    
3700
    dns_data = netutils.GetHostInfo(node_name)
3701

    
3702
    node = dns_data.name
3703
    primary_ip = self.op.primary_ip = dns_data.ip
3704
    if self.op.secondary_ip is None:
3705
      self.op.secondary_ip = primary_ip
3706
    if not netutils.IsValidIP4(self.op.secondary_ip):
3707
      raise errors.OpPrereqError("Invalid secondary IP given",
3708
                                 errors.ECODE_INVAL)
3709
    secondary_ip = self.op.secondary_ip
3710

    
3711
    node_list = cfg.GetNodeList()
3712
    if not self.op.readd and node in node_list:
3713
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3714
                                 node, errors.ECODE_EXISTS)
3715
    elif self.op.readd and node not in node_list:
3716
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3717
                                 errors.ECODE_NOENT)
3718

    
3719
    self.changed_primary_ip = False
3720

    
3721
    for existing_node_name in node_list:
3722
      existing_node = cfg.GetNodeInfo(existing_node_name)
3723

    
3724
      if self.op.readd and node == existing_node_name:
3725
        if existing_node.secondary_ip != secondary_ip:
3726
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3727
                                     " address configuration as before",
3728
                                     errors.ECODE_INVAL)
3729
        if existing_node.primary_ip != primary_ip:
3730
          self.changed_primary_ip = True
3731

    
3732
        continue
3733

    
3734
      if (existing_node.primary_ip == primary_ip or
3735
          existing_node.secondary_ip == primary_ip or
3736
          existing_node.primary_ip == secondary_ip or
3737
          existing_node.secondary_ip == secondary_ip):
3738
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3739
                                   " existing node %s" % existing_node.name,
3740
                                   errors.ECODE_NOTUNIQUE)
3741

    
3742
    # check that the type of the node (single versus dual homed) is the
3743
    # same as for the master
3744
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
3745
    master_singlehomed = myself.secondary_ip == myself.primary_ip
3746
    newbie_singlehomed = secondary_ip == primary_ip
3747
    if master_singlehomed != newbie_singlehomed:
3748
      if master_singlehomed:
3749
        raise errors.OpPrereqError("The master has no private ip but the"
3750
                                   " new node has one",
3751
                                   errors.ECODE_INVAL)
3752
      else:
3753
        raise errors.OpPrereqError("The master has a private ip but the"
3754
                                   " new node doesn't have one",
3755
                                   errors.ECODE_INVAL)
3756

    
3757
    # checks reachability
3758
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3759
      raise errors.OpPrereqError("Node not reachable by ping",
3760
                                 errors.ECODE_ENVIRON)
3761

    
3762
    if not newbie_singlehomed:
3763
      # check reachability from my secondary ip to newbie's secondary ip
3764
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3765
                           source=myself.secondary_ip):
3766
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3767
                                   " based ping to noded port",
3768
                                   errors.ECODE_ENVIRON)
3769

    
3770
    if self.op.readd:
3771
      exceptions = [node]
3772
    else:
3773
      exceptions = []
3774

    
3775
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3776

    
3777
    if self.op.readd:
3778
      self.new_node = self.cfg.GetNodeInfo(node)
3779
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
3780
    else:
3781
      self.new_node = objects.Node(name=node,
3782
                                   primary_ip=primary_ip,
3783
                                   secondary_ip=secondary_ip,
3784
                                   master_candidate=self.master_candidate,
3785
                                   offline=False, drained=False)
3786

    
3787
  def Exec(self, feedback_fn):
3788
    """Adds the new node to the cluster.
3789

3790
    """
3791
    new_node = self.new_node
3792
    node = new_node.name
3793

    
3794
    # for re-adds, reset the offline/drained/master-candidate flags;
3795
    # we need to reset here, otherwise offline would prevent RPC calls
3796
    # later in the procedure; this also means that if the re-add
3797
    # fails, we are left with a non-offlined, broken node
3798
    if self.op.readd:
3799
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3800
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3801
      # if we demote the node, we do cleanup later in the procedure
3802
      new_node.master_candidate = self.master_candidate
3803
      if self.changed_primary_ip:
3804
        new_node.primary_ip = self.op.primary_ip
3805

    
3806
    # notify the user about any possible mc promotion
3807
    if new_node.master_candidate:
3808
      self.LogInfo("Node will be a master candidate")
3809

    
3810
    # check connectivity
3811
    result = self.rpc.call_version([node])[node]
3812
    result.Raise("Can't get version information from node %s" % node)
3813
    if constants.PROTOCOL_VERSION == result.payload:
3814
      logging.info("Communication to node %s fine, sw version %s match",
3815
                   node, result.payload)
3816
    else:
3817
      raise errors.OpExecError("Version mismatch master version %s,"
3818
                               " node version %s" %
3819
                               (constants.PROTOCOL_VERSION, result.payload))
3820

    
3821
    # setup ssh on node
3822
    if self.cfg.GetClusterInfo().modify_ssh_setup:
3823
      logging.info("Copy ssh key to node %s", node)
3824
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
3825
      keyarray = []
3826
      keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
3827
                  constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
3828
                  priv_key, pub_key]
3829

    
3830
      for i in keyfiles:
3831
        keyarray.append(utils.ReadFile(i))
3832

    
3833
      result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
3834
                                      keyarray[2], keyarray[3], keyarray[4],
3835
                                      keyarray[5])
3836
      result.Raise("Cannot transfer ssh keys to the new node")
3837

    
3838
    # Add node to our /etc/hosts, and add key to known_hosts
3839
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3840
      # FIXME: this should be done via an rpc call to node daemon
3841
      utils.AddHostToEtcHosts(new_node.name)
3842

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

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

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

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

    
3887

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

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

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

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

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

    
3925

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

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

3935
    This runs on the master node.
3936

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

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

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

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

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

    
3965

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

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

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

    
3991
    return
3992

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

3996
    """
3997
    node = self.node
3998

    
3999
    result = []
4000
    changed_mc = False
4001

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

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

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

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

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

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

    
4051
    return result
4052

    
4053

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

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

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

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

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

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

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

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

    
4089

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

4093
  """
4094
  REQ_BGL = False
4095

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

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

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

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

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

    
4145
    return result
4146

    
4147

    
4148
class LUQueryConfigValues(NoHooksLU):
4149
  """Return configuration values.
4150

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

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

    
4163
  def ExpandNames(self):
4164
    self.needed_locks = {}
4165

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

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

    
4185

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

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

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

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

    
4205
  def CheckPrereq(self):
4206
    """Check prerequisites.
4207

4208
    This checks that the instance is in the cluster.
4209

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

    
4216
  def Exec(self, feedback_fn):
4217
    """Activate the disks.
4218

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

    
4226
    return disks_info
4227

    
4228

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

4233
  This sets up the block devices on all nodes.
4234

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

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

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

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

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

    
4283
  # FIXME: race condition on drbd migration to primary
4284

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

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

    
4306
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4307

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

    
4314
  return disks_ok, device_info
4315

    
4316

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

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

    
4331

    
4332
class LUDeactivateInstanceDisks(NoHooksLU):
4333
  """Shutdown an instance's disks.
4334

4335
  """
4336
  _OP_PARAMS = [
4337
    _PInstanceName,
4338
    ]
4339
  REQ_BGL = False
4340

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

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

    
4350
  def CheckPrereq(self):
4351
    """Check prerequisites.
4352

4353
    This checks that the instance is in the cluster.
4354

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

    
4360
  def Exec(self, feedback_fn):
4361
    """Deactivate the disks
4362

4363
    """
4364
    instance = self.instance
4365
    _SafeShutdownInstanceDisks(self, instance)
4366

    
4367

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

4371
  This function checks if an instance is running, before calling
4372
  _ShutdownInstanceDisks.
4373

4374
  """
4375
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4376
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4377

    
4378

    
4379
def _ExpandCheckDisks(instance, disks):
4380
  """Return the instance disks selected by the disks list
4381

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

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

    
4396

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

4400
  This does the shutdown on all nodes of the instance.
4401

4402
  If the ignore_primary is false, errors on the primary node are
4403
  ignored.
4404

4405
  """
4406
  all_result = True
4407
  disks = _ExpandCheckDisks(instance, disks)
4408

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

    
4421

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

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

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

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

    
4458

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

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

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

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

    
4494

    
4495
class LUStartupInstance(LogicalUnit):
4496
  """Starts an instance.
4497

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

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

    
4515
  def ExpandNames(self):
4516
    self._ExpandAndLockInstance()
4517

    
4518
  def BuildHooksEnv(self):
4519
    """Build hooks env.
4520

4521
    This runs on master, primary and secondary nodes of the instance.
4522

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

    
4531
  def CheckPrereq(self):
4532
    """Check prerequisites.
4533

4534
    This checks that the instance is in the cluster.
4535

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

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

    
4552
    _CheckNodeOnline(self, instance.primary_node)
4553

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

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

    
4568
  def Exec(self, feedback_fn):
4569
    """Start the instance.
4570

4571
    """
4572
    instance = self.instance
4573
    force = self.op.force
4574

    
4575
    self.cfg.MarkInstanceUp(instance.name)
4576

    
4577
    node_current = instance.primary_node
4578

    
4579
    _StartInstanceDisks(self, instance, force)
4580

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

    
4588

    
4589
class LURebootInstance(LogicalUnit):
4590
  """Reboot an instance.
4591

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

    
4603
  def ExpandNames(self):
4604
    self._ExpandAndLockInstance()
4605

    
4606
  def BuildHooksEnv(self):
4607
    """Build hooks env.
4608

4609
    This runs on master, primary and secondary nodes of the instance.
4610

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

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

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

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

    
4631
    _CheckNodeOnline(self, instance.primary_node)
4632

    
4633
    # check bridges existence
4634
    _CheckInstanceBridgesExist(self, instance)
4635

    
4636
  def Exec(self, feedback_fn):
4637
    """Reboot the instance.
4638

4639
    """
4640
    instance = self.instance
4641
    ignore_secondaries = self.op.ignore_secondaries
4642
    reboot_type = self.op.reboot_type
4643

    
4644
    node_current = instance.primary_node
4645

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

    
4667
    self.cfg.MarkInstanceUp(instance.name)
4668

    
4669

    
4670
class LUShutdownInstance(LogicalUnit):
4671
  """Shutdown an instance.
4672

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

    
4682
  def ExpandNames(self):
4683
    self._ExpandAndLockInstance()
4684

    
4685
  def BuildHooksEnv(self):
4686
    """Build hooks env.
4687

4688
    This runs on master, primary and secondary nodes of the instance.
4689

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

    
4696
  def CheckPrereq(self):
4697
    """Check prerequisites.
4698

4699
    This checks that the instance is in the cluster.
4700

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

    
4707
  def Exec(self, feedback_fn):
4708
    """Shutdown the instance.
4709

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

    
4720
    _ShutdownInstanceDisks(self, instance)
4721

    
4722

    
4723
class LUReinstallInstance(LogicalUnit):
4724
  """Reinstall an instance.
4725

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

    
4736
  def ExpandNames(self):
4737
    self._ExpandAndLockInstance()
4738

    
4739
  def BuildHooksEnv(self):
4740
    """Build hooks env.
4741

4742
    This runs on master, primary and secondary nodes of the instance.
4743

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

    
4749
  def CheckPrereq(self):
4750
    """Check prerequisites.
4751

4752
    This checks that the instance is in the cluster and is not running.
4753

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

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

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

    
4771
    self.instance = instance
4772

    
4773
  def Exec(self, feedback_fn):
4774
    """Reinstall the instance.
4775

4776
    """
4777
    inst = self.instance
4778

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

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

    
4795

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

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

    
4808
  def ExpandNames(self):
4809
    self._ExpandAndLockInstance()
4810

    
4811
  def BuildHooksEnv(self):
4812
    """Build hooks env.
4813

4814
    This runs on master, primary and secondary nodes of the instance.
4815

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

    
4821
  def CheckPrereq(self):
4822
    """Check prerequisites.
4823

4824
    This checks that the instance is in the cluster and is not running.
4825

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

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

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

    
4845
    self.instance = instance
4846

    
4847
  def Exec(self, feedback_fn):
4848
    """Recreate the disks.
4849

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

    
4857
    _CreateDisks(self, self.instance, to_skip=to_skip)
4858

    
4859

    
4860
class LURenameInstance(LogicalUnit):
4861
  """Rename an instance.
4862

4863
  """
4864
  HPATH = "instance-rename"
4865
  HTYPE = constants.HTYPE_INSTANCE
4866
  _OP_PARAMS = [
4867
    _PInstanceName,
4868
    ("new_name", _NoDefault, _TNonEmptyString),
4869
    ("ignore_ip", False, _TBool),
4870
    ("check_name", True, _TBool),
4871
    ]
4872

    
4873
  def BuildHooksEnv(self):
4874
    """Build hooks env.
4875

4876
    This runs on master, primary and secondary nodes of the instance.
4877

4878
    """
4879
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4880
    env["INSTANCE_NEW_NAME"] = self.op.new_name
4881
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4882
    return env, nl, nl
4883

    
4884
  def CheckPrereq(self):
4885
    """Check prerequisites.
4886

4887
    This checks that the instance is in the cluster and is not running.
4888

4889
    """
4890
    self.op.instance_name = _ExpandInstanceName(self.cfg,
4891
                                                self.op.instance_name)
4892
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4893
    assert instance is not None
4894
    _CheckNodeOnline(self, instance.primary_node)
4895
    _CheckInstanceDown(self, instance, "cannot rename")
4896
    self.instance = instance
4897

    
4898
    # new name verification
4899
    if self.op.check_name:
4900
      name_info = netutils.GetHostInfo(self.op.new_name)
4901
      self.op.new_name = name_info.name
4902

    
4903
    new_name = self.op.new_name
4904

    
4905
    instance_list = self.cfg.GetInstanceList()
4906
    if new_name in instance_list:
4907
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4908
                                 new_name, errors.ECODE_EXISTS)
4909

    
4910
    if not self.op.ignore_ip:
4911
      if netutils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
4912
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4913
                                   (name_info.ip, new_name),
4914
                                   errors.ECODE_NOTUNIQUE)
4915

    
4916
  def Exec(self, feedback_fn):
4917
    """Reinstall the instance.
4918

4919
    """
4920
    inst = self.instance
4921
    old_name = inst.name
4922

    
4923
    if inst.disk_template == constants.DT_FILE:
4924
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4925

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

    
4931
    # re-read the instance from the configuration after rename
4932
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
4933

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

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

    
4957

    
4958
class LURemoveInstance(LogicalUnit):
4959
  """Remove an instance.
4960

4961
  """
4962
  HPATH = "instance-remove"
4963
  HTYPE = constants.HTYPE_INSTANCE
4964
  _OP_PARAMS = [
4965
    _PInstanceName,
4966
    ("ignore_failures", False, _TBool),
4967
    _PShutdownTimeout,
4968
    ]
4969
  REQ_BGL = False
4970

    
4971
  def ExpandNames(self):
4972
    self._ExpandAndLockInstance()
4973
    self.needed_locks[locking.LEVEL_NODE] = []
4974
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4975

    
4976
  def DeclareLocks(self, level):
4977
    if level == locking.LEVEL_NODE:
4978
      self._LockInstancesNodes()
4979

    
4980
  def BuildHooksEnv(self):
4981
    """Build hooks env.
4982

4983
    This runs on master, primary and secondary nodes of the instance.
4984

4985
    """
4986
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4987
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
4988
    nl = [self.cfg.GetMasterNode()]
4989
    nl_post = list(self.instance.all_nodes) + nl
4990
    return env, nl, nl_post
4991

    
4992
  def CheckPrereq(self):
4993
    """Check prerequisites.
4994

4995
    This checks that the instance is in the cluster.
4996

4997
    """
4998
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4999
    assert self.instance is not None, \
5000
      "Cannot retrieve locked instance %s" % self.op.instance_name
5001

    
5002
  def Exec(self, feedback_fn):
5003
    """Remove the instance.
5004

5005
    """
5006
    instance = self.instance
5007
    logging.info("Shutting down instance %s on node %s",
5008
                 instance.name, instance.primary_node)
5009

    
5010
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5011
                                             self.op.shutdown_timeout)
5012
    msg = result.fail_msg
5013
    if msg:
5014
      if self.op.ignore_failures:
5015
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5016
      else:
5017
        raise errors.OpExecError("Could not shutdown instance %s on"
5018
                                 " node %s: %s" %
5019
                                 (instance.name, instance.primary_node, msg))
5020

    
5021
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5022

    
5023

    
5024
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5025
  """Utility function to remove an instance.
5026

5027
  """
5028
  logging.info("Removing block devices for instance %s", instance.name)
5029

    
5030
  if not _RemoveDisks(lu, instance):
5031
    if not ignore_failures:
5032
      raise errors.OpExecError("Can't remove instance's disks")
5033
    feedback_fn("Warning: can't remove instance's disks")
5034

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

    
5037
  lu.cfg.RemoveInstance(instance.name)
5038

    
5039
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5040
    "Instance lock removal conflict"
5041

    
5042
  # Remove lock for the instance
5043
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5044

    
5045

    
5046
class LUQueryInstances(NoHooksLU):
5047
  """Logical unit for querying instances.
5048

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

    
5083

    
5084
  def CheckArguments(self):
5085
    _CheckOutputFields(static=self._FIELDS_STATIC,
5086
                       dynamic=self._FIELDS_DYNAMIC,
5087
                       selected=self.op.output_fields)
5088

    
5089
  def ExpandNames(self):
5090
    self.needed_locks = {}
5091
    self.share_locks[locking.LEVEL_INSTANCE] = 1
5092
    self.share_locks[locking.LEVEL_NODE] = 1
5093

    
5094
    if self.op.names:
5095
      self.wanted = _GetWantedInstances(self, self.op.names)
5096
    else:
5097
      self.wanted = locking.ALL_SET
5098

    
5099
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
5100
    self.do_locking = self.do_node_query and self.op.use_locking
5101
    if self.do_locking:
5102
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
5103
      self.needed_locks[locking.LEVEL_NODE] = []
5104
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5105

    
5106
  def DeclareLocks(self, level):
5107
    if level == locking.LEVEL_NODE and self.do_locking:
5108
      self._LockInstancesNodes()
5109

    
5110
  def Exec(self, feedback_fn):
5111
    """Computes the list of nodes and their attributes.
5112

5113
    """
5114
    # pylint: disable-msg=R0912
5115
    # way too many branches here
5116
    all_info = self.cfg.GetAllInstancesInfo()
5117
    if self.wanted == locking.ALL_SET:
5118
      # caller didn't specify instance names, so ordering is not important
5119
      if self.do_locking:
5120
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5121
      else:
5122
        instance_names = all_info.keys()
5123
      instance_names = utils.NiceSort(instance_names)
5124
    else:
5125
      # caller did specify names, so we must keep the ordering
5126
      if self.do_locking:
5127
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
5128
      else:
5129
        tgt_set = all_info.keys()
5130
      missing = set(self.wanted).difference(tgt_set)
5131
      if missing:
5132
        raise errors.OpExecError("Some instances were removed before"
5133
                                 " retrieving their data: %s" % missing)
5134
      instance_names = self.wanted
5135

    
5136
    instance_list = [all_info[iname] for iname in instance_names]
5137

    
5138
    # begin data gathering
5139

    
5140
    nodes = frozenset([inst.primary_node for inst in instance_list])
5141
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
5142

    
5143
    bad_nodes = []
5144
    off_nodes = []
5145
    if self.do_node_query:
5146
      live_data = {}
5147
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
5148
      for name in nodes:
5149
        result = node_data[name]
5150
        if result.offline:
5151
          # offline nodes will be in both lists
5152
          off_nodes.append(name)
5153
        if result.fail_msg:
5154
          bad_nodes.append(name)
5155
        else:
5156
          if result.payload:
5157
            live_data.update(result.payload)
5158
          # else no instance is alive
5159
    else:
5160
      live_data = dict([(name, {}) for name in instance_names])
5161

    
5162
    # end data gathering
5163

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

    
5334
    return output
5335

    
5336

    
5337
class LUFailoverInstance(LogicalUnit):
5338
  """Failover an instance.
5339

5340
  """
5341
  HPATH = "instance-failover"
5342
  HTYPE = constants.HTYPE_INSTANCE
5343
  _OP_PARAMS = [
5344
    _PInstanceName,
5345
    ("ignore_consistency", False, _TBool),
5346
    _PShutdownTimeout,
5347
    ]
5348
  REQ_BGL = False
5349

    
5350
  def ExpandNames(self):
5351
    self._ExpandAndLockInstance()
5352
    self.needed_locks[locking.LEVEL_NODE] = []
5353
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5354

    
5355
  def DeclareLocks(self, level):
5356
    if level == locking.LEVEL_NODE:
5357
      self._LockInstancesNodes()
5358

    
5359
  def BuildHooksEnv(self):
5360
    """Build hooks env.
5361

5362
    This runs on master, primary and secondary nodes of the instance.
5363

5364
    """
5365
    instance = self.instance
5366
    source_node = instance.primary_node
5367
    target_node = instance.secondary_nodes[0]
5368
    env = {
5369
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5370
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5371
      "OLD_PRIMARY": source_node,
5372
      "OLD_SECONDARY": target_node,
5373
      "NEW_PRIMARY": target_node,
5374
      "NEW_SECONDARY": source_node,
5375
      }
5376
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5377
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5378
    nl_post = list(nl)
5379
    nl_post.append(source_node)
5380
    return env, nl, nl_post
5381

    
5382
  def CheckPrereq(self):
5383
    """Check prerequisites.
5384

5385
    This checks that the instance is in the cluster.
5386

5387
    """
5388
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5389
    assert self.instance is not None, \
5390
      "Cannot retrieve locked instance %s" % self.op.instance_name
5391

    
5392
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5393
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5394
      raise errors.OpPrereqError("Instance's disk layout is not"
5395
                                 " network mirrored, cannot failover.",
5396
                                 errors.ECODE_STATE)
5397

    
5398
    secondary_nodes = instance.secondary_nodes
5399
    if not secondary_nodes:
5400
      raise errors.ProgrammerError("no secondary node but using "
5401
                                   "a mirrored disk template")
5402

    
5403
    target_node = secondary_nodes[0]
5404
    _CheckNodeOnline(self, target_node)
5405
    _CheckNodeNotDrained(self, target_node)
5406
    if instance.admin_up:
5407
      # check memory requirements on the secondary node
5408
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5409
                           instance.name, bep[constants.BE_MEMORY],
5410
                           instance.hypervisor)
5411
    else:
5412
      self.LogInfo("Not checking memory on the secondary node as"
5413
                   " instance will not be started")
5414

    
5415
    # check bridge existance
5416
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5417

    
5418
  def Exec(self, feedback_fn):
5419
    """Failover an instance.
5420

5421
    The failover is done by shutting it down on its present node and
5422
    starting it on the secondary.
5423

5424
    """
5425
    instance = self.instance
5426

    
5427
    source_node = instance.primary_node
5428
    target_node = instance.secondary_nodes[0]
5429

    
5430
    if instance.admin_up:
5431
      feedback_fn("* checking disk consistency between source and target")
5432
      for dev in instance.disks:
5433
        # for drbd, these are drbd over lvm
5434
        if not _CheckDiskConsistency(self, dev, target_node, False):
5435
          if not self.op.ignore_consistency:
5436
            raise errors.OpExecError("Disk %s is degraded on target node,"
5437
                                     " aborting failover." % dev.iv_name)
5438
    else:
5439
      feedback_fn("* not checking disk consistency as instance is not running")
5440

    
5441
    feedback_fn("* shutting down instance on source node")
5442
    logging.info("Shutting down instance %s on node %s",
5443
                 instance.name, source_node)
5444

    
5445
    result = self.rpc.call_instance_shutdown(source_node, instance,
5446
                                             self.op.shutdown_timeout)
5447
    msg = result.fail_msg
5448
    if msg:
5449
      if self.op.ignore_consistency:
5450
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5451
                             " Proceeding anyway. Please make sure node"
5452
                             " %s is down. Error details: %s",
5453
                             instance.name, source_node, source_node, msg)
5454
      else:
5455
        raise errors.OpExecError("Could not shutdown instance %s on"
5456
                                 " node %s: %s" %
5457
                                 (instance.name, source_node, msg))
5458

    
5459
    feedback_fn("* deactivating the instance's disks on source node")
5460
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5461
      raise errors.OpExecError("Can't shut down the instance's disks.")
5462

    
5463
    instance.primary_node = target_node
5464
    # distribute new instance config to the other nodes
5465
    self.cfg.Update(instance, feedback_fn)
5466

    
5467
    # Only start the instance if it's marked as up
5468
    if instance.admin_up:
5469
      feedback_fn("* activating the instance's disks on target node")
5470
      logging.info("Starting instance %s on node %s",
5471
                   instance.name, target_node)
5472

    
5473
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5474
                                           ignore_secondaries=True)
5475
      if not disks_ok:
5476
        _ShutdownInstanceDisks(self, instance)
5477
        raise errors.OpExecError("Can't activate the instance's disks")
5478

    
5479
      feedback_fn("* starting the instance on the target node")
5480
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5481
      msg = result.fail_msg
5482
      if msg:
5483
        _ShutdownInstanceDisks(self, instance)
5484
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5485
                                 (instance.name, target_node, msg))
5486

    
5487

    
5488
class LUMigrateInstance(LogicalUnit):
5489
  """Migrate an instance.
5490

5491
  This is migration without shutting down, compared to the failover,
5492
  which is done with shutdown.
5493

5494
  """
5495
  HPATH = "instance-migrate"
5496
  HTYPE = constants.HTYPE_INSTANCE
5497
  _OP_PARAMS = [
5498
    _PInstanceName,
5499
    _PMigrationMode,
5500
    ("cleanup", False, _TBool),
5501
    ]
5502

    
5503
  REQ_BGL = False
5504

    
5505
  def ExpandNames(self):
5506
    self._ExpandAndLockInstance()
5507

    
5508
    self.needed_locks[locking.LEVEL_NODE] = []
5509
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5510

    
5511
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5512
                                       self.op.cleanup)
5513
    self.tasklets = [self._migrater]
5514

    
5515
  def DeclareLocks(self, level):
5516
    if level == locking.LEVEL_NODE:
5517
      self._LockInstancesNodes()
5518

    
5519
  def BuildHooksEnv(self):
5520
    """Build hooks env.
5521

5522
    This runs on master, primary and secondary nodes of the instance.
5523

5524
    """
5525
    instance = self._migrater.instance
5526
    source_node = instance.primary_node
5527
    target_node = instance.secondary_nodes[0]
5528
    env = _BuildInstanceHookEnvByObject(self, instance)
5529
    env["MIGRATE_LIVE"] = self._migrater.live
5530
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5531
    env.update({
5532
        "OLD_PRIMARY": source_node,
5533
        "OLD_SECONDARY": target_node,
5534
        "NEW_PRIMARY": target_node,
5535
        "NEW_SECONDARY": source_node,
5536
        })
5537
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5538
    nl_post = list(nl)
5539
    nl_post.append(source_node)
5540
    return env, nl, nl_post
5541

    
5542

    
5543
class LUMoveInstance(LogicalUnit):
5544
  """Move an instance by data-copying.
5545

5546
  """
5547
  HPATH = "instance-move"
5548
  HTYPE = constants.HTYPE_INSTANCE
5549
  _OP_PARAMS = [
5550
    _PInstanceName,
5551
    ("target_node", _NoDefault, _TNonEmptyString),
5552
    _PShutdownTimeout,
5553
    ]
5554
  REQ_BGL = False
5555

    
5556
  def ExpandNames(self):
5557
    self._ExpandAndLockInstance()
5558
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5559
    self.op.target_node = target_node
5560
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5561
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5562

    
5563
  def DeclareLocks(self, level):
5564
    if level == locking.LEVEL_NODE:
5565
      self._LockInstancesNodes(primary_only=True)
5566

    
5567
  def BuildHooksEnv(self):
5568
    """Build hooks env.
5569

5570
    This runs on master, primary and secondary nodes of the instance.
5571

5572
    """
5573
    env = {
5574
      "TARGET_NODE": self.op.target_node,
5575
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5576
      }
5577
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5578
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5579
                                       self.op.target_node]
5580
    return env, nl, nl
5581

    
5582
  def CheckPrereq(self):
5583
    """Check prerequisites.
5584

5585
    This checks that the instance is in the cluster.
5586

5587
    """
5588
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5589
    assert self.instance is not None, \
5590
      "Cannot retrieve locked instance %s" % self.op.instance_name
5591

    
5592
    node = self.cfg.GetNodeInfo(self.op.target_node)
5593
    assert node is not None, \
5594
      "Cannot retrieve locked node %s" % self.op.target_node
5595

    
5596
    self.target_node = target_node = node.name
5597

    
5598
    if target_node == instance.primary_node:
5599
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5600
                                 (instance.name, target_node),
5601
                                 errors.ECODE_STATE)
5602

    
5603
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5604

    
5605
    for idx, dsk in enumerate(instance.disks):
5606
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5607
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5608
                                   " cannot copy" % idx, errors.ECODE_STATE)
5609

    
5610
    _CheckNodeOnline(self, target_node)
5611
    _CheckNodeNotDrained(self, target_node)
5612

    
5613
    if instance.admin_up:
5614
      # check memory requirements on the secondary node
5615
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5616
                           instance.name, bep[constants.BE_MEMORY],
5617
                           instance.hypervisor)
5618
    else:
5619
      self.LogInfo("Not checking memory on the secondary node as"
5620
                   " instance will not be started")
5621

    
5622
    # check bridge existance
5623
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5624

    
5625
  def Exec(self, feedback_fn):
5626
    """Move an instance.
5627

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

5631
    """
5632
    instance = self.instance
5633

    
5634
    source_node = instance.primary_node
5635
    target_node = self.target_node
5636

    
5637
    self.LogInfo("Shutting down instance %s on source node %s",
5638
                 instance.name, source_node)
5639

    
5640
    result = self.rpc.call_instance_shutdown(source_node, instance,
5641
                                             self.op.shutdown_timeout)
5642
    msg = result.fail_msg
5643
    if msg:
5644
      if self.op.ignore_consistency:
5645
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5646
                             " Proceeding anyway. Please make sure node"
5647
                             " %s is down. Error details: %s",
5648
                             instance.name, source_node, source_node, msg)
5649
      else:
5650
        raise errors.OpExecError("Could not shutdown instance %s on"
5651
                                 " node %s: %s" %
5652
                                 (instance.name, source_node, msg))
5653

    
5654
    # create the target disks
5655
    try:
5656
      _CreateDisks(self, instance, target_node=target_node)
5657
    except errors.OpExecError:
5658
      self.LogWarning("Device creation failed, reverting...")
5659
      try:
5660
        _RemoveDisks(self, instance, target_node=target_node)
5661
      finally:
5662
        self.cfg.ReleaseDRBDMinors(instance.name)
5663
        raise
5664

    
5665
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5666

    
5667
    errs = []
5668
    # activate, get path, copy the data over
5669
    for idx, disk in enumerate(instance.disks):
5670
      self.LogInfo("Copying data for disk %d", idx)
5671
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5672
                                               instance.name, True)
5673
      if result.fail_msg:
5674
        self.LogWarning("Can't assemble newly created disk %d: %s",
5675
                        idx, result.fail_msg)
5676
        errs.append(result.fail_msg)
5677
        break
5678
      dev_path = result.payload
5679
      result = self.rpc.call_blockdev_export(source_node, disk,
5680
                                             target_node, dev_path,
5681
                                             cluster_name)
5682
      if result.fail_msg:
5683
        self.LogWarning("Can't copy data over for disk %d: %s",
5684
                        idx, result.fail_msg)
5685
        errs.append(result.fail_msg)
5686
        break
5687

    
5688
    if errs:
5689
      self.LogWarning("Some disks failed to copy, aborting")
5690
      try:
5691
        _RemoveDisks(self, instance, target_node=target_node)
5692
      finally:
5693
        self.cfg.ReleaseDRBDMinors(instance.name)
5694
        raise errors.OpExecError("Errors during disk copy: %s" %
5695
                                 (",".join(errs),))
5696

    
5697
    instance.primary_node = target_node
5698
    self.cfg.Update(instance, feedback_fn)
5699

    
5700
    self.LogInfo("Removing the disks on the original node")
5701
    _RemoveDisks(self, instance, target_node=source_node)
5702

    
5703
    # Only start the instance if it's marked as up
5704
    if instance.admin_up:
5705
      self.LogInfo("Starting instance %s on node %s",
5706
                   instance.name, target_node)
5707

    
5708
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5709
                                           ignore_secondaries=True)
5710
      if not disks_ok:
5711
        _ShutdownInstanceDisks(self, instance)
5712
        raise errors.OpExecError("Can't activate the instance's disks")
5713

    
5714
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5715
      msg = result.fail_msg
5716
      if msg:
5717
        _ShutdownInstanceDisks(self, instance)
5718
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5719
                                 (instance.name, target_node, msg))
5720

    
5721

    
5722
class LUMigrateNode(LogicalUnit):
5723
  """Migrate all instances from a node.
5724

5725
  """
5726
  HPATH = "node-migrate"
5727
  HTYPE = constants.HTYPE_NODE
5728
  _OP_PARAMS = [
5729
    _PNodeName,
5730
    _PMigrationMode,
5731
    ]
5732
  REQ_BGL = False
5733

    
5734
  def ExpandNames(self):
5735
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5736

    
5737
    self.needed_locks = {
5738
      locking.LEVEL_NODE: [self.op.node_name],
5739
      }
5740

    
5741
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5742

    
5743
    # Create tasklets for migrating instances for all instances on this node
5744
    names = []
5745
    tasklets = []
5746

    
5747
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5748
      logging.debug("Migrating instance %s", inst.name)
5749
      names.append(inst.name)
5750

    
5751
      tasklets.append(TLMigrateInstance(self, inst.name, False))
5752

    
5753
    self.tasklets = tasklets
5754

    
5755
    # Declare instance locks
5756
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5757

    
5758
  def DeclareLocks(self, level):
5759
    if level == locking.LEVEL_NODE:
5760
      self._LockInstancesNodes()
5761

    
5762
  def BuildHooksEnv(self):
5763
    """Build hooks env.
5764

5765
    This runs on the master, the primary and all the secondaries.
5766

5767
    """
5768
    env = {
5769
      "NODE_NAME": self.op.node_name,
5770
      }
5771

    
5772
    nl = [self.cfg.GetMasterNode()]
5773

    
5774
    return (env, nl, nl)
5775

    
5776

    
5777
class TLMigrateInstance(Tasklet):
5778
  """Tasklet class for instance migration.
5779

5780
  @type live: boolean
5781
  @ivar live: whether the migration will be done live or non-live;
5782
      this variable is initalized only after CheckPrereq has run
5783

5784
  """
5785
  def __init__(self, lu, instance_name, cleanup):
5786
    """Initializes this class.
5787

5788
    """
5789
    Tasklet.__init__(self, lu)
5790

    
5791
    # Parameters
5792
    self.instance_name = instance_name
5793
    self.cleanup = cleanup
5794
    self.live = False # will be overridden later
5795

    
5796
  def CheckPrereq(self):
5797
    """Check prerequisites.
5798

5799
    This checks that the instance is in the cluster.
5800

5801
    """
5802
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
5803
    instance = self.cfg.GetInstanceInfo(instance_name)
5804
    assert instance is not None
5805

    
5806
    if instance.disk_template != constants.DT_DRBD8:
5807
      raise errors.OpPrereqError("Instance's disk layout is not"
5808
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5809

    
5810
    secondary_nodes = instance.secondary_nodes
5811
    if not secondary_nodes:
5812
      raise errors.ConfigurationError("No secondary node but using"
5813
                                      " drbd8 disk template")
5814

    
5815
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5816

    
5817
    target_node = secondary_nodes[0]
5818
    # check memory requirements on the secondary node
5819
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
5820
                         instance.name, i_be[constants.BE_MEMORY],
5821
                         instance.hypervisor)
5822

    
5823
    # check bridge existance
5824
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
5825

    
5826
    if not self.cleanup:
5827
      _CheckNodeNotDrained(self.lu, target_node)
5828
      result = self.rpc.call_instance_migratable(instance.primary_node,
5829
                                                 instance)
5830
      result.Raise("Can't migrate, please use failover",
5831
                   prereq=True, ecode=errors.ECODE_STATE)
5832

    
5833
    self.instance = instance
5834

    
5835
    if self.lu.op.mode is None:
5836
      # read the default value from the hypervisor
5837
      i_hv = self.cfg.GetClusterInfo().FillHV(instance, skip_globals=False)
5838
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
5839

    
5840
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
5841

    
5842
  def _WaitUntilSync(self):
5843
    """Poll with custom rpc for disk sync.
5844

5845
    This uses our own step-based rpc call.
5846

5847
    """
5848
    self.feedback_fn("* wait until resync is done")
5849
    all_done = False
5850
    while not all_done:
5851
      all_done = True
5852
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
5853
                                            self.nodes_ip,
5854
                                            self.instance.disks)
5855
      min_percent = 100
5856
      for node, nres in result.items():
5857
        nres.Raise("Cannot resync disks on node %s" % node)
5858
        node_done, node_percent = nres.payload
5859
        all_done = all_done and node_done
5860
        if node_percent is not None:
5861
          min_percent = min(min_percent, node_percent)
5862
      if not all_done:
5863
        if min_percent < 100:
5864
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
5865
        time.sleep(2)
5866

    
5867
  def _EnsureSecondary(self, node):
5868
    """Demote a node to secondary.
5869

5870
    """
5871
    self.feedback_fn("* switching node %s to secondary mode" % node)
5872

    
5873
    for dev in self.instance.disks:
5874
      self.cfg.SetDiskID(dev, node)
5875

    
5876
    result = self.rpc.call_blockdev_close(node, self.instance.name,
5877
                                          self.instance.disks)
5878
    result.Raise("Cannot change disk to secondary on node %s" % node)
5879

    
5880
  def _GoStandalone(self):
5881
    """Disconnect from the network.
5882

5883
    """
5884
    self.feedback_fn("* changing into standalone mode")
5885
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
5886
                                               self.instance.disks)
5887
    for node, nres in result.items():
5888
      nres.Raise("Cannot disconnect disks node %s" % node)
5889

    
5890
  def _GoReconnect(self, multimaster):
5891
    """Reconnect to the network.
5892

5893
    """
5894
    if multimaster:
5895
      msg = "dual-master"
5896
    else:
5897
      msg = "single-master"
5898
    self.feedback_fn("* changing disks into %s mode" % msg)
5899
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
5900
                                           self.instance.disks,
5901
                                           self.instance.name, multimaster)
5902
    for node, nres in result.items():
5903
      nres.Raise("Cannot change disks config on node %s" % node)
5904

    
5905
  def _ExecCleanup(self):
5906
    """Try to cleanup after a failed migration.
5907

5908
    The cleanup is done by:
5909
      - check that the instance is running only on one node
5910
        (and update the config if needed)
5911
      - change disks on its secondary node to secondary
5912
      - wait until disks are fully synchronized
5913
      - disconnect from the network
5914
      - change disks into single-master mode
5915
      - wait again until disks are fully synchronized
5916

5917
    """
5918
    instance = self.instance
5919
    target_node = self.target_node
5920
    source_node = self.source_node
5921

    
5922
    # check running on only one node
5923
    self.feedback_fn("* checking where the instance actually runs"
5924
                     " (if this hangs, the hypervisor might be in"
5925
                     " a bad state)")
5926
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
5927
    for node, result in ins_l.items():
5928
      result.Raise("Can't contact node %s" % node)
5929

    
5930
    runningon_source = instance.name in ins_l[source_node].payload
5931
    runningon_target = instance.name in ins_l[target_node].payload
5932

    
5933
    if runningon_source and runningon_target:
5934
      raise errors.OpExecError("Instance seems to be running on two nodes,"
5935
                               " or the hypervisor is confused. You will have"
5936
                               " to ensure manually that it runs only on one"
5937
                               " and restart this operation.")
5938

    
5939
    if not (runningon_source or runningon_target):
5940
      raise errors.OpExecError("Instance does not seem to be running at all."
5941
                               " In this case, it's safer to repair by"
5942
                               " running 'gnt-instance stop' to ensure disk"
5943
                               " shutdown, and then restarting it.")
5944

    
5945
    if runningon_target:
5946
      # the migration has actually succeeded, we need to update the config
5947
      self.feedback_fn("* instance running on secondary node (%s),"
5948
                       " updating config" % target_node)
5949
      instance.primary_node = target_node
5950
      self.cfg.Update(instance, self.feedback_fn)
5951
      demoted_node = source_node
5952
    else:
5953
      self.feedback_fn("* instance confirmed to be running on its"
5954
                       " primary node (%s)" % source_node)
5955
      demoted_node = target_node
5956

    
5957
    self._EnsureSecondary(demoted_node)
5958
    try:
5959
      self._WaitUntilSync()
5960
    except errors.OpExecError:
5961
      # we ignore here errors, since if the device is standalone, it
5962
      # won't be able to sync
5963
      pass
5964
    self._GoStandalone()
5965
    self._GoReconnect(False)
5966
    self._WaitUntilSync()
5967

    
5968
    self.feedback_fn("* done")
5969

    
5970
  def _RevertDiskStatus(self):
5971
    """Try to revert the disk status after a failed migration.
5972

5973
    """
5974
    target_node = self.target_node
5975
    try:
5976
      self._EnsureSecondary(target_node)
5977
      self._GoStandalone()
5978
      self._GoReconnect(False)
5979
      self._WaitUntilSync()
5980
    except errors.OpExecError, err:
5981
      self.lu.LogWarning("Migration failed and I can't reconnect the"
5982
                         " drives: error '%s'\n"
5983
                         "Please look and recover the instance status" %
5984
                         str(err))
5985

    
5986
  def _AbortMigration(self):
5987
    """Call the hypervisor code to abort a started migration.
5988

5989
    """
5990
    instance = self.instance
5991
    target_node = self.target_node
5992
    migration_info = self.migration_info
5993

    
5994
    abort_result = self.rpc.call_finalize_migration(target_node,
5995
                                                    instance,
5996
                                                    migration_info,
5997
                                                    False)
5998
    abort_msg = abort_result.fail_msg
5999
    if abort_msg:
6000
      logging.error("Aborting migration failed on target node %s: %s",
6001
                    target_node, abort_msg)
6002
      # Don't raise an exception here, as we stil have to try to revert the
6003
      # disk status, even if this step failed.
6004

    
6005
  def _ExecMigration(self):
6006
    """Migrate an instance.
6007

6008
    The migrate is done by:
6009
      - change the disks into dual-master mode
6010
      - wait until disks are fully synchronized again
6011
      - migrate the instance
6012
      - change disks on the new secondary node (the old primary) to secondary
6013
      - wait until disks are fully synchronized
6014
      - change disks into single-master mode
6015

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

    
6021
    self.feedback_fn("* checking disk consistency between source and target")
6022
    for dev in instance.disks:
6023
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6024
        raise errors.OpExecError("Disk %s is degraded or not fully"
6025
                                 " synchronized on target node,"
6026
                                 " aborting migrate." % dev.iv_name)
6027

    
6028
    # First get the migration information from the remote node
6029
    result = self.rpc.call_migration_info(source_node, instance)
6030
    msg = result.fail_msg
6031
    if msg:
6032
      log_err = ("Failed fetching source migration information from %s: %s" %
6033
                 (source_node, msg))
6034
      logging.error(log_err)
6035
      raise errors.OpExecError(log_err)
6036

    
6037
    self.migration_info = migration_info = result.payload
6038

    
6039
    # Then switch the disks to master/master mode
6040
    self._EnsureSecondary(target_node)
6041
    self._GoStandalone()
6042
    self._GoReconnect(True)
6043
    self._WaitUntilSync()
6044

    
6045
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6046
    result = self.rpc.call_accept_instance(target_node,
6047
                                           instance,
6048
                                           migration_info,
6049
                                           self.nodes_ip[target_node])
6050

    
6051
    msg = result.fail_msg
6052
    if msg:
6053
      logging.error("Instance pre-migration failed, trying to revert"
6054
                    " disk status: %s", msg)
6055
      self.feedback_fn("Pre-migration failed, aborting")
6056
      self._AbortMigration()
6057
      self._RevertDiskStatus()
6058
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6059
                               (instance.name, msg))
6060

    
6061
    self.feedback_fn("* migrating instance to %s" % target_node)
6062
    time.sleep(10)
6063
    result = self.rpc.call_instance_migrate(source_node, instance,
6064
                                            self.nodes_ip[target_node],
6065
                                            self.live)
6066
    msg = result.fail_msg
6067
    if msg:
6068
      logging.error("Instance migration failed, trying to revert"
6069
                    " disk status: %s", msg)
6070
      self.feedback_fn("Migration failed, aborting")
6071
      self._AbortMigration()
6072
      self._RevertDiskStatus()
6073
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6074
                               (instance.name, msg))
6075
    time.sleep(10)
6076

    
6077
    instance.primary_node = target_node
6078
    # distribute new instance config to the other nodes
6079
    self.cfg.Update(instance, self.feedback_fn)
6080

    
6081
    result = self.rpc.call_finalize_migration(target_node,
6082
                                              instance,
6083
                                              migration_info,
6084
                                              True)
6085
    msg = result.fail_msg
6086
    if msg:
6087
      logging.error("Instance migration succeeded, but finalization failed:"
6088
                    " %s", msg)
6089
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6090
                               msg)
6091

    
6092
    self._EnsureSecondary(source_node)
6093
    self._WaitUntilSync()
6094
    self._GoStandalone()
6095
    self._GoReconnect(False)
6096
    self._WaitUntilSync()
6097

    
6098
    self.feedback_fn("* done")
6099

    
6100
  def Exec(self, feedback_fn):
6101
    """Perform the migration.
6102

6103
    """
6104
    feedback_fn("Migrating instance %s" % self.instance.name)
6105

    
6106
    self.feedback_fn = feedback_fn
6107

    
6108
    self.source_node = self.instance.primary_node
6109
    self.target_node = self.instance.secondary_nodes[0]
6110
    self.all_nodes = [self.source_node, self.target_node]
6111
    self.nodes_ip = {
6112
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6113
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6114
      }
6115

    
6116
    if self.cleanup:
6117
      return self._ExecCleanup()
6118
    else:
6119
      return self._ExecMigration()
6120

    
6121

    
6122
def _CreateBlockDev(lu, node, instance, device, force_create,
6123
                    info, force_open):
6124
  """Create a tree of block devices on a given node.
6125

6126
  If this device type has to be created on secondaries, create it and
6127
  all its children.
6128

6129
  If not, just recurse to children keeping the same 'force' value.
6130

6131
  @param lu: the lu on whose behalf we execute
6132
  @param node: the node on which to create the device
6133
  @type instance: L{objects.Instance}
6134
  @param instance: the instance which owns the device
6135
  @type device: L{objects.Disk}
6136
  @param device: the device to create
6137
  @type force_create: boolean
6138
  @param force_create: whether to force creation of this device; this
6139
      will be change to True whenever we find a device which has
6140
      CreateOnSecondary() attribute
6141
  @param info: the extra 'metadata' we should attach to the device
6142
      (this will be represented as a LVM tag)
6143
  @type force_open: boolean
6144
  @param force_open: this parameter will be passes to the
6145
      L{backend.BlockdevCreate} function where it specifies
6146
      whether we run on primary or not, and it affects both
6147
      the child assembly and the device own Open() execution
6148

6149
  """
6150
  if device.CreateOnSecondary():
6151
    force_create = True
6152

    
6153
  if device.children:
6154
    for child in device.children:
6155
      _CreateBlockDev(lu, node, instance, child, force_create,
6156
                      info, force_open)
6157

    
6158
  if not force_create:
6159
    return
6160

    
6161
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6162

    
6163

    
6164
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6165
  """Create a single block device on a given node.
6166

6167
  This will not recurse over children of the device, so they must be
6168
  created in advance.
6169

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

6184
  """
6185
  lu.cfg.SetDiskID(device, node)
6186
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6187
                                       instance.name, force_open, info)
6188
  result.Raise("Can't create block device %s on"
6189
               " node %s for instance %s" % (device, node, instance.name))
6190
  if device.physical_id is None:
6191
    device.physical_id = result.payload
6192

    
6193

    
6194
def _GenerateUniqueNames(lu, exts):
6195
  """Generate a suitable LV name.
6196

6197
  This will generate a logical volume name for the given instance.
6198

6199
  """
6200
  results = []
6201
  for val in exts:
6202
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6203
    results.append("%s%s" % (new_id, val))
6204
  return results
6205

    
6206

    
6207
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
6208
                         p_minor, s_minor):
6209
  """Generate a drbd8 device complete with its children.
6210

6211
  """
6212
  port = lu.cfg.AllocatePort()
6213
  vgname = lu.cfg.GetVGName()
6214
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6215
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6216
                          logical_id=(vgname, names[0]))
6217
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6218
                          logical_id=(vgname, names[1]))
6219
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6220
                          logical_id=(primary, secondary, port,
6221
                                      p_minor, s_minor,
6222
                                      shared_secret),
6223
                          children=[dev_data, dev_meta],
6224
                          iv_name=iv_name)
6225
  return drbd_dev
6226

    
6227

    
6228
def _GenerateDiskTemplate(lu, template_name,
6229
                          instance_name, primary_node,
6230
                          secondary_nodes, disk_info,
6231
                          file_storage_dir, file_driver,
6232
                          base_index):
6233
  """Generate the entire disk layout for a given template type.
6234

6235
  """
6236
  #TODO: compute space requirements
6237

    
6238
  vgname = lu.cfg.GetVGName()
6239
  disk_count = len(disk_info)
6240
  disks = []
6241
  if template_name == constants.DT_DISKLESS:
6242
    pass
6243
  elif template_name == constants.DT_PLAIN:
6244
    if len(secondary_nodes) != 0:
6245
      raise errors.ProgrammerError("Wrong template configuration")
6246

    
6247
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6248
                                      for i in range(disk_count)])
6249
    for idx, disk in enumerate(disk_info):
6250
      disk_index = idx + base_index
6251
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6252
                              logical_id=(vgname, names[idx]),
6253
                              iv_name="disk/%d" % disk_index,
6254
                              mode=disk["mode"])
6255
      disks.append(disk_dev)
6256
  elif template_name == constants.DT_DRBD8:
6257
    if len(secondary_nodes) != 1:
6258
      raise errors.ProgrammerError("Wrong template configuration")
6259
    remote_node = secondary_nodes[0]
6260
    minors = lu.cfg.AllocateDRBDMinor(
6261
      [primary_node, remote_node] * len(disk_info), instance_name)
6262

    
6263
    names = []
6264
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6265
                                               for i in range(disk_count)]):
6266
      names.append(lv_prefix + "_data")
6267
      names.append(lv_prefix + "_meta")
6268
    for idx, disk in enumerate(disk_info):
6269
      disk_index = idx + base_index
6270
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6271
                                      disk["size"], names[idx*2:idx*2+2],
6272
                                      "disk/%d" % disk_index,
6273
                                      minors[idx*2], minors[idx*2+1])
6274
      disk_dev.mode = disk["mode"]
6275
      disks.append(disk_dev)
6276
  elif template_name == constants.DT_FILE:
6277
    if len(secondary_nodes) != 0:
6278
      raise errors.ProgrammerError("Wrong template configuration")
6279

    
6280
    _RequireFileStorage()
6281

    
6282
    for idx, disk in enumerate(disk_info):
6283
      disk_index = idx + base_index
6284
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6285
                              iv_name="disk/%d" % disk_index,
6286
                              logical_id=(file_driver,
6287
                                          "%s/disk%d" % (file_storage_dir,
6288
                                                         disk_index)),
6289
                              mode=disk["mode"])
6290
      disks.append(disk_dev)
6291
  else:
6292
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6293
  return disks
6294

    
6295

    
6296
def _GetInstanceInfoText(instance):
6297
  """Compute that text that should be added to the disk's metadata.
6298

6299
  """
6300
  return "originstname+%s" % instance.name
6301

    
6302

    
6303
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6304
  """Create all disks for an instance.
6305

6306
  This abstracts away some work from AddInstance.
6307

6308
  @type lu: L{LogicalUnit}
6309
  @param lu: the logical unit on whose behalf we execute
6310
  @type instance: L{objects.Instance}
6311
  @param instance: the instance whose disks we should create
6312
  @type to_skip: list
6313
  @param to_skip: list of indices to skip
6314
  @type target_node: string
6315
  @param target_node: if passed, overrides the target node for creation
6316
  @rtype: boolean
6317
  @return: the success of the creation
6318

6319
  """
6320
  info = _GetInstanceInfoText(instance)
6321
  if target_node is None:
6322
    pnode = instance.primary_node
6323
    all_nodes = instance.all_nodes
6324
  else:
6325
    pnode = target_node
6326
    all_nodes = [pnode]
6327

    
6328
  if instance.disk_template == constants.DT_FILE:
6329
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6330
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6331

    
6332
    result.Raise("Failed to create directory '%s' on"
6333
                 " node %s" % (file_storage_dir, pnode))
6334

    
6335
  # Note: this needs to be kept in sync with adding of disks in
6336
  # LUSetInstanceParams
6337
  for idx, device in enumerate(instance.disks):
6338
    if to_skip and idx in to_skip:
6339
      continue
6340
    logging.info("Creating volume %s for instance %s",
6341
                 device.iv_name, instance.name)
6342
    #HARDCODE
6343
    for node in all_nodes:
6344
      f_create = node == pnode
6345
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6346

    
6347

    
6348
def _RemoveDisks(lu, instance, target_node=None):
6349
  """Remove all disks for an instance.
6350

6351
  This abstracts away some work from `AddInstance()` and
6352
  `RemoveInstance()`. Note that in case some of the devices couldn't
6353
  be removed, the removal will continue with the other ones (compare
6354
  with `_CreateDisks()`).
6355

6356
  @type lu: L{LogicalUnit}
6357
  @param lu: the logical unit on whose behalf we execute
6358
  @type instance: L{objects.Instance}
6359
  @param instance: the instance whose disks we should remove
6360
  @type target_node: string
6361
  @param target_node: used to override the node on which to remove the disks
6362
  @rtype: boolean
6363
  @return: the success of the removal
6364

6365
  """
6366
  logging.info("Removing block devices for instance %s", instance.name)
6367

    
6368
  all_result = True
6369
  for device in instance.disks:
6370
    if target_node:
6371
      edata = [(target_node, device)]
6372
    else:
6373
      edata = device.ComputeNodeTree(instance.primary_node)
6374
    for node, disk in edata:
6375
      lu.cfg.SetDiskID(disk, node)
6376
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6377
      if msg:
6378
        lu.LogWarning("Could not remove block device %s on node %s,"
6379
                      " continuing anyway: %s", device.iv_name, node, msg)
6380
        all_result = False
6381

    
6382
  if instance.disk_template == constants.DT_FILE:
6383
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6384
    if target_node:
6385
      tgt = target_node
6386
    else:
6387
      tgt = instance.primary_node
6388
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6389
    if result.fail_msg:
6390
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6391
                    file_storage_dir, instance.primary_node, result.fail_msg)
6392
      all_result = False
6393

    
6394
  return all_result
6395

    
6396

    
6397
def _ComputeDiskSize(disk_template, disks):
6398
  """Compute disk size requirements in the volume group
6399

6400
  """
6401
  # Required free disk space as a function of disk and swap space
6402
  req_size_dict = {
6403
    constants.DT_DISKLESS: None,
6404
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6405
    # 128 MB are added for drbd metadata for each disk
6406
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6407
    constants.DT_FILE: None,
6408
  }
6409

    
6410
  if disk_template not in req_size_dict:
6411
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6412
                                 " is unknown" %  disk_template)
6413

    
6414
  return req_size_dict[disk_template]
6415

    
6416

    
6417
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6418
  """Hypervisor parameter validation.
6419

6420
  This function abstract the hypervisor parameter validation to be
6421
  used in both instance create and instance modify.
6422

6423
  @type lu: L{LogicalUnit}
6424
  @param lu: the logical unit for which we check
6425
  @type nodenames: list
6426
  @param nodenames: the list of nodes on which we should check
6427
  @type hvname: string
6428
  @param hvname: the name of the hypervisor we should use
6429
  @type hvparams: dict
6430
  @param hvparams: the parameters which we need to check
6431
  @raise errors.OpPrereqError: if the parameters are not valid
6432

6433
  """
6434
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6435
                                                  hvname,
6436
                                                  hvparams)
6437
  for node in nodenames:
6438
    info = hvinfo[node]
6439
    if info.offline:
6440
      continue
6441
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6442

    
6443

    
6444
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6445
  """OS parameters validation.
6446

6447
  @type lu: L{LogicalUnit}
6448
  @param lu: the logical unit for which we check
6449
  @type required: boolean
6450
  @param required: whether the validation should fail if the OS is not
6451
      found
6452
  @type nodenames: list
6453
  @param nodenames: the list of nodes on which we should check
6454
  @type osname: string
6455
  @param osname: the name of the hypervisor we should use
6456
  @type osparams: dict
6457
  @param osparams: the parameters which we need to check
6458
  @raise errors.OpPrereqError: if the parameters are not valid
6459

6460
  """
6461
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6462
                                   [constants.OS_VALIDATE_PARAMETERS],
6463
                                   osparams)
6464
  for node, nres in result.items():
6465
    # we don't check for offline cases since this should be run only
6466
    # against the master node and/or an instance's nodes
6467
    nres.Raise("OS Parameters validation failed on node %s" % node)
6468
    if not nres.payload:
6469
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6470
                 osname, node)
6471

    
6472

    
6473
class LUCreateInstance(LogicalUnit):
6474
  """Create an instance.
6475

6476
  """
6477
  HPATH = "instance-add"
6478
  HTYPE = constants.HTYPE_INSTANCE
6479
  _OP_PARAMS = [
6480
    _PInstanceName,
6481
    ("mode", _NoDefault, _TElemOf(constants.INSTANCE_CREATE_MODES)),
6482
    ("start", True, _TBool),
6483
    ("wait_for_sync", True, _TBool),
6484
    ("ip_check", True, _TBool),
6485
    ("name_check", True, _TBool),
6486
    ("disks", _NoDefault, _TListOf(_TDict)),
6487
    ("nics", _NoDefault, _TListOf(_TDict)),
6488
    ("hvparams", _EmptyDict, _TDict),
6489
    ("beparams", _EmptyDict, _TDict),
6490
    ("osparams", _EmptyDict, _TDict),
6491
    ("no_install", None, _TMaybeBool),
6492
    ("os_type", None, _TMaybeString),
6493
    ("force_variant", False, _TBool),
6494
    ("source_handshake", None, _TOr(_TList, _TNone)),
6495
    ("source_x509_ca", None, _TOr(_TList, _TNone)),
6496
    ("source_instance_name", None, _TMaybeString),
6497
    ("src_node", None, _TMaybeString),
6498
    ("src_path", None, _TMaybeString),
6499
    ("pnode", None, _TMaybeString),
6500
    ("snode", None, _TMaybeString),
6501
    ("iallocator", None, _TMaybeString),
6502
    ("hypervisor", None, _TMaybeString),
6503
    ("disk_template", _NoDefault, _CheckDiskTemplate),
6504
    ("identify_defaults", False, _TBool),
6505
    ("file_driver", None, _TOr(_TNone, _TElemOf(constants.FILE_DRIVER))),
6506
    ("file_storage_dir", None, _TMaybeString),
6507
    ("dry_run", False, _TBool),
6508
    ]
6509
  REQ_BGL = False
6510

    
6511
  def CheckArguments(self):
6512
    """Check arguments.
6513

6514
    """
6515
    # do not require name_check to ease forward/backward compatibility
6516
    # for tools
6517
    if self.op.no_install and self.op.start:
6518
      self.LogInfo("No-installation mode selected, disabling startup")
6519
      self.op.start = False
6520
    # validate/normalize the instance name
6521
    self.op.instance_name = \
6522
      netutils.HostInfo.NormalizeName(self.op.instance_name)
6523

    
6524
    if self.op.ip_check and not self.op.name_check:
6525
      # TODO: make the ip check more flexible and not depend on the name check
6526
      raise errors.OpPrereqError("Cannot do ip checks without a name check",
6527
                                 errors.ECODE_INVAL)
6528

    
6529
    # check nics' parameter names
6530
    for nic in self.op.nics:
6531
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6532

    
6533
    # check disks. parameter names and consistent adopt/no-adopt strategy
6534
    has_adopt = has_no_adopt = False
6535
    for disk in self.op.disks:
6536
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6537
      if "adopt" in disk:
6538
        has_adopt = True
6539
      else:
6540
        has_no_adopt = True
6541
    if has_adopt and has_no_adopt:
6542
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6543
                                 errors.ECODE_INVAL)
6544
    if has_adopt:
6545
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6546
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6547
                                   " '%s' disk template" %
6548
                                   self.op.disk_template,
6549
                                   errors.ECODE_INVAL)
6550
      if self.op.iallocator is not None:
6551
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6552
                                   " iallocator script", errors.ECODE_INVAL)
6553
      if self.op.mode == constants.INSTANCE_IMPORT:
6554
        raise errors.OpPrereqError("Disk adoption not allowed for"
6555
                                   " instance import", errors.ECODE_INVAL)
6556

    
6557
    self.adopt_disks = has_adopt
6558

    
6559
    # instance name verification
6560
    if self.op.name_check:
6561
      self.hostname1 = netutils.GetHostInfo(self.op.instance_name)
6562
      self.op.instance_name = self.hostname1.name
6563
      # used in CheckPrereq for ip ping check
6564
      self.check_ip = self.hostname1.ip
6565
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6566
      raise errors.OpPrereqError("Remote imports require names to be checked" %
6567
                                 errors.ECODE_INVAL)
6568
    else:
6569
      self.check_ip = None
6570

    
6571
    # file storage checks
6572
    if (self.op.file_driver and
6573
        not self.op.file_driver in constants.FILE_DRIVER):
6574
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6575
                                 self.op.file_driver, errors.ECODE_INVAL)
6576

    
6577
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6578
      raise errors.OpPrereqError("File storage directory path not absolute",
6579
                                 errors.ECODE_INVAL)
6580

    
6581
    ### Node/iallocator related checks
6582
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
6583

    
6584
    self._cds = _GetClusterDomainSecret()
6585

    
6586
    if self.op.mode == constants.INSTANCE_IMPORT:
6587
      # On import force_variant must be True, because if we forced it at
6588
      # initial install, our only chance when importing it back is that it
6589
      # works again!
6590
      self.op.force_variant = True
6591

    
6592
      if self.op.no_install:
6593
        self.LogInfo("No-installation mode has no effect during import")
6594

    
6595
    elif self.op.mode == constants.INSTANCE_CREATE:
6596
      if self.op.os_type is None:
6597
        raise errors.OpPrereqError("No guest OS specified",
6598
                                   errors.ECODE_INVAL)
6599
      if self.op.disk_template is None:
6600
        raise errors.OpPrereqError("No disk template specified",
6601
                                   errors.ECODE_INVAL)
6602

    
6603
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6604
      # Check handshake to ensure both clusters have the same domain secret
6605
      src_handshake = self.op.source_handshake
6606
      if not src_handshake:
6607
        raise errors.OpPrereqError("Missing source handshake",
6608
                                   errors.ECODE_INVAL)
6609

    
6610
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6611
                                                           src_handshake)
6612
      if errmsg:
6613
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6614
                                   errors.ECODE_INVAL)
6615

    
6616
      # Load and check source CA
6617
      self.source_x509_ca_pem = self.op.source_x509_ca
6618
      if not self.source_x509_ca_pem:
6619
        raise errors.OpPrereqError("Missing source X509 CA",
6620
                                   errors.ECODE_INVAL)
6621

    
6622
      try:
6623
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
6624
                                                    self._cds)
6625
      except OpenSSL.crypto.Error, err:
6626
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
6627
                                   (err, ), errors.ECODE_INVAL)
6628

    
6629
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
6630
      if errcode is not None:
6631
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
6632
                                   errors.ECODE_INVAL)
6633

    
6634
      self.source_x509_ca = cert
6635

    
6636
      src_instance_name = self.op.source_instance_name
6637
      if not src_instance_name:
6638
        raise errors.OpPrereqError("Missing source instance name",
6639
                                   errors.ECODE_INVAL)
6640

    
6641
      norm_name = netutils.HostInfo.NormalizeName(src_instance_name)
6642
      self.source_instance_name = netutils.GetHostInfo(norm_name).name
6643

    
6644
    else:
6645
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
6646
                                 self.op.mode, errors.ECODE_INVAL)
6647

    
6648
  def ExpandNames(self):
6649
    """ExpandNames for CreateInstance.
6650

6651
    Figure out the right locks for instance creation.
6652

6653
    """
6654
    self.needed_locks = {}
6655

    
6656
    instance_name = self.op.instance_name
6657
    # this is just a preventive check, but someone might still add this
6658
    # instance in the meantime, and creation will fail at lock-add time
6659
    if instance_name in self.cfg.GetInstanceList():
6660
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6661
                                 instance_name, errors.ECODE_EXISTS)
6662

    
6663
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
6664

    
6665
    if self.op.iallocator:
6666
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6667
    else:
6668
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
6669
      nodelist = [self.op.pnode]
6670
      if self.op.snode is not None:
6671
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
6672
        nodelist.append(self.op.snode)
6673
      self.needed_locks[locking.LEVEL_NODE] = nodelist
6674

    
6675
    # in case of import lock the source node too
6676
    if self.op.mode == constants.INSTANCE_IMPORT:
6677
      src_node = self.op.src_node
6678
      src_path = self.op.src_path
6679

    
6680
      if src_path is None:
6681
        self.op.src_path = src_path = self.op.instance_name
6682

    
6683
      if src_node is None:
6684
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6685
        self.op.src_node = None
6686
        if os.path.isabs(src_path):
6687
          raise errors.OpPrereqError("Importing an instance from an absolute"
6688
                                     " path requires a source node option.",
6689
                                     errors.ECODE_INVAL)
6690
      else:
6691
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
6692
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
6693
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
6694
        if not os.path.isabs(src_path):
6695
          self.op.src_path = src_path = \
6696
            utils.PathJoin(constants.EXPORT_DIR, src_path)
6697

    
6698
  def _RunAllocator(self):
6699
    """Run the allocator based on input opcode.
6700

6701
    """
6702
    nics = [n.ToDict() for n in self.nics]
6703
    ial = IAllocator(self.cfg, self.rpc,
6704
                     mode=constants.IALLOCATOR_MODE_ALLOC,
6705
                     name=self.op.instance_name,
6706
                     disk_template=self.op.disk_template,
6707
                     tags=[],
6708
                     os=self.op.os_type,
6709
                     vcpus=self.be_full[constants.BE_VCPUS],
6710
                     mem_size=self.be_full[constants.BE_MEMORY],
6711
                     disks=self.disks,
6712
                     nics=nics,
6713
                     hypervisor=self.op.hypervisor,
6714
                     )
6715

    
6716
    ial.Run(self.op.iallocator)
6717

    
6718
    if not ial.success:
6719
      raise errors.OpPrereqError("Can't compute nodes using"
6720
                                 " iallocator '%s': %s" %
6721
                                 (self.op.iallocator, ial.info),
6722
                                 errors.ECODE_NORES)
6723
    if len(ial.result) != ial.required_nodes:
6724
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6725
                                 " of nodes (%s), required %s" %
6726
                                 (self.op.iallocator, len(ial.result),
6727
                                  ial.required_nodes), errors.ECODE_FAULT)
6728
    self.op.pnode = ial.result[0]
6729
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6730
                 self.op.instance_name, self.op.iallocator,
6731
                 utils.CommaJoin(ial.result))
6732
    if ial.required_nodes == 2:
6733
      self.op.snode = ial.result[1]
6734

    
6735
  def BuildHooksEnv(self):
6736
    """Build hooks env.
6737

6738
    This runs on master, primary and secondary nodes of the instance.
6739

6740
    """
6741
    env = {
6742
      "ADD_MODE": self.op.mode,
6743
      }
6744
    if self.op.mode == constants.INSTANCE_IMPORT:
6745
      env["SRC_NODE"] = self.op.src_node
6746
      env["SRC_PATH"] = self.op.src_path
6747
      env["SRC_IMAGES"] = self.src_images
6748

    
6749
    env.update(_BuildInstanceHookEnv(
6750
      name=self.op.instance_name,
6751
      primary_node=self.op.pnode,
6752
      secondary_nodes=self.secondaries,
6753
      status=self.op.start,
6754
      os_type=self.op.os_type,
6755
      memory=self.be_full[constants.BE_MEMORY],
6756
      vcpus=self.be_full[constants.BE_VCPUS],
6757
      nics=_NICListToTuple(self, self.nics),
6758
      disk_template=self.op.disk_template,
6759
      disks=[(d["size"], d["mode"]) for d in self.disks],
6760
      bep=self.be_full,
6761
      hvp=self.hv_full,
6762
      hypervisor_name=self.op.hypervisor,
6763
    ))
6764

    
6765
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
6766
          self.secondaries)
6767
    return env, nl, nl
6768

    
6769
  def _ReadExportInfo(self):
6770
    """Reads the export information from disk.
6771

6772
    It will override the opcode source node and path with the actual
6773
    information, if these two were not specified before.
6774

6775
    @return: the export information
6776

6777
    """
6778
    assert self.op.mode == constants.INSTANCE_IMPORT
6779

    
6780
    src_node = self.op.src_node
6781
    src_path = self.op.src_path
6782

    
6783
    if src_node is None:
6784
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
6785
      exp_list = self.rpc.call_export_list(locked_nodes)
6786
      found = False
6787
      for node in exp_list:
6788
        if exp_list[node].fail_msg:
6789
          continue
6790
        if src_path in exp_list[node].payload:
6791
          found = True
6792
          self.op.src_node = src_node = node
6793
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
6794
                                                       src_path)
6795
          break
6796
      if not found:
6797
        raise errors.OpPrereqError("No export found for relative path %s" %
6798
                                    src_path, errors.ECODE_INVAL)
6799

    
6800
    _CheckNodeOnline(self, src_node)
6801
    result = self.rpc.call_export_info(src_node, src_path)
6802
    result.Raise("No export or invalid export found in dir %s" % src_path)
6803

    
6804
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
6805
    if not export_info.has_section(constants.INISECT_EXP):
6806
      raise errors.ProgrammerError("Corrupted export config",
6807
                                   errors.ECODE_ENVIRON)
6808

    
6809
    ei_version = export_info.get(constants.INISECT_EXP, "version")
6810
    if (int(ei_version) != constants.EXPORT_VERSION):
6811
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
6812
                                 (ei_version, constants.EXPORT_VERSION),
6813
                                 errors.ECODE_ENVIRON)
6814
    return export_info
6815

    
6816
  def _ReadExportParams(self, einfo):
6817
    """Use export parameters as defaults.
6818

6819
    In case the opcode doesn't specify (as in override) some instance
6820
    parameters, then try to use them from the export information, if
6821
    that declares them.
6822

6823
    """
6824
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
6825

    
6826
    if self.op.disk_template is None:
6827
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
6828
        self.op.disk_template = einfo.get(constants.INISECT_INS,
6829
                                          "disk_template")
6830
      else:
6831
        raise errors.OpPrereqError("No disk template specified and the export"
6832
                                   " is missing the disk_template information",
6833
                                   errors.ECODE_INVAL)
6834

    
6835
    if not self.op.disks:
6836
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
6837
        disks = []
6838
        # TODO: import the disk iv_name too
6839
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
6840
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
6841
          disks.append({"size": disk_sz})
6842
        self.op.disks = disks
6843
      else:
6844
        raise errors.OpPrereqError("No disk info specified and the export"
6845
                                   " is missing the disk information",
6846
                                   errors.ECODE_INVAL)
6847

    
6848
    if (not self.op.nics and
6849
        einfo.has_option(constants.INISECT_INS, "nic_count")):
6850
      nics = []
6851
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
6852
        ndict = {}
6853
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
6854
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
6855
          ndict[name] = v
6856
        nics.append(ndict)
6857
      self.op.nics = nics
6858

    
6859
    if (self.op.hypervisor is None and
6860
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
6861
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
6862
    if einfo.has_section(constants.INISECT_HYP):
6863
      # use the export parameters but do not override the ones
6864
      # specified by the user
6865
      for name, value in einfo.items(constants.INISECT_HYP):
6866
        if name not in self.op.hvparams:
6867
          self.op.hvparams[name] = value
6868

    
6869
    if einfo.has_section(constants.INISECT_BEP):
6870
      # use the parameters, without overriding
6871
      for name, value in einfo.items(constants.INISECT_BEP):
6872
        if name not in self.op.beparams:
6873
          self.op.beparams[name] = value
6874
    else:
6875
      # try to read the parameters old style, from the main section
6876
      for name in constants.BES_PARAMETERS:
6877
        if (name not in self.op.beparams and
6878
            einfo.has_option(constants.INISECT_INS, name)):
6879
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
6880

    
6881
    if einfo.has_section(constants.INISECT_OSP):
6882
      # use the parameters, without overriding
6883
      for name, value in einfo.items(constants.INISECT_OSP):
6884
        if name not in self.op.osparams:
6885
          self.op.osparams[name] = value
6886

    
6887
  def _RevertToDefaults(self, cluster):
6888
    """Revert the instance parameters to the default values.
6889

6890
    """
6891
    # hvparams
6892
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
6893
    for name in self.op.hvparams.keys():
6894
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
6895
        del self.op.hvparams[name]
6896
    # beparams
6897
    be_defs = cluster.SimpleFillBE({})
6898
    for name in self.op.beparams.keys():
6899
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
6900
        del self.op.beparams[name]
6901
    # nic params
6902
    nic_defs = cluster.SimpleFillNIC({})
6903
    for nic in self.op.nics:
6904
      for name in constants.NICS_PARAMETERS:
6905
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
6906
          del nic[name]
6907
    # osparams
6908
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
6909
    for name in self.op.osparams.keys():
6910
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
6911
        del self.op.osparams[name]
6912

    
6913
  def CheckPrereq(self):
6914
    """Check prerequisites.
6915

6916
    """
6917
    if self.op.mode == constants.INSTANCE_IMPORT:
6918
      export_info = self._ReadExportInfo()
6919
      self._ReadExportParams(export_info)
6920

    
6921
    _CheckDiskTemplate(self.op.disk_template)
6922

    
6923
    if (not self.cfg.GetVGName() and
6924
        self.op.disk_template not in constants.DTS_NOT_LVM):
6925
      raise errors.OpPrereqError("Cluster does not support lvm-based"
6926
                                 " instances", errors.ECODE_STATE)
6927

    
6928
    if self.op.hypervisor is None:
6929
      self.op.hypervisor = self.cfg.GetHypervisorType()
6930

    
6931
    cluster = self.cfg.GetClusterInfo()
6932
    enabled_hvs = cluster.enabled_hypervisors
6933
    if self.op.hypervisor not in enabled_hvs:
6934
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
6935
                                 " cluster (%s)" % (self.op.hypervisor,
6936
                                  ",".join(enabled_hvs)),
6937
                                 errors.ECODE_STATE)
6938

    
6939
    # check hypervisor parameter syntax (locally)
6940
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
6941
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
6942
                                      self.op.hvparams)
6943
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
6944
    hv_type.CheckParameterSyntax(filled_hvp)
6945
    self.hv_full = filled_hvp
6946
    # check that we don't specify global parameters on an instance
6947
    _CheckGlobalHvParams(self.op.hvparams)
6948

    
6949
    # fill and remember the beparams dict
6950
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
6951
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
6952

    
6953
    # build os parameters
6954
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
6955

    
6956
    # now that hvp/bep are in final format, let's reset to defaults,
6957
    # if told to do so
6958
    if self.op.identify_defaults:
6959
      self._RevertToDefaults(cluster)
6960

    
6961
    # NIC buildup
6962
    self.nics = []
6963
    for idx, nic in enumerate(self.op.nics):
6964
      nic_mode_req = nic.get("mode", None)
6965
      nic_mode = nic_mode_req
6966
      if nic_mode is None:
6967
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
6968

    
6969
      # in routed mode, for the first nic, the default ip is 'auto'
6970
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
6971
        default_ip_mode = constants.VALUE_AUTO
6972
      else:
6973
        default_ip_mode = constants.VALUE_NONE
6974

    
6975
      # ip validity checks
6976
      ip = nic.get("ip", default_ip_mode)
6977
      if ip is None or ip.lower() == constants.VALUE_NONE:
6978
        nic_ip = None
6979
      elif ip.lower() == constants.VALUE_AUTO:
6980
        if not self.op.name_check:
6981
          raise errors.OpPrereqError("IP address set to auto but name checks"
6982
                                     " have been skipped. Aborting.",
6983
                                     errors.ECODE_INVAL)
6984
        nic_ip = self.hostname1.ip
6985
      else:
6986
        if not netutils.IsValidIP4(ip):
6987
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
6988
                                     " like a valid IP" % ip,
6989
                                     errors.ECODE_INVAL)
6990
        nic_ip = ip
6991

    
6992
      # TODO: check the ip address for uniqueness
6993
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
6994
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
6995
                                   errors.ECODE_INVAL)
6996

    
6997
      # MAC address verification
6998
      mac = nic.get("mac", constants.VALUE_AUTO)
6999
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7000
        mac = utils.NormalizeAndValidateMac(mac)
7001

    
7002
        try:
7003
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7004
        except errors.ReservationError:
7005
          raise errors.OpPrereqError("MAC address %s already in use"
7006
                                     " in cluster" % mac,
7007
                                     errors.ECODE_NOTUNIQUE)
7008

    
7009
      # bridge verification
7010
      bridge = nic.get("bridge", None)
7011
      link = nic.get("link", None)
7012
      if bridge and link:
7013
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7014
                                   " at the same time", errors.ECODE_INVAL)
7015
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7016
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7017
                                   errors.ECODE_INVAL)
7018
      elif bridge:
7019
        link = bridge
7020

    
7021
      nicparams = {}
7022
      if nic_mode_req:
7023
        nicparams[constants.NIC_MODE] = nic_mode_req
7024
      if link:
7025
        nicparams[constants.NIC_LINK] = link
7026

    
7027
      check_params = cluster.SimpleFillNIC(nicparams)
7028
      objects.NIC.CheckParameterSyntax(check_params)
7029
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7030

    
7031
    # disk checks/pre-build
7032
    self.disks = []
7033
    for disk in self.op.disks:
7034
      mode = disk.get("mode", constants.DISK_RDWR)
7035
      if mode not in constants.DISK_ACCESS_SET:
7036
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7037
                                   mode, errors.ECODE_INVAL)
7038
      size = disk.get("size", None)
7039
      if size is None:
7040
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7041
      try:
7042
        size = int(size)
7043
      except (TypeError, ValueError):
7044
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7045
                                   errors.ECODE_INVAL)
7046
      new_disk = {"size": size, "mode": mode}
7047
      if "adopt" in disk:
7048
        new_disk["adopt"] = disk["adopt"]
7049
      self.disks.append(new_disk)
7050

    
7051
    if self.op.mode == constants.INSTANCE_IMPORT:
7052

    
7053
      # Check that the new instance doesn't have less disks than the export
7054
      instance_disks = len(self.disks)
7055
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7056
      if instance_disks < export_disks:
7057
        raise errors.OpPrereqError("Not enough disks to import."
7058
                                   " (instance: %d, export: %d)" %
7059
                                   (instance_disks, export_disks),
7060
                                   errors.ECODE_INVAL)
7061

    
7062
      disk_images = []
7063
      for idx in range(export_disks):
7064
        option = 'disk%d_dump' % idx
7065
        if export_info.has_option(constants.INISECT_INS, option):
7066
          # FIXME: are the old os-es, disk sizes, etc. useful?
7067
          export_name = export_info.get(constants.INISECT_INS, option)
7068
          image = utils.PathJoin(self.op.src_path, export_name)
7069
          disk_images.append(image)
7070
        else:
7071
          disk_images.append(False)
7072

    
7073
      self.src_images = disk_images
7074

    
7075
      old_name = export_info.get(constants.INISECT_INS, 'name')
7076
      try:
7077
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7078
      except (TypeError, ValueError), err:
7079
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7080
                                   " an integer: %s" % str(err),
7081
                                   errors.ECODE_STATE)
7082
      if self.op.instance_name == old_name:
7083
        for idx, nic in enumerate(self.nics):
7084
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7085
            nic_mac_ini = 'nic%d_mac' % idx
7086
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7087

    
7088
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7089

    
7090
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7091
    if self.op.ip_check:
7092
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7093
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7094
                                   (self.check_ip, self.op.instance_name),
7095
                                   errors.ECODE_NOTUNIQUE)
7096

    
7097
    #### mac address generation
7098
    # By generating here the mac address both the allocator and the hooks get
7099
    # the real final mac address rather than the 'auto' or 'generate' value.
7100
    # There is a race condition between the generation and the instance object
7101
    # creation, which means that we know the mac is valid now, but we're not
7102
    # sure it will be when we actually add the instance. If things go bad
7103
    # adding the instance will abort because of a duplicate mac, and the
7104
    # creation job will fail.
7105
    for nic in self.nics:
7106
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7107
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7108

    
7109
    #### allocator run
7110

    
7111
    if self.op.iallocator is not None:
7112
      self._RunAllocator()
7113

    
7114
    #### node related checks
7115

    
7116
    # check primary node
7117
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7118
    assert self.pnode is not None, \
7119
      "Cannot retrieve locked node %s" % self.op.pnode
7120
    if pnode.offline:
7121
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7122
                                 pnode.name, errors.ECODE_STATE)
7123
    if pnode.drained:
7124
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7125
                                 pnode.name, errors.ECODE_STATE)
7126

    
7127
    self.secondaries = []
7128

    
7129
    # mirror node verification
7130
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7131
      if self.op.snode is None:
7132
        raise errors.OpPrereqError("The networked disk templates need"
7133
                                   " a mirror node", errors.ECODE_INVAL)
7134
      if self.op.snode == pnode.name:
7135
        raise errors.OpPrereqError("The secondary node cannot be the"
7136
                                   " primary node.", errors.ECODE_INVAL)
7137
      _CheckNodeOnline(self, self.op.snode)
7138
      _CheckNodeNotDrained(self, self.op.snode)
7139
      self.secondaries.append(self.op.snode)
7140

    
7141
    nodenames = [pnode.name] + self.secondaries
7142

    
7143
    req_size = _ComputeDiskSize(self.op.disk_template,
7144
                                self.disks)
7145

    
7146
    # Check lv size requirements, if not adopting
7147
    if req_size is not None and not self.adopt_disks:
7148
      _CheckNodesFreeDisk(self, nodenames, req_size)
7149

    
7150
    if self.adopt_disks: # instead, we must check the adoption data
7151
      all_lvs = set([i["adopt"] for i in self.disks])
7152
      if len(all_lvs) != len(self.disks):
7153
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7154
                                   errors.ECODE_INVAL)
7155
      for lv_name in all_lvs:
7156
        try:
7157
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7158
        except errors.ReservationError:
7159
          raise errors.OpPrereqError("LV named %s used by another instance" %
7160
                                     lv_name, errors.ECODE_NOTUNIQUE)
7161

    
7162
      node_lvs = self.rpc.call_lv_list([pnode.name],
7163
                                       self.cfg.GetVGName())[pnode.name]
7164
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7165
      node_lvs = node_lvs.payload
7166
      delta = all_lvs.difference(node_lvs.keys())
7167
      if delta:
7168
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7169
                                   utils.CommaJoin(delta),
7170
                                   errors.ECODE_INVAL)
7171
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7172
      if online_lvs:
7173
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7174
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7175
                                   errors.ECODE_STATE)
7176
      # update the size of disk based on what is found
7177
      for dsk in self.disks:
7178
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
7179

    
7180
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7181

    
7182
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7183
    # check OS parameters (remotely)
7184
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7185

    
7186
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7187

    
7188
    # memory check on primary node
7189
    if self.op.start:
7190
      _CheckNodeFreeMemory(self, self.pnode.name,
7191
                           "creating instance %s" % self.op.instance_name,
7192
                           self.be_full[constants.BE_MEMORY],
7193
                           self.op.hypervisor)
7194

    
7195
    self.dry_run_result = list(nodenames)
7196

    
7197
  def Exec(self, feedback_fn):
7198
    """Create and add the instance to the cluster.
7199

7200
    """
7201
    instance = self.op.instance_name
7202
    pnode_name = self.pnode.name
7203

    
7204
    ht_kind = self.op.hypervisor
7205
    if ht_kind in constants.HTS_REQ_PORT:
7206
      network_port = self.cfg.AllocatePort()
7207
    else:
7208
      network_port = None
7209

    
7210
    if constants.ENABLE_FILE_STORAGE:
7211
      # this is needed because os.path.join does not accept None arguments
7212
      if self.op.file_storage_dir is None:
7213
        string_file_storage_dir = ""
7214
      else:
7215
        string_file_storage_dir = self.op.file_storage_dir
7216

    
7217
      # build the full file storage dir path
7218
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7219
                                        string_file_storage_dir, instance)
7220
    else:
7221
      file_storage_dir = ""
7222

    
7223
    disks = _GenerateDiskTemplate(self,
7224
                                  self.op.disk_template,
7225
                                  instance, pnode_name,
7226
                                  self.secondaries,
7227
                                  self.disks,
7228
                                  file_storage_dir,
7229
                                  self.op.file_driver,
7230
                                  0)
7231

    
7232
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7233
                            primary_node=pnode_name,
7234
                            nics=self.nics, disks=disks,
7235
                            disk_template=self.op.disk_template,
7236
                            admin_up=False,
7237
                            network_port=network_port,
7238
                            beparams=self.op.beparams,
7239
                            hvparams=self.op.hvparams,
7240
                            hypervisor=self.op.hypervisor,
7241
                            osparams=self.op.osparams,
7242
                            )
7243

    
7244
    if self.adopt_disks:
7245
      # rename LVs to the newly-generated names; we need to construct
7246
      # 'fake' LV disks with the old data, plus the new unique_id
7247
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7248
      rename_to = []
7249
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7250
        rename_to.append(t_dsk.logical_id)
7251
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7252
        self.cfg.SetDiskID(t_dsk, pnode_name)
7253
      result = self.rpc.call_blockdev_rename(pnode_name,
7254
                                             zip(tmp_disks, rename_to))
7255
      result.Raise("Failed to rename adoped LVs")
7256
    else:
7257
      feedback_fn("* creating instance disks...")
7258
      try:
7259
        _CreateDisks(self, iobj)
7260
      except errors.OpExecError:
7261
        self.LogWarning("Device creation failed, reverting...")
7262
        try:
7263
          _RemoveDisks(self, iobj)
7264
        finally:
7265
          self.cfg.ReleaseDRBDMinors(instance)
7266
          raise
7267

    
7268
    feedback_fn("adding instance %s to cluster config" % instance)
7269

    
7270
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7271

    
7272
    # Declare that we don't want to remove the instance lock anymore, as we've
7273
    # added the instance to the config
7274
    del self.remove_locks[locking.LEVEL_INSTANCE]
7275
    # Unlock all the nodes
7276
    if self.op.mode == constants.INSTANCE_IMPORT:
7277
      nodes_keep = [self.op.src_node]
7278
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7279
                       if node != self.op.src_node]
7280
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7281
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7282
    else:
7283
      self.context.glm.release(locking.LEVEL_NODE)
7284
      del self.acquired_locks[locking.LEVEL_NODE]
7285

    
7286
    if self.op.wait_for_sync:
7287
      disk_abort = not _WaitForSync(self, iobj)
7288
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7289
      # make sure the disks are not degraded (still sync-ing is ok)
7290
      time.sleep(15)
7291
      feedback_fn("* checking mirrors status")
7292
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7293
    else:
7294
      disk_abort = False
7295

    
7296
    if disk_abort:
7297
      _RemoveDisks(self, iobj)
7298
      self.cfg.RemoveInstance(iobj.name)
7299
      # Make sure the instance lock gets removed
7300
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7301
      raise errors.OpExecError("There are some degraded disks for"
7302
                               " this instance")
7303

    
7304
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7305
      if self.op.mode == constants.INSTANCE_CREATE:
7306
        if not self.op.no_install:
7307
          feedback_fn("* running the instance OS create scripts...")
7308
          # FIXME: pass debug option from opcode to backend
7309
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7310
                                                 self.op.debug_level)
7311
          result.Raise("Could not add os for instance %s"
7312
                       " on node %s" % (instance, pnode_name))
7313

    
7314
      elif self.op.mode == constants.INSTANCE_IMPORT:
7315
        feedback_fn("* running the instance OS import scripts...")
7316

    
7317
        transfers = []
7318

    
7319
        for idx, image in enumerate(self.src_images):
7320
          if not image:
7321
            continue
7322

    
7323
          # FIXME: pass debug option from opcode to backend
7324
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7325
                                             constants.IEIO_FILE, (image, ),
7326
                                             constants.IEIO_SCRIPT,
7327
                                             (iobj.disks[idx], idx),
7328
                                             None)
7329
          transfers.append(dt)
7330

    
7331
        import_result = \
7332
          masterd.instance.TransferInstanceData(self, feedback_fn,
7333
                                                self.op.src_node, pnode_name,
7334
                                                self.pnode.secondary_ip,
7335
                                                iobj, transfers)
7336
        if not compat.all(import_result):
7337
          self.LogWarning("Some disks for instance %s on node %s were not"
7338
                          " imported successfully" % (instance, pnode_name))
7339

    
7340
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7341
        feedback_fn("* preparing remote import...")
7342
        connect_timeout = constants.RIE_CONNECT_TIMEOUT
7343
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7344

    
7345
        disk_results = masterd.instance.RemoteImport(self, feedback_fn, iobj,
7346
                                                     self.source_x509_ca,
7347
                                                     self._cds, timeouts)
7348
        if not compat.all(disk_results):
7349
          # TODO: Should the instance still be started, even if some disks
7350
          # failed to import (valid for local imports, too)?
7351
          self.LogWarning("Some disks for instance %s on node %s were not"
7352
                          " imported successfully" % (instance, pnode_name))
7353

    
7354
        # Run rename script on newly imported instance
7355
        assert iobj.name == instance
7356
        feedback_fn("Running rename script for %s" % instance)
7357
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7358
                                                   self.source_instance_name,
7359
                                                   self.op.debug_level)
7360
        if result.fail_msg:
7361
          self.LogWarning("Failed to run rename script for %s on node"
7362
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7363

    
7364
      else:
7365
        # also checked in the prereq part
7366
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7367
                                     % self.op.mode)
7368

    
7369
    if self.op.start:
7370
      iobj.admin_up = True
7371
      self.cfg.Update(iobj, feedback_fn)
7372
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7373
      feedback_fn("* starting instance...")
7374
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7375
      result.Raise("Could not start instance")
7376

    
7377
    return list(iobj.all_nodes)
7378

    
7379

    
7380
class LUConnectConsole(NoHooksLU):
7381
  """Connect to an instance's console.
7382

7383
  This is somewhat special in that it returns the command line that
7384
  you need to run on the master node in order to connect to the
7385
  console.
7386

7387
  """
7388
  _OP_PARAMS = [
7389
    _PInstanceName
7390
    ]
7391
  REQ_BGL = False
7392

    
7393
  def ExpandNames(self):
7394
    self._ExpandAndLockInstance()
7395

    
7396
  def CheckPrereq(self):
7397
    """Check prerequisites.
7398

7399
    This checks that the instance is in the cluster.
7400

7401
    """
7402
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7403
    assert self.instance is not None, \
7404
      "Cannot retrieve locked instance %s" % self.op.instance_name
7405
    _CheckNodeOnline(self, self.instance.primary_node)
7406

    
7407
  def Exec(self, feedback_fn):
7408
    """Connect to the console of an instance
7409

7410
    """
7411
    instance = self.instance
7412
    node = instance.primary_node
7413

    
7414
    node_insts = self.rpc.call_instance_list([node],
7415
                                             [instance.hypervisor])[node]
7416
    node_insts.Raise("Can't get node information from %s" % node)
7417

    
7418
    if instance.name not in node_insts.payload:
7419
      raise errors.OpExecError("Instance %s is not running." % instance.name)
7420

    
7421
    logging.debug("Connecting to console of %s on %s", instance.name, node)
7422

    
7423
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
7424
    cluster = self.cfg.GetClusterInfo()
7425
    # beparams and hvparams are passed separately, to avoid editing the
7426
    # instance and then saving the defaults in the instance itself.
7427
    hvparams = cluster.FillHV(instance)
7428
    beparams = cluster.FillBE(instance)
7429
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
7430

    
7431
    # build ssh cmdline
7432
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
7433

    
7434

    
7435
class LUReplaceDisks(LogicalUnit):
7436
  """Replace the disks of an instance.
7437

7438
  """
7439
  HPATH = "mirrors-replace"
7440
  HTYPE = constants.HTYPE_INSTANCE
7441
  _OP_PARAMS = [
7442
    _PInstanceName,
7443
    ("mode", _NoDefault, _TElemOf(constants.REPLACE_MODES)),
7444
    ("disks", _EmptyList, _TListOf(_TPositiveInt)),
7445
    ("remote_node", None, _TMaybeString),
7446
    ("iallocator", None, _TMaybeString),
7447
    ("early_release", False, _TBool),
7448
    ]
7449
  REQ_BGL = False
7450

    
7451
  def CheckArguments(self):
7452
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7453
                                  self.op.iallocator)
7454

    
7455
  def ExpandNames(self):
7456
    self._ExpandAndLockInstance()
7457

    
7458
    if self.op.iallocator is not None:
7459
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7460

    
7461
    elif self.op.remote_node is not None:
7462
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7463
      self.op.remote_node = remote_node
7464

    
7465
      # Warning: do not remove the locking of the new secondary here
7466
      # unless DRBD8.AddChildren is changed to work in parallel;
7467
      # currently it doesn't since parallel invocations of
7468
      # FindUnusedMinor will conflict
7469
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7470
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7471

    
7472
    else:
7473
      self.needed_locks[locking.LEVEL_NODE] = []
7474
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7475

    
7476
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7477
                                   self.op.iallocator, self.op.remote_node,
7478
                                   self.op.disks, False, self.op.early_release)
7479

    
7480
    self.tasklets = [self.replacer]
7481

    
7482
  def DeclareLocks(self, level):
7483
    # If we're not already locking all nodes in the set we have to declare the
7484
    # instance's primary/secondary nodes.
7485
    if (level == locking.LEVEL_NODE and
7486
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7487
      self._LockInstancesNodes()
7488

    
7489
  def BuildHooksEnv(self):
7490
    """Build hooks env.
7491

7492
    This runs on the master, the primary and all the secondaries.
7493

7494
    """
7495
    instance = self.replacer.instance
7496
    env = {
7497
      "MODE": self.op.mode,
7498
      "NEW_SECONDARY": self.op.remote_node,
7499
      "OLD_SECONDARY": instance.secondary_nodes[0],
7500
      }
7501
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7502
    nl = [
7503
      self.cfg.GetMasterNode(),
7504
      instance.primary_node,
7505
      ]
7506
    if self.op.remote_node is not None:
7507
      nl.append(self.op.remote_node)
7508
    return env, nl, nl
7509

    
7510

    
7511
class TLReplaceDisks(Tasklet):
7512
  """Replaces disks for an instance.
7513

7514
  Note: Locking is not within the scope of this class.
7515

7516
  """
7517
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7518
               disks, delay_iallocator, early_release):
7519
    """Initializes this class.
7520

7521
    """
7522
    Tasklet.__init__(self, lu)
7523

    
7524
    # Parameters
7525
    self.instance_name = instance_name
7526
    self.mode = mode
7527
    self.iallocator_name = iallocator_name
7528
    self.remote_node = remote_node
7529
    self.disks = disks
7530
    self.delay_iallocator = delay_iallocator
7531
    self.early_release = early_release
7532

    
7533
    # Runtime data
7534
    self.instance = None
7535
    self.new_node = None
7536
    self.target_node = None
7537
    self.other_node = None
7538
    self.remote_node_info = None
7539
    self.node_secondary_ip = None
7540

    
7541
  @staticmethod
7542
  def CheckArguments(mode, remote_node, iallocator):
7543
    """Helper function for users of this class.
7544

7545
    """
7546
    # check for valid parameter combination
7547
    if mode == constants.REPLACE_DISK_CHG:
7548
      if remote_node is None and iallocator is None:
7549
        raise errors.OpPrereqError("When changing the secondary either an"
7550
                                   " iallocator script must be used or the"
7551
                                   " new node given", errors.ECODE_INVAL)
7552

    
7553
      if remote_node is not None and iallocator is not None:
7554
        raise errors.OpPrereqError("Give either the iallocator or the new"
7555
                                   " secondary, not both", errors.ECODE_INVAL)
7556

    
7557
    elif remote_node is not None or iallocator is not None:
7558
      # Not replacing the secondary
7559
      raise errors.OpPrereqError("The iallocator and new node options can"
7560
                                 " only be used when changing the"
7561
                                 " secondary node", errors.ECODE_INVAL)
7562

    
7563
  @staticmethod
7564
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7565
    """Compute a new secondary node using an IAllocator.
7566

7567
    """
7568
    ial = IAllocator(lu.cfg, lu.rpc,
7569
                     mode=constants.IALLOCATOR_MODE_RELOC,
7570
                     name=instance_name,
7571
                     relocate_from=relocate_from)
7572

    
7573
    ial.Run(iallocator_name)
7574

    
7575
    if not ial.success:
7576
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7577
                                 " %s" % (iallocator_name, ial.info),
7578
                                 errors.ECODE_NORES)
7579

    
7580
    if len(ial.result) != ial.required_nodes:
7581
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7582
                                 " of nodes (%s), required %s" %
7583
                                 (iallocator_name,
7584
                                  len(ial.result), ial.required_nodes),
7585
                                 errors.ECODE_FAULT)
7586

    
7587
    remote_node_name = ial.result[0]
7588

    
7589
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7590
               instance_name, remote_node_name)
7591

    
7592
    return remote_node_name
7593

    
7594
  def _FindFaultyDisks(self, node_name):
7595
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7596
                                    node_name, True)
7597

    
7598
  def CheckPrereq(self):
7599
    """Check prerequisites.
7600

7601
    This checks that the instance is in the cluster.
7602

7603
    """
7604
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7605
    assert instance is not None, \
7606
      "Cannot retrieve locked instance %s" % self.instance_name
7607

    
7608
    if instance.disk_template != constants.DT_DRBD8:
7609
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7610
                                 " instances", errors.ECODE_INVAL)
7611

    
7612
    if len(instance.secondary_nodes) != 1:
7613
      raise errors.OpPrereqError("The instance has a strange layout,"
7614
                                 " expected one secondary but found %d" %
7615
                                 len(instance.secondary_nodes),
7616
                                 errors.ECODE_FAULT)
7617

    
7618
    if not self.delay_iallocator:
7619
      self._CheckPrereq2()
7620

    
7621
  def _CheckPrereq2(self):
7622
    """Check prerequisites, second part.
7623

7624
    This function should always be part of CheckPrereq. It was separated and is
7625
    now called from Exec because during node evacuation iallocator was only
7626
    called with an unmodified cluster model, not taking planned changes into
7627
    account.
7628

7629
    """
7630
    instance = self.instance
7631
    secondary_node = instance.secondary_nodes[0]
7632

    
7633
    if self.iallocator_name is None:
7634
      remote_node = self.remote_node
7635
    else:
7636
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
7637
                                       instance.name, instance.secondary_nodes)
7638

    
7639
    if remote_node is not None:
7640
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
7641
      assert self.remote_node_info is not None, \
7642
        "Cannot retrieve locked node %s" % remote_node
7643
    else:
7644
      self.remote_node_info = None
7645

    
7646
    if remote_node == self.instance.primary_node:
7647
      raise errors.OpPrereqError("The specified node is the primary node of"
7648
                                 " the instance.", errors.ECODE_INVAL)
7649

    
7650
    if remote_node == secondary_node:
7651
      raise errors.OpPrereqError("The specified node is already the"
7652
                                 " secondary node of the instance.",
7653
                                 errors.ECODE_INVAL)
7654

    
7655
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
7656
                                    constants.REPLACE_DISK_CHG):
7657
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
7658
                                 errors.ECODE_INVAL)
7659

    
7660
    if self.mode == constants.REPLACE_DISK_AUTO:
7661
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
7662
      faulty_secondary = self._FindFaultyDisks(secondary_node)
7663

    
7664
      if faulty_primary and faulty_secondary:
7665
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
7666
                                   " one node and can not be repaired"
7667
                                   " automatically" % self.instance_name,
7668
                                   errors.ECODE_STATE)
7669

    
7670
      if faulty_primary:
7671
        self.disks = faulty_primary
7672
        self.target_node = instance.primary_node
7673
        self.other_node = secondary_node
7674
        check_nodes = [self.target_node, self.other_node]
7675
      elif faulty_secondary:
7676
        self.disks = faulty_secondary
7677
        self.target_node = secondary_node
7678
        self.other_node = instance.primary_node
7679
        check_nodes = [self.target_node, self.other_node]
7680
      else:
7681
        self.disks = []
7682
        check_nodes = []
7683

    
7684
    else:
7685
      # Non-automatic modes
7686
      if self.mode == constants.REPLACE_DISK_PRI:
7687
        self.target_node = instance.primary_node
7688
        self.other_node = secondary_node
7689
        check_nodes = [self.target_node, self.other_node]
7690

    
7691
      elif self.mode == constants.REPLACE_DISK_SEC:
7692
        self.target_node = secondary_node
7693
        self.other_node = instance.primary_node
7694
        check_nodes = [self.target_node, self.other_node]
7695

    
7696
      elif self.mode == constants.REPLACE_DISK_CHG:
7697
        self.new_node = remote_node
7698
        self.other_node = instance.primary_node
7699
        self.target_node = secondary_node
7700
        check_nodes = [self.new_node, self.other_node]
7701

    
7702
        _CheckNodeNotDrained(self.lu, remote_node)
7703

    
7704
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
7705
        assert old_node_info is not None
7706
        if old_node_info.offline and not self.early_release:
7707
          # doesn't make sense to delay the release
7708
          self.early_release = True
7709
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
7710
                          " early-release mode", secondary_node)
7711

    
7712
      else:
7713
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
7714
                                     self.mode)
7715

    
7716
      # If not specified all disks should be replaced
7717
      if not self.disks:
7718
        self.disks = range(len(self.instance.disks))
7719

    
7720
    for node in check_nodes:
7721
      _CheckNodeOnline(self.lu, node)
7722

    
7723
    # Check whether disks are valid
7724
    for disk_idx in self.disks:
7725
      instance.FindDisk(disk_idx)
7726

    
7727
    # Get secondary node IP addresses
7728
    node_2nd_ip = {}
7729

    
7730
    for node_name in [self.target_node, self.other_node, self.new_node]:
7731
      if node_name is not None:
7732
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
7733

    
7734
    self.node_secondary_ip = node_2nd_ip
7735

    
7736
  def Exec(self, feedback_fn):
7737
    """Execute disk replacement.
7738

7739
    This dispatches the disk replacement to the appropriate handler.
7740

7741
    """
7742
    if self.delay_iallocator:
7743
      self._CheckPrereq2()
7744

    
7745
    if not self.disks:
7746
      feedback_fn("No disks need replacement")
7747
      return
7748

    
7749
    feedback_fn("Replacing disk(s) %s for %s" %
7750
                (utils.CommaJoin(self.disks), self.instance.name))
7751

    
7752
    activate_disks = (not self.instance.admin_up)
7753

    
7754
    # Activate the instance disks if we're replacing them on a down instance
7755
    if activate_disks:
7756
      _StartInstanceDisks(self.lu, self.instance, True)
7757

    
7758
    try:
7759
      # Should we replace the secondary node?
7760
      if self.new_node is not None:
7761
        fn = self._ExecDrbd8Secondary
7762
      else:
7763
        fn = self._ExecDrbd8DiskOnly
7764

    
7765
      return fn(feedback_fn)
7766

    
7767
    finally:
7768
      # Deactivate the instance disks if we're replacing them on a
7769
      # down instance
7770
      if activate_disks:
7771
        _SafeShutdownInstanceDisks(self.lu, self.instance)
7772

    
7773
  def _CheckVolumeGroup(self, nodes):
7774
    self.lu.LogInfo("Checking volume groups")
7775

    
7776
    vgname = self.cfg.GetVGName()
7777

    
7778
    # Make sure volume group exists on all involved nodes
7779
    results = self.rpc.call_vg_list(nodes)
7780
    if not results:
7781
      raise errors.OpExecError("Can't list volume groups on the nodes")
7782

    
7783
    for node in nodes:
7784
      res = results[node]
7785
      res.Raise("Error checking node %s" % node)
7786
      if vgname not in res.payload:
7787
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
7788
                                 (vgname, node))
7789

    
7790
  def _CheckDisksExistence(self, nodes):
7791
    # Check disk existence
7792
    for idx, dev in enumerate(self.instance.disks):
7793
      if idx not in self.disks:
7794
        continue
7795

    
7796
      for node in nodes:
7797
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
7798
        self.cfg.SetDiskID(dev, node)
7799

    
7800
        result = self.rpc.call_blockdev_find(node, dev)
7801

    
7802
        msg = result.fail_msg
7803
        if msg or not result.payload:
7804
          if not msg:
7805
            msg = "disk not found"
7806
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
7807
                                   (idx, node, msg))
7808

    
7809
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
7810
    for idx, dev in enumerate(self.instance.disks):
7811
      if idx not in self.disks:
7812
        continue
7813

    
7814
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
7815
                      (idx, node_name))
7816

    
7817
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
7818
                                   ldisk=ldisk):
7819
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
7820
                                 " replace disks for instance %s" %
7821
                                 (node_name, self.instance.name))
7822

    
7823
  def _CreateNewStorage(self, node_name):
7824
    vgname = self.cfg.GetVGName()
7825
    iv_names = {}
7826

    
7827
    for idx, dev in enumerate(self.instance.disks):
7828
      if idx not in self.disks:
7829
        continue
7830

    
7831
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
7832

    
7833
      self.cfg.SetDiskID(dev, node_name)
7834

    
7835
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
7836
      names = _GenerateUniqueNames(self.lu, lv_names)
7837

    
7838
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
7839
                             logical_id=(vgname, names[0]))
7840
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7841
                             logical_id=(vgname, names[1]))
7842

    
7843
      new_lvs = [lv_data, lv_meta]
7844
      old_lvs = dev.children
7845
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
7846

    
7847
      # we pass force_create=True to force the LVM creation
7848
      for new_lv in new_lvs:
7849
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
7850
                        _GetInstanceInfoText(self.instance), False)
7851

    
7852
    return iv_names
7853

    
7854
  def _CheckDevices(self, node_name, iv_names):
7855
    for name, (dev, _, _) in iv_names.iteritems():
7856
      self.cfg.SetDiskID(dev, node_name)
7857

    
7858
      result = self.rpc.call_blockdev_find(node_name, dev)
7859

    
7860
      msg = result.fail_msg
7861
      if msg or not result.payload:
7862
        if not msg:
7863
          msg = "disk not found"
7864
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
7865
                                 (name, msg))
7866

    
7867
      if result.payload.is_degraded:
7868
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
7869

    
7870
  def _RemoveOldStorage(self, node_name, iv_names):
7871
    for name, (_, old_lvs, _) in iv_names.iteritems():
7872
      self.lu.LogInfo("Remove logical volumes for %s" % name)
7873

    
7874
      for lv in old_lvs:
7875
        self.cfg.SetDiskID(lv, node_name)
7876

    
7877
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
7878
        if msg:
7879
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
7880
                             hint="remove unused LVs manually")
7881

    
7882
  def _ReleaseNodeLock(self, node_name):
7883
    """Releases the lock for a given node."""
7884
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
7885

    
7886
  def _ExecDrbd8DiskOnly(self, feedback_fn):
7887
    """Replace a disk on the primary or secondary for DRBD 8.
7888

7889
    The algorithm for replace is quite complicated:
7890

7891
      1. for each disk to be replaced:
7892

7893
        1. create new LVs on the target node with unique names
7894
        1. detach old LVs from the drbd device
7895
        1. rename old LVs to name_replaced.<time_t>
7896
        1. rename new LVs to old LVs
7897
        1. attach the new LVs (with the old names now) to the drbd device
7898

7899
      1. wait for sync across all devices
7900

7901
      1. for each modified disk:
7902

7903
        1. remove old LVs (which have the name name_replaces.<time_t>)
7904

7905
    Failures are not very well handled.
7906

7907
    """
7908
    steps_total = 6
7909

    
7910
    # Step: check device activation
7911
    self.lu.LogStep(1, steps_total, "Check device existence")
7912
    self._CheckDisksExistence([self.other_node, self.target_node])
7913
    self._CheckVolumeGroup([self.target_node, self.other_node])
7914

    
7915
    # Step: check other node consistency
7916
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7917
    self._CheckDisksConsistency(self.other_node,
7918
                                self.other_node == self.instance.primary_node,
7919
                                False)
7920

    
7921
    # Step: create new storage
7922
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7923
    iv_names = self._CreateNewStorage(self.target_node)
7924

    
7925
    # Step: for each lv, detach+rename*2+attach
7926
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7927
    for dev, old_lvs, new_lvs in iv_names.itervalues():
7928
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
7929

    
7930
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
7931
                                                     old_lvs)
7932
      result.Raise("Can't detach drbd from local storage on node"
7933
                   " %s for device %s" % (self.target_node, dev.iv_name))
7934
      #dev.children = []
7935
      #cfg.Update(instance)
7936

    
7937
      # ok, we created the new LVs, so now we know we have the needed
7938
      # storage; as such, we proceed on the target node to rename
7939
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
7940
      # using the assumption that logical_id == physical_id (which in
7941
      # turn is the unique_id on that node)
7942

    
7943
      # FIXME(iustin): use a better name for the replaced LVs
7944
      temp_suffix = int(time.time())
7945
      ren_fn = lambda d, suff: (d.physical_id[0],
7946
                                d.physical_id[1] + "_replaced-%s" % suff)
7947

    
7948
      # Build the rename list based on what LVs exist on the node
7949
      rename_old_to_new = []
7950
      for to_ren in old_lvs:
7951
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
7952
        if not result.fail_msg and result.payload:
7953
          # device exists
7954
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
7955

    
7956
      self.lu.LogInfo("Renaming the old LVs on the target node")
7957
      result = self.rpc.call_blockdev_rename(self.target_node,
7958
                                             rename_old_to_new)
7959
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
7960

    
7961
      # Now we rename the new LVs to the old LVs
7962
      self.lu.LogInfo("Renaming the new LVs on the target node")
7963
      rename_new_to_old = [(new, old.physical_id)
7964
                           for old, new in zip(old_lvs, new_lvs)]
7965
      result = self.rpc.call_blockdev_rename(self.target_node,
7966
                                             rename_new_to_old)
7967
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
7968

    
7969
      for old, new in zip(old_lvs, new_lvs):
7970
        new.logical_id = old.logical_id
7971
        self.cfg.SetDiskID(new, self.target_node)
7972

    
7973
      for disk in old_lvs:
7974
        disk.logical_id = ren_fn(disk, temp_suffix)
7975
        self.cfg.SetDiskID(disk, self.target_node)
7976

    
7977
      # Now that the new lvs have the old name, we can add them to the device
7978
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
7979
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
7980
                                                  new_lvs)
7981
      msg = result.fail_msg
7982
      if msg:
7983
        for new_lv in new_lvs:
7984
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
7985
                                               new_lv).fail_msg
7986
          if msg2:
7987
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
7988
                               hint=("cleanup manually the unused logical"
7989
                                     "volumes"))
7990
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
7991

    
7992
      dev.children = new_lvs
7993

    
7994
      self.cfg.Update(self.instance, feedback_fn)
7995

    
7996
    cstep = 5
7997
    if self.early_release:
7998
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7999
      cstep += 1
8000
      self._RemoveOldStorage(self.target_node, iv_names)
8001
      # WARNING: we release both node locks here, do not do other RPCs
8002
      # than WaitForSync to the primary node
8003
      self._ReleaseNodeLock([self.target_node, self.other_node])
8004

    
8005
    # Wait for sync
8006
    # This can fail as the old devices are degraded and _WaitForSync
8007
    # does a combined result over all disks, so we don't check its return value
8008
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8009
    cstep += 1
8010
    _WaitForSync(self.lu, self.instance)
8011

    
8012
    # Check all devices manually
8013
    self._CheckDevices(self.instance.primary_node, iv_names)
8014

    
8015
    # Step: remove old storage
8016
    if not self.early_release:
8017
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8018
      cstep += 1
8019
      self._RemoveOldStorage(self.target_node, iv_names)
8020

    
8021
  def _ExecDrbd8Secondary(self, feedback_fn):
8022
    """Replace the secondary node for DRBD 8.
8023

8024
    The algorithm for replace is quite complicated:
8025
      - for all disks of the instance:
8026
        - create new LVs on the new node with same names
8027
        - shutdown the drbd device on the old secondary
8028
        - disconnect the drbd network on the primary
8029
        - create the drbd device on the new secondary
8030
        - network attach the drbd on the primary, using an artifice:
8031
          the drbd code for Attach() will connect to the network if it
8032
          finds a device which is connected to the good local disks but
8033
          not network enabled
8034
      - wait for sync across all devices
8035
      - remove all disks from the old secondary
8036

8037
    Failures are not very well handled.
8038

8039
    """
8040
    steps_total = 6
8041

    
8042
    # Step: check device activation
8043
    self.lu.LogStep(1, steps_total, "Check device existence")
8044
    self._CheckDisksExistence([self.instance.primary_node])
8045
    self._CheckVolumeGroup([self.instance.primary_node])
8046

    
8047
    # Step: check other node consistency
8048
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8049
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8050

    
8051
    # Step: create new storage
8052
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8053
    for idx, dev in enumerate(self.instance.disks):
8054
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8055
                      (self.new_node, idx))
8056
      # we pass force_create=True to force LVM creation
8057
      for new_lv in dev.children:
8058
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8059
                        _GetInstanceInfoText(self.instance), False)
8060

    
8061
    # Step 4: dbrd minors and drbd setups changes
8062
    # after this, we must manually remove the drbd minors on both the
8063
    # error and the success paths
8064
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8065
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8066
                                         for dev in self.instance.disks],
8067
                                        self.instance.name)
8068
    logging.debug("Allocated minors %r", minors)
8069

    
8070
    iv_names = {}
8071
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8072
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8073
                      (self.new_node, idx))
8074
      # create new devices on new_node; note that we create two IDs:
8075
      # one without port, so the drbd will be activated without
8076
      # networking information on the new node at this stage, and one
8077
      # with network, for the latter activation in step 4
8078
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8079
      if self.instance.primary_node == o_node1:
8080
        p_minor = o_minor1
8081
      else:
8082
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8083
        p_minor = o_minor2
8084

    
8085
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8086
                      p_minor, new_minor, o_secret)
8087
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8088
                    p_minor, new_minor, o_secret)
8089

    
8090
      iv_names[idx] = (dev, dev.children, new_net_id)
8091
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8092
                    new_net_id)
8093
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8094
                              logical_id=new_alone_id,
8095
                              children=dev.children,
8096
                              size=dev.size)
8097
      try:
8098
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8099
                              _GetInstanceInfoText(self.instance), False)
8100
      except errors.GenericError:
8101
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8102
        raise
8103

    
8104
    # We have new devices, shutdown the drbd on the old secondary
8105
    for idx, dev in enumerate(self.instance.disks):
8106
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8107
      self.cfg.SetDiskID(dev, self.target_node)
8108
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8109
      if msg:
8110
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8111
                           "node: %s" % (idx, msg),
8112
                           hint=("Please cleanup this device manually as"
8113
                                 " soon as possible"))
8114

    
8115
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8116
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8117
                                               self.node_secondary_ip,
8118
                                               self.instance.disks)\
8119
                                              [self.instance.primary_node]
8120

    
8121
    msg = result.fail_msg
8122
    if msg:
8123
      # detaches didn't succeed (unlikely)
8124
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8125
      raise errors.OpExecError("Can't detach the disks from the network on"
8126
                               " old node: %s" % (msg,))
8127

    
8128
    # if we managed to detach at least one, we update all the disks of
8129
    # the instance to point to the new secondary
8130
    self.lu.LogInfo("Updating instance configuration")
8131
    for dev, _, new_logical_id in iv_names.itervalues():
8132
      dev.logical_id = new_logical_id
8133
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8134

    
8135
    self.cfg.Update(self.instance, feedback_fn)
8136

    
8137
    # and now perform the drbd attach
8138
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8139
                    " (standalone => connected)")
8140
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8141
                                            self.new_node],
8142
                                           self.node_secondary_ip,
8143
                                           self.instance.disks,
8144
                                           self.instance.name,
8145
                                           False)
8146
    for to_node, to_result in result.items():
8147
      msg = to_result.fail_msg
8148
      if msg:
8149
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8150
                           to_node, msg,
8151
                           hint=("please do a gnt-instance info to see the"
8152
                                 " status of disks"))
8153
    cstep = 5
8154
    if self.early_release:
8155
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8156
      cstep += 1
8157
      self._RemoveOldStorage(self.target_node, iv_names)
8158
      # WARNING: we release all node locks here, do not do other RPCs
8159
      # than WaitForSync to the primary node
8160
      self._ReleaseNodeLock([self.instance.primary_node,
8161
                             self.target_node,
8162
                             self.new_node])
8163

    
8164
    # Wait for sync
8165
    # This can fail as the old devices are degraded and _WaitForSync
8166
    # does a combined result over all disks, so we don't check its return value
8167
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8168
    cstep += 1
8169
    _WaitForSync(self.lu, self.instance)
8170

    
8171
    # Check all devices manually
8172
    self._CheckDevices(self.instance.primary_node, iv_names)
8173

    
8174
    # Step: remove old storage
8175
    if not self.early_release:
8176
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8177
      self._RemoveOldStorage(self.target_node, iv_names)
8178

    
8179

    
8180
class LURepairNodeStorage(NoHooksLU):
8181
  """Repairs the volume group on a node.
8182

8183
  """
8184
  _OP_PARAMS = [
8185
    _PNodeName,
8186
    ("storage_type", _NoDefault, _CheckStorageType),
8187
    ("name", _NoDefault, _TNonEmptyString),
8188
    ("ignore_consistency", False, _TBool),
8189
    ]
8190
  REQ_BGL = False
8191

    
8192
  def CheckArguments(self):
8193
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8194

    
8195
    storage_type = self.op.storage_type
8196

    
8197
    if (constants.SO_FIX_CONSISTENCY not in
8198
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8199
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8200
                                 " repaired" % storage_type,
8201
                                 errors.ECODE_INVAL)
8202

    
8203
  def ExpandNames(self):
8204
    self.needed_locks = {
8205
      locking.LEVEL_NODE: [self.op.node_name],
8206
      }
8207

    
8208
  def _CheckFaultyDisks(self, instance, node_name):
8209
    """Ensure faulty disks abort the opcode or at least warn."""
8210
    try:
8211
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8212
                                  node_name, True):
8213
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8214
                                   " node '%s'" % (instance.name, node_name),
8215
                                   errors.ECODE_STATE)
8216
    except errors.OpPrereqError, err:
8217
      if self.op.ignore_consistency:
8218
        self.proc.LogWarning(str(err.args[0]))
8219
      else:
8220
        raise
8221

    
8222
  def CheckPrereq(self):
8223
    """Check prerequisites.
8224

8225
    """
8226
    # Check whether any instance on this node has faulty disks
8227
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8228
      if not inst.admin_up:
8229
        continue
8230
      check_nodes = set(inst.all_nodes)
8231
      check_nodes.discard(self.op.node_name)
8232
      for inst_node_name in check_nodes:
8233
        self._CheckFaultyDisks(inst, inst_node_name)
8234

    
8235
  def Exec(self, feedback_fn):
8236
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8237
                (self.op.name, self.op.node_name))
8238

    
8239
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8240
    result = self.rpc.call_storage_execute(self.op.node_name,
8241
                                           self.op.storage_type, st_args,
8242
                                           self.op.name,
8243
                                           constants.SO_FIX_CONSISTENCY)
8244
    result.Raise("Failed to repair storage unit '%s' on %s" %
8245
                 (self.op.name, self.op.node_name))
8246

    
8247

    
8248
class LUNodeEvacuationStrategy(NoHooksLU):
8249
  """Computes the node evacuation strategy.
8250

8251
  """
8252
  _OP_PARAMS = [
8253
    ("nodes", _NoDefault, _TListOf(_TNonEmptyString)),
8254
    ("remote_node", None, _TMaybeString),
8255
    ("iallocator", None, _TMaybeString),
8256
    ]
8257
  REQ_BGL = False
8258

    
8259
  def CheckArguments(self):
8260
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8261

    
8262
  def ExpandNames(self):
8263
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8264
    self.needed_locks = locks = {}
8265
    if self.op.remote_node is None:
8266
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8267
    else:
8268
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8269
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8270

    
8271
  def Exec(self, feedback_fn):
8272
    if self.op.remote_node is not None:
8273
      instances = []
8274
      for node in self.op.nodes:
8275
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8276
      result = []
8277
      for i in instances:
8278
        if i.primary_node == self.op.remote_node:
8279
          raise errors.OpPrereqError("Node %s is the primary node of"
8280
                                     " instance %s, cannot use it as"
8281
                                     " secondary" %
8282
                                     (self.op.remote_node, i.name),
8283
                                     errors.ECODE_INVAL)
8284
        result.append([i.name, self.op.remote_node])
8285
    else:
8286
      ial = IAllocator(self.cfg, self.rpc,
8287
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8288
                       evac_nodes=self.op.nodes)
8289
      ial.Run(self.op.iallocator, validate=True)
8290
      if not ial.success:
8291
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8292
                                 errors.ECODE_NORES)
8293
      result = ial.result
8294
    return result
8295

    
8296

    
8297
class LUGrowDisk(LogicalUnit):
8298
  """Grow a disk of an instance.
8299

8300
  """
8301
  HPATH = "disk-grow"
8302
  HTYPE = constants.HTYPE_INSTANCE
8303
  _OP_PARAMS = [
8304
    _PInstanceName,
8305
    ("disk", _NoDefault, _TInt),
8306
    ("amount", _NoDefault, _TInt),
8307
    ("wait_for_sync", True, _TBool),
8308
    ]
8309
  REQ_BGL = False
8310

    
8311
  def ExpandNames(self):
8312
    self._ExpandAndLockInstance()
8313
    self.needed_locks[locking.LEVEL_NODE] = []
8314
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8315

    
8316
  def DeclareLocks(self, level):
8317
    if level == locking.LEVEL_NODE:
8318
      self._LockInstancesNodes()
8319

    
8320
  def BuildHooksEnv(self):
8321
    """Build hooks env.
8322

8323
    This runs on the master, the primary and all the secondaries.
8324

8325
    """
8326
    env = {
8327
      "DISK": self.op.disk,
8328
      "AMOUNT": self.op.amount,
8329
      }
8330
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8331
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8332
    return env, nl, nl
8333

    
8334
  def CheckPrereq(self):
8335
    """Check prerequisites.
8336

8337
    This checks that the instance is in the cluster.
8338

8339
    """
8340
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8341
    assert instance is not None, \
8342
      "Cannot retrieve locked instance %s" % self.op.instance_name
8343
    nodenames = list(instance.all_nodes)
8344
    for node in nodenames:
8345
      _CheckNodeOnline(self, node)
8346

    
8347
    self.instance = instance
8348

    
8349
    if instance.disk_template not in constants.DTS_GROWABLE:
8350
      raise errors.OpPrereqError("Instance's disk layout does not support"
8351
                                 " growing.", errors.ECODE_INVAL)
8352

    
8353
    self.disk = instance.FindDisk(self.op.disk)
8354

    
8355
    if instance.disk_template != constants.DT_FILE:
8356
      # TODO: check the free disk space for file, when that feature will be
8357
      # supported
8358
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
8359

    
8360
  def Exec(self, feedback_fn):
8361
    """Execute disk grow.
8362

8363
    """
8364
    instance = self.instance
8365
    disk = self.disk
8366

    
8367
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8368
    if not disks_ok:
8369
      raise errors.OpExecError("Cannot activate block device to grow")
8370

    
8371
    for node in instance.all_nodes:
8372
      self.cfg.SetDiskID(disk, node)
8373
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8374
      result.Raise("Grow request failed to node %s" % node)
8375

    
8376
      # TODO: Rewrite code to work properly
8377
      # DRBD goes into sync mode for a short amount of time after executing the
8378
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8379
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8380
      # time is a work-around.
8381
      time.sleep(5)
8382

    
8383
    disk.RecordGrow(self.op.amount)
8384
    self.cfg.Update(instance, feedback_fn)
8385
    if self.op.wait_for_sync:
8386
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8387
      if disk_abort:
8388
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8389
                             " status.\nPlease check the instance.")
8390
      if not instance.admin_up:
8391
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8392
    elif not instance.admin_up:
8393
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8394
                           " not supposed to be running because no wait for"
8395
                           " sync mode was requested.")
8396

    
8397

    
8398
class LUQueryInstanceData(NoHooksLU):
8399
  """Query runtime instance data.
8400

8401
  """
8402
  _OP_PARAMS = [
8403
    ("instances", _EmptyList, _TListOf(_TNonEmptyString)),
8404
    ("static", False, _TBool),
8405
    ]
8406
  REQ_BGL = False
8407

    
8408
  def ExpandNames(self):
8409
    self.needed_locks = {}
8410
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8411

    
8412
    if self.op.instances:
8413
      self.wanted_names = []
8414
      for name in self.op.instances:
8415
        full_name = _ExpandInstanceName(self.cfg, name)
8416
        self.wanted_names.append(full_name)
8417
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8418
    else:
8419
      self.wanted_names = None
8420
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8421

    
8422
    self.needed_locks[locking.LEVEL_NODE] = []
8423
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8424

    
8425
  def DeclareLocks(self, level):
8426
    if level == locking.LEVEL_NODE:
8427
      self._LockInstancesNodes()
8428

    
8429
  def CheckPrereq(self):
8430
    """Check prerequisites.
8431

8432
    This only checks the optional instance list against the existing names.
8433

8434
    """
8435
    if self.wanted_names is None:
8436
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8437

    
8438
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8439
                             in self.wanted_names]
8440

    
8441
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8442
    """Returns the status of a block device
8443

8444
    """
8445
    if self.op.static or not node:
8446
      return None
8447

    
8448
    self.cfg.SetDiskID(dev, node)
8449

    
8450
    result = self.rpc.call_blockdev_find(node, dev)
8451
    if result.offline:
8452
      return None
8453

    
8454
    result.Raise("Can't compute disk status for %s" % instance_name)
8455

    
8456
    status = result.payload
8457
    if status is None:
8458
      return None
8459

    
8460
    return (status.dev_path, status.major, status.minor,
8461
            status.sync_percent, status.estimated_time,
8462
            status.is_degraded, status.ldisk_status)
8463

    
8464
  def _ComputeDiskStatus(self, instance, snode, dev):
8465
    """Compute block device status.
8466

8467
    """
8468
    if dev.dev_type in constants.LDS_DRBD:
8469
      # we change the snode then (otherwise we use the one passed in)
8470
      if dev.logical_id[0] == instance.primary_node:
8471
        snode = dev.logical_id[1]
8472
      else:
8473
        snode = dev.logical_id[0]
8474

    
8475
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8476
                                              instance.name, dev)
8477
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8478

    
8479
    if dev.children:
8480
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8481
                      for child in dev.children]
8482
    else:
8483
      dev_children = []
8484

    
8485
    data = {
8486
      "iv_name": dev.iv_name,
8487
      "dev_type": dev.dev_type,
8488
      "logical_id": dev.logical_id,
8489
      "physical_id": dev.physical_id,
8490
      "pstatus": dev_pstatus,
8491
      "sstatus": dev_sstatus,
8492
      "children": dev_children,
8493
      "mode": dev.mode,
8494
      "size": dev.size,
8495
      }
8496

    
8497
    return data
8498

    
8499
  def Exec(self, feedback_fn):
8500
    """Gather and return data"""
8501
    result = {}
8502

    
8503
    cluster = self.cfg.GetClusterInfo()
8504

    
8505
    for instance in self.wanted_instances:
8506
      if not self.op.static:
8507
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8508
                                                  instance.name,
8509
                                                  instance.hypervisor)
8510
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8511
        remote_info = remote_info.payload
8512
        if remote_info and "state" in remote_info:
8513
          remote_state = "up"
8514
        else:
8515
          remote_state = "down"
8516
      else:
8517
        remote_state = None
8518
      if instance.admin_up:
8519
        config_state = "up"
8520
      else:
8521
        config_state = "down"
8522

    
8523
      disks = [self._ComputeDiskStatus(instance, None, device)
8524
               for device in instance.disks]
8525

    
8526
      idict = {
8527
        "name": instance.name,
8528
        "config_state": config_state,
8529
        "run_state": remote_state,
8530
        "pnode": instance.primary_node,
8531
        "snodes": instance.secondary_nodes,
8532
        "os": instance.os,
8533
        # this happens to be the same format used for hooks
8534
        "nics": _NICListToTuple(self, instance.nics),
8535
        "disk_template": instance.disk_template,
8536
        "disks": disks,
8537
        "hypervisor": instance.hypervisor,
8538
        "network_port": instance.network_port,
8539
        "hv_instance": instance.hvparams,
8540
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8541
        "be_instance": instance.beparams,
8542
        "be_actual": cluster.FillBE(instance),
8543
        "os_instance": instance.osparams,
8544
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8545
        "serial_no": instance.serial_no,
8546
        "mtime": instance.mtime,
8547
        "ctime": instance.ctime,
8548
        "uuid": instance.uuid,
8549
        }
8550

    
8551
      result[instance.name] = idict
8552

    
8553
    return result
8554

    
8555

    
8556
class LUSetInstanceParams(LogicalUnit):
8557
  """Modifies an instances's parameters.
8558

8559
  """
8560
  HPATH = "instance-modify"
8561
  HTYPE = constants.HTYPE_INSTANCE
8562
  _OP_PARAMS = [
8563
    _PInstanceName,
8564
    ("nics", _EmptyList, _TList),
8565
    ("disks", _EmptyList, _TList),
8566
    ("beparams", _EmptyDict, _TDict),
8567
    ("hvparams", _EmptyDict, _TDict),
8568
    ("disk_template", None, _TMaybeString),
8569
    ("remote_node", None, _TMaybeString),
8570
    ("os_name", None, _TMaybeString),
8571
    ("force_variant", False, _TBool),
8572
    ("osparams", None, _TOr(_TDict, _TNone)),
8573
    _PForce,
8574
    ]
8575
  REQ_BGL = False
8576

    
8577
  def CheckArguments(self):
8578
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8579
            self.op.hvparams or self.op.beparams or self.op.os_name):
8580
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8581

    
8582
    if self.op.hvparams:
8583
      _CheckGlobalHvParams(self.op.hvparams)
8584

    
8585
    # Disk validation
8586
    disk_addremove = 0
8587
    for disk_op, disk_dict in self.op.disks:
8588
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8589
      if disk_op == constants.DDM_REMOVE:
8590
        disk_addremove += 1
8591
        continue
8592
      elif disk_op == constants.DDM_ADD:
8593
        disk_addremove += 1
8594
      else:
8595
        if not isinstance(disk_op, int):
8596
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8597
        if not isinstance(disk_dict, dict):
8598
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8599
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8600

    
8601
      if disk_op == constants.DDM_ADD:
8602
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8603
        if mode not in constants.DISK_ACCESS_SET:
8604
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8605
                                     errors.ECODE_INVAL)
8606
        size = disk_dict.get('size', None)
8607
        if size is None:
8608
          raise errors.OpPrereqError("Required disk parameter size missing",
8609
                                     errors.ECODE_INVAL)
8610
        try:
8611
          size = int(size)
8612
        except (TypeError, ValueError), err:
8613
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8614
                                     str(err), errors.ECODE_INVAL)
8615
        disk_dict['size'] = size
8616
      else:
8617
        # modification of disk
8618
        if 'size' in disk_dict:
8619
          raise errors.OpPrereqError("Disk size change not possible, use"
8620
                                     " grow-disk", errors.ECODE_INVAL)
8621

    
8622
    if disk_addremove > 1:
8623
      raise errors.OpPrereqError("Only one disk add or remove operation"
8624
                                 " supported at a time", errors.ECODE_INVAL)
8625

    
8626
    if self.op.disks and self.op.disk_template is not None:
8627
      raise errors.OpPrereqError("Disk template conversion and other disk"
8628
                                 " changes not supported at the same time",
8629
                                 errors.ECODE_INVAL)
8630

    
8631
    if self.op.disk_template:
8632
      _CheckDiskTemplate(self.op.disk_template)
8633
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
8634
          self.op.remote_node is None):
8635
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
8636
                                   " one requires specifying a secondary node",
8637
                                   errors.ECODE_INVAL)
8638

    
8639
    # NIC validation
8640
    nic_addremove = 0
8641
    for nic_op, nic_dict in self.op.nics:
8642
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
8643
      if nic_op == constants.DDM_REMOVE:
8644
        nic_addremove += 1
8645
        continue
8646
      elif nic_op == constants.DDM_ADD:
8647
        nic_addremove += 1
8648
      else:
8649
        if not isinstance(nic_op, int):
8650
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
8651
        if not isinstance(nic_dict, dict):
8652
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
8653
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8654

    
8655
      # nic_dict should be a dict
8656
      nic_ip = nic_dict.get('ip', None)
8657
      if nic_ip is not None:
8658
        if nic_ip.lower() == constants.VALUE_NONE:
8659
          nic_dict['ip'] = None
8660
        else:
8661
          if not netutils.IsValidIP4(nic_ip):
8662
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
8663
                                       errors.ECODE_INVAL)
8664

    
8665
      nic_bridge = nic_dict.get('bridge', None)
8666
      nic_link = nic_dict.get('link', None)
8667
      if nic_bridge and nic_link:
8668
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
8669
                                   " at the same time", errors.ECODE_INVAL)
8670
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
8671
        nic_dict['bridge'] = None
8672
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
8673
        nic_dict['link'] = None
8674

    
8675
      if nic_op == constants.DDM_ADD:
8676
        nic_mac = nic_dict.get('mac', None)
8677
        if nic_mac is None:
8678
          nic_dict['mac'] = constants.VALUE_AUTO
8679

    
8680
      if 'mac' in nic_dict:
8681
        nic_mac = nic_dict['mac']
8682
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8683
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
8684

    
8685
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
8686
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
8687
                                     " modifying an existing nic",
8688
                                     errors.ECODE_INVAL)
8689

    
8690
    if nic_addremove > 1:
8691
      raise errors.OpPrereqError("Only one NIC add or remove operation"
8692
                                 " supported at a time", errors.ECODE_INVAL)
8693

    
8694
  def ExpandNames(self):
8695
    self._ExpandAndLockInstance()
8696
    self.needed_locks[locking.LEVEL_NODE] = []
8697
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8698

    
8699
  def DeclareLocks(self, level):
8700
    if level == locking.LEVEL_NODE:
8701
      self._LockInstancesNodes()
8702
      if self.op.disk_template and self.op.remote_node:
8703
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8704
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
8705

    
8706
  def BuildHooksEnv(self):
8707
    """Build hooks env.
8708

8709
    This runs on the master, primary and secondaries.
8710

8711
    """
8712
    args = dict()
8713
    if constants.BE_MEMORY in self.be_new:
8714
      args['memory'] = self.be_new[constants.BE_MEMORY]
8715
    if constants.BE_VCPUS in self.be_new:
8716
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
8717
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
8718
    # information at all.
8719
    if self.op.nics:
8720
      args['nics'] = []
8721
      nic_override = dict(self.op.nics)
8722
      for idx, nic in enumerate(self.instance.nics):
8723
        if idx in nic_override:
8724
          this_nic_override = nic_override[idx]
8725
        else:
8726
          this_nic_override = {}
8727
        if 'ip' in this_nic_override:
8728
          ip = this_nic_override['ip']
8729
        else:
8730
          ip = nic.ip
8731
        if 'mac' in this_nic_override:
8732
          mac = this_nic_override['mac']
8733
        else:
8734
          mac = nic.mac
8735
        if idx in self.nic_pnew:
8736
          nicparams = self.nic_pnew[idx]
8737
        else:
8738
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
8739
        mode = nicparams[constants.NIC_MODE]
8740
        link = nicparams[constants.NIC_LINK]
8741
        args['nics'].append((ip, mac, mode, link))
8742
      if constants.DDM_ADD in nic_override:
8743
        ip = nic_override[constants.DDM_ADD].get('ip', None)
8744
        mac = nic_override[constants.DDM_ADD]['mac']
8745
        nicparams = self.nic_pnew[constants.DDM_ADD]
8746
        mode = nicparams[constants.NIC_MODE]
8747
        link = nicparams[constants.NIC_LINK]
8748
        args['nics'].append((ip, mac, mode, link))
8749
      elif constants.DDM_REMOVE in nic_override:
8750
        del args['nics'][-1]
8751

    
8752
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
8753
    if self.op.disk_template:
8754
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
8755
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8756
    return env, nl, nl
8757

    
8758
  def CheckPrereq(self):
8759
    """Check prerequisites.
8760

8761
    This only checks the instance list against the existing names.
8762

8763
    """
8764
    # checking the new params on the primary/secondary nodes
8765

    
8766
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8767
    cluster = self.cluster = self.cfg.GetClusterInfo()
8768
    assert self.instance is not None, \
8769
      "Cannot retrieve locked instance %s" % self.op.instance_name
8770
    pnode = instance.primary_node
8771
    nodelist = list(instance.all_nodes)
8772

    
8773
    # OS change
8774
    if self.op.os_name and not self.op.force:
8775
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
8776
                      self.op.force_variant)
8777
      instance_os = self.op.os_name
8778
    else:
8779
      instance_os = instance.os
8780

    
8781
    if self.op.disk_template:
8782
      if instance.disk_template == self.op.disk_template:
8783
        raise errors.OpPrereqError("Instance already has disk template %s" %
8784
                                   instance.disk_template, errors.ECODE_INVAL)
8785

    
8786
      if (instance.disk_template,
8787
          self.op.disk_template) not in self._DISK_CONVERSIONS:
8788
        raise errors.OpPrereqError("Unsupported disk template conversion from"
8789
                                   " %s to %s" % (instance.disk_template,
8790
                                                  self.op.disk_template),
8791
                                   errors.ECODE_INVAL)
8792
      _CheckInstanceDown(self, instance, "cannot change disk template")
8793
      if self.op.disk_template in constants.DTS_NET_MIRROR:
8794
        if self.op.remote_node == pnode:
8795
          raise errors.OpPrereqError("Given new secondary node %s is the same"
8796
                                     " as the primary node of the instance" %
8797
                                     self.op.remote_node, errors.ECODE_STATE)
8798
        _CheckNodeOnline(self, self.op.remote_node)
8799
        _CheckNodeNotDrained(self, self.op.remote_node)
8800
        disks = [{"size": d.size} for d in instance.disks]
8801
        required = _ComputeDiskSize(self.op.disk_template, disks)
8802
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
8803

    
8804
    # hvparams processing
8805
    if self.op.hvparams:
8806
      hv_type = instance.hypervisor
8807
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
8808
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
8809
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
8810

    
8811
      # local check
8812
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
8813
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
8814
      self.hv_new = hv_new # the new actual values
8815
      self.hv_inst = i_hvdict # the new dict (without defaults)
8816
    else:
8817
      self.hv_new = self.hv_inst = {}
8818

    
8819
    # beparams processing
8820
    if self.op.beparams:
8821
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
8822
                                   use_none=True)
8823
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
8824
      be_new = cluster.SimpleFillBE(i_bedict)
8825
      self.be_new = be_new # the new actual values
8826
      self.be_inst = i_bedict # the new dict (without defaults)
8827
    else:
8828
      self.be_new = self.be_inst = {}
8829

    
8830
    # osparams processing
8831
    if self.op.osparams:
8832
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
8833
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
8834
      self.os_new = cluster.SimpleFillOS(instance_os, i_osdict)
8835
      self.os_inst = i_osdict # the new dict (without defaults)
8836
    else:
8837
      self.os_new = self.os_inst = {}
8838

    
8839
    self.warn = []
8840

    
8841
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
8842
      mem_check_list = [pnode]
8843
      if be_new[constants.BE_AUTO_BALANCE]:
8844
        # either we changed auto_balance to yes or it was from before
8845
        mem_check_list.extend(instance.secondary_nodes)
8846
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
8847
                                                  instance.hypervisor)
8848
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
8849
                                         instance.hypervisor)
8850
      pninfo = nodeinfo[pnode]
8851
      msg = pninfo.fail_msg
8852
      if msg:
8853
        # Assume the primary node is unreachable and go ahead
8854
        self.warn.append("Can't get info from primary node %s: %s" %
8855
                         (pnode,  msg))
8856
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
8857
        self.warn.append("Node data from primary node %s doesn't contain"
8858
                         " free memory information" % pnode)
8859
      elif instance_info.fail_msg:
8860
        self.warn.append("Can't get instance runtime information: %s" %
8861
                        instance_info.fail_msg)
8862
      else:
8863
        if instance_info.payload:
8864
          current_mem = int(instance_info.payload['memory'])
8865
        else:
8866
          # Assume instance not running
8867
          # (there is a slight race condition here, but it's not very probable,
8868
          # and we have no other way to check)
8869
          current_mem = 0
8870
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
8871
                    pninfo.payload['memory_free'])
8872
        if miss_mem > 0:
8873
          raise errors.OpPrereqError("This change will prevent the instance"
8874
                                     " from starting, due to %d MB of memory"
8875
                                     " missing on its primary node" % miss_mem,
8876
                                     errors.ECODE_NORES)
8877

    
8878
      if be_new[constants.BE_AUTO_BALANCE]:
8879
        for node, nres in nodeinfo.items():
8880
          if node not in instance.secondary_nodes:
8881
            continue
8882
          msg = nres.fail_msg
8883
          if msg:
8884
            self.warn.append("Can't get info from secondary node %s: %s" %
8885
                             (node, msg))
8886
          elif not isinstance(nres.payload.get('memory_free', None), int):
8887
            self.warn.append("Secondary node %s didn't return free"
8888
                             " memory information" % node)
8889
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
8890
            self.warn.append("Not enough memory to failover instance to"
8891
                             " secondary node %s" % node)
8892

    
8893
    # NIC processing
8894
    self.nic_pnew = {}
8895
    self.nic_pinst = {}
8896
    for nic_op, nic_dict in self.op.nics:
8897
      if nic_op == constants.DDM_REMOVE:
8898
        if not instance.nics:
8899
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
8900
                                     errors.ECODE_INVAL)
8901
        continue
8902
      if nic_op != constants.DDM_ADD:
8903
        # an existing nic
8904
        if not instance.nics:
8905
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
8906
                                     " no NICs" % nic_op,
8907
                                     errors.ECODE_INVAL)
8908
        if nic_op < 0 or nic_op >= len(instance.nics):
8909
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
8910
                                     " are 0 to %d" %
8911
                                     (nic_op, len(instance.nics) - 1),
8912
                                     errors.ECODE_INVAL)
8913
        old_nic_params = instance.nics[nic_op].nicparams
8914
        old_nic_ip = instance.nics[nic_op].ip
8915
      else:
8916
        old_nic_params = {}
8917
        old_nic_ip = None
8918

    
8919
      update_params_dict = dict([(key, nic_dict[key])
8920
                                 for key in constants.NICS_PARAMETERS
8921
                                 if key in nic_dict])
8922

    
8923
      if 'bridge' in nic_dict:
8924
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
8925

    
8926
      new_nic_params = _GetUpdatedParams(old_nic_params,
8927
                                         update_params_dict)
8928
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
8929
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
8930
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
8931
      self.nic_pinst[nic_op] = new_nic_params
8932
      self.nic_pnew[nic_op] = new_filled_nic_params
8933
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
8934

    
8935
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
8936
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
8937
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
8938
        if msg:
8939
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
8940
          if self.op.force:
8941
            self.warn.append(msg)
8942
          else:
8943
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
8944
      if new_nic_mode == constants.NIC_MODE_ROUTED:
8945
        if 'ip' in nic_dict:
8946
          nic_ip = nic_dict['ip']
8947
        else:
8948
          nic_ip = old_nic_ip
8949
        if nic_ip is None:
8950
          raise errors.OpPrereqError('Cannot set the nic ip to None'
8951
                                     ' on a routed nic', errors.ECODE_INVAL)
8952
      if 'mac' in nic_dict:
8953
        nic_mac = nic_dict['mac']
8954
        if nic_mac is None:
8955
          raise errors.OpPrereqError('Cannot set the nic mac to None',
8956
                                     errors.ECODE_INVAL)
8957
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8958
          # otherwise generate the mac
8959
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
8960
        else:
8961
          # or validate/reserve the current one
8962
          try:
8963
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
8964
          except errors.ReservationError:
8965
            raise errors.OpPrereqError("MAC address %s already in use"
8966
                                       " in cluster" % nic_mac,
8967
                                       errors.ECODE_NOTUNIQUE)
8968

    
8969
    # DISK processing
8970
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
8971
      raise errors.OpPrereqError("Disk operations not supported for"
8972
                                 " diskless instances",
8973
                                 errors.ECODE_INVAL)
8974
    for disk_op, _ in self.op.disks:
8975
      if disk_op == constants.DDM_REMOVE:
8976
        if len(instance.disks) == 1:
8977
          raise errors.OpPrereqError("Cannot remove the last disk of"
8978
                                     " an instance", errors.ECODE_INVAL)
8979
        _CheckInstanceDown(self, instance, "cannot remove disks")
8980

    
8981
      if (disk_op == constants.DDM_ADD and
8982
          len(instance.nics) >= constants.MAX_DISKS):
8983
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
8984
                                   " add more" % constants.MAX_DISKS,
8985
                                   errors.ECODE_STATE)
8986
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
8987
        # an existing disk
8988
        if disk_op < 0 or disk_op >= len(instance.disks):
8989
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
8990
                                     " are 0 to %d" %
8991
                                     (disk_op, len(instance.disks)),
8992
                                     errors.ECODE_INVAL)
8993

    
8994
    return
8995

    
8996
  def _ConvertPlainToDrbd(self, feedback_fn):
8997
    """Converts an instance from plain to drbd.
8998

8999
    """
9000
    feedback_fn("Converting template to drbd")
9001
    instance = self.instance
9002
    pnode = instance.primary_node
9003
    snode = self.op.remote_node
9004

    
9005
    # create a fake disk info for _GenerateDiskTemplate
9006
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
9007
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9008
                                      instance.name, pnode, [snode],
9009
                                      disk_info, None, None, 0)
9010
    info = _GetInstanceInfoText(instance)
9011
    feedback_fn("Creating aditional volumes...")
9012
    # first, create the missing data and meta devices
9013
    for disk in new_disks:
9014
      # unfortunately this is... not too nice
9015
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9016
                            info, True)
9017
      for child in disk.children:
9018
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9019
    # at this stage, all new LVs have been created, we can rename the
9020
    # old ones
9021
    feedback_fn("Renaming original volumes...")
9022
    rename_list = [(o, n.children[0].logical_id)
9023
                   for (o, n) in zip(instance.disks, new_disks)]
9024
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9025
    result.Raise("Failed to rename original LVs")
9026

    
9027
    feedback_fn("Initializing DRBD devices...")
9028
    # all child devices are in place, we can now create the DRBD devices
9029
    for disk in new_disks:
9030
      for node in [pnode, snode]:
9031
        f_create = node == pnode
9032
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9033

    
9034
    # at this point, the instance has been modified
9035
    instance.disk_template = constants.DT_DRBD8
9036
    instance.disks = new_disks
9037
    self.cfg.Update(instance, feedback_fn)
9038

    
9039
    # disks are created, waiting for sync
9040
    disk_abort = not _WaitForSync(self, instance)
9041
    if disk_abort:
9042
      raise errors.OpExecError("There are some degraded disks for"
9043
                               " this instance, please cleanup manually")
9044

    
9045
  def _ConvertDrbdToPlain(self, feedback_fn):
9046
    """Converts an instance from drbd to plain.
9047

9048
    """
9049
    instance = self.instance
9050
    assert len(instance.secondary_nodes) == 1
9051
    pnode = instance.primary_node
9052
    snode = instance.secondary_nodes[0]
9053
    feedback_fn("Converting template to plain")
9054

    
9055
    old_disks = instance.disks
9056
    new_disks = [d.children[0] for d in old_disks]
9057

    
9058
    # copy over size and mode
9059
    for parent, child in zip(old_disks, new_disks):
9060
      child.size = parent.size
9061
      child.mode = parent.mode
9062

    
9063
    # update instance structure
9064
    instance.disks = new_disks
9065
    instance.disk_template = constants.DT_PLAIN
9066
    self.cfg.Update(instance, feedback_fn)
9067

    
9068
    feedback_fn("Removing volumes on the secondary node...")
9069
    for disk in old_disks:
9070
      self.cfg.SetDiskID(disk, snode)
9071
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9072
      if msg:
9073
        self.LogWarning("Could not remove block device %s on node %s,"
9074
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9075

    
9076
    feedback_fn("Removing unneeded volumes on the primary node...")
9077
    for idx, disk in enumerate(old_disks):
9078
      meta = disk.children[1]
9079
      self.cfg.SetDiskID(meta, pnode)
9080
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9081
      if msg:
9082
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9083
                        " continuing anyway: %s", idx, pnode, msg)
9084

    
9085

    
9086
  def Exec(self, feedback_fn):
9087
    """Modifies an instance.
9088

9089
    All parameters take effect only at the next restart of the instance.
9090

9091
    """
9092
    # Process here the warnings from CheckPrereq, as we don't have a
9093
    # feedback_fn there.
9094
    for warn in self.warn:
9095
      feedback_fn("WARNING: %s" % warn)
9096

    
9097
    result = []
9098
    instance = self.instance
9099
    # disk changes
9100
    for disk_op, disk_dict in self.op.disks:
9101
      if disk_op == constants.DDM_REMOVE:
9102
        # remove the last disk
9103
        device = instance.disks.pop()
9104
        device_idx = len(instance.disks)
9105
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9106
          self.cfg.SetDiskID(disk, node)
9107
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9108
          if msg:
9109
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9110
                            " continuing anyway", device_idx, node, msg)
9111
        result.append(("disk/%d" % device_idx, "remove"))
9112
      elif disk_op == constants.DDM_ADD:
9113
        # add a new disk
9114
        if instance.disk_template == constants.DT_FILE:
9115
          file_driver, file_path = instance.disks[0].logical_id
9116
          file_path = os.path.dirname(file_path)
9117
        else:
9118
          file_driver = file_path = None
9119
        disk_idx_base = len(instance.disks)
9120
        new_disk = _GenerateDiskTemplate(self,
9121
                                         instance.disk_template,
9122
                                         instance.name, instance.primary_node,
9123
                                         instance.secondary_nodes,
9124
                                         [disk_dict],
9125
                                         file_path,
9126
                                         file_driver,
9127
                                         disk_idx_base)[0]
9128
        instance.disks.append(new_disk)
9129
        info = _GetInstanceInfoText(instance)
9130

    
9131
        logging.info("Creating volume %s for instance %s",
9132
                     new_disk.iv_name, instance.name)
9133
        # Note: this needs to be kept in sync with _CreateDisks
9134
        #HARDCODE
9135
        for node in instance.all_nodes:
9136
          f_create = node == instance.primary_node
9137
          try:
9138
            _CreateBlockDev(self, node, instance, new_disk,
9139
                            f_create, info, f_create)
9140
          except errors.OpExecError, err:
9141
            self.LogWarning("Failed to create volume %s (%s) on"
9142
                            " node %s: %s",
9143
                            new_disk.iv_name, new_disk, node, err)
9144
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9145
                       (new_disk.size, new_disk.mode)))
9146
      else:
9147
        # change a given disk
9148
        instance.disks[disk_op].mode = disk_dict['mode']
9149
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9150

    
9151
    if self.op.disk_template:
9152
      r_shut = _ShutdownInstanceDisks(self, instance)
9153
      if not r_shut:
9154
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
9155
                                 " proceed with disk template conversion")
9156
      mode = (instance.disk_template, self.op.disk_template)
9157
      try:
9158
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9159
      except:
9160
        self.cfg.ReleaseDRBDMinors(instance.name)
9161
        raise
9162
      result.append(("disk_template", self.op.disk_template))
9163

    
9164
    # NIC changes
9165
    for nic_op, nic_dict in self.op.nics:
9166
      if nic_op == constants.DDM_REMOVE:
9167
        # remove the last nic
9168
        del instance.nics[-1]
9169
        result.append(("nic.%d" % len(instance.nics), "remove"))
9170
      elif nic_op == constants.DDM_ADD:
9171
        # mac and bridge should be set, by now
9172
        mac = nic_dict['mac']
9173
        ip = nic_dict.get('ip', None)
9174
        nicparams = self.nic_pinst[constants.DDM_ADD]
9175
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9176
        instance.nics.append(new_nic)
9177
        result.append(("nic.%d" % (len(instance.nics) - 1),
9178
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9179
                       (new_nic.mac, new_nic.ip,
9180
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9181
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9182
                       )))
9183
      else:
9184
        for key in 'mac', 'ip':
9185
          if key in nic_dict:
9186
            setattr(instance.nics[nic_op], key, nic_dict[key])
9187
        if nic_op in self.nic_pinst:
9188
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9189
        for key, val in nic_dict.iteritems():
9190
          result.append(("nic.%s/%d" % (key, nic_op), val))
9191

    
9192
    # hvparams changes
9193
    if self.op.hvparams:
9194
      instance.hvparams = self.hv_inst
9195
      for key, val in self.op.hvparams.iteritems():
9196
        result.append(("hv/%s" % key, val))
9197

    
9198
    # beparams changes
9199
    if self.op.beparams:
9200
      instance.beparams = self.be_inst
9201
      for key, val in self.op.beparams.iteritems():
9202
        result.append(("be/%s" % key, val))
9203

    
9204
    # OS change
9205
    if self.op.os_name:
9206
      instance.os = self.op.os_name
9207

    
9208
    # osparams changes
9209
    if self.op.osparams:
9210
      instance.osparams = self.os_inst
9211
      for key, val in self.op.osparams.iteritems():
9212
        result.append(("os/%s" % key, val))
9213

    
9214
    self.cfg.Update(instance, feedback_fn)
9215

    
9216
    return result
9217

    
9218
  _DISK_CONVERSIONS = {
9219
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9220
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9221
    }
9222

    
9223

    
9224
class LUQueryExports(NoHooksLU):
9225
  """Query the exports list
9226

9227
  """
9228
  _OP_PARAMS = [
9229
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
9230
    ("use_locking", False, _TBool),
9231
    ]
9232
  REQ_BGL = False
9233

    
9234
  def ExpandNames(self):
9235
    self.needed_locks = {}
9236
    self.share_locks[locking.LEVEL_NODE] = 1
9237
    if not self.op.nodes:
9238
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9239
    else:
9240
      self.needed_locks[locking.LEVEL_NODE] = \
9241
        _GetWantedNodes(self, self.op.nodes)
9242

    
9243
  def Exec(self, feedback_fn):
9244
    """Compute the list of all the exported system images.
9245

9246
    @rtype: dict
9247
    @return: a dictionary with the structure node->(export-list)
9248
        where export-list is a list of the instances exported on
9249
        that node.
9250

9251
    """
9252
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9253
    rpcresult = self.rpc.call_export_list(self.nodes)
9254
    result = {}
9255
    for node in rpcresult:
9256
      if rpcresult[node].fail_msg:
9257
        result[node] = False
9258
      else:
9259
        result[node] = rpcresult[node].payload
9260

    
9261
    return result
9262

    
9263

    
9264
class LUPrepareExport(NoHooksLU):
9265
  """Prepares an instance for an export and returns useful information.
9266

9267
  """
9268
  _OP_PARAMS = [
9269
    _PInstanceName,
9270
    ("mode", _NoDefault, _TElemOf(constants.EXPORT_MODES)),
9271
    ]
9272
  REQ_BGL = False
9273

    
9274
  def ExpandNames(self):
9275
    self._ExpandAndLockInstance()
9276

    
9277
  def CheckPrereq(self):
9278
    """Check prerequisites.
9279

9280
    """
9281
    instance_name = self.op.instance_name
9282

    
9283
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9284
    assert self.instance is not None, \
9285
          "Cannot retrieve locked instance %s" % self.op.instance_name
9286
    _CheckNodeOnline(self, self.instance.primary_node)
9287

    
9288
    self._cds = _GetClusterDomainSecret()
9289

    
9290
  def Exec(self, feedback_fn):
9291
    """Prepares an instance for an export.
9292

9293
    """
9294
    instance = self.instance
9295

    
9296
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9297
      salt = utils.GenerateSecret(8)
9298

    
9299
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9300
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9301
                                              constants.RIE_CERT_VALIDITY)
9302
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9303

    
9304
      (name, cert_pem) = result.payload
9305

    
9306
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9307
                                             cert_pem)
9308

    
9309
      return {
9310
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9311
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9312
                          salt),
9313
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9314
        }
9315

    
9316
    return None
9317

    
9318

    
9319
class LUExportInstance(LogicalUnit):
9320
  """Export an instance to an image in the cluster.
9321

9322
  """
9323
  HPATH = "instance-export"
9324
  HTYPE = constants.HTYPE_INSTANCE
9325
  _OP_PARAMS = [
9326
    _PInstanceName,
9327
    ("target_node", _NoDefault, _TOr(_TNonEmptyString, _TList)),
9328
    ("shutdown", True, _TBool),
9329
    _PShutdownTimeout,
9330
    ("remove_instance", False, _TBool),
9331
    ("ignore_remove_failures", False, _TBool),
9332
    ("mode", constants.EXPORT_MODE_LOCAL, _TElemOf(constants.EXPORT_MODES)),
9333
    ("x509_key_name", None, _TOr(_TList, _TNone)),
9334
    ("destination_x509_ca", None, _TMaybeString),
9335
    ]
9336
  REQ_BGL = False
9337

    
9338
  def CheckArguments(self):
9339
    """Check the arguments.
9340

9341
    """
9342
    self.x509_key_name = self.op.x509_key_name
9343
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9344

    
9345
    if self.op.remove_instance and not self.op.shutdown:
9346
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9347
                                 " down before")
9348

    
9349
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9350
      if not self.x509_key_name:
9351
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9352
                                   errors.ECODE_INVAL)
9353

    
9354
      if not self.dest_x509_ca_pem:
9355
        raise errors.OpPrereqError("Missing destination X509 CA",
9356
                                   errors.ECODE_INVAL)
9357

    
9358
  def ExpandNames(self):
9359
    self._ExpandAndLockInstance()
9360

    
9361
    # Lock all nodes for local exports
9362
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9363
      # FIXME: lock only instance primary and destination node
9364
      #
9365
      # Sad but true, for now we have do lock all nodes, as we don't know where
9366
      # the previous export might be, and in this LU we search for it and
9367
      # remove it from its current node. In the future we could fix this by:
9368
      #  - making a tasklet to search (share-lock all), then create the
9369
      #    new one, then one to remove, after
9370
      #  - removing the removal operation altogether
9371
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9372

    
9373
  def DeclareLocks(self, level):
9374
    """Last minute lock declaration."""
9375
    # All nodes are locked anyway, so nothing to do here.
9376

    
9377
  def BuildHooksEnv(self):
9378
    """Build hooks env.
9379

9380
    This will run on the master, primary node and target node.
9381

9382
    """
9383
    env = {
9384
      "EXPORT_MODE": self.op.mode,
9385
      "EXPORT_NODE": self.op.target_node,
9386
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9387
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9388
      # TODO: Generic function for boolean env variables
9389
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9390
      }
9391

    
9392
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9393

    
9394
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9395

    
9396
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9397
      nl.append(self.op.target_node)
9398

    
9399
    return env, nl, nl
9400

    
9401
  def CheckPrereq(self):
9402
    """Check prerequisites.
9403

9404
    This checks that the instance and node names are valid.
9405

9406
    """
9407
    instance_name = self.op.instance_name
9408

    
9409
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9410
    assert self.instance is not None, \
9411
          "Cannot retrieve locked instance %s" % self.op.instance_name
9412
    _CheckNodeOnline(self, self.instance.primary_node)
9413

    
9414
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9415
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9416
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9417
      assert self.dst_node is not None
9418

    
9419
      _CheckNodeOnline(self, self.dst_node.name)
9420
      _CheckNodeNotDrained(self, self.dst_node.name)
9421

    
9422
      self._cds = None
9423
      self.dest_disk_info = None
9424
      self.dest_x509_ca = None
9425

    
9426
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9427
      self.dst_node = None
9428

    
9429
      if len(self.op.target_node) != len(self.instance.disks):
9430
        raise errors.OpPrereqError(("Received destination information for %s"
9431
                                    " disks, but instance %s has %s disks") %
9432
                                   (len(self.op.target_node), instance_name,
9433
                                    len(self.instance.disks)),
9434
                                   errors.ECODE_INVAL)
9435

    
9436
      cds = _GetClusterDomainSecret()
9437

    
9438
      # Check X509 key name
9439
      try:
9440
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9441
      except (TypeError, ValueError), err:
9442
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9443

    
9444
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9445
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9446
                                   errors.ECODE_INVAL)
9447

    
9448
      # Load and verify CA
9449
      try:
9450
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9451
      except OpenSSL.crypto.Error, err:
9452
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9453
                                   (err, ), errors.ECODE_INVAL)
9454

    
9455
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9456
      if errcode is not None:
9457
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9458
                                   (msg, ), errors.ECODE_INVAL)
9459

    
9460
      self.dest_x509_ca = cert
9461

    
9462
      # Verify target information
9463
      disk_info = []
9464
      for idx, disk_data in enumerate(self.op.target_node):
9465
        try:
9466
          (host, port, magic) = \
9467
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9468
        except errors.GenericError, err:
9469
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9470
                                     (idx, err), errors.ECODE_INVAL)
9471

    
9472
        disk_info.append((host, port, magic))
9473

    
9474
      assert len(disk_info) == len(self.op.target_node)
9475
      self.dest_disk_info = disk_info
9476

    
9477
    else:
9478
      raise errors.ProgrammerError("Unhandled export mode %r" %
9479
                                   self.op.mode)
9480

    
9481
    # instance disk type verification
9482
    # TODO: Implement export support for file-based disks
9483
    for disk in self.instance.disks:
9484
      if disk.dev_type == constants.LD_FILE:
9485
        raise errors.OpPrereqError("Export not supported for instances with"
9486
                                   " file-based disks", errors.ECODE_INVAL)
9487

    
9488
  def _CleanupExports(self, feedback_fn):
9489
    """Removes exports of current instance from all other nodes.
9490

9491
    If an instance in a cluster with nodes A..D was exported to node C, its
9492
    exports will be removed from the nodes A, B and D.
9493

9494
    """
9495
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9496

    
9497
    nodelist = self.cfg.GetNodeList()
9498
    nodelist.remove(self.dst_node.name)
9499

    
9500
    # on one-node clusters nodelist will be empty after the removal
9501
    # if we proceed the backup would be removed because OpQueryExports
9502
    # substitutes an empty list with the full cluster node list.
9503
    iname = self.instance.name
9504
    if nodelist:
9505
      feedback_fn("Removing old exports for instance %s" % iname)
9506
      exportlist = self.rpc.call_export_list(nodelist)
9507
      for node in exportlist:
9508
        if exportlist[node].fail_msg:
9509
          continue
9510
        if iname in exportlist[node].payload:
9511
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9512
          if msg:
9513
            self.LogWarning("Could not remove older export for instance %s"
9514
                            " on node %s: %s", iname, node, msg)
9515

    
9516
  def Exec(self, feedback_fn):
9517
    """Export an instance to an image in the cluster.
9518

9519
    """
9520
    assert self.op.mode in constants.EXPORT_MODES
9521

    
9522
    instance = self.instance
9523
    src_node = instance.primary_node
9524

    
9525
    if self.op.shutdown:
9526
      # shutdown the instance, but not the disks
9527
      feedback_fn("Shutting down instance %s" % instance.name)
9528
      result = self.rpc.call_instance_shutdown(src_node, instance,
9529
                                               self.op.shutdown_timeout)
9530
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9531
      result.Raise("Could not shutdown instance %s on"
9532
                   " node %s" % (instance.name, src_node))
9533

    
9534
    # set the disks ID correctly since call_instance_start needs the
9535
    # correct drbd minor to create the symlinks
9536
    for disk in instance.disks:
9537
      self.cfg.SetDiskID(disk, src_node)
9538

    
9539
    activate_disks = (not instance.admin_up)
9540

    
9541
    if activate_disks:
9542
      # Activate the instance disks if we'exporting a stopped instance
9543
      feedback_fn("Activating disks for %s" % instance.name)
9544
      _StartInstanceDisks(self, instance, None)
9545

    
9546
    try:
9547
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9548
                                                     instance)
9549

    
9550
      helper.CreateSnapshots()
9551
      try:
9552
        if (self.op.shutdown and instance.admin_up and
9553
            not self.op.remove_instance):
9554
          assert not activate_disks
9555
          feedback_fn("Starting instance %s" % instance.name)
9556
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9557
          msg = result.fail_msg
9558
          if msg:
9559
            feedback_fn("Failed to start instance: %s" % msg)
9560
            _ShutdownInstanceDisks(self, instance)
9561
            raise errors.OpExecError("Could not start instance: %s" % msg)
9562

    
9563
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9564
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9565
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9566
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9567
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9568

    
9569
          (key_name, _, _) = self.x509_key_name
9570

    
9571
          dest_ca_pem = \
9572
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9573
                                            self.dest_x509_ca)
9574

    
9575
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9576
                                                     key_name, dest_ca_pem,
9577
                                                     timeouts)
9578
      finally:
9579
        helper.Cleanup()
9580

    
9581
      # Check for backwards compatibility
9582
      assert len(dresults) == len(instance.disks)
9583
      assert compat.all(isinstance(i, bool) for i in dresults), \
9584
             "Not all results are boolean: %r" % dresults
9585

    
9586
    finally:
9587
      if activate_disks:
9588
        feedback_fn("Deactivating disks for %s" % instance.name)
9589
        _ShutdownInstanceDisks(self, instance)
9590

    
9591
    if not (compat.all(dresults) and fin_resu):
9592
      failures = []
9593
      if not fin_resu:
9594
        failures.append("export finalization")
9595
      if not compat.all(dresults):
9596
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
9597
                               if not dsk)
9598
        failures.append("disk export: disk(s) %s" % fdsk)
9599

    
9600
      raise errors.OpExecError("Export failed, errors in %s" %
9601
                               utils.CommaJoin(failures))
9602

    
9603
    # At this point, the export was successful, we can cleanup/finish
9604

    
9605
    # Remove instance if requested
9606
    if self.op.remove_instance:
9607
      feedback_fn("Removing instance %s" % instance.name)
9608
      _RemoveInstance(self, feedback_fn, instance,
9609
                      self.op.ignore_remove_failures)
9610

    
9611
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9612
      self._CleanupExports(feedback_fn)
9613

    
9614
    return fin_resu, dresults
9615

    
9616

    
9617
class LURemoveExport(NoHooksLU):
9618
  """Remove exports related to the named instance.
9619

9620
  """
9621
  _OP_PARAMS = [
9622
    _PInstanceName,
9623
    ]
9624
  REQ_BGL = False
9625

    
9626
  def ExpandNames(self):
9627
    self.needed_locks = {}
9628
    # We need all nodes to be locked in order for RemoveExport to work, but we
9629
    # don't need to lock the instance itself, as nothing will happen to it (and
9630
    # we can remove exports also for a removed instance)
9631
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9632

    
9633
  def Exec(self, feedback_fn):
9634
    """Remove any export.
9635

9636
    """
9637
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9638
    # If the instance was not found we'll try with the name that was passed in.
9639
    # This will only work if it was an FQDN, though.
9640
    fqdn_warn = False
9641
    if not instance_name:
9642
      fqdn_warn = True
9643
      instance_name = self.op.instance_name
9644

    
9645
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
9646
    exportlist = self.rpc.call_export_list(locked_nodes)
9647
    found = False
9648
    for node in exportlist:
9649
      msg = exportlist[node].fail_msg
9650
      if msg:
9651
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
9652
        continue
9653
      if instance_name in exportlist[node].payload:
9654
        found = True
9655
        result = self.rpc.call_export_remove(node, instance_name)
9656
        msg = result.fail_msg
9657
        if msg:
9658
          logging.error("Could not remove export for instance %s"
9659
                        " on node %s: %s", instance_name, node, msg)
9660

    
9661
    if fqdn_warn and not found:
9662
      feedback_fn("Export not found. If trying to remove an export belonging"
9663
                  " to a deleted instance please use its Fully Qualified"
9664
                  " Domain Name.")
9665

    
9666

    
9667
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
9668
  """Generic tags LU.
9669

9670
  This is an abstract class which is the parent of all the other tags LUs.
9671

9672
  """
9673

    
9674
  def ExpandNames(self):
9675
    self.needed_locks = {}
9676
    if self.op.kind == constants.TAG_NODE:
9677
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
9678
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
9679
    elif self.op.kind == constants.TAG_INSTANCE:
9680
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
9681
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
9682

    
9683
  def CheckPrereq(self):
9684
    """Check prerequisites.
9685

9686
    """
9687
    if self.op.kind == constants.TAG_CLUSTER:
9688
      self.target = self.cfg.GetClusterInfo()
9689
    elif self.op.kind == constants.TAG_NODE:
9690
      self.target = self.cfg.GetNodeInfo(self.op.name)
9691
    elif self.op.kind == constants.TAG_INSTANCE:
9692
      self.target = self.cfg.GetInstanceInfo(self.op.name)
9693
    else:
9694
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
9695
                                 str(self.op.kind), errors.ECODE_INVAL)
9696

    
9697

    
9698
class LUGetTags(TagsLU):
9699
  """Returns the tags of a given object.
9700

9701
  """
9702
  _OP_PARAMS = [
9703
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9704
    ("name", _NoDefault, _TNonEmptyString),
9705
    ]
9706
  REQ_BGL = False
9707

    
9708
  def Exec(self, feedback_fn):
9709
    """Returns the tag list.
9710

9711
    """
9712
    return list(self.target.GetTags())
9713

    
9714

    
9715
class LUSearchTags(NoHooksLU):
9716
  """Searches the tags for a given pattern.
9717

9718
  """
9719
  _OP_PARAMS = [
9720
    ("pattern", _NoDefault, _TNonEmptyString),
9721
    ]
9722
  REQ_BGL = False
9723

    
9724
  def ExpandNames(self):
9725
    self.needed_locks = {}
9726

    
9727
  def CheckPrereq(self):
9728
    """Check prerequisites.
9729

9730
    This checks the pattern passed for validity by compiling it.
9731

9732
    """
9733
    try:
9734
      self.re = re.compile(self.op.pattern)
9735
    except re.error, err:
9736
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
9737
                                 (self.op.pattern, err), errors.ECODE_INVAL)
9738

    
9739
  def Exec(self, feedback_fn):
9740
    """Returns the tag list.
9741

9742
    """
9743
    cfg = self.cfg
9744
    tgts = [("/cluster", cfg.GetClusterInfo())]
9745
    ilist = cfg.GetAllInstancesInfo().values()
9746
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
9747
    nlist = cfg.GetAllNodesInfo().values()
9748
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
9749
    results = []
9750
    for path, target in tgts:
9751
      for tag in target.GetTags():
9752
        if self.re.search(tag):
9753
          results.append((path, tag))
9754
    return results
9755

    
9756

    
9757
class LUAddTags(TagsLU):
9758
  """Sets a tag on a given object.
9759

9760
  """
9761
  _OP_PARAMS = [
9762
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9763
    ("name", _NoDefault, _TNonEmptyString),
9764
    ("tags", _NoDefault, _TListOf(_TNonEmptyString)),
9765
    ]
9766
  REQ_BGL = False
9767

    
9768
  def CheckPrereq(self):
9769
    """Check prerequisites.
9770

9771
    This checks the type and length of the tag name and value.
9772

9773
    """
9774
    TagsLU.CheckPrereq(self)
9775
    for tag in self.op.tags:
9776
      objects.TaggableObject.ValidateTag(tag)
9777

    
9778
  def Exec(self, feedback_fn):
9779
    """Sets the tag.
9780

9781
    """
9782
    try:
9783
      for tag in self.op.tags:
9784
        self.target.AddTag(tag)
9785
    except errors.TagError, err:
9786
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
9787
    self.cfg.Update(self.target, feedback_fn)
9788

    
9789

    
9790
class LUDelTags(TagsLU):
9791
  """Delete a list of tags from 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 that we have the given tag.
9805

9806
    """
9807
    TagsLU.CheckPrereq(self)
9808
    for tag in self.op.tags:
9809
      objects.TaggableObject.ValidateTag(tag)
9810
    del_tags = frozenset(self.op.tags)
9811
    cur_tags = self.target.GetTags()
9812
    if not del_tags <= cur_tags:
9813
      diff_tags = del_tags - cur_tags
9814
      diff_names = ["'%s'" % tag for tag in diff_tags]
9815
      diff_names.sort()
9816
      raise errors.OpPrereqError("Tag(s) %s not found" %
9817
                                 (",".join(diff_names)), errors.ECODE_NOENT)
9818

    
9819
  def Exec(self, feedback_fn):
9820
    """Remove the tag from the object.
9821

9822
    """
9823
    for tag in self.op.tags:
9824
      self.target.RemoveTag(tag)
9825
    self.cfg.Update(self.target, feedback_fn)
9826

    
9827

    
9828
class LUTestDelay(NoHooksLU):
9829
  """Sleep for a specified amount of time.
9830

9831
  This LU sleeps on the master and/or nodes for a specified amount of
9832
  time.
9833

9834
  """
9835
  _OP_PARAMS = [
9836
    ("duration", _NoDefault, _TFloat),
9837
    ("on_master", True, _TBool),
9838
    ("on_nodes", _EmptyList, _TListOf(_TNonEmptyString)),
9839
    ("repeat", 0, _TPositiveInt)
9840
    ]
9841
  REQ_BGL = False
9842

    
9843
  def ExpandNames(self):
9844
    """Expand names and set required locks.
9845

9846
    This expands the node list, if any.
9847

9848
    """
9849
    self.needed_locks = {}
9850
    if self.op.on_nodes:
9851
      # _GetWantedNodes can be used here, but is not always appropriate to use
9852
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
9853
      # more information.
9854
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
9855
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
9856

    
9857
  def _TestDelay(self):
9858
    """Do the actual sleep.
9859

9860
    """
9861
    if self.op.on_master:
9862
      if not utils.TestDelay(self.op.duration):
9863
        raise errors.OpExecError("Error during master delay test")
9864
    if self.op.on_nodes:
9865
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
9866
      for node, node_result in result.items():
9867
        node_result.Raise("Failure during rpc call to node %s" % node)
9868

    
9869
  def Exec(self, feedback_fn):
9870
    """Execute the test delay opcode, with the wanted repetitions.
9871

9872
    """
9873
    if self.op.repeat == 0:
9874
      self._TestDelay()
9875
    else:
9876
      top_value = self.op.repeat - 1
9877
      for i in range(self.op.repeat):
9878
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
9879
        self._TestDelay()
9880

    
9881

    
9882
class LUTestJobqueue(NoHooksLU):
9883
  """Utility LU to test some aspects of the job queue.
9884

9885
  """
9886
  _OP_PARAMS = [
9887
    ("notify_waitlock", False, _TBool),
9888
    ("notify_exec", False, _TBool),
9889
    ("log_messages", _EmptyList, _TListOf(_TString)),
9890
    ("fail", False, _TBool),
9891
    ]
9892
  REQ_BGL = False
9893

    
9894
  # Must be lower than default timeout for WaitForJobChange to see whether it
9895
  # notices changed jobs
9896
  _CLIENT_CONNECT_TIMEOUT = 20.0
9897
  _CLIENT_CONFIRM_TIMEOUT = 60.0
9898

    
9899
  @classmethod
9900
  def _NotifyUsingSocket(cls, cb, errcls):
9901
    """Opens a Unix socket and waits for another program to connect.
9902

9903
    @type cb: callable
9904
    @param cb: Callback to send socket name to client
9905
    @type errcls: class
9906
    @param errcls: Exception class to use for errors
9907

9908
    """
9909
    # Using a temporary directory as there's no easy way to create temporary
9910
    # sockets without writing a custom loop around tempfile.mktemp and
9911
    # socket.bind
9912
    tmpdir = tempfile.mkdtemp()
9913
    try:
9914
      tmpsock = utils.PathJoin(tmpdir, "sock")
9915

    
9916
      logging.debug("Creating temporary socket at %s", tmpsock)
9917
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
9918
      try:
9919
        sock.bind(tmpsock)
9920
        sock.listen(1)
9921

    
9922
        # Send details to client
9923
        cb(tmpsock)
9924

    
9925
        # Wait for client to connect before continuing
9926
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
9927
        try:
9928
          (conn, _) = sock.accept()
9929
        except socket.error, err:
9930
          raise errcls("Client didn't connect in time (%s)" % err)
9931
      finally:
9932
        sock.close()
9933
    finally:
9934
      # Remove as soon as client is connected
9935
      shutil.rmtree(tmpdir)
9936

    
9937
    # Wait for client to close
9938
    try:
9939
      try:
9940
        # pylint: disable-msg=E1101
9941
        # Instance of '_socketobject' has no ... member
9942
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
9943
        conn.recv(1)
9944
      except socket.error, err:
9945
        raise errcls("Client failed to confirm notification (%s)" % err)
9946
    finally:
9947
      conn.close()
9948

    
9949
  def _SendNotification(self, test, arg, sockname):
9950
    """Sends a notification to the client.
9951

9952
    @type test: string
9953
    @param test: Test name
9954
    @param arg: Test argument (depends on test)
9955
    @type sockname: string
9956
    @param sockname: Socket path
9957

9958
    """
9959
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
9960

    
9961
  def _Notify(self, prereq, test, arg):
9962
    """Notifies the client of a test.
9963

9964
    @type prereq: bool
9965
    @param prereq: Whether this is a prereq-phase test
9966
    @type test: string
9967
    @param test: Test name
9968
    @param arg: Test argument (depends on test)
9969

9970
    """
9971
    if prereq:
9972
      errcls = errors.OpPrereqError
9973
    else:
9974
      errcls = errors.OpExecError
9975

    
9976
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
9977
                                                  test, arg),
9978
                                   errcls)
9979

    
9980
  def CheckArguments(self):
9981
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
9982
    self.expandnames_calls = 0
9983

    
9984
  def ExpandNames(self):
9985
    checkargs_calls = getattr(self, "checkargs_calls", 0)
9986
    if checkargs_calls < 1:
9987
      raise errors.ProgrammerError("CheckArguments was not called")
9988

    
9989
    self.expandnames_calls += 1
9990

    
9991
    if self.op.notify_waitlock:
9992
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
9993

    
9994
    self.LogInfo("Expanding names")
9995

    
9996
    # Get lock on master node (just to get a lock, not for a particular reason)
9997
    self.needed_locks = {
9998
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
9999
      }
10000

    
10001
  def Exec(self, feedback_fn):
10002
    if self.expandnames_calls < 1:
10003
      raise errors.ProgrammerError("ExpandNames was not called")
10004

    
10005
    if self.op.notify_exec:
10006
      self._Notify(False, constants.JQT_EXEC, None)
10007

    
10008
    self.LogInfo("Executing")
10009

    
10010
    if self.op.log_messages:
10011
      for idx, msg in enumerate(self.op.log_messages):
10012
        self.LogInfo("Sending log message %s", idx + 1)
10013
        feedback_fn(constants.JQT_MSGPREFIX + msg)
10014
        # Report how many test messages have been sent
10015
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
10016

    
10017
    if self.op.fail:
10018
      raise errors.OpExecError("Opcode failure was requested")
10019

    
10020
    return True
10021

    
10022

    
10023
class IAllocator(object):
10024
  """IAllocator framework.
10025

10026
  An IAllocator instance has three sets of attributes:
10027
    - cfg that is needed to query the cluster
10028
    - input data (all members of the _KEYS class attribute are required)
10029
    - four buffer attributes (in|out_data|text), that represent the
10030
      input (to the external script) in text and data structure format,
10031
      and the output from it, again in two formats
10032
    - the result variables from the script (success, info, nodes) for
10033
      easy usage
10034

10035
  """
10036
  # pylint: disable-msg=R0902
10037
  # lots of instance attributes
10038
  _ALLO_KEYS = [
10039
    "name", "mem_size", "disks", "disk_template",
10040
    "os", "tags", "nics", "vcpus", "hypervisor",
10041
    ]
10042
  _RELO_KEYS = [
10043
    "name", "relocate_from",
10044
    ]
10045
  _EVAC_KEYS = [
10046
    "evac_nodes",
10047
    ]
10048

    
10049
  def __init__(self, cfg, rpc, mode, **kwargs):
10050
    self.cfg = cfg
10051
    self.rpc = rpc
10052
    # init buffer variables
10053
    self.in_text = self.out_text = self.in_data = self.out_data = None
10054
    # init all input fields so that pylint is happy
10055
    self.mode = mode
10056
    self.mem_size = self.disks = self.disk_template = None
10057
    self.os = self.tags = self.nics = self.vcpus = None
10058
    self.hypervisor = None
10059
    self.relocate_from = None
10060
    self.name = None
10061
    self.evac_nodes = None
10062
    # computed fields
10063
    self.required_nodes = None
10064
    # init result fields
10065
    self.success = self.info = self.result = None
10066
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10067
      keyset = self._ALLO_KEYS
10068
      fn = self._AddNewInstance
10069
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10070
      keyset = self._RELO_KEYS
10071
      fn = self._AddRelocateInstance
10072
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10073
      keyset = self._EVAC_KEYS
10074
      fn = self._AddEvacuateNodes
10075
    else:
10076
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
10077
                                   " IAllocator" % self.mode)
10078
    for key in kwargs:
10079
      if key not in keyset:
10080
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
10081
                                     " IAllocator" % key)
10082
      setattr(self, key, kwargs[key])
10083

    
10084
    for key in keyset:
10085
      if key not in kwargs:
10086
        raise errors.ProgrammerError("Missing input parameter '%s' to"
10087
                                     " IAllocator" % key)
10088
    self._BuildInputData(fn)
10089

    
10090
  def _ComputeClusterData(self):
10091
    """Compute the generic allocator input data.
10092

10093
    This is the data that is independent of the actual operation.
10094

10095
    """
10096
    cfg = self.cfg
10097
    cluster_info = cfg.GetClusterInfo()
10098
    # cluster data
10099
    data = {
10100
      "version": constants.IALLOCATOR_VERSION,
10101
      "cluster_name": cfg.GetClusterName(),
10102
      "cluster_tags": list(cluster_info.GetTags()),
10103
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
10104
      # we don't have job IDs
10105
      }
10106
    iinfo = cfg.GetAllInstancesInfo().values()
10107
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
10108

    
10109
    # node data
10110
    node_results = {}
10111
    node_list = cfg.GetNodeList()
10112

    
10113
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10114
      hypervisor_name = self.hypervisor
10115
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10116
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
10117
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10118
      hypervisor_name = cluster_info.enabled_hypervisors[0]
10119

    
10120
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
10121
                                        hypervisor_name)
10122
    node_iinfo = \
10123
      self.rpc.call_all_instances_info(node_list,
10124
                                       cluster_info.enabled_hypervisors)
10125
    for nname, nresult in node_data.items():
10126
      # first fill in static (config-based) values
10127
      ninfo = cfg.GetNodeInfo(nname)
10128
      pnr = {
10129
        "tags": list(ninfo.GetTags()),
10130
        "primary_ip": ninfo.primary_ip,
10131
        "secondary_ip": ninfo.secondary_ip,
10132
        "offline": ninfo.offline,
10133
        "drained": ninfo.drained,
10134
        "master_candidate": ninfo.master_candidate,
10135
        }
10136

    
10137
      if not (ninfo.offline or ninfo.drained):
10138
        nresult.Raise("Can't get data for node %s" % nname)
10139
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
10140
                                nname)
10141
        remote_info = nresult.payload
10142

    
10143
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
10144
                     'vg_size', 'vg_free', 'cpu_total']:
10145
          if attr not in remote_info:
10146
            raise errors.OpExecError("Node '%s' didn't return attribute"
10147
                                     " '%s'" % (nname, attr))
10148
          if not isinstance(remote_info[attr], int):
10149
            raise errors.OpExecError("Node '%s' returned invalid value"
10150
                                     " for '%s': %s" %
10151
                                     (nname, attr, remote_info[attr]))
10152
        # compute memory used by primary instances
10153
        i_p_mem = i_p_up_mem = 0
10154
        for iinfo, beinfo in i_list:
10155
          if iinfo.primary_node == nname:
10156
            i_p_mem += beinfo[constants.BE_MEMORY]
10157
            if iinfo.name not in node_iinfo[nname].payload:
10158
              i_used_mem = 0
10159
            else:
10160
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
10161
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
10162
            remote_info['memory_free'] -= max(0, i_mem_diff)
10163

    
10164
            if iinfo.admin_up:
10165
              i_p_up_mem += beinfo[constants.BE_MEMORY]
10166

    
10167
        # compute memory used by instances
10168
        pnr_dyn = {
10169
          "total_memory": remote_info['memory_total'],
10170
          "reserved_memory": remote_info['memory_dom0'],
10171
          "free_memory": remote_info['memory_free'],
10172
          "total_disk": remote_info['vg_size'],
10173
          "free_disk": remote_info['vg_free'],
10174
          "total_cpus": remote_info['cpu_total'],
10175
          "i_pri_memory": i_p_mem,
10176
          "i_pri_up_memory": i_p_up_mem,
10177
          }
10178
        pnr.update(pnr_dyn)
10179

    
10180
      node_results[nname] = pnr
10181
    data["nodes"] = node_results
10182

    
10183
    # instance data
10184
    instance_data = {}
10185
    for iinfo, beinfo in i_list:
10186
      nic_data = []
10187
      for nic in iinfo.nics:
10188
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
10189
        nic_dict = {"mac": nic.mac,
10190
                    "ip": nic.ip,
10191
                    "mode": filled_params[constants.NIC_MODE],
10192
                    "link": filled_params[constants.NIC_LINK],
10193
                   }
10194
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
10195
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
10196
        nic_data.append(nic_dict)
10197
      pir = {
10198
        "tags": list(iinfo.GetTags()),
10199
        "admin_up": iinfo.admin_up,
10200
        "vcpus": beinfo[constants.BE_VCPUS],
10201
        "memory": beinfo[constants.BE_MEMORY],
10202
        "os": iinfo.os,
10203
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
10204
        "nics": nic_data,
10205
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
10206
        "disk_template": iinfo.disk_template,
10207
        "hypervisor": iinfo.hypervisor,
10208
        }
10209
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
10210
                                                 pir["disks"])
10211
      instance_data[iinfo.name] = pir
10212

    
10213
    data["instances"] = instance_data
10214

    
10215
    self.in_data = data
10216

    
10217
  def _AddNewInstance(self):
10218
    """Add new instance data to allocator structure.
10219

10220
    This in combination with _AllocatorGetClusterData will create the
10221
    correct structure needed as input for the allocator.
10222

10223
    The checks for the completeness of the opcode must have already been
10224
    done.
10225

10226
    """
10227
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
10228

    
10229
    if self.disk_template in constants.DTS_NET_MIRROR:
10230
      self.required_nodes = 2
10231
    else:
10232
      self.required_nodes = 1
10233
    request = {
10234
      "name": self.name,
10235
      "disk_template": self.disk_template,
10236
      "tags": self.tags,
10237
      "os": self.os,
10238
      "vcpus": self.vcpus,
10239
      "memory": self.mem_size,
10240
      "disks": self.disks,
10241
      "disk_space_total": disk_space,
10242
      "nics": self.nics,
10243
      "required_nodes": self.required_nodes,
10244
      }
10245
    return request
10246

    
10247
  def _AddRelocateInstance(self):
10248
    """Add relocate instance data to allocator structure.
10249

10250
    This in combination with _IAllocatorGetClusterData will create the
10251
    correct structure needed as input for the allocator.
10252

10253
    The checks for the completeness of the opcode must have already been
10254
    done.
10255

10256
    """
10257
    instance = self.cfg.GetInstanceInfo(self.name)
10258
    if instance is None:
10259
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
10260
                                   " IAllocator" % self.name)
10261

    
10262
    if instance.disk_template not in constants.DTS_NET_MIRROR:
10263
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
10264
                                 errors.ECODE_INVAL)
10265

    
10266
    if len(instance.secondary_nodes) != 1:
10267
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
10268
                                 errors.ECODE_STATE)
10269

    
10270
    self.required_nodes = 1
10271
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
10272
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
10273

    
10274
    request = {
10275
      "name": self.name,
10276
      "disk_space_total": disk_space,
10277
      "required_nodes": self.required_nodes,
10278
      "relocate_from": self.relocate_from,
10279
      }
10280
    return request
10281

    
10282
  def _AddEvacuateNodes(self):
10283
    """Add evacuate nodes data to allocator structure.
10284

10285
    """
10286
    request = {
10287
      "evac_nodes": self.evac_nodes
10288
      }
10289
    return request
10290

    
10291
  def _BuildInputData(self, fn):
10292
    """Build input data structures.
10293

10294
    """
10295
    self._ComputeClusterData()
10296

    
10297
    request = fn()
10298
    request["type"] = self.mode
10299
    self.in_data["request"] = request
10300

    
10301
    self.in_text = serializer.Dump(self.in_data)
10302

    
10303
  def Run(self, name, validate=True, call_fn=None):
10304
    """Run an instance allocator and return the results.
10305

10306
    """
10307
    if call_fn is None:
10308
      call_fn = self.rpc.call_iallocator_runner
10309

    
10310
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
10311
    result.Raise("Failure while running the iallocator script")
10312

    
10313
    self.out_text = result.payload
10314
    if validate:
10315
      self._ValidateResult()
10316

    
10317
  def _ValidateResult(self):
10318
    """Process the allocator results.
10319

10320
    This will process and if successful save the result in
10321
    self.out_data and the other parameters.
10322

10323
    """
10324
    try:
10325
      rdict = serializer.Load(self.out_text)
10326
    except Exception, err:
10327
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
10328

    
10329
    if not isinstance(rdict, dict):
10330
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
10331

    
10332
    # TODO: remove backwards compatiblity in later versions
10333
    if "nodes" in rdict and "result" not in rdict:
10334
      rdict["result"] = rdict["nodes"]
10335
      del rdict["nodes"]
10336

    
10337
    for key in "success", "info", "result":
10338
      if key not in rdict:
10339
        raise errors.OpExecError("Can't parse iallocator results:"
10340
                                 " missing key '%s'" % key)
10341
      setattr(self, key, rdict[key])
10342

    
10343
    if not isinstance(rdict["result"], list):
10344
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
10345
                               " is not a list")
10346
    self.out_data = rdict
10347

    
10348

    
10349
class LUTestAllocator(NoHooksLU):
10350
  """Run allocator tests.
10351

10352
  This LU runs the allocator tests
10353

10354
  """
10355
  _OP_PARAMS = [
10356
    ("direction", _NoDefault, _TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS)),
10357
    ("mode", _NoDefault, _TElemOf(constants.VALID_IALLOCATOR_MODES)),
10358
    ("name", _NoDefault, _TNonEmptyString),
10359
    ("nics", _NoDefault, _TOr(_TNone, _TListOf(
10360
      _TDictOf(_TElemOf(["mac", "ip", "bridge"]),
10361
               _TOr(_TNone, _TNonEmptyString))))),
10362
    ("disks", _NoDefault, _TOr(_TNone, _TList)),
10363
    ("hypervisor", None, _TMaybeString),
10364
    ("allocator", None, _TMaybeString),
10365
    ("tags", _EmptyList, _TListOf(_TNonEmptyString)),
10366
    ("mem_size", None, _TOr(_TNone, _TPositiveInt)),
10367
    ("vcpus", None, _TOr(_TNone, _TPositiveInt)),
10368
    ("os", None, _TMaybeString),
10369
    ("disk_template", None, _TMaybeString),
10370
    ("evac_nodes", None, _TOr(_TNone, _TListOf(_TNonEmptyString))),
10371
    ]
10372

    
10373
  def CheckPrereq(self):
10374
    """Check prerequisites.
10375

10376
    This checks the opcode parameters depending on the director and mode test.
10377

10378
    """
10379
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10380
      for attr in ["mem_size", "disks", "disk_template",
10381
                   "os", "tags", "nics", "vcpus"]:
10382
        if not hasattr(self.op, attr):
10383
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
10384
                                     attr, errors.ECODE_INVAL)
10385
      iname = self.cfg.ExpandInstanceName(self.op.name)
10386
      if iname is not None:
10387
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
10388
                                   iname, errors.ECODE_EXISTS)
10389
      if not isinstance(self.op.nics, list):
10390
        raise errors.OpPrereqError("Invalid parameter 'nics'",
10391
                                   errors.ECODE_INVAL)
10392
      if not isinstance(self.op.disks, list):
10393
        raise errors.OpPrereqError("Invalid parameter 'disks'",
10394
                                   errors.ECODE_INVAL)
10395
      for row in self.op.disks:
10396
        if (not isinstance(row, dict) or
10397
            "size" not in row or
10398
            not isinstance(row["size"], int) or
10399
            "mode" not in row or
10400
            row["mode"] not in ['r', 'w']):
10401
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
10402
                                     " parameter", errors.ECODE_INVAL)
10403
      if self.op.hypervisor is None:
10404
        self.op.hypervisor = self.cfg.GetHypervisorType()
10405
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10406
      fname = _ExpandInstanceName(self.cfg, self.op.name)
10407
      self.op.name = fname
10408
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
10409
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10410
      if not hasattr(self.op, "evac_nodes"):
10411
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
10412
                                   " opcode input", errors.ECODE_INVAL)
10413
    else:
10414
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
10415
                                 self.op.mode, errors.ECODE_INVAL)
10416

    
10417
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
10418
      if self.op.allocator is None:
10419
        raise errors.OpPrereqError("Missing allocator name",
10420
                                   errors.ECODE_INVAL)
10421
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
10422
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
10423
                                 self.op.direction, errors.ECODE_INVAL)
10424

    
10425
  def Exec(self, feedback_fn):
10426
    """Run the allocator test.
10427

10428
    """
10429
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10430
      ial = IAllocator(self.cfg, self.rpc,
10431
                       mode=self.op.mode,
10432
                       name=self.op.name,
10433
                       mem_size=self.op.mem_size,
10434
                       disks=self.op.disks,
10435
                       disk_template=self.op.disk_template,
10436
                       os=self.op.os,
10437
                       tags=self.op.tags,
10438
                       nics=self.op.nics,
10439
                       vcpus=self.op.vcpus,
10440
                       hypervisor=self.op.hypervisor,
10441
                       )
10442
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10443
      ial = IAllocator(self.cfg, self.rpc,
10444
                       mode=self.op.mode,
10445
                       name=self.op.name,
10446
                       relocate_from=list(self.relocate_from),
10447
                       )
10448
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10449
      ial = IAllocator(self.cfg, self.rpc,
10450
                       mode=self.op.mode,
10451
                       evac_nodes=self.op.evac_nodes)
10452
    else:
10453
      raise errors.ProgrammerError("Uncatched mode %s in"
10454
                                   " LUTestAllocator.Exec", self.op.mode)
10455

    
10456
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
10457
      result = ial.in_text
10458
    else:
10459
      ial.Run(self.op.allocator, validate=False)
10460
      result = ial.out_text
10461
    return result