Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 3fe11ba3

History | View | Annotate | Download (364.6 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
    ("reserved_lvs", None, _TOr(_TListOf(_TNonEmptyString), _TNone)),
2610
    ]
2611
  REQ_BGL = False
2612

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2885

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

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

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

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

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

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

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

    
2930

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

2934
  This is a very simple LU.
2935

2936
  """
2937
  REQ_BGL = False
2938

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

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

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

    
2952

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

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

    
2960
  disks = _ExpandCheckDisks(instance, disks)
2961

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

    
2965
  node = instance.primary_node
2966

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

    
2970
  # TODO: Convert to utils.Retry
2971

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

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

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

    
3018
    if done or oneshot:
3019
      break
3020

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

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

    
3027

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

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

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

    
3038
  result = True
3039

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

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

    
3059
  return result
3060

    
3061

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3181
    return output
3182

    
3183

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

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

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

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

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

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

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

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

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

    
3228
    instance_list = self.cfg.GetInstanceList()
3229

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

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

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

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

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

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

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

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

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

    
3279

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

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

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

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

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

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

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

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

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

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

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

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

    
3349
    # begin data gathering
3350

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

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

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

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

    
3391
    master_node = self.cfg.GetMasterNode()
3392

    
3393
    # end data gathering
3394

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

    
3435
    return output
3436

    
3437

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

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

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

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

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

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

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

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

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

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

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

    
3515
        output.append(node_output)
3516

    
3517
    return output
3518

    
3519

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

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

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

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

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

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

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

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

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

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

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

    
3573
    result = []
3574

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

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

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

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

    
3590
        out = []
3591

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

    
3602
          out.append(val)
3603

    
3604
        result.append(out)
3605

    
3606
    return result
3607

    
3608

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

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

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

    
3624
    storage_type = self.op.storage_type
3625

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

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

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

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

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

    
3656

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

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

    
3670
  def CheckArguments(self):
3671
    # validate/normalize the node name
3672
    self.op.node_name = netutils.HostInfo.NormalizeName(self.op.node_name)
3673

    
3674
  def BuildHooksEnv(self):
3675
    """Build hooks env.
3676

3677
    This will run on all nodes before, and on all nodes + the new node after.
3678

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

    
3690
  def CheckPrereq(self):
3691
    """Check prerequisites.
3692

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

3698
    Any errors are signaled by raising errors.OpPrereqError.
3699

3700
    """
3701
    node_name = self.op.node_name
3702
    cfg = self.cfg
3703

    
3704
    dns_data = netutils.GetHostInfo(node_name)
3705

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

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

    
3723
    self.changed_primary_ip = False
3724

    
3725
    for existing_node_name in node_list:
3726
      existing_node = cfg.GetNodeInfo(existing_node_name)
3727

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

    
3736
        continue
3737

    
3738
      if (existing_node.primary_ip == primary_ip or
3739
          existing_node.secondary_ip == primary_ip or
3740
          existing_node.primary_ip == secondary_ip or
3741
          existing_node.secondary_ip == secondary_ip):
3742
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3743
                                   " existing node %s" % existing_node.name,
3744
                                   errors.ECODE_NOTUNIQUE)
3745

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

    
3761
    # checks reachability
3762
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3763
      raise errors.OpPrereqError("Node not reachable by ping",
3764
                                 errors.ECODE_ENVIRON)
3765

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

    
3774
    if self.op.readd:
3775
      exceptions = [node]
3776
    else:
3777
      exceptions = []
3778

    
3779
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3780

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

    
3791
  def Exec(self, feedback_fn):
3792
    """Adds the new node to the cluster.
3793

3794
    """
3795
    new_node = self.new_node
3796
    node = new_node.name
3797

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

    
3810
    # notify the user about any possible mc promotion
3811
    if new_node.master_candidate:
3812
      self.LogInfo("Node will be a master candidate")
3813

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

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

    
3834
      for i in keyfiles:
3835
        keyarray.append(utils.ReadFile(i))
3836

    
3837
      result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
3838
                                      keyarray[2], keyarray[3], keyarray[4],
3839
                                      keyarray[5])
3840
      result.Raise("Cannot transfer ssh keys to the new node")
3841

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

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

    
3857
    node_verify_list = [self.cfg.GetMasterNode()]
3858
    node_verify_param = {
3859
      constants.NV_NODELIST: [node],
3860
      # TODO: do a node-net-test as well?
3861
    }
3862

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

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

    
3891

    
3892
class LUSetNodeParams(LogicalUnit):
3893
  """Modifies the parameters of a node.
3894

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

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

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

    
3927
    self.lock_all = self.op.auto_promote and self.might_demote
3928

    
3929

    
3930
  def ExpandNames(self):
3931
    if self.lock_all:
3932
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
3933
    else:
3934
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3935

    
3936
  def BuildHooksEnv(self):
3937
    """Build hooks env.
3938

3939
    This runs on the master node.
3940

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

    
3952
  def CheckPrereq(self):
3953
    """Check prerequisites.
3954

3955
    This only checks the instance list against the existing names.
3956

3957
    """
3958
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3959

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

    
3969

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

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

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

    
3995
    return
3996

    
3997
  def Exec(self, feedback_fn):
3998
    """Modifies a node.
3999

4000
    """
4001
    node = self.node
4002

    
4003
    result = []
4004
    changed_mc = False
4005

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

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

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

    
4044
    # we locked all nodes, we adjust the CP before updating this node
4045
    if self.lock_all:
4046
      _AdjustCandidatePool(self, [node.name])
4047

    
4048
    # this will trigger configuration file update, if needed
4049
    self.cfg.Update(node, feedback_fn)
4050

    
4051
    # this will trigger job queue propagation or cleanup
4052
    if changed_mc:
4053
      self.context.ReaddNode(node)
4054

    
4055
    return result
4056

    
4057

    
4058
class LUPowercycleNode(NoHooksLU):
4059
  """Powercycles a node.
4060

4061
  """
4062
  _OP_PARAMS = [
4063
    _PNodeName,
4064
    _PForce,
4065
    ]
4066
  REQ_BGL = False
4067

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

    
4075
  def ExpandNames(self):
4076
    """Locking for PowercycleNode.
4077

4078
    This is a last-resort option and shouldn't block on other
4079
    jobs. Therefore, we grab no locks.
4080

4081
    """
4082
    self.needed_locks = {}
4083

    
4084
  def Exec(self, feedback_fn):
4085
    """Reboots a node.
4086

4087
    """
4088
    result = self.rpc.call_node_powercycle(self.op.node_name,
4089
                                           self.cfg.GetHypervisorType())
4090
    result.Raise("Failed to schedule the reboot")
4091
    return result.payload
4092

    
4093

    
4094
class LUQueryClusterInfo(NoHooksLU):
4095
  """Query cluster configuration.
4096

4097
  """
4098
  REQ_BGL = False
4099

    
4100
  def ExpandNames(self):
4101
    self.needed_locks = {}
4102

    
4103
  def Exec(self, feedback_fn):
4104
    """Return cluster config.
4105

4106
    """
4107
    cluster = self.cfg.GetClusterInfo()
4108
    os_hvp = {}
4109

    
4110
    # Filter just for enabled hypervisors
4111
    for os_name, hv_dict in cluster.os_hvp.items():
4112
      os_hvp[os_name] = {}
4113
      for hv_name, hv_params in hv_dict.items():
4114
        if hv_name in cluster.enabled_hypervisors:
4115
          os_hvp[os_name][hv_name] = hv_params
4116

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

    
4149
    return result
4150

    
4151

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

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

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

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

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

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

    
4189

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

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

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

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

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

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

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

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

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

    
4230
    return disks_info
4231

    
4232

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

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

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

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

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

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

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

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

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

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

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

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

    
4318
  return disks_ok, device_info
4319

    
4320

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

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

    
4335

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

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

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

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

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

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

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

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

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

    
4371

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

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

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

    
4382

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

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

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

    
4400

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

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

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

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

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

    
4425

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

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

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

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

    
4462

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

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

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

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

    
4498

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

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

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

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

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

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

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

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

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

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

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

    
4556
    _CheckNodeOnline(self, instance.primary_node)
4557

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

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

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

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

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

    
4581
    node_current = instance.primary_node
4582

    
4583
    _StartInstanceDisks(self, instance, force)
4584

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

    
4592

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

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

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

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

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

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

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

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

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

    
4635
    _CheckNodeOnline(self, instance.primary_node)
4636

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

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

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

    
4648
    node_current = instance.primary_node
4649

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

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

    
4673

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

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

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

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

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

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

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

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

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

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

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

    
4724
    _ShutdownInstanceDisks(self, instance)
4725

    
4726

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

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

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

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

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

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

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

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

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

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

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

    
4775
    self.instance = instance
4776

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

4780
    """
4781
    inst = self.instance
4782

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

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

    
4799

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

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

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

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

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

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

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

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

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

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

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

    
4849
    self.instance = instance
4850

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

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

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

    
4863

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

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

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

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

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

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

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

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

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

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

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

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

    
4926

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

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

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

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

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

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

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

    
4968

    
4969
class LURemoveInstance(LogicalUnit):
4970
  """Remove an instance.
4971

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

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

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

    
4991
  def BuildHooksEnv(self):
4992
    """Build hooks env.
4993

4994
    This runs on master, primary and secondary nodes of the instance.
4995

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

    
5003
  def CheckPrereq(self):
5004
    """Check prerequisites.
5005

5006
    This checks that the instance is in the cluster.
5007

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

    
5013
  def Exec(self, feedback_fn):
5014
    """Remove the instance.
5015

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

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

    
5032
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5033

    
5034

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

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

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

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

    
5048
  lu.cfg.RemoveInstance(instance.name)
5049

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

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

    
5056

    
5057
class LUQueryInstances(NoHooksLU):
5058
  """Logical unit for querying instances.
5059

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

    
5094

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

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

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

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

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

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

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

    
5147
    instance_list = [all_info[iname] for iname in instance_names]
5148

    
5149
    # begin data gathering
5150

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

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

    
5173
    # end data gathering
5174

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

    
5345
    return output
5346

    
5347

    
5348
class LUFailoverInstance(LogicalUnit):
5349
  """Failover an instance.
5350

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

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

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

    
5370
  def BuildHooksEnv(self):
5371
    """Build hooks env.
5372

5373
    This runs on master, primary and secondary nodes of the instance.
5374

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

    
5393
  def CheckPrereq(self):
5394
    """Check prerequisites.
5395

5396
    This checks that the instance is in the cluster.
5397

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

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

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

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

    
5426
    # check bridge existance
5427
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5428

    
5429
  def Exec(self, feedback_fn):
5430
    """Failover an instance.
5431

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

5435
    """
5436
    instance = self.instance
5437

    
5438
    source_node = instance.primary_node
5439
    target_node = instance.secondary_nodes[0]
5440

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

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

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

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

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

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

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

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

    
5498

    
5499
class LUMigrateInstance(LogicalUnit):
5500
  """Migrate an instance.
5501

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

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

    
5514
  REQ_BGL = False
5515

    
5516
  def ExpandNames(self):
5517
    self._ExpandAndLockInstance()
5518

    
5519
    self.needed_locks[locking.LEVEL_NODE] = []
5520
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5521

    
5522
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5523
                                       self.op.cleanup)
5524
    self.tasklets = [self._migrater]
5525

    
5526
  def DeclareLocks(self, level):
5527
    if level == locking.LEVEL_NODE:
5528
      self._LockInstancesNodes()
5529

    
5530
  def BuildHooksEnv(self):
5531
    """Build hooks env.
5532

5533
    This runs on master, primary and secondary nodes of the instance.
5534

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

    
5553

    
5554
class LUMoveInstance(LogicalUnit):
5555
  """Move an instance by data-copying.
5556

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

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

    
5574
  def DeclareLocks(self, level):
5575
    if level == locking.LEVEL_NODE:
5576
      self._LockInstancesNodes(primary_only=True)
5577

    
5578
  def BuildHooksEnv(self):
5579
    """Build hooks env.
5580

5581
    This runs on master, primary and secondary nodes of the instance.
5582

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

    
5593
  def CheckPrereq(self):
5594
    """Check prerequisites.
5595

5596
    This checks that the instance is in the cluster.
5597

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

    
5603
    node = self.cfg.GetNodeInfo(self.op.target_node)
5604
    assert node is not None, \
5605
      "Cannot retrieve locked node %s" % self.op.target_node
5606

    
5607
    self.target_node = target_node = node.name
5608

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

    
5614
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5615

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

    
5621
    _CheckNodeOnline(self, target_node)
5622
    _CheckNodeNotDrained(self, target_node)
5623

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

    
5633
    # check bridge existance
5634
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5635

    
5636
  def Exec(self, feedback_fn):
5637
    """Move an instance.
5638

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

5642
    """
5643
    instance = self.instance
5644

    
5645
    source_node = instance.primary_node
5646
    target_node = self.target_node
5647

    
5648
    self.LogInfo("Shutting down instance %s on source node %s",
5649
                 instance.name, source_node)
5650

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

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

    
5676
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5677

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

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

    
5708
    instance.primary_node = target_node
5709
    self.cfg.Update(instance, feedback_fn)
5710

    
5711
    self.LogInfo("Removing the disks on the original node")
5712
    _RemoveDisks(self, instance, target_node=source_node)
5713

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

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

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

    
5732

    
5733
class LUMigrateNode(LogicalUnit):
5734
  """Migrate all instances from a node.
5735

5736
  """
5737
  HPATH = "node-migrate"
5738
  HTYPE = constants.HTYPE_NODE
5739
  _OP_PARAMS = [
5740
    _PNodeName,
5741
    _PMigrationMode,
5742
    ]
5743
  REQ_BGL = False
5744

    
5745
  def ExpandNames(self):
5746
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5747

    
5748
    self.needed_locks = {
5749
      locking.LEVEL_NODE: [self.op.node_name],
5750
      }
5751

    
5752
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5753

    
5754
    # Create tasklets for migrating instances for all instances on this node
5755
    names = []
5756
    tasklets = []
5757

    
5758
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5759
      logging.debug("Migrating instance %s", inst.name)
5760
      names.append(inst.name)
5761

    
5762
      tasklets.append(TLMigrateInstance(self, inst.name, False))
5763

    
5764
    self.tasklets = tasklets
5765

    
5766
    # Declare instance locks
5767
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5768

    
5769
  def DeclareLocks(self, level):
5770
    if level == locking.LEVEL_NODE:
5771
      self._LockInstancesNodes()
5772

    
5773
  def BuildHooksEnv(self):
5774
    """Build hooks env.
5775

5776
    This runs on the master, the primary and all the secondaries.
5777

5778
    """
5779
    env = {
5780
      "NODE_NAME": self.op.node_name,
5781
      }
5782

    
5783
    nl = [self.cfg.GetMasterNode()]
5784

    
5785
    return (env, nl, nl)
5786

    
5787

    
5788
class TLMigrateInstance(Tasklet):
5789
  """Tasklet class for instance migration.
5790

5791
  @type live: boolean
5792
  @ivar live: whether the migration will be done live or non-live;
5793
      this variable is initalized only after CheckPrereq has run
5794

5795
  """
5796
  def __init__(self, lu, instance_name, cleanup):
5797
    """Initializes this class.
5798

5799
    """
5800
    Tasklet.__init__(self, lu)
5801

    
5802
    # Parameters
5803
    self.instance_name = instance_name
5804
    self.cleanup = cleanup
5805
    self.live = False # will be overridden later
5806

    
5807
  def CheckPrereq(self):
5808
    """Check prerequisites.
5809

5810
    This checks that the instance is in the cluster.
5811

5812
    """
5813
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
5814
    instance = self.cfg.GetInstanceInfo(instance_name)
5815
    assert instance is not None
5816

    
5817
    if instance.disk_template != constants.DT_DRBD8:
5818
      raise errors.OpPrereqError("Instance's disk layout is not"
5819
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5820

    
5821
    secondary_nodes = instance.secondary_nodes
5822
    if not secondary_nodes:
5823
      raise errors.ConfigurationError("No secondary node but using"
5824
                                      " drbd8 disk template")
5825

    
5826
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5827

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

    
5834
    # check bridge existance
5835
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
5836

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

    
5844
    self.instance = instance
5845

    
5846
    if self.lu.op.mode is None:
5847
      # read the default value from the hypervisor
5848
      i_hv = self.cfg.GetClusterInfo().FillHV(instance, skip_globals=False)
5849
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
5850

    
5851
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
5852

    
5853
  def _WaitUntilSync(self):
5854
    """Poll with custom rpc for disk sync.
5855

5856
    This uses our own step-based rpc call.
5857

5858
    """
5859
    self.feedback_fn("* wait until resync is done")
5860
    all_done = False
5861
    while not all_done:
5862
      all_done = True
5863
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
5864
                                            self.nodes_ip,
5865
                                            self.instance.disks)
5866
      min_percent = 100
5867
      for node, nres in result.items():
5868
        nres.Raise("Cannot resync disks on node %s" % node)
5869
        node_done, node_percent = nres.payload
5870
        all_done = all_done and node_done
5871
        if node_percent is not None:
5872
          min_percent = min(min_percent, node_percent)
5873
      if not all_done:
5874
        if min_percent < 100:
5875
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
5876
        time.sleep(2)
5877

    
5878
  def _EnsureSecondary(self, node):
5879
    """Demote a node to secondary.
5880

5881
    """
5882
    self.feedback_fn("* switching node %s to secondary mode" % node)
5883

    
5884
    for dev in self.instance.disks:
5885
      self.cfg.SetDiskID(dev, node)
5886

    
5887
    result = self.rpc.call_blockdev_close(node, self.instance.name,
5888
                                          self.instance.disks)
5889
    result.Raise("Cannot change disk to secondary on node %s" % node)
5890

    
5891
  def _GoStandalone(self):
5892
    """Disconnect from the network.
5893

5894
    """
5895
    self.feedback_fn("* changing into standalone mode")
5896
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
5897
                                               self.instance.disks)
5898
    for node, nres in result.items():
5899
      nres.Raise("Cannot disconnect disks node %s" % node)
5900

    
5901
  def _GoReconnect(self, multimaster):
5902
    """Reconnect to the network.
5903

5904
    """
5905
    if multimaster:
5906
      msg = "dual-master"
5907
    else:
5908
      msg = "single-master"
5909
    self.feedback_fn("* changing disks into %s mode" % msg)
5910
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
5911
                                           self.instance.disks,
5912
                                           self.instance.name, multimaster)
5913
    for node, nres in result.items():
5914
      nres.Raise("Cannot change disks config on node %s" % node)
5915

    
5916
  def _ExecCleanup(self):
5917
    """Try to cleanup after a failed migration.
5918

5919
    The cleanup is done by:
5920
      - check that the instance is running only on one node
5921
        (and update the config if needed)
5922
      - change disks on its secondary node to secondary
5923
      - wait until disks are fully synchronized
5924
      - disconnect from the network
5925
      - change disks into single-master mode
5926
      - wait again until disks are fully synchronized
5927

5928
    """
5929
    instance = self.instance
5930
    target_node = self.target_node
5931
    source_node = self.source_node
5932

    
5933
    # check running on only one node
5934
    self.feedback_fn("* checking where the instance actually runs"
5935
                     " (if this hangs, the hypervisor might be in"
5936
                     " a bad state)")
5937
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
5938
    for node, result in ins_l.items():
5939
      result.Raise("Can't contact node %s" % node)
5940

    
5941
    runningon_source = instance.name in ins_l[source_node].payload
5942
    runningon_target = instance.name in ins_l[target_node].payload
5943

    
5944
    if runningon_source and runningon_target:
5945
      raise errors.OpExecError("Instance seems to be running on two nodes,"
5946
                               " or the hypervisor is confused. You will have"
5947
                               " to ensure manually that it runs only on one"
5948
                               " and restart this operation.")
5949

    
5950
    if not (runningon_source or runningon_target):
5951
      raise errors.OpExecError("Instance does not seem to be running at all."
5952
                               " In this case, it's safer to repair by"
5953
                               " running 'gnt-instance stop' to ensure disk"
5954
                               " shutdown, and then restarting it.")
5955

    
5956
    if runningon_target:
5957
      # the migration has actually succeeded, we need to update the config
5958
      self.feedback_fn("* instance running on secondary node (%s),"
5959
                       " updating config" % target_node)
5960
      instance.primary_node = target_node
5961
      self.cfg.Update(instance, self.feedback_fn)
5962
      demoted_node = source_node
5963
    else:
5964
      self.feedback_fn("* instance confirmed to be running on its"
5965
                       " primary node (%s)" % source_node)
5966
      demoted_node = target_node
5967

    
5968
    self._EnsureSecondary(demoted_node)
5969
    try:
5970
      self._WaitUntilSync()
5971
    except errors.OpExecError:
5972
      # we ignore here errors, since if the device is standalone, it
5973
      # won't be able to sync
5974
      pass
5975
    self._GoStandalone()
5976
    self._GoReconnect(False)
5977
    self._WaitUntilSync()
5978

    
5979
    self.feedback_fn("* done")
5980

    
5981
  def _RevertDiskStatus(self):
5982
    """Try to revert the disk status after a failed migration.
5983

5984
    """
5985
    target_node = self.target_node
5986
    try:
5987
      self._EnsureSecondary(target_node)
5988
      self._GoStandalone()
5989
      self._GoReconnect(False)
5990
      self._WaitUntilSync()
5991
    except errors.OpExecError, err:
5992
      self.lu.LogWarning("Migration failed and I can't reconnect the"
5993
                         " drives: error '%s'\n"
5994
                         "Please look and recover the instance status" %
5995
                         str(err))
5996

    
5997
  def _AbortMigration(self):
5998
    """Call the hypervisor code to abort a started migration.
5999

6000
    """
6001
    instance = self.instance
6002
    target_node = self.target_node
6003
    migration_info = self.migration_info
6004

    
6005
    abort_result = self.rpc.call_finalize_migration(target_node,
6006
                                                    instance,
6007
                                                    migration_info,
6008
                                                    False)
6009
    abort_msg = abort_result.fail_msg
6010
    if abort_msg:
6011
      logging.error("Aborting migration failed on target node %s: %s",
6012
                    target_node, abort_msg)
6013
      # Don't raise an exception here, as we stil have to try to revert the
6014
      # disk status, even if this step failed.
6015

    
6016
  def _ExecMigration(self):
6017
    """Migrate an instance.
6018

6019
    The migrate is done by:
6020
      - change the disks into dual-master mode
6021
      - wait until disks are fully synchronized again
6022
      - migrate the instance
6023
      - change disks on the new secondary node (the old primary) to secondary
6024
      - wait until disks are fully synchronized
6025
      - change disks into single-master mode
6026

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

    
6032
    self.feedback_fn("* checking disk consistency between source and target")
6033
    for dev in instance.disks:
6034
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6035
        raise errors.OpExecError("Disk %s is degraded or not fully"
6036
                                 " synchronized on target node,"
6037
                                 " aborting migrate." % dev.iv_name)
6038

    
6039
    # First get the migration information from the remote node
6040
    result = self.rpc.call_migration_info(source_node, instance)
6041
    msg = result.fail_msg
6042
    if msg:
6043
      log_err = ("Failed fetching source migration information from %s: %s" %
6044
                 (source_node, msg))
6045
      logging.error(log_err)
6046
      raise errors.OpExecError(log_err)
6047

    
6048
    self.migration_info = migration_info = result.payload
6049

    
6050
    # Then switch the disks to master/master mode
6051
    self._EnsureSecondary(target_node)
6052
    self._GoStandalone()
6053
    self._GoReconnect(True)
6054
    self._WaitUntilSync()
6055

    
6056
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6057
    result = self.rpc.call_accept_instance(target_node,
6058
                                           instance,
6059
                                           migration_info,
6060
                                           self.nodes_ip[target_node])
6061

    
6062
    msg = result.fail_msg
6063
    if msg:
6064
      logging.error("Instance pre-migration failed, trying to revert"
6065
                    " disk status: %s", msg)
6066
      self.feedback_fn("Pre-migration failed, aborting")
6067
      self._AbortMigration()
6068
      self._RevertDiskStatus()
6069
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6070
                               (instance.name, msg))
6071

    
6072
    self.feedback_fn("* migrating instance to %s" % target_node)
6073
    time.sleep(10)
6074
    result = self.rpc.call_instance_migrate(source_node, instance,
6075
                                            self.nodes_ip[target_node],
6076
                                            self.live)
6077
    msg = result.fail_msg
6078
    if msg:
6079
      logging.error("Instance migration failed, trying to revert"
6080
                    " disk status: %s", msg)
6081
      self.feedback_fn("Migration failed, aborting")
6082
      self._AbortMigration()
6083
      self._RevertDiskStatus()
6084
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6085
                               (instance.name, msg))
6086
    time.sleep(10)
6087

    
6088
    instance.primary_node = target_node
6089
    # distribute new instance config to the other nodes
6090
    self.cfg.Update(instance, self.feedback_fn)
6091

    
6092
    result = self.rpc.call_finalize_migration(target_node,
6093
                                              instance,
6094
                                              migration_info,
6095
                                              True)
6096
    msg = result.fail_msg
6097
    if msg:
6098
      logging.error("Instance migration succeeded, but finalization failed:"
6099
                    " %s", msg)
6100
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6101
                               msg)
6102

    
6103
    self._EnsureSecondary(source_node)
6104
    self._WaitUntilSync()
6105
    self._GoStandalone()
6106
    self._GoReconnect(False)
6107
    self._WaitUntilSync()
6108

    
6109
    self.feedback_fn("* done")
6110

    
6111
  def Exec(self, feedback_fn):
6112
    """Perform the migration.
6113

6114
    """
6115
    feedback_fn("Migrating instance %s" % self.instance.name)
6116

    
6117
    self.feedback_fn = feedback_fn
6118

    
6119
    self.source_node = self.instance.primary_node
6120
    self.target_node = self.instance.secondary_nodes[0]
6121
    self.all_nodes = [self.source_node, self.target_node]
6122
    self.nodes_ip = {
6123
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6124
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6125
      }
6126

    
6127
    if self.cleanup:
6128
      return self._ExecCleanup()
6129
    else:
6130
      return self._ExecMigration()
6131

    
6132

    
6133
def _CreateBlockDev(lu, node, instance, device, force_create,
6134
                    info, force_open):
6135
  """Create a tree of block devices on a given node.
6136

6137
  If this device type has to be created on secondaries, create it and
6138
  all its children.
6139

6140
  If not, just recurse to children keeping the same 'force' value.
6141

6142
  @param lu: the lu on whose behalf we execute
6143
  @param node: the node on which to create the device
6144
  @type instance: L{objects.Instance}
6145
  @param instance: the instance which owns the device
6146
  @type device: L{objects.Disk}
6147
  @param device: the device to create
6148
  @type force_create: boolean
6149
  @param force_create: whether to force creation of this device; this
6150
      will be change to True whenever we find a device which has
6151
      CreateOnSecondary() attribute
6152
  @param info: the extra 'metadata' we should attach to the device
6153
      (this will be represented as a LVM tag)
6154
  @type force_open: boolean
6155
  @param force_open: this parameter will be passes to the
6156
      L{backend.BlockdevCreate} function where it specifies
6157
      whether we run on primary or not, and it affects both
6158
      the child assembly and the device own Open() execution
6159

6160
  """
6161
  if device.CreateOnSecondary():
6162
    force_create = True
6163

    
6164
  if device.children:
6165
    for child in device.children:
6166
      _CreateBlockDev(lu, node, instance, child, force_create,
6167
                      info, force_open)
6168

    
6169
  if not force_create:
6170
    return
6171

    
6172
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6173

    
6174

    
6175
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6176
  """Create a single block device on a given node.
6177

6178
  This will not recurse over children of the device, so they must be
6179
  created in advance.
6180

6181
  @param lu: the lu on whose behalf we execute
6182
  @param node: the node on which to create the device
6183
  @type instance: L{objects.Instance}
6184
  @param instance: the instance which owns the device
6185
  @type device: L{objects.Disk}
6186
  @param device: the device to create
6187
  @param info: the extra 'metadata' we should attach to the device
6188
      (this will be represented as a LVM tag)
6189
  @type force_open: boolean
6190
  @param force_open: this parameter will be passes to the
6191
      L{backend.BlockdevCreate} function where it specifies
6192
      whether we run on primary or not, and it affects both
6193
      the child assembly and the device own Open() execution
6194

6195
  """
6196
  lu.cfg.SetDiskID(device, node)
6197
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6198
                                       instance.name, force_open, info)
6199
  result.Raise("Can't create block device %s on"
6200
               " node %s for instance %s" % (device, node, instance.name))
6201
  if device.physical_id is None:
6202
    device.physical_id = result.payload
6203

    
6204

    
6205
def _GenerateUniqueNames(lu, exts):
6206
  """Generate a suitable LV name.
6207

6208
  This will generate a logical volume name for the given instance.
6209

6210
  """
6211
  results = []
6212
  for val in exts:
6213
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6214
    results.append("%s%s" % (new_id, val))
6215
  return results
6216

    
6217

    
6218
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
6219
                         p_minor, s_minor):
6220
  """Generate a drbd8 device complete with its children.
6221

6222
  """
6223
  port = lu.cfg.AllocatePort()
6224
  vgname = lu.cfg.GetVGName()
6225
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6226
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6227
                          logical_id=(vgname, names[0]))
6228
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6229
                          logical_id=(vgname, names[1]))
6230
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6231
                          logical_id=(primary, secondary, port,
6232
                                      p_minor, s_minor,
6233
                                      shared_secret),
6234
                          children=[dev_data, dev_meta],
6235
                          iv_name=iv_name)
6236
  return drbd_dev
6237

    
6238

    
6239
def _GenerateDiskTemplate(lu, template_name,
6240
                          instance_name, primary_node,
6241
                          secondary_nodes, disk_info,
6242
                          file_storage_dir, file_driver,
6243
                          base_index):
6244
  """Generate the entire disk layout for a given template type.
6245

6246
  """
6247
  #TODO: compute space requirements
6248

    
6249
  vgname = lu.cfg.GetVGName()
6250
  disk_count = len(disk_info)
6251
  disks = []
6252
  if template_name == constants.DT_DISKLESS:
6253
    pass
6254
  elif template_name == constants.DT_PLAIN:
6255
    if len(secondary_nodes) != 0:
6256
      raise errors.ProgrammerError("Wrong template configuration")
6257

    
6258
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6259
                                      for i in range(disk_count)])
6260
    for idx, disk in enumerate(disk_info):
6261
      disk_index = idx + base_index
6262
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6263
                              logical_id=(vgname, names[idx]),
6264
                              iv_name="disk/%d" % disk_index,
6265
                              mode=disk["mode"])
6266
      disks.append(disk_dev)
6267
  elif template_name == constants.DT_DRBD8:
6268
    if len(secondary_nodes) != 1:
6269
      raise errors.ProgrammerError("Wrong template configuration")
6270
    remote_node = secondary_nodes[0]
6271
    minors = lu.cfg.AllocateDRBDMinor(
6272
      [primary_node, remote_node] * len(disk_info), instance_name)
6273

    
6274
    names = []
6275
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6276
                                               for i in range(disk_count)]):
6277
      names.append(lv_prefix + "_data")
6278
      names.append(lv_prefix + "_meta")
6279
    for idx, disk in enumerate(disk_info):
6280
      disk_index = idx + base_index
6281
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6282
                                      disk["size"], names[idx*2:idx*2+2],
6283
                                      "disk/%d" % disk_index,
6284
                                      minors[idx*2], minors[idx*2+1])
6285
      disk_dev.mode = disk["mode"]
6286
      disks.append(disk_dev)
6287
  elif template_name == constants.DT_FILE:
6288
    if len(secondary_nodes) != 0:
6289
      raise errors.ProgrammerError("Wrong template configuration")
6290

    
6291
    _RequireFileStorage()
6292

    
6293
    for idx, disk in enumerate(disk_info):
6294
      disk_index = idx + base_index
6295
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6296
                              iv_name="disk/%d" % disk_index,
6297
                              logical_id=(file_driver,
6298
                                          "%s/disk%d" % (file_storage_dir,
6299
                                                         disk_index)),
6300
                              mode=disk["mode"])
6301
      disks.append(disk_dev)
6302
  else:
6303
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6304
  return disks
6305

    
6306

    
6307
def _GetInstanceInfoText(instance):
6308
  """Compute that text that should be added to the disk's metadata.
6309

6310
  """
6311
  return "originstname+%s" % instance.name
6312

    
6313

    
6314
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6315
  """Create all disks for an instance.
6316

6317
  This abstracts away some work from AddInstance.
6318

6319
  @type lu: L{LogicalUnit}
6320
  @param lu: the logical unit on whose behalf we execute
6321
  @type instance: L{objects.Instance}
6322
  @param instance: the instance whose disks we should create
6323
  @type to_skip: list
6324
  @param to_skip: list of indices to skip
6325
  @type target_node: string
6326
  @param target_node: if passed, overrides the target node for creation
6327
  @rtype: boolean
6328
  @return: the success of the creation
6329

6330
  """
6331
  info = _GetInstanceInfoText(instance)
6332
  if target_node is None:
6333
    pnode = instance.primary_node
6334
    all_nodes = instance.all_nodes
6335
  else:
6336
    pnode = target_node
6337
    all_nodes = [pnode]
6338

    
6339
  if instance.disk_template == constants.DT_FILE:
6340
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6341
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6342

    
6343
    result.Raise("Failed to create directory '%s' on"
6344
                 " node %s" % (file_storage_dir, pnode))
6345

    
6346
  # Note: this needs to be kept in sync with adding of disks in
6347
  # LUSetInstanceParams
6348
  for idx, device in enumerate(instance.disks):
6349
    if to_skip and idx in to_skip:
6350
      continue
6351
    logging.info("Creating volume %s for instance %s",
6352
                 device.iv_name, instance.name)
6353
    #HARDCODE
6354
    for node in all_nodes:
6355
      f_create = node == pnode
6356
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6357

    
6358

    
6359
def _RemoveDisks(lu, instance, target_node=None):
6360
  """Remove all disks for an instance.
6361

6362
  This abstracts away some work from `AddInstance()` and
6363
  `RemoveInstance()`. Note that in case some of the devices couldn't
6364
  be removed, the removal will continue with the other ones (compare
6365
  with `_CreateDisks()`).
6366

6367
  @type lu: L{LogicalUnit}
6368
  @param lu: the logical unit on whose behalf we execute
6369
  @type instance: L{objects.Instance}
6370
  @param instance: the instance whose disks we should remove
6371
  @type target_node: string
6372
  @param target_node: used to override the node on which to remove the disks
6373
  @rtype: boolean
6374
  @return: the success of the removal
6375

6376
  """
6377
  logging.info("Removing block devices for instance %s", instance.name)
6378

    
6379
  all_result = True
6380
  for device in instance.disks:
6381
    if target_node:
6382
      edata = [(target_node, device)]
6383
    else:
6384
      edata = device.ComputeNodeTree(instance.primary_node)
6385
    for node, disk in edata:
6386
      lu.cfg.SetDiskID(disk, node)
6387
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6388
      if msg:
6389
        lu.LogWarning("Could not remove block device %s on node %s,"
6390
                      " continuing anyway: %s", device.iv_name, node, msg)
6391
        all_result = False
6392

    
6393
  if instance.disk_template == constants.DT_FILE:
6394
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6395
    if target_node:
6396
      tgt = target_node
6397
    else:
6398
      tgt = instance.primary_node
6399
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6400
    if result.fail_msg:
6401
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6402
                    file_storage_dir, instance.primary_node, result.fail_msg)
6403
      all_result = False
6404

    
6405
  return all_result
6406

    
6407

    
6408
def _ComputeDiskSize(disk_template, disks):
6409
  """Compute disk size requirements in the volume group
6410

6411
  """
6412
  # Required free disk space as a function of disk and swap space
6413
  req_size_dict = {
6414
    constants.DT_DISKLESS: None,
6415
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6416
    # 128 MB are added for drbd metadata for each disk
6417
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6418
    constants.DT_FILE: None,
6419
  }
6420

    
6421
  if disk_template not in req_size_dict:
6422
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6423
                                 " is unknown" %  disk_template)
6424

    
6425
  return req_size_dict[disk_template]
6426

    
6427

    
6428
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6429
  """Hypervisor parameter validation.
6430

6431
  This function abstract the hypervisor parameter validation to be
6432
  used in both instance create and instance modify.
6433

6434
  @type lu: L{LogicalUnit}
6435
  @param lu: the logical unit for which we check
6436
  @type nodenames: list
6437
  @param nodenames: the list of nodes on which we should check
6438
  @type hvname: string
6439
  @param hvname: the name of the hypervisor we should use
6440
  @type hvparams: dict
6441
  @param hvparams: the parameters which we need to check
6442
  @raise errors.OpPrereqError: if the parameters are not valid
6443

6444
  """
6445
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6446
                                                  hvname,
6447
                                                  hvparams)
6448
  for node in nodenames:
6449
    info = hvinfo[node]
6450
    if info.offline:
6451
      continue
6452
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6453

    
6454

    
6455
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6456
  """OS parameters validation.
6457

6458
  @type lu: L{LogicalUnit}
6459
  @param lu: the logical unit for which we check
6460
  @type required: boolean
6461
  @param required: whether the validation should fail if the OS is not
6462
      found
6463
  @type nodenames: list
6464
  @param nodenames: the list of nodes on which we should check
6465
  @type osname: string
6466
  @param osname: the name of the hypervisor we should use
6467
  @type osparams: dict
6468
  @param osparams: the parameters which we need to check
6469
  @raise errors.OpPrereqError: if the parameters are not valid
6470

6471
  """
6472
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6473
                                   [constants.OS_VALIDATE_PARAMETERS],
6474
                                   osparams)
6475
  for node, nres in result.items():
6476
    # we don't check for offline cases since this should be run only
6477
    # against the master node and/or an instance's nodes
6478
    nres.Raise("OS Parameters validation failed on node %s" % node)
6479
    if not nres.payload:
6480
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6481
                 osname, node)
6482

    
6483

    
6484
class LUCreateInstance(LogicalUnit):
6485
  """Create an instance.
6486

6487
  """
6488
  HPATH = "instance-add"
6489
  HTYPE = constants.HTYPE_INSTANCE
6490
  _OP_PARAMS = [
6491
    _PInstanceName,
6492
    ("mode", _NoDefault, _TElemOf(constants.INSTANCE_CREATE_MODES)),
6493
    ("start", True, _TBool),
6494
    ("wait_for_sync", True, _TBool),
6495
    ("ip_check", True, _TBool),
6496
    ("name_check", True, _TBool),
6497
    ("disks", _NoDefault, _TListOf(_TDict)),
6498
    ("nics", _NoDefault, _TListOf(_TDict)),
6499
    ("hvparams", _EmptyDict, _TDict),
6500
    ("beparams", _EmptyDict, _TDict),
6501
    ("osparams", _EmptyDict, _TDict),
6502
    ("no_install", None, _TMaybeBool),
6503
    ("os_type", None, _TMaybeString),
6504
    ("force_variant", False, _TBool),
6505
    ("source_handshake", None, _TOr(_TList, _TNone)),
6506
    ("source_x509_ca", None, _TOr(_TList, _TNone)),
6507
    ("source_instance_name", None, _TMaybeString),
6508
    ("src_node", None, _TMaybeString),
6509
    ("src_path", None, _TMaybeString),
6510
    ("pnode", None, _TMaybeString),
6511
    ("snode", None, _TMaybeString),
6512
    ("iallocator", None, _TMaybeString),
6513
    ("hypervisor", None, _TMaybeString),
6514
    ("disk_template", _NoDefault, _CheckDiskTemplate),
6515
    ("identify_defaults", False, _TBool),
6516
    ("file_driver", None, _TOr(_TNone, _TElemOf(constants.FILE_DRIVER))),
6517
    ("file_storage_dir", None, _TMaybeString),
6518
    ("dry_run", False, _TBool),
6519
    ]
6520
  REQ_BGL = False
6521

    
6522
  def CheckArguments(self):
6523
    """Check arguments.
6524

6525
    """
6526
    # do not require name_check to ease forward/backward compatibility
6527
    # for tools
6528
    if self.op.no_install and self.op.start:
6529
      self.LogInfo("No-installation mode selected, disabling startup")
6530
      self.op.start = False
6531
    # validate/normalize the instance name
6532
    self.op.instance_name = \
6533
      netutils.HostInfo.NormalizeName(self.op.instance_name)
6534

    
6535
    if self.op.ip_check and not self.op.name_check:
6536
      # TODO: make the ip check more flexible and not depend on the name check
6537
      raise errors.OpPrereqError("Cannot do ip check without a name check",
6538
                                 errors.ECODE_INVAL)
6539

    
6540
    # check nics' parameter names
6541
    for nic in self.op.nics:
6542
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6543

    
6544
    # check disks. parameter names and consistent adopt/no-adopt strategy
6545
    has_adopt = has_no_adopt = False
6546
    for disk in self.op.disks:
6547
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6548
      if "adopt" in disk:
6549
        has_adopt = True
6550
      else:
6551
        has_no_adopt = True
6552
    if has_adopt and has_no_adopt:
6553
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6554
                                 errors.ECODE_INVAL)
6555
    if has_adopt:
6556
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6557
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6558
                                   " '%s' disk template" %
6559
                                   self.op.disk_template,
6560
                                   errors.ECODE_INVAL)
6561
      if self.op.iallocator is not None:
6562
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6563
                                   " iallocator script", errors.ECODE_INVAL)
6564
      if self.op.mode == constants.INSTANCE_IMPORT:
6565
        raise errors.OpPrereqError("Disk adoption not allowed for"
6566
                                   " instance import", errors.ECODE_INVAL)
6567

    
6568
    self.adopt_disks = has_adopt
6569

    
6570
    # instance name verification
6571
    if self.op.name_check:
6572
      self.hostname1 = netutils.GetHostInfo(self.op.instance_name)
6573
      self.op.instance_name = self.hostname1.name
6574
      # used in CheckPrereq for ip ping check
6575
      self.check_ip = self.hostname1.ip
6576
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6577
      raise errors.OpPrereqError("Remote imports require names to be checked" %
6578
                                 errors.ECODE_INVAL)
6579
    else:
6580
      self.check_ip = None
6581

    
6582
    # file storage checks
6583
    if (self.op.file_driver and
6584
        not self.op.file_driver in constants.FILE_DRIVER):
6585
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6586
                                 self.op.file_driver, errors.ECODE_INVAL)
6587

    
6588
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6589
      raise errors.OpPrereqError("File storage directory path not absolute",
6590
                                 errors.ECODE_INVAL)
6591

    
6592
    ### Node/iallocator related checks
6593
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
6594

    
6595
    self._cds = _GetClusterDomainSecret()
6596

    
6597
    if self.op.mode == constants.INSTANCE_IMPORT:
6598
      # On import force_variant must be True, because if we forced it at
6599
      # initial install, our only chance when importing it back is that it
6600
      # works again!
6601
      self.op.force_variant = True
6602

    
6603
      if self.op.no_install:
6604
        self.LogInfo("No-installation mode has no effect during import")
6605

    
6606
    elif self.op.mode == constants.INSTANCE_CREATE:
6607
      if self.op.os_type is None:
6608
        raise errors.OpPrereqError("No guest OS specified",
6609
                                   errors.ECODE_INVAL)
6610
      if self.op.disk_template is None:
6611
        raise errors.OpPrereqError("No disk template specified",
6612
                                   errors.ECODE_INVAL)
6613

    
6614
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6615
      # Check handshake to ensure both clusters have the same domain secret
6616
      src_handshake = self.op.source_handshake
6617
      if not src_handshake:
6618
        raise errors.OpPrereqError("Missing source handshake",
6619
                                   errors.ECODE_INVAL)
6620

    
6621
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6622
                                                           src_handshake)
6623
      if errmsg:
6624
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6625
                                   errors.ECODE_INVAL)
6626

    
6627
      # Load and check source CA
6628
      self.source_x509_ca_pem = self.op.source_x509_ca
6629
      if not self.source_x509_ca_pem:
6630
        raise errors.OpPrereqError("Missing source X509 CA",
6631
                                   errors.ECODE_INVAL)
6632

    
6633
      try:
6634
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
6635
                                                    self._cds)
6636
      except OpenSSL.crypto.Error, err:
6637
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
6638
                                   (err, ), errors.ECODE_INVAL)
6639

    
6640
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
6641
      if errcode is not None:
6642
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
6643
                                   errors.ECODE_INVAL)
6644

    
6645
      self.source_x509_ca = cert
6646

    
6647
      src_instance_name = self.op.source_instance_name
6648
      if not src_instance_name:
6649
        raise errors.OpPrereqError("Missing source instance name",
6650
                                   errors.ECODE_INVAL)
6651

    
6652
      norm_name = netutils.HostInfo.NormalizeName(src_instance_name)
6653
      self.source_instance_name = netutils.GetHostInfo(norm_name).name
6654

    
6655
    else:
6656
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
6657
                                 self.op.mode, errors.ECODE_INVAL)
6658

    
6659
  def ExpandNames(self):
6660
    """ExpandNames for CreateInstance.
6661

6662
    Figure out the right locks for instance creation.
6663

6664
    """
6665
    self.needed_locks = {}
6666

    
6667
    instance_name = self.op.instance_name
6668
    # this is just a preventive check, but someone might still add this
6669
    # instance in the meantime, and creation will fail at lock-add time
6670
    if instance_name in self.cfg.GetInstanceList():
6671
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6672
                                 instance_name, errors.ECODE_EXISTS)
6673

    
6674
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
6675

    
6676
    if self.op.iallocator:
6677
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6678
    else:
6679
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
6680
      nodelist = [self.op.pnode]
6681
      if self.op.snode is not None:
6682
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
6683
        nodelist.append(self.op.snode)
6684
      self.needed_locks[locking.LEVEL_NODE] = nodelist
6685

    
6686
    # in case of import lock the source node too
6687
    if self.op.mode == constants.INSTANCE_IMPORT:
6688
      src_node = self.op.src_node
6689
      src_path = self.op.src_path
6690

    
6691
      if src_path is None:
6692
        self.op.src_path = src_path = self.op.instance_name
6693

    
6694
      if src_node is None:
6695
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6696
        self.op.src_node = None
6697
        if os.path.isabs(src_path):
6698
          raise errors.OpPrereqError("Importing an instance from an absolute"
6699
                                     " path requires a source node option.",
6700
                                     errors.ECODE_INVAL)
6701
      else:
6702
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
6703
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
6704
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
6705
        if not os.path.isabs(src_path):
6706
          self.op.src_path = src_path = \
6707
            utils.PathJoin(constants.EXPORT_DIR, src_path)
6708

    
6709
  def _RunAllocator(self):
6710
    """Run the allocator based on input opcode.
6711

6712
    """
6713
    nics = [n.ToDict() for n in self.nics]
6714
    ial = IAllocator(self.cfg, self.rpc,
6715
                     mode=constants.IALLOCATOR_MODE_ALLOC,
6716
                     name=self.op.instance_name,
6717
                     disk_template=self.op.disk_template,
6718
                     tags=[],
6719
                     os=self.op.os_type,
6720
                     vcpus=self.be_full[constants.BE_VCPUS],
6721
                     mem_size=self.be_full[constants.BE_MEMORY],
6722
                     disks=self.disks,
6723
                     nics=nics,
6724
                     hypervisor=self.op.hypervisor,
6725
                     )
6726

    
6727
    ial.Run(self.op.iallocator)
6728

    
6729
    if not ial.success:
6730
      raise errors.OpPrereqError("Can't compute nodes using"
6731
                                 " iallocator '%s': %s" %
6732
                                 (self.op.iallocator, ial.info),
6733
                                 errors.ECODE_NORES)
6734
    if len(ial.result) != ial.required_nodes:
6735
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6736
                                 " of nodes (%s), required %s" %
6737
                                 (self.op.iallocator, len(ial.result),
6738
                                  ial.required_nodes), errors.ECODE_FAULT)
6739
    self.op.pnode = ial.result[0]
6740
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6741
                 self.op.instance_name, self.op.iallocator,
6742
                 utils.CommaJoin(ial.result))
6743
    if ial.required_nodes == 2:
6744
      self.op.snode = ial.result[1]
6745

    
6746
  def BuildHooksEnv(self):
6747
    """Build hooks env.
6748

6749
    This runs on master, primary and secondary nodes of the instance.
6750

6751
    """
6752
    env = {
6753
      "ADD_MODE": self.op.mode,
6754
      }
6755
    if self.op.mode == constants.INSTANCE_IMPORT:
6756
      env["SRC_NODE"] = self.op.src_node
6757
      env["SRC_PATH"] = self.op.src_path
6758
      env["SRC_IMAGES"] = self.src_images
6759

    
6760
    env.update(_BuildInstanceHookEnv(
6761
      name=self.op.instance_name,
6762
      primary_node=self.op.pnode,
6763
      secondary_nodes=self.secondaries,
6764
      status=self.op.start,
6765
      os_type=self.op.os_type,
6766
      memory=self.be_full[constants.BE_MEMORY],
6767
      vcpus=self.be_full[constants.BE_VCPUS],
6768
      nics=_NICListToTuple(self, self.nics),
6769
      disk_template=self.op.disk_template,
6770
      disks=[(d["size"], d["mode"]) for d in self.disks],
6771
      bep=self.be_full,
6772
      hvp=self.hv_full,
6773
      hypervisor_name=self.op.hypervisor,
6774
    ))
6775

    
6776
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
6777
          self.secondaries)
6778
    return env, nl, nl
6779

    
6780
  def _ReadExportInfo(self):
6781
    """Reads the export information from disk.
6782

6783
    It will override the opcode source node and path with the actual
6784
    information, if these two were not specified before.
6785

6786
    @return: the export information
6787

6788
    """
6789
    assert self.op.mode == constants.INSTANCE_IMPORT
6790

    
6791
    src_node = self.op.src_node
6792
    src_path = self.op.src_path
6793

    
6794
    if src_node is None:
6795
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
6796
      exp_list = self.rpc.call_export_list(locked_nodes)
6797
      found = False
6798
      for node in exp_list:
6799
        if exp_list[node].fail_msg:
6800
          continue
6801
        if src_path in exp_list[node].payload:
6802
          found = True
6803
          self.op.src_node = src_node = node
6804
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
6805
                                                       src_path)
6806
          break
6807
      if not found:
6808
        raise errors.OpPrereqError("No export found for relative path %s" %
6809
                                    src_path, errors.ECODE_INVAL)
6810

    
6811
    _CheckNodeOnline(self, src_node)
6812
    result = self.rpc.call_export_info(src_node, src_path)
6813
    result.Raise("No export or invalid export found in dir %s" % src_path)
6814

    
6815
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
6816
    if not export_info.has_section(constants.INISECT_EXP):
6817
      raise errors.ProgrammerError("Corrupted export config",
6818
                                   errors.ECODE_ENVIRON)
6819

    
6820
    ei_version = export_info.get(constants.INISECT_EXP, "version")
6821
    if (int(ei_version) != constants.EXPORT_VERSION):
6822
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
6823
                                 (ei_version, constants.EXPORT_VERSION),
6824
                                 errors.ECODE_ENVIRON)
6825
    return export_info
6826

    
6827
  def _ReadExportParams(self, einfo):
6828
    """Use export parameters as defaults.
6829

6830
    In case the opcode doesn't specify (as in override) some instance
6831
    parameters, then try to use them from the export information, if
6832
    that declares them.
6833

6834
    """
6835
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
6836

    
6837
    if self.op.disk_template is None:
6838
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
6839
        self.op.disk_template = einfo.get(constants.INISECT_INS,
6840
                                          "disk_template")
6841
      else:
6842
        raise errors.OpPrereqError("No disk template specified and the export"
6843
                                   " is missing the disk_template information",
6844
                                   errors.ECODE_INVAL)
6845

    
6846
    if not self.op.disks:
6847
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
6848
        disks = []
6849
        # TODO: import the disk iv_name too
6850
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
6851
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
6852
          disks.append({"size": disk_sz})
6853
        self.op.disks = disks
6854
      else:
6855
        raise errors.OpPrereqError("No disk info specified and the export"
6856
                                   " is missing the disk information",
6857
                                   errors.ECODE_INVAL)
6858

    
6859
    if (not self.op.nics and
6860
        einfo.has_option(constants.INISECT_INS, "nic_count")):
6861
      nics = []
6862
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
6863
        ndict = {}
6864
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
6865
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
6866
          ndict[name] = v
6867
        nics.append(ndict)
6868
      self.op.nics = nics
6869

    
6870
    if (self.op.hypervisor is None and
6871
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
6872
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
6873
    if einfo.has_section(constants.INISECT_HYP):
6874
      # use the export parameters but do not override the ones
6875
      # specified by the user
6876
      for name, value in einfo.items(constants.INISECT_HYP):
6877
        if name not in self.op.hvparams:
6878
          self.op.hvparams[name] = value
6879

    
6880
    if einfo.has_section(constants.INISECT_BEP):
6881
      # use the parameters, without overriding
6882
      for name, value in einfo.items(constants.INISECT_BEP):
6883
        if name not in self.op.beparams:
6884
          self.op.beparams[name] = value
6885
    else:
6886
      # try to read the parameters old style, from the main section
6887
      for name in constants.BES_PARAMETERS:
6888
        if (name not in self.op.beparams and
6889
            einfo.has_option(constants.INISECT_INS, name)):
6890
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
6891

    
6892
    if einfo.has_section(constants.INISECT_OSP):
6893
      # use the parameters, without overriding
6894
      for name, value in einfo.items(constants.INISECT_OSP):
6895
        if name not in self.op.osparams:
6896
          self.op.osparams[name] = value
6897

    
6898
  def _RevertToDefaults(self, cluster):
6899
    """Revert the instance parameters to the default values.
6900

6901
    """
6902
    # hvparams
6903
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
6904
    for name in self.op.hvparams.keys():
6905
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
6906
        del self.op.hvparams[name]
6907
    # beparams
6908
    be_defs = cluster.SimpleFillBE({})
6909
    for name in self.op.beparams.keys():
6910
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
6911
        del self.op.beparams[name]
6912
    # nic params
6913
    nic_defs = cluster.SimpleFillNIC({})
6914
    for nic in self.op.nics:
6915
      for name in constants.NICS_PARAMETERS:
6916
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
6917
          del nic[name]
6918
    # osparams
6919
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
6920
    for name in self.op.osparams.keys():
6921
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
6922
        del self.op.osparams[name]
6923

    
6924
  def CheckPrereq(self):
6925
    """Check prerequisites.
6926

6927
    """
6928
    if self.op.mode == constants.INSTANCE_IMPORT:
6929
      export_info = self._ReadExportInfo()
6930
      self._ReadExportParams(export_info)
6931

    
6932
    _CheckDiskTemplate(self.op.disk_template)
6933

    
6934
    if (not self.cfg.GetVGName() and
6935
        self.op.disk_template not in constants.DTS_NOT_LVM):
6936
      raise errors.OpPrereqError("Cluster does not support lvm-based"
6937
                                 " instances", errors.ECODE_STATE)
6938

    
6939
    if self.op.hypervisor is None:
6940
      self.op.hypervisor = self.cfg.GetHypervisorType()
6941

    
6942
    cluster = self.cfg.GetClusterInfo()
6943
    enabled_hvs = cluster.enabled_hypervisors
6944
    if self.op.hypervisor not in enabled_hvs:
6945
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
6946
                                 " cluster (%s)" % (self.op.hypervisor,
6947
                                  ",".join(enabled_hvs)),
6948
                                 errors.ECODE_STATE)
6949

    
6950
    # check hypervisor parameter syntax (locally)
6951
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
6952
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
6953
                                      self.op.hvparams)
6954
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
6955
    hv_type.CheckParameterSyntax(filled_hvp)
6956
    self.hv_full = filled_hvp
6957
    # check that we don't specify global parameters on an instance
6958
    _CheckGlobalHvParams(self.op.hvparams)
6959

    
6960
    # fill and remember the beparams dict
6961
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
6962
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
6963

    
6964
    # build os parameters
6965
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
6966

    
6967
    # now that hvp/bep are in final format, let's reset to defaults,
6968
    # if told to do so
6969
    if self.op.identify_defaults:
6970
      self._RevertToDefaults(cluster)
6971

    
6972
    # NIC buildup
6973
    self.nics = []
6974
    for idx, nic in enumerate(self.op.nics):
6975
      nic_mode_req = nic.get("mode", None)
6976
      nic_mode = nic_mode_req
6977
      if nic_mode is None:
6978
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
6979

    
6980
      # in routed mode, for the first nic, the default ip is 'auto'
6981
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
6982
        default_ip_mode = constants.VALUE_AUTO
6983
      else:
6984
        default_ip_mode = constants.VALUE_NONE
6985

    
6986
      # ip validity checks
6987
      ip = nic.get("ip", default_ip_mode)
6988
      if ip is None or ip.lower() == constants.VALUE_NONE:
6989
        nic_ip = None
6990
      elif ip.lower() == constants.VALUE_AUTO:
6991
        if not self.op.name_check:
6992
          raise errors.OpPrereqError("IP address set to auto but name checks"
6993
                                     " have been skipped. Aborting.",
6994
                                     errors.ECODE_INVAL)
6995
        nic_ip = self.hostname1.ip
6996
      else:
6997
        if not netutils.IsValidIP4(ip):
6998
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
6999
                                     " like a valid IP" % ip,
7000
                                     errors.ECODE_INVAL)
7001
        nic_ip = ip
7002

    
7003
      # TODO: check the ip address for uniqueness
7004
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7005
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7006
                                   errors.ECODE_INVAL)
7007

    
7008
      # MAC address verification
7009
      mac = nic.get("mac", constants.VALUE_AUTO)
7010
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7011
        mac = utils.NormalizeAndValidateMac(mac)
7012

    
7013
        try:
7014
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7015
        except errors.ReservationError:
7016
          raise errors.OpPrereqError("MAC address %s already in use"
7017
                                     " in cluster" % mac,
7018
                                     errors.ECODE_NOTUNIQUE)
7019

    
7020
      # bridge verification
7021
      bridge = nic.get("bridge", None)
7022
      link = nic.get("link", None)
7023
      if bridge and link:
7024
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7025
                                   " at the same time", errors.ECODE_INVAL)
7026
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7027
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7028
                                   errors.ECODE_INVAL)
7029
      elif bridge:
7030
        link = bridge
7031

    
7032
      nicparams = {}
7033
      if nic_mode_req:
7034
        nicparams[constants.NIC_MODE] = nic_mode_req
7035
      if link:
7036
        nicparams[constants.NIC_LINK] = link
7037

    
7038
      check_params = cluster.SimpleFillNIC(nicparams)
7039
      objects.NIC.CheckParameterSyntax(check_params)
7040
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7041

    
7042
    # disk checks/pre-build
7043
    self.disks = []
7044
    for disk in self.op.disks:
7045
      mode = disk.get("mode", constants.DISK_RDWR)
7046
      if mode not in constants.DISK_ACCESS_SET:
7047
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7048
                                   mode, errors.ECODE_INVAL)
7049
      size = disk.get("size", None)
7050
      if size is None:
7051
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7052
      try:
7053
        size = int(size)
7054
      except (TypeError, ValueError):
7055
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7056
                                   errors.ECODE_INVAL)
7057
      new_disk = {"size": size, "mode": mode}
7058
      if "adopt" in disk:
7059
        new_disk["adopt"] = disk["adopt"]
7060
      self.disks.append(new_disk)
7061

    
7062
    if self.op.mode == constants.INSTANCE_IMPORT:
7063

    
7064
      # Check that the new instance doesn't have less disks than the export
7065
      instance_disks = len(self.disks)
7066
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7067
      if instance_disks < export_disks:
7068
        raise errors.OpPrereqError("Not enough disks to import."
7069
                                   " (instance: %d, export: %d)" %
7070
                                   (instance_disks, export_disks),
7071
                                   errors.ECODE_INVAL)
7072

    
7073
      disk_images = []
7074
      for idx in range(export_disks):
7075
        option = 'disk%d_dump' % idx
7076
        if export_info.has_option(constants.INISECT_INS, option):
7077
          # FIXME: are the old os-es, disk sizes, etc. useful?
7078
          export_name = export_info.get(constants.INISECT_INS, option)
7079
          image = utils.PathJoin(self.op.src_path, export_name)
7080
          disk_images.append(image)
7081
        else:
7082
          disk_images.append(False)
7083

    
7084
      self.src_images = disk_images
7085

    
7086
      old_name = export_info.get(constants.INISECT_INS, 'name')
7087
      try:
7088
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7089
      except (TypeError, ValueError), err:
7090
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7091
                                   " an integer: %s" % str(err),
7092
                                   errors.ECODE_STATE)
7093
      if self.op.instance_name == old_name:
7094
        for idx, nic in enumerate(self.nics):
7095
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7096
            nic_mac_ini = 'nic%d_mac' % idx
7097
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7098

    
7099
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7100

    
7101
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7102
    if self.op.ip_check:
7103
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7104
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7105
                                   (self.check_ip, self.op.instance_name),
7106
                                   errors.ECODE_NOTUNIQUE)
7107

    
7108
    #### mac address generation
7109
    # By generating here the mac address both the allocator and the hooks get
7110
    # the real final mac address rather than the 'auto' or 'generate' value.
7111
    # There is a race condition between the generation and the instance object
7112
    # creation, which means that we know the mac is valid now, but we're not
7113
    # sure it will be when we actually add the instance. If things go bad
7114
    # adding the instance will abort because of a duplicate mac, and the
7115
    # creation job will fail.
7116
    for nic in self.nics:
7117
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7118
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7119

    
7120
    #### allocator run
7121

    
7122
    if self.op.iallocator is not None:
7123
      self._RunAllocator()
7124

    
7125
    #### node related checks
7126

    
7127
    # check primary node
7128
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7129
    assert self.pnode is not None, \
7130
      "Cannot retrieve locked node %s" % self.op.pnode
7131
    if pnode.offline:
7132
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7133
                                 pnode.name, errors.ECODE_STATE)
7134
    if pnode.drained:
7135
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7136
                                 pnode.name, errors.ECODE_STATE)
7137

    
7138
    self.secondaries = []
7139

    
7140
    # mirror node verification
7141
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7142
      if self.op.snode is None:
7143
        raise errors.OpPrereqError("The networked disk templates need"
7144
                                   " a mirror node", errors.ECODE_INVAL)
7145
      if self.op.snode == pnode.name:
7146
        raise errors.OpPrereqError("The secondary node cannot be the"
7147
                                   " primary node.", errors.ECODE_INVAL)
7148
      _CheckNodeOnline(self, self.op.snode)
7149
      _CheckNodeNotDrained(self, self.op.snode)
7150
      self.secondaries.append(self.op.snode)
7151

    
7152
    nodenames = [pnode.name] + self.secondaries
7153

    
7154
    req_size = _ComputeDiskSize(self.op.disk_template,
7155
                                self.disks)
7156

    
7157
    # Check lv size requirements, if not adopting
7158
    if req_size is not None and not self.adopt_disks:
7159
      _CheckNodesFreeDisk(self, nodenames, req_size)
7160

    
7161
    if self.adopt_disks: # instead, we must check the adoption data
7162
      all_lvs = set([i["adopt"] for i in self.disks])
7163
      if len(all_lvs) != len(self.disks):
7164
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7165
                                   errors.ECODE_INVAL)
7166
      for lv_name in all_lvs:
7167
        try:
7168
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7169
        except errors.ReservationError:
7170
          raise errors.OpPrereqError("LV named %s used by another instance" %
7171
                                     lv_name, errors.ECODE_NOTUNIQUE)
7172

    
7173
      node_lvs = self.rpc.call_lv_list([pnode.name],
7174
                                       self.cfg.GetVGName())[pnode.name]
7175
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7176
      node_lvs = node_lvs.payload
7177
      delta = all_lvs.difference(node_lvs.keys())
7178
      if delta:
7179
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7180
                                   utils.CommaJoin(delta),
7181
                                   errors.ECODE_INVAL)
7182
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7183
      if online_lvs:
7184
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7185
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7186
                                   errors.ECODE_STATE)
7187
      # update the size of disk based on what is found
7188
      for dsk in self.disks:
7189
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
7190

    
7191
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7192

    
7193
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7194
    # check OS parameters (remotely)
7195
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7196

    
7197
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7198

    
7199
    # memory check on primary node
7200
    if self.op.start:
7201
      _CheckNodeFreeMemory(self, self.pnode.name,
7202
                           "creating instance %s" % self.op.instance_name,
7203
                           self.be_full[constants.BE_MEMORY],
7204
                           self.op.hypervisor)
7205

    
7206
    self.dry_run_result = list(nodenames)
7207

    
7208
  def Exec(self, feedback_fn):
7209
    """Create and add the instance to the cluster.
7210

7211
    """
7212
    instance = self.op.instance_name
7213
    pnode_name = self.pnode.name
7214

    
7215
    ht_kind = self.op.hypervisor
7216
    if ht_kind in constants.HTS_REQ_PORT:
7217
      network_port = self.cfg.AllocatePort()
7218
    else:
7219
      network_port = None
7220

    
7221
    if constants.ENABLE_FILE_STORAGE:
7222
      # this is needed because os.path.join does not accept None arguments
7223
      if self.op.file_storage_dir is None:
7224
        string_file_storage_dir = ""
7225
      else:
7226
        string_file_storage_dir = self.op.file_storage_dir
7227

    
7228
      # build the full file storage dir path
7229
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7230
                                        string_file_storage_dir, instance)
7231
    else:
7232
      file_storage_dir = ""
7233

    
7234
    disks = _GenerateDiskTemplate(self,
7235
                                  self.op.disk_template,
7236
                                  instance, pnode_name,
7237
                                  self.secondaries,
7238
                                  self.disks,
7239
                                  file_storage_dir,
7240
                                  self.op.file_driver,
7241
                                  0)
7242

    
7243
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7244
                            primary_node=pnode_name,
7245
                            nics=self.nics, disks=disks,
7246
                            disk_template=self.op.disk_template,
7247
                            admin_up=False,
7248
                            network_port=network_port,
7249
                            beparams=self.op.beparams,
7250
                            hvparams=self.op.hvparams,
7251
                            hypervisor=self.op.hypervisor,
7252
                            osparams=self.op.osparams,
7253
                            )
7254

    
7255
    if self.adopt_disks:
7256
      # rename LVs to the newly-generated names; we need to construct
7257
      # 'fake' LV disks with the old data, plus the new unique_id
7258
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7259
      rename_to = []
7260
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7261
        rename_to.append(t_dsk.logical_id)
7262
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7263
        self.cfg.SetDiskID(t_dsk, pnode_name)
7264
      result = self.rpc.call_blockdev_rename(pnode_name,
7265
                                             zip(tmp_disks, rename_to))
7266
      result.Raise("Failed to rename adoped LVs")
7267
    else:
7268
      feedback_fn("* creating instance disks...")
7269
      try:
7270
        _CreateDisks(self, iobj)
7271
      except errors.OpExecError:
7272
        self.LogWarning("Device creation failed, reverting...")
7273
        try:
7274
          _RemoveDisks(self, iobj)
7275
        finally:
7276
          self.cfg.ReleaseDRBDMinors(instance)
7277
          raise
7278

    
7279
    feedback_fn("adding instance %s to cluster config" % instance)
7280

    
7281
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7282

    
7283
    # Declare that we don't want to remove the instance lock anymore, as we've
7284
    # added the instance to the config
7285
    del self.remove_locks[locking.LEVEL_INSTANCE]
7286
    # Unlock all the nodes
7287
    if self.op.mode == constants.INSTANCE_IMPORT:
7288
      nodes_keep = [self.op.src_node]
7289
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7290
                       if node != self.op.src_node]
7291
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7292
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7293
    else:
7294
      self.context.glm.release(locking.LEVEL_NODE)
7295
      del self.acquired_locks[locking.LEVEL_NODE]
7296

    
7297
    if self.op.wait_for_sync:
7298
      disk_abort = not _WaitForSync(self, iobj)
7299
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7300
      # make sure the disks are not degraded (still sync-ing is ok)
7301
      time.sleep(15)
7302
      feedback_fn("* checking mirrors status")
7303
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7304
    else:
7305
      disk_abort = False
7306

    
7307
    if disk_abort:
7308
      _RemoveDisks(self, iobj)
7309
      self.cfg.RemoveInstance(iobj.name)
7310
      # Make sure the instance lock gets removed
7311
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7312
      raise errors.OpExecError("There are some degraded disks for"
7313
                               " this instance")
7314

    
7315
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7316
      if self.op.mode == constants.INSTANCE_CREATE:
7317
        if not self.op.no_install:
7318
          feedback_fn("* running the instance OS create scripts...")
7319
          # FIXME: pass debug option from opcode to backend
7320
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7321
                                                 self.op.debug_level)
7322
          result.Raise("Could not add os for instance %s"
7323
                       " on node %s" % (instance, pnode_name))
7324

    
7325
      elif self.op.mode == constants.INSTANCE_IMPORT:
7326
        feedback_fn("* running the instance OS import scripts...")
7327

    
7328
        transfers = []
7329

    
7330
        for idx, image in enumerate(self.src_images):
7331
          if not image:
7332
            continue
7333

    
7334
          # FIXME: pass debug option from opcode to backend
7335
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7336
                                             constants.IEIO_FILE, (image, ),
7337
                                             constants.IEIO_SCRIPT,
7338
                                             (iobj.disks[idx], idx),
7339
                                             None)
7340
          transfers.append(dt)
7341

    
7342
        import_result = \
7343
          masterd.instance.TransferInstanceData(self, feedback_fn,
7344
                                                self.op.src_node, pnode_name,
7345
                                                self.pnode.secondary_ip,
7346
                                                iobj, transfers)
7347
        if not compat.all(import_result):
7348
          self.LogWarning("Some disks for instance %s on node %s were not"
7349
                          " imported successfully" % (instance, pnode_name))
7350

    
7351
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7352
        feedback_fn("* preparing remote import...")
7353
        connect_timeout = constants.RIE_CONNECT_TIMEOUT
7354
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7355

    
7356
        disk_results = masterd.instance.RemoteImport(self, feedback_fn, iobj,
7357
                                                     self.source_x509_ca,
7358
                                                     self._cds, timeouts)
7359
        if not compat.all(disk_results):
7360
          # TODO: Should the instance still be started, even if some disks
7361
          # failed to import (valid for local imports, too)?
7362
          self.LogWarning("Some disks for instance %s on node %s were not"
7363
                          " imported successfully" % (instance, pnode_name))
7364

    
7365
        # Run rename script on newly imported instance
7366
        assert iobj.name == instance
7367
        feedback_fn("Running rename script for %s" % instance)
7368
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7369
                                                   self.source_instance_name,
7370
                                                   self.op.debug_level)
7371
        if result.fail_msg:
7372
          self.LogWarning("Failed to run rename script for %s on node"
7373
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7374

    
7375
      else:
7376
        # also checked in the prereq part
7377
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7378
                                     % self.op.mode)
7379

    
7380
    if self.op.start:
7381
      iobj.admin_up = True
7382
      self.cfg.Update(iobj, feedback_fn)
7383
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7384
      feedback_fn("* starting instance...")
7385
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7386
      result.Raise("Could not start instance")
7387

    
7388
    return list(iobj.all_nodes)
7389

    
7390

    
7391
class LUConnectConsole(NoHooksLU):
7392
  """Connect to an instance's console.
7393

7394
  This is somewhat special in that it returns the command line that
7395
  you need to run on the master node in order to connect to the
7396
  console.
7397

7398
  """
7399
  _OP_PARAMS = [
7400
    _PInstanceName
7401
    ]
7402
  REQ_BGL = False
7403

    
7404
  def ExpandNames(self):
7405
    self._ExpandAndLockInstance()
7406

    
7407
  def CheckPrereq(self):
7408
    """Check prerequisites.
7409

7410
    This checks that the instance is in the cluster.
7411

7412
    """
7413
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7414
    assert self.instance is not None, \
7415
      "Cannot retrieve locked instance %s" % self.op.instance_name
7416
    _CheckNodeOnline(self, self.instance.primary_node)
7417

    
7418
  def Exec(self, feedback_fn):
7419
    """Connect to the console of an instance
7420

7421
    """
7422
    instance = self.instance
7423
    node = instance.primary_node
7424

    
7425
    node_insts = self.rpc.call_instance_list([node],
7426
                                             [instance.hypervisor])[node]
7427
    node_insts.Raise("Can't get node information from %s" % node)
7428

    
7429
    if instance.name not in node_insts.payload:
7430
      raise errors.OpExecError("Instance %s is not running." % instance.name)
7431

    
7432
    logging.debug("Connecting to console of %s on %s", instance.name, node)
7433

    
7434
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
7435
    cluster = self.cfg.GetClusterInfo()
7436
    # beparams and hvparams are passed separately, to avoid editing the
7437
    # instance and then saving the defaults in the instance itself.
7438
    hvparams = cluster.FillHV(instance)
7439
    beparams = cluster.FillBE(instance)
7440
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
7441

    
7442
    # build ssh cmdline
7443
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
7444

    
7445

    
7446
class LUReplaceDisks(LogicalUnit):
7447
  """Replace the disks of an instance.
7448

7449
  """
7450
  HPATH = "mirrors-replace"
7451
  HTYPE = constants.HTYPE_INSTANCE
7452
  _OP_PARAMS = [
7453
    _PInstanceName,
7454
    ("mode", _NoDefault, _TElemOf(constants.REPLACE_MODES)),
7455
    ("disks", _EmptyList, _TListOf(_TPositiveInt)),
7456
    ("remote_node", None, _TMaybeString),
7457
    ("iallocator", None, _TMaybeString),
7458
    ("early_release", False, _TBool),
7459
    ]
7460
  REQ_BGL = False
7461

    
7462
  def CheckArguments(self):
7463
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7464
                                  self.op.iallocator)
7465

    
7466
  def ExpandNames(self):
7467
    self._ExpandAndLockInstance()
7468

    
7469
    if self.op.iallocator is not None:
7470
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7471

    
7472
    elif self.op.remote_node is not None:
7473
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7474
      self.op.remote_node = remote_node
7475

    
7476
      # Warning: do not remove the locking of the new secondary here
7477
      # unless DRBD8.AddChildren is changed to work in parallel;
7478
      # currently it doesn't since parallel invocations of
7479
      # FindUnusedMinor will conflict
7480
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7481
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7482

    
7483
    else:
7484
      self.needed_locks[locking.LEVEL_NODE] = []
7485
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7486

    
7487
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7488
                                   self.op.iallocator, self.op.remote_node,
7489
                                   self.op.disks, False, self.op.early_release)
7490

    
7491
    self.tasklets = [self.replacer]
7492

    
7493
  def DeclareLocks(self, level):
7494
    # If we're not already locking all nodes in the set we have to declare the
7495
    # instance's primary/secondary nodes.
7496
    if (level == locking.LEVEL_NODE and
7497
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7498
      self._LockInstancesNodes()
7499

    
7500
  def BuildHooksEnv(self):
7501
    """Build hooks env.
7502

7503
    This runs on the master, the primary and all the secondaries.
7504

7505
    """
7506
    instance = self.replacer.instance
7507
    env = {
7508
      "MODE": self.op.mode,
7509
      "NEW_SECONDARY": self.op.remote_node,
7510
      "OLD_SECONDARY": instance.secondary_nodes[0],
7511
      }
7512
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7513
    nl = [
7514
      self.cfg.GetMasterNode(),
7515
      instance.primary_node,
7516
      ]
7517
    if self.op.remote_node is not None:
7518
      nl.append(self.op.remote_node)
7519
    return env, nl, nl
7520

    
7521

    
7522
class TLReplaceDisks(Tasklet):
7523
  """Replaces disks for an instance.
7524

7525
  Note: Locking is not within the scope of this class.
7526

7527
  """
7528
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7529
               disks, delay_iallocator, early_release):
7530
    """Initializes this class.
7531

7532
    """
7533
    Tasklet.__init__(self, lu)
7534

    
7535
    # Parameters
7536
    self.instance_name = instance_name
7537
    self.mode = mode
7538
    self.iallocator_name = iallocator_name
7539
    self.remote_node = remote_node
7540
    self.disks = disks
7541
    self.delay_iallocator = delay_iallocator
7542
    self.early_release = early_release
7543

    
7544
    # Runtime data
7545
    self.instance = None
7546
    self.new_node = None
7547
    self.target_node = None
7548
    self.other_node = None
7549
    self.remote_node_info = None
7550
    self.node_secondary_ip = None
7551

    
7552
  @staticmethod
7553
  def CheckArguments(mode, remote_node, iallocator):
7554
    """Helper function for users of this class.
7555

7556
    """
7557
    # check for valid parameter combination
7558
    if mode == constants.REPLACE_DISK_CHG:
7559
      if remote_node is None and iallocator is None:
7560
        raise errors.OpPrereqError("When changing the secondary either an"
7561
                                   " iallocator script must be used or the"
7562
                                   " new node given", errors.ECODE_INVAL)
7563

    
7564
      if remote_node is not None and iallocator is not None:
7565
        raise errors.OpPrereqError("Give either the iallocator or the new"
7566
                                   " secondary, not both", errors.ECODE_INVAL)
7567

    
7568
    elif remote_node is not None or iallocator is not None:
7569
      # Not replacing the secondary
7570
      raise errors.OpPrereqError("The iallocator and new node options can"
7571
                                 " only be used when changing the"
7572
                                 " secondary node", errors.ECODE_INVAL)
7573

    
7574
  @staticmethod
7575
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7576
    """Compute a new secondary node using an IAllocator.
7577

7578
    """
7579
    ial = IAllocator(lu.cfg, lu.rpc,
7580
                     mode=constants.IALLOCATOR_MODE_RELOC,
7581
                     name=instance_name,
7582
                     relocate_from=relocate_from)
7583

    
7584
    ial.Run(iallocator_name)
7585

    
7586
    if not ial.success:
7587
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7588
                                 " %s" % (iallocator_name, ial.info),
7589
                                 errors.ECODE_NORES)
7590

    
7591
    if len(ial.result) != ial.required_nodes:
7592
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7593
                                 " of nodes (%s), required %s" %
7594
                                 (iallocator_name,
7595
                                  len(ial.result), ial.required_nodes),
7596
                                 errors.ECODE_FAULT)
7597

    
7598
    remote_node_name = ial.result[0]
7599

    
7600
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7601
               instance_name, remote_node_name)
7602

    
7603
    return remote_node_name
7604

    
7605
  def _FindFaultyDisks(self, node_name):
7606
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7607
                                    node_name, True)
7608

    
7609
  def CheckPrereq(self):
7610
    """Check prerequisites.
7611

7612
    This checks that the instance is in the cluster.
7613

7614
    """
7615
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7616
    assert instance is not None, \
7617
      "Cannot retrieve locked instance %s" % self.instance_name
7618

    
7619
    if instance.disk_template != constants.DT_DRBD8:
7620
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7621
                                 " instances", errors.ECODE_INVAL)
7622

    
7623
    if len(instance.secondary_nodes) != 1:
7624
      raise errors.OpPrereqError("The instance has a strange layout,"
7625
                                 " expected one secondary but found %d" %
7626
                                 len(instance.secondary_nodes),
7627
                                 errors.ECODE_FAULT)
7628

    
7629
    if not self.delay_iallocator:
7630
      self._CheckPrereq2()
7631

    
7632
  def _CheckPrereq2(self):
7633
    """Check prerequisites, second part.
7634

7635
    This function should always be part of CheckPrereq. It was separated and is
7636
    now called from Exec because during node evacuation iallocator was only
7637
    called with an unmodified cluster model, not taking planned changes into
7638
    account.
7639

7640
    """
7641
    instance = self.instance
7642
    secondary_node = instance.secondary_nodes[0]
7643

    
7644
    if self.iallocator_name is None:
7645
      remote_node = self.remote_node
7646
    else:
7647
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
7648
                                       instance.name, instance.secondary_nodes)
7649

    
7650
    if remote_node is not None:
7651
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
7652
      assert self.remote_node_info is not None, \
7653
        "Cannot retrieve locked node %s" % remote_node
7654
    else:
7655
      self.remote_node_info = None
7656

    
7657
    if remote_node == self.instance.primary_node:
7658
      raise errors.OpPrereqError("The specified node is the primary node of"
7659
                                 " the instance.", errors.ECODE_INVAL)
7660

    
7661
    if remote_node == secondary_node:
7662
      raise errors.OpPrereqError("The specified node is already the"
7663
                                 " secondary node of the instance.",
7664
                                 errors.ECODE_INVAL)
7665

    
7666
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
7667
                                    constants.REPLACE_DISK_CHG):
7668
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
7669
                                 errors.ECODE_INVAL)
7670

    
7671
    if self.mode == constants.REPLACE_DISK_AUTO:
7672
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
7673
      faulty_secondary = self._FindFaultyDisks(secondary_node)
7674

    
7675
      if faulty_primary and faulty_secondary:
7676
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
7677
                                   " one node and can not be repaired"
7678
                                   " automatically" % self.instance_name,
7679
                                   errors.ECODE_STATE)
7680

    
7681
      if faulty_primary:
7682
        self.disks = faulty_primary
7683
        self.target_node = instance.primary_node
7684
        self.other_node = secondary_node
7685
        check_nodes = [self.target_node, self.other_node]
7686
      elif faulty_secondary:
7687
        self.disks = faulty_secondary
7688
        self.target_node = secondary_node
7689
        self.other_node = instance.primary_node
7690
        check_nodes = [self.target_node, self.other_node]
7691
      else:
7692
        self.disks = []
7693
        check_nodes = []
7694

    
7695
    else:
7696
      # Non-automatic modes
7697
      if self.mode == constants.REPLACE_DISK_PRI:
7698
        self.target_node = instance.primary_node
7699
        self.other_node = secondary_node
7700
        check_nodes = [self.target_node, self.other_node]
7701

    
7702
      elif self.mode == constants.REPLACE_DISK_SEC:
7703
        self.target_node = secondary_node
7704
        self.other_node = instance.primary_node
7705
        check_nodes = [self.target_node, self.other_node]
7706

    
7707
      elif self.mode == constants.REPLACE_DISK_CHG:
7708
        self.new_node = remote_node
7709
        self.other_node = instance.primary_node
7710
        self.target_node = secondary_node
7711
        check_nodes = [self.new_node, self.other_node]
7712

    
7713
        _CheckNodeNotDrained(self.lu, remote_node)
7714

    
7715
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
7716
        assert old_node_info is not None
7717
        if old_node_info.offline and not self.early_release:
7718
          # doesn't make sense to delay the release
7719
          self.early_release = True
7720
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
7721
                          " early-release mode", secondary_node)
7722

    
7723
      else:
7724
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
7725
                                     self.mode)
7726

    
7727
      # If not specified all disks should be replaced
7728
      if not self.disks:
7729
        self.disks = range(len(self.instance.disks))
7730

    
7731
    for node in check_nodes:
7732
      _CheckNodeOnline(self.lu, node)
7733

    
7734
    # Check whether disks are valid
7735
    for disk_idx in self.disks:
7736
      instance.FindDisk(disk_idx)
7737

    
7738
    # Get secondary node IP addresses
7739
    node_2nd_ip = {}
7740

    
7741
    for node_name in [self.target_node, self.other_node, self.new_node]:
7742
      if node_name is not None:
7743
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
7744

    
7745
    self.node_secondary_ip = node_2nd_ip
7746

    
7747
  def Exec(self, feedback_fn):
7748
    """Execute disk replacement.
7749

7750
    This dispatches the disk replacement to the appropriate handler.
7751

7752
    """
7753
    if self.delay_iallocator:
7754
      self._CheckPrereq2()
7755

    
7756
    if not self.disks:
7757
      feedback_fn("No disks need replacement")
7758
      return
7759

    
7760
    feedback_fn("Replacing disk(s) %s for %s" %
7761
                (utils.CommaJoin(self.disks), self.instance.name))
7762

    
7763
    activate_disks = (not self.instance.admin_up)
7764

    
7765
    # Activate the instance disks if we're replacing them on a down instance
7766
    if activate_disks:
7767
      _StartInstanceDisks(self.lu, self.instance, True)
7768

    
7769
    try:
7770
      # Should we replace the secondary node?
7771
      if self.new_node is not None:
7772
        fn = self._ExecDrbd8Secondary
7773
      else:
7774
        fn = self._ExecDrbd8DiskOnly
7775

    
7776
      return fn(feedback_fn)
7777

    
7778
    finally:
7779
      # Deactivate the instance disks if we're replacing them on a
7780
      # down instance
7781
      if activate_disks:
7782
        _SafeShutdownInstanceDisks(self.lu, self.instance)
7783

    
7784
  def _CheckVolumeGroup(self, nodes):
7785
    self.lu.LogInfo("Checking volume groups")
7786

    
7787
    vgname = self.cfg.GetVGName()
7788

    
7789
    # Make sure volume group exists on all involved nodes
7790
    results = self.rpc.call_vg_list(nodes)
7791
    if not results:
7792
      raise errors.OpExecError("Can't list volume groups on the nodes")
7793

    
7794
    for node in nodes:
7795
      res = results[node]
7796
      res.Raise("Error checking node %s" % node)
7797
      if vgname not in res.payload:
7798
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
7799
                                 (vgname, node))
7800

    
7801
  def _CheckDisksExistence(self, nodes):
7802
    # Check disk existence
7803
    for idx, dev in enumerate(self.instance.disks):
7804
      if idx not in self.disks:
7805
        continue
7806

    
7807
      for node in nodes:
7808
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
7809
        self.cfg.SetDiskID(dev, node)
7810

    
7811
        result = self.rpc.call_blockdev_find(node, dev)
7812

    
7813
        msg = result.fail_msg
7814
        if msg or not result.payload:
7815
          if not msg:
7816
            msg = "disk not found"
7817
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
7818
                                   (idx, node, msg))
7819

    
7820
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
7821
    for idx, dev in enumerate(self.instance.disks):
7822
      if idx not in self.disks:
7823
        continue
7824

    
7825
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
7826
                      (idx, node_name))
7827

    
7828
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
7829
                                   ldisk=ldisk):
7830
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
7831
                                 " replace disks for instance %s" %
7832
                                 (node_name, self.instance.name))
7833

    
7834
  def _CreateNewStorage(self, node_name):
7835
    vgname = self.cfg.GetVGName()
7836
    iv_names = {}
7837

    
7838
    for idx, dev in enumerate(self.instance.disks):
7839
      if idx not in self.disks:
7840
        continue
7841

    
7842
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
7843

    
7844
      self.cfg.SetDiskID(dev, node_name)
7845

    
7846
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
7847
      names = _GenerateUniqueNames(self.lu, lv_names)
7848

    
7849
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
7850
                             logical_id=(vgname, names[0]))
7851
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7852
                             logical_id=(vgname, names[1]))
7853

    
7854
      new_lvs = [lv_data, lv_meta]
7855
      old_lvs = dev.children
7856
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
7857

    
7858
      # we pass force_create=True to force the LVM creation
7859
      for new_lv in new_lvs:
7860
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
7861
                        _GetInstanceInfoText(self.instance), False)
7862

    
7863
    return iv_names
7864

    
7865
  def _CheckDevices(self, node_name, iv_names):
7866
    for name, (dev, _, _) in iv_names.iteritems():
7867
      self.cfg.SetDiskID(dev, node_name)
7868

    
7869
      result = self.rpc.call_blockdev_find(node_name, dev)
7870

    
7871
      msg = result.fail_msg
7872
      if msg or not result.payload:
7873
        if not msg:
7874
          msg = "disk not found"
7875
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
7876
                                 (name, msg))
7877

    
7878
      if result.payload.is_degraded:
7879
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
7880

    
7881
  def _RemoveOldStorage(self, node_name, iv_names):
7882
    for name, (_, old_lvs, _) in iv_names.iteritems():
7883
      self.lu.LogInfo("Remove logical volumes for %s" % name)
7884

    
7885
      for lv in old_lvs:
7886
        self.cfg.SetDiskID(lv, node_name)
7887

    
7888
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
7889
        if msg:
7890
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
7891
                             hint="remove unused LVs manually")
7892

    
7893
  def _ReleaseNodeLock(self, node_name):
7894
    """Releases the lock for a given node."""
7895
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
7896

    
7897
  def _ExecDrbd8DiskOnly(self, feedback_fn):
7898
    """Replace a disk on the primary or secondary for DRBD 8.
7899

7900
    The algorithm for replace is quite complicated:
7901

7902
      1. for each disk to be replaced:
7903

7904
        1. create new LVs on the target node with unique names
7905
        1. detach old LVs from the drbd device
7906
        1. rename old LVs to name_replaced.<time_t>
7907
        1. rename new LVs to old LVs
7908
        1. attach the new LVs (with the old names now) to the drbd device
7909

7910
      1. wait for sync across all devices
7911

7912
      1. for each modified disk:
7913

7914
        1. remove old LVs (which have the name name_replaces.<time_t>)
7915

7916
    Failures are not very well handled.
7917

7918
    """
7919
    steps_total = 6
7920

    
7921
    # Step: check device activation
7922
    self.lu.LogStep(1, steps_total, "Check device existence")
7923
    self._CheckDisksExistence([self.other_node, self.target_node])
7924
    self._CheckVolumeGroup([self.target_node, self.other_node])
7925

    
7926
    # Step: check other node consistency
7927
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7928
    self._CheckDisksConsistency(self.other_node,
7929
                                self.other_node == self.instance.primary_node,
7930
                                False)
7931

    
7932
    # Step: create new storage
7933
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7934
    iv_names = self._CreateNewStorage(self.target_node)
7935

    
7936
    # Step: for each lv, detach+rename*2+attach
7937
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7938
    for dev, old_lvs, new_lvs in iv_names.itervalues():
7939
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
7940

    
7941
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
7942
                                                     old_lvs)
7943
      result.Raise("Can't detach drbd from local storage on node"
7944
                   " %s for device %s" % (self.target_node, dev.iv_name))
7945
      #dev.children = []
7946
      #cfg.Update(instance)
7947

    
7948
      # ok, we created the new LVs, so now we know we have the needed
7949
      # storage; as such, we proceed on the target node to rename
7950
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
7951
      # using the assumption that logical_id == physical_id (which in
7952
      # turn is the unique_id on that node)
7953

    
7954
      # FIXME(iustin): use a better name for the replaced LVs
7955
      temp_suffix = int(time.time())
7956
      ren_fn = lambda d, suff: (d.physical_id[0],
7957
                                d.physical_id[1] + "_replaced-%s" % suff)
7958

    
7959
      # Build the rename list based on what LVs exist on the node
7960
      rename_old_to_new = []
7961
      for to_ren in old_lvs:
7962
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
7963
        if not result.fail_msg and result.payload:
7964
          # device exists
7965
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
7966

    
7967
      self.lu.LogInfo("Renaming the old LVs on the target node")
7968
      result = self.rpc.call_blockdev_rename(self.target_node,
7969
                                             rename_old_to_new)
7970
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
7971

    
7972
      # Now we rename the new LVs to the old LVs
7973
      self.lu.LogInfo("Renaming the new LVs on the target node")
7974
      rename_new_to_old = [(new, old.physical_id)
7975
                           for old, new in zip(old_lvs, new_lvs)]
7976
      result = self.rpc.call_blockdev_rename(self.target_node,
7977
                                             rename_new_to_old)
7978
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
7979

    
7980
      for old, new in zip(old_lvs, new_lvs):
7981
        new.logical_id = old.logical_id
7982
        self.cfg.SetDiskID(new, self.target_node)
7983

    
7984
      for disk in old_lvs:
7985
        disk.logical_id = ren_fn(disk, temp_suffix)
7986
        self.cfg.SetDiskID(disk, self.target_node)
7987

    
7988
      # Now that the new lvs have the old name, we can add them to the device
7989
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
7990
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
7991
                                                  new_lvs)
7992
      msg = result.fail_msg
7993
      if msg:
7994
        for new_lv in new_lvs:
7995
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
7996
                                               new_lv).fail_msg
7997
          if msg2:
7998
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
7999
                               hint=("cleanup manually the unused logical"
8000
                                     "volumes"))
8001
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8002

    
8003
      dev.children = new_lvs
8004

    
8005
      self.cfg.Update(self.instance, feedback_fn)
8006

    
8007
    cstep = 5
8008
    if self.early_release:
8009
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8010
      cstep += 1
8011
      self._RemoveOldStorage(self.target_node, iv_names)
8012
      # WARNING: we release both node locks here, do not do other RPCs
8013
      # than WaitForSync to the primary node
8014
      self._ReleaseNodeLock([self.target_node, self.other_node])
8015

    
8016
    # Wait for sync
8017
    # This can fail as the old devices are degraded and _WaitForSync
8018
    # does a combined result over all disks, so we don't check its return value
8019
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8020
    cstep += 1
8021
    _WaitForSync(self.lu, self.instance)
8022

    
8023
    # Check all devices manually
8024
    self._CheckDevices(self.instance.primary_node, iv_names)
8025

    
8026
    # Step: remove old storage
8027
    if not self.early_release:
8028
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8029
      cstep += 1
8030
      self._RemoveOldStorage(self.target_node, iv_names)
8031

    
8032
  def _ExecDrbd8Secondary(self, feedback_fn):
8033
    """Replace the secondary node for DRBD 8.
8034

8035
    The algorithm for replace is quite complicated:
8036
      - for all disks of the instance:
8037
        - create new LVs on the new node with same names
8038
        - shutdown the drbd device on the old secondary
8039
        - disconnect the drbd network on the primary
8040
        - create the drbd device on the new secondary
8041
        - network attach the drbd on the primary, using an artifice:
8042
          the drbd code for Attach() will connect to the network if it
8043
          finds a device which is connected to the good local disks but
8044
          not network enabled
8045
      - wait for sync across all devices
8046
      - remove all disks from the old secondary
8047

8048
    Failures are not very well handled.
8049

8050
    """
8051
    steps_total = 6
8052

    
8053
    # Step: check device activation
8054
    self.lu.LogStep(1, steps_total, "Check device existence")
8055
    self._CheckDisksExistence([self.instance.primary_node])
8056
    self._CheckVolumeGroup([self.instance.primary_node])
8057

    
8058
    # Step: check other node consistency
8059
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8060
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8061

    
8062
    # Step: create new storage
8063
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8064
    for idx, dev in enumerate(self.instance.disks):
8065
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8066
                      (self.new_node, idx))
8067
      # we pass force_create=True to force LVM creation
8068
      for new_lv in dev.children:
8069
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8070
                        _GetInstanceInfoText(self.instance), False)
8071

    
8072
    # Step 4: dbrd minors and drbd setups changes
8073
    # after this, we must manually remove the drbd minors on both the
8074
    # error and the success paths
8075
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8076
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8077
                                         for dev in self.instance.disks],
8078
                                        self.instance.name)
8079
    logging.debug("Allocated minors %r", minors)
8080

    
8081
    iv_names = {}
8082
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8083
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8084
                      (self.new_node, idx))
8085
      # create new devices on new_node; note that we create two IDs:
8086
      # one without port, so the drbd will be activated without
8087
      # networking information on the new node at this stage, and one
8088
      # with network, for the latter activation in step 4
8089
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8090
      if self.instance.primary_node == o_node1:
8091
        p_minor = o_minor1
8092
      else:
8093
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8094
        p_minor = o_minor2
8095

    
8096
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8097
                      p_minor, new_minor, o_secret)
8098
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8099
                    p_minor, new_minor, o_secret)
8100

    
8101
      iv_names[idx] = (dev, dev.children, new_net_id)
8102
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8103
                    new_net_id)
8104
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8105
                              logical_id=new_alone_id,
8106
                              children=dev.children,
8107
                              size=dev.size)
8108
      try:
8109
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8110
                              _GetInstanceInfoText(self.instance), False)
8111
      except errors.GenericError:
8112
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8113
        raise
8114

    
8115
    # We have new devices, shutdown the drbd on the old secondary
8116
    for idx, dev in enumerate(self.instance.disks):
8117
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8118
      self.cfg.SetDiskID(dev, self.target_node)
8119
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8120
      if msg:
8121
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8122
                           "node: %s" % (idx, msg),
8123
                           hint=("Please cleanup this device manually as"
8124
                                 " soon as possible"))
8125

    
8126
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8127
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8128
                                               self.node_secondary_ip,
8129
                                               self.instance.disks)\
8130
                                              [self.instance.primary_node]
8131

    
8132
    msg = result.fail_msg
8133
    if msg:
8134
      # detaches didn't succeed (unlikely)
8135
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8136
      raise errors.OpExecError("Can't detach the disks from the network on"
8137
                               " old node: %s" % (msg,))
8138

    
8139
    # if we managed to detach at least one, we update all the disks of
8140
    # the instance to point to the new secondary
8141
    self.lu.LogInfo("Updating instance configuration")
8142
    for dev, _, new_logical_id in iv_names.itervalues():
8143
      dev.logical_id = new_logical_id
8144
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8145

    
8146
    self.cfg.Update(self.instance, feedback_fn)
8147

    
8148
    # and now perform the drbd attach
8149
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8150
                    " (standalone => connected)")
8151
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8152
                                            self.new_node],
8153
                                           self.node_secondary_ip,
8154
                                           self.instance.disks,
8155
                                           self.instance.name,
8156
                                           False)
8157
    for to_node, to_result in result.items():
8158
      msg = to_result.fail_msg
8159
      if msg:
8160
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8161
                           to_node, msg,
8162
                           hint=("please do a gnt-instance info to see the"
8163
                                 " status of disks"))
8164
    cstep = 5
8165
    if self.early_release:
8166
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8167
      cstep += 1
8168
      self._RemoveOldStorage(self.target_node, iv_names)
8169
      # WARNING: we release all node locks here, do not do other RPCs
8170
      # than WaitForSync to the primary node
8171
      self._ReleaseNodeLock([self.instance.primary_node,
8172
                             self.target_node,
8173
                             self.new_node])
8174

    
8175
    # Wait for sync
8176
    # This can fail as the old devices are degraded and _WaitForSync
8177
    # does a combined result over all disks, so we don't check its return value
8178
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8179
    cstep += 1
8180
    _WaitForSync(self.lu, self.instance)
8181

    
8182
    # Check all devices manually
8183
    self._CheckDevices(self.instance.primary_node, iv_names)
8184

    
8185
    # Step: remove old storage
8186
    if not self.early_release:
8187
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8188
      self._RemoveOldStorage(self.target_node, iv_names)
8189

    
8190

    
8191
class LURepairNodeStorage(NoHooksLU):
8192
  """Repairs the volume group on a node.
8193

8194
  """
8195
  _OP_PARAMS = [
8196
    _PNodeName,
8197
    ("storage_type", _NoDefault, _CheckStorageType),
8198
    ("name", _NoDefault, _TNonEmptyString),
8199
    ("ignore_consistency", False, _TBool),
8200
    ]
8201
  REQ_BGL = False
8202

    
8203
  def CheckArguments(self):
8204
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8205

    
8206
    storage_type = self.op.storage_type
8207

    
8208
    if (constants.SO_FIX_CONSISTENCY not in
8209
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8210
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8211
                                 " repaired" % storage_type,
8212
                                 errors.ECODE_INVAL)
8213

    
8214
  def ExpandNames(self):
8215
    self.needed_locks = {
8216
      locking.LEVEL_NODE: [self.op.node_name],
8217
      }
8218

    
8219
  def _CheckFaultyDisks(self, instance, node_name):
8220
    """Ensure faulty disks abort the opcode or at least warn."""
8221
    try:
8222
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8223
                                  node_name, True):
8224
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8225
                                   " node '%s'" % (instance.name, node_name),
8226
                                   errors.ECODE_STATE)
8227
    except errors.OpPrereqError, err:
8228
      if self.op.ignore_consistency:
8229
        self.proc.LogWarning(str(err.args[0]))
8230
      else:
8231
        raise
8232

    
8233
  def CheckPrereq(self):
8234
    """Check prerequisites.
8235

8236
    """
8237
    # Check whether any instance on this node has faulty disks
8238
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8239
      if not inst.admin_up:
8240
        continue
8241
      check_nodes = set(inst.all_nodes)
8242
      check_nodes.discard(self.op.node_name)
8243
      for inst_node_name in check_nodes:
8244
        self._CheckFaultyDisks(inst, inst_node_name)
8245

    
8246
  def Exec(self, feedback_fn):
8247
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8248
                (self.op.name, self.op.node_name))
8249

    
8250
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8251
    result = self.rpc.call_storage_execute(self.op.node_name,
8252
                                           self.op.storage_type, st_args,
8253
                                           self.op.name,
8254
                                           constants.SO_FIX_CONSISTENCY)
8255
    result.Raise("Failed to repair storage unit '%s' on %s" %
8256
                 (self.op.name, self.op.node_name))
8257

    
8258

    
8259
class LUNodeEvacuationStrategy(NoHooksLU):
8260
  """Computes the node evacuation strategy.
8261

8262
  """
8263
  _OP_PARAMS = [
8264
    ("nodes", _NoDefault, _TListOf(_TNonEmptyString)),
8265
    ("remote_node", None, _TMaybeString),
8266
    ("iallocator", None, _TMaybeString),
8267
    ]
8268
  REQ_BGL = False
8269

    
8270
  def CheckArguments(self):
8271
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8272

    
8273
  def ExpandNames(self):
8274
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8275
    self.needed_locks = locks = {}
8276
    if self.op.remote_node is None:
8277
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8278
    else:
8279
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8280
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8281

    
8282
  def Exec(self, feedback_fn):
8283
    if self.op.remote_node is not None:
8284
      instances = []
8285
      for node in self.op.nodes:
8286
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8287
      result = []
8288
      for i in instances:
8289
        if i.primary_node == self.op.remote_node:
8290
          raise errors.OpPrereqError("Node %s is the primary node of"
8291
                                     " instance %s, cannot use it as"
8292
                                     " secondary" %
8293
                                     (self.op.remote_node, i.name),
8294
                                     errors.ECODE_INVAL)
8295
        result.append([i.name, self.op.remote_node])
8296
    else:
8297
      ial = IAllocator(self.cfg, self.rpc,
8298
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8299
                       evac_nodes=self.op.nodes)
8300
      ial.Run(self.op.iallocator, validate=True)
8301
      if not ial.success:
8302
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8303
                                 errors.ECODE_NORES)
8304
      result = ial.result
8305
    return result
8306

    
8307

    
8308
class LUGrowDisk(LogicalUnit):
8309
  """Grow a disk of an instance.
8310

8311
  """
8312
  HPATH = "disk-grow"
8313
  HTYPE = constants.HTYPE_INSTANCE
8314
  _OP_PARAMS = [
8315
    _PInstanceName,
8316
    ("disk", _NoDefault, _TInt),
8317
    ("amount", _NoDefault, _TInt),
8318
    ("wait_for_sync", True, _TBool),
8319
    ]
8320
  REQ_BGL = False
8321

    
8322
  def ExpandNames(self):
8323
    self._ExpandAndLockInstance()
8324
    self.needed_locks[locking.LEVEL_NODE] = []
8325
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8326

    
8327
  def DeclareLocks(self, level):
8328
    if level == locking.LEVEL_NODE:
8329
      self._LockInstancesNodes()
8330

    
8331
  def BuildHooksEnv(self):
8332
    """Build hooks env.
8333

8334
    This runs on the master, the primary and all the secondaries.
8335

8336
    """
8337
    env = {
8338
      "DISK": self.op.disk,
8339
      "AMOUNT": self.op.amount,
8340
      }
8341
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8342
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8343
    return env, nl, nl
8344

    
8345
  def CheckPrereq(self):
8346
    """Check prerequisites.
8347

8348
    This checks that the instance is in the cluster.
8349

8350
    """
8351
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8352
    assert instance is not None, \
8353
      "Cannot retrieve locked instance %s" % self.op.instance_name
8354
    nodenames = list(instance.all_nodes)
8355
    for node in nodenames:
8356
      _CheckNodeOnline(self, node)
8357

    
8358
    self.instance = instance
8359

    
8360
    if instance.disk_template not in constants.DTS_GROWABLE:
8361
      raise errors.OpPrereqError("Instance's disk layout does not support"
8362
                                 " growing.", errors.ECODE_INVAL)
8363

    
8364
    self.disk = instance.FindDisk(self.op.disk)
8365

    
8366
    if instance.disk_template != constants.DT_FILE:
8367
      # TODO: check the free disk space for file, when that feature will be
8368
      # supported
8369
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
8370

    
8371
  def Exec(self, feedback_fn):
8372
    """Execute disk grow.
8373

8374
    """
8375
    instance = self.instance
8376
    disk = self.disk
8377

    
8378
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8379
    if not disks_ok:
8380
      raise errors.OpExecError("Cannot activate block device to grow")
8381

    
8382
    for node in instance.all_nodes:
8383
      self.cfg.SetDiskID(disk, node)
8384
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8385
      result.Raise("Grow request failed to node %s" % node)
8386

    
8387
      # TODO: Rewrite code to work properly
8388
      # DRBD goes into sync mode for a short amount of time after executing the
8389
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8390
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8391
      # time is a work-around.
8392
      time.sleep(5)
8393

    
8394
    disk.RecordGrow(self.op.amount)
8395
    self.cfg.Update(instance, feedback_fn)
8396
    if self.op.wait_for_sync:
8397
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8398
      if disk_abort:
8399
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8400
                             " status.\nPlease check the instance.")
8401
      if not instance.admin_up:
8402
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8403
    elif not instance.admin_up:
8404
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8405
                           " not supposed to be running because no wait for"
8406
                           " sync mode was requested.")
8407

    
8408

    
8409
class LUQueryInstanceData(NoHooksLU):
8410
  """Query runtime instance data.
8411

8412
  """
8413
  _OP_PARAMS = [
8414
    ("instances", _EmptyList, _TListOf(_TNonEmptyString)),
8415
    ("static", False, _TBool),
8416
    ]
8417
  REQ_BGL = False
8418

    
8419
  def ExpandNames(self):
8420
    self.needed_locks = {}
8421
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8422

    
8423
    if self.op.instances:
8424
      self.wanted_names = []
8425
      for name in self.op.instances:
8426
        full_name = _ExpandInstanceName(self.cfg, name)
8427
        self.wanted_names.append(full_name)
8428
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8429
    else:
8430
      self.wanted_names = None
8431
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8432

    
8433
    self.needed_locks[locking.LEVEL_NODE] = []
8434
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8435

    
8436
  def DeclareLocks(self, level):
8437
    if level == locking.LEVEL_NODE:
8438
      self._LockInstancesNodes()
8439

    
8440
  def CheckPrereq(self):
8441
    """Check prerequisites.
8442

8443
    This only checks the optional instance list against the existing names.
8444

8445
    """
8446
    if self.wanted_names is None:
8447
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8448

    
8449
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8450
                             in self.wanted_names]
8451

    
8452
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8453
    """Returns the status of a block device
8454

8455
    """
8456
    if self.op.static or not node:
8457
      return None
8458

    
8459
    self.cfg.SetDiskID(dev, node)
8460

    
8461
    result = self.rpc.call_blockdev_find(node, dev)
8462
    if result.offline:
8463
      return None
8464

    
8465
    result.Raise("Can't compute disk status for %s" % instance_name)
8466

    
8467
    status = result.payload
8468
    if status is None:
8469
      return None
8470

    
8471
    return (status.dev_path, status.major, status.minor,
8472
            status.sync_percent, status.estimated_time,
8473
            status.is_degraded, status.ldisk_status)
8474

    
8475
  def _ComputeDiskStatus(self, instance, snode, dev):
8476
    """Compute block device status.
8477

8478
    """
8479
    if dev.dev_type in constants.LDS_DRBD:
8480
      # we change the snode then (otherwise we use the one passed in)
8481
      if dev.logical_id[0] == instance.primary_node:
8482
        snode = dev.logical_id[1]
8483
      else:
8484
        snode = dev.logical_id[0]
8485

    
8486
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8487
                                              instance.name, dev)
8488
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8489

    
8490
    if dev.children:
8491
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8492
                      for child in dev.children]
8493
    else:
8494
      dev_children = []
8495

    
8496
    data = {
8497
      "iv_name": dev.iv_name,
8498
      "dev_type": dev.dev_type,
8499
      "logical_id": dev.logical_id,
8500
      "physical_id": dev.physical_id,
8501
      "pstatus": dev_pstatus,
8502
      "sstatus": dev_sstatus,
8503
      "children": dev_children,
8504
      "mode": dev.mode,
8505
      "size": dev.size,
8506
      }
8507

    
8508
    return data
8509

    
8510
  def Exec(self, feedback_fn):
8511
    """Gather and return data"""
8512
    result = {}
8513

    
8514
    cluster = self.cfg.GetClusterInfo()
8515

    
8516
    for instance in self.wanted_instances:
8517
      if not self.op.static:
8518
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8519
                                                  instance.name,
8520
                                                  instance.hypervisor)
8521
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8522
        remote_info = remote_info.payload
8523
        if remote_info and "state" in remote_info:
8524
          remote_state = "up"
8525
        else:
8526
          remote_state = "down"
8527
      else:
8528
        remote_state = None
8529
      if instance.admin_up:
8530
        config_state = "up"
8531
      else:
8532
        config_state = "down"
8533

    
8534
      disks = [self._ComputeDiskStatus(instance, None, device)
8535
               for device in instance.disks]
8536

    
8537
      idict = {
8538
        "name": instance.name,
8539
        "config_state": config_state,
8540
        "run_state": remote_state,
8541
        "pnode": instance.primary_node,
8542
        "snodes": instance.secondary_nodes,
8543
        "os": instance.os,
8544
        # this happens to be the same format used for hooks
8545
        "nics": _NICListToTuple(self, instance.nics),
8546
        "disk_template": instance.disk_template,
8547
        "disks": disks,
8548
        "hypervisor": instance.hypervisor,
8549
        "network_port": instance.network_port,
8550
        "hv_instance": instance.hvparams,
8551
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8552
        "be_instance": instance.beparams,
8553
        "be_actual": cluster.FillBE(instance),
8554
        "os_instance": instance.osparams,
8555
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8556
        "serial_no": instance.serial_no,
8557
        "mtime": instance.mtime,
8558
        "ctime": instance.ctime,
8559
        "uuid": instance.uuid,
8560
        }
8561

    
8562
      result[instance.name] = idict
8563

    
8564
    return result
8565

    
8566

    
8567
class LUSetInstanceParams(LogicalUnit):
8568
  """Modifies an instances's parameters.
8569

8570
  """
8571
  HPATH = "instance-modify"
8572
  HTYPE = constants.HTYPE_INSTANCE
8573
  _OP_PARAMS = [
8574
    _PInstanceName,
8575
    ("nics", _EmptyList, _TList),
8576
    ("disks", _EmptyList, _TList),
8577
    ("beparams", _EmptyDict, _TDict),
8578
    ("hvparams", _EmptyDict, _TDict),
8579
    ("disk_template", None, _TMaybeString),
8580
    ("remote_node", None, _TMaybeString),
8581
    ("os_name", None, _TMaybeString),
8582
    ("force_variant", False, _TBool),
8583
    ("osparams", None, _TOr(_TDict, _TNone)),
8584
    _PForce,
8585
    ]
8586
  REQ_BGL = False
8587

    
8588
  def CheckArguments(self):
8589
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8590
            self.op.hvparams or self.op.beparams or self.op.os_name):
8591
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8592

    
8593
    if self.op.hvparams:
8594
      _CheckGlobalHvParams(self.op.hvparams)
8595

    
8596
    # Disk validation
8597
    disk_addremove = 0
8598
    for disk_op, disk_dict in self.op.disks:
8599
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8600
      if disk_op == constants.DDM_REMOVE:
8601
        disk_addremove += 1
8602
        continue
8603
      elif disk_op == constants.DDM_ADD:
8604
        disk_addremove += 1
8605
      else:
8606
        if not isinstance(disk_op, int):
8607
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8608
        if not isinstance(disk_dict, dict):
8609
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8610
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8611

    
8612
      if disk_op == constants.DDM_ADD:
8613
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8614
        if mode not in constants.DISK_ACCESS_SET:
8615
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8616
                                     errors.ECODE_INVAL)
8617
        size = disk_dict.get('size', None)
8618
        if size is None:
8619
          raise errors.OpPrereqError("Required disk parameter size missing",
8620
                                     errors.ECODE_INVAL)
8621
        try:
8622
          size = int(size)
8623
        except (TypeError, ValueError), err:
8624
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8625
                                     str(err), errors.ECODE_INVAL)
8626
        disk_dict['size'] = size
8627
      else:
8628
        # modification of disk
8629
        if 'size' in disk_dict:
8630
          raise errors.OpPrereqError("Disk size change not possible, use"
8631
                                     " grow-disk", errors.ECODE_INVAL)
8632

    
8633
    if disk_addremove > 1:
8634
      raise errors.OpPrereqError("Only one disk add or remove operation"
8635
                                 " supported at a time", errors.ECODE_INVAL)
8636

    
8637
    if self.op.disks and self.op.disk_template is not None:
8638
      raise errors.OpPrereqError("Disk template conversion and other disk"
8639
                                 " changes not supported at the same time",
8640
                                 errors.ECODE_INVAL)
8641

    
8642
    if self.op.disk_template:
8643
      _CheckDiskTemplate(self.op.disk_template)
8644
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
8645
          self.op.remote_node is None):
8646
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
8647
                                   " one requires specifying a secondary node",
8648
                                   errors.ECODE_INVAL)
8649

    
8650
    # NIC validation
8651
    nic_addremove = 0
8652
    for nic_op, nic_dict in self.op.nics:
8653
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
8654
      if nic_op == constants.DDM_REMOVE:
8655
        nic_addremove += 1
8656
        continue
8657
      elif nic_op == constants.DDM_ADD:
8658
        nic_addremove += 1
8659
      else:
8660
        if not isinstance(nic_op, int):
8661
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
8662
        if not isinstance(nic_dict, dict):
8663
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
8664
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8665

    
8666
      # nic_dict should be a dict
8667
      nic_ip = nic_dict.get('ip', None)
8668
      if nic_ip is not None:
8669
        if nic_ip.lower() == constants.VALUE_NONE:
8670
          nic_dict['ip'] = None
8671
        else:
8672
          if not netutils.IsValidIP4(nic_ip):
8673
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
8674
                                       errors.ECODE_INVAL)
8675

    
8676
      nic_bridge = nic_dict.get('bridge', None)
8677
      nic_link = nic_dict.get('link', None)
8678
      if nic_bridge and nic_link:
8679
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
8680
                                   " at the same time", errors.ECODE_INVAL)
8681
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
8682
        nic_dict['bridge'] = None
8683
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
8684
        nic_dict['link'] = None
8685

    
8686
      if nic_op == constants.DDM_ADD:
8687
        nic_mac = nic_dict.get('mac', None)
8688
        if nic_mac is None:
8689
          nic_dict['mac'] = constants.VALUE_AUTO
8690

    
8691
      if 'mac' in nic_dict:
8692
        nic_mac = nic_dict['mac']
8693
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8694
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
8695

    
8696
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
8697
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
8698
                                     " modifying an existing nic",
8699
                                     errors.ECODE_INVAL)
8700

    
8701
    if nic_addremove > 1:
8702
      raise errors.OpPrereqError("Only one NIC add or remove operation"
8703
                                 " supported at a time", errors.ECODE_INVAL)
8704

    
8705
  def ExpandNames(self):
8706
    self._ExpandAndLockInstance()
8707
    self.needed_locks[locking.LEVEL_NODE] = []
8708
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8709

    
8710
  def DeclareLocks(self, level):
8711
    if level == locking.LEVEL_NODE:
8712
      self._LockInstancesNodes()
8713
      if self.op.disk_template and self.op.remote_node:
8714
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8715
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
8716

    
8717
  def BuildHooksEnv(self):
8718
    """Build hooks env.
8719

8720
    This runs on the master, primary and secondaries.
8721

8722
    """
8723
    args = dict()
8724
    if constants.BE_MEMORY in self.be_new:
8725
      args['memory'] = self.be_new[constants.BE_MEMORY]
8726
    if constants.BE_VCPUS in self.be_new:
8727
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
8728
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
8729
    # information at all.
8730
    if self.op.nics:
8731
      args['nics'] = []
8732
      nic_override = dict(self.op.nics)
8733
      for idx, nic in enumerate(self.instance.nics):
8734
        if idx in nic_override:
8735
          this_nic_override = nic_override[idx]
8736
        else:
8737
          this_nic_override = {}
8738
        if 'ip' in this_nic_override:
8739
          ip = this_nic_override['ip']
8740
        else:
8741
          ip = nic.ip
8742
        if 'mac' in this_nic_override:
8743
          mac = this_nic_override['mac']
8744
        else:
8745
          mac = nic.mac
8746
        if idx in self.nic_pnew:
8747
          nicparams = self.nic_pnew[idx]
8748
        else:
8749
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
8750
        mode = nicparams[constants.NIC_MODE]
8751
        link = nicparams[constants.NIC_LINK]
8752
        args['nics'].append((ip, mac, mode, link))
8753
      if constants.DDM_ADD in nic_override:
8754
        ip = nic_override[constants.DDM_ADD].get('ip', None)
8755
        mac = nic_override[constants.DDM_ADD]['mac']
8756
        nicparams = self.nic_pnew[constants.DDM_ADD]
8757
        mode = nicparams[constants.NIC_MODE]
8758
        link = nicparams[constants.NIC_LINK]
8759
        args['nics'].append((ip, mac, mode, link))
8760
      elif constants.DDM_REMOVE in nic_override:
8761
        del args['nics'][-1]
8762

    
8763
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
8764
    if self.op.disk_template:
8765
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
8766
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8767
    return env, nl, nl
8768

    
8769
  def CheckPrereq(self):
8770
    """Check prerequisites.
8771

8772
    This only checks the instance list against the existing names.
8773

8774
    """
8775
    # checking the new params on the primary/secondary nodes
8776

    
8777
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8778
    cluster = self.cluster = self.cfg.GetClusterInfo()
8779
    assert self.instance is not None, \
8780
      "Cannot retrieve locked instance %s" % self.op.instance_name
8781
    pnode = instance.primary_node
8782
    nodelist = list(instance.all_nodes)
8783

    
8784
    # OS change
8785
    if self.op.os_name and not self.op.force:
8786
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
8787
                      self.op.force_variant)
8788
      instance_os = self.op.os_name
8789
    else:
8790
      instance_os = instance.os
8791

    
8792
    if self.op.disk_template:
8793
      if instance.disk_template == self.op.disk_template:
8794
        raise errors.OpPrereqError("Instance already has disk template %s" %
8795
                                   instance.disk_template, errors.ECODE_INVAL)
8796

    
8797
      if (instance.disk_template,
8798
          self.op.disk_template) not in self._DISK_CONVERSIONS:
8799
        raise errors.OpPrereqError("Unsupported disk template conversion from"
8800
                                   " %s to %s" % (instance.disk_template,
8801
                                                  self.op.disk_template),
8802
                                   errors.ECODE_INVAL)
8803
      _CheckInstanceDown(self, instance, "cannot change disk template")
8804
      if self.op.disk_template in constants.DTS_NET_MIRROR:
8805
        if self.op.remote_node == pnode:
8806
          raise errors.OpPrereqError("Given new secondary node %s is the same"
8807
                                     " as the primary node of the instance" %
8808
                                     self.op.remote_node, errors.ECODE_STATE)
8809
        _CheckNodeOnline(self, self.op.remote_node)
8810
        _CheckNodeNotDrained(self, self.op.remote_node)
8811
        disks = [{"size": d.size} for d in instance.disks]
8812
        required = _ComputeDiskSize(self.op.disk_template, disks)
8813
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
8814

    
8815
    # hvparams processing
8816
    if self.op.hvparams:
8817
      hv_type = instance.hypervisor
8818
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
8819
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
8820
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
8821

    
8822
      # local check
8823
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
8824
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
8825
      self.hv_new = hv_new # the new actual values
8826
      self.hv_inst = i_hvdict # the new dict (without defaults)
8827
    else:
8828
      self.hv_new = self.hv_inst = {}
8829

    
8830
    # beparams processing
8831
    if self.op.beparams:
8832
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
8833
                                   use_none=True)
8834
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
8835
      be_new = cluster.SimpleFillBE(i_bedict)
8836
      self.be_new = be_new # the new actual values
8837
      self.be_inst = i_bedict # the new dict (without defaults)
8838
    else:
8839
      self.be_new = self.be_inst = {}
8840

    
8841
    # osparams processing
8842
    if self.op.osparams:
8843
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
8844
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
8845
      self.os_new = cluster.SimpleFillOS(instance_os, i_osdict)
8846
      self.os_inst = i_osdict # the new dict (without defaults)
8847
    else:
8848
      self.os_new = self.os_inst = {}
8849

    
8850
    self.warn = []
8851

    
8852
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
8853
      mem_check_list = [pnode]
8854
      if be_new[constants.BE_AUTO_BALANCE]:
8855
        # either we changed auto_balance to yes or it was from before
8856
        mem_check_list.extend(instance.secondary_nodes)
8857
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
8858
                                                  instance.hypervisor)
8859
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
8860
                                         instance.hypervisor)
8861
      pninfo = nodeinfo[pnode]
8862
      msg = pninfo.fail_msg
8863
      if msg:
8864
        # Assume the primary node is unreachable and go ahead
8865
        self.warn.append("Can't get info from primary node %s: %s" %
8866
                         (pnode,  msg))
8867
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
8868
        self.warn.append("Node data from primary node %s doesn't contain"
8869
                         " free memory information" % pnode)
8870
      elif instance_info.fail_msg:
8871
        self.warn.append("Can't get instance runtime information: %s" %
8872
                        instance_info.fail_msg)
8873
      else:
8874
        if instance_info.payload:
8875
          current_mem = int(instance_info.payload['memory'])
8876
        else:
8877
          # Assume instance not running
8878
          # (there is a slight race condition here, but it's not very probable,
8879
          # and we have no other way to check)
8880
          current_mem = 0
8881
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
8882
                    pninfo.payload['memory_free'])
8883
        if miss_mem > 0:
8884
          raise errors.OpPrereqError("This change will prevent the instance"
8885
                                     " from starting, due to %d MB of memory"
8886
                                     " missing on its primary node" % miss_mem,
8887
                                     errors.ECODE_NORES)
8888

    
8889
      if be_new[constants.BE_AUTO_BALANCE]:
8890
        for node, nres in nodeinfo.items():
8891
          if node not in instance.secondary_nodes:
8892
            continue
8893
          msg = nres.fail_msg
8894
          if msg:
8895
            self.warn.append("Can't get info from secondary node %s: %s" %
8896
                             (node, msg))
8897
          elif not isinstance(nres.payload.get('memory_free', None), int):
8898
            self.warn.append("Secondary node %s didn't return free"
8899
                             " memory information" % node)
8900
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
8901
            self.warn.append("Not enough memory to failover instance to"
8902
                             " secondary node %s" % node)
8903

    
8904
    # NIC processing
8905
    self.nic_pnew = {}
8906
    self.nic_pinst = {}
8907
    for nic_op, nic_dict in self.op.nics:
8908
      if nic_op == constants.DDM_REMOVE:
8909
        if not instance.nics:
8910
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
8911
                                     errors.ECODE_INVAL)
8912
        continue
8913
      if nic_op != constants.DDM_ADD:
8914
        # an existing nic
8915
        if not instance.nics:
8916
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
8917
                                     " no NICs" % nic_op,
8918
                                     errors.ECODE_INVAL)
8919
        if nic_op < 0 or nic_op >= len(instance.nics):
8920
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
8921
                                     " are 0 to %d" %
8922
                                     (nic_op, len(instance.nics) - 1),
8923
                                     errors.ECODE_INVAL)
8924
        old_nic_params = instance.nics[nic_op].nicparams
8925
        old_nic_ip = instance.nics[nic_op].ip
8926
      else:
8927
        old_nic_params = {}
8928
        old_nic_ip = None
8929

    
8930
      update_params_dict = dict([(key, nic_dict[key])
8931
                                 for key in constants.NICS_PARAMETERS
8932
                                 if key in nic_dict])
8933

    
8934
      if 'bridge' in nic_dict:
8935
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
8936

    
8937
      new_nic_params = _GetUpdatedParams(old_nic_params,
8938
                                         update_params_dict)
8939
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
8940
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
8941
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
8942
      self.nic_pinst[nic_op] = new_nic_params
8943
      self.nic_pnew[nic_op] = new_filled_nic_params
8944
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
8945

    
8946
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
8947
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
8948
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
8949
        if msg:
8950
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
8951
          if self.op.force:
8952
            self.warn.append(msg)
8953
          else:
8954
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
8955
      if new_nic_mode == constants.NIC_MODE_ROUTED:
8956
        if 'ip' in nic_dict:
8957
          nic_ip = nic_dict['ip']
8958
        else:
8959
          nic_ip = old_nic_ip
8960
        if nic_ip is None:
8961
          raise errors.OpPrereqError('Cannot set the nic ip to None'
8962
                                     ' on a routed nic', errors.ECODE_INVAL)
8963
      if 'mac' in nic_dict:
8964
        nic_mac = nic_dict['mac']
8965
        if nic_mac is None:
8966
          raise errors.OpPrereqError('Cannot set the nic mac to None',
8967
                                     errors.ECODE_INVAL)
8968
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8969
          # otherwise generate the mac
8970
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
8971
        else:
8972
          # or validate/reserve the current one
8973
          try:
8974
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
8975
          except errors.ReservationError:
8976
            raise errors.OpPrereqError("MAC address %s already in use"
8977
                                       " in cluster" % nic_mac,
8978
                                       errors.ECODE_NOTUNIQUE)
8979

    
8980
    # DISK processing
8981
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
8982
      raise errors.OpPrereqError("Disk operations not supported for"
8983
                                 " diskless instances",
8984
                                 errors.ECODE_INVAL)
8985
    for disk_op, _ in self.op.disks:
8986
      if disk_op == constants.DDM_REMOVE:
8987
        if len(instance.disks) == 1:
8988
          raise errors.OpPrereqError("Cannot remove the last disk of"
8989
                                     " an instance", errors.ECODE_INVAL)
8990
        _CheckInstanceDown(self, instance, "cannot remove disks")
8991

    
8992
      if (disk_op == constants.DDM_ADD and
8993
          len(instance.nics) >= constants.MAX_DISKS):
8994
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
8995
                                   " add more" % constants.MAX_DISKS,
8996
                                   errors.ECODE_STATE)
8997
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
8998
        # an existing disk
8999
        if disk_op < 0 or disk_op >= len(instance.disks):
9000
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9001
                                     " are 0 to %d" %
9002
                                     (disk_op, len(instance.disks)),
9003
                                     errors.ECODE_INVAL)
9004

    
9005
    return
9006

    
9007
  def _ConvertPlainToDrbd(self, feedback_fn):
9008
    """Converts an instance from plain to drbd.
9009

9010
    """
9011
    feedback_fn("Converting template to drbd")
9012
    instance = self.instance
9013
    pnode = instance.primary_node
9014
    snode = self.op.remote_node
9015

    
9016
    # create a fake disk info for _GenerateDiskTemplate
9017
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
9018
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9019
                                      instance.name, pnode, [snode],
9020
                                      disk_info, None, None, 0)
9021
    info = _GetInstanceInfoText(instance)
9022
    feedback_fn("Creating aditional volumes...")
9023
    # first, create the missing data and meta devices
9024
    for disk in new_disks:
9025
      # unfortunately this is... not too nice
9026
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9027
                            info, True)
9028
      for child in disk.children:
9029
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9030
    # at this stage, all new LVs have been created, we can rename the
9031
    # old ones
9032
    feedback_fn("Renaming original volumes...")
9033
    rename_list = [(o, n.children[0].logical_id)
9034
                   for (o, n) in zip(instance.disks, new_disks)]
9035
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9036
    result.Raise("Failed to rename original LVs")
9037

    
9038
    feedback_fn("Initializing DRBD devices...")
9039
    # all child devices are in place, we can now create the DRBD devices
9040
    for disk in new_disks:
9041
      for node in [pnode, snode]:
9042
        f_create = node == pnode
9043
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9044

    
9045
    # at this point, the instance has been modified
9046
    instance.disk_template = constants.DT_DRBD8
9047
    instance.disks = new_disks
9048
    self.cfg.Update(instance, feedback_fn)
9049

    
9050
    # disks are created, waiting for sync
9051
    disk_abort = not _WaitForSync(self, instance)
9052
    if disk_abort:
9053
      raise errors.OpExecError("There are some degraded disks for"
9054
                               " this instance, please cleanup manually")
9055

    
9056
  def _ConvertDrbdToPlain(self, feedback_fn):
9057
    """Converts an instance from drbd to plain.
9058

9059
    """
9060
    instance = self.instance
9061
    assert len(instance.secondary_nodes) == 1
9062
    pnode = instance.primary_node
9063
    snode = instance.secondary_nodes[0]
9064
    feedback_fn("Converting template to plain")
9065

    
9066
    old_disks = instance.disks
9067
    new_disks = [d.children[0] for d in old_disks]
9068

    
9069
    # copy over size and mode
9070
    for parent, child in zip(old_disks, new_disks):
9071
      child.size = parent.size
9072
      child.mode = parent.mode
9073

    
9074
    # update instance structure
9075
    instance.disks = new_disks
9076
    instance.disk_template = constants.DT_PLAIN
9077
    self.cfg.Update(instance, feedback_fn)
9078

    
9079
    feedback_fn("Removing volumes on the secondary node...")
9080
    for disk in old_disks:
9081
      self.cfg.SetDiskID(disk, snode)
9082
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9083
      if msg:
9084
        self.LogWarning("Could not remove block device %s on node %s,"
9085
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9086

    
9087
    feedback_fn("Removing unneeded volumes on the primary node...")
9088
    for idx, disk in enumerate(old_disks):
9089
      meta = disk.children[1]
9090
      self.cfg.SetDiskID(meta, pnode)
9091
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9092
      if msg:
9093
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9094
                        " continuing anyway: %s", idx, pnode, msg)
9095

    
9096

    
9097
  def Exec(self, feedback_fn):
9098
    """Modifies an instance.
9099

9100
    All parameters take effect only at the next restart of the instance.
9101

9102
    """
9103
    # Process here the warnings from CheckPrereq, as we don't have a
9104
    # feedback_fn there.
9105
    for warn in self.warn:
9106
      feedback_fn("WARNING: %s" % warn)
9107

    
9108
    result = []
9109
    instance = self.instance
9110
    # disk changes
9111
    for disk_op, disk_dict in self.op.disks:
9112
      if disk_op == constants.DDM_REMOVE:
9113
        # remove the last disk
9114
        device = instance.disks.pop()
9115
        device_idx = len(instance.disks)
9116
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9117
          self.cfg.SetDiskID(disk, node)
9118
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9119
          if msg:
9120
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9121
                            " continuing anyway", device_idx, node, msg)
9122
        result.append(("disk/%d" % device_idx, "remove"))
9123
      elif disk_op == constants.DDM_ADD:
9124
        # add a new disk
9125
        if instance.disk_template == constants.DT_FILE:
9126
          file_driver, file_path = instance.disks[0].logical_id
9127
          file_path = os.path.dirname(file_path)
9128
        else:
9129
          file_driver = file_path = None
9130
        disk_idx_base = len(instance.disks)
9131
        new_disk = _GenerateDiskTemplate(self,
9132
                                         instance.disk_template,
9133
                                         instance.name, instance.primary_node,
9134
                                         instance.secondary_nodes,
9135
                                         [disk_dict],
9136
                                         file_path,
9137
                                         file_driver,
9138
                                         disk_idx_base)[0]
9139
        instance.disks.append(new_disk)
9140
        info = _GetInstanceInfoText(instance)
9141

    
9142
        logging.info("Creating volume %s for instance %s",
9143
                     new_disk.iv_name, instance.name)
9144
        # Note: this needs to be kept in sync with _CreateDisks
9145
        #HARDCODE
9146
        for node in instance.all_nodes:
9147
          f_create = node == instance.primary_node
9148
          try:
9149
            _CreateBlockDev(self, node, instance, new_disk,
9150
                            f_create, info, f_create)
9151
          except errors.OpExecError, err:
9152
            self.LogWarning("Failed to create volume %s (%s) on"
9153
                            " node %s: %s",
9154
                            new_disk.iv_name, new_disk, node, err)
9155
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9156
                       (new_disk.size, new_disk.mode)))
9157
      else:
9158
        # change a given disk
9159
        instance.disks[disk_op].mode = disk_dict['mode']
9160
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9161

    
9162
    if self.op.disk_template:
9163
      r_shut = _ShutdownInstanceDisks(self, instance)
9164
      if not r_shut:
9165
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
9166
                                 " proceed with disk template conversion")
9167
      mode = (instance.disk_template, self.op.disk_template)
9168
      try:
9169
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9170
      except:
9171
        self.cfg.ReleaseDRBDMinors(instance.name)
9172
        raise
9173
      result.append(("disk_template", self.op.disk_template))
9174

    
9175
    # NIC changes
9176
    for nic_op, nic_dict in self.op.nics:
9177
      if nic_op == constants.DDM_REMOVE:
9178
        # remove the last nic
9179
        del instance.nics[-1]
9180
        result.append(("nic.%d" % len(instance.nics), "remove"))
9181
      elif nic_op == constants.DDM_ADD:
9182
        # mac and bridge should be set, by now
9183
        mac = nic_dict['mac']
9184
        ip = nic_dict.get('ip', None)
9185
        nicparams = self.nic_pinst[constants.DDM_ADD]
9186
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9187
        instance.nics.append(new_nic)
9188
        result.append(("nic.%d" % (len(instance.nics) - 1),
9189
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9190
                       (new_nic.mac, new_nic.ip,
9191
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9192
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9193
                       )))
9194
      else:
9195
        for key in 'mac', 'ip':
9196
          if key in nic_dict:
9197
            setattr(instance.nics[nic_op], key, nic_dict[key])
9198
        if nic_op in self.nic_pinst:
9199
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9200
        for key, val in nic_dict.iteritems():
9201
          result.append(("nic.%s/%d" % (key, nic_op), val))
9202

    
9203
    # hvparams changes
9204
    if self.op.hvparams:
9205
      instance.hvparams = self.hv_inst
9206
      for key, val in self.op.hvparams.iteritems():
9207
        result.append(("hv/%s" % key, val))
9208

    
9209
    # beparams changes
9210
    if self.op.beparams:
9211
      instance.beparams = self.be_inst
9212
      for key, val in self.op.beparams.iteritems():
9213
        result.append(("be/%s" % key, val))
9214

    
9215
    # OS change
9216
    if self.op.os_name:
9217
      instance.os = self.op.os_name
9218

    
9219
    # osparams changes
9220
    if self.op.osparams:
9221
      instance.osparams = self.os_inst
9222
      for key, val in self.op.osparams.iteritems():
9223
        result.append(("os/%s" % key, val))
9224

    
9225
    self.cfg.Update(instance, feedback_fn)
9226

    
9227
    return result
9228

    
9229
  _DISK_CONVERSIONS = {
9230
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9231
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9232
    }
9233

    
9234

    
9235
class LUQueryExports(NoHooksLU):
9236
  """Query the exports list
9237

9238
  """
9239
  _OP_PARAMS = [
9240
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
9241
    ("use_locking", False, _TBool),
9242
    ]
9243
  REQ_BGL = False
9244

    
9245
  def ExpandNames(self):
9246
    self.needed_locks = {}
9247
    self.share_locks[locking.LEVEL_NODE] = 1
9248
    if not self.op.nodes:
9249
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9250
    else:
9251
      self.needed_locks[locking.LEVEL_NODE] = \
9252
        _GetWantedNodes(self, self.op.nodes)
9253

    
9254
  def Exec(self, feedback_fn):
9255
    """Compute the list of all the exported system images.
9256

9257
    @rtype: dict
9258
    @return: a dictionary with the structure node->(export-list)
9259
        where export-list is a list of the instances exported on
9260
        that node.
9261

9262
    """
9263
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9264
    rpcresult = self.rpc.call_export_list(self.nodes)
9265
    result = {}
9266
    for node in rpcresult:
9267
      if rpcresult[node].fail_msg:
9268
        result[node] = False
9269
      else:
9270
        result[node] = rpcresult[node].payload
9271

    
9272
    return result
9273

    
9274

    
9275
class LUPrepareExport(NoHooksLU):
9276
  """Prepares an instance for an export and returns useful information.
9277

9278
  """
9279
  _OP_PARAMS = [
9280
    _PInstanceName,
9281
    ("mode", _NoDefault, _TElemOf(constants.EXPORT_MODES)),
9282
    ]
9283
  REQ_BGL = False
9284

    
9285
  def ExpandNames(self):
9286
    self._ExpandAndLockInstance()
9287

    
9288
  def CheckPrereq(self):
9289
    """Check prerequisites.
9290

9291
    """
9292
    instance_name = self.op.instance_name
9293

    
9294
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9295
    assert self.instance is not None, \
9296
          "Cannot retrieve locked instance %s" % self.op.instance_name
9297
    _CheckNodeOnline(self, self.instance.primary_node)
9298

    
9299
    self._cds = _GetClusterDomainSecret()
9300

    
9301
  def Exec(self, feedback_fn):
9302
    """Prepares an instance for an export.
9303

9304
    """
9305
    instance = self.instance
9306

    
9307
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9308
      salt = utils.GenerateSecret(8)
9309

    
9310
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9311
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9312
                                              constants.RIE_CERT_VALIDITY)
9313
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9314

    
9315
      (name, cert_pem) = result.payload
9316

    
9317
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9318
                                             cert_pem)
9319

    
9320
      return {
9321
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9322
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9323
                          salt),
9324
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9325
        }
9326

    
9327
    return None
9328

    
9329

    
9330
class LUExportInstance(LogicalUnit):
9331
  """Export an instance to an image in the cluster.
9332

9333
  """
9334
  HPATH = "instance-export"
9335
  HTYPE = constants.HTYPE_INSTANCE
9336
  _OP_PARAMS = [
9337
    _PInstanceName,
9338
    ("target_node", _NoDefault, _TOr(_TNonEmptyString, _TList)),
9339
    ("shutdown", True, _TBool),
9340
    _PShutdownTimeout,
9341
    ("remove_instance", False, _TBool),
9342
    ("ignore_remove_failures", False, _TBool),
9343
    ("mode", constants.EXPORT_MODE_LOCAL, _TElemOf(constants.EXPORT_MODES)),
9344
    ("x509_key_name", None, _TOr(_TList, _TNone)),
9345
    ("destination_x509_ca", None, _TMaybeString),
9346
    ]
9347
  REQ_BGL = False
9348

    
9349
  def CheckArguments(self):
9350
    """Check the arguments.
9351

9352
    """
9353
    self.x509_key_name = self.op.x509_key_name
9354
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9355

    
9356
    if self.op.remove_instance and not self.op.shutdown:
9357
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9358
                                 " down before")
9359

    
9360
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9361
      if not self.x509_key_name:
9362
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9363
                                   errors.ECODE_INVAL)
9364

    
9365
      if not self.dest_x509_ca_pem:
9366
        raise errors.OpPrereqError("Missing destination X509 CA",
9367
                                   errors.ECODE_INVAL)
9368

    
9369
  def ExpandNames(self):
9370
    self._ExpandAndLockInstance()
9371

    
9372
    # Lock all nodes for local exports
9373
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9374
      # FIXME: lock only instance primary and destination node
9375
      #
9376
      # Sad but true, for now we have do lock all nodes, as we don't know where
9377
      # the previous export might be, and in this LU we search for it and
9378
      # remove it from its current node. In the future we could fix this by:
9379
      #  - making a tasklet to search (share-lock all), then create the
9380
      #    new one, then one to remove, after
9381
      #  - removing the removal operation altogether
9382
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9383

    
9384
  def DeclareLocks(self, level):
9385
    """Last minute lock declaration."""
9386
    # All nodes are locked anyway, so nothing to do here.
9387

    
9388
  def BuildHooksEnv(self):
9389
    """Build hooks env.
9390

9391
    This will run on the master, primary node and target node.
9392

9393
    """
9394
    env = {
9395
      "EXPORT_MODE": self.op.mode,
9396
      "EXPORT_NODE": self.op.target_node,
9397
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9398
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9399
      # TODO: Generic function for boolean env variables
9400
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9401
      }
9402

    
9403
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9404

    
9405
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9406

    
9407
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9408
      nl.append(self.op.target_node)
9409

    
9410
    return env, nl, nl
9411

    
9412
  def CheckPrereq(self):
9413
    """Check prerequisites.
9414

9415
    This checks that the instance and node names are valid.
9416

9417
    """
9418
    instance_name = self.op.instance_name
9419

    
9420
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9421
    assert self.instance is not None, \
9422
          "Cannot retrieve locked instance %s" % self.op.instance_name
9423
    _CheckNodeOnline(self, self.instance.primary_node)
9424

    
9425
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9426
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9427
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9428
      assert self.dst_node is not None
9429

    
9430
      _CheckNodeOnline(self, self.dst_node.name)
9431
      _CheckNodeNotDrained(self, self.dst_node.name)
9432

    
9433
      self._cds = None
9434
      self.dest_disk_info = None
9435
      self.dest_x509_ca = None
9436

    
9437
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9438
      self.dst_node = None
9439

    
9440
      if len(self.op.target_node) != len(self.instance.disks):
9441
        raise errors.OpPrereqError(("Received destination information for %s"
9442
                                    " disks, but instance %s has %s disks") %
9443
                                   (len(self.op.target_node), instance_name,
9444
                                    len(self.instance.disks)),
9445
                                   errors.ECODE_INVAL)
9446

    
9447
      cds = _GetClusterDomainSecret()
9448

    
9449
      # Check X509 key name
9450
      try:
9451
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9452
      except (TypeError, ValueError), err:
9453
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9454

    
9455
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9456
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9457
                                   errors.ECODE_INVAL)
9458

    
9459
      # Load and verify CA
9460
      try:
9461
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9462
      except OpenSSL.crypto.Error, err:
9463
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9464
                                   (err, ), errors.ECODE_INVAL)
9465

    
9466
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9467
      if errcode is not None:
9468
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9469
                                   (msg, ), errors.ECODE_INVAL)
9470

    
9471
      self.dest_x509_ca = cert
9472

    
9473
      # Verify target information
9474
      disk_info = []
9475
      for idx, disk_data in enumerate(self.op.target_node):
9476
        try:
9477
          (host, port, magic) = \
9478
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9479
        except errors.GenericError, err:
9480
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9481
                                     (idx, err), errors.ECODE_INVAL)
9482

    
9483
        disk_info.append((host, port, magic))
9484

    
9485
      assert len(disk_info) == len(self.op.target_node)
9486
      self.dest_disk_info = disk_info
9487

    
9488
    else:
9489
      raise errors.ProgrammerError("Unhandled export mode %r" %
9490
                                   self.op.mode)
9491

    
9492
    # instance disk type verification
9493
    # TODO: Implement export support for file-based disks
9494
    for disk in self.instance.disks:
9495
      if disk.dev_type == constants.LD_FILE:
9496
        raise errors.OpPrereqError("Export not supported for instances with"
9497
                                   " file-based disks", errors.ECODE_INVAL)
9498

    
9499
  def _CleanupExports(self, feedback_fn):
9500
    """Removes exports of current instance from all other nodes.
9501

9502
    If an instance in a cluster with nodes A..D was exported to node C, its
9503
    exports will be removed from the nodes A, B and D.
9504

9505
    """
9506
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9507

    
9508
    nodelist = self.cfg.GetNodeList()
9509
    nodelist.remove(self.dst_node.name)
9510

    
9511
    # on one-node clusters nodelist will be empty after the removal
9512
    # if we proceed the backup would be removed because OpQueryExports
9513
    # substitutes an empty list with the full cluster node list.
9514
    iname = self.instance.name
9515
    if nodelist:
9516
      feedback_fn("Removing old exports for instance %s" % iname)
9517
      exportlist = self.rpc.call_export_list(nodelist)
9518
      for node in exportlist:
9519
        if exportlist[node].fail_msg:
9520
          continue
9521
        if iname in exportlist[node].payload:
9522
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9523
          if msg:
9524
            self.LogWarning("Could not remove older export for instance %s"
9525
                            " on node %s: %s", iname, node, msg)
9526

    
9527
  def Exec(self, feedback_fn):
9528
    """Export an instance to an image in the cluster.
9529

9530
    """
9531
    assert self.op.mode in constants.EXPORT_MODES
9532

    
9533
    instance = self.instance
9534
    src_node = instance.primary_node
9535

    
9536
    if self.op.shutdown:
9537
      # shutdown the instance, but not the disks
9538
      feedback_fn("Shutting down instance %s" % instance.name)
9539
      result = self.rpc.call_instance_shutdown(src_node, instance,
9540
                                               self.op.shutdown_timeout)
9541
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9542
      result.Raise("Could not shutdown instance %s on"
9543
                   " node %s" % (instance.name, src_node))
9544

    
9545
    # set the disks ID correctly since call_instance_start needs the
9546
    # correct drbd minor to create the symlinks
9547
    for disk in instance.disks:
9548
      self.cfg.SetDiskID(disk, src_node)
9549

    
9550
    activate_disks = (not instance.admin_up)
9551

    
9552
    if activate_disks:
9553
      # Activate the instance disks if we'exporting a stopped instance
9554
      feedback_fn("Activating disks for %s" % instance.name)
9555
      _StartInstanceDisks(self, instance, None)
9556

    
9557
    try:
9558
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9559
                                                     instance)
9560

    
9561
      helper.CreateSnapshots()
9562
      try:
9563
        if (self.op.shutdown and instance.admin_up and
9564
            not self.op.remove_instance):
9565
          assert not activate_disks
9566
          feedback_fn("Starting instance %s" % instance.name)
9567
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9568
          msg = result.fail_msg
9569
          if msg:
9570
            feedback_fn("Failed to start instance: %s" % msg)
9571
            _ShutdownInstanceDisks(self, instance)
9572
            raise errors.OpExecError("Could not start instance: %s" % msg)
9573

    
9574
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9575
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9576
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9577
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9578
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9579

    
9580
          (key_name, _, _) = self.x509_key_name
9581

    
9582
          dest_ca_pem = \
9583
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9584
                                            self.dest_x509_ca)
9585

    
9586
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9587
                                                     key_name, dest_ca_pem,
9588
                                                     timeouts)
9589
      finally:
9590
        helper.Cleanup()
9591

    
9592
      # Check for backwards compatibility
9593
      assert len(dresults) == len(instance.disks)
9594
      assert compat.all(isinstance(i, bool) for i in dresults), \
9595
             "Not all results are boolean: %r" % dresults
9596

    
9597
    finally:
9598
      if activate_disks:
9599
        feedback_fn("Deactivating disks for %s" % instance.name)
9600
        _ShutdownInstanceDisks(self, instance)
9601

    
9602
    if not (compat.all(dresults) and fin_resu):
9603
      failures = []
9604
      if not fin_resu:
9605
        failures.append("export finalization")
9606
      if not compat.all(dresults):
9607
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
9608
                               if not dsk)
9609
        failures.append("disk export: disk(s) %s" % fdsk)
9610

    
9611
      raise errors.OpExecError("Export failed, errors in %s" %
9612
                               utils.CommaJoin(failures))
9613

    
9614
    # At this point, the export was successful, we can cleanup/finish
9615

    
9616
    # Remove instance if requested
9617
    if self.op.remove_instance:
9618
      feedback_fn("Removing instance %s" % instance.name)
9619
      _RemoveInstance(self, feedback_fn, instance,
9620
                      self.op.ignore_remove_failures)
9621

    
9622
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9623
      self._CleanupExports(feedback_fn)
9624

    
9625
    return fin_resu, dresults
9626

    
9627

    
9628
class LURemoveExport(NoHooksLU):
9629
  """Remove exports related to the named instance.
9630

9631
  """
9632
  _OP_PARAMS = [
9633
    _PInstanceName,
9634
    ]
9635
  REQ_BGL = False
9636

    
9637
  def ExpandNames(self):
9638
    self.needed_locks = {}
9639
    # We need all nodes to be locked in order for RemoveExport to work, but we
9640
    # don't need to lock the instance itself, as nothing will happen to it (and
9641
    # we can remove exports also for a removed instance)
9642
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9643

    
9644
  def Exec(self, feedback_fn):
9645
    """Remove any export.
9646

9647
    """
9648
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9649
    # If the instance was not found we'll try with the name that was passed in.
9650
    # This will only work if it was an FQDN, though.
9651
    fqdn_warn = False
9652
    if not instance_name:
9653
      fqdn_warn = True
9654
      instance_name = self.op.instance_name
9655

    
9656
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
9657
    exportlist = self.rpc.call_export_list(locked_nodes)
9658
    found = False
9659
    for node in exportlist:
9660
      msg = exportlist[node].fail_msg
9661
      if msg:
9662
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
9663
        continue
9664
      if instance_name in exportlist[node].payload:
9665
        found = True
9666
        result = self.rpc.call_export_remove(node, instance_name)
9667
        msg = result.fail_msg
9668
        if msg:
9669
          logging.error("Could not remove export for instance %s"
9670
                        " on node %s: %s", instance_name, node, msg)
9671

    
9672
    if fqdn_warn and not found:
9673
      feedback_fn("Export not found. If trying to remove an export belonging"
9674
                  " to a deleted instance please use its Fully Qualified"
9675
                  " Domain Name.")
9676

    
9677

    
9678
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
9679
  """Generic tags LU.
9680

9681
  This is an abstract class which is the parent of all the other tags LUs.
9682

9683
  """
9684

    
9685
  def ExpandNames(self):
9686
    self.needed_locks = {}
9687
    if self.op.kind == constants.TAG_NODE:
9688
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
9689
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
9690
    elif self.op.kind == constants.TAG_INSTANCE:
9691
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
9692
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
9693

    
9694
  def CheckPrereq(self):
9695
    """Check prerequisites.
9696

9697
    """
9698
    if self.op.kind == constants.TAG_CLUSTER:
9699
      self.target = self.cfg.GetClusterInfo()
9700
    elif self.op.kind == constants.TAG_NODE:
9701
      self.target = self.cfg.GetNodeInfo(self.op.name)
9702
    elif self.op.kind == constants.TAG_INSTANCE:
9703
      self.target = self.cfg.GetInstanceInfo(self.op.name)
9704
    else:
9705
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
9706
                                 str(self.op.kind), errors.ECODE_INVAL)
9707

    
9708

    
9709
class LUGetTags(TagsLU):
9710
  """Returns the tags of a given object.
9711

9712
  """
9713
  _OP_PARAMS = [
9714
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9715
    ("name", _NoDefault, _TNonEmptyString),
9716
    ]
9717
  REQ_BGL = False
9718

    
9719
  def Exec(self, feedback_fn):
9720
    """Returns the tag list.
9721

9722
    """
9723
    return list(self.target.GetTags())
9724

    
9725

    
9726
class LUSearchTags(NoHooksLU):
9727
  """Searches the tags for a given pattern.
9728

9729
  """
9730
  _OP_PARAMS = [
9731
    ("pattern", _NoDefault, _TNonEmptyString),
9732
    ]
9733
  REQ_BGL = False
9734

    
9735
  def ExpandNames(self):
9736
    self.needed_locks = {}
9737

    
9738
  def CheckPrereq(self):
9739
    """Check prerequisites.
9740

9741
    This checks the pattern passed for validity by compiling it.
9742

9743
    """
9744
    try:
9745
      self.re = re.compile(self.op.pattern)
9746
    except re.error, err:
9747
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
9748
                                 (self.op.pattern, err), errors.ECODE_INVAL)
9749

    
9750
  def Exec(self, feedback_fn):
9751
    """Returns the tag list.
9752

9753
    """
9754
    cfg = self.cfg
9755
    tgts = [("/cluster", cfg.GetClusterInfo())]
9756
    ilist = cfg.GetAllInstancesInfo().values()
9757
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
9758
    nlist = cfg.GetAllNodesInfo().values()
9759
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
9760
    results = []
9761
    for path, target in tgts:
9762
      for tag in target.GetTags():
9763
        if self.re.search(tag):
9764
          results.append((path, tag))
9765
    return results
9766

    
9767

    
9768
class LUAddTags(TagsLU):
9769
  """Sets a tag on a given object.
9770

9771
  """
9772
  _OP_PARAMS = [
9773
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9774
    ("name", _NoDefault, _TNonEmptyString),
9775
    ("tags", _NoDefault, _TListOf(_TNonEmptyString)),
9776
    ]
9777
  REQ_BGL = False
9778

    
9779
  def CheckPrereq(self):
9780
    """Check prerequisites.
9781

9782
    This checks the type and length of the tag name and value.
9783

9784
    """
9785
    TagsLU.CheckPrereq(self)
9786
    for tag in self.op.tags:
9787
      objects.TaggableObject.ValidateTag(tag)
9788

    
9789
  def Exec(self, feedback_fn):
9790
    """Sets the tag.
9791

9792
    """
9793
    try:
9794
      for tag in self.op.tags:
9795
        self.target.AddTag(tag)
9796
    except errors.TagError, err:
9797
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
9798
    self.cfg.Update(self.target, feedback_fn)
9799

    
9800

    
9801
class LUDelTags(TagsLU):
9802
  """Delete a list of tags from a given object.
9803

9804
  """
9805
  _OP_PARAMS = [
9806
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9807
    ("name", _NoDefault, _TNonEmptyString),
9808
    ("tags", _NoDefault, _TListOf(_TNonEmptyString)),
9809
    ]
9810
  REQ_BGL = False
9811

    
9812
  def CheckPrereq(self):
9813
    """Check prerequisites.
9814

9815
    This checks that we have the given tag.
9816

9817
    """
9818
    TagsLU.CheckPrereq(self)
9819
    for tag in self.op.tags:
9820
      objects.TaggableObject.ValidateTag(tag)
9821
    del_tags = frozenset(self.op.tags)
9822
    cur_tags = self.target.GetTags()
9823
    if not del_tags <= cur_tags:
9824
      diff_tags = del_tags - cur_tags
9825
      diff_names = ["'%s'" % tag for tag in diff_tags]
9826
      diff_names.sort()
9827
      raise errors.OpPrereqError("Tag(s) %s not found" %
9828
                                 (",".join(diff_names)), errors.ECODE_NOENT)
9829

    
9830
  def Exec(self, feedback_fn):
9831
    """Remove the tag from the object.
9832

9833
    """
9834
    for tag in self.op.tags:
9835
      self.target.RemoveTag(tag)
9836
    self.cfg.Update(self.target, feedback_fn)
9837

    
9838

    
9839
class LUTestDelay(NoHooksLU):
9840
  """Sleep for a specified amount of time.
9841

9842
  This LU sleeps on the master and/or nodes for a specified amount of
9843
  time.
9844

9845
  """
9846
  _OP_PARAMS = [
9847
    ("duration", _NoDefault, _TFloat),
9848
    ("on_master", True, _TBool),
9849
    ("on_nodes", _EmptyList, _TListOf(_TNonEmptyString)),
9850
    ("repeat", 0, _TPositiveInt)
9851
    ]
9852
  REQ_BGL = False
9853

    
9854
  def ExpandNames(self):
9855
    """Expand names and set required locks.
9856

9857
    This expands the node list, if any.
9858

9859
    """
9860
    self.needed_locks = {}
9861
    if self.op.on_nodes:
9862
      # _GetWantedNodes can be used here, but is not always appropriate to use
9863
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
9864
      # more information.
9865
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
9866
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
9867

    
9868
  def _TestDelay(self):
9869
    """Do the actual sleep.
9870

9871
    """
9872
    if self.op.on_master:
9873
      if not utils.TestDelay(self.op.duration):
9874
        raise errors.OpExecError("Error during master delay test")
9875
    if self.op.on_nodes:
9876
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
9877
      for node, node_result in result.items():
9878
        node_result.Raise("Failure during rpc call to node %s" % node)
9879

    
9880
  def Exec(self, feedback_fn):
9881
    """Execute the test delay opcode, with the wanted repetitions.
9882

9883
    """
9884
    if self.op.repeat == 0:
9885
      self._TestDelay()
9886
    else:
9887
      top_value = self.op.repeat - 1
9888
      for i in range(self.op.repeat):
9889
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
9890
        self._TestDelay()
9891

    
9892

    
9893
class LUTestJobqueue(NoHooksLU):
9894
  """Utility LU to test some aspects of the job queue.
9895

9896
  """
9897
  _OP_PARAMS = [
9898
    ("notify_waitlock", False, _TBool),
9899
    ("notify_exec", False, _TBool),
9900
    ("log_messages", _EmptyList, _TListOf(_TString)),
9901
    ("fail", False, _TBool),
9902
    ]
9903
  REQ_BGL = False
9904

    
9905
  # Must be lower than default timeout for WaitForJobChange to see whether it
9906
  # notices changed jobs
9907
  _CLIENT_CONNECT_TIMEOUT = 20.0
9908
  _CLIENT_CONFIRM_TIMEOUT = 60.0
9909

    
9910
  @classmethod
9911
  def _NotifyUsingSocket(cls, cb, errcls):
9912
    """Opens a Unix socket and waits for another program to connect.
9913

9914
    @type cb: callable
9915
    @param cb: Callback to send socket name to client
9916
    @type errcls: class
9917
    @param errcls: Exception class to use for errors
9918

9919
    """
9920
    # Using a temporary directory as there's no easy way to create temporary
9921
    # sockets without writing a custom loop around tempfile.mktemp and
9922
    # socket.bind
9923
    tmpdir = tempfile.mkdtemp()
9924
    try:
9925
      tmpsock = utils.PathJoin(tmpdir, "sock")
9926

    
9927
      logging.debug("Creating temporary socket at %s", tmpsock)
9928
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
9929
      try:
9930
        sock.bind(tmpsock)
9931
        sock.listen(1)
9932

    
9933
        # Send details to client
9934
        cb(tmpsock)
9935

    
9936
        # Wait for client to connect before continuing
9937
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
9938
        try:
9939
          (conn, _) = sock.accept()
9940
        except socket.error, err:
9941
          raise errcls("Client didn't connect in time (%s)" % err)
9942
      finally:
9943
        sock.close()
9944
    finally:
9945
      # Remove as soon as client is connected
9946
      shutil.rmtree(tmpdir)
9947

    
9948
    # Wait for client to close
9949
    try:
9950
      try:
9951
        # pylint: disable-msg=E1101
9952
        # Instance of '_socketobject' has no ... member
9953
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
9954
        conn.recv(1)
9955
      except socket.error, err:
9956
        raise errcls("Client failed to confirm notification (%s)" % err)
9957
    finally:
9958
      conn.close()
9959

    
9960
  def _SendNotification(self, test, arg, sockname):
9961
    """Sends a notification to the client.
9962

9963
    @type test: string
9964
    @param test: Test name
9965
    @param arg: Test argument (depends on test)
9966
    @type sockname: string
9967
    @param sockname: Socket path
9968

9969
    """
9970
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
9971

    
9972
  def _Notify(self, prereq, test, arg):
9973
    """Notifies the client of a test.
9974

9975
    @type prereq: bool
9976
    @param prereq: Whether this is a prereq-phase test
9977
    @type test: string
9978
    @param test: Test name
9979
    @param arg: Test argument (depends on test)
9980

9981
    """
9982
    if prereq:
9983
      errcls = errors.OpPrereqError
9984
    else:
9985
      errcls = errors.OpExecError
9986

    
9987
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
9988
                                                  test, arg),
9989
                                   errcls)
9990

    
9991
  def CheckArguments(self):
9992
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
9993
    self.expandnames_calls = 0
9994

    
9995
  def ExpandNames(self):
9996
    checkargs_calls = getattr(self, "checkargs_calls", 0)
9997
    if checkargs_calls < 1:
9998
      raise errors.ProgrammerError("CheckArguments was not called")
9999

    
10000
    self.expandnames_calls += 1
10001

    
10002
    if self.op.notify_waitlock:
10003
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
10004

    
10005
    self.LogInfo("Expanding names")
10006

    
10007
    # Get lock on master node (just to get a lock, not for a particular reason)
10008
    self.needed_locks = {
10009
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
10010
      }
10011

    
10012
  def Exec(self, feedback_fn):
10013
    if self.expandnames_calls < 1:
10014
      raise errors.ProgrammerError("ExpandNames was not called")
10015

    
10016
    if self.op.notify_exec:
10017
      self._Notify(False, constants.JQT_EXEC, None)
10018

    
10019
    self.LogInfo("Executing")
10020

    
10021
    if self.op.log_messages:
10022
      for idx, msg in enumerate(self.op.log_messages):
10023
        self.LogInfo("Sending log message %s", idx + 1)
10024
        feedback_fn(constants.JQT_MSGPREFIX + msg)
10025
        # Report how many test messages have been sent
10026
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
10027

    
10028
    if self.op.fail:
10029
      raise errors.OpExecError("Opcode failure was requested")
10030

    
10031
    return True
10032

    
10033

    
10034
class IAllocator(object):
10035
  """IAllocator framework.
10036

10037
  An IAllocator instance has three sets of attributes:
10038
    - cfg that is needed to query the cluster
10039
    - input data (all members of the _KEYS class attribute are required)
10040
    - four buffer attributes (in|out_data|text), that represent the
10041
      input (to the external script) in text and data structure format,
10042
      and the output from it, again in two formats
10043
    - the result variables from the script (success, info, nodes) for
10044
      easy usage
10045

10046
  """
10047
  # pylint: disable-msg=R0902
10048
  # lots of instance attributes
10049
  _ALLO_KEYS = [
10050
    "name", "mem_size", "disks", "disk_template",
10051
    "os", "tags", "nics", "vcpus", "hypervisor",
10052
    ]
10053
  _RELO_KEYS = [
10054
    "name", "relocate_from",
10055
    ]
10056
  _EVAC_KEYS = [
10057
    "evac_nodes",
10058
    ]
10059

    
10060
  def __init__(self, cfg, rpc, mode, **kwargs):
10061
    self.cfg = cfg
10062
    self.rpc = rpc
10063
    # init buffer variables
10064
    self.in_text = self.out_text = self.in_data = self.out_data = None
10065
    # init all input fields so that pylint is happy
10066
    self.mode = mode
10067
    self.mem_size = self.disks = self.disk_template = None
10068
    self.os = self.tags = self.nics = self.vcpus = None
10069
    self.hypervisor = None
10070
    self.relocate_from = None
10071
    self.name = None
10072
    self.evac_nodes = None
10073
    # computed fields
10074
    self.required_nodes = None
10075
    # init result fields
10076
    self.success = self.info = self.result = None
10077
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10078
      keyset = self._ALLO_KEYS
10079
      fn = self._AddNewInstance
10080
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10081
      keyset = self._RELO_KEYS
10082
      fn = self._AddRelocateInstance
10083
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10084
      keyset = self._EVAC_KEYS
10085
      fn = self._AddEvacuateNodes
10086
    else:
10087
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
10088
                                   " IAllocator" % self.mode)
10089
    for key in kwargs:
10090
      if key not in keyset:
10091
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
10092
                                     " IAllocator" % key)
10093
      setattr(self, key, kwargs[key])
10094

    
10095
    for key in keyset:
10096
      if key not in kwargs:
10097
        raise errors.ProgrammerError("Missing input parameter '%s' to"
10098
                                     " IAllocator" % key)
10099
    self._BuildInputData(fn)
10100

    
10101
  def _ComputeClusterData(self):
10102
    """Compute the generic allocator input data.
10103

10104
    This is the data that is independent of the actual operation.
10105

10106
    """
10107
    cfg = self.cfg
10108
    cluster_info = cfg.GetClusterInfo()
10109
    # cluster data
10110
    data = {
10111
      "version": constants.IALLOCATOR_VERSION,
10112
      "cluster_name": cfg.GetClusterName(),
10113
      "cluster_tags": list(cluster_info.GetTags()),
10114
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
10115
      # we don't have job IDs
10116
      }
10117
    iinfo = cfg.GetAllInstancesInfo().values()
10118
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
10119

    
10120
    # node data
10121
    node_results = {}
10122
    node_list = cfg.GetNodeList()
10123

    
10124
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10125
      hypervisor_name = self.hypervisor
10126
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10127
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
10128
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10129
      hypervisor_name = cluster_info.enabled_hypervisors[0]
10130

    
10131
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
10132
                                        hypervisor_name)
10133
    node_iinfo = \
10134
      self.rpc.call_all_instances_info(node_list,
10135
                                       cluster_info.enabled_hypervisors)
10136
    for nname, nresult in node_data.items():
10137
      # first fill in static (config-based) values
10138
      ninfo = cfg.GetNodeInfo(nname)
10139
      pnr = {
10140
        "tags": list(ninfo.GetTags()),
10141
        "primary_ip": ninfo.primary_ip,
10142
        "secondary_ip": ninfo.secondary_ip,
10143
        "offline": ninfo.offline,
10144
        "drained": ninfo.drained,
10145
        "master_candidate": ninfo.master_candidate,
10146
        }
10147

    
10148
      if not (ninfo.offline or ninfo.drained):
10149
        nresult.Raise("Can't get data for node %s" % nname)
10150
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
10151
                                nname)
10152
        remote_info = nresult.payload
10153

    
10154
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
10155
                     'vg_size', 'vg_free', 'cpu_total']:
10156
          if attr not in remote_info:
10157
            raise errors.OpExecError("Node '%s' didn't return attribute"
10158
                                     " '%s'" % (nname, attr))
10159
          if not isinstance(remote_info[attr], int):
10160
            raise errors.OpExecError("Node '%s' returned invalid value"
10161
                                     " for '%s': %s" %
10162
                                     (nname, attr, remote_info[attr]))
10163
        # compute memory used by primary instances
10164
        i_p_mem = i_p_up_mem = 0
10165
        for iinfo, beinfo in i_list:
10166
          if iinfo.primary_node == nname:
10167
            i_p_mem += beinfo[constants.BE_MEMORY]
10168
            if iinfo.name not in node_iinfo[nname].payload:
10169
              i_used_mem = 0
10170
            else:
10171
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
10172
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
10173
            remote_info['memory_free'] -= max(0, i_mem_diff)
10174

    
10175
            if iinfo.admin_up:
10176
              i_p_up_mem += beinfo[constants.BE_MEMORY]
10177

    
10178
        # compute memory used by instances
10179
        pnr_dyn = {
10180
          "total_memory": remote_info['memory_total'],
10181
          "reserved_memory": remote_info['memory_dom0'],
10182
          "free_memory": remote_info['memory_free'],
10183
          "total_disk": remote_info['vg_size'],
10184
          "free_disk": remote_info['vg_free'],
10185
          "total_cpus": remote_info['cpu_total'],
10186
          "i_pri_memory": i_p_mem,
10187
          "i_pri_up_memory": i_p_up_mem,
10188
          }
10189
        pnr.update(pnr_dyn)
10190

    
10191
      node_results[nname] = pnr
10192
    data["nodes"] = node_results
10193

    
10194
    # instance data
10195
    instance_data = {}
10196
    for iinfo, beinfo in i_list:
10197
      nic_data = []
10198
      for nic in iinfo.nics:
10199
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
10200
        nic_dict = {"mac": nic.mac,
10201
                    "ip": nic.ip,
10202
                    "mode": filled_params[constants.NIC_MODE],
10203
                    "link": filled_params[constants.NIC_LINK],
10204
                   }
10205
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
10206
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
10207
        nic_data.append(nic_dict)
10208
      pir = {
10209
        "tags": list(iinfo.GetTags()),
10210
        "admin_up": iinfo.admin_up,
10211
        "vcpus": beinfo[constants.BE_VCPUS],
10212
        "memory": beinfo[constants.BE_MEMORY],
10213
        "os": iinfo.os,
10214
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
10215
        "nics": nic_data,
10216
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
10217
        "disk_template": iinfo.disk_template,
10218
        "hypervisor": iinfo.hypervisor,
10219
        }
10220
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
10221
                                                 pir["disks"])
10222
      instance_data[iinfo.name] = pir
10223

    
10224
    data["instances"] = instance_data
10225

    
10226
    self.in_data = data
10227

    
10228
  def _AddNewInstance(self):
10229
    """Add new instance data to allocator structure.
10230

10231
    This in combination with _AllocatorGetClusterData will create the
10232
    correct structure needed as input for the allocator.
10233

10234
    The checks for the completeness of the opcode must have already been
10235
    done.
10236

10237
    """
10238
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
10239

    
10240
    if self.disk_template in constants.DTS_NET_MIRROR:
10241
      self.required_nodes = 2
10242
    else:
10243
      self.required_nodes = 1
10244
    request = {
10245
      "name": self.name,
10246
      "disk_template": self.disk_template,
10247
      "tags": self.tags,
10248
      "os": self.os,
10249
      "vcpus": self.vcpus,
10250
      "memory": self.mem_size,
10251
      "disks": self.disks,
10252
      "disk_space_total": disk_space,
10253
      "nics": self.nics,
10254
      "required_nodes": self.required_nodes,
10255
      }
10256
    return request
10257

    
10258
  def _AddRelocateInstance(self):
10259
    """Add relocate instance data to allocator structure.
10260

10261
    This in combination with _IAllocatorGetClusterData will create the
10262
    correct structure needed as input for the allocator.
10263

10264
    The checks for the completeness of the opcode must have already been
10265
    done.
10266

10267
    """
10268
    instance = self.cfg.GetInstanceInfo(self.name)
10269
    if instance is None:
10270
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
10271
                                   " IAllocator" % self.name)
10272

    
10273
    if instance.disk_template not in constants.DTS_NET_MIRROR:
10274
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
10275
                                 errors.ECODE_INVAL)
10276

    
10277
    if len(instance.secondary_nodes) != 1:
10278
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
10279
                                 errors.ECODE_STATE)
10280

    
10281
    self.required_nodes = 1
10282
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
10283
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
10284

    
10285
    request = {
10286
      "name": self.name,
10287
      "disk_space_total": disk_space,
10288
      "required_nodes": self.required_nodes,
10289
      "relocate_from": self.relocate_from,
10290
      }
10291
    return request
10292

    
10293
  def _AddEvacuateNodes(self):
10294
    """Add evacuate nodes data to allocator structure.
10295

10296
    """
10297
    request = {
10298
      "evac_nodes": self.evac_nodes
10299
      }
10300
    return request
10301

    
10302
  def _BuildInputData(self, fn):
10303
    """Build input data structures.
10304

10305
    """
10306
    self._ComputeClusterData()
10307

    
10308
    request = fn()
10309
    request["type"] = self.mode
10310
    self.in_data["request"] = request
10311

    
10312
    self.in_text = serializer.Dump(self.in_data)
10313

    
10314
  def Run(self, name, validate=True, call_fn=None):
10315
    """Run an instance allocator and return the results.
10316

10317
    """
10318
    if call_fn is None:
10319
      call_fn = self.rpc.call_iallocator_runner
10320

    
10321
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
10322
    result.Raise("Failure while running the iallocator script")
10323

    
10324
    self.out_text = result.payload
10325
    if validate:
10326
      self._ValidateResult()
10327

    
10328
  def _ValidateResult(self):
10329
    """Process the allocator results.
10330

10331
    This will process and if successful save the result in
10332
    self.out_data and the other parameters.
10333

10334
    """
10335
    try:
10336
      rdict = serializer.Load(self.out_text)
10337
    except Exception, err:
10338
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
10339

    
10340
    if not isinstance(rdict, dict):
10341
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
10342

    
10343
    # TODO: remove backwards compatiblity in later versions
10344
    if "nodes" in rdict and "result" not in rdict:
10345
      rdict["result"] = rdict["nodes"]
10346
      del rdict["nodes"]
10347

    
10348
    for key in "success", "info", "result":
10349
      if key not in rdict:
10350
        raise errors.OpExecError("Can't parse iallocator results:"
10351
                                 " missing key '%s'" % key)
10352
      setattr(self, key, rdict[key])
10353

    
10354
    if not isinstance(rdict["result"], list):
10355
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
10356
                               " is not a list")
10357
    self.out_data = rdict
10358

    
10359

    
10360
class LUTestAllocator(NoHooksLU):
10361
  """Run allocator tests.
10362

10363
  This LU runs the allocator tests
10364

10365
  """
10366
  _OP_PARAMS = [
10367
    ("direction", _NoDefault, _TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS)),
10368
    ("mode", _NoDefault, _TElemOf(constants.VALID_IALLOCATOR_MODES)),
10369
    ("name", _NoDefault, _TNonEmptyString),
10370
    ("nics", _NoDefault, _TOr(_TNone, _TListOf(
10371
      _TDictOf(_TElemOf(["mac", "ip", "bridge"]),
10372
               _TOr(_TNone, _TNonEmptyString))))),
10373
    ("disks", _NoDefault, _TOr(_TNone, _TList)),
10374
    ("hypervisor", None, _TMaybeString),
10375
    ("allocator", None, _TMaybeString),
10376
    ("tags", _EmptyList, _TListOf(_TNonEmptyString)),
10377
    ("mem_size", None, _TOr(_TNone, _TPositiveInt)),
10378
    ("vcpus", None, _TOr(_TNone, _TPositiveInt)),
10379
    ("os", None, _TMaybeString),
10380
    ("disk_template", None, _TMaybeString),
10381
    ("evac_nodes", None, _TOr(_TNone, _TListOf(_TNonEmptyString))),
10382
    ]
10383

    
10384
  def CheckPrereq(self):
10385
    """Check prerequisites.
10386

10387
    This checks the opcode parameters depending on the director and mode test.
10388

10389
    """
10390
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10391
      for attr in ["mem_size", "disks", "disk_template",
10392
                   "os", "tags", "nics", "vcpus"]:
10393
        if not hasattr(self.op, attr):
10394
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
10395
                                     attr, errors.ECODE_INVAL)
10396
      iname = self.cfg.ExpandInstanceName(self.op.name)
10397
      if iname is not None:
10398
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
10399
                                   iname, errors.ECODE_EXISTS)
10400
      if not isinstance(self.op.nics, list):
10401
        raise errors.OpPrereqError("Invalid parameter 'nics'",
10402
                                   errors.ECODE_INVAL)
10403
      if not isinstance(self.op.disks, list):
10404
        raise errors.OpPrereqError("Invalid parameter 'disks'",
10405
                                   errors.ECODE_INVAL)
10406
      for row in self.op.disks:
10407
        if (not isinstance(row, dict) or
10408
            "size" not in row or
10409
            not isinstance(row["size"], int) or
10410
            "mode" not in row or
10411
            row["mode"] not in ['r', 'w']):
10412
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
10413
                                     " parameter", errors.ECODE_INVAL)
10414
      if self.op.hypervisor is None:
10415
        self.op.hypervisor = self.cfg.GetHypervisorType()
10416
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10417
      fname = _ExpandInstanceName(self.cfg, self.op.name)
10418
      self.op.name = fname
10419
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
10420
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10421
      if not hasattr(self.op, "evac_nodes"):
10422
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
10423
                                   " opcode input", errors.ECODE_INVAL)
10424
    else:
10425
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
10426
                                 self.op.mode, errors.ECODE_INVAL)
10427

    
10428
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
10429
      if self.op.allocator is None:
10430
        raise errors.OpPrereqError("Missing allocator name",
10431
                                   errors.ECODE_INVAL)
10432
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
10433
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
10434
                                 self.op.direction, errors.ECODE_INVAL)
10435

    
10436
  def Exec(self, feedback_fn):
10437
    """Run the allocator test.
10438

10439
    """
10440
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10441
      ial = IAllocator(self.cfg, self.rpc,
10442
                       mode=self.op.mode,
10443
                       name=self.op.name,
10444
                       mem_size=self.op.mem_size,
10445
                       disks=self.op.disks,
10446
                       disk_template=self.op.disk_template,
10447
                       os=self.op.os,
10448
                       tags=self.op.tags,
10449
                       nics=self.op.nics,
10450
                       vcpus=self.op.vcpus,
10451
                       hypervisor=self.op.hypervisor,
10452
                       )
10453
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10454
      ial = IAllocator(self.cfg, self.rpc,
10455
                       mode=self.op.mode,
10456
                       name=self.op.name,
10457
                       relocate_from=list(self.relocate_from),
10458
                       )
10459
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10460
      ial = IAllocator(self.cfg, self.rpc,
10461
                       mode=self.op.mode,
10462
                       evac_nodes=self.op.evac_nodes)
10463
    else:
10464
      raise errors.ProgrammerError("Uncatched mode %s in"
10465
                                   " LUTestAllocator.Exec", self.op.mode)
10466

    
10467
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
10468
      result = ial.in_text
10469
    else:
10470
      ial.Run(self.op.allocator, validate=False)
10471
      result = ial.out_text
10472
    return result