Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 877b849b

History | View | Annotate | Download (379 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
from ganeti import ht
57

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

    
60
# Common opcode attributes
61

    
62
#: output fields for a query operation
63
_POutputFields = ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString))
64

    
65

    
66
#: the shutdown timeout
67
_PShutdownTimeout = ("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
68
                     ht.TPositiveInt)
69

    
70
#: the force parameter
71
_PForce = ("force", False, ht.TBool)
72

    
73
#: a required instance name (for single-instance LUs)
74
_PInstanceName = ("instance_name", ht.NoDefault, ht.TNonEmptyString)
75

    
76
#: Whether to ignore offline nodes
77
_PIgnoreOfflineNodes = ("ignore_offline_nodes", False, ht.TBool)
78

    
79
#: a required node name (for single-node LUs)
80
_PNodeName = ("node_name", ht.NoDefault, ht.TNonEmptyString)
81

    
82
#: the migration type (live/non-live)
83
_PMigrationMode = ("mode", None,
84
                   ht.TOr(ht.TNone, ht.TElemOf(constants.HT_MIGRATION_MODES)))
85

    
86
#: the obsolete 'live' mode (boolean)
87
_PMigrationLive = ("live", None, ht.TMaybeBool)
88

    
89

    
90
# End types
91
class LogicalUnit(object):
92
  """Logical Unit base class.
93

94
  Subclasses must follow these rules:
95
    - implement ExpandNames
96
    - implement CheckPrereq (except when tasklets are used)
97
    - implement Exec (except when tasklets are used)
98
    - implement BuildHooksEnv
99
    - redefine HPATH and HTYPE
100
    - optionally redefine their run requirements:
101
        REQ_BGL: the LU needs to hold the Big Ganeti Lock exclusively
102

103
  Note that all commands require root permissions.
104

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

110
  """
111
  HPATH = None
112
  HTYPE = None
113
  _OP_PARAMS = []
114
  REQ_BGL = True
115

    
116
  def __init__(self, processor, op, context, rpc):
117
    """Constructor for LogicalUnit.
118

119
    This needs to be overridden in derived classes in order to check op
120
    validity.
121

122
    """
123
    self.proc = processor
124
    self.op = op
125
    self.cfg = context.cfg
126
    self.context = context
127
    self.rpc = rpc
128
    # Dicts used to declare locking needs to mcpu
129
    self.needed_locks = None
130
    self.acquired_locks = {}
131
    self.share_locks = dict.fromkeys(locking.LEVELS, 0)
132
    self.add_locks = {}
133
    self.remove_locks = {}
134
    # Used to force good behavior when calling helper functions
135
    self.recalculate_locks = {}
136
    self.__ssh = None
137
    # logging
138
    self.Log = processor.Log # pylint: disable-msg=C0103
139
    self.LogWarning = processor.LogWarning # pylint: disable-msg=C0103
140
    self.LogInfo = processor.LogInfo # pylint: disable-msg=C0103
141
    self.LogStep = processor.LogStep # pylint: disable-msg=C0103
142
    # support for dry-run
143
    self.dry_run_result = None
144
    # support for generic debug attribute
145
    if (not hasattr(self.op, "debug_level") or
146
        not isinstance(self.op.debug_level, int)):
147
      self.op.debug_level = 0
148

    
149
    # Tasklets
150
    self.tasklets = None
151

    
152
    # The new kind-of-type-system
153
    op_id = self.op.OP_ID
154
    for attr_name, aval, test in self._OP_PARAMS:
155
      if not hasattr(op, attr_name):
156
        if aval == ht.NoDefault:
157
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
158
                                     (op_id, attr_name), errors.ECODE_INVAL)
159
        else:
160
          if callable(aval):
161
            dval = aval()
162
          else:
163
            dval = aval
164
          setattr(self.op, attr_name, dval)
165
      attr_val = getattr(op, attr_name)
166
      if test == ht.NoType:
167
        # no tests here
168
        continue
169
      if not callable(test):
170
        raise errors.ProgrammerError("Validation for parameter '%s.%s' failed,"
171
                                     " given type is not a proper type (%s)" %
172
                                     (op_id, attr_name, test))
173
      if not test(attr_val):
174
        logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
175
                      self.op.OP_ID, attr_name, type(attr_val), attr_val)
176
        raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
177
                                   (op_id, attr_name), errors.ECODE_INVAL)
178

    
179
    self.CheckArguments()
180

    
181
  def __GetSSH(self):
182
    """Returns the SshRunner object
183

184
    """
185
    if not self.__ssh:
186
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
187
    return self.__ssh
188

    
189
  ssh = property(fget=__GetSSH)
190

    
191
  def CheckArguments(self):
192
    """Check syntactic validity for the opcode arguments.
193

194
    This method is for doing a simple syntactic check and ensure
195
    validity of opcode parameters, without any cluster-related
196
    checks. While the same can be accomplished in ExpandNames and/or
197
    CheckPrereq, doing these separate is better because:
198

199
      - ExpandNames is left as as purely a lock-related function
200
      - CheckPrereq is run after we have acquired locks (and possible
201
        waited for them)
202

203
    The function is allowed to change the self.op attribute so that
204
    later methods can no longer worry about missing parameters.
205

206
    """
207
    pass
208

    
209
  def ExpandNames(self):
210
    """Expand names for this LU.
211

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

217
    LUs which implement this method must also populate the self.needed_locks
218
    member, as a dict with lock levels as keys, and a list of needed lock names
219
    as values. Rules:
220

221
      - use an empty dict if you don't need any lock
222
      - if you don't need any lock at a particular level omit that level
223
      - don't put anything for the BGL level
224
      - if you want all locks at a level use locking.ALL_SET as a value
225

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

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

234
    Examples::
235

236
      # Acquire all nodes and one instance
237
      self.needed_locks = {
238
        locking.LEVEL_NODE: locking.ALL_SET,
239
        locking.LEVEL_INSTANCE: ['instance1.example.com'],
240
      }
241
      # Acquire just two nodes
242
      self.needed_locks = {
243
        locking.LEVEL_NODE: ['node1.example.com', 'node2.example.com'],
244
      }
245
      # Acquire no locks
246
      self.needed_locks = {} # No, you can't leave it to the default value None
247

248
    """
249
    # The implementation of this method is mandatory only if the new LU is
250
    # concurrent, so that old LUs don't need to be changed all at the same
251
    # time.
252
    if self.REQ_BGL:
253
      self.needed_locks = {} # Exclusive LUs don't need locks.
254
    else:
255
      raise NotImplementedError
256

    
257
  def DeclareLocks(self, level):
258
    """Declare LU locking needs for a level
259

260
    While most LUs can just declare their locking needs at ExpandNames time,
261
    sometimes there's the need to calculate some locks after having acquired
262
    the ones before. This function is called just before acquiring locks at a
263
    particular level, but after acquiring the ones at lower levels, and permits
264
    such calculations. It can be used to modify self.needed_locks, and by
265
    default it does nothing.
266

267
    This function is only called if you have something already set in
268
    self.needed_locks for the level.
269

270
    @param level: Locking level which is going to be locked
271
    @type level: member of ganeti.locking.LEVELS
272

273
    """
274

    
275
  def CheckPrereq(self):
276
    """Check prerequisites for this LU.
277

278
    This method should check that the prerequisites for the execution
279
    of this LU are fulfilled. It can do internode communication, but
280
    it should be idempotent - no cluster or system changes are
281
    allowed.
282

283
    The method should raise errors.OpPrereqError in case something is
284
    not fulfilled. Its return value is ignored.
285

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

289
    """
290
    if self.tasklets is not None:
291
      for (idx, tl) in enumerate(self.tasklets):
292
        logging.debug("Checking prerequisites for tasklet %s/%s",
293
                      idx + 1, len(self.tasklets))
294
        tl.CheckPrereq()
295
    else:
296
      pass
297

    
298
  def Exec(self, feedback_fn):
299
    """Execute the LU.
300

301
    This method should implement the actual work. It should raise
302
    errors.OpExecError for failures that are somewhat dealt with in
303
    code, or expected.
304

305
    """
306
    if self.tasklets is not None:
307
      for (idx, tl) in enumerate(self.tasklets):
308
        logging.debug("Executing tasklet %s/%s", idx + 1, len(self.tasklets))
309
        tl.Exec(feedback_fn)
310
    else:
311
      raise NotImplementedError
312

    
313
  def BuildHooksEnv(self):
314
    """Build hooks environment for this LU.
315

316
    This method should return a three-node tuple consisting of: a dict
317
    containing the environment that will be used for running the
318
    specific hook for this LU, a list of node names on which the hook
319
    should run before the execution, and a list of node names on which
320
    the hook should run after the execution.
321

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

327
    No nodes should be returned as an empty list (and not None).
328

329
    Note that if the HPATH for a LU class is None, this function will
330
    not be called.
331

332
    """
333
    raise NotImplementedError
334

    
335
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
336
    """Notify the LU about the results of its hooks.
337

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

344
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
345
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
346
    @param hook_results: the results of the multi-node hooks rpc call
347
    @param feedback_fn: function used send feedback back to the caller
348
    @param lu_result: the previous Exec result this LU had, or None
349
        in the PRE phase
350
    @return: the new Exec result, based on the previous result
351
        and hook results
352

353
    """
354
    # API must be kept, thus we ignore the unused argument and could
355
    # be a function warnings
356
    # pylint: disable-msg=W0613,R0201
357
    return lu_result
358

    
359
  def _ExpandAndLockInstance(self):
360
    """Helper function to expand and lock an instance.
361

362
    Many LUs that work on an instance take its name in self.op.instance_name
363
    and need to expand it and then declare the expanded name for locking. This
364
    function does it, and then updates self.op.instance_name to the expanded
365
    name. It also initializes needed_locks as a dict, if this hasn't been done
366
    before.
367

368
    """
369
    if self.needed_locks is None:
370
      self.needed_locks = {}
371
    else:
372
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
373
        "_ExpandAndLockInstance called with instance-level locks set"
374
    self.op.instance_name = _ExpandInstanceName(self.cfg,
375
                                                self.op.instance_name)
376
    self.needed_locks[locking.LEVEL_INSTANCE] = self.op.instance_name
377

    
378
  def _LockInstancesNodes(self, primary_only=False):
379
    """Helper function to declare instances' nodes for locking.
380

381
    This function should be called after locking one or more instances to lock
382
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
383
    with all primary or secondary nodes for instances already locked and
384
    present in self.needed_locks[locking.LEVEL_INSTANCE].
385

386
    It should be called from DeclareLocks, and for safety only works if
387
    self.recalculate_locks[locking.LEVEL_NODE] is set.
388

389
    In the future it may grow parameters to just lock some instance's nodes, or
390
    to just lock primaries or secondary nodes, if needed.
391

392
    If should be called in DeclareLocks in a way similar to::
393

394
      if level == locking.LEVEL_NODE:
395
        self._LockInstancesNodes()
396

397
    @type primary_only: boolean
398
    @param primary_only: only lock primary nodes of locked instances
399

400
    """
401
    assert locking.LEVEL_NODE in self.recalculate_locks, \
402
      "_LockInstancesNodes helper function called with no nodes to recalculate"
403

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

    
406
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
407
    # future we might want to have different behaviors depending on the value
408
    # of self.recalculate_locks[locking.LEVEL_NODE]
409
    wanted_nodes = []
410
    for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
411
      instance = self.context.cfg.GetInstanceInfo(instance_name)
412
      wanted_nodes.append(instance.primary_node)
413
      if not primary_only:
414
        wanted_nodes.extend(instance.secondary_nodes)
415

    
416
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
417
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
418
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
419
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
420

    
421
    del self.recalculate_locks[locking.LEVEL_NODE]
422

    
423

    
424
class NoHooksLU(LogicalUnit): # pylint: disable-msg=W0223
425
  """Simple LU which runs no hooks.
426

427
  This LU is intended as a parent for other LogicalUnits which will
428
  run no hooks, in order to reduce duplicate code.
429

430
  """
431
  HPATH = None
432
  HTYPE = None
433

    
434
  def BuildHooksEnv(self):
435
    """Empty BuildHooksEnv for NoHooksLu.
436

437
    This just raises an error.
438

439
    """
440
    assert False, "BuildHooksEnv called for NoHooksLUs"
441

    
442

    
443
class Tasklet:
444
  """Tasklet base class.
445

446
  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
447
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
448
  tasklets know nothing about locks.
449

450
  Subclasses must follow these rules:
451
    - Implement CheckPrereq
452
    - Implement Exec
453

454
  """
455
  def __init__(self, lu):
456
    self.lu = lu
457

    
458
    # Shortcuts
459
    self.cfg = lu.cfg
460
    self.rpc = lu.rpc
461

    
462
  def CheckPrereq(self):
463
    """Check prerequisites for this tasklets.
464

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

469
    The method should raise errors.OpPrereqError in case something is not
470
    fulfilled. Its return value is ignored.
471

472
    This method should also update all parameters to their canonical form if it
473
    hasn't been done before.
474

475
    """
476
    pass
477

    
478
  def Exec(self, feedback_fn):
479
    """Execute the tasklet.
480

481
    This method should implement the actual work. It should raise
482
    errors.OpExecError for failures that are somewhat dealt with in code, or
483
    expected.
484

485
    """
486
    raise NotImplementedError
487

    
488

    
489
def _GetWantedNodes(lu, nodes):
490
  """Returns list of checked and expanded node names.
491

492
  @type lu: L{LogicalUnit}
493
  @param lu: the logical unit on whose behalf we execute
494
  @type nodes: list
495
  @param nodes: list of node names or None for all nodes
496
  @rtype: list
497
  @return: the list of nodes, sorted
498
  @raise errors.ProgrammerError: if the nodes parameter is wrong type
499

500
  """
501
  if not nodes:
502
    raise errors.ProgrammerError("_GetWantedNodes should only be called with a"
503
      " non-empty list of nodes whose name is to be expanded.")
504

    
505
  wanted = [_ExpandNodeName(lu.cfg, name) for name in nodes]
506
  return utils.NiceSort(wanted)
507

    
508

    
509
def _GetWantedInstances(lu, instances):
510
  """Returns list of checked and expanded instance names.
511

512
  @type lu: L{LogicalUnit}
513
  @param lu: the logical unit on whose behalf we execute
514
  @type instances: list
515
  @param instances: list of instance names or None for all instances
516
  @rtype: list
517
  @return: the list of instances, sorted
518
  @raise errors.OpPrereqError: if the instances parameter is wrong type
519
  @raise errors.OpPrereqError: if any of the passed instances is not found
520

521
  """
522
  if instances:
523
    wanted = [_ExpandInstanceName(lu.cfg, name) for name in instances]
524
  else:
525
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
526
  return wanted
527

    
528

    
529
def _GetUpdatedParams(old_params, update_dict,
530
                      use_default=True, use_none=False):
531
  """Return the new version of a parameter dictionary.
532

533
  @type old_params: dict
534
  @param old_params: old parameters
535
  @type update_dict: dict
536
  @param update_dict: dict containing new parameter values, or
537
      constants.VALUE_DEFAULT to reset the parameter to its default
538
      value
539
  @param use_default: boolean
540
  @type use_default: whether to recognise L{constants.VALUE_DEFAULT}
541
      values as 'to be deleted' values
542
  @param use_none: boolean
543
  @type use_none: whether to recognise C{None} values as 'to be
544
      deleted' values
545
  @rtype: dict
546
  @return: the new parameter dictionary
547

548
  """
549
  params_copy = copy.deepcopy(old_params)
550
  for key, val in update_dict.iteritems():
551
    if ((use_default and val == constants.VALUE_DEFAULT) or
552
        (use_none and val is None)):
553
      try:
554
        del params_copy[key]
555
      except KeyError:
556
        pass
557
    else:
558
      params_copy[key] = val
559
  return params_copy
560

    
561

    
562
def _CheckOutputFields(static, dynamic, selected):
563
  """Checks whether all selected fields are valid.
564

565
  @type static: L{utils.FieldSet}
566
  @param static: static fields set
567
  @type dynamic: L{utils.FieldSet}
568
  @param dynamic: dynamic fields set
569

570
  """
571
  f = utils.FieldSet()
572
  f.Extend(static)
573
  f.Extend(dynamic)
574

    
575
  delta = f.NonMatching(selected)
576
  if delta:
577
    raise errors.OpPrereqError("Unknown output fields selected: %s"
578
                               % ",".join(delta), errors.ECODE_INVAL)
579

    
580

    
581
def _CheckGlobalHvParams(params):
582
  """Validates that given hypervisor params are not global ones.
583

584
  This will ensure that instances don't get customised versions of
585
  global params.
586

587
  """
588
  used_globals = constants.HVC_GLOBALS.intersection(params)
589
  if used_globals:
590
    msg = ("The following hypervisor parameters are global and cannot"
591
           " be customized at instance level, please modify them at"
592
           " cluster level: %s" % utils.CommaJoin(used_globals))
593
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
594

    
595

    
596
def _CheckNodeOnline(lu, node):
597
  """Ensure that a given node is online.
598

599
  @param lu: the LU on behalf of which we make the check
600
  @param node: the node to check
601
  @raise errors.OpPrereqError: if the node is offline
602

603
  """
604
  if lu.cfg.GetNodeInfo(node).offline:
605
    raise errors.OpPrereqError("Can't use offline node %s" % node,
606
                               errors.ECODE_STATE)
607

    
608

    
609
def _CheckNodeNotDrained(lu, node):
610
  """Ensure that a given node is not drained.
611

612
  @param lu: the LU on behalf of which we make the check
613
  @param node: the node to check
614
  @raise errors.OpPrereqError: if the node is drained
615

616
  """
617
  if lu.cfg.GetNodeInfo(node).drained:
618
    raise errors.OpPrereqError("Can't use drained node %s" % node,
619
                               errors.ECODE_STATE)
620

    
621

    
622
def _CheckNodeVmCapable(lu, node):
623
  """Ensure that a given node is vm capable.
624

625
  @param lu: the LU on behalf of which we make the check
626
  @param node: the node to check
627
  @raise errors.OpPrereqError: if the node is not vm capable
628

629
  """
630
  if not lu.cfg.GetNodeInfo(node).vm_capable:
631
    raise errors.OpPrereqError("Can't use non-vm_capable node %s" % node,
632
                               errors.ECODE_STATE)
633

    
634

    
635
def _CheckNodeHasOS(lu, node, os_name, force_variant):
636
  """Ensure that a node supports a given OS.
637

638
  @param lu: the LU on behalf of which we make the check
639
  @param node: the node to check
640
  @param os_name: the OS to query about
641
  @param force_variant: whether to ignore variant errors
642
  @raise errors.OpPrereqError: if the node is not supporting the OS
643

644
  """
645
  result = lu.rpc.call_os_get(node, os_name)
646
  result.Raise("OS '%s' not in supported OS list for node %s" %
647
               (os_name, node),
648
               prereq=True, ecode=errors.ECODE_INVAL)
649
  if not force_variant:
650
    _CheckOSVariant(result.payload, os_name)
651

    
652

    
653
def _RequireFileStorage():
654
  """Checks that file storage is enabled.
655

656
  @raise errors.OpPrereqError: when file storage is disabled
657

658
  """
659
  if not constants.ENABLE_FILE_STORAGE:
660
    raise errors.OpPrereqError("File storage disabled at configure time",
661
                               errors.ECODE_INVAL)
662

    
663

    
664
def _CheckDiskTemplate(template):
665
  """Ensure a given disk template is valid.
666

667
  """
668
  if template not in constants.DISK_TEMPLATES:
669
    msg = ("Invalid disk template name '%s', valid templates are: %s" %
670
           (template, utils.CommaJoin(constants.DISK_TEMPLATES)))
671
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
672
  if template == constants.DT_FILE:
673
    _RequireFileStorage()
674
  return True
675

    
676

    
677
def _CheckStorageType(storage_type):
678
  """Ensure a given storage type is valid.
679

680
  """
681
  if storage_type not in constants.VALID_STORAGE_TYPES:
682
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
683
                               errors.ECODE_INVAL)
684
  if storage_type == constants.ST_FILE:
685
    _RequireFileStorage()
686
  return True
687

    
688

    
689
def _GetClusterDomainSecret():
690
  """Reads the cluster domain secret.
691

692
  """
693
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
694
                               strict=True)
695

    
696

    
697
def _CheckInstanceDown(lu, instance, reason):
698
  """Ensure that an instance is not running."""
699
  if instance.admin_up:
700
    raise errors.OpPrereqError("Instance %s is marked to be up, %s" %
701
                               (instance.name, reason), errors.ECODE_STATE)
702

    
703
  pnode = instance.primary_node
704
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
705
  ins_l.Raise("Can't contact node %s for instance information" % pnode,
706
              prereq=True, ecode=errors.ECODE_ENVIRON)
707

    
708
  if instance.name in ins_l.payload:
709
    raise errors.OpPrereqError("Instance %s is running, %s" %
710
                               (instance.name, reason), errors.ECODE_STATE)
711

    
712

    
713
def _ExpandItemName(fn, name, kind):
714
  """Expand an item name.
715

716
  @param fn: the function to use for expansion
717
  @param name: requested item name
718
  @param kind: text description ('Node' or 'Instance')
719
  @return: the resolved (full) name
720
  @raise errors.OpPrereqError: if the item is not found
721

722
  """
723
  full_name = fn(name)
724
  if full_name is None:
725
    raise errors.OpPrereqError("%s '%s' not known" % (kind, name),
726
                               errors.ECODE_NOENT)
727
  return full_name
728

    
729

    
730
def _ExpandNodeName(cfg, name):
731
  """Wrapper over L{_ExpandItemName} for nodes."""
732
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
733

    
734

    
735
def _ExpandInstanceName(cfg, name):
736
  """Wrapper over L{_ExpandItemName} for instance."""
737
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
738

    
739

    
740
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
741
                          memory, vcpus, nics, disk_template, disks,
742
                          bep, hvp, hypervisor_name):
743
  """Builds instance related env variables for hooks
744

745
  This builds the hook environment from individual variables.
746

747
  @type name: string
748
  @param name: the name of the instance
749
  @type primary_node: string
750
  @param primary_node: the name of the instance's primary node
751
  @type secondary_nodes: list
752
  @param secondary_nodes: list of secondary nodes as strings
753
  @type os_type: string
754
  @param os_type: the name of the instance's OS
755
  @type status: boolean
756
  @param status: the should_run status of the instance
757
  @type memory: string
758
  @param memory: the memory size of the instance
759
  @type vcpus: string
760
  @param vcpus: the count of VCPUs the instance has
761
  @type nics: list
762
  @param nics: list of tuples (ip, mac, mode, link) representing
763
      the NICs the instance has
764
  @type disk_template: string
765
  @param disk_template: the disk template of the instance
766
  @type disks: list
767
  @param disks: the list of (size, mode) pairs
768
  @type bep: dict
769
  @param bep: the backend parameters for the instance
770
  @type hvp: dict
771
  @param hvp: the hypervisor parameters for the instance
772
  @type hypervisor_name: string
773
  @param hypervisor_name: the hypervisor for the instance
774
  @rtype: dict
775
  @return: the hook environment for this instance
776

777
  """
778
  if status:
779
    str_status = "up"
780
  else:
781
    str_status = "down"
782
  env = {
783
    "OP_TARGET": name,
784
    "INSTANCE_NAME": name,
785
    "INSTANCE_PRIMARY": primary_node,
786
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
787
    "INSTANCE_OS_TYPE": os_type,
788
    "INSTANCE_STATUS": str_status,
789
    "INSTANCE_MEMORY": memory,
790
    "INSTANCE_VCPUS": vcpus,
791
    "INSTANCE_DISK_TEMPLATE": disk_template,
792
    "INSTANCE_HYPERVISOR": hypervisor_name,
793
  }
794

    
795
  if nics:
796
    nic_count = len(nics)
797
    for idx, (ip, mac, mode, link) in enumerate(nics):
798
      if ip is None:
799
        ip = ""
800
      env["INSTANCE_NIC%d_IP" % idx] = ip
801
      env["INSTANCE_NIC%d_MAC" % idx] = mac
802
      env["INSTANCE_NIC%d_MODE" % idx] = mode
803
      env["INSTANCE_NIC%d_LINK" % idx] = link
804
      if mode == constants.NIC_MODE_BRIDGED:
805
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
806
  else:
807
    nic_count = 0
808

    
809
  env["INSTANCE_NIC_COUNT"] = nic_count
810

    
811
  if disks:
812
    disk_count = len(disks)
813
    for idx, (size, mode) in enumerate(disks):
814
      env["INSTANCE_DISK%d_SIZE" % idx] = size
815
      env["INSTANCE_DISK%d_MODE" % idx] = mode
816
  else:
817
    disk_count = 0
818

    
819
  env["INSTANCE_DISK_COUNT"] = disk_count
820

    
821
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
822
    for key, value in source.items():
823
      env["INSTANCE_%s_%s" % (kind, key)] = value
824

    
825
  return env
826

    
827

    
828
def _NICListToTuple(lu, nics):
829
  """Build a list of nic information tuples.
830

831
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
832
  value in LUQueryInstanceData.
833

834
  @type lu:  L{LogicalUnit}
835
  @param lu: the logical unit on whose behalf we execute
836
  @type nics: list of L{objects.NIC}
837
  @param nics: list of nics to convert to hooks tuples
838

839
  """
840
  hooks_nics = []
841
  cluster = lu.cfg.GetClusterInfo()
842
  for nic in nics:
843
    ip = nic.ip
844
    mac = nic.mac
845
    filled_params = cluster.SimpleFillNIC(nic.nicparams)
846
    mode = filled_params[constants.NIC_MODE]
847
    link = filled_params[constants.NIC_LINK]
848
    hooks_nics.append((ip, mac, mode, link))
849
  return hooks_nics
850

    
851

    
852
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
853
  """Builds instance related env variables for hooks from an object.
854

855
  @type lu: L{LogicalUnit}
856
  @param lu: the logical unit on whose behalf we execute
857
  @type instance: L{objects.Instance}
858
  @param instance: the instance for which we should build the
859
      environment
860
  @type override: dict
861
  @param override: dictionary with key/values that will override
862
      our values
863
  @rtype: dict
864
  @return: the hook environment dictionary
865

866
  """
867
  cluster = lu.cfg.GetClusterInfo()
868
  bep = cluster.FillBE(instance)
869
  hvp = cluster.FillHV(instance)
870
  args = {
871
    'name': instance.name,
872
    'primary_node': instance.primary_node,
873
    'secondary_nodes': instance.secondary_nodes,
874
    'os_type': instance.os,
875
    'status': instance.admin_up,
876
    'memory': bep[constants.BE_MEMORY],
877
    'vcpus': bep[constants.BE_VCPUS],
878
    'nics': _NICListToTuple(lu, instance.nics),
879
    'disk_template': instance.disk_template,
880
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
881
    'bep': bep,
882
    'hvp': hvp,
883
    'hypervisor_name': instance.hypervisor,
884
  }
885
  if override:
886
    args.update(override)
887
  return _BuildInstanceHookEnv(**args) # pylint: disable-msg=W0142
888

    
889

    
890
def _AdjustCandidatePool(lu, exceptions):
891
  """Adjust the candidate pool after node operations.
892

893
  """
894
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
895
  if mod_list:
896
    lu.LogInfo("Promoted nodes to master candidate role: %s",
897
               utils.CommaJoin(node.name for node in mod_list))
898
    for name in mod_list:
899
      lu.context.ReaddNode(name)
900
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
901
  if mc_now > mc_max:
902
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
903
               (mc_now, mc_max))
904

    
905

    
906
def _DecideSelfPromotion(lu, exceptions=None):
907
  """Decide whether I should promote myself as a master candidate.
908

909
  """
910
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
911
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
912
  # the new node will increase mc_max with one, so:
913
  mc_should = min(mc_should + 1, cp_size)
914
  return mc_now < mc_should
915

    
916

    
917
def _CheckNicsBridgesExist(lu, target_nics, target_node):
918
  """Check that the brigdes needed by a list of nics exist.
919

920
  """
921
  cluster = lu.cfg.GetClusterInfo()
922
  paramslist = [cluster.SimpleFillNIC(nic.nicparams) for nic in target_nics]
923
  brlist = [params[constants.NIC_LINK] for params in paramslist
924
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
925
  if brlist:
926
    result = lu.rpc.call_bridges_exist(target_node, brlist)
927
    result.Raise("Error checking bridges on destination node '%s'" %
928
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
929

    
930

    
931
def _CheckInstanceBridgesExist(lu, instance, node=None):
932
  """Check that the brigdes needed by an instance exist.
933

934
  """
935
  if node is None:
936
    node = instance.primary_node
937
  _CheckNicsBridgesExist(lu, instance.nics, node)
938

    
939

    
940
def _CheckOSVariant(os_obj, name):
941
  """Check whether an OS name conforms to the os variants specification.
942

943
  @type os_obj: L{objects.OS}
944
  @param os_obj: OS object to check
945
  @type name: string
946
  @param name: OS name passed by the user, to check for validity
947

948
  """
949
  if not os_obj.supported_variants:
950
    return
951
  variant = objects.OS.GetVariant(name)
952
  if not variant:
953
    raise errors.OpPrereqError("OS name must include a variant",
954
                               errors.ECODE_INVAL)
955

    
956
  if variant not in os_obj.supported_variants:
957
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
958

    
959

    
960
def _GetNodeInstancesInner(cfg, fn):
961
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
962

    
963

    
964
def _GetNodeInstances(cfg, node_name):
965
  """Returns a list of all primary and secondary instances on a node.
966

967
  """
968

    
969
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
970

    
971

    
972
def _GetNodePrimaryInstances(cfg, node_name):
973
  """Returns primary instances on a node.
974

975
  """
976
  return _GetNodeInstancesInner(cfg,
977
                                lambda inst: node_name == inst.primary_node)
978

    
979

    
980
def _GetNodeSecondaryInstances(cfg, node_name):
981
  """Returns secondary instances on a node.
982

983
  """
984
  return _GetNodeInstancesInner(cfg,
985
                                lambda inst: node_name in inst.secondary_nodes)
986

    
987

    
988
def _GetStorageTypeArgs(cfg, storage_type):
989
  """Returns the arguments for a storage type.
990

991
  """
992
  # Special case for file storage
993
  if storage_type == constants.ST_FILE:
994
    # storage.FileStorage wants a list of storage directories
995
    return [[cfg.GetFileStorageDir()]]
996

    
997
  return []
998

    
999

    
1000
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
1001
  faulty = []
1002

    
1003
  for dev in instance.disks:
1004
    cfg.SetDiskID(dev, node_name)
1005

    
1006
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
1007
  result.Raise("Failed to get disk status from node %s" % node_name,
1008
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
1009

    
1010
  for idx, bdev_status in enumerate(result.payload):
1011
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
1012
      faulty.append(idx)
1013

    
1014
  return faulty
1015

    
1016

    
1017
def _CheckIAllocatorOrNode(lu, iallocator_slot, node_slot):
1018
  """Check the sanity of iallocator and node arguments and use the
1019
  cluster-wide iallocator if appropriate.
1020

1021
  Check that at most one of (iallocator, node) is specified. If none is
1022
  specified, then the LU's opcode's iallocator slot is filled with the
1023
  cluster-wide default iallocator.
1024

1025
  @type iallocator_slot: string
1026
  @param iallocator_slot: the name of the opcode iallocator slot
1027
  @type node_slot: string
1028
  @param node_slot: the name of the opcode target node slot
1029

1030
  """
1031
  node = getattr(lu.op, node_slot, None)
1032
  iallocator = getattr(lu.op, iallocator_slot, None)
1033

    
1034
  if node is not None and iallocator is not None:
1035
    raise errors.OpPrereqError("Do not specify both, iallocator and node.",
1036
                               errors.ECODE_INVAL)
1037
  elif node is None and iallocator is None:
1038
    default_iallocator = lu.cfg.GetDefaultIAllocator()
1039
    if default_iallocator:
1040
      setattr(lu.op, iallocator_slot, default_iallocator)
1041
    else:
1042
      raise errors.OpPrereqError("No iallocator or node given and no"
1043
                                 " cluster-wide default iallocator found."
1044
                                 " Please specify either an iallocator or a"
1045
                                 " node, or set a cluster-wide default"
1046
                                 " iallocator.")
1047

    
1048

    
1049
class LUPostInitCluster(LogicalUnit):
1050
  """Logical unit for running hooks after cluster initialization.
1051

1052
  """
1053
  HPATH = "cluster-init"
1054
  HTYPE = constants.HTYPE_CLUSTER
1055

    
1056
  def BuildHooksEnv(self):
1057
    """Build hooks env.
1058

1059
    """
1060
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1061
    mn = self.cfg.GetMasterNode()
1062
    return env, [], [mn]
1063

    
1064
  def Exec(self, feedback_fn):
1065
    """Nothing to do.
1066

1067
    """
1068
    return True
1069

    
1070

    
1071
class LUDestroyCluster(LogicalUnit):
1072
  """Logical unit for destroying the cluster.
1073

1074
  """
1075
  HPATH = "cluster-destroy"
1076
  HTYPE = constants.HTYPE_CLUSTER
1077

    
1078
  def BuildHooksEnv(self):
1079
    """Build hooks env.
1080

1081
    """
1082
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1083
    return env, [], []
1084

    
1085
  def CheckPrereq(self):
1086
    """Check prerequisites.
1087

1088
    This checks whether the cluster is empty.
1089

1090
    Any errors are signaled by raising errors.OpPrereqError.
1091

1092
    """
1093
    master = self.cfg.GetMasterNode()
1094

    
1095
    nodelist = self.cfg.GetNodeList()
1096
    if len(nodelist) != 1 or nodelist[0] != master:
1097
      raise errors.OpPrereqError("There are still %d node(s) in"
1098
                                 " this cluster." % (len(nodelist) - 1),
1099
                                 errors.ECODE_INVAL)
1100
    instancelist = self.cfg.GetInstanceList()
1101
    if instancelist:
1102
      raise errors.OpPrereqError("There are still %d instance(s) in"
1103
                                 " this cluster." % len(instancelist),
1104
                                 errors.ECODE_INVAL)
1105

    
1106
  def Exec(self, feedback_fn):
1107
    """Destroys the cluster.
1108

1109
    """
1110
    master = self.cfg.GetMasterNode()
1111

    
1112
    # Run post hooks on master node before it's removed
1113
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
1114
    try:
1115
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
1116
    except:
1117
      # pylint: disable-msg=W0702
1118
      self.LogWarning("Errors occurred running hooks on %s" % master)
1119

    
1120
    result = self.rpc.call_node_stop_master(master, False)
1121
    result.Raise("Could not disable the master role")
1122

    
1123
    return master
1124

    
1125

    
1126
def _VerifyCertificate(filename):
1127
  """Verifies a certificate for LUVerifyCluster.
1128

1129
  @type filename: string
1130
  @param filename: Path to PEM file
1131

1132
  """
1133
  try:
1134
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1135
                                           utils.ReadFile(filename))
1136
  except Exception, err: # pylint: disable-msg=W0703
1137
    return (LUVerifyCluster.ETYPE_ERROR,
1138
            "Failed to load X509 certificate %s: %s" % (filename, err))
1139

    
1140
  (errcode, msg) = \
1141
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1142
                                constants.SSL_CERT_EXPIRATION_ERROR)
1143

    
1144
  if msg:
1145
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1146
  else:
1147
    fnamemsg = None
1148

    
1149
  if errcode is None:
1150
    return (None, fnamemsg)
1151
  elif errcode == utils.CERT_WARNING:
1152
    return (LUVerifyCluster.ETYPE_WARNING, fnamemsg)
1153
  elif errcode == utils.CERT_ERROR:
1154
    return (LUVerifyCluster.ETYPE_ERROR, fnamemsg)
1155

    
1156
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1157

    
1158

    
1159
class LUVerifyCluster(LogicalUnit):
1160
  """Verifies the cluster status.
1161

1162
  """
1163
  HPATH = "cluster-verify"
1164
  HTYPE = constants.HTYPE_CLUSTER
1165
  _OP_PARAMS = [
1166
    ("skip_checks", ht.EmptyList,
1167
     ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS))),
1168
    ("verbose", False, ht.TBool),
1169
    ("error_codes", False, ht.TBool),
1170
    ("debug_simulate_errors", False, ht.TBool),
1171
    ]
1172
  REQ_BGL = False
1173

    
1174
  TCLUSTER = "cluster"
1175
  TNODE = "node"
1176
  TINSTANCE = "instance"
1177

    
1178
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1179
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1180
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1181
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1182
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1183
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1184
  EINSTANCEFAULTYDISK = (TINSTANCE, "EINSTANCEFAULTYDISK")
1185
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1186
  ENODEDRBD = (TNODE, "ENODEDRBD")
1187
  ENODEDRBDHELPER = (TNODE, "ENODEDRBDHELPER")
1188
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1189
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1190
  ENODEHV = (TNODE, "ENODEHV")
1191
  ENODELVM = (TNODE, "ENODELVM")
1192
  ENODEN1 = (TNODE, "ENODEN1")
1193
  ENODENET = (TNODE, "ENODENET")
1194
  ENODEOS = (TNODE, "ENODEOS")
1195
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1196
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1197
  ENODERPC = (TNODE, "ENODERPC")
1198
  ENODESSH = (TNODE, "ENODESSH")
1199
  ENODEVERSION = (TNODE, "ENODEVERSION")
1200
  ENODESETUP = (TNODE, "ENODESETUP")
1201
  ENODETIME = (TNODE, "ENODETIME")
1202

    
1203
  ETYPE_FIELD = "code"
1204
  ETYPE_ERROR = "ERROR"
1205
  ETYPE_WARNING = "WARNING"
1206

    
1207
  class NodeImage(object):
1208
    """A class representing the logical and physical status of a node.
1209

1210
    @type name: string
1211
    @ivar name: the node name to which this object refers
1212
    @ivar volumes: a structure as returned from
1213
        L{ganeti.backend.GetVolumeList} (runtime)
1214
    @ivar instances: a list of running instances (runtime)
1215
    @ivar pinst: list of configured primary instances (config)
1216
    @ivar sinst: list of configured secondary instances (config)
1217
    @ivar sbp: diction of {secondary-node: list of instances} of all peers
1218
        of this node (config)
1219
    @ivar mfree: free memory, as reported by hypervisor (runtime)
1220
    @ivar dfree: free disk, as reported by the node (runtime)
1221
    @ivar offline: the offline status (config)
1222
    @type rpc_fail: boolean
1223
    @ivar rpc_fail: whether the RPC verify call was successfull (overall,
1224
        not whether the individual keys were correct) (runtime)
1225
    @type lvm_fail: boolean
1226
    @ivar lvm_fail: whether the RPC call didn't return valid LVM data
1227
    @type hyp_fail: boolean
1228
    @ivar hyp_fail: whether the RPC call didn't return the instance list
1229
    @type ghost: boolean
1230
    @ivar ghost: whether this is a known node or not (config)
1231
    @type os_fail: boolean
1232
    @ivar os_fail: whether the RPC call didn't return valid OS data
1233
    @type oslist: list
1234
    @ivar oslist: list of OSes as diagnosed by DiagnoseOS
1235
    @type vm_capable: boolean
1236
    @ivar vm_capable: whether the node can host instances
1237

1238
    """
1239
    def __init__(self, offline=False, name=None, vm_capable=True):
1240
      self.name = name
1241
      self.volumes = {}
1242
      self.instances = []
1243
      self.pinst = []
1244
      self.sinst = []
1245
      self.sbp = {}
1246
      self.mfree = 0
1247
      self.dfree = 0
1248
      self.offline = offline
1249
      self.vm_capable = vm_capable
1250
      self.rpc_fail = False
1251
      self.lvm_fail = False
1252
      self.hyp_fail = False
1253
      self.ghost = False
1254
      self.os_fail = False
1255
      self.oslist = {}
1256

    
1257
  def ExpandNames(self):
1258
    self.needed_locks = {
1259
      locking.LEVEL_NODE: locking.ALL_SET,
1260
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1261
    }
1262
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1263

    
1264
  def _Error(self, ecode, item, msg, *args, **kwargs):
1265
    """Format an error message.
1266

1267
    Based on the opcode's error_codes parameter, either format a
1268
    parseable error code, or a simpler error string.
1269

1270
    This must be called only from Exec and functions called from Exec.
1271

1272
    """
1273
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1274
    itype, etxt = ecode
1275
    # first complete the msg
1276
    if args:
1277
      msg = msg % args
1278
    # then format the whole message
1279
    if self.op.error_codes:
1280
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1281
    else:
1282
      if item:
1283
        item = " " + item
1284
      else:
1285
        item = ""
1286
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1287
    # and finally report it via the feedback_fn
1288
    self._feedback_fn("  - %s" % msg)
1289

    
1290
  def _ErrorIf(self, cond, *args, **kwargs):
1291
    """Log an error message if the passed condition is True.
1292

1293
    """
1294
    cond = bool(cond) or self.op.debug_simulate_errors
1295
    if cond:
1296
      self._Error(*args, **kwargs)
1297
    # do not mark the operation as failed for WARN cases only
1298
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1299
      self.bad = self.bad or cond
1300

    
1301
  def _VerifyNode(self, ninfo, nresult):
1302
    """Perform some basic validation on data returned from a node.
1303

1304
      - check the result data structure is well formed and has all the
1305
        mandatory fields
1306
      - check ganeti version
1307

1308
    @type ninfo: L{objects.Node}
1309
    @param ninfo: the node to check
1310
    @param nresult: the results from the node
1311
    @rtype: boolean
1312
    @return: whether overall this call was successful (and we can expect
1313
         reasonable values in the respose)
1314

1315
    """
1316
    node = ninfo.name
1317
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1318

    
1319
    # main result, nresult should be a non-empty dict
1320
    test = not nresult or not isinstance(nresult, dict)
1321
    _ErrorIf(test, self.ENODERPC, node,
1322
                  "unable to verify node: no data returned")
1323
    if test:
1324
      return False
1325

    
1326
    # compares ganeti version
1327
    local_version = constants.PROTOCOL_VERSION
1328
    remote_version = nresult.get("version", None)
1329
    test = not (remote_version and
1330
                isinstance(remote_version, (list, tuple)) and
1331
                len(remote_version) == 2)
1332
    _ErrorIf(test, self.ENODERPC, node,
1333
             "connection to node returned invalid data")
1334
    if test:
1335
      return False
1336

    
1337
    test = local_version != remote_version[0]
1338
    _ErrorIf(test, self.ENODEVERSION, node,
1339
             "incompatible protocol versions: master %s,"
1340
             " node %s", local_version, remote_version[0])
1341
    if test:
1342
      return False
1343

    
1344
    # node seems compatible, we can actually try to look into its results
1345

    
1346
    # full package version
1347
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1348
                  self.ENODEVERSION, node,
1349
                  "software version mismatch: master %s, node %s",
1350
                  constants.RELEASE_VERSION, remote_version[1],
1351
                  code=self.ETYPE_WARNING)
1352

    
1353
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1354
    if ninfo.vm_capable and isinstance(hyp_result, dict):
1355
      for hv_name, hv_result in hyp_result.iteritems():
1356
        test = hv_result is not None
1357
        _ErrorIf(test, self.ENODEHV, node,
1358
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1359

    
1360
    test = nresult.get(constants.NV_NODESETUP,
1361
                           ["Missing NODESETUP results"])
1362
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1363
             "; ".join(test))
1364

    
1365
    return True
1366

    
1367
  def _VerifyNodeTime(self, ninfo, nresult,
1368
                      nvinfo_starttime, nvinfo_endtime):
1369
    """Check the node time.
1370

1371
    @type ninfo: L{objects.Node}
1372
    @param ninfo: the node to check
1373
    @param nresult: the remote results for the node
1374
    @param nvinfo_starttime: the start time of the RPC call
1375
    @param nvinfo_endtime: the end time of the RPC call
1376

1377
    """
1378
    node = ninfo.name
1379
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1380

    
1381
    ntime = nresult.get(constants.NV_TIME, None)
1382
    try:
1383
      ntime_merged = utils.MergeTime(ntime)
1384
    except (ValueError, TypeError):
1385
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1386
      return
1387

    
1388
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1389
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1390
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1391
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1392
    else:
1393
      ntime_diff = None
1394

    
1395
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1396
             "Node time diverges by at least %s from master node time",
1397
             ntime_diff)
1398

    
1399
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1400
    """Check the node time.
1401

1402
    @type ninfo: L{objects.Node}
1403
    @param ninfo: the node to check
1404
    @param nresult: the remote results for the node
1405
    @param vg_name: the configured VG name
1406

1407
    """
1408
    if vg_name is None:
1409
      return
1410

    
1411
    node = ninfo.name
1412
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1413

    
1414
    # checks vg existence and size > 20G
1415
    vglist = nresult.get(constants.NV_VGLIST, None)
1416
    test = not vglist
1417
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1418
    if not test:
1419
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1420
                                            constants.MIN_VG_SIZE)
1421
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1422

    
1423
    # check pv names
1424
    pvlist = nresult.get(constants.NV_PVLIST, None)
1425
    test = pvlist is None
1426
    _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1427
    if not test:
1428
      # check that ':' is not present in PV names, since it's a
1429
      # special character for lvcreate (denotes the range of PEs to
1430
      # use on the PV)
1431
      for _, pvname, owner_vg in pvlist:
1432
        test = ":" in pvname
1433
        _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1434
                 " '%s' of VG '%s'", pvname, owner_vg)
1435

    
1436
  def _VerifyNodeNetwork(self, ninfo, nresult):
1437
    """Check the node time.
1438

1439
    @type ninfo: L{objects.Node}
1440
    @param ninfo: the node to check
1441
    @param nresult: the remote results for the node
1442

1443
    """
1444
    node = ninfo.name
1445
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1446

    
1447
    test = constants.NV_NODELIST not in nresult
1448
    _ErrorIf(test, self.ENODESSH, node,
1449
             "node hasn't returned node ssh connectivity data")
1450
    if not test:
1451
      if nresult[constants.NV_NODELIST]:
1452
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1453
          _ErrorIf(True, self.ENODESSH, node,
1454
                   "ssh communication with node '%s': %s", a_node, a_msg)
1455

    
1456
    test = constants.NV_NODENETTEST not in nresult
1457
    _ErrorIf(test, self.ENODENET, node,
1458
             "node hasn't returned node tcp connectivity data")
1459
    if not test:
1460
      if nresult[constants.NV_NODENETTEST]:
1461
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1462
        for anode in nlist:
1463
          _ErrorIf(True, self.ENODENET, node,
1464
                   "tcp communication with node '%s': %s",
1465
                   anode, nresult[constants.NV_NODENETTEST][anode])
1466

    
1467
    test = constants.NV_MASTERIP not in nresult
1468
    _ErrorIf(test, self.ENODENET, node,
1469
             "node hasn't returned node master IP reachability data")
1470
    if not test:
1471
      if not nresult[constants.NV_MASTERIP]:
1472
        if node == self.master_node:
1473
          msg = "the master node cannot reach the master IP (not configured?)"
1474
        else:
1475
          msg = "cannot reach the master IP"
1476
        _ErrorIf(True, self.ENODENET, node, msg)
1477

    
1478
  def _VerifyInstance(self, instance, instanceconfig, node_image,
1479
                      diskstatus):
1480
    """Verify an instance.
1481

1482
    This function checks to see if the required block devices are
1483
    available on the instance's node.
1484

1485
    """
1486
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1487
    node_current = instanceconfig.primary_node
1488

    
1489
    node_vol_should = {}
1490
    instanceconfig.MapLVsByNode(node_vol_should)
1491

    
1492
    for node in node_vol_should:
1493
      n_img = node_image[node]
1494
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1495
        # ignore missing volumes on offline or broken nodes
1496
        continue
1497
      for volume in node_vol_should[node]:
1498
        test = volume not in n_img.volumes
1499
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1500
                 "volume %s missing on node %s", volume, node)
1501

    
1502
    if instanceconfig.admin_up:
1503
      pri_img = node_image[node_current]
1504
      test = instance not in pri_img.instances and not pri_img.offline
1505
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1506
               "instance not running on its primary node %s",
1507
               node_current)
1508

    
1509
    for node, n_img in node_image.items():
1510
      if (not node == node_current):
1511
        test = instance in n_img.instances
1512
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1513
                 "instance should not run on node %s", node)
1514

    
1515
    diskdata = [(nname, disk, idx)
1516
                for (nname, disks) in diskstatus.items()
1517
                for idx, disk in enumerate(disks)]
1518

    
1519
    for nname, bdev_status, idx in diskdata:
1520
      _ErrorIf(not bdev_status,
1521
               self.EINSTANCEFAULTYDISK, instance,
1522
               "couldn't retrieve status for disk/%s on %s", idx, nname)
1523
      _ErrorIf(bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY,
1524
               self.EINSTANCEFAULTYDISK, instance,
1525
               "disk/%s on %s is faulty", idx, nname)
1526

    
1527
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1528
    """Verify if there are any unknown volumes in the cluster.
1529

1530
    The .os, .swap and backup volumes are ignored. All other volumes are
1531
    reported as unknown.
1532

1533
    @type reserved: L{ganeti.utils.FieldSet}
1534
    @param reserved: a FieldSet of reserved volume names
1535

1536
    """
1537
    for node, n_img in node_image.items():
1538
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1539
        # skip non-healthy nodes
1540
        continue
1541
      for volume in n_img.volumes:
1542
        test = ((node not in node_vol_should or
1543
                volume not in node_vol_should[node]) and
1544
                not reserved.Matches(volume))
1545
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1546
                      "volume %s is unknown", volume)
1547

    
1548
  def _VerifyOrphanInstances(self, instancelist, node_image):
1549
    """Verify the list of running instances.
1550

1551
    This checks what instances are running but unknown to the cluster.
1552

1553
    """
1554
    for node, n_img in node_image.items():
1555
      for o_inst in n_img.instances:
1556
        test = o_inst not in instancelist
1557
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1558
                      "instance %s on node %s should not exist", o_inst, node)
1559

    
1560
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1561
    """Verify N+1 Memory Resilience.
1562

1563
    Check that if one single node dies we can still start all the
1564
    instances it was primary for.
1565

1566
    """
1567
    for node, n_img in node_image.items():
1568
      # This code checks that every node which is now listed as
1569
      # secondary has enough memory to host all instances it is
1570
      # supposed to should a single other node in the cluster fail.
1571
      # FIXME: not ready for failover to an arbitrary node
1572
      # FIXME: does not support file-backed instances
1573
      # WARNING: we currently take into account down instances as well
1574
      # as up ones, considering that even if they're down someone
1575
      # might want to start them even in the event of a node failure.
1576
      for prinode, instances in n_img.sbp.items():
1577
        needed_mem = 0
1578
        for instance in instances:
1579
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1580
          if bep[constants.BE_AUTO_BALANCE]:
1581
            needed_mem += bep[constants.BE_MEMORY]
1582
        test = n_img.mfree < needed_mem
1583
        self._ErrorIf(test, self.ENODEN1, node,
1584
                      "not enough memory on to accommodate"
1585
                      " failovers should peer node %s fail", prinode)
1586

    
1587
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1588
                       master_files):
1589
    """Verifies and computes the node required file checksums.
1590

1591
    @type ninfo: L{objects.Node}
1592
    @param ninfo: the node to check
1593
    @param nresult: the remote results for the node
1594
    @param file_list: required list of files
1595
    @param local_cksum: dictionary of local files and their checksums
1596
    @param master_files: list of files that only masters should have
1597

1598
    """
1599
    node = ninfo.name
1600
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1601

    
1602
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1603
    test = not isinstance(remote_cksum, dict)
1604
    _ErrorIf(test, self.ENODEFILECHECK, node,
1605
             "node hasn't returned file checksum data")
1606
    if test:
1607
      return
1608

    
1609
    for file_name in file_list:
1610
      node_is_mc = ninfo.master_candidate
1611
      must_have = (file_name not in master_files) or node_is_mc
1612
      # missing
1613
      test1 = file_name not in remote_cksum
1614
      # invalid checksum
1615
      test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1616
      # existing and good
1617
      test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1618
      _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1619
               "file '%s' missing", file_name)
1620
      _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1621
               "file '%s' has wrong checksum", file_name)
1622
      # not candidate and this is not a must-have file
1623
      _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1624
               "file '%s' should not exist on non master"
1625
               " candidates (and the file is outdated)", file_name)
1626
      # all good, except non-master/non-must have combination
1627
      _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1628
               "file '%s' should not exist"
1629
               " on non master candidates", file_name)
1630

    
1631
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1632
                      drbd_map):
1633
    """Verifies and the node DRBD status.
1634

1635
    @type ninfo: L{objects.Node}
1636
    @param ninfo: the node to check
1637
    @param nresult: the remote results for the node
1638
    @param instanceinfo: the dict of instances
1639
    @param drbd_helper: the configured DRBD usermode helper
1640
    @param drbd_map: the DRBD map as returned by
1641
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1642

1643
    """
1644
    node = ninfo.name
1645
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1646

    
1647
    if drbd_helper:
1648
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1649
      test = (helper_result == None)
1650
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1651
               "no drbd usermode helper returned")
1652
      if helper_result:
1653
        status, payload = helper_result
1654
        test = not status
1655
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1656
                 "drbd usermode helper check unsuccessful: %s", payload)
1657
        test = status and (payload != drbd_helper)
1658
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1659
                 "wrong drbd usermode helper: %s", payload)
1660

    
1661
    # compute the DRBD minors
1662
    node_drbd = {}
1663
    for minor, instance in drbd_map[node].items():
1664
      test = instance not in instanceinfo
1665
      _ErrorIf(test, self.ECLUSTERCFG, None,
1666
               "ghost instance '%s' in temporary DRBD map", instance)
1667
        # ghost instance should not be running, but otherwise we
1668
        # don't give double warnings (both ghost instance and
1669
        # unallocated minor in use)
1670
      if test:
1671
        node_drbd[minor] = (instance, False)
1672
      else:
1673
        instance = instanceinfo[instance]
1674
        node_drbd[minor] = (instance.name, instance.admin_up)
1675

    
1676
    # and now check them
1677
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1678
    test = not isinstance(used_minors, (tuple, list))
1679
    _ErrorIf(test, self.ENODEDRBD, node,
1680
             "cannot parse drbd status file: %s", str(used_minors))
1681
    if test:
1682
      # we cannot check drbd status
1683
      return
1684

    
1685
    for minor, (iname, must_exist) in node_drbd.items():
1686
      test = minor not in used_minors and must_exist
1687
      _ErrorIf(test, self.ENODEDRBD, node,
1688
               "drbd minor %d of instance %s is not active", minor, iname)
1689
    for minor in used_minors:
1690
      test = minor not in node_drbd
1691
      _ErrorIf(test, self.ENODEDRBD, node,
1692
               "unallocated drbd minor %d is in use", minor)
1693

    
1694
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1695
    """Builds the node OS structures.
1696

1697
    @type ninfo: L{objects.Node}
1698
    @param ninfo: the node to check
1699
    @param nresult: the remote results for the node
1700
    @param nimg: the node image object
1701

1702
    """
1703
    node = ninfo.name
1704
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1705

    
1706
    remote_os = nresult.get(constants.NV_OSLIST, None)
1707
    test = (not isinstance(remote_os, list) or
1708
            not compat.all(isinstance(v, list) and len(v) == 7
1709
                           for v in remote_os))
1710

    
1711
    _ErrorIf(test, self.ENODEOS, node,
1712
             "node hasn't returned valid OS data")
1713

    
1714
    nimg.os_fail = test
1715

    
1716
    if test:
1717
      return
1718

    
1719
    os_dict = {}
1720

    
1721
    for (name, os_path, status, diagnose,
1722
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1723

    
1724
      if name not in os_dict:
1725
        os_dict[name] = []
1726

    
1727
      # parameters is a list of lists instead of list of tuples due to
1728
      # JSON lacking a real tuple type, fix it:
1729
      parameters = [tuple(v) for v in parameters]
1730
      os_dict[name].append((os_path, status, diagnose,
1731
                            set(variants), set(parameters), set(api_ver)))
1732

    
1733
    nimg.oslist = os_dict
1734

    
1735
  def _VerifyNodeOS(self, ninfo, nimg, base):
1736
    """Verifies the node OS list.
1737

1738
    @type ninfo: L{objects.Node}
1739
    @param ninfo: the node to check
1740
    @param nimg: the node image object
1741
    @param base: the 'template' node we match against (e.g. from the master)
1742

1743
    """
1744
    node = ninfo.name
1745
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1746

    
1747
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1748

    
1749
    for os_name, os_data in nimg.oslist.items():
1750
      assert os_data, "Empty OS status for OS %s?!" % os_name
1751
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
1752
      _ErrorIf(not f_status, self.ENODEOS, node,
1753
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
1754
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
1755
               "OS '%s' has multiple entries (first one shadows the rest): %s",
1756
               os_name, utils.CommaJoin([v[0] for v in os_data]))
1757
      # this will catched in backend too
1758
      _ErrorIf(compat.any(v >= constants.OS_API_V15 for v in f_api)
1759
               and not f_var, self.ENODEOS, node,
1760
               "OS %s with API at least %d does not declare any variant",
1761
               os_name, constants.OS_API_V15)
1762
      # comparisons with the 'base' image
1763
      test = os_name not in base.oslist
1764
      _ErrorIf(test, self.ENODEOS, node,
1765
               "Extra OS %s not present on reference node (%s)",
1766
               os_name, base.name)
1767
      if test:
1768
        continue
1769
      assert base.oslist[os_name], "Base node has empty OS status?"
1770
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
1771
      if not b_status:
1772
        # base OS is invalid, skipping
1773
        continue
1774
      for kind, a, b in [("API version", f_api, b_api),
1775
                         ("variants list", f_var, b_var),
1776
                         ("parameters", f_param, b_param)]:
1777
        _ErrorIf(a != b, self.ENODEOS, node,
1778
                 "OS %s %s differs from reference node %s: %s vs. %s",
1779
                 kind, os_name, base.name,
1780
                 utils.CommaJoin(a), utils.CommaJoin(b))
1781

    
1782
    # check any missing OSes
1783
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
1784
    _ErrorIf(missing, self.ENODEOS, node,
1785
             "OSes present on reference node %s but missing on this node: %s",
1786
             base.name, utils.CommaJoin(missing))
1787

    
1788
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1789
    """Verifies and updates the node volume data.
1790

1791
    This function will update a L{NodeImage}'s internal structures
1792
    with data from the remote call.
1793

1794
    @type ninfo: L{objects.Node}
1795
    @param ninfo: the node to check
1796
    @param nresult: the remote results for the node
1797
    @param nimg: the node image object
1798
    @param vg_name: the configured VG name
1799

1800
    """
1801
    node = ninfo.name
1802
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1803

    
1804
    nimg.lvm_fail = True
1805
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1806
    if vg_name is None:
1807
      pass
1808
    elif isinstance(lvdata, basestring):
1809
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1810
               utils.SafeEncode(lvdata))
1811
    elif not isinstance(lvdata, dict):
1812
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1813
    else:
1814
      nimg.volumes = lvdata
1815
      nimg.lvm_fail = False
1816

    
1817
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1818
    """Verifies and updates the node instance list.
1819

1820
    If the listing was successful, then updates this node's instance
1821
    list. Otherwise, it marks the RPC call as failed for the instance
1822
    list key.
1823

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

1829
    """
1830
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1831
    test = not isinstance(idata, list)
1832
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1833
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1834
    if test:
1835
      nimg.hyp_fail = True
1836
    else:
1837
      nimg.instances = idata
1838

    
1839
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1840
    """Verifies and computes a node information map
1841

1842
    @type ninfo: L{objects.Node}
1843
    @param ninfo: the node to check
1844
    @param nresult: the remote results for the node
1845
    @param nimg: the node image object
1846
    @param vg_name: the configured VG name
1847

1848
    """
1849
    node = ninfo.name
1850
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1851

    
1852
    # try to read free memory (from the hypervisor)
1853
    hv_info = nresult.get(constants.NV_HVINFO, None)
1854
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
1855
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1856
    if not test:
1857
      try:
1858
        nimg.mfree = int(hv_info["memory_free"])
1859
      except (ValueError, TypeError):
1860
        _ErrorIf(True, self.ENODERPC, node,
1861
                 "node returned invalid nodeinfo, check hypervisor")
1862

    
1863
    # FIXME: devise a free space model for file based instances as well
1864
    if vg_name is not None:
1865
      test = (constants.NV_VGLIST not in nresult or
1866
              vg_name not in nresult[constants.NV_VGLIST])
1867
      _ErrorIf(test, self.ENODELVM, node,
1868
               "node didn't return data for the volume group '%s'"
1869
               " - it is either missing or broken", vg_name)
1870
      if not test:
1871
        try:
1872
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
1873
        except (ValueError, TypeError):
1874
          _ErrorIf(True, self.ENODERPC, node,
1875
                   "node returned invalid LVM info, check LVM status")
1876

    
1877
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
1878
    """Gets per-disk status information for all instances.
1879

1880
    @type nodelist: list of strings
1881
    @param nodelist: Node names
1882
    @type node_image: dict of (name, L{objects.Node})
1883
    @param node_image: Node objects
1884
    @type instanceinfo: dict of (name, L{objects.Instance})
1885
    @param instanceinfo: Instance objects
1886

1887
    """
1888
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1889

    
1890
    node_disks = {}
1891
    node_disks_devonly = {}
1892

    
1893
    for nname in nodelist:
1894
      disks = [(inst, disk)
1895
               for instlist in [node_image[nname].pinst,
1896
                                node_image[nname].sinst]
1897
               for inst in instlist
1898
               for disk in instanceinfo[inst].disks]
1899

    
1900
      if not disks:
1901
        # No need to collect data
1902
        continue
1903

    
1904
      node_disks[nname] = disks
1905

    
1906
      # Creating copies as SetDiskID below will modify the objects and that can
1907
      # lead to incorrect data returned from nodes
1908
      devonly = [dev.Copy() for (_, dev) in disks]
1909

    
1910
      for dev in devonly:
1911
        self.cfg.SetDiskID(dev, nname)
1912

    
1913
      node_disks_devonly[nname] = devonly
1914

    
1915
    assert len(node_disks) == len(node_disks_devonly)
1916

    
1917
    # Collect data from all nodes with disks
1918
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
1919
                                                          node_disks_devonly)
1920

    
1921
    assert len(result) == len(node_disks)
1922

    
1923
    instdisk = {}
1924

    
1925
    for (nname, nres) in result.items():
1926
      if nres.offline:
1927
        # Ignore offline node
1928
        continue
1929

    
1930
      disks = node_disks[nname]
1931

    
1932
      msg = nres.fail_msg
1933
      _ErrorIf(msg, self.ENODERPC, nname,
1934
               "while getting disk information: %s", nres.fail_msg)
1935
      if msg:
1936
        # No data from this node
1937
        data = len(disks) * [None]
1938
      else:
1939
        data = nres.payload
1940

    
1941
      for ((inst, _), status) in zip(disks, data):
1942
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
1943

    
1944
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
1945
                      len(nnames) <= len(instanceinfo[inst].all_nodes)
1946
                      for inst, nnames in instdisk.items()
1947
                      for nname, statuses in nnames.items())
1948

    
1949
    return instdisk
1950

    
1951
  def BuildHooksEnv(self):
1952
    """Build hooks env.
1953

1954
    Cluster-Verify hooks just ran in the post phase and their failure makes
1955
    the output be logged in the verify output and the verification to fail.
1956

1957
    """
1958
    all_nodes = self.cfg.GetNodeList()
1959
    env = {
1960
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
1961
      }
1962
    for node in self.cfg.GetAllNodesInfo().values():
1963
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
1964

    
1965
    return env, [], all_nodes
1966

    
1967
  def Exec(self, feedback_fn):
1968
    """Verify integrity of cluster, performing various test on nodes.
1969

1970
    """
1971
    self.bad = False
1972
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1973
    verbose = self.op.verbose
1974
    self._feedback_fn = feedback_fn
1975
    feedback_fn("* Verifying global settings")
1976
    for msg in self.cfg.VerifyConfig():
1977
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
1978

    
1979
    # Check the cluster certificates
1980
    for cert_filename in constants.ALL_CERT_FILES:
1981
      (errcode, msg) = _VerifyCertificate(cert_filename)
1982
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
1983

    
1984
    vg_name = self.cfg.GetVGName()
1985
    drbd_helper = self.cfg.GetDRBDHelper()
1986
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
1987
    cluster = self.cfg.GetClusterInfo()
1988
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
1989
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
1990
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
1991
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
1992
                        for iname in instancelist)
1993
    i_non_redundant = [] # Non redundant instances
1994
    i_non_a_balanced = [] # Non auto-balanced instances
1995
    n_offline = 0 # Count of offline nodes
1996
    n_drained = 0 # Count of nodes being drained
1997
    node_vol_should = {}
1998

    
1999
    # FIXME: verify OS list
2000
    # do local checksums
2001
    master_files = [constants.CLUSTER_CONF_FILE]
2002
    master_node = self.master_node = self.cfg.GetMasterNode()
2003
    master_ip = self.cfg.GetMasterIP()
2004

    
2005
    file_names = ssconf.SimpleStore().GetFileList()
2006
    file_names.extend(constants.ALL_CERT_FILES)
2007
    file_names.extend(master_files)
2008
    if cluster.modify_etc_hosts:
2009
      file_names.append(constants.ETC_HOSTS)
2010

    
2011
    local_checksums = utils.FingerprintFiles(file_names)
2012

    
2013
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
2014
    node_verify_param = {
2015
      constants.NV_FILELIST: file_names,
2016
      constants.NV_NODELIST: [node.name for node in nodeinfo
2017
                              if not node.offline],
2018
      constants.NV_HYPERVISOR: hypervisors,
2019
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
2020
                                  node.secondary_ip) for node in nodeinfo
2021
                                 if not node.offline],
2022
      constants.NV_INSTANCELIST: hypervisors,
2023
      constants.NV_VERSION: None,
2024
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2025
      constants.NV_NODESETUP: None,
2026
      constants.NV_TIME: None,
2027
      constants.NV_MASTERIP: (master_node, master_ip),
2028
      constants.NV_OSLIST: None,
2029
      constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2030
      }
2031

    
2032
    if vg_name is not None:
2033
      node_verify_param[constants.NV_VGLIST] = None
2034
      node_verify_param[constants.NV_LVLIST] = vg_name
2035
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2036
      node_verify_param[constants.NV_DRBDLIST] = None
2037

    
2038
    if drbd_helper:
2039
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2040

    
2041
    # Build our expected cluster state
2042
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2043
                                                 name=node.name,
2044
                                                 vm_capable=node.vm_capable))
2045
                      for node in nodeinfo)
2046

    
2047
    for instance in instancelist:
2048
      inst_config = instanceinfo[instance]
2049

    
2050
      for nname in inst_config.all_nodes:
2051
        if nname not in node_image:
2052
          # ghost node
2053
          gnode = self.NodeImage(name=nname)
2054
          gnode.ghost = True
2055
          node_image[nname] = gnode
2056

    
2057
      inst_config.MapLVsByNode(node_vol_should)
2058

    
2059
      pnode = inst_config.primary_node
2060
      node_image[pnode].pinst.append(instance)
2061

    
2062
      for snode in inst_config.secondary_nodes:
2063
        nimg = node_image[snode]
2064
        nimg.sinst.append(instance)
2065
        if pnode not in nimg.sbp:
2066
          nimg.sbp[pnode] = []
2067
        nimg.sbp[pnode].append(instance)
2068

    
2069
    # At this point, we have the in-memory data structures complete,
2070
    # except for the runtime information, which we'll gather next
2071

    
2072
    # Due to the way our RPC system works, exact response times cannot be
2073
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2074
    # time before and after executing the request, we can at least have a time
2075
    # window.
2076
    nvinfo_starttime = time.time()
2077
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
2078
                                           self.cfg.GetClusterName())
2079
    nvinfo_endtime = time.time()
2080

    
2081
    all_drbd_map = self.cfg.ComputeDRBDMap()
2082

    
2083
    feedback_fn("* Gathering disk information (%s nodes)" % len(nodelist))
2084
    instdisk = self._CollectDiskInfo(nodelist, node_image, instanceinfo)
2085

    
2086
    feedback_fn("* Verifying node status")
2087

    
2088
    refos_img = None
2089

    
2090
    for node_i in nodeinfo:
2091
      node = node_i.name
2092
      nimg = node_image[node]
2093

    
2094
      if node_i.offline:
2095
        if verbose:
2096
          feedback_fn("* Skipping offline node %s" % (node,))
2097
        n_offline += 1
2098
        continue
2099

    
2100
      if node == master_node:
2101
        ntype = "master"
2102
      elif node_i.master_candidate:
2103
        ntype = "master candidate"
2104
      elif node_i.drained:
2105
        ntype = "drained"
2106
        n_drained += 1
2107
      else:
2108
        ntype = "regular"
2109
      if verbose:
2110
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2111

    
2112
      msg = all_nvinfo[node].fail_msg
2113
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2114
      if msg:
2115
        nimg.rpc_fail = True
2116
        continue
2117

    
2118
      nresult = all_nvinfo[node].payload
2119

    
2120
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2121
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2122
      self._VerifyNodeNetwork(node_i, nresult)
2123
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2124
                            master_files)
2125

    
2126
      if nimg.vm_capable:
2127
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2128
        self._VerifyNodeDrbd(node_i, nresult, instanceinfo, drbd_helper,
2129
                             all_drbd_map)
2130

    
2131
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2132
        self._UpdateNodeInstances(node_i, nresult, nimg)
2133
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2134
        self._UpdateNodeOS(node_i, nresult, nimg)
2135
        if not nimg.os_fail:
2136
          if refos_img is None:
2137
            refos_img = nimg
2138
          self._VerifyNodeOS(node_i, nimg, refos_img)
2139

    
2140
    feedback_fn("* Verifying instance status")
2141
    for instance in instancelist:
2142
      if verbose:
2143
        feedback_fn("* Verifying instance %s" % instance)
2144
      inst_config = instanceinfo[instance]
2145
      self._VerifyInstance(instance, inst_config, node_image,
2146
                           instdisk[instance])
2147
      inst_nodes_offline = []
2148

    
2149
      pnode = inst_config.primary_node
2150
      pnode_img = node_image[pnode]
2151
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2152
               self.ENODERPC, pnode, "instance %s, connection to"
2153
               " primary node failed", instance)
2154

    
2155
      if pnode_img.offline:
2156
        inst_nodes_offline.append(pnode)
2157

    
2158
      # If the instance is non-redundant we cannot survive losing its primary
2159
      # node, so we are not N+1 compliant. On the other hand we have no disk
2160
      # templates with more than one secondary so that situation is not well
2161
      # supported either.
2162
      # FIXME: does not support file-backed instances
2163
      if not inst_config.secondary_nodes:
2164
        i_non_redundant.append(instance)
2165
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2166
               instance, "instance has multiple secondary nodes: %s",
2167
               utils.CommaJoin(inst_config.secondary_nodes),
2168
               code=self.ETYPE_WARNING)
2169

    
2170
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2171
        i_non_a_balanced.append(instance)
2172

    
2173
      for snode in inst_config.secondary_nodes:
2174
        s_img = node_image[snode]
2175
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2176
                 "instance %s, connection to secondary node failed", instance)
2177

    
2178
        if s_img.offline:
2179
          inst_nodes_offline.append(snode)
2180

    
2181
      # warn that the instance lives on offline nodes
2182
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2183
               "instance lives on offline node(s) %s",
2184
               utils.CommaJoin(inst_nodes_offline))
2185
      # ... or ghost/non-vm_capable nodes
2186
      for node in inst_config.all_nodes:
2187
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2188
                 "instance lives on ghost node %s", node)
2189
        _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2190
                 instance, "instance lives on non-vm_capable node %s", node)
2191

    
2192
    feedback_fn("* Verifying orphan volumes")
2193
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2194
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2195

    
2196
    feedback_fn("* Verifying orphan instances")
2197
    self._VerifyOrphanInstances(instancelist, node_image)
2198

    
2199
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2200
      feedback_fn("* Verifying N+1 Memory redundancy")
2201
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2202

    
2203
    feedback_fn("* Other Notes")
2204
    if i_non_redundant:
2205
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2206
                  % len(i_non_redundant))
2207

    
2208
    if i_non_a_balanced:
2209
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2210
                  % len(i_non_a_balanced))
2211

    
2212
    if n_offline:
2213
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2214

    
2215
    if n_drained:
2216
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2217

    
2218
    return not self.bad
2219

    
2220
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2221
    """Analyze the post-hooks' result
2222

2223
    This method analyses the hook result, handles it, and sends some
2224
    nicely-formatted feedback back to the user.
2225

2226
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2227
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2228
    @param hooks_results: the results of the multi-node hooks rpc call
2229
    @param feedback_fn: function used send feedback back to the caller
2230
    @param lu_result: previous Exec result
2231
    @return: the new Exec result, based on the previous result
2232
        and hook results
2233

2234
    """
2235
    # We only really run POST phase hooks, and are only interested in
2236
    # their results
2237
    if phase == constants.HOOKS_PHASE_POST:
2238
      # Used to change hooks' output to proper indentation
2239
      indent_re = re.compile('^', re.M)
2240
      feedback_fn("* Hooks Results")
2241
      assert hooks_results, "invalid result from hooks"
2242

    
2243
      for node_name in hooks_results:
2244
        res = hooks_results[node_name]
2245
        msg = res.fail_msg
2246
        test = msg and not res.offline
2247
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2248
                      "Communication failure in hooks execution: %s", msg)
2249
        if res.offline or msg:
2250
          # No need to investigate payload if node is offline or gave an error.
2251
          # override manually lu_result here as _ErrorIf only
2252
          # overrides self.bad
2253
          lu_result = 1
2254
          continue
2255
        for script, hkr, output in res.payload:
2256
          test = hkr == constants.HKR_FAIL
2257
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2258
                        "Script %s failed, output:", script)
2259
          if test:
2260
            output = indent_re.sub('      ', output)
2261
            feedback_fn("%s" % output)
2262
            lu_result = 0
2263

    
2264
      return lu_result
2265

    
2266

    
2267
class LUVerifyDisks(NoHooksLU):
2268
  """Verifies the cluster disks status.
2269

2270
  """
2271
  REQ_BGL = False
2272

    
2273
  def ExpandNames(self):
2274
    self.needed_locks = {
2275
      locking.LEVEL_NODE: locking.ALL_SET,
2276
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2277
    }
2278
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2279

    
2280
  def Exec(self, feedback_fn):
2281
    """Verify integrity of cluster disks.
2282

2283
    @rtype: tuple of three items
2284
    @return: a tuple of (dict of node-to-node_error, list of instances
2285
        which need activate-disks, dict of instance: (node, volume) for
2286
        missing volumes
2287

2288
    """
2289
    result = res_nodes, res_instances, res_missing = {}, [], {}
2290

    
2291
    vg_name = self.cfg.GetVGName()
2292
    nodes = utils.NiceSort(self.cfg.GetNodeList())
2293
    instances = [self.cfg.GetInstanceInfo(name)
2294
                 for name in self.cfg.GetInstanceList()]
2295

    
2296
    nv_dict = {}
2297
    for inst in instances:
2298
      inst_lvs = {}
2299
      if (not inst.admin_up or
2300
          inst.disk_template not in constants.DTS_NET_MIRROR):
2301
        continue
2302
      inst.MapLVsByNode(inst_lvs)
2303
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2304
      for node, vol_list in inst_lvs.iteritems():
2305
        for vol in vol_list:
2306
          nv_dict[(node, vol)] = inst
2307

    
2308
    if not nv_dict:
2309
      return result
2310

    
2311
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
2312

    
2313
    for node in nodes:
2314
      # node_volume
2315
      node_res = node_lvs[node]
2316
      if node_res.offline:
2317
        continue
2318
      msg = node_res.fail_msg
2319
      if msg:
2320
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2321
        res_nodes[node] = msg
2322
        continue
2323

    
2324
      lvs = node_res.payload
2325
      for lv_name, (_, _, lv_online) in lvs.items():
2326
        inst = nv_dict.pop((node, lv_name), None)
2327
        if (not lv_online and inst is not None
2328
            and inst.name not in res_instances):
2329
          res_instances.append(inst.name)
2330

    
2331
    # any leftover items in nv_dict are missing LVs, let's arrange the
2332
    # data better
2333
    for key, inst in nv_dict.iteritems():
2334
      if inst.name not in res_missing:
2335
        res_missing[inst.name] = []
2336
      res_missing[inst.name].append(key)
2337

    
2338
    return result
2339

    
2340

    
2341
class LURepairDiskSizes(NoHooksLU):
2342
  """Verifies the cluster disks sizes.
2343

2344
  """
2345
  _OP_PARAMS = [("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString))]
2346
  REQ_BGL = False
2347

    
2348
  def ExpandNames(self):
2349
    if self.op.instances:
2350
      self.wanted_names = []
2351
      for name in self.op.instances:
2352
        full_name = _ExpandInstanceName(self.cfg, name)
2353
        self.wanted_names.append(full_name)
2354
      self.needed_locks = {
2355
        locking.LEVEL_NODE: [],
2356
        locking.LEVEL_INSTANCE: self.wanted_names,
2357
        }
2358
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2359
    else:
2360
      self.wanted_names = None
2361
      self.needed_locks = {
2362
        locking.LEVEL_NODE: locking.ALL_SET,
2363
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2364
        }
2365
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2366

    
2367
  def DeclareLocks(self, level):
2368
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2369
      self._LockInstancesNodes(primary_only=True)
2370

    
2371
  def CheckPrereq(self):
2372
    """Check prerequisites.
2373

2374
    This only checks the optional instance list against the existing names.
2375

2376
    """
2377
    if self.wanted_names is None:
2378
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2379

    
2380
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2381
                             in self.wanted_names]
2382

    
2383
  def _EnsureChildSizes(self, disk):
2384
    """Ensure children of the disk have the needed disk size.
2385

2386
    This is valid mainly for DRBD8 and fixes an issue where the
2387
    children have smaller disk size.
2388

2389
    @param disk: an L{ganeti.objects.Disk} object
2390

2391
    """
2392
    if disk.dev_type == constants.LD_DRBD8:
2393
      assert disk.children, "Empty children for DRBD8?"
2394
      fchild = disk.children[0]
2395
      mismatch = fchild.size < disk.size
2396
      if mismatch:
2397
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2398
                     fchild.size, disk.size)
2399
        fchild.size = disk.size
2400

    
2401
      # and we recurse on this child only, not on the metadev
2402
      return self._EnsureChildSizes(fchild) or mismatch
2403
    else:
2404
      return False
2405

    
2406
  def Exec(self, feedback_fn):
2407
    """Verify the size of cluster disks.
2408

2409
    """
2410
    # TODO: check child disks too
2411
    # TODO: check differences in size between primary/secondary nodes
2412
    per_node_disks = {}
2413
    for instance in self.wanted_instances:
2414
      pnode = instance.primary_node
2415
      if pnode not in per_node_disks:
2416
        per_node_disks[pnode] = []
2417
      for idx, disk in enumerate(instance.disks):
2418
        per_node_disks[pnode].append((instance, idx, disk))
2419

    
2420
    changed = []
2421
    for node, dskl in per_node_disks.items():
2422
      newl = [v[2].Copy() for v in dskl]
2423
      for dsk in newl:
2424
        self.cfg.SetDiskID(dsk, node)
2425
      result = self.rpc.call_blockdev_getsizes(node, newl)
2426
      if result.fail_msg:
2427
        self.LogWarning("Failure in blockdev_getsizes call to node"
2428
                        " %s, ignoring", node)
2429
        continue
2430
      if len(result.data) != len(dskl):
2431
        self.LogWarning("Invalid result from node %s, ignoring node results",
2432
                        node)
2433
        continue
2434
      for ((instance, idx, disk), size) in zip(dskl, result.data):
2435
        if size is None:
2436
          self.LogWarning("Disk %d of instance %s did not return size"
2437
                          " information, ignoring", idx, instance.name)
2438
          continue
2439
        if not isinstance(size, (int, long)):
2440
          self.LogWarning("Disk %d of instance %s did not return valid"
2441
                          " size information, ignoring", idx, instance.name)
2442
          continue
2443
        size = size >> 20
2444
        if size != disk.size:
2445
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2446
                       " correcting: recorded %d, actual %d", idx,
2447
                       instance.name, disk.size, size)
2448
          disk.size = size
2449
          self.cfg.Update(instance, feedback_fn)
2450
          changed.append((instance.name, idx, size))
2451
        if self._EnsureChildSizes(disk):
2452
          self.cfg.Update(instance, feedback_fn)
2453
          changed.append((instance.name, idx, disk.size))
2454
    return changed
2455

    
2456

    
2457
class LURenameCluster(LogicalUnit):
2458
  """Rename the cluster.
2459

2460
  """
2461
  HPATH = "cluster-rename"
2462
  HTYPE = constants.HTYPE_CLUSTER
2463
  _OP_PARAMS = [("name", ht.NoDefault, ht.TNonEmptyString)]
2464

    
2465
  def BuildHooksEnv(self):
2466
    """Build hooks env.
2467

2468
    """
2469
    env = {
2470
      "OP_TARGET": self.cfg.GetClusterName(),
2471
      "NEW_NAME": self.op.name,
2472
      }
2473
    mn = self.cfg.GetMasterNode()
2474
    all_nodes = self.cfg.GetNodeList()
2475
    return env, [mn], all_nodes
2476

    
2477
  def CheckPrereq(self):
2478
    """Verify that the passed name is a valid one.
2479

2480
    """
2481
    hostname = netutils.GetHostname(name=self.op.name,
2482
                                    family=self.cfg.GetPrimaryIPFamily())
2483

    
2484
    new_name = hostname.name
2485
    self.ip = new_ip = hostname.ip
2486
    old_name = self.cfg.GetClusterName()
2487
    old_ip = self.cfg.GetMasterIP()
2488
    if new_name == old_name and new_ip == old_ip:
2489
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2490
                                 " cluster has changed",
2491
                                 errors.ECODE_INVAL)
2492
    if new_ip != old_ip:
2493
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2494
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2495
                                   " reachable on the network" %
2496
                                   new_ip, errors.ECODE_NOTUNIQUE)
2497

    
2498
    self.op.name = new_name
2499

    
2500
  def Exec(self, feedback_fn):
2501
    """Rename the cluster.
2502

2503
    """
2504
    clustername = self.op.name
2505
    ip = self.ip
2506

    
2507
    # shutdown the master IP
2508
    master = self.cfg.GetMasterNode()
2509
    result = self.rpc.call_node_stop_master(master, False)
2510
    result.Raise("Could not disable the master role")
2511

    
2512
    try:
2513
      cluster = self.cfg.GetClusterInfo()
2514
      cluster.cluster_name = clustername
2515
      cluster.master_ip = ip
2516
      self.cfg.Update(cluster, feedback_fn)
2517

    
2518
      # update the known hosts file
2519
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2520
      node_list = self.cfg.GetNodeList()
2521
      try:
2522
        node_list.remove(master)
2523
      except ValueError:
2524
        pass
2525
      _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
2526
    finally:
2527
      result = self.rpc.call_node_start_master(master, False, False)
2528
      msg = result.fail_msg
2529
      if msg:
2530
        self.LogWarning("Could not re-enable the master role on"
2531
                        " the master, please restart manually: %s", msg)
2532

    
2533
    return clustername
2534

    
2535

    
2536
class LUSetClusterParams(LogicalUnit):
2537
  """Change the parameters of the cluster.
2538

2539
  """
2540
  HPATH = "cluster-modify"
2541
  HTYPE = constants.HTYPE_CLUSTER
2542
  _OP_PARAMS = [
2543
    ("vg_name", None, ht.TMaybeString),
2544
    ("enabled_hypervisors", None,
2545
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
2546
            ht.TNone)),
2547
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2548
                              ht.TNone)),
2549
    ("beparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2550
                              ht.TNone)),
2551
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2552
                            ht.TNone)),
2553
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2554
                              ht.TNone)),
2555
    ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone)),
2556
    ("uid_pool", None, ht.NoType),
2557
    ("add_uids", None, ht.NoType),
2558
    ("remove_uids", None, ht.NoType),
2559
    ("maintain_node_health", None, ht.TMaybeBool),
2560
    ("prealloc_wipe_disks", None, ht.TMaybeBool),
2561
    ("nicparams", None, ht.TOr(ht.TDict, ht.TNone)),
2562
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone)),
2563
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone)),
2564
    ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone)),
2565
    ("hidden_os", None, ht.TOr(ht.TListOf(\
2566
          ht.TAnd(ht.TList,
2567
                ht.TIsLength(2),
2568
                ht.TMap(lambda v: v[0], ht.TElemOf(constants.DDMS_VALUES)))),
2569
          ht.TNone)),
2570
    ("blacklisted_os", None, ht.TOr(ht.TListOf(\
2571
          ht.TAnd(ht.TList,
2572
                ht.TIsLength(2),
2573
                ht.TMap(lambda v: v[0], ht.TElemOf(constants.DDMS_VALUES)))),
2574
          ht.TNone)),
2575
    ]
2576
  REQ_BGL = False
2577

    
2578
  def CheckArguments(self):
2579
    """Check parameters
2580

2581
    """
2582
    if self.op.uid_pool:
2583
      uidpool.CheckUidPool(self.op.uid_pool)
2584

    
2585
    if self.op.add_uids:
2586
      uidpool.CheckUidPool(self.op.add_uids)
2587

    
2588
    if self.op.remove_uids:
2589
      uidpool.CheckUidPool(self.op.remove_uids)
2590

    
2591
  def ExpandNames(self):
2592
    # FIXME: in the future maybe other cluster params won't require checking on
2593
    # all nodes to be modified.
2594
    self.needed_locks = {
2595
      locking.LEVEL_NODE: locking.ALL_SET,
2596
    }
2597
    self.share_locks[locking.LEVEL_NODE] = 1
2598

    
2599
  def BuildHooksEnv(self):
2600
    """Build hooks env.
2601

2602
    """
2603
    env = {
2604
      "OP_TARGET": self.cfg.GetClusterName(),
2605
      "NEW_VG_NAME": self.op.vg_name,
2606
      }
2607
    mn = self.cfg.GetMasterNode()
2608
    return env, [mn], [mn]
2609

    
2610
  def CheckPrereq(self):
2611
    """Check prerequisites.
2612

2613
    This checks whether the given params don't conflict and
2614
    if the given volume group is valid.
2615

2616
    """
2617
    if self.op.vg_name is not None and not self.op.vg_name:
2618
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2619
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2620
                                   " instances exist", errors.ECODE_INVAL)
2621

    
2622
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
2623
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
2624
        raise errors.OpPrereqError("Cannot disable drbd helper while"
2625
                                   " drbd-based instances exist",
2626
                                   errors.ECODE_INVAL)
2627

    
2628
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2629

    
2630
    # if vg_name not None, checks given volume group on all nodes
2631
    if self.op.vg_name:
2632
      vglist = self.rpc.call_vg_list(node_list)
2633
      for node in node_list:
2634
        msg = vglist[node].fail_msg
2635
        if msg:
2636
          # ignoring down node
2637
          self.LogWarning("Error while gathering data on node %s"
2638
                          " (ignoring node): %s", node, msg)
2639
          continue
2640
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2641
                                              self.op.vg_name,
2642
                                              constants.MIN_VG_SIZE)
2643
        if vgstatus:
2644
          raise errors.OpPrereqError("Error on node '%s': %s" %
2645
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2646

    
2647
    if self.op.drbd_helper:
2648
      # checks given drbd helper on all nodes
2649
      helpers = self.rpc.call_drbd_helper(node_list)
2650
      for node in node_list:
2651
        ninfo = self.cfg.GetNodeInfo(node)
2652
        if ninfo.offline:
2653
          self.LogInfo("Not checking drbd helper on offline node %s", node)
2654
          continue
2655
        msg = helpers[node].fail_msg
2656
        if msg:
2657
          raise errors.OpPrereqError("Error checking drbd helper on node"
2658
                                     " '%s': %s" % (node, msg),
2659
                                     errors.ECODE_ENVIRON)
2660
        node_helper = helpers[node].payload
2661
        if node_helper != self.op.drbd_helper:
2662
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
2663
                                     (node, node_helper), errors.ECODE_ENVIRON)
2664

    
2665
    self.cluster = cluster = self.cfg.GetClusterInfo()
2666
    # validate params changes
2667
    if self.op.beparams:
2668
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2669
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2670

    
2671
    if self.op.nicparams:
2672
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2673
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2674
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2675
      nic_errors = []
2676

    
2677
      # check all instances for consistency
2678
      for instance in self.cfg.GetAllInstancesInfo().values():
2679
        for nic_idx, nic in enumerate(instance.nics):
2680
          params_copy = copy.deepcopy(nic.nicparams)
2681
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2682

    
2683
          # check parameter syntax
2684
          try:
2685
            objects.NIC.CheckParameterSyntax(params_filled)
2686
          except errors.ConfigurationError, err:
2687
            nic_errors.append("Instance %s, nic/%d: %s" %
2688
                              (instance.name, nic_idx, err))
2689

    
2690
          # if we're moving instances to routed, check that they have an ip
2691
          target_mode = params_filled[constants.NIC_MODE]
2692
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2693
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2694
                              (instance.name, nic_idx))
2695
      if nic_errors:
2696
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2697
                                   "\n".join(nic_errors))
2698

    
2699
    # hypervisor list/parameters
2700
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2701
    if self.op.hvparams:
2702
      for hv_name, hv_dict in self.op.hvparams.items():
2703
        if hv_name not in self.new_hvparams:
2704
          self.new_hvparams[hv_name] = hv_dict
2705
        else:
2706
          self.new_hvparams[hv_name].update(hv_dict)
2707

    
2708
    # os hypervisor parameters
2709
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2710
    if self.op.os_hvp:
2711
      for os_name, hvs in self.op.os_hvp.items():
2712
        if os_name not in self.new_os_hvp:
2713
          self.new_os_hvp[os_name] = hvs
2714
        else:
2715
          for hv_name, hv_dict in hvs.items():
2716
            if hv_name not in self.new_os_hvp[os_name]:
2717
              self.new_os_hvp[os_name][hv_name] = hv_dict
2718
            else:
2719
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2720

    
2721
    # os parameters
2722
    self.new_osp = objects.FillDict(cluster.osparams, {})
2723
    if self.op.osparams:
2724
      for os_name, osp in self.op.osparams.items():
2725
        if os_name not in self.new_osp:
2726
          self.new_osp[os_name] = {}
2727

    
2728
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2729
                                                  use_none=True)
2730

    
2731
        if not self.new_osp[os_name]:
2732
          # we removed all parameters
2733
          del self.new_osp[os_name]
2734
        else:
2735
          # check the parameter validity (remote check)
2736
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
2737
                         os_name, self.new_osp[os_name])
2738

    
2739
    # changes to the hypervisor list
2740
    if self.op.enabled_hypervisors is not None:
2741
      self.hv_list = self.op.enabled_hypervisors
2742
      for hv in self.hv_list:
2743
        # if the hypervisor doesn't already exist in the cluster
2744
        # hvparams, we initialize it to empty, and then (in both
2745
        # cases) we make sure to fill the defaults, as we might not
2746
        # have a complete defaults list if the hypervisor wasn't
2747
        # enabled before
2748
        if hv not in new_hvp:
2749
          new_hvp[hv] = {}
2750
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2751
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2752
    else:
2753
      self.hv_list = cluster.enabled_hypervisors
2754

    
2755
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2756
      # either the enabled list has changed, or the parameters have, validate
2757
      for hv_name, hv_params in self.new_hvparams.items():
2758
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2759
            (self.op.enabled_hypervisors and
2760
             hv_name in self.op.enabled_hypervisors)):
2761
          # either this is a new hypervisor, or its parameters have changed
2762
          hv_class = hypervisor.GetHypervisor(hv_name)
2763
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2764
          hv_class.CheckParameterSyntax(hv_params)
2765
          _CheckHVParams(self, node_list, hv_name, hv_params)
2766

    
2767
    if self.op.os_hvp:
2768
      # no need to check any newly-enabled hypervisors, since the
2769
      # defaults have already been checked in the above code-block
2770
      for os_name, os_hvp in self.new_os_hvp.items():
2771
        for hv_name, hv_params in os_hvp.items():
2772
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2773
          # we need to fill in the new os_hvp on top of the actual hv_p
2774
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2775
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2776
          hv_class = hypervisor.GetHypervisor(hv_name)
2777
          hv_class.CheckParameterSyntax(new_osp)
2778
          _CheckHVParams(self, node_list, hv_name, new_osp)
2779

    
2780
    if self.op.default_iallocator:
2781
      alloc_script = utils.FindFile(self.op.default_iallocator,
2782
                                    constants.IALLOCATOR_SEARCH_PATH,
2783
                                    os.path.isfile)
2784
      if alloc_script is None:
2785
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
2786
                                   " specified" % self.op.default_iallocator,
2787
                                   errors.ECODE_INVAL)
2788

    
2789
  def Exec(self, feedback_fn):
2790
    """Change the parameters of the cluster.
2791

2792
    """
2793
    if self.op.vg_name is not None:
2794
      new_volume = self.op.vg_name
2795
      if not new_volume:
2796
        new_volume = None
2797
      if new_volume != self.cfg.GetVGName():
2798
        self.cfg.SetVGName(new_volume)
2799
      else:
2800
        feedback_fn("Cluster LVM configuration already in desired"
2801
                    " state, not changing")
2802
    if self.op.drbd_helper is not None:
2803
      new_helper = self.op.drbd_helper
2804
      if not new_helper:
2805
        new_helper = None
2806
      if new_helper != self.cfg.GetDRBDHelper():
2807
        self.cfg.SetDRBDHelper(new_helper)
2808
      else:
2809
        feedback_fn("Cluster DRBD helper already in desired state,"
2810
                    " not changing")
2811
    if self.op.hvparams:
2812
      self.cluster.hvparams = self.new_hvparams
2813
    if self.op.os_hvp:
2814
      self.cluster.os_hvp = self.new_os_hvp
2815
    if self.op.enabled_hypervisors is not None:
2816
      self.cluster.hvparams = self.new_hvparams
2817
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2818
    if self.op.beparams:
2819
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2820
    if self.op.nicparams:
2821
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2822
    if self.op.osparams:
2823
      self.cluster.osparams = self.new_osp
2824

    
2825
    if self.op.candidate_pool_size is not None:
2826
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2827
      # we need to update the pool size here, otherwise the save will fail
2828
      _AdjustCandidatePool(self, [])
2829

    
2830
    if self.op.maintain_node_health is not None:
2831
      self.cluster.maintain_node_health = self.op.maintain_node_health
2832

    
2833
    if self.op.prealloc_wipe_disks is not None:
2834
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
2835

    
2836
    if self.op.add_uids is not None:
2837
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2838

    
2839
    if self.op.remove_uids is not None:
2840
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2841

    
2842
    if self.op.uid_pool is not None:
2843
      self.cluster.uid_pool = self.op.uid_pool
2844

    
2845
    if self.op.default_iallocator is not None:
2846
      self.cluster.default_iallocator = self.op.default_iallocator
2847

    
2848
    if self.op.reserved_lvs is not None:
2849
      self.cluster.reserved_lvs = self.op.reserved_lvs
2850

    
2851
    def helper_os(aname, mods, desc):
2852
      desc += " OS list"
2853
      lst = getattr(self.cluster, aname)
2854
      for key, val in mods:
2855
        if key == constants.DDM_ADD:
2856
          if val in lst:
2857
            feedback_fn("OS %s already in %s, ignoring", val, desc)
2858
          else:
2859
            lst.append(val)
2860
        elif key == constants.DDM_REMOVE:
2861
          if val in lst:
2862
            lst.remove(val)
2863
          else:
2864
            feedback_fn("OS %s not found in %s, ignoring", val, desc)
2865
        else:
2866
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
2867

    
2868
    if self.op.hidden_os:
2869
      helper_os("hidden_os", self.op.hidden_os, "hidden")
2870

    
2871
    if self.op.blacklisted_os:
2872
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
2873

    
2874
    self.cfg.Update(self.cluster, feedback_fn)
2875

    
2876

    
2877
def _UploadHelper(lu, nodes, fname):
2878
  """Helper for uploading a file and showing warnings.
2879

2880
  """
2881
  if os.path.exists(fname):
2882
    result = lu.rpc.call_upload_file(nodes, fname)
2883
    for to_node, to_result in result.items():
2884
      msg = to_result.fail_msg
2885
      if msg:
2886
        msg = ("Copy of file %s to node %s failed: %s" %
2887
               (fname, to_node, msg))
2888
        lu.proc.LogWarning(msg)
2889

    
2890

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

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

2898
  @param lu: calling logical unit
2899
  @param additional_nodes: list of nodes not in the config to distribute to
2900
  @type additional_vm: boolean
2901
  @param additional_vm: whether the additional nodes are vm-capable or not
2902

2903
  """
2904
  # 1. Gather target nodes
2905
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2906
  dist_nodes = lu.cfg.GetOnlineNodeList()
2907
  nvm_nodes = lu.cfg.GetNonVmCapableNodeList()
2908
  vm_nodes = [name for name in dist_nodes if name not in nvm_nodes]
2909
  if additional_nodes is not None:
2910
    dist_nodes.extend(additional_nodes)
2911
    if additional_vm:
2912
      vm_nodes.extend(additional_nodes)
2913
  if myself.name in dist_nodes:
2914
    dist_nodes.remove(myself.name)
2915
  if myself.name in vm_nodes:
2916
    vm_nodes.remove(myself.name)
2917

    
2918
  # 2. Gather files to distribute
2919
  dist_files = set([constants.ETC_HOSTS,
2920
                    constants.SSH_KNOWN_HOSTS_FILE,
2921
                    constants.RAPI_CERT_FILE,
2922
                    constants.RAPI_USERS_FILE,
2923
                    constants.CONFD_HMAC_KEY,
2924
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
2925
                   ])
2926

    
2927
  vm_files = set()
2928
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2929
  for hv_name in enabled_hypervisors:
2930
    hv_class = hypervisor.GetHypervisor(hv_name)
2931
    vm_files.update(hv_class.GetAncillaryFiles())
2932

    
2933
  # 3. Perform the files upload
2934
  for fname in dist_files:
2935
    _UploadHelper(lu, dist_nodes, fname)
2936
  for fname in vm_files:
2937
    _UploadHelper(lu, vm_nodes, fname)
2938

    
2939

    
2940
class LURedistributeConfig(NoHooksLU):
2941
  """Force the redistribution of cluster configuration.
2942

2943
  This is a very simple LU.
2944

2945
  """
2946
  REQ_BGL = False
2947

    
2948
  def ExpandNames(self):
2949
    self.needed_locks = {
2950
      locking.LEVEL_NODE: locking.ALL_SET,
2951
    }
2952
    self.share_locks[locking.LEVEL_NODE] = 1
2953

    
2954
  def Exec(self, feedback_fn):
2955
    """Redistribute the configuration.
2956

2957
    """
2958
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2959
    _RedistributeAncillaryFiles(self)
2960

    
2961

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

2965
  """
2966
  if not instance.disks or disks is not None and not disks:
2967
    return True
2968

    
2969
  disks = _ExpandCheckDisks(instance, disks)
2970

    
2971
  if not oneshot:
2972
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2973

    
2974
  node = instance.primary_node
2975

    
2976
  for dev in disks:
2977
    lu.cfg.SetDiskID(dev, node)
2978

    
2979
  # TODO: Convert to utils.Retry
2980

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

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

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

    
3027
    if done or oneshot:
3028
      break
3029

    
3030
    time.sleep(min(60, max_time))
3031

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

    
3036

    
3037
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3038
  """Check that mirrors are not degraded.
3039

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

3044
  """
3045
  lu.cfg.SetDiskID(dev, node)
3046

    
3047
  result = True
3048

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

    
3064
  if dev.children:
3065
    for child in dev.children:
3066
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3067

    
3068
  return result
3069

    
3070

    
3071
class LUDiagnoseOS(NoHooksLU):
3072
  """Logical unit for OS diagnose/query.
3073

3074
  """
3075
  _OP_PARAMS = [
3076
    _POutputFields,
3077
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3078
    ]
3079
  REQ_BGL = False
3080
  _HID = "hidden"
3081
  _BLK = "blacklisted"
3082
  _VLD = "valid"
3083
  _FIELDS_STATIC = utils.FieldSet()
3084
  _FIELDS_DYNAMIC = utils.FieldSet("name", _VLD, "node_status", "variants",
3085
                                   "parameters", "api_versions", _HID, _BLK)
3086

    
3087
  def CheckArguments(self):
3088
    if self.op.names:
3089
      raise errors.OpPrereqError("Selective OS query not supported",
3090
                                 errors.ECODE_INVAL)
3091

    
3092
    _CheckOutputFields(static=self._FIELDS_STATIC,
3093
                       dynamic=self._FIELDS_DYNAMIC,
3094
                       selected=self.op.output_fields)
3095

    
3096
  def ExpandNames(self):
3097
    # Lock all nodes, in shared mode
3098
    # Temporary removal of locks, should be reverted later
3099
    # TODO: reintroduce locks when they are lighter-weight
3100
    self.needed_locks = {}
3101
    #self.share_locks[locking.LEVEL_NODE] = 1
3102
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3103

    
3104
  @staticmethod
3105
  def _DiagnoseByOS(rlist):
3106
    """Remaps a per-node return list into an a per-os per-node dictionary
3107

3108
    @param rlist: a map with node names as keys and OS objects as values
3109

3110
    @rtype: dict
3111
    @return: a dictionary with osnames as keys and as value another
3112
        map, with nodes as keys and tuples of (path, status, diagnose,
3113
        variants, parameters, api_versions) as values, eg::
3114

3115
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3116
                                     (/srv/..., False, "invalid api")],
3117
                           "node2": [(/srv/..., True, "", [], [])]}
3118
          }
3119

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

    
3144
  def Exec(self, feedback_fn):
3145
    """Compute the list of OSes.
3146

3147
    """
3148
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
3149
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3150
    pol = self._DiagnoseByOS(node_data)
3151
    output = []
3152
    cluster = self.cfg.GetClusterInfo()
3153

    
3154
    for os_name in utils.NiceSort(pol.keys()):
3155
      os_data = pol[os_name]
3156
      row = []
3157
      valid = True
3158
      (variants, params, api_versions) = null_state = (set(), set(), set())
3159
      for idx, osl in enumerate(os_data.values()):
3160
        valid = bool(valid and osl and osl[0][1])
3161
        if not valid:
3162
          (variants, params, api_versions) = null_state
3163
          break
3164
        node_variants, node_params, node_api = osl[0][3:6]
3165
        if idx == 0: # first entry
3166
          variants = set(node_variants)
3167
          params = set(node_params)
3168
          api_versions = set(node_api)
3169
        else: # keep consistency
3170
          variants.intersection_update(node_variants)
3171
          params.intersection_update(node_params)
3172
          api_versions.intersection_update(node_api)
3173

    
3174
      is_hid = os_name in cluster.hidden_os
3175
      is_blk = os_name in cluster.blacklisted_os
3176
      if ((self._HID not in self.op.output_fields and is_hid) or
3177
          (self._BLK not in self.op.output_fields and is_blk) or
3178
          (self._VLD not in self.op.output_fields and not valid)):
3179
        continue
3180

    
3181
      for field in self.op.output_fields:
3182
        if field == "name":
3183
          val = os_name
3184
        elif field == self._VLD:
3185
          val = valid
3186
        elif field == "node_status":
3187
          # this is just a copy of the dict
3188
          val = {}
3189
          for node_name, nos_list in os_data.items():
3190
            val[node_name] = nos_list
3191
        elif field == "variants":
3192
          val = utils.NiceSort(list(variants))
3193
        elif field == "parameters":
3194
          val = list(params)
3195
        elif field == "api_versions":
3196
          val = list(api_versions)
3197
        elif field == self._HID:
3198
          val = is_hid
3199
        elif field == self._BLK:
3200
          val = is_blk
3201
        else:
3202
          raise errors.ParameterError(field)
3203
        row.append(val)
3204
      output.append(row)
3205

    
3206
    return output
3207

    
3208

    
3209
class LURemoveNode(LogicalUnit):
3210
  """Logical unit for removing a node.
3211

3212
  """
3213
  HPATH = "node-remove"
3214
  HTYPE = constants.HTYPE_NODE
3215
  _OP_PARAMS = [
3216
    _PNodeName,
3217
    ]
3218

    
3219
  def BuildHooksEnv(self):
3220
    """Build hooks env.
3221

3222
    This doesn't run on the target node in the pre phase as a failed
3223
    node would then be impossible to remove.
3224

3225
    """
3226
    env = {
3227
      "OP_TARGET": self.op.node_name,
3228
      "NODE_NAME": self.op.node_name,
3229
      }
3230
    all_nodes = self.cfg.GetNodeList()
3231
    try:
3232
      all_nodes.remove(self.op.node_name)
3233
    except ValueError:
3234
      logging.warning("Node %s which is about to be removed not found"
3235
                      " in the all nodes list", self.op.node_name)
3236
    return env, all_nodes, all_nodes
3237

    
3238
  def CheckPrereq(self):
3239
    """Check prerequisites.
3240

3241
    This checks:
3242
     - the node exists in the configuration
3243
     - it does not have primary or secondary instances
3244
     - it's not the master
3245

3246
    Any errors are signaled by raising errors.OpPrereqError.
3247

3248
    """
3249
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3250
    node = self.cfg.GetNodeInfo(self.op.node_name)
3251
    assert node is not None
3252

    
3253
    instance_list = self.cfg.GetInstanceList()
3254

    
3255
    masternode = self.cfg.GetMasterNode()
3256
    if node.name == masternode:
3257
      raise errors.OpPrereqError("Node is the master node,"
3258
                                 " you need to failover first.",
3259
                                 errors.ECODE_INVAL)
3260

    
3261
    for instance_name in instance_list:
3262
      instance = self.cfg.GetInstanceInfo(instance_name)
3263
      if node.name in instance.all_nodes:
3264
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3265
                                   " please remove first." % instance_name,
3266
                                   errors.ECODE_INVAL)
3267
    self.op.node_name = node.name
3268
    self.node = node
3269

    
3270
  def Exec(self, feedback_fn):
3271
    """Removes the node from the cluster.
3272

3273
    """
3274
    node = self.node
3275
    logging.info("Stopping the node daemon and removing configs from node %s",
3276
                 node.name)
3277

    
3278
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3279

    
3280
    # Promote nodes to master candidate as needed
3281
    _AdjustCandidatePool(self, exceptions=[node.name])
3282
    self.context.RemoveNode(node.name)
3283

    
3284
    # Run post hooks on the node before it's removed
3285
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3286
    try:
3287
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3288
    except:
3289
      # pylint: disable-msg=W0702
3290
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3291

    
3292
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3293
    msg = result.fail_msg
3294
    if msg:
3295
      self.LogWarning("Errors encountered on the remote node while leaving"
3296
                      " the cluster: %s", msg)
3297

    
3298
    # Remove node from our /etc/hosts
3299
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3300
      master_node = self.cfg.GetMasterNode()
3301
      result = self.rpc.call_etc_hosts_modify(master_node,
3302
                                              constants.ETC_HOSTS_REMOVE,
3303
                                              node.name, None)
3304
      result.Raise("Can't update hosts file with new host data")
3305
      _RedistributeAncillaryFiles(self)
3306

    
3307

    
3308
class LUQueryNodes(NoHooksLU):
3309
  """Logical unit for querying nodes.
3310

3311
  """
3312
  # pylint: disable-msg=W0142
3313
  _OP_PARAMS = [
3314
    _POutputFields,
3315
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3316
    ("use_locking", False, ht.TBool),
3317
    ]
3318
  REQ_BGL = False
3319

    
3320
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
3321
                    "master_candidate", "offline", "drained",
3322
                    "master_capable", "vm_capable"]
3323

    
3324
  _FIELDS_DYNAMIC = utils.FieldSet(
3325
    "dtotal", "dfree",
3326
    "mtotal", "mnode", "mfree",
3327
    "bootid",
3328
    "ctotal", "cnodes", "csockets",
3329
    )
3330

    
3331
  _FIELDS_STATIC = utils.FieldSet(*[
3332
    "pinst_cnt", "sinst_cnt",
3333
    "pinst_list", "sinst_list",
3334
    "pip", "sip", "tags",
3335
    "master",
3336
    "role"] + _SIMPLE_FIELDS
3337
    )
3338

    
3339
  def CheckArguments(self):
3340
    _CheckOutputFields(static=self._FIELDS_STATIC,
3341
                       dynamic=self._FIELDS_DYNAMIC,
3342
                       selected=self.op.output_fields)
3343

    
3344
  def ExpandNames(self):
3345
    self.needed_locks = {}
3346
    self.share_locks[locking.LEVEL_NODE] = 1
3347

    
3348
    if self.op.names:
3349
      self.wanted = _GetWantedNodes(self, self.op.names)
3350
    else:
3351
      self.wanted = locking.ALL_SET
3352

    
3353
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3354
    self.do_locking = self.do_node_query and self.op.use_locking
3355
    if self.do_locking:
3356
      # if we don't request only static fields, we need to lock the nodes
3357
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
3358

    
3359
  def Exec(self, feedback_fn):
3360
    """Computes the list of nodes and their attributes.
3361

3362
    """
3363
    all_info = self.cfg.GetAllNodesInfo()
3364
    if self.do_locking:
3365
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
3366
    elif self.wanted != locking.ALL_SET:
3367
      nodenames = self.wanted
3368
      missing = set(nodenames).difference(all_info.keys())
3369
      if missing:
3370
        raise errors.OpExecError(
3371
          "Some nodes were removed before retrieving their data: %s" % missing)
3372
    else:
3373
      nodenames = all_info.keys()
3374

    
3375
    nodenames = utils.NiceSort(nodenames)
3376
    nodelist = [all_info[name] for name in nodenames]
3377

    
3378
    # begin data gathering
3379

    
3380
    if self.do_node_query:
3381
      live_data = {}
3382
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
3383
                                          self.cfg.GetHypervisorType())
3384
      for name in nodenames:
3385
        nodeinfo = node_data[name]
3386
        if not nodeinfo.fail_msg and nodeinfo.payload:
3387
          nodeinfo = nodeinfo.payload
3388
          fn = utils.TryConvert
3389
          live_data[name] = {
3390
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
3391
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
3392
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
3393
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
3394
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
3395
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
3396
            "bootid": nodeinfo.get('bootid', None),
3397
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
3398
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
3399
            }
3400
        else:
3401
          live_data[name] = {}
3402
    else:
3403
      live_data = dict.fromkeys(nodenames, {})
3404

    
3405
    node_to_primary = dict([(name, set()) for name in nodenames])
3406
    node_to_secondary = dict([(name, set()) for name in nodenames])
3407

    
3408
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
3409
                             "sinst_cnt", "sinst_list"))
3410
    if inst_fields & frozenset(self.op.output_fields):
3411
      inst_data = self.cfg.GetAllInstancesInfo()
3412

    
3413
      for inst in inst_data.values():
3414
        if inst.primary_node in node_to_primary:
3415
          node_to_primary[inst.primary_node].add(inst.name)
3416
        for secnode in inst.secondary_nodes:
3417
          if secnode in node_to_secondary:
3418
            node_to_secondary[secnode].add(inst.name)
3419

    
3420
    master_node = self.cfg.GetMasterNode()
3421

    
3422
    # end data gathering
3423

    
3424
    output = []
3425
    for node in nodelist:
3426
      node_output = []
3427
      for field in self.op.output_fields:
3428
        if field in self._SIMPLE_FIELDS:
3429
          val = getattr(node, field)
3430
        elif field == "pinst_list":
3431
          val = list(node_to_primary[node.name])
3432
        elif field == "sinst_list":
3433
          val = list(node_to_secondary[node.name])
3434
        elif field == "pinst_cnt":
3435
          val = len(node_to_primary[node.name])
3436
        elif field == "sinst_cnt":
3437
          val = len(node_to_secondary[node.name])
3438
        elif field == "pip":
3439
          val = node.primary_ip
3440
        elif field == "sip":
3441
          val = node.secondary_ip
3442
        elif field == "tags":
3443
          val = list(node.GetTags())
3444
        elif field == "master":
3445
          val = node.name == master_node
3446
        elif self._FIELDS_DYNAMIC.Matches(field):
3447
          val = live_data[node.name].get(field, None)
3448
        elif field == "role":
3449
          if node.name == master_node:
3450
            val = "M"
3451
          elif node.master_candidate:
3452
            val = "C"
3453
          elif node.drained:
3454
            val = "D"
3455
          elif node.offline:
3456
            val = "O"
3457
          else:
3458
            val = "R"
3459
        else:
3460
          raise errors.ParameterError(field)
3461
        node_output.append(val)
3462
      output.append(node_output)
3463

    
3464
    return output
3465

    
3466

    
3467
class LUQueryNodeVolumes(NoHooksLU):
3468
  """Logical unit for getting volumes on node(s).
3469

3470
  """
3471
  _OP_PARAMS = [
3472
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3473
    ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
3474
    ]
3475
  REQ_BGL = False
3476
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3477
  _FIELDS_STATIC = utils.FieldSet("node")
3478

    
3479
  def CheckArguments(self):
3480
    _CheckOutputFields(static=self._FIELDS_STATIC,
3481
                       dynamic=self._FIELDS_DYNAMIC,
3482
                       selected=self.op.output_fields)
3483

    
3484
  def ExpandNames(self):
3485
    self.needed_locks = {}
3486
    self.share_locks[locking.LEVEL_NODE] = 1
3487
    if not self.op.nodes:
3488
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3489
    else:
3490
      self.needed_locks[locking.LEVEL_NODE] = \
3491
        _GetWantedNodes(self, self.op.nodes)
3492

    
3493
  def Exec(self, feedback_fn):
3494
    """Computes the list of nodes and their attributes.
3495

3496
    """
3497
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3498
    volumes = self.rpc.call_node_volumes(nodenames)
3499

    
3500
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3501
             in self.cfg.GetInstanceList()]
3502

    
3503
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3504

    
3505
    output = []
3506
    for node in nodenames:
3507
      nresult = volumes[node]
3508
      if nresult.offline:
3509
        continue
3510
      msg = nresult.fail_msg
3511
      if msg:
3512
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3513
        continue
3514

    
3515
      node_vols = nresult.payload[:]
3516
      node_vols.sort(key=lambda vol: vol['dev'])
3517

    
3518
      for vol in node_vols:
3519
        node_output = []
3520
        for field in self.op.output_fields:
3521
          if field == "node":
3522
            val = node
3523
          elif field == "phys":
3524
            val = vol['dev']
3525
          elif field == "vg":
3526
            val = vol['vg']
3527
          elif field == "name":
3528
            val = vol['name']
3529
          elif field == "size":
3530
            val = int(float(vol['size']))
3531
          elif field == "instance":
3532
            for inst in ilist:
3533
              if node not in lv_by_node[inst]:
3534
                continue
3535
              if vol['name'] in lv_by_node[inst][node]:
3536
                val = inst.name
3537
                break
3538
            else:
3539
              val = '-'
3540
          else:
3541
            raise errors.ParameterError(field)
3542
          node_output.append(str(val))
3543

    
3544
        output.append(node_output)
3545

    
3546
    return output
3547

    
3548

    
3549
class LUQueryNodeStorage(NoHooksLU):
3550
  """Logical unit for getting information on storage units on node(s).
3551

3552
  """
3553
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3554
  _OP_PARAMS = [
3555
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3556
    ("storage_type", ht.NoDefault, _CheckStorageType),
3557
    ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
3558
    ("name", None, ht.TMaybeString),
3559
    ]
3560
  REQ_BGL = False
3561

    
3562
  def CheckArguments(self):
3563
    _CheckOutputFields(static=self._FIELDS_STATIC,
3564
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3565
                       selected=self.op.output_fields)
3566

    
3567
  def ExpandNames(self):
3568
    self.needed_locks = {}
3569
    self.share_locks[locking.LEVEL_NODE] = 1
3570

    
3571
    if self.op.nodes:
3572
      self.needed_locks[locking.LEVEL_NODE] = \
3573
        _GetWantedNodes(self, self.op.nodes)
3574
    else:
3575
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3576

    
3577
  def Exec(self, feedback_fn):
3578
    """Computes the list of nodes and their attributes.
3579

3580
    """
3581
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3582

    
3583
    # Always get name to sort by
3584
    if constants.SF_NAME in self.op.output_fields:
3585
      fields = self.op.output_fields[:]
3586
    else:
3587
      fields = [constants.SF_NAME] + self.op.output_fields
3588

    
3589
    # Never ask for node or type as it's only known to the LU
3590
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3591
      while extra in fields:
3592
        fields.remove(extra)
3593

    
3594
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3595
    name_idx = field_idx[constants.SF_NAME]
3596

    
3597
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3598
    data = self.rpc.call_storage_list(self.nodes,
3599
                                      self.op.storage_type, st_args,
3600
                                      self.op.name, fields)
3601

    
3602
    result = []
3603

    
3604
    for node in utils.NiceSort(self.nodes):
3605
      nresult = data[node]
3606
      if nresult.offline:
3607
        continue
3608

    
3609
      msg = nresult.fail_msg
3610
      if msg:
3611
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3612
        continue
3613

    
3614
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3615

    
3616
      for name in utils.NiceSort(rows.keys()):
3617
        row = rows[name]
3618

    
3619
        out = []
3620

    
3621
        for field in self.op.output_fields:
3622
          if field == constants.SF_NODE:
3623
            val = node
3624
          elif field == constants.SF_TYPE:
3625
            val = self.op.storage_type
3626
          elif field in field_idx:
3627
            val = row[field_idx[field]]
3628
          else:
3629
            raise errors.ParameterError(field)
3630

    
3631
          out.append(val)
3632

    
3633
        result.append(out)
3634

    
3635
    return result
3636

    
3637

    
3638
class LUModifyNodeStorage(NoHooksLU):
3639
  """Logical unit for modifying a storage volume on a node.
3640

3641
  """
3642
  _OP_PARAMS = [
3643
    _PNodeName,
3644
    ("storage_type", ht.NoDefault, _CheckStorageType),
3645
    ("name", ht.NoDefault, ht.TNonEmptyString),
3646
    ("changes", ht.NoDefault, ht.TDict),
3647
    ]
3648
  REQ_BGL = False
3649

    
3650
  def CheckArguments(self):
3651
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3652

    
3653
    storage_type = self.op.storage_type
3654

    
3655
    try:
3656
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3657
    except KeyError:
3658
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3659
                                 " modified" % storage_type,
3660
                                 errors.ECODE_INVAL)
3661

    
3662
    diff = set(self.op.changes.keys()) - modifiable
3663
    if diff:
3664
      raise errors.OpPrereqError("The following fields can not be modified for"
3665
                                 " storage units of type '%s': %r" %
3666
                                 (storage_type, list(diff)),
3667
                                 errors.ECODE_INVAL)
3668

    
3669
  def ExpandNames(self):
3670
    self.needed_locks = {
3671
      locking.LEVEL_NODE: self.op.node_name,
3672
      }
3673

    
3674
  def Exec(self, feedback_fn):
3675
    """Computes the list of nodes and their attributes.
3676

3677
    """
3678
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3679
    result = self.rpc.call_storage_modify(self.op.node_name,
3680
                                          self.op.storage_type, st_args,
3681
                                          self.op.name, self.op.changes)
3682
    result.Raise("Failed to modify storage unit '%s' on %s" %
3683
                 (self.op.name, self.op.node_name))
3684

    
3685

    
3686
class LUAddNode(LogicalUnit):
3687
  """Logical unit for adding node to the cluster.
3688

3689
  """
3690
  HPATH = "node-add"
3691
  HTYPE = constants.HTYPE_NODE
3692
  _OP_PARAMS = [
3693
    _PNodeName,
3694
    ("primary_ip", None, ht.NoType),
3695
    ("secondary_ip", None, ht.TMaybeString),
3696
    ("readd", False, ht.TBool),
3697
    ("group", None, ht.TMaybeString),
3698
    ("master_capable", None, ht.TMaybeBool),
3699
    ("vm_capable", None, ht.TMaybeBool),
3700
    ]
3701
  _NFLAGS = ["master_capable", "vm_capable"]
3702

    
3703
  def CheckArguments(self):
3704
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
3705
    # validate/normalize the node name
3706
    self.hostname = netutils.GetHostname(name=self.op.node_name,
3707
                                         family=self.primary_ip_family)
3708
    self.op.node_name = self.hostname.name
3709
    if self.op.readd and self.op.group:
3710
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
3711
                                 " being readded", errors.ECODE_INVAL)
3712

    
3713
  def BuildHooksEnv(self):
3714
    """Build hooks env.
3715

3716
    This will run on all nodes before, and on all nodes + the new node after.
3717

3718
    """
3719
    env = {
3720
      "OP_TARGET": self.op.node_name,
3721
      "NODE_NAME": self.op.node_name,
3722
      "NODE_PIP": self.op.primary_ip,
3723
      "NODE_SIP": self.op.secondary_ip,
3724
      "MASTER_CAPABLE": str(self.op.master_capable),
3725
      "VM_CAPABLE": str(self.op.vm_capable),
3726
      }
3727
    nodes_0 = self.cfg.GetNodeList()
3728
    nodes_1 = nodes_0 + [self.op.node_name, ]
3729
    return env, nodes_0, nodes_1
3730

    
3731
  def CheckPrereq(self):
3732
    """Check prerequisites.
3733

3734
    This checks:
3735
     - the new node is not already in the config
3736
     - it is resolvable
3737
     - its parameters (single/dual homed) matches the cluster
3738

3739
    Any errors are signaled by raising errors.OpPrereqError.
3740

3741
    """
3742
    cfg = self.cfg
3743
    hostname = self.hostname
3744
    node = hostname.name
3745
    primary_ip = self.op.primary_ip = hostname.ip
3746
    if self.op.secondary_ip is None:
3747
      if self.primary_ip_family == netutils.IP6Address.family:
3748
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
3749
                                   " IPv4 address must be given as secondary",
3750
                                   errors.ECODE_INVAL)
3751
      self.op.secondary_ip = primary_ip
3752

    
3753
    secondary_ip = self.op.secondary_ip
3754
    if not netutils.IP4Address.IsValid(secondary_ip):
3755
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
3756
                                 " address" % secondary_ip, errors.ECODE_INVAL)
3757

    
3758
    node_list = cfg.GetNodeList()
3759
    if not self.op.readd and node in node_list:
3760
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3761
                                 node, errors.ECODE_EXISTS)
3762
    elif self.op.readd and node not in node_list:
3763
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3764
                                 errors.ECODE_NOENT)
3765

    
3766
    self.changed_primary_ip = False
3767

    
3768
    for existing_node_name in node_list:
3769
      existing_node = cfg.GetNodeInfo(existing_node_name)
3770

    
3771
      if self.op.readd and node == existing_node_name:
3772
        if existing_node.secondary_ip != secondary_ip:
3773
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3774
                                     " address configuration as before",
3775
                                     errors.ECODE_INVAL)
3776
        if existing_node.primary_ip != primary_ip:
3777
          self.changed_primary_ip = True
3778

    
3779
        continue
3780

    
3781
      if (existing_node.primary_ip == primary_ip or
3782
          existing_node.secondary_ip == primary_ip or
3783
          existing_node.primary_ip == secondary_ip or
3784
          existing_node.secondary_ip == secondary_ip):
3785
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3786
                                   " existing node %s" % existing_node.name,
3787
                                   errors.ECODE_NOTUNIQUE)
3788

    
3789
    # After this 'if' block, None is no longer a valid value for the
3790
    # _capable op attributes
3791
    if self.op.readd:
3792
      old_node = self.cfg.GetNodeInfo(node)
3793
      assert old_node is not None, "Can't retrieve locked node %s" % node
3794
      for attr in self._NFLAGS:
3795
        if getattr(self.op, attr) is None:
3796
          setattr(self.op, attr, getattr(old_node, attr))
3797
    else:
3798
      for attr in self._NFLAGS:
3799
        if getattr(self.op, attr) is None:
3800
          setattr(self.op, attr, True)
3801

    
3802
    if self.op.readd and not self.op.vm_capable:
3803
      pri, sec = cfg.GetNodeInstances(node)
3804
      if pri or sec:
3805
        raise errors.OpPrereqError("Node %s being re-added with vm_capable"
3806
                                   " flag set to false, but it already holds"
3807
                                   " instances" % node,
3808
                                   errors.ECODE_STATE)
3809

    
3810
    # check that the type of the node (single versus dual homed) is the
3811
    # same as for the master
3812
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
3813
    master_singlehomed = myself.secondary_ip == myself.primary_ip
3814
    newbie_singlehomed = secondary_ip == primary_ip
3815
    if master_singlehomed != newbie_singlehomed:
3816
      if master_singlehomed:
3817
        raise errors.OpPrereqError("The master has no private ip but the"
3818
                                   " new node has one",
3819
                                   errors.ECODE_INVAL)
3820
      else:
3821
        raise errors.OpPrereqError("The master has a private ip but the"
3822
                                   " new node doesn't have one",
3823
                                   errors.ECODE_INVAL)
3824

    
3825
    # checks reachability
3826
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3827
      raise errors.OpPrereqError("Node not reachable by ping",
3828
                                 errors.ECODE_ENVIRON)
3829

    
3830
    if not newbie_singlehomed:
3831
      # check reachability from my secondary ip to newbie's secondary ip
3832
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3833
                           source=myself.secondary_ip):
3834
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3835
                                   " based ping to noded port",
3836
                                   errors.ECODE_ENVIRON)
3837

    
3838
    if self.op.readd:
3839
      exceptions = [node]
3840
    else:
3841
      exceptions = []
3842

    
3843
    if self.op.master_capable:
3844
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3845
    else:
3846
      self.master_candidate = False
3847

    
3848
    if self.op.readd:
3849
      self.new_node = old_node
3850
    else:
3851
      node_group = cfg.LookupNodeGroup(self.op.group)
3852
      self.new_node = objects.Node(name=node,
3853
                                   primary_ip=primary_ip,
3854
                                   secondary_ip=secondary_ip,
3855
                                   master_candidate=self.master_candidate,
3856
                                   offline=False, drained=False,
3857
                                   group=node_group)
3858

    
3859
  def Exec(self, feedback_fn):
3860
    """Adds the new node to the cluster.
3861

3862
    """
3863
    new_node = self.new_node
3864
    node = new_node.name
3865

    
3866
    # for re-adds, reset the offline/drained/master-candidate flags;
3867
    # we need to reset here, otherwise offline would prevent RPC calls
3868
    # later in the procedure; this also means that if the re-add
3869
    # fails, we are left with a non-offlined, broken node
3870
    if self.op.readd:
3871
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3872
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3873
      # if we demote the node, we do cleanup later in the procedure
3874
      new_node.master_candidate = self.master_candidate
3875
      if self.changed_primary_ip:
3876
        new_node.primary_ip = self.op.primary_ip
3877

    
3878
    # copy the master/vm_capable flags
3879
    for attr in self._NFLAGS:
3880
      setattr(new_node, attr, getattr(self.op, attr))
3881

    
3882
    # notify the user about any possible mc promotion
3883
    if new_node.master_candidate:
3884
      self.LogInfo("Node will be a master candidate")
3885

    
3886
    # check connectivity
3887
    result = self.rpc.call_version([node])[node]
3888
    result.Raise("Can't get version information from node %s" % node)
3889
    if constants.PROTOCOL_VERSION == result.payload:
3890
      logging.info("Communication to node %s fine, sw version %s match",
3891
                   node, result.payload)
3892
    else:
3893
      raise errors.OpExecError("Version mismatch master version %s,"
3894
                               " node version %s" %
3895
                               (constants.PROTOCOL_VERSION, result.payload))
3896

    
3897
    # Add node to our /etc/hosts, and add key to known_hosts
3898
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3899
      master_node = self.cfg.GetMasterNode()
3900
      result = self.rpc.call_etc_hosts_modify(master_node,
3901
                                              constants.ETC_HOSTS_ADD,
3902
                                              self.hostname.name,
3903
                                              self.hostname.ip)
3904
      result.Raise("Can't update hosts file with new host data")
3905

    
3906
    if new_node.secondary_ip != new_node.primary_ip:
3907
      result = self.rpc.call_node_has_ip_address(new_node.name,
3908
                                                 new_node.secondary_ip)
3909
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
3910
                   prereq=True, ecode=errors.ECODE_ENVIRON)
3911
      if not result.payload:
3912
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
3913
                                 " you gave (%s). Please fix and re-run this"
3914
                                 " command." % new_node.secondary_ip)
3915

    
3916
    node_verify_list = [self.cfg.GetMasterNode()]
3917
    node_verify_param = {
3918
      constants.NV_NODELIST: [node],
3919
      # TODO: do a node-net-test as well?
3920
    }
3921

    
3922
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3923
                                       self.cfg.GetClusterName())
3924
    for verifier in node_verify_list:
3925
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3926
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3927
      if nl_payload:
3928
        for failed in nl_payload:
3929
          feedback_fn("ssh/hostname verification failed"
3930
                      " (checking from %s): %s" %
3931
                      (verifier, nl_payload[failed]))
3932
        raise errors.OpExecError("ssh/hostname verification failed.")
3933

    
3934
    if self.op.readd:
3935
      _RedistributeAncillaryFiles(self)
3936
      self.context.ReaddNode(new_node)
3937
      # make sure we redistribute the config
3938
      self.cfg.Update(new_node, feedback_fn)
3939
      # and make sure the new node will not have old files around
3940
      if not new_node.master_candidate:
3941
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3942
        msg = result.fail_msg
3943
        if msg:
3944
          self.LogWarning("Node failed to demote itself from master"
3945
                          " candidate status: %s" % msg)
3946
    else:
3947
      _RedistributeAncillaryFiles(self, additional_nodes=[node],
3948
                                  additional_vm=self.op.vm_capable)
3949
      self.context.AddNode(new_node, self.proc.GetECId())
3950

    
3951

    
3952
class LUSetNodeParams(LogicalUnit):
3953
  """Modifies the parameters of a node.
3954

3955
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
3956
      to the node role (as _ROLE_*)
3957
  @cvar _R2F: a dictionary from node role to tuples of flags
3958
  @cvar _FLAGS: a list of attribute names corresponding to the flags
3959

3960
  """
3961
  HPATH = "node-modify"
3962
  HTYPE = constants.HTYPE_NODE
3963
  _OP_PARAMS = [
3964
    _PNodeName,
3965
    ("master_candidate", None, ht.TMaybeBool),
3966
    ("offline", None, ht.TMaybeBool),
3967
    ("drained", None, ht.TMaybeBool),
3968
    ("auto_promote", False, ht.TBool),
3969
    ("master_capable", None, ht.TMaybeBool),
3970
    ("vm_capable", None, ht.TMaybeBool),
3971
    _PForce,
3972
    ]
3973
  REQ_BGL = False
3974
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
3975
  _F2R = {
3976
    (True, False, False): _ROLE_CANDIDATE,
3977
    (False, True, False): _ROLE_DRAINED,
3978
    (False, False, True): _ROLE_OFFLINE,
3979
    (False, False, False): _ROLE_REGULAR,
3980
    }
3981
  _R2F = dict((v, k) for k, v in _F2R.items())
3982
  _FLAGS = ["master_candidate", "drained", "offline"]
3983

    
3984
  def CheckArguments(self):
3985
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3986
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
3987
                self.op.master_capable, self.op.vm_capable]
3988
    if all_mods.count(None) == len(all_mods):
3989
      raise errors.OpPrereqError("Please pass at least one modification",
3990
                                 errors.ECODE_INVAL)
3991
    if all_mods.count(True) > 1:
3992
      raise errors.OpPrereqError("Can't set the node into more than one"
3993
                                 " state at the same time",
3994
                                 errors.ECODE_INVAL)
3995

    
3996
    # Boolean value that tells us whether we might be demoting from MC
3997
    self.might_demote = (self.op.master_candidate == False or
3998
                         self.op.offline == True or
3999
                         self.op.drained == True or
4000
                         self.op.master_capable == False)
4001

    
4002
    self.lock_all = self.op.auto_promote and self.might_demote
4003

    
4004
  def ExpandNames(self):
4005
    if self.lock_all:
4006
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
4007
    else:
4008
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
4009

    
4010
  def BuildHooksEnv(self):
4011
    """Build hooks env.
4012

4013
    This runs on the master node.
4014

4015
    """
4016
    env = {
4017
      "OP_TARGET": self.op.node_name,
4018
      "MASTER_CANDIDATE": str(self.op.master_candidate),
4019
      "OFFLINE": str(self.op.offline),
4020
      "DRAINED": str(self.op.drained),
4021
      "MASTER_CAPABLE": str(self.op.master_capable),
4022
      "VM_CAPABLE": str(self.op.vm_capable),
4023
      }
4024
    nl = [self.cfg.GetMasterNode(),
4025
          self.op.node_name]
4026
    return env, nl, nl
4027

    
4028
  def CheckPrereq(self):
4029
    """Check prerequisites.
4030

4031
    This only checks the instance list against the existing names.
4032

4033
    """
4034
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
4035

    
4036
    if (self.op.master_candidate is not None or
4037
        self.op.drained is not None or
4038
        self.op.offline is not None):
4039
      # we can't change the master's node flags
4040
      if self.op.node_name == self.cfg.GetMasterNode():
4041
        raise errors.OpPrereqError("The master role can be changed"
4042
                                   " only via master-failover",
4043
                                   errors.ECODE_INVAL)
4044

    
4045
    if self.op.master_candidate and not node.master_capable:
4046
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4047
                                 " it a master candidate" % node.name,
4048
                                 errors.ECODE_STATE)
4049

    
4050
    if self.op.vm_capable == False:
4051
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
4052
      if ipri or isec:
4053
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
4054
                                   " the vm_capable flag" % node.name,
4055
                                   errors.ECODE_STATE)
4056

    
4057
    if node.master_candidate and self.might_demote and not self.lock_all:
4058
      assert not self.op.auto_promote, "auto-promote set but lock_all not"
4059
      # check if after removing the current node, we're missing master
4060
      # candidates
4061
      (mc_remaining, mc_should, _) = \
4062
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
4063
      if mc_remaining < mc_should:
4064
        raise errors.OpPrereqError("Not enough master candidates, please"
4065
                                   " pass auto_promote to allow promotion",
4066
                                   errors.ECODE_STATE)
4067

    
4068
    self.old_flags = old_flags = (node.master_candidate,
4069
                                  node.drained, node.offline)
4070
    assert old_flags in self._F2R, "Un-handled old flags  %s" % str(old_flags)
4071
    self.old_role = self._F2R[old_flags]
4072

    
4073
    # Check for ineffective changes
4074
    for attr in self._FLAGS:
4075
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
4076
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
4077
        setattr(self.op, attr, None)
4078

    
4079
    # Past this point, any flag change to False means a transition
4080
    # away from the respective state, as only real changes are kept
4081

    
4082
    # If we're being deofflined/drained, we'll MC ourself if needed
4083
    if (self.op.drained == False or self.op.offline == False or
4084
        (self.op.master_capable and not node.master_capable)):
4085
      if _DecideSelfPromotion(self):
4086
        self.op.master_candidate = True
4087
        self.LogInfo("Auto-promoting node to master candidate")
4088

    
4089
    # If we're no longer master capable, we'll demote ourselves from MC
4090
    if self.op.master_capable == False and node.master_candidate:
4091
      self.LogInfo("Demoting from master candidate")
4092
      self.op.master_candidate = False
4093

    
4094
  def Exec(self, feedback_fn):
4095
    """Modifies a node.
4096

4097
    """
4098
    node = self.node
4099
    old_role = self.old_role
4100

    
4101
    assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
4102

    
4103
    # compute new flags
4104
    if self.op.master_candidate:
4105
      new_role = self._ROLE_CANDIDATE
4106
    elif self.op.drained:
4107
      new_role = self._ROLE_DRAINED
4108
    elif self.op.offline:
4109
      new_role = self._ROLE_OFFLINE
4110
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
4111
      # False is still in new flags, which means we're un-setting (the
4112
      # only) True flag
4113
      new_role = self._ROLE_REGULAR
4114
    else: # no new flags, nothing, keep old role
4115
      new_role = old_role
4116

    
4117
    result = []
4118

    
4119
    for attr in ["master_capable", "vm_capable"]:
4120
      val = getattr(self.op, attr)
4121
      if val is not None:
4122
        setattr(node, attr, val)
4123
        result.append((attr, str(val)))
4124

    
4125
    if new_role != old_role:
4126
      # Tell the node to demote itself, if no longer MC and not offline
4127
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
4128
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
4129
        if msg:
4130
          self.LogWarning("Node failed to demote itself: %s", msg)
4131

    
4132
      new_flags = self._R2F[new_role]
4133
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
4134
        if of != nf:
4135
          result.append((desc, str(nf)))
4136
      (node.master_candidate, node.drained, node.offline) = new_flags
4137

    
4138
      # we locked all nodes, we adjust the CP before updating this node
4139
      if self.lock_all:
4140
        _AdjustCandidatePool(self, [node.name])
4141

    
4142
    # this will trigger configuration file update, if needed
4143
    self.cfg.Update(node, feedback_fn)
4144

    
4145
    # this will trigger job queue propagation or cleanup if the mc
4146
    # flag changed
4147
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
4148
      self.context.ReaddNode(node)
4149

    
4150
    return result
4151

    
4152

    
4153
class LUPowercycleNode(NoHooksLU):
4154
  """Powercycles a node.
4155

4156
  """
4157
  _OP_PARAMS = [
4158
    _PNodeName,
4159
    _PForce,
4160
    ]
4161
  REQ_BGL = False
4162

    
4163
  def CheckArguments(self):
4164
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4165
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4166
      raise errors.OpPrereqError("The node is the master and the force"
4167
                                 " parameter was not set",
4168
                                 errors.ECODE_INVAL)
4169

    
4170
  def ExpandNames(self):
4171
    """Locking for PowercycleNode.
4172

4173
    This is a last-resort option and shouldn't block on other
4174
    jobs. Therefore, we grab no locks.
4175

4176
    """
4177
    self.needed_locks = {}
4178

    
4179
  def Exec(self, feedback_fn):
4180
    """Reboots a node.
4181

4182
    """
4183
    result = self.rpc.call_node_powercycle(self.op.node_name,
4184
                                           self.cfg.GetHypervisorType())
4185
    result.Raise("Failed to schedule the reboot")
4186
    return result.payload
4187

    
4188

    
4189
class LUQueryClusterInfo(NoHooksLU):
4190
  """Query cluster configuration.
4191

4192
  """
4193
  REQ_BGL = False
4194

    
4195
  def ExpandNames(self):
4196
    self.needed_locks = {}
4197

    
4198
  def Exec(self, feedback_fn):
4199
    """Return cluster config.
4200

4201
    """
4202
    cluster = self.cfg.GetClusterInfo()
4203
    os_hvp = {}
4204

    
4205
    # Filter just for enabled hypervisors
4206
    for os_name, hv_dict in cluster.os_hvp.items():
4207
      os_hvp[os_name] = {}
4208
      for hv_name, hv_params in hv_dict.items():
4209
        if hv_name in cluster.enabled_hypervisors:
4210
          os_hvp[os_name][hv_name] = hv_params
4211

    
4212
    # Convert ip_family to ip_version
4213
    primary_ip_version = constants.IP4_VERSION
4214
    if cluster.primary_ip_family == netutils.IP6Address.family:
4215
      primary_ip_version = constants.IP6_VERSION
4216

    
4217
    result = {
4218
      "software_version": constants.RELEASE_VERSION,
4219
      "protocol_version": constants.PROTOCOL_VERSION,
4220
      "config_version": constants.CONFIG_VERSION,
4221
      "os_api_version": max(constants.OS_API_VERSIONS),
4222
      "export_version": constants.EXPORT_VERSION,
4223
      "architecture": (platform.architecture()[0], platform.machine()),
4224
      "name": cluster.cluster_name,
4225
      "master": cluster.master_node,
4226
      "default_hypervisor": cluster.enabled_hypervisors[0],
4227
      "enabled_hypervisors": cluster.enabled_hypervisors,
4228
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4229
                        for hypervisor_name in cluster.enabled_hypervisors]),
4230
      "os_hvp": os_hvp,
4231
      "beparams": cluster.beparams,
4232
      "osparams": cluster.osparams,
4233
      "nicparams": cluster.nicparams,
4234
      "candidate_pool_size": cluster.candidate_pool_size,
4235
      "master_netdev": cluster.master_netdev,
4236
      "volume_group_name": cluster.volume_group_name,
4237
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
4238
      "file_storage_dir": cluster.file_storage_dir,
4239
      "maintain_node_health": cluster.maintain_node_health,
4240
      "ctime": cluster.ctime,
4241
      "mtime": cluster.mtime,
4242
      "uuid": cluster.uuid,
4243
      "tags": list(cluster.GetTags()),
4244
      "uid_pool": cluster.uid_pool,
4245
      "default_iallocator": cluster.default_iallocator,
4246
      "reserved_lvs": cluster.reserved_lvs,
4247
      "primary_ip_version": primary_ip_version,
4248
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
4249
      }
4250

    
4251
    return result
4252

    
4253

    
4254
class LUQueryConfigValues(NoHooksLU):
4255
  """Return configuration values.
4256

4257
  """
4258
  _OP_PARAMS = [_POutputFields]
4259
  REQ_BGL = False
4260
  _FIELDS_DYNAMIC = utils.FieldSet()
4261
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4262
                                  "watcher_pause", "volume_group_name")
4263

    
4264
  def CheckArguments(self):
4265
    _CheckOutputFields(static=self._FIELDS_STATIC,
4266
                       dynamic=self._FIELDS_DYNAMIC,
4267
                       selected=self.op.output_fields)
4268

    
4269
  def ExpandNames(self):
4270
    self.needed_locks = {}
4271

    
4272
  def Exec(self, feedback_fn):
4273
    """Dump a representation of the cluster config to the standard output.
4274

4275
    """
4276
    values = []
4277
    for field in self.op.output_fields:
4278
      if field == "cluster_name":
4279
        entry = self.cfg.GetClusterName()
4280
      elif field == "master_node":
4281
        entry = self.cfg.GetMasterNode()
4282
      elif field == "drain_flag":
4283
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4284
      elif field == "watcher_pause":
4285
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4286
      elif field == "volume_group_name":
4287
        entry = self.cfg.GetVGName()
4288
      else:
4289
        raise errors.ParameterError(field)
4290
      values.append(entry)
4291
    return values
4292

    
4293

    
4294
class LUActivateInstanceDisks(NoHooksLU):
4295
  """Bring up an instance's disks.
4296

4297
  """
4298
  _OP_PARAMS = [
4299
    _PInstanceName,
4300
    ("ignore_size", False, ht.TBool),
4301
    ]
4302
  REQ_BGL = False
4303

    
4304
  def ExpandNames(self):
4305
    self._ExpandAndLockInstance()
4306
    self.needed_locks[locking.LEVEL_NODE] = []
4307
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4308

    
4309
  def DeclareLocks(self, level):
4310
    if level == locking.LEVEL_NODE:
4311
      self._LockInstancesNodes()
4312

    
4313
  def CheckPrereq(self):
4314
    """Check prerequisites.
4315

4316
    This checks that the instance is in the cluster.
4317

4318
    """
4319
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4320
    assert self.instance is not None, \
4321
      "Cannot retrieve locked instance %s" % self.op.instance_name
4322
    _CheckNodeOnline(self, self.instance.primary_node)
4323

    
4324
  def Exec(self, feedback_fn):
4325
    """Activate the disks.
4326

4327
    """
4328
    disks_ok, disks_info = \
4329
              _AssembleInstanceDisks(self, self.instance,
4330
                                     ignore_size=self.op.ignore_size)
4331
    if not disks_ok:
4332
      raise errors.OpExecError("Cannot activate block devices")
4333

    
4334
    return disks_info
4335

    
4336

    
4337
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4338
                           ignore_size=False):
4339
  """Prepare the block devices for an instance.
4340

4341
  This sets up the block devices on all nodes.
4342

4343
  @type lu: L{LogicalUnit}
4344
  @param lu: the logical unit on whose behalf we execute
4345
  @type instance: L{objects.Instance}
4346
  @param instance: the instance for whose disks we assemble
4347
  @type disks: list of L{objects.Disk} or None
4348
  @param disks: which disks to assemble (or all, if None)
4349
  @type ignore_secondaries: boolean
4350
  @param ignore_secondaries: if true, errors on secondary nodes
4351
      won't result in an error return from the function
4352
  @type ignore_size: boolean
4353
  @param ignore_size: if true, the current known size of the disk
4354
      will not be used during the disk activation, useful for cases
4355
      when the size is wrong
4356
  @return: False if the operation failed, otherwise a list of
4357
      (host, instance_visible_name, node_visible_name)
4358
      with the mapping from node devices to instance devices
4359

4360
  """
4361
  device_info = []
4362
  disks_ok = True
4363
  iname = instance.name
4364
  disks = _ExpandCheckDisks(instance, disks)
4365

    
4366
  # With the two passes mechanism we try to reduce the window of
4367
  # opportunity for the race condition of switching DRBD to primary
4368
  # before handshaking occured, but we do not eliminate it
4369

    
4370
  # The proper fix would be to wait (with some limits) until the
4371
  # connection has been made and drbd transitions from WFConnection
4372
  # into any other network-connected state (Connected, SyncTarget,
4373
  # SyncSource, etc.)
4374

    
4375
  # 1st pass, assemble on all nodes in secondary mode
4376
  for inst_disk in disks:
4377
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4378
      if ignore_size:
4379
        node_disk = node_disk.Copy()
4380
        node_disk.UnsetSize()
4381
      lu.cfg.SetDiskID(node_disk, node)
4382
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
4383
      msg = result.fail_msg
4384
      if msg:
4385
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4386
                           " (is_primary=False, pass=1): %s",
4387
                           inst_disk.iv_name, node, msg)
4388
        if not ignore_secondaries:
4389
          disks_ok = False
4390

    
4391
  # FIXME: race condition on drbd migration to primary
4392

    
4393
  # 2nd pass, do only the primary node
4394
  for inst_disk in disks:
4395
    dev_path = None
4396

    
4397
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4398
      if node != instance.primary_node:
4399
        continue
4400
      if ignore_size:
4401
        node_disk = node_disk.Copy()
4402
        node_disk.UnsetSize()
4403
      lu.cfg.SetDiskID(node_disk, node)
4404
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
4405
      msg = result.fail_msg
4406
      if msg:
4407
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4408
                           " (is_primary=True, pass=2): %s",
4409
                           inst_disk.iv_name, node, msg)
4410
        disks_ok = False
4411
      else:
4412
        dev_path = result.payload
4413

    
4414
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4415

    
4416
  # leave the disks configured for the primary node
4417
  # this is a workaround that would be fixed better by
4418
  # improving the logical/physical id handling
4419
  for disk in disks:
4420
    lu.cfg.SetDiskID(disk, instance.primary_node)
4421

    
4422
  return disks_ok, device_info
4423

    
4424

    
4425
def _StartInstanceDisks(lu, instance, force):
4426
  """Start the disks of an instance.
4427

4428
  """
4429
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4430
                                           ignore_secondaries=force)
4431
  if not disks_ok:
4432
    _ShutdownInstanceDisks(lu, instance)
4433
    if force is not None and not force:
4434
      lu.proc.LogWarning("", hint="If the message above refers to a"
4435
                         " secondary node,"
4436
                         " you can retry the operation using '--force'.")
4437
    raise errors.OpExecError("Disk consistency error")
4438

    
4439

    
4440
class LUDeactivateInstanceDisks(NoHooksLU):
4441
  """Shutdown an instance's disks.
4442

4443
  """
4444
  _OP_PARAMS = [
4445
    _PInstanceName,
4446
    ]
4447
  REQ_BGL = False
4448

    
4449
  def ExpandNames(self):
4450
    self._ExpandAndLockInstance()
4451
    self.needed_locks[locking.LEVEL_NODE] = []
4452
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4453

    
4454
  def DeclareLocks(self, level):
4455
    if level == locking.LEVEL_NODE:
4456
      self._LockInstancesNodes()
4457

    
4458
  def CheckPrereq(self):
4459
    """Check prerequisites.
4460

4461
    This checks that the instance is in the cluster.
4462

4463
    """
4464
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4465
    assert self.instance is not None, \
4466
      "Cannot retrieve locked instance %s" % self.op.instance_name
4467

    
4468
  def Exec(self, feedback_fn):
4469
    """Deactivate the disks
4470

4471
    """
4472
    instance = self.instance
4473
    _SafeShutdownInstanceDisks(self, instance)
4474

    
4475

    
4476
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4477
  """Shutdown block devices of an instance.
4478

4479
  This function checks if an instance is running, before calling
4480
  _ShutdownInstanceDisks.
4481

4482
  """
4483
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4484
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4485

    
4486

    
4487
def _ExpandCheckDisks(instance, disks):
4488
  """Return the instance disks selected by the disks list
4489

4490
  @type disks: list of L{objects.Disk} or None
4491
  @param disks: selected disks
4492
  @rtype: list of L{objects.Disk}
4493
  @return: selected instance disks to act on
4494

4495
  """
4496
  if disks is None:
4497
    return instance.disks
4498
  else:
4499
    if not set(disks).issubset(instance.disks):
4500
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4501
                                   " target instance")
4502
    return disks
4503

    
4504

    
4505
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4506
  """Shutdown block devices of an instance.
4507

4508
  This does the shutdown on all nodes of the instance.
4509

4510
  If the ignore_primary is false, errors on the primary node are
4511
  ignored.
4512

4513
  """
4514
  all_result = True
4515
  disks = _ExpandCheckDisks(instance, disks)
4516

    
4517
  for disk in disks:
4518
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4519
      lu.cfg.SetDiskID(top_disk, node)
4520
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4521
      msg = result.fail_msg
4522
      if msg:
4523
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4524
                      disk.iv_name, node, msg)
4525
        if not ignore_primary or node != instance.primary_node:
4526
          all_result = False
4527
  return all_result
4528

    
4529

    
4530
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4531
  """Checks if a node has enough free memory.
4532

4533
  This function check if a given node has the needed amount of free
4534
  memory. In case the node has less memory or we cannot get the
4535
  information from the node, this function raise an OpPrereqError
4536
  exception.
4537

4538
  @type lu: C{LogicalUnit}
4539
  @param lu: a logical unit from which we get configuration data
4540
  @type node: C{str}
4541
  @param node: the node to check
4542
  @type reason: C{str}
4543
  @param reason: string to use in the error message
4544
  @type requested: C{int}
4545
  @param requested: the amount of memory in MiB to check for
4546
  @type hypervisor_name: C{str}
4547
  @param hypervisor_name: the hypervisor to ask for memory stats
4548
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4549
      we cannot check the node
4550

4551
  """
4552
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
4553
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4554
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4555
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4556
  if not isinstance(free_mem, int):
4557
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4558
                               " was '%s'" % (node, free_mem),
4559
                               errors.ECODE_ENVIRON)
4560
  if requested > free_mem:
4561
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
4562
                               " needed %s MiB, available %s MiB" %
4563
                               (node, reason, requested, free_mem),
4564
                               errors.ECODE_NORES)
4565

    
4566

    
4567
def _CheckNodesFreeDisk(lu, nodenames, requested):
4568
  """Checks if nodes have enough free disk space in the default VG.
4569

4570
  This function check if all given nodes have the needed amount of
4571
  free disk. In case any node has less disk or we cannot get the
4572
  information from the node, this function raise an OpPrereqError
4573
  exception.
4574

4575
  @type lu: C{LogicalUnit}
4576
  @param lu: a logical unit from which we get configuration data
4577
  @type nodenames: C{list}
4578
  @param nodenames: the list of node names to check
4579
  @type requested: C{int}
4580
  @param requested: the amount of disk in MiB to check for
4581
  @raise errors.OpPrereqError: if the node doesn't have enough disk, or
4582
      we cannot check the node
4583

4584
  """
4585
  nodeinfo = lu.rpc.call_node_info(nodenames, lu.cfg.GetVGName(),
4586
                                   lu.cfg.GetHypervisorType())
4587
  for node in nodenames:
4588
    info = nodeinfo[node]
4589
    info.Raise("Cannot get current information from node %s" % node,
4590
               prereq=True, ecode=errors.ECODE_ENVIRON)
4591
    vg_free = info.payload.get("vg_free", None)
4592
    if not isinstance(vg_free, int):
4593
      raise errors.OpPrereqError("Can't compute free disk space on node %s,"
4594
                                 " result was '%s'" % (node, vg_free),
4595
                                 errors.ECODE_ENVIRON)
4596
    if requested > vg_free:
4597
      raise errors.OpPrereqError("Not enough disk space on target node %s:"
4598
                                 " required %d MiB, available %d MiB" %
4599
                                 (node, requested, vg_free),
4600
                                 errors.ECODE_NORES)
4601

    
4602

    
4603
class LUStartupInstance(LogicalUnit):
4604
  """Starts an instance.
4605

4606
  """
4607
  HPATH = "instance-start"
4608
  HTYPE = constants.HTYPE_INSTANCE
4609
  _OP_PARAMS = [
4610
    _PInstanceName,
4611
    _PForce,
4612
    _PIgnoreOfflineNodes,
4613
    ("hvparams", ht.EmptyDict, ht.TDict),
4614
    ("beparams", ht.EmptyDict, ht.TDict),
4615
    ]
4616
  REQ_BGL = False
4617

    
4618
  def CheckArguments(self):
4619
    # extra beparams
4620
    if self.op.beparams:
4621
      # fill the beparams dict
4622
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
4623

    
4624
  def ExpandNames(self):
4625
    self._ExpandAndLockInstance()
4626

    
4627
  def BuildHooksEnv(self):
4628
    """Build hooks env.
4629

4630
    This runs on master, primary and secondary nodes of the instance.
4631

4632
    """
4633
    env = {
4634
      "FORCE": self.op.force,
4635
      }
4636
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4637
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4638
    return env, nl, nl
4639

    
4640
  def CheckPrereq(self):
4641
    """Check prerequisites.
4642

4643
    This checks that the instance is in the cluster.
4644

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

    
4650
    # extra hvparams
4651
    if self.op.hvparams:
4652
      # check hypervisor parameter syntax (locally)
4653
      cluster = self.cfg.GetClusterInfo()
4654
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
4655
      filled_hvp = cluster.FillHV(instance)
4656
      filled_hvp.update(self.op.hvparams)
4657
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
4658
      hv_type.CheckParameterSyntax(filled_hvp)
4659
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
4660

    
4661
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
4662

    
4663
    if self.primary_offline and self.op.ignore_offline_nodes:
4664
      self.proc.LogWarning("Ignoring offline primary node")
4665

    
4666
      if self.op.hvparams or self.op.beparams:
4667
        self.proc.LogWarning("Overridden parameters are ignored")
4668
    else:
4669
      _CheckNodeOnline(self, instance.primary_node)
4670

    
4671
      bep = self.cfg.GetClusterInfo().FillBE(instance)
4672

    
4673
      # check bridges existence
4674
      _CheckInstanceBridgesExist(self, instance)
4675

    
4676
      remote_info = self.rpc.call_instance_info(instance.primary_node,
4677
                                                instance.name,
4678
                                                instance.hypervisor)
4679
      remote_info.Raise("Error checking node %s" % instance.primary_node,
4680
                        prereq=True, ecode=errors.ECODE_ENVIRON)
4681
      if not remote_info.payload: # not running already
4682
        _CheckNodeFreeMemory(self, instance.primary_node,
4683
                             "starting instance %s" % instance.name,
4684
                             bep[constants.BE_MEMORY], instance.hypervisor)
4685

    
4686
  def Exec(self, feedback_fn):
4687
    """Start the instance.
4688

4689
    """
4690
    instance = self.instance
4691
    force = self.op.force
4692

    
4693
    self.cfg.MarkInstanceUp(instance.name)
4694

    
4695
    if self.primary_offline:
4696
      assert self.op.ignore_offline_nodes
4697
      self.proc.LogInfo("Primary node offline, marked instance as started")
4698
    else:
4699
      node_current = instance.primary_node
4700

    
4701
      _StartInstanceDisks(self, instance, force)
4702

    
4703
      result = self.rpc.call_instance_start(node_current, instance,
4704
                                            self.op.hvparams, self.op.beparams)
4705
      msg = result.fail_msg
4706
      if msg:
4707
        _ShutdownInstanceDisks(self, instance)
4708
        raise errors.OpExecError("Could not start instance: %s" % msg)
4709

    
4710

    
4711
class LURebootInstance(LogicalUnit):
4712
  """Reboot an instance.
4713

4714
  """
4715
  HPATH = "instance-reboot"
4716
  HTYPE = constants.HTYPE_INSTANCE
4717
  _OP_PARAMS = [
4718
    _PInstanceName,
4719
    ("ignore_secondaries", False, ht.TBool),
4720
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES)),
4721
    _PShutdownTimeout,
4722
    ]
4723
  REQ_BGL = False
4724

    
4725
  def ExpandNames(self):
4726
    self._ExpandAndLockInstance()
4727

    
4728
  def BuildHooksEnv(self):
4729
    """Build hooks env.
4730

4731
    This runs on master, primary and secondary nodes of the instance.
4732

4733
    """
4734
    env = {
4735
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
4736
      "REBOOT_TYPE": self.op.reboot_type,
4737
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
4738
      }
4739
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4740
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4741
    return env, nl, nl
4742

    
4743
  def CheckPrereq(self):
4744
    """Check prerequisites.
4745

4746
    This checks that the instance is in the cluster.
4747

4748
    """
4749
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4750
    assert self.instance is not None, \
4751
      "Cannot retrieve locked instance %s" % self.op.instance_name
4752

    
4753
    _CheckNodeOnline(self, instance.primary_node)
4754

    
4755
    # check bridges existence
4756
    _CheckInstanceBridgesExist(self, instance)
4757

    
4758
  def Exec(self, feedback_fn):
4759
    """Reboot the instance.
4760

4761
    """
4762
    instance = self.instance
4763
    ignore_secondaries = self.op.ignore_secondaries
4764
    reboot_type = self.op.reboot_type
4765

    
4766
    node_current = instance.primary_node
4767

    
4768
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
4769
                       constants.INSTANCE_REBOOT_HARD]:
4770
      for disk in instance.disks:
4771
        self.cfg.SetDiskID(disk, node_current)
4772
      result = self.rpc.call_instance_reboot(node_current, instance,
4773
                                             reboot_type,
4774
                                             self.op.shutdown_timeout)
4775
      result.Raise("Could not reboot instance")
4776
    else:
4777
      result = self.rpc.call_instance_shutdown(node_current, instance,
4778
                                               self.op.shutdown_timeout)
4779
      result.Raise("Could not shutdown instance for full reboot")
4780
      _ShutdownInstanceDisks(self, instance)
4781
      _StartInstanceDisks(self, instance, ignore_secondaries)
4782
      result = self.rpc.call_instance_start(node_current, instance, None, None)
4783
      msg = result.fail_msg
4784
      if msg:
4785
        _ShutdownInstanceDisks(self, instance)
4786
        raise errors.OpExecError("Could not start instance for"
4787
                                 " full reboot: %s" % msg)
4788

    
4789
    self.cfg.MarkInstanceUp(instance.name)
4790

    
4791

    
4792
class LUShutdownInstance(LogicalUnit):
4793
  """Shutdown an instance.
4794

4795
  """
4796
  HPATH = "instance-stop"
4797
  HTYPE = constants.HTYPE_INSTANCE
4798
  _OP_PARAMS = [
4799
    _PInstanceName,
4800
    _PIgnoreOfflineNodes,
4801
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt),
4802
    ]
4803
  REQ_BGL = False
4804

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

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

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

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

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

4822
    This checks that the instance is in the cluster.
4823

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

    
4829
    self.primary_offline = \
4830
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
4831

    
4832
    if self.primary_offline and self.op.ignore_offline_nodes:
4833
      self.proc.LogWarning("Ignoring offline primary node")
4834
    else:
4835
      _CheckNodeOnline(self, self.instance.primary_node)
4836

    
4837
  def Exec(self, feedback_fn):
4838
    """Shutdown the instance.
4839

4840
    """
4841
    instance = self.instance
4842
    node_current = instance.primary_node
4843
    timeout = self.op.timeout
4844

    
4845
    self.cfg.MarkInstanceDown(instance.name)
4846

    
4847
    if self.primary_offline:
4848
      assert self.op.ignore_offline_nodes
4849
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
4850
    else:
4851
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
4852
      msg = result.fail_msg
4853
      if msg:
4854
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
4855

    
4856
      _ShutdownInstanceDisks(self, instance)
4857

    
4858

    
4859
class LUReinstallInstance(LogicalUnit):
4860
  """Reinstall an instance.
4861

4862
  """
4863
  HPATH = "instance-reinstall"
4864
  HTYPE = constants.HTYPE_INSTANCE
4865
  _OP_PARAMS = [
4866
    _PInstanceName,
4867
    ("os_type", None, ht.TMaybeString),
4868
    ("force_variant", False, ht.TBool),
4869
    ("osparams", None, ht.TOr(ht.TDict, ht.TNone)),
4870
    ]
4871
  REQ_BGL = False
4872

    
4873
  def ExpandNames(self):
4874
    self._ExpandAndLockInstance()
4875

    
4876
  def BuildHooksEnv(self):
4877
    """Build hooks env.
4878

4879
    This runs on master, primary and secondary nodes of the instance.
4880

4881
    """
4882
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4883
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4884
    return env, nl, nl
4885

    
4886
  def CheckPrereq(self):
4887
    """Check prerequisites.
4888

4889
    This checks that the instance is in the cluster and is not running.
4890

4891
    """
4892
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4893
    assert instance is not None, \
4894
      "Cannot retrieve locked instance %s" % self.op.instance_name
4895
    _CheckNodeOnline(self, instance.primary_node)
4896

    
4897
    if instance.disk_template == constants.DT_DISKLESS:
4898
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4899
                                 self.op.instance_name,
4900
                                 errors.ECODE_INVAL)
4901
    _CheckInstanceDown(self, instance, "cannot reinstall")
4902

    
4903
    if self.op.os_type is not None:
4904
      # OS verification
4905
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
4906
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
4907
      instance_os = self.op.os_type
4908
    else:
4909
      instance_os = instance.os
4910

    
4911
    nodelist = list(instance.all_nodes)
4912

    
4913
    if self.op.osparams:
4914
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
4915
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
4916
      self.os_inst = i_osdict # the new dict (without defaults)
4917
    else:
4918
      self.os_inst = None
4919

    
4920
    self.instance = instance
4921

    
4922
  def Exec(self, feedback_fn):
4923
    """Reinstall the instance.
4924

4925
    """
4926
    inst = self.instance
4927

    
4928
    if self.op.os_type is not None:
4929
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
4930
      inst.os = self.op.os_type
4931
      # Write to configuration
4932
      self.cfg.Update(inst, feedback_fn)
4933

    
4934
    _StartInstanceDisks(self, inst, None)
4935
    try:
4936
      feedback_fn("Running the instance OS create scripts...")
4937
      # FIXME: pass debug option from opcode to backend
4938
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
4939
                                             self.op.debug_level,
4940
                                             osparams=self.os_inst)
4941
      result.Raise("Could not install OS for instance %s on node %s" %
4942
                   (inst.name, inst.primary_node))
4943
    finally:
4944
      _ShutdownInstanceDisks(self, inst)
4945

    
4946

    
4947
class LURecreateInstanceDisks(LogicalUnit):
4948
  """Recreate an instance's missing disks.
4949

4950
  """
4951
  HPATH = "instance-recreate-disks"
4952
  HTYPE = constants.HTYPE_INSTANCE
4953
  _OP_PARAMS = [
4954
    _PInstanceName,
4955
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt)),
4956
    ]
4957
  REQ_BGL = False
4958

    
4959
  def ExpandNames(self):
4960
    self._ExpandAndLockInstance()
4961

    
4962
  def BuildHooksEnv(self):
4963
    """Build hooks env.
4964

4965
    This runs on master, primary and secondary nodes of the instance.
4966

4967
    """
4968
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4969
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4970
    return env, nl, nl
4971

    
4972
  def CheckPrereq(self):
4973
    """Check prerequisites.
4974

4975
    This checks that the instance is in the cluster and is not running.
4976

4977
    """
4978
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4979
    assert instance is not None, \
4980
      "Cannot retrieve locked instance %s" % self.op.instance_name
4981
    _CheckNodeOnline(self, instance.primary_node)
4982

    
4983
    if instance.disk_template == constants.DT_DISKLESS:
4984
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4985
                                 self.op.instance_name, errors.ECODE_INVAL)
4986
    _CheckInstanceDown(self, instance, "cannot recreate disks")
4987

    
4988
    if not self.op.disks:
4989
      self.op.disks = range(len(instance.disks))
4990
    else:
4991
      for idx in self.op.disks:
4992
        if idx >= len(instance.disks):
4993
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
4994
                                     errors.ECODE_INVAL)
4995

    
4996
    self.instance = instance
4997

    
4998
  def Exec(self, feedback_fn):
4999
    """Recreate the disks.
5000

5001
    """
5002
    to_skip = []
5003
    for idx, _ in enumerate(self.instance.disks):
5004
      if idx not in self.op.disks: # disk idx has not been passed in
5005
        to_skip.append(idx)
5006
        continue
5007

    
5008
    _CreateDisks(self, self.instance, to_skip=to_skip)
5009

    
5010

    
5011
class LURenameInstance(LogicalUnit):
5012
  """Rename an instance.
5013

5014
  """
5015
  HPATH = "instance-rename"
5016
  HTYPE = constants.HTYPE_INSTANCE
5017
  _OP_PARAMS = [
5018
    _PInstanceName,
5019
    ("new_name", ht.NoDefault, ht.TNonEmptyString),
5020
    ("ip_check", False, ht.TBool),
5021
    ("name_check", True, ht.TBool),
5022
    ]
5023

    
5024
  def CheckArguments(self):
5025
    """Check arguments.
5026

5027
    """
5028
    if self.op.ip_check and not self.op.name_check:
5029
      # TODO: make the ip check more flexible and not depend on the name check
5030
      raise errors.OpPrereqError("Cannot do ip check without a name check",
5031
                                 errors.ECODE_INVAL)
5032

    
5033
  def BuildHooksEnv(self):
5034
    """Build hooks env.
5035

5036
    This runs on master, primary and secondary nodes of the instance.
5037

5038
    """
5039
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5040
    env["INSTANCE_NEW_NAME"] = self.op.new_name
5041
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5042
    return env, nl, nl
5043

    
5044
  def CheckPrereq(self):
5045
    """Check prerequisites.
5046

5047
    This checks that the instance is in the cluster and is not running.
5048

5049
    """
5050
    self.op.instance_name = _ExpandInstanceName(self.cfg,
5051
                                                self.op.instance_name)
5052
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5053
    assert instance is not None
5054
    _CheckNodeOnline(self, instance.primary_node)
5055
    _CheckInstanceDown(self, instance, "cannot rename")
5056
    self.instance = instance
5057

    
5058
    new_name = self.op.new_name
5059
    if self.op.name_check:
5060
      hostname = netutils.GetHostname(name=new_name)
5061
      new_name = self.op.new_name = hostname.name
5062
      if (self.op.ip_check and
5063
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
5064
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
5065
                                   (hostname.ip, new_name),
5066
                                   errors.ECODE_NOTUNIQUE)
5067

    
5068
    instance_list = self.cfg.GetInstanceList()
5069
    if new_name in instance_list:
5070
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5071
                                 new_name, errors.ECODE_EXISTS)
5072

    
5073
  def Exec(self, feedback_fn):
5074
    """Reinstall the instance.
5075

5076
    """
5077
    inst = self.instance
5078
    old_name = inst.name
5079

    
5080
    if inst.disk_template == constants.DT_FILE:
5081
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5082

    
5083
    self.cfg.RenameInstance(inst.name, self.op.new_name)
5084
    # Change the instance lock. This is definitely safe while we hold the BGL
5085
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
5086
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
5087

    
5088
    # re-read the instance from the configuration after rename
5089
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
5090

    
5091
    if inst.disk_template == constants.DT_FILE:
5092
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5093
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
5094
                                                     old_file_storage_dir,
5095
                                                     new_file_storage_dir)
5096
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
5097
                   " (but the instance has been renamed in Ganeti)" %
5098
                   (inst.primary_node, old_file_storage_dir,
5099
                    new_file_storage_dir))
5100

    
5101
    _StartInstanceDisks(self, inst, None)
5102
    try:
5103
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
5104
                                                 old_name, self.op.debug_level)
5105
      msg = result.fail_msg
5106
      if msg:
5107
        msg = ("Could not run OS rename script for instance %s on node %s"
5108
               " (but the instance has been renamed in Ganeti): %s" %
5109
               (inst.name, inst.primary_node, msg))
5110
        self.proc.LogWarning(msg)
5111
    finally:
5112
      _ShutdownInstanceDisks(self, inst)
5113

    
5114
    return inst.name
5115

    
5116

    
5117
class LURemoveInstance(LogicalUnit):
5118
  """Remove an instance.
5119

5120
  """
5121
  HPATH = "instance-remove"
5122
  HTYPE = constants.HTYPE_INSTANCE
5123
  _OP_PARAMS = [
5124
    _PInstanceName,
5125
    ("ignore_failures", False, ht.TBool),
5126
    _PShutdownTimeout,
5127
    ]
5128
  REQ_BGL = False
5129

    
5130
  def ExpandNames(self):
5131
    self._ExpandAndLockInstance()
5132
    self.needed_locks[locking.LEVEL_NODE] = []
5133
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5134

    
5135
  def DeclareLocks(self, level):
5136
    if level == locking.LEVEL_NODE:
5137
      self._LockInstancesNodes()
5138

    
5139
  def BuildHooksEnv(self):
5140
    """Build hooks env.
5141

5142
    This runs on master, primary and secondary nodes of the instance.
5143

5144
    """
5145
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5146
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
5147
    nl = [self.cfg.GetMasterNode()]
5148
    nl_post = list(self.instance.all_nodes) + nl
5149
    return env, nl, nl_post
5150

    
5151
  def CheckPrereq(self):
5152
    """Check prerequisites.
5153

5154
    This checks that the instance is in the cluster.
5155

5156
    """
5157
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5158
    assert self.instance is not None, \
5159
      "Cannot retrieve locked instance %s" % self.op.instance_name
5160

    
5161
  def Exec(self, feedback_fn):
5162
    """Remove the instance.
5163

5164
    """
5165
    instance = self.instance
5166
    logging.info("Shutting down instance %s on node %s",
5167
                 instance.name, instance.primary_node)
5168

    
5169
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5170
                                             self.op.shutdown_timeout)
5171
    msg = result.fail_msg
5172
    if msg:
5173
      if self.op.ignore_failures:
5174
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5175
      else:
5176
        raise errors.OpExecError("Could not shutdown instance %s on"
5177
                                 " node %s: %s" %
5178
                                 (instance.name, instance.primary_node, msg))
5179

    
5180
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5181

    
5182

    
5183
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5184
  """Utility function to remove an instance.
5185

5186
  """
5187
  logging.info("Removing block devices for instance %s", instance.name)
5188

    
5189
  if not _RemoveDisks(lu, instance):
5190
    if not ignore_failures:
5191
      raise errors.OpExecError("Can't remove instance's disks")
5192
    feedback_fn("Warning: can't remove instance's disks")
5193

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

    
5196
  lu.cfg.RemoveInstance(instance.name)
5197

    
5198
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5199
    "Instance lock removal conflict"
5200

    
5201
  # Remove lock for the instance
5202
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5203

    
5204

    
5205
class LUQueryInstances(NoHooksLU):
5206
  """Logical unit for querying instances.
5207

5208
  """
5209
  # pylint: disable-msg=W0142
5210
  _OP_PARAMS = [
5211
    ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
5212
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
5213
    ("use_locking", False, ht.TBool),
5214
    ]
5215
  REQ_BGL = False
5216
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
5217
                    "serial_no", "ctime", "mtime", "uuid"]
5218
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
5219
                                    "admin_state",
5220
                                    "disk_template", "ip", "mac", "bridge",
5221
                                    "nic_mode", "nic_link",
5222
                                    "sda_size", "sdb_size", "vcpus", "tags",
5223
                                    "network_port", "beparams",
5224
                                    r"(disk)\.(size)/([0-9]+)",
5225
                                    r"(disk)\.(sizes)", "disk_usage",
5226
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
5227
                                    r"(nic)\.(bridge)/([0-9]+)",
5228
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
5229
                                    r"(disk|nic)\.(count)",
5230
                                    "hvparams", "custom_hvparams",
5231
                                    "custom_beparams", "custom_nicparams",
5232
                                    ] + _SIMPLE_FIELDS +
5233
                                  ["hv/%s" % name
5234
                                   for name in constants.HVS_PARAMETERS
5235
                                   if name not in constants.HVC_GLOBALS] +
5236
                                  ["be/%s" % name
5237
                                   for name in constants.BES_PARAMETERS])
5238
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state",
5239
                                   "oper_ram",
5240
                                   "oper_vcpus",
5241
                                   "status")
5242

    
5243

    
5244
  def CheckArguments(self):
5245
    _CheckOutputFields(static=self._FIELDS_STATIC,
5246
                       dynamic=self._FIELDS_DYNAMIC,
5247
                       selected=self.op.output_fields)
5248

    
5249
  def ExpandNames(self):
5250
    self.needed_locks = {}
5251
    self.share_locks[locking.LEVEL_INSTANCE] = 1
5252
    self.share_locks[locking.LEVEL_NODE] = 1
5253

    
5254
    if self.op.names:
5255
      self.wanted = _GetWantedInstances(self, self.op.names)
5256
    else:
5257
      self.wanted = locking.ALL_SET
5258

    
5259
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
5260
    self.do_locking = self.do_node_query and self.op.use_locking
5261
    if self.do_locking:
5262
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
5263
      self.needed_locks[locking.LEVEL_NODE] = []
5264
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5265

    
5266
  def DeclareLocks(self, level):
5267
    if level == locking.LEVEL_NODE and self.do_locking:
5268
      self._LockInstancesNodes()
5269

    
5270
  def Exec(self, feedback_fn):
5271
    """Computes the list of nodes and their attributes.
5272

5273
    """
5274
    # pylint: disable-msg=R0912
5275
    # way too many branches here
5276
    all_info = self.cfg.GetAllInstancesInfo()
5277
    if self.wanted == locking.ALL_SET:
5278
      # caller didn't specify instance names, so ordering is not important
5279
      if self.do_locking:
5280
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5281
      else:
5282
        instance_names = all_info.keys()
5283
      instance_names = utils.NiceSort(instance_names)
5284
    else:
5285
      # caller did specify names, so we must keep the ordering
5286
      if self.do_locking:
5287
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
5288
      else:
5289
        tgt_set = all_info.keys()
5290
      missing = set(self.wanted).difference(tgt_set)
5291
      if missing:
5292
        raise errors.OpExecError("Some instances were removed before"
5293
                                 " retrieving their data: %s" % missing)
5294
      instance_names = self.wanted
5295

    
5296
    instance_list = [all_info[iname] for iname in instance_names]
5297

    
5298
    # begin data gathering
5299

    
5300
    nodes = frozenset([inst.primary_node for inst in instance_list])
5301
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
5302

    
5303
    bad_nodes = []
5304
    off_nodes = []
5305
    if self.do_node_query:
5306
      live_data = {}
5307
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
5308
      for name in nodes:
5309
        result = node_data[name]
5310
        if result.offline:
5311
          # offline nodes will be in both lists
5312
          off_nodes.append(name)
5313
        if result.fail_msg:
5314
          bad_nodes.append(name)
5315
        else:
5316
          if result.payload:
5317
            live_data.update(result.payload)
5318
          # else no instance is alive
5319
    else:
5320
      live_data = dict([(name, {}) for name in instance_names])
5321

    
5322
    # end data gathering
5323

    
5324
    HVPREFIX = "hv/"
5325
    BEPREFIX = "be/"
5326
    output = []
5327
    cluster = self.cfg.GetClusterInfo()
5328
    for instance in instance_list:
5329
      iout = []
5330
      i_hv = cluster.FillHV(instance, skip_globals=True)
5331
      i_be = cluster.FillBE(instance)
5332
      i_nicp = [cluster.SimpleFillNIC(nic.nicparams) for nic in instance.nics]
5333
      for field in self.op.output_fields:
5334
        st_match = self._FIELDS_STATIC.Matches(field)
5335
        if field in self._SIMPLE_FIELDS:
5336
          val = getattr(instance, field)
5337
        elif field == "pnode":
5338
          val = instance.primary_node
5339
        elif field == "snodes":
5340
          val = list(instance.secondary_nodes)
5341
        elif field == "admin_state":
5342
          val = instance.admin_up
5343
        elif field == "oper_state":
5344
          if instance.primary_node in bad_nodes:
5345
            val = None
5346
          else:
5347
            val = bool(live_data.get(instance.name))
5348
        elif field == "status":
5349
          if instance.primary_node in off_nodes:
5350
            val = "ERROR_nodeoffline"
5351
          elif instance.primary_node in bad_nodes:
5352
            val = "ERROR_nodedown"
5353
          else:
5354
            running = bool(live_data.get(instance.name))
5355
            if running:
5356
              if instance.admin_up:
5357
                val = "running"
5358
              else:
5359
                val = "ERROR_up"
5360
            else:
5361
              if instance.admin_up:
5362
                val = "ERROR_down"
5363
              else:
5364
                val = "ADMIN_down"
5365
        elif field == "oper_ram":
5366
          if instance.primary_node in bad_nodes:
5367
            val = None
5368
          elif instance.name in live_data:
5369
            val = live_data[instance.name].get("memory", "?")
5370
          else:
5371
            val = "-"
5372
        elif field == "oper_vcpus":
5373
          if instance.primary_node in bad_nodes:
5374
            val = None
5375
          elif instance.name in live_data:
5376
            val = live_data[instance.name].get("vcpus", "?")
5377
          else:
5378
            val = "-"
5379
        elif field == "vcpus":
5380
          val = i_be[constants.BE_VCPUS]
5381
        elif field == "disk_template":
5382
          val = instance.disk_template
5383
        elif field == "ip":
5384
          if instance.nics:
5385
            val = instance.nics[0].ip
5386
          else:
5387
            val = None
5388
        elif field == "nic_mode":
5389
          if instance.nics:
5390
            val = i_nicp[0][constants.NIC_MODE]
5391
          else:
5392
            val = None
5393
        elif field == "nic_link":
5394
          if instance.nics:
5395
            val = i_nicp[0][constants.NIC_LINK]
5396
          else:
5397
            val = None
5398
        elif field == "bridge":
5399
          if (instance.nics and
5400
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
5401
            val = i_nicp[0][constants.NIC_LINK]
5402
          else:
5403
            val = None
5404
        elif field == "mac":
5405
          if instance.nics:
5406
            val = instance.nics[0].mac
5407
          else:
5408
            val = None
5409
        elif field == "custom_nicparams":
5410
          val = [nic.nicparams for nic in instance.nics]
5411
        elif field == "sda_size" or field == "sdb_size":
5412
          idx = ord(field[2]) - ord('a')
5413
          try:
5414
            val = instance.FindDisk(idx).size
5415
          except errors.OpPrereqError:
5416
            val = None
5417
        elif field == "disk_usage": # total disk usage per node
5418
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
5419
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
5420
        elif field == "tags":
5421
          val = list(instance.GetTags())
5422
        elif field == "custom_hvparams":
5423
          val = instance.hvparams # not filled!
5424
        elif field == "hvparams":
5425
          val = i_hv
5426
        elif (field.startswith(HVPREFIX) and
5427
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS and
5428
              field[len(HVPREFIX):] not in constants.HVC_GLOBALS):
5429
          val = i_hv.get(field[len(HVPREFIX):], None)
5430
        elif field == "custom_beparams":
5431
          val = instance.beparams
5432
        elif field == "beparams":
5433
          val = i_be
5434
        elif (field.startswith(BEPREFIX) and
5435
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
5436
          val = i_be.get(field[len(BEPREFIX):], None)
5437
        elif st_match and st_match.groups():
5438
          # matches a variable list
5439
          st_groups = st_match.groups()
5440
          if st_groups and st_groups[0] == "disk":
5441
            if st_groups[1] == "count":
5442
              val = len(instance.disks)
5443
            elif st_groups[1] == "sizes":
5444
              val = [disk.size for disk in instance.disks]
5445
            elif st_groups[1] == "size":
5446
              try:
5447
                val = instance.FindDisk(st_groups[2]).size
5448
              except errors.OpPrereqError:
5449
                val = None
5450
            else:
5451
              assert False, "Unhandled disk parameter"
5452
          elif st_groups[0] == "nic":
5453
            if st_groups[1] == "count":
5454
              val = len(instance.nics)
5455
            elif st_groups[1] == "macs":
5456
              val = [nic.mac for nic in instance.nics]
5457
            elif st_groups[1] == "ips":
5458
              val = [nic.ip for nic in instance.nics]
5459
            elif st_groups[1] == "modes":
5460
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
5461
            elif st_groups[1] == "links":
5462
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
5463
            elif st_groups[1] == "bridges":
5464
              val = []
5465
              for nicp in i_nicp:
5466
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
5467
                  val.append(nicp[constants.NIC_LINK])
5468
                else:
5469
                  val.append(None)
5470
            else:
5471
              # index-based item
5472
              nic_idx = int(st_groups[2])
5473
              if nic_idx >= len(instance.nics):
5474
                val = None
5475
              else:
5476
                if st_groups[1] == "mac":
5477
                  val = instance.nics[nic_idx].mac
5478
                elif st_groups[1] == "ip":
5479
                  val = instance.nics[nic_idx].ip
5480
                elif st_groups[1] == "mode":
5481
                  val = i_nicp[nic_idx][constants.NIC_MODE]
5482
                elif st_groups[1] == "link":
5483
                  val = i_nicp[nic_idx][constants.NIC_LINK]
5484
                elif st_groups[1] == "bridge":
5485
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
5486
                  if nic_mode == constants.NIC_MODE_BRIDGED:
5487
                    val = i_nicp[nic_idx][constants.NIC_LINK]
5488
                  else:
5489
                    val = None
5490
                else:
5491
                  assert False, "Unhandled NIC parameter"
5492
          else:
5493
            assert False, ("Declared but unhandled variable parameter '%s'" %
5494
                           field)
5495
        else:
5496
          assert False, "Declared but unhandled parameter '%s'" % field
5497
        iout.append(val)
5498
      output.append(iout)
5499

    
5500
    return output
5501

    
5502

    
5503
class LUFailoverInstance(LogicalUnit):
5504
  """Failover an instance.
5505

5506
  """
5507
  HPATH = "instance-failover"
5508
  HTYPE = constants.HTYPE_INSTANCE
5509
  _OP_PARAMS = [
5510
    _PInstanceName,
5511
    ("ignore_consistency", False, ht.TBool),
5512
    _PShutdownTimeout,
5513
    ]
5514
  REQ_BGL = False
5515

    
5516
  def ExpandNames(self):
5517
    self._ExpandAndLockInstance()
5518
    self.needed_locks[locking.LEVEL_NODE] = []
5519
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5520

    
5521
  def DeclareLocks(self, level):
5522
    if level == locking.LEVEL_NODE:
5523
      self._LockInstancesNodes()
5524

    
5525
  def BuildHooksEnv(self):
5526
    """Build hooks env.
5527

5528
    This runs on master, primary and secondary nodes of the instance.
5529

5530
    """
5531
    instance = self.instance
5532
    source_node = instance.primary_node
5533
    target_node = instance.secondary_nodes[0]
5534
    env = {
5535
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5536
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5537
      "OLD_PRIMARY": source_node,
5538
      "OLD_SECONDARY": target_node,
5539
      "NEW_PRIMARY": target_node,
5540
      "NEW_SECONDARY": source_node,
5541
      }
5542
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5543
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5544
    nl_post = list(nl)
5545
    nl_post.append(source_node)
5546
    return env, nl, nl_post
5547

    
5548
  def CheckPrereq(self):
5549
    """Check prerequisites.
5550

5551
    This checks that the instance is in the cluster.
5552

5553
    """
5554
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5555
    assert self.instance is not None, \
5556
      "Cannot retrieve locked instance %s" % self.op.instance_name
5557

    
5558
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5559
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5560
      raise errors.OpPrereqError("Instance's disk layout is not"
5561
                                 " network mirrored, cannot failover.",
5562
                                 errors.ECODE_STATE)
5563

    
5564
    secondary_nodes = instance.secondary_nodes
5565
    if not secondary_nodes:
5566
      raise errors.ProgrammerError("no secondary node but using "
5567
                                   "a mirrored disk template")
5568

    
5569
    target_node = secondary_nodes[0]
5570
    _CheckNodeOnline(self, target_node)
5571
    _CheckNodeNotDrained(self, target_node)
5572
    if instance.admin_up:
5573
      # check memory requirements on the secondary node
5574
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5575
                           instance.name, bep[constants.BE_MEMORY],
5576
                           instance.hypervisor)
5577
    else:
5578
      self.LogInfo("Not checking memory on the secondary node as"
5579
                   " instance will not be started")
5580

    
5581
    # check bridge existance
5582
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5583

    
5584
  def Exec(self, feedback_fn):
5585
    """Failover an instance.
5586

5587
    The failover is done by shutting it down on its present node and
5588
    starting it on the secondary.
5589

5590
    """
5591
    instance = self.instance
5592
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
5593

    
5594
    source_node = instance.primary_node
5595
    target_node = instance.secondary_nodes[0]
5596

    
5597
    if instance.admin_up:
5598
      feedback_fn("* checking disk consistency between source and target")
5599
      for dev in instance.disks:
5600
        # for drbd, these are drbd over lvm
5601
        if not _CheckDiskConsistency(self, dev, target_node, False):
5602
          if not self.op.ignore_consistency:
5603
            raise errors.OpExecError("Disk %s is degraded on target node,"
5604
                                     " aborting failover." % dev.iv_name)
5605
    else:
5606
      feedback_fn("* not checking disk consistency as instance is not running")
5607

    
5608
    feedback_fn("* shutting down instance on source node")
5609
    logging.info("Shutting down instance %s on node %s",
5610
                 instance.name, source_node)
5611

    
5612
    result = self.rpc.call_instance_shutdown(source_node, instance,
5613
                                             self.op.shutdown_timeout)
5614
    msg = result.fail_msg
5615
    if msg:
5616
      if self.op.ignore_consistency or primary_node.offline:
5617
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5618
                             " Proceeding anyway. Please make sure node"
5619
                             " %s is down. Error details: %s",
5620
                             instance.name, source_node, source_node, msg)
5621
      else:
5622
        raise errors.OpExecError("Could not shutdown instance %s on"
5623
                                 " node %s: %s" %
5624
                                 (instance.name, source_node, msg))
5625

    
5626
    feedback_fn("* deactivating the instance's disks on source node")
5627
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5628
      raise errors.OpExecError("Can't shut down the instance's disks.")
5629

    
5630
    instance.primary_node = target_node
5631
    # distribute new instance config to the other nodes
5632
    self.cfg.Update(instance, feedback_fn)
5633

    
5634
    # Only start the instance if it's marked as up
5635
    if instance.admin_up:
5636
      feedback_fn("* activating the instance's disks on target node")
5637
      logging.info("Starting instance %s on node %s",
5638
                   instance.name, target_node)
5639

    
5640
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5641
                                           ignore_secondaries=True)
5642
      if not disks_ok:
5643
        _ShutdownInstanceDisks(self, instance)
5644
        raise errors.OpExecError("Can't activate the instance's disks")
5645

    
5646
      feedback_fn("* starting the instance on the target node")
5647
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5648
      msg = result.fail_msg
5649
      if msg:
5650
        _ShutdownInstanceDisks(self, instance)
5651
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5652
                                 (instance.name, target_node, msg))
5653

    
5654

    
5655
class LUMigrateInstance(LogicalUnit):
5656
  """Migrate an instance.
5657

5658
  This is migration without shutting down, compared to the failover,
5659
  which is done with shutdown.
5660

5661
  """
5662
  HPATH = "instance-migrate"
5663
  HTYPE = constants.HTYPE_INSTANCE
5664
  _OP_PARAMS = [
5665
    _PInstanceName,
5666
    _PMigrationMode,
5667
    _PMigrationLive,
5668
    ("cleanup", False, ht.TBool),
5669
    ]
5670

    
5671
  REQ_BGL = False
5672

    
5673
  def ExpandNames(self):
5674
    self._ExpandAndLockInstance()
5675

    
5676
    self.needed_locks[locking.LEVEL_NODE] = []
5677
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5678

    
5679
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5680
                                       self.op.cleanup)
5681
    self.tasklets = [self._migrater]
5682

    
5683
  def DeclareLocks(self, level):
5684
    if level == locking.LEVEL_NODE:
5685
      self._LockInstancesNodes()
5686

    
5687
  def BuildHooksEnv(self):
5688
    """Build hooks env.
5689

5690
    This runs on master, primary and secondary nodes of the instance.
5691

5692
    """
5693
    instance = self._migrater.instance
5694
    source_node = instance.primary_node
5695
    target_node = instance.secondary_nodes[0]
5696
    env = _BuildInstanceHookEnvByObject(self, instance)
5697
    env["MIGRATE_LIVE"] = self._migrater.live
5698
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5699
    env.update({
5700
        "OLD_PRIMARY": source_node,
5701
        "OLD_SECONDARY": target_node,
5702
        "NEW_PRIMARY": target_node,
5703
        "NEW_SECONDARY": source_node,
5704
        })
5705
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5706
    nl_post = list(nl)
5707
    nl_post.append(source_node)
5708
    return env, nl, nl_post
5709

    
5710

    
5711
class LUMoveInstance(LogicalUnit):
5712
  """Move an instance by data-copying.
5713

5714
  """
5715
  HPATH = "instance-move"
5716
  HTYPE = constants.HTYPE_INSTANCE
5717
  _OP_PARAMS = [
5718
    _PInstanceName,
5719
    ("target_node", ht.NoDefault, ht.TNonEmptyString),
5720
    _PShutdownTimeout,
5721
    ]
5722
  REQ_BGL = False
5723

    
5724
  def ExpandNames(self):
5725
    self._ExpandAndLockInstance()
5726
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5727
    self.op.target_node = target_node
5728
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5729
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5730

    
5731
  def DeclareLocks(self, level):
5732
    if level == locking.LEVEL_NODE:
5733
      self._LockInstancesNodes(primary_only=True)
5734

    
5735
  def BuildHooksEnv(self):
5736
    """Build hooks env.
5737

5738
    This runs on master, primary and secondary nodes of the instance.
5739

5740
    """
5741
    env = {
5742
      "TARGET_NODE": self.op.target_node,
5743
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5744
      }
5745
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5746
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5747
                                       self.op.target_node]
5748
    return env, nl, nl
5749

    
5750
  def CheckPrereq(self):
5751
    """Check prerequisites.
5752

5753
    This checks that the instance is in the cluster.
5754

5755
    """
5756
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5757
    assert self.instance is not None, \
5758
      "Cannot retrieve locked instance %s" % self.op.instance_name
5759

    
5760
    node = self.cfg.GetNodeInfo(self.op.target_node)
5761
    assert node is not None, \
5762
      "Cannot retrieve locked node %s" % self.op.target_node
5763

    
5764
    self.target_node = target_node = node.name
5765

    
5766
    if target_node == instance.primary_node:
5767
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5768
                                 (instance.name, target_node),
5769
                                 errors.ECODE_STATE)
5770

    
5771
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5772

    
5773
    for idx, dsk in enumerate(instance.disks):
5774
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5775
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5776
                                   " cannot copy" % idx, errors.ECODE_STATE)
5777

    
5778
    _CheckNodeOnline(self, target_node)
5779
    _CheckNodeNotDrained(self, target_node)
5780
    _CheckNodeVmCapable(self, target_node)
5781

    
5782
    if instance.admin_up:
5783
      # check memory requirements on the secondary node
5784
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5785
                           instance.name, bep[constants.BE_MEMORY],
5786
                           instance.hypervisor)
5787
    else:
5788
      self.LogInfo("Not checking memory on the secondary node as"
5789
                   " instance will not be started")
5790

    
5791
    # check bridge existance
5792
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5793

    
5794
  def Exec(self, feedback_fn):
5795
    """Move an instance.
5796

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

5800
    """
5801
    instance = self.instance
5802

    
5803
    source_node = instance.primary_node
5804
    target_node = self.target_node
5805

    
5806
    self.LogInfo("Shutting down instance %s on source node %s",
5807
                 instance.name, source_node)
5808

    
5809
    result = self.rpc.call_instance_shutdown(source_node, instance,
5810
                                             self.op.shutdown_timeout)
5811
    msg = result.fail_msg
5812
    if msg:
5813
      if self.op.ignore_consistency:
5814
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5815
                             " Proceeding anyway. Please make sure node"
5816
                             " %s is down. Error details: %s",
5817
                             instance.name, source_node, source_node, msg)
5818
      else:
5819
        raise errors.OpExecError("Could not shutdown instance %s on"
5820
                                 " node %s: %s" %
5821
                                 (instance.name, source_node, msg))
5822

    
5823
    # create the target disks
5824
    try:
5825
      _CreateDisks(self, instance, target_node=target_node)
5826
    except errors.OpExecError:
5827
      self.LogWarning("Device creation failed, reverting...")
5828
      try:
5829
        _RemoveDisks(self, instance, target_node=target_node)
5830
      finally:
5831
        self.cfg.ReleaseDRBDMinors(instance.name)
5832
        raise
5833

    
5834
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5835

    
5836
    errs = []
5837
    # activate, get path, copy the data over
5838
    for idx, disk in enumerate(instance.disks):
5839
      self.LogInfo("Copying data for disk %d", idx)
5840
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5841
                                               instance.name, True)
5842
      if result.fail_msg:
5843
        self.LogWarning("Can't assemble newly created disk %d: %s",
5844
                        idx, result.fail_msg)
5845
        errs.append(result.fail_msg)
5846
        break
5847
      dev_path = result.payload
5848
      result = self.rpc.call_blockdev_export(source_node, disk,
5849
                                             target_node, dev_path,
5850
                                             cluster_name)
5851
      if result.fail_msg:
5852
        self.LogWarning("Can't copy data over for disk %d: %s",
5853
                        idx, result.fail_msg)
5854
        errs.append(result.fail_msg)
5855
        break
5856

    
5857
    if errs:
5858
      self.LogWarning("Some disks failed to copy, aborting")
5859
      try:
5860
        _RemoveDisks(self, instance, target_node=target_node)
5861
      finally:
5862
        self.cfg.ReleaseDRBDMinors(instance.name)
5863
        raise errors.OpExecError("Errors during disk copy: %s" %
5864
                                 (",".join(errs),))
5865

    
5866
    instance.primary_node = target_node
5867
    self.cfg.Update(instance, feedback_fn)
5868

    
5869
    self.LogInfo("Removing the disks on the original node")
5870
    _RemoveDisks(self, instance, target_node=source_node)
5871

    
5872
    # Only start the instance if it's marked as up
5873
    if instance.admin_up:
5874
      self.LogInfo("Starting instance %s on node %s",
5875
                   instance.name, target_node)
5876

    
5877
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5878
                                           ignore_secondaries=True)
5879
      if not disks_ok:
5880
        _ShutdownInstanceDisks(self, instance)
5881
        raise errors.OpExecError("Can't activate the instance's disks")
5882

    
5883
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5884
      msg = result.fail_msg
5885
      if msg:
5886
        _ShutdownInstanceDisks(self, instance)
5887
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5888
                                 (instance.name, target_node, msg))
5889

    
5890

    
5891
class LUMigrateNode(LogicalUnit):
5892
  """Migrate all instances from a node.
5893

5894
  """
5895
  HPATH = "node-migrate"
5896
  HTYPE = constants.HTYPE_NODE
5897
  _OP_PARAMS = [
5898
    _PNodeName,
5899
    _PMigrationMode,
5900
    _PMigrationLive,
5901
    ]
5902
  REQ_BGL = False
5903

    
5904
  def ExpandNames(self):
5905
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5906

    
5907
    self.needed_locks = {
5908
      locking.LEVEL_NODE: [self.op.node_name],
5909
      }
5910

    
5911
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5912

    
5913
    # Create tasklets for migrating instances for all instances on this node
5914
    names = []
5915
    tasklets = []
5916

    
5917
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5918
      logging.debug("Migrating instance %s", inst.name)
5919
      names.append(inst.name)
5920

    
5921
      tasklets.append(TLMigrateInstance(self, inst.name, False))
5922

    
5923
    self.tasklets = tasklets
5924

    
5925
    # Declare instance locks
5926
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5927

    
5928
  def DeclareLocks(self, level):
5929
    if level == locking.LEVEL_NODE:
5930
      self._LockInstancesNodes()
5931

    
5932
  def BuildHooksEnv(self):
5933
    """Build hooks env.
5934

5935
    This runs on the master, the primary and all the secondaries.
5936

5937
    """
5938
    env = {
5939
      "NODE_NAME": self.op.node_name,
5940
      }
5941

    
5942
    nl = [self.cfg.GetMasterNode()]
5943

    
5944
    return (env, nl, nl)
5945

    
5946

    
5947
class TLMigrateInstance(Tasklet):
5948
  """Tasklet class for instance migration.
5949

5950
  @type live: boolean
5951
  @ivar live: whether the migration will be done live or non-live;
5952
      this variable is initalized only after CheckPrereq has run
5953

5954
  """
5955
  def __init__(self, lu, instance_name, cleanup):
5956
    """Initializes this class.
5957

5958
    """
5959
    Tasklet.__init__(self, lu)
5960

    
5961
    # Parameters
5962
    self.instance_name = instance_name
5963
    self.cleanup = cleanup
5964
    self.live = False # will be overridden later
5965

    
5966
  def CheckPrereq(self):
5967
    """Check prerequisites.
5968

5969
    This checks that the instance is in the cluster.
5970

5971
    """
5972
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
5973
    instance = self.cfg.GetInstanceInfo(instance_name)
5974
    assert instance is not None
5975

    
5976
    if instance.disk_template != constants.DT_DRBD8:
5977
      raise errors.OpPrereqError("Instance's disk layout is not"
5978
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5979

    
5980
    secondary_nodes = instance.secondary_nodes
5981
    if not secondary_nodes:
5982
      raise errors.ConfigurationError("No secondary node but using"
5983
                                      " drbd8 disk template")
5984

    
5985
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5986

    
5987
    target_node = secondary_nodes[0]
5988
    # check memory requirements on the secondary node
5989
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
5990
                         instance.name, i_be[constants.BE_MEMORY],
5991
                         instance.hypervisor)
5992

    
5993
    # check bridge existance
5994
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
5995

    
5996
    if not self.cleanup:
5997
      _CheckNodeNotDrained(self.lu, target_node)
5998
      result = self.rpc.call_instance_migratable(instance.primary_node,
5999
                                                 instance)
6000
      result.Raise("Can't migrate, please use failover",
6001
                   prereq=True, ecode=errors.ECODE_STATE)
6002

    
6003
    self.instance = instance
6004

    
6005
    if self.lu.op.live is not None and self.lu.op.mode is not None:
6006
      raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
6007
                                 " parameters are accepted",
6008
                                 errors.ECODE_INVAL)
6009
    if self.lu.op.live is not None:
6010
      if self.lu.op.live:
6011
        self.lu.op.mode = constants.HT_MIGRATION_LIVE
6012
      else:
6013
        self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6014
      # reset the 'live' parameter to None so that repeated
6015
      # invocations of CheckPrereq do not raise an exception
6016
      self.lu.op.live = None
6017
    elif self.lu.op.mode is None:
6018
      # read the default value from the hypervisor
6019
      i_hv = self.cfg.GetClusterInfo().FillHV(instance, skip_globals=False)
6020
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6021

    
6022
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6023

    
6024
  def _WaitUntilSync(self):
6025
    """Poll with custom rpc for disk sync.
6026

6027
    This uses our own step-based rpc call.
6028

6029
    """
6030
    self.feedback_fn("* wait until resync is done")
6031
    all_done = False
6032
    while not all_done:
6033
      all_done = True
6034
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6035
                                            self.nodes_ip,
6036
                                            self.instance.disks)
6037
      min_percent = 100
6038
      for node, nres in result.items():
6039
        nres.Raise("Cannot resync disks on node %s" % node)
6040
        node_done, node_percent = nres.payload
6041
        all_done = all_done and node_done
6042
        if node_percent is not None:
6043
          min_percent = min(min_percent, node_percent)
6044
      if not all_done:
6045
        if min_percent < 100:
6046
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6047
        time.sleep(2)
6048

    
6049
  def _EnsureSecondary(self, node):
6050
    """Demote a node to secondary.
6051

6052
    """
6053
    self.feedback_fn("* switching node %s to secondary mode" % node)
6054

    
6055
    for dev in self.instance.disks:
6056
      self.cfg.SetDiskID(dev, node)
6057

    
6058
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6059
                                          self.instance.disks)
6060
    result.Raise("Cannot change disk to secondary on node %s" % node)
6061

    
6062
  def _GoStandalone(self):
6063
    """Disconnect from the network.
6064

6065
    """
6066
    self.feedback_fn("* changing into standalone mode")
6067
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6068
                                               self.instance.disks)
6069
    for node, nres in result.items():
6070
      nres.Raise("Cannot disconnect disks node %s" % node)
6071

    
6072
  def _GoReconnect(self, multimaster):
6073
    """Reconnect to the network.
6074

6075
    """
6076
    if multimaster:
6077
      msg = "dual-master"
6078
    else:
6079
      msg = "single-master"
6080
    self.feedback_fn("* changing disks into %s mode" % msg)
6081
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6082
                                           self.instance.disks,
6083
                                           self.instance.name, multimaster)
6084
    for node, nres in result.items():
6085
      nres.Raise("Cannot change disks config on node %s" % node)
6086

    
6087
  def _ExecCleanup(self):
6088
    """Try to cleanup after a failed migration.
6089

6090
    The cleanup is done by:
6091
      - check that the instance is running only on one node
6092
        (and update the config if needed)
6093
      - change disks on its secondary node to secondary
6094
      - wait until disks are fully synchronized
6095
      - disconnect from the network
6096
      - change disks into single-master mode
6097
      - wait again until disks are fully synchronized
6098

6099
    """
6100
    instance = self.instance
6101
    target_node = self.target_node
6102
    source_node = self.source_node
6103

    
6104
    # check running on only one node
6105
    self.feedback_fn("* checking where the instance actually runs"
6106
                     " (if this hangs, the hypervisor might be in"
6107
                     " a bad state)")
6108
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
6109
    for node, result in ins_l.items():
6110
      result.Raise("Can't contact node %s" % node)
6111

    
6112
    runningon_source = instance.name in ins_l[source_node].payload
6113
    runningon_target = instance.name in ins_l[target_node].payload
6114

    
6115
    if runningon_source and runningon_target:
6116
      raise errors.OpExecError("Instance seems to be running on two nodes,"
6117
                               " or the hypervisor is confused. You will have"
6118
                               " to ensure manually that it runs only on one"
6119
                               " and restart this operation.")
6120

    
6121
    if not (runningon_source or runningon_target):
6122
      raise errors.OpExecError("Instance does not seem to be running at all."
6123
                               " In this case, it's safer to repair by"
6124
                               " running 'gnt-instance stop' to ensure disk"
6125
                               " shutdown, and then restarting it.")
6126

    
6127
    if runningon_target:
6128
      # the migration has actually succeeded, we need to update the config
6129
      self.feedback_fn("* instance running on secondary node (%s),"
6130
                       " updating config" % target_node)
6131
      instance.primary_node = target_node
6132
      self.cfg.Update(instance, self.feedback_fn)
6133
      demoted_node = source_node
6134
    else:
6135
      self.feedback_fn("* instance confirmed to be running on its"
6136
                       " primary node (%s)" % source_node)
6137
      demoted_node = target_node
6138

    
6139
    self._EnsureSecondary(demoted_node)
6140
    try:
6141
      self._WaitUntilSync()
6142
    except errors.OpExecError:
6143
      # we ignore here errors, since if the device is standalone, it
6144
      # won't be able to sync
6145
      pass
6146
    self._GoStandalone()
6147
    self._GoReconnect(False)
6148
    self._WaitUntilSync()
6149

    
6150
    self.feedback_fn("* done")
6151

    
6152
  def _RevertDiskStatus(self):
6153
    """Try to revert the disk status after a failed migration.
6154

6155
    """
6156
    target_node = self.target_node
6157
    try:
6158
      self._EnsureSecondary(target_node)
6159
      self._GoStandalone()
6160
      self._GoReconnect(False)
6161
      self._WaitUntilSync()
6162
    except errors.OpExecError, err:
6163
      self.lu.LogWarning("Migration failed and I can't reconnect the"
6164
                         " drives: error '%s'\n"
6165
                         "Please look and recover the instance status" %
6166
                         str(err))
6167

    
6168
  def _AbortMigration(self):
6169
    """Call the hypervisor code to abort a started migration.
6170

6171
    """
6172
    instance = self.instance
6173
    target_node = self.target_node
6174
    migration_info = self.migration_info
6175

    
6176
    abort_result = self.rpc.call_finalize_migration(target_node,
6177
                                                    instance,
6178
                                                    migration_info,
6179
                                                    False)
6180
    abort_msg = abort_result.fail_msg
6181
    if abort_msg:
6182
      logging.error("Aborting migration failed on target node %s: %s",
6183
                    target_node, abort_msg)
6184
      # Don't raise an exception here, as we stil have to try to revert the
6185
      # disk status, even if this step failed.
6186

    
6187
  def _ExecMigration(self):
6188
    """Migrate an instance.
6189

6190
    The migrate is done by:
6191
      - change the disks into dual-master mode
6192
      - wait until disks are fully synchronized again
6193
      - migrate the instance
6194
      - change disks on the new secondary node (the old primary) to secondary
6195
      - wait until disks are fully synchronized
6196
      - change disks into single-master mode
6197

6198
    """
6199
    instance = self.instance
6200
    target_node = self.target_node
6201
    source_node = self.source_node
6202

    
6203
    self.feedback_fn("* checking disk consistency between source and target")
6204
    for dev in instance.disks:
6205
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6206
        raise errors.OpExecError("Disk %s is degraded or not fully"
6207
                                 " synchronized on target node,"
6208
                                 " aborting migrate." % dev.iv_name)
6209

    
6210
    # First get the migration information from the remote node
6211
    result = self.rpc.call_migration_info(source_node, instance)
6212
    msg = result.fail_msg
6213
    if msg:
6214
      log_err = ("Failed fetching source migration information from %s: %s" %
6215
                 (source_node, msg))
6216
      logging.error(log_err)
6217
      raise errors.OpExecError(log_err)
6218

    
6219
    self.migration_info = migration_info = result.payload
6220

    
6221
    # Then switch the disks to master/master mode
6222
    self._EnsureSecondary(target_node)
6223
    self._GoStandalone()
6224
    self._GoReconnect(True)
6225
    self._WaitUntilSync()
6226

    
6227
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6228
    result = self.rpc.call_accept_instance(target_node,
6229
                                           instance,
6230
                                           migration_info,
6231
                                           self.nodes_ip[target_node])
6232

    
6233
    msg = result.fail_msg
6234
    if msg:
6235
      logging.error("Instance pre-migration failed, trying to revert"
6236
                    " disk status: %s", msg)
6237
      self.feedback_fn("Pre-migration failed, aborting")
6238
      self._AbortMigration()
6239
      self._RevertDiskStatus()
6240
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6241
                               (instance.name, msg))
6242

    
6243
    self.feedback_fn("* migrating instance to %s" % target_node)
6244
    time.sleep(10)
6245
    result = self.rpc.call_instance_migrate(source_node, instance,
6246
                                            self.nodes_ip[target_node],
6247
                                            self.live)
6248
    msg = result.fail_msg
6249
    if msg:
6250
      logging.error("Instance migration failed, trying to revert"
6251
                    " disk status: %s", msg)
6252
      self.feedback_fn("Migration failed, aborting")
6253
      self._AbortMigration()
6254
      self._RevertDiskStatus()
6255
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6256
                               (instance.name, msg))
6257
    time.sleep(10)
6258

    
6259
    instance.primary_node = target_node
6260
    # distribute new instance config to the other nodes
6261
    self.cfg.Update(instance, self.feedback_fn)
6262

    
6263
    result = self.rpc.call_finalize_migration(target_node,
6264
                                              instance,
6265
                                              migration_info,
6266
                                              True)
6267
    msg = result.fail_msg
6268
    if msg:
6269
      logging.error("Instance migration succeeded, but finalization failed:"
6270
                    " %s", msg)
6271
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6272
                               msg)
6273

    
6274
    self._EnsureSecondary(source_node)
6275
    self._WaitUntilSync()
6276
    self._GoStandalone()
6277
    self._GoReconnect(False)
6278
    self._WaitUntilSync()
6279

    
6280
    self.feedback_fn("* done")
6281

    
6282
  def Exec(self, feedback_fn):
6283
    """Perform the migration.
6284

6285
    """
6286
    feedback_fn("Migrating instance %s" % self.instance.name)
6287

    
6288
    self.feedback_fn = feedback_fn
6289

    
6290
    self.source_node = self.instance.primary_node
6291
    self.target_node = self.instance.secondary_nodes[0]
6292
    self.all_nodes = [self.source_node, self.target_node]
6293
    self.nodes_ip = {
6294
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6295
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6296
      }
6297

    
6298
    if self.cleanup:
6299
      return self._ExecCleanup()
6300
    else:
6301
      return self._ExecMigration()
6302

    
6303

    
6304
def _CreateBlockDev(lu, node, instance, device, force_create,
6305
                    info, force_open):
6306
  """Create a tree of block devices on a given node.
6307

6308
  If this device type has to be created on secondaries, create it and
6309
  all its children.
6310

6311
  If not, just recurse to children keeping the same 'force' value.
6312

6313
  @param lu: the lu on whose behalf we execute
6314
  @param node: the node on which to create the device
6315
  @type instance: L{objects.Instance}
6316
  @param instance: the instance which owns the device
6317
  @type device: L{objects.Disk}
6318
  @param device: the device to create
6319
  @type force_create: boolean
6320
  @param force_create: whether to force creation of this device; this
6321
      will be change to True whenever we find a device which has
6322
      CreateOnSecondary() attribute
6323
  @param info: the extra 'metadata' we should attach to the device
6324
      (this will be represented as a LVM tag)
6325
  @type force_open: boolean
6326
  @param force_open: this parameter will be passes to the
6327
      L{backend.BlockdevCreate} function where it specifies
6328
      whether we run on primary or not, and it affects both
6329
      the child assembly and the device own Open() execution
6330

6331
  """
6332
  if device.CreateOnSecondary():
6333
    force_create = True
6334

    
6335
  if device.children:
6336
    for child in device.children:
6337
      _CreateBlockDev(lu, node, instance, child, force_create,
6338
                      info, force_open)
6339

    
6340
  if not force_create:
6341
    return
6342

    
6343
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6344

    
6345

    
6346
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6347
  """Create a single block device on a given node.
6348

6349
  This will not recurse over children of the device, so they must be
6350
  created in advance.
6351

6352
  @param lu: the lu on whose behalf we execute
6353
  @param node: the node on which to create the device
6354
  @type instance: L{objects.Instance}
6355
  @param instance: the instance which owns the device
6356
  @type device: L{objects.Disk}
6357
  @param device: the device to create
6358
  @param info: the extra 'metadata' we should attach to the device
6359
      (this will be represented as a LVM tag)
6360
  @type force_open: boolean
6361
  @param force_open: this parameter will be passes to the
6362
      L{backend.BlockdevCreate} function where it specifies
6363
      whether we run on primary or not, and it affects both
6364
      the child assembly and the device own Open() execution
6365

6366
  """
6367
  lu.cfg.SetDiskID(device, node)
6368
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6369
                                       instance.name, force_open, info)
6370
  result.Raise("Can't create block device %s on"
6371
               " node %s for instance %s" % (device, node, instance.name))
6372
  if device.physical_id is None:
6373
    device.physical_id = result.payload
6374

    
6375

    
6376
def _GenerateUniqueNames(lu, exts):
6377
  """Generate a suitable LV name.
6378

6379
  This will generate a logical volume name for the given instance.
6380

6381
  """
6382
  results = []
6383
  for val in exts:
6384
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6385
    results.append("%s%s" % (new_id, val))
6386
  return results
6387

    
6388

    
6389
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
6390
                         p_minor, s_minor):
6391
  """Generate a drbd8 device complete with its children.
6392

6393
  """
6394
  port = lu.cfg.AllocatePort()
6395
  vgname = lu.cfg.GetVGName()
6396
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6397
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6398
                          logical_id=(vgname, names[0]))
6399
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6400
                          logical_id=(vgname, names[1]))
6401
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6402
                          logical_id=(primary, secondary, port,
6403
                                      p_minor, s_minor,
6404
                                      shared_secret),
6405
                          children=[dev_data, dev_meta],
6406
                          iv_name=iv_name)
6407
  return drbd_dev
6408

    
6409

    
6410
def _GenerateDiskTemplate(lu, template_name,
6411
                          instance_name, primary_node,
6412
                          secondary_nodes, disk_info,
6413
                          file_storage_dir, file_driver,
6414
                          base_index):
6415
  """Generate the entire disk layout for a given template type.
6416

6417
  """
6418
  #TODO: compute space requirements
6419

    
6420
  vgname = lu.cfg.GetVGName()
6421
  disk_count = len(disk_info)
6422
  disks = []
6423
  if template_name == constants.DT_DISKLESS:
6424
    pass
6425
  elif template_name == constants.DT_PLAIN:
6426
    if len(secondary_nodes) != 0:
6427
      raise errors.ProgrammerError("Wrong template configuration")
6428

    
6429
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6430
                                      for i in range(disk_count)])
6431
    for idx, disk in enumerate(disk_info):
6432
      disk_index = idx + base_index
6433
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6434
                              logical_id=(vgname, names[idx]),
6435
                              iv_name="disk/%d" % disk_index,
6436
                              mode=disk["mode"])
6437
      disks.append(disk_dev)
6438
  elif template_name == constants.DT_DRBD8:
6439
    if len(secondary_nodes) != 1:
6440
      raise errors.ProgrammerError("Wrong template configuration")
6441
    remote_node = secondary_nodes[0]
6442
    minors = lu.cfg.AllocateDRBDMinor(
6443
      [primary_node, remote_node] * len(disk_info), instance_name)
6444

    
6445
    names = []
6446
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6447
                                               for i in range(disk_count)]):
6448
      names.append(lv_prefix + "_data")
6449
      names.append(lv_prefix + "_meta")
6450
    for idx, disk in enumerate(disk_info):
6451
      disk_index = idx + base_index
6452
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6453
                                      disk["size"], names[idx*2:idx*2+2],
6454
                                      "disk/%d" % disk_index,
6455
                                      minors[idx*2], minors[idx*2+1])
6456
      disk_dev.mode = disk["mode"]
6457
      disks.append(disk_dev)
6458
  elif template_name == constants.DT_FILE:
6459
    if len(secondary_nodes) != 0:
6460
      raise errors.ProgrammerError("Wrong template configuration")
6461

    
6462
    _RequireFileStorage()
6463

    
6464
    for idx, disk in enumerate(disk_info):
6465
      disk_index = idx + base_index
6466
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6467
                              iv_name="disk/%d" % disk_index,
6468
                              logical_id=(file_driver,
6469
                                          "%s/disk%d" % (file_storage_dir,
6470
                                                         disk_index)),
6471
                              mode=disk["mode"])
6472
      disks.append(disk_dev)
6473
  else:
6474
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6475
  return disks
6476

    
6477

    
6478
def _GetInstanceInfoText(instance):
6479
  """Compute that text that should be added to the disk's metadata.
6480

6481
  """
6482
  return "originstname+%s" % instance.name
6483

    
6484

    
6485
def _CalcEta(time_taken, written, total_size):
6486
  """Calculates the ETA based on size written and total size.
6487

6488
  @param time_taken: The time taken so far
6489
  @param written: amount written so far
6490
  @param total_size: The total size of data to be written
6491
  @return: The remaining time in seconds
6492

6493
  """
6494
  avg_time = time_taken / float(written)
6495
  return (total_size - written) * avg_time
6496

    
6497

    
6498
def _WipeDisks(lu, instance):
6499
  """Wipes instance disks.
6500

6501
  @type lu: L{LogicalUnit}
6502
  @param lu: the logical unit on whose behalf we execute
6503
  @type instance: L{objects.Instance}
6504
  @param instance: the instance whose disks we should create
6505
  @return: the success of the wipe
6506

6507
  """
6508
  node = instance.primary_node
6509
  for idx, device in enumerate(instance.disks):
6510
    lu.LogInfo("* Wiping disk %d", idx)
6511
    logging.info("Wiping disk %d for instance %s", idx, instance.name)
6512

    
6513
    # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
6514
    # MAX_WIPE_CHUNK at max
6515
    wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
6516
                          constants.MIN_WIPE_CHUNK_PERCENT)
6517

    
6518
    offset = 0
6519
    size = device.size
6520
    last_output = 0
6521
    start_time = time.time()
6522

    
6523
    while offset < size:
6524
      wipe_size = min(wipe_chunk_size, size - offset)
6525
      result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
6526
      result.Raise("Could not wipe disk %d at offset %d for size %d" %
6527
                   (idx, offset, wipe_size))
6528
      now = time.time()
6529
      offset += wipe_size
6530
      if now - last_output >= 60:
6531
        eta = _CalcEta(now - start_time, offset, size)
6532
        lu.LogInfo(" - done: %.1f%% ETA: %s" %
6533
                   (offset / float(size) * 100, utils.FormatSeconds(eta)))
6534
        last_output = now
6535

    
6536

    
6537
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6538
  """Create all disks for an instance.
6539

6540
  This abstracts away some work from AddInstance.
6541

6542
  @type lu: L{LogicalUnit}
6543
  @param lu: the logical unit on whose behalf we execute
6544
  @type instance: L{objects.Instance}
6545
  @param instance: the instance whose disks we should create
6546
  @type to_skip: list
6547
  @param to_skip: list of indices to skip
6548
  @type target_node: string
6549
  @param target_node: if passed, overrides the target node for creation
6550
  @rtype: boolean
6551
  @return: the success of the creation
6552

6553
  """
6554
  info = _GetInstanceInfoText(instance)
6555
  if target_node is None:
6556
    pnode = instance.primary_node
6557
    all_nodes = instance.all_nodes
6558
  else:
6559
    pnode = target_node
6560
    all_nodes = [pnode]
6561

    
6562
  if instance.disk_template == constants.DT_FILE:
6563
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6564
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6565

    
6566
    result.Raise("Failed to create directory '%s' on"
6567
                 " node %s" % (file_storage_dir, pnode))
6568

    
6569
  # Note: this needs to be kept in sync with adding of disks in
6570
  # LUSetInstanceParams
6571
  for idx, device in enumerate(instance.disks):
6572
    if to_skip and idx in to_skip:
6573
      continue
6574
    logging.info("Creating volume %s for instance %s",
6575
                 device.iv_name, instance.name)
6576
    #HARDCODE
6577
    for node in all_nodes:
6578
      f_create = node == pnode
6579
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6580

    
6581

    
6582
def _RemoveDisks(lu, instance, target_node=None):
6583
  """Remove all disks for an instance.
6584

6585
  This abstracts away some work from `AddInstance()` and
6586
  `RemoveInstance()`. Note that in case some of the devices couldn't
6587
  be removed, the removal will continue with the other ones (compare
6588
  with `_CreateDisks()`).
6589

6590
  @type lu: L{LogicalUnit}
6591
  @param lu: the logical unit on whose behalf we execute
6592
  @type instance: L{objects.Instance}
6593
  @param instance: the instance whose disks we should remove
6594
  @type target_node: string
6595
  @param target_node: used to override the node on which to remove the disks
6596
  @rtype: boolean
6597
  @return: the success of the removal
6598

6599
  """
6600
  logging.info("Removing block devices for instance %s", instance.name)
6601

    
6602
  all_result = True
6603
  for device in instance.disks:
6604
    if target_node:
6605
      edata = [(target_node, device)]
6606
    else:
6607
      edata = device.ComputeNodeTree(instance.primary_node)
6608
    for node, disk in edata:
6609
      lu.cfg.SetDiskID(disk, node)
6610
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6611
      if msg:
6612
        lu.LogWarning("Could not remove block device %s on node %s,"
6613
                      " continuing anyway: %s", device.iv_name, node, msg)
6614
        all_result = False
6615

    
6616
  if instance.disk_template == constants.DT_FILE:
6617
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6618
    if target_node:
6619
      tgt = target_node
6620
    else:
6621
      tgt = instance.primary_node
6622
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6623
    if result.fail_msg:
6624
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6625
                    file_storage_dir, instance.primary_node, result.fail_msg)
6626
      all_result = False
6627

    
6628
  return all_result
6629

    
6630

    
6631
def _ComputeDiskSize(disk_template, disks):
6632
  """Compute disk size requirements in the volume group
6633

6634
  """
6635
  # Required free disk space as a function of disk and swap space
6636
  req_size_dict = {
6637
    constants.DT_DISKLESS: None,
6638
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6639
    # 128 MB are added for drbd metadata for each disk
6640
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6641
    constants.DT_FILE: None,
6642
  }
6643

    
6644
  if disk_template not in req_size_dict:
6645
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6646
                                 " is unknown" %  disk_template)
6647

    
6648
  return req_size_dict[disk_template]
6649

    
6650

    
6651
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6652
  """Hypervisor parameter validation.
6653

6654
  This function abstract the hypervisor parameter validation to be
6655
  used in both instance create and instance modify.
6656

6657
  @type lu: L{LogicalUnit}
6658
  @param lu: the logical unit for which we check
6659
  @type nodenames: list
6660
  @param nodenames: the list of nodes on which we should check
6661
  @type hvname: string
6662
  @param hvname: the name of the hypervisor we should use
6663
  @type hvparams: dict
6664
  @param hvparams: the parameters which we need to check
6665
  @raise errors.OpPrereqError: if the parameters are not valid
6666

6667
  """
6668
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6669
                                                  hvname,
6670
                                                  hvparams)
6671
  for node in nodenames:
6672
    info = hvinfo[node]
6673
    if info.offline:
6674
      continue
6675
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6676

    
6677

    
6678
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6679
  """OS parameters validation.
6680

6681
  @type lu: L{LogicalUnit}
6682
  @param lu: the logical unit for which we check
6683
  @type required: boolean
6684
  @param required: whether the validation should fail if the OS is not
6685
      found
6686
  @type nodenames: list
6687
  @param nodenames: the list of nodes on which we should check
6688
  @type osname: string
6689
  @param osname: the name of the hypervisor we should use
6690
  @type osparams: dict
6691
  @param osparams: the parameters which we need to check
6692
  @raise errors.OpPrereqError: if the parameters are not valid
6693

6694
  """
6695
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6696
                                   [constants.OS_VALIDATE_PARAMETERS],
6697
                                   osparams)
6698
  for node, nres in result.items():
6699
    # we don't check for offline cases since this should be run only
6700
    # against the master node and/or an instance's nodes
6701
    nres.Raise("OS Parameters validation failed on node %s" % node)
6702
    if not nres.payload:
6703
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6704
                 osname, node)
6705

    
6706

    
6707
class LUCreateInstance(LogicalUnit):
6708
  """Create an instance.
6709

6710
  """
6711
  HPATH = "instance-add"
6712
  HTYPE = constants.HTYPE_INSTANCE
6713
  _OP_PARAMS = [
6714
    _PInstanceName,
6715
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES)),
6716
    ("start", True, ht.TBool),
6717
    ("wait_for_sync", True, ht.TBool),
6718
    ("ip_check", True, ht.TBool),
6719
    ("name_check", True, ht.TBool),
6720
    ("disks", ht.NoDefault, ht.TListOf(ht.TDict)),
6721
    ("nics", ht.NoDefault, ht.TListOf(ht.TDict)),
6722
    ("hvparams", ht.EmptyDict, ht.TDict),
6723
    ("beparams", ht.EmptyDict, ht.TDict),
6724
    ("osparams", ht.EmptyDict, ht.TDict),
6725
    ("no_install", None, ht.TMaybeBool),
6726
    ("os_type", None, ht.TMaybeString),
6727
    ("force_variant", False, ht.TBool),
6728
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone)),
6729
    ("source_x509_ca", None, ht.TMaybeString),
6730
    ("source_instance_name", None, ht.TMaybeString),
6731
    ("src_node", None, ht.TMaybeString),
6732
    ("src_path", None, ht.TMaybeString),
6733
    ("pnode", None, ht.TMaybeString),
6734
    ("snode", None, ht.TMaybeString),
6735
    ("iallocator", None, ht.TMaybeString),
6736
    ("hypervisor", None, ht.TMaybeString),
6737
    ("disk_template", ht.NoDefault, _CheckDiskTemplate),
6738
    ("identify_defaults", False, ht.TBool),
6739
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER))),
6740
    ("file_storage_dir", None, ht.TMaybeString),
6741
    ]
6742
  REQ_BGL = False
6743

    
6744
  def CheckArguments(self):
6745
    """Check arguments.
6746

6747
    """
6748
    # do not require name_check to ease forward/backward compatibility
6749
    # for tools
6750
    if self.op.no_install and self.op.start:
6751
      self.LogInfo("No-installation mode selected, disabling startup")
6752
      self.op.start = False
6753
    # validate/normalize the instance name
6754
    self.op.instance_name = \
6755
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
6756

    
6757
    if self.op.ip_check and not self.op.name_check:
6758
      # TODO: make the ip check more flexible and not depend on the name check
6759
      raise errors.OpPrereqError("Cannot do ip check without a name check",
6760
                                 errors.ECODE_INVAL)
6761

    
6762
    # check nics' parameter names
6763
    for nic in self.op.nics:
6764
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6765

    
6766
    # check disks. parameter names and consistent adopt/no-adopt strategy
6767
    has_adopt = has_no_adopt = False
6768
    for disk in self.op.disks:
6769
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6770
      if "adopt" in disk:
6771
        has_adopt = True
6772
      else:
6773
        has_no_adopt = True
6774
    if has_adopt and has_no_adopt:
6775
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6776
                                 errors.ECODE_INVAL)
6777
    if has_adopt:
6778
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6779
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6780
                                   " '%s' disk template" %
6781
                                   self.op.disk_template,
6782
                                   errors.ECODE_INVAL)
6783
      if self.op.iallocator is not None:
6784
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6785
                                   " iallocator script", errors.ECODE_INVAL)
6786
      if self.op.mode == constants.INSTANCE_IMPORT:
6787
        raise errors.OpPrereqError("Disk adoption not allowed for"
6788
                                   " instance import", errors.ECODE_INVAL)
6789

    
6790
    self.adopt_disks = has_adopt
6791

    
6792
    # instance name verification
6793
    if self.op.name_check:
6794
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
6795
      self.op.instance_name = self.hostname1.name
6796
      # used in CheckPrereq for ip ping check
6797
      self.check_ip = self.hostname1.ip
6798
    else:
6799
      self.check_ip = None
6800

    
6801
    # file storage checks
6802
    if (self.op.file_driver and
6803
        not self.op.file_driver in constants.FILE_DRIVER):
6804
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6805
                                 self.op.file_driver, errors.ECODE_INVAL)
6806

    
6807
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6808
      raise errors.OpPrereqError("File storage directory path not absolute",
6809
                                 errors.ECODE_INVAL)
6810

    
6811
    ### Node/iallocator related checks
6812
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
6813

    
6814
    if self.op.pnode is not None:
6815
      if self.op.disk_template in constants.DTS_NET_MIRROR:
6816
        if self.op.snode is None:
6817
          raise errors.OpPrereqError("The networked disk templates need"
6818
                                     " a mirror node", errors.ECODE_INVAL)
6819
      elif self.op.snode:
6820
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
6821
                        " template")
6822
        self.op.snode = None
6823

    
6824
    self._cds = _GetClusterDomainSecret()
6825

    
6826
    if self.op.mode == constants.INSTANCE_IMPORT:
6827
      # On import force_variant must be True, because if we forced it at
6828
      # initial install, our only chance when importing it back is that it
6829
      # works again!
6830
      self.op.force_variant = True
6831

    
6832
      if self.op.no_install:
6833
        self.LogInfo("No-installation mode has no effect during import")
6834

    
6835
    elif self.op.mode == constants.INSTANCE_CREATE:
6836
      if self.op.os_type is None:
6837
        raise errors.OpPrereqError("No guest OS specified",
6838
                                   errors.ECODE_INVAL)
6839
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
6840
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
6841
                                   " installation" % self.op.os_type,
6842
                                   errors.ECODE_STATE)
6843
      if self.op.disk_template is None:
6844
        raise errors.OpPrereqError("No disk template specified",
6845
                                   errors.ECODE_INVAL)
6846

    
6847
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6848
      # Check handshake to ensure both clusters have the same domain secret
6849
      src_handshake = self.op.source_handshake
6850
      if not src_handshake:
6851
        raise errors.OpPrereqError("Missing source handshake",
6852
                                   errors.ECODE_INVAL)
6853

    
6854
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6855
                                                           src_handshake)
6856
      if errmsg:
6857
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6858
                                   errors.ECODE_INVAL)
6859

    
6860
      # Load and check source CA
6861
      self.source_x509_ca_pem = self.op.source_x509_ca
6862
      if not self.source_x509_ca_pem:
6863
        raise errors.OpPrereqError("Missing source X509 CA",
6864
                                   errors.ECODE_INVAL)
6865

    
6866
      try:
6867
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
6868
                                                    self._cds)
6869
      except OpenSSL.crypto.Error, err:
6870
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
6871
                                   (err, ), errors.ECODE_INVAL)
6872

    
6873
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
6874
      if errcode is not None:
6875
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
6876
                                   errors.ECODE_INVAL)
6877

    
6878
      self.source_x509_ca = cert
6879

    
6880
      src_instance_name = self.op.source_instance_name
6881
      if not src_instance_name:
6882
        raise errors.OpPrereqError("Missing source instance name",
6883
                                   errors.ECODE_INVAL)
6884

    
6885
      self.source_instance_name = \
6886
          netutils.GetHostname(name=src_instance_name).name
6887

    
6888
    else:
6889
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
6890
                                 self.op.mode, errors.ECODE_INVAL)
6891

    
6892
  def ExpandNames(self):
6893
    """ExpandNames for CreateInstance.
6894

6895
    Figure out the right locks for instance creation.
6896

6897
    """
6898
    self.needed_locks = {}
6899

    
6900
    instance_name = self.op.instance_name
6901
    # this is just a preventive check, but someone might still add this
6902
    # instance in the meantime, and creation will fail at lock-add time
6903
    if instance_name in self.cfg.GetInstanceList():
6904
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6905
                                 instance_name, errors.ECODE_EXISTS)
6906

    
6907
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
6908

    
6909
    if self.op.iallocator:
6910
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6911
    else:
6912
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
6913
      nodelist = [self.op.pnode]
6914
      if self.op.snode is not None:
6915
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
6916
        nodelist.append(self.op.snode)
6917
      self.needed_locks[locking.LEVEL_NODE] = nodelist
6918

    
6919
    # in case of import lock the source node too
6920
    if self.op.mode == constants.INSTANCE_IMPORT:
6921
      src_node = self.op.src_node
6922
      src_path = self.op.src_path
6923

    
6924
      if src_path is None:
6925
        self.op.src_path = src_path = self.op.instance_name
6926

    
6927
      if src_node is None:
6928
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6929
        self.op.src_node = None
6930
        if os.path.isabs(src_path):
6931
          raise errors.OpPrereqError("Importing an instance from an absolute"
6932
                                     " path requires a source node option.",
6933
                                     errors.ECODE_INVAL)
6934
      else:
6935
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
6936
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
6937
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
6938
        if not os.path.isabs(src_path):
6939
          self.op.src_path = src_path = \
6940
            utils.PathJoin(constants.EXPORT_DIR, src_path)
6941

    
6942
  def _RunAllocator(self):
6943
    """Run the allocator based on input opcode.
6944

6945
    """
6946
    nics = [n.ToDict() for n in self.nics]
6947
    ial = IAllocator(self.cfg, self.rpc,
6948
                     mode=constants.IALLOCATOR_MODE_ALLOC,
6949
                     name=self.op.instance_name,
6950
                     disk_template=self.op.disk_template,
6951
                     tags=[],
6952
                     os=self.op.os_type,
6953
                     vcpus=self.be_full[constants.BE_VCPUS],
6954
                     mem_size=self.be_full[constants.BE_MEMORY],
6955
                     disks=self.disks,
6956
                     nics=nics,
6957
                     hypervisor=self.op.hypervisor,
6958
                     )
6959

    
6960
    ial.Run(self.op.iallocator)
6961

    
6962
    if not ial.success:
6963
      raise errors.OpPrereqError("Can't compute nodes using"
6964
                                 " iallocator '%s': %s" %
6965
                                 (self.op.iallocator, ial.info),
6966
                                 errors.ECODE_NORES)
6967
    if len(ial.result) != ial.required_nodes:
6968
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6969
                                 " of nodes (%s), required %s" %
6970
                                 (self.op.iallocator, len(ial.result),
6971
                                  ial.required_nodes), errors.ECODE_FAULT)
6972
    self.op.pnode = ial.result[0]
6973
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6974
                 self.op.instance_name, self.op.iallocator,
6975
                 utils.CommaJoin(ial.result))
6976
    if ial.required_nodes == 2:
6977
      self.op.snode = ial.result[1]
6978

    
6979
  def BuildHooksEnv(self):
6980
    """Build hooks env.
6981

6982
    This runs on master, primary and secondary nodes of the instance.
6983

6984
    """
6985
    env = {
6986
      "ADD_MODE": self.op.mode,
6987
      }
6988
    if self.op.mode == constants.INSTANCE_IMPORT:
6989
      env["SRC_NODE"] = self.op.src_node
6990
      env["SRC_PATH"] = self.op.src_path
6991
      env["SRC_IMAGES"] = self.src_images
6992

    
6993
    env.update(_BuildInstanceHookEnv(
6994
      name=self.op.instance_name,
6995
      primary_node=self.op.pnode,
6996
      secondary_nodes=self.secondaries,
6997
      status=self.op.start,
6998
      os_type=self.op.os_type,
6999
      memory=self.be_full[constants.BE_MEMORY],
7000
      vcpus=self.be_full[constants.BE_VCPUS],
7001
      nics=_NICListToTuple(self, self.nics),
7002
      disk_template=self.op.disk_template,
7003
      disks=[(d["size"], d["mode"]) for d in self.disks],
7004
      bep=self.be_full,
7005
      hvp=self.hv_full,
7006
      hypervisor_name=self.op.hypervisor,
7007
    ))
7008

    
7009
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
7010
          self.secondaries)
7011
    return env, nl, nl
7012

    
7013
  def _ReadExportInfo(self):
7014
    """Reads the export information from disk.
7015

7016
    It will override the opcode source node and path with the actual
7017
    information, if these two were not specified before.
7018

7019
    @return: the export information
7020

7021
    """
7022
    assert self.op.mode == constants.INSTANCE_IMPORT
7023

    
7024
    src_node = self.op.src_node
7025
    src_path = self.op.src_path
7026

    
7027
    if src_node is None:
7028
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
7029
      exp_list = self.rpc.call_export_list(locked_nodes)
7030
      found = False
7031
      for node in exp_list:
7032
        if exp_list[node].fail_msg:
7033
          continue
7034
        if src_path in exp_list[node].payload:
7035
          found = True
7036
          self.op.src_node = src_node = node
7037
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
7038
                                                       src_path)
7039
          break
7040
      if not found:
7041
        raise errors.OpPrereqError("No export found for relative path %s" %
7042
                                    src_path, errors.ECODE_INVAL)
7043

    
7044
    _CheckNodeOnline(self, src_node)
7045
    result = self.rpc.call_export_info(src_node, src_path)
7046
    result.Raise("No export or invalid export found in dir %s" % src_path)
7047

    
7048
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
7049
    if not export_info.has_section(constants.INISECT_EXP):
7050
      raise errors.ProgrammerError("Corrupted export config",
7051
                                   errors.ECODE_ENVIRON)
7052

    
7053
    ei_version = export_info.get(constants.INISECT_EXP, "version")
7054
    if (int(ei_version) != constants.EXPORT_VERSION):
7055
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
7056
                                 (ei_version, constants.EXPORT_VERSION),
7057
                                 errors.ECODE_ENVIRON)
7058
    return export_info
7059

    
7060
  def _ReadExportParams(self, einfo):
7061
    """Use export parameters as defaults.
7062

7063
    In case the opcode doesn't specify (as in override) some instance
7064
    parameters, then try to use them from the export information, if
7065
    that declares them.
7066

7067
    """
7068
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
7069

    
7070
    if self.op.disk_template is None:
7071
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
7072
        self.op.disk_template = einfo.get(constants.INISECT_INS,
7073
                                          "disk_template")
7074
      else:
7075
        raise errors.OpPrereqError("No disk template specified and the export"
7076
                                   " is missing the disk_template information",
7077
                                   errors.ECODE_INVAL)
7078

    
7079
    if not self.op.disks:
7080
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
7081
        disks = []
7082
        # TODO: import the disk iv_name too
7083
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
7084
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
7085
          disks.append({"size": disk_sz})
7086
        self.op.disks = disks
7087
      else:
7088
        raise errors.OpPrereqError("No disk info specified and the export"
7089
                                   " is missing the disk information",
7090
                                   errors.ECODE_INVAL)
7091

    
7092
    if (not self.op.nics and
7093
        einfo.has_option(constants.INISECT_INS, "nic_count")):
7094
      nics = []
7095
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
7096
        ndict = {}
7097
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
7098
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
7099
          ndict[name] = v
7100
        nics.append(ndict)
7101
      self.op.nics = nics
7102

    
7103
    if (self.op.hypervisor is None and
7104
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
7105
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
7106
    if einfo.has_section(constants.INISECT_HYP):
7107
      # use the export parameters but do not override the ones
7108
      # specified by the user
7109
      for name, value in einfo.items(constants.INISECT_HYP):
7110
        if name not in self.op.hvparams:
7111
          self.op.hvparams[name] = value
7112

    
7113
    if einfo.has_section(constants.INISECT_BEP):
7114
      # use the parameters, without overriding
7115
      for name, value in einfo.items(constants.INISECT_BEP):
7116
        if name not in self.op.beparams:
7117
          self.op.beparams[name] = value
7118
    else:
7119
      # try to read the parameters old style, from the main section
7120
      for name in constants.BES_PARAMETERS:
7121
        if (name not in self.op.beparams and
7122
            einfo.has_option(constants.INISECT_INS, name)):
7123
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
7124

    
7125
    if einfo.has_section(constants.INISECT_OSP):
7126
      # use the parameters, without overriding
7127
      for name, value in einfo.items(constants.INISECT_OSP):
7128
        if name not in self.op.osparams:
7129
          self.op.osparams[name] = value
7130

    
7131
  def _RevertToDefaults(self, cluster):
7132
    """Revert the instance parameters to the default values.
7133

7134
    """
7135
    # hvparams
7136
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
7137
    for name in self.op.hvparams.keys():
7138
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
7139
        del self.op.hvparams[name]
7140
    # beparams
7141
    be_defs = cluster.SimpleFillBE({})
7142
    for name in self.op.beparams.keys():
7143
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
7144
        del self.op.beparams[name]
7145
    # nic params
7146
    nic_defs = cluster.SimpleFillNIC({})
7147
    for nic in self.op.nics:
7148
      for name in constants.NICS_PARAMETERS:
7149
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
7150
          del nic[name]
7151
    # osparams
7152
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
7153
    for name in self.op.osparams.keys():
7154
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
7155
        del self.op.osparams[name]
7156

    
7157
  def CheckPrereq(self):
7158
    """Check prerequisites.
7159

7160
    """
7161
    if self.op.mode == constants.INSTANCE_IMPORT:
7162
      export_info = self._ReadExportInfo()
7163
      self._ReadExportParams(export_info)
7164

    
7165
    _CheckDiskTemplate(self.op.disk_template)
7166

    
7167
    if (not self.cfg.GetVGName() and
7168
        self.op.disk_template not in constants.DTS_NOT_LVM):
7169
      raise errors.OpPrereqError("Cluster does not support lvm-based"
7170
                                 " instances", errors.ECODE_STATE)
7171

    
7172
    if self.op.hypervisor is None:
7173
      self.op.hypervisor = self.cfg.GetHypervisorType()
7174

    
7175
    cluster = self.cfg.GetClusterInfo()
7176
    enabled_hvs = cluster.enabled_hypervisors
7177
    if self.op.hypervisor not in enabled_hvs:
7178
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
7179
                                 " cluster (%s)" % (self.op.hypervisor,
7180
                                  ",".join(enabled_hvs)),
7181
                                 errors.ECODE_STATE)
7182

    
7183
    # check hypervisor parameter syntax (locally)
7184
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
7185
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
7186
                                      self.op.hvparams)
7187
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
7188
    hv_type.CheckParameterSyntax(filled_hvp)
7189
    self.hv_full = filled_hvp
7190
    # check that we don't specify global parameters on an instance
7191
    _CheckGlobalHvParams(self.op.hvparams)
7192

    
7193
    # fill and remember the beparams dict
7194
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
7195
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
7196

    
7197
    # build os parameters
7198
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
7199

    
7200
    # now that hvp/bep are in final format, let's reset to defaults,
7201
    # if told to do so
7202
    if self.op.identify_defaults:
7203
      self._RevertToDefaults(cluster)
7204

    
7205
    # NIC buildup
7206
    self.nics = []
7207
    for idx, nic in enumerate(self.op.nics):
7208
      nic_mode_req = nic.get("mode", None)
7209
      nic_mode = nic_mode_req
7210
      if nic_mode is None:
7211
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
7212

    
7213
      # in routed mode, for the first nic, the default ip is 'auto'
7214
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
7215
        default_ip_mode = constants.VALUE_AUTO
7216
      else:
7217
        default_ip_mode = constants.VALUE_NONE
7218

    
7219
      # ip validity checks
7220
      ip = nic.get("ip", default_ip_mode)
7221
      if ip is None or ip.lower() == constants.VALUE_NONE:
7222
        nic_ip = None
7223
      elif ip.lower() == constants.VALUE_AUTO:
7224
        if not self.op.name_check:
7225
          raise errors.OpPrereqError("IP address set to auto but name checks"
7226
                                     " have been skipped",
7227
                                     errors.ECODE_INVAL)
7228
        nic_ip = self.hostname1.ip
7229
      else:
7230
        if not netutils.IPAddress.IsValid(ip):
7231
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
7232
                                     errors.ECODE_INVAL)
7233
        nic_ip = ip
7234

    
7235
      # TODO: check the ip address for uniqueness
7236
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7237
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7238
                                   errors.ECODE_INVAL)
7239

    
7240
      # MAC address verification
7241
      mac = nic.get("mac", constants.VALUE_AUTO)
7242
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7243
        mac = utils.NormalizeAndValidateMac(mac)
7244

    
7245
        try:
7246
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7247
        except errors.ReservationError:
7248
          raise errors.OpPrereqError("MAC address %s already in use"
7249
                                     " in cluster" % mac,
7250
                                     errors.ECODE_NOTUNIQUE)
7251

    
7252
      # bridge verification
7253
      bridge = nic.get("bridge", None)
7254
      link = nic.get("link", None)
7255
      if bridge and link:
7256
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7257
                                   " at the same time", errors.ECODE_INVAL)
7258
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7259
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7260
                                   errors.ECODE_INVAL)
7261
      elif bridge:
7262
        link = bridge
7263

    
7264
      nicparams = {}
7265
      if nic_mode_req:
7266
        nicparams[constants.NIC_MODE] = nic_mode_req
7267
      if link:
7268
        nicparams[constants.NIC_LINK] = link
7269

    
7270
      check_params = cluster.SimpleFillNIC(nicparams)
7271
      objects.NIC.CheckParameterSyntax(check_params)
7272
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7273

    
7274
    # disk checks/pre-build
7275
    self.disks = []
7276
    for disk in self.op.disks:
7277
      mode = disk.get("mode", constants.DISK_RDWR)
7278
      if mode not in constants.DISK_ACCESS_SET:
7279
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7280
                                   mode, errors.ECODE_INVAL)
7281
      size = disk.get("size", None)
7282
      if size is None:
7283
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7284
      try:
7285
        size = int(size)
7286
      except (TypeError, ValueError):
7287
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7288
                                   errors.ECODE_INVAL)
7289
      new_disk = {"size": size, "mode": mode}
7290
      if "adopt" in disk:
7291
        new_disk["adopt"] = disk["adopt"]
7292
      self.disks.append(new_disk)
7293

    
7294
    if self.op.mode == constants.INSTANCE_IMPORT:
7295

    
7296
      # Check that the new instance doesn't have less disks than the export
7297
      instance_disks = len(self.disks)
7298
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7299
      if instance_disks < export_disks:
7300
        raise errors.OpPrereqError("Not enough disks to import."
7301
                                   " (instance: %d, export: %d)" %
7302
                                   (instance_disks, export_disks),
7303
                                   errors.ECODE_INVAL)
7304

    
7305
      disk_images = []
7306
      for idx in range(export_disks):
7307
        option = 'disk%d_dump' % idx
7308
        if export_info.has_option(constants.INISECT_INS, option):
7309
          # FIXME: are the old os-es, disk sizes, etc. useful?
7310
          export_name = export_info.get(constants.INISECT_INS, option)
7311
          image = utils.PathJoin(self.op.src_path, export_name)
7312
          disk_images.append(image)
7313
        else:
7314
          disk_images.append(False)
7315

    
7316
      self.src_images = disk_images
7317

    
7318
      old_name = export_info.get(constants.INISECT_INS, 'name')
7319
      try:
7320
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7321
      except (TypeError, ValueError), err:
7322
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7323
                                   " an integer: %s" % str(err),
7324
                                   errors.ECODE_STATE)
7325
      if self.op.instance_name == old_name:
7326
        for idx, nic in enumerate(self.nics):
7327
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7328
            nic_mac_ini = 'nic%d_mac' % idx
7329
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7330

    
7331
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7332

    
7333
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7334
    if self.op.ip_check:
7335
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7336
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7337
                                   (self.check_ip, self.op.instance_name),
7338
                                   errors.ECODE_NOTUNIQUE)
7339

    
7340
    #### mac address generation
7341
    # By generating here the mac address both the allocator and the hooks get
7342
    # the real final mac address rather than the 'auto' or 'generate' value.
7343
    # There is a race condition between the generation and the instance object
7344
    # creation, which means that we know the mac is valid now, but we're not
7345
    # sure it will be when we actually add the instance. If things go bad
7346
    # adding the instance will abort because of a duplicate mac, and the
7347
    # creation job will fail.
7348
    for nic in self.nics:
7349
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7350
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7351

    
7352
    #### allocator run
7353

    
7354
    if self.op.iallocator is not None:
7355
      self._RunAllocator()
7356

    
7357
    #### node related checks
7358

    
7359
    # check primary node
7360
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7361
    assert self.pnode is not None, \
7362
      "Cannot retrieve locked node %s" % self.op.pnode
7363
    if pnode.offline:
7364
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7365
                                 pnode.name, errors.ECODE_STATE)
7366
    if pnode.drained:
7367
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7368
                                 pnode.name, errors.ECODE_STATE)
7369
    if not pnode.vm_capable:
7370
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
7371
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
7372

    
7373
    self.secondaries = []
7374

    
7375
    # mirror node verification
7376
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7377
      if self.op.snode == pnode.name:
7378
        raise errors.OpPrereqError("The secondary node cannot be the"
7379
                                   " primary node.", errors.ECODE_INVAL)
7380
      _CheckNodeOnline(self, self.op.snode)
7381
      _CheckNodeNotDrained(self, self.op.snode)
7382
      _CheckNodeVmCapable(self, self.op.snode)
7383
      self.secondaries.append(self.op.snode)
7384

    
7385
    nodenames = [pnode.name] + self.secondaries
7386

    
7387
    req_size = _ComputeDiskSize(self.op.disk_template,
7388
                                self.disks)
7389

    
7390
    # Check lv size requirements, if not adopting
7391
    if req_size is not None and not self.adopt_disks:
7392
      _CheckNodesFreeDisk(self, nodenames, req_size)
7393

    
7394
    if self.adopt_disks: # instead, we must check the adoption data
7395
      all_lvs = set([i["adopt"] for i in self.disks])
7396
      if len(all_lvs) != len(self.disks):
7397
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7398
                                   errors.ECODE_INVAL)
7399
      for lv_name in all_lvs:
7400
        try:
7401
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7402
        except errors.ReservationError:
7403
          raise errors.OpPrereqError("LV named %s used by another instance" %
7404
                                     lv_name, errors.ECODE_NOTUNIQUE)
7405

    
7406
      node_lvs = self.rpc.call_lv_list([pnode.name],
7407
                                       self.cfg.GetVGName())[pnode.name]
7408
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7409
      node_lvs = node_lvs.payload
7410
      delta = all_lvs.difference(node_lvs.keys())
7411
      if delta:
7412
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7413
                                   utils.CommaJoin(delta),
7414
                                   errors.ECODE_INVAL)
7415
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7416
      if online_lvs:
7417
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7418
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7419
                                   errors.ECODE_STATE)
7420
      # update the size of disk based on what is found
7421
      for dsk in self.disks:
7422
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
7423

    
7424
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7425

    
7426
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7427
    # check OS parameters (remotely)
7428
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7429

    
7430
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7431

    
7432
    # memory check on primary node
7433
    if self.op.start:
7434
      _CheckNodeFreeMemory(self, self.pnode.name,
7435
                           "creating instance %s" % self.op.instance_name,
7436
                           self.be_full[constants.BE_MEMORY],
7437
                           self.op.hypervisor)
7438

    
7439
    self.dry_run_result = list(nodenames)
7440

    
7441
  def Exec(self, feedback_fn):
7442
    """Create and add the instance to the cluster.
7443

7444
    """
7445
    instance = self.op.instance_name
7446
    pnode_name = self.pnode.name
7447

    
7448
    ht_kind = self.op.hypervisor
7449
    if ht_kind in constants.HTS_REQ_PORT:
7450
      network_port = self.cfg.AllocatePort()
7451
    else:
7452
      network_port = None
7453

    
7454
    if constants.ENABLE_FILE_STORAGE:
7455
      # this is needed because os.path.join does not accept None arguments
7456
      if self.op.file_storage_dir is None:
7457
        string_file_storage_dir = ""
7458
      else:
7459
        string_file_storage_dir = self.op.file_storage_dir
7460

    
7461
      # build the full file storage dir path
7462
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7463
                                        string_file_storage_dir, instance)
7464
    else:
7465
      file_storage_dir = ""
7466

    
7467
    disks = _GenerateDiskTemplate(self,
7468
                                  self.op.disk_template,
7469
                                  instance, pnode_name,
7470
                                  self.secondaries,
7471
                                  self.disks,
7472
                                  file_storage_dir,
7473
                                  self.op.file_driver,
7474
                                  0)
7475

    
7476
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7477
                            primary_node=pnode_name,
7478
                            nics=self.nics, disks=disks,
7479
                            disk_template=self.op.disk_template,
7480
                            admin_up=False,
7481
                            network_port=network_port,
7482
                            beparams=self.op.beparams,
7483
                            hvparams=self.op.hvparams,
7484
                            hypervisor=self.op.hypervisor,
7485
                            osparams=self.op.osparams,
7486
                            )
7487

    
7488
    if self.adopt_disks:
7489
      # rename LVs to the newly-generated names; we need to construct
7490
      # 'fake' LV disks with the old data, plus the new unique_id
7491
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7492
      rename_to = []
7493
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7494
        rename_to.append(t_dsk.logical_id)
7495
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7496
        self.cfg.SetDiskID(t_dsk, pnode_name)
7497
      result = self.rpc.call_blockdev_rename(pnode_name,
7498
                                             zip(tmp_disks, rename_to))
7499
      result.Raise("Failed to rename adoped LVs")
7500
    else:
7501
      feedback_fn("* creating instance disks...")
7502
      try:
7503
        _CreateDisks(self, iobj)
7504
      except errors.OpExecError:
7505
        self.LogWarning("Device creation failed, reverting...")
7506
        try:
7507
          _RemoveDisks(self, iobj)
7508
        finally:
7509
          self.cfg.ReleaseDRBDMinors(instance)
7510
          raise
7511

    
7512
      if self.cfg.GetClusterInfo().prealloc_wipe_disks:
7513
        feedback_fn("* wiping instance disks...")
7514
        try:
7515
          _WipeDisks(self, iobj)
7516
        except errors.OpExecError:
7517
          self.LogWarning("Device wiping failed, reverting...")
7518
          try:
7519
            _RemoveDisks(self, iobj)
7520
          finally:
7521
            self.cfg.ReleaseDRBDMinors(instance)
7522
            raise
7523

    
7524
    feedback_fn("adding instance %s to cluster config" % instance)
7525

    
7526
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7527

    
7528
    # Declare that we don't want to remove the instance lock anymore, as we've
7529
    # added the instance to the config
7530
    del self.remove_locks[locking.LEVEL_INSTANCE]
7531
    # Unlock all the nodes
7532
    if self.op.mode == constants.INSTANCE_IMPORT:
7533
      nodes_keep = [self.op.src_node]
7534
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7535
                       if node != self.op.src_node]
7536
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7537
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7538
    else:
7539
      self.context.glm.release(locking.LEVEL_NODE)
7540
      del self.acquired_locks[locking.LEVEL_NODE]
7541

    
7542
    if self.op.wait_for_sync:
7543
      disk_abort = not _WaitForSync(self, iobj)
7544
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7545
      # make sure the disks are not degraded (still sync-ing is ok)
7546
      time.sleep(15)
7547
      feedback_fn("* checking mirrors status")
7548
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7549
    else:
7550
      disk_abort = False
7551

    
7552
    if disk_abort:
7553
      _RemoveDisks(self, iobj)
7554
      self.cfg.RemoveInstance(iobj.name)
7555
      # Make sure the instance lock gets removed
7556
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7557
      raise errors.OpExecError("There are some degraded disks for"
7558
                               " this instance")
7559

    
7560
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7561
      if self.op.mode == constants.INSTANCE_CREATE:
7562
        if not self.op.no_install:
7563
          feedback_fn("* running the instance OS create scripts...")
7564
          # FIXME: pass debug option from opcode to backend
7565
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7566
                                                 self.op.debug_level)
7567
          result.Raise("Could not add os for instance %s"
7568
                       " on node %s" % (instance, pnode_name))
7569

    
7570
      elif self.op.mode == constants.INSTANCE_IMPORT:
7571
        feedback_fn("* running the instance OS import scripts...")
7572

    
7573
        transfers = []
7574

    
7575
        for idx, image in enumerate(self.src_images):
7576
          if not image:
7577
            continue
7578

    
7579
          # FIXME: pass debug option from opcode to backend
7580
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7581
                                             constants.IEIO_FILE, (image, ),
7582
                                             constants.IEIO_SCRIPT,
7583
                                             (iobj.disks[idx], idx),
7584
                                             None)
7585
          transfers.append(dt)
7586

    
7587
        import_result = \
7588
          masterd.instance.TransferInstanceData(self, feedback_fn,
7589
                                                self.op.src_node, pnode_name,
7590
                                                self.pnode.secondary_ip,
7591
                                                iobj, transfers)
7592
        if not compat.all(import_result):
7593
          self.LogWarning("Some disks for instance %s on node %s were not"
7594
                          " imported successfully" % (instance, pnode_name))
7595

    
7596
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7597
        feedback_fn("* preparing remote import...")
7598
        connect_timeout = constants.RIE_CONNECT_TIMEOUT
7599
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7600

    
7601
        disk_results = masterd.instance.RemoteImport(self, feedback_fn, iobj,
7602
                                                     self.source_x509_ca,
7603
                                                     self._cds, timeouts)
7604
        if not compat.all(disk_results):
7605
          # TODO: Should the instance still be started, even if some disks
7606
          # failed to import (valid for local imports, too)?
7607
          self.LogWarning("Some disks for instance %s on node %s were not"
7608
                          " imported successfully" % (instance, pnode_name))
7609

    
7610
        # Run rename script on newly imported instance
7611
        assert iobj.name == instance
7612
        feedback_fn("Running rename script for %s" % instance)
7613
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7614
                                                   self.source_instance_name,
7615
                                                   self.op.debug_level)
7616
        if result.fail_msg:
7617
          self.LogWarning("Failed to run rename script for %s on node"
7618
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7619

    
7620
      else:
7621
        # also checked in the prereq part
7622
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7623
                                     % self.op.mode)
7624

    
7625
    if self.op.start:
7626
      iobj.admin_up = True
7627
      self.cfg.Update(iobj, feedback_fn)
7628
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7629
      feedback_fn("* starting instance...")
7630
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7631
      result.Raise("Could not start instance")
7632

    
7633
    return list(iobj.all_nodes)
7634

    
7635

    
7636
class LUConnectConsole(NoHooksLU):
7637
  """Connect to an instance's console.
7638

7639
  This is somewhat special in that it returns the command line that
7640
  you need to run on the master node in order to connect to the
7641
  console.
7642

7643
  """
7644
  _OP_PARAMS = [
7645
    _PInstanceName
7646
    ]
7647
  REQ_BGL = False
7648

    
7649
  def ExpandNames(self):
7650
    self._ExpandAndLockInstance()
7651

    
7652
  def CheckPrereq(self):
7653
    """Check prerequisites.
7654

7655
    This checks that the instance is in the cluster.
7656

7657
    """
7658
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7659
    assert self.instance is not None, \
7660
      "Cannot retrieve locked instance %s" % self.op.instance_name
7661
    _CheckNodeOnline(self, self.instance.primary_node)
7662

    
7663
  def Exec(self, feedback_fn):
7664
    """Connect to the console of an instance
7665

7666
    """
7667
    instance = self.instance
7668
    node = instance.primary_node
7669

    
7670
    node_insts = self.rpc.call_instance_list([node],
7671
                                             [instance.hypervisor])[node]
7672
    node_insts.Raise("Can't get node information from %s" % node)
7673

    
7674
    if instance.name not in node_insts.payload:
7675
      if instance.admin_up:
7676
        state = "ERROR_down"
7677
      else:
7678
        state = "ADMIN_down"
7679
      raise errors.OpExecError("Instance %s is not running (state %s)" %
7680
                               (instance.name, state))
7681

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

    
7684
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
7685
    cluster = self.cfg.GetClusterInfo()
7686
    # beparams and hvparams are passed separately, to avoid editing the
7687
    # instance and then saving the defaults in the instance itself.
7688
    hvparams = cluster.FillHV(instance)
7689
    beparams = cluster.FillBE(instance)
7690
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
7691

    
7692
    # build ssh cmdline
7693
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
7694

    
7695

    
7696
class LUReplaceDisks(LogicalUnit):
7697
  """Replace the disks of an instance.
7698

7699
  """
7700
  HPATH = "mirrors-replace"
7701
  HTYPE = constants.HTYPE_INSTANCE
7702
  _OP_PARAMS = [
7703
    _PInstanceName,
7704
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES)),
7705
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt)),
7706
    ("remote_node", None, ht.TMaybeString),
7707
    ("iallocator", None, ht.TMaybeString),
7708
    ("early_release", False, ht.TBool),
7709
    ]
7710
  REQ_BGL = False
7711

    
7712
  def CheckArguments(self):
7713
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7714
                                  self.op.iallocator)
7715

    
7716
  def ExpandNames(self):
7717
    self._ExpandAndLockInstance()
7718

    
7719
    if self.op.iallocator is not None:
7720
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7721

    
7722
    elif self.op.remote_node is not None:
7723
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7724
      self.op.remote_node = remote_node
7725

    
7726
      # Warning: do not remove the locking of the new secondary here
7727
      # unless DRBD8.AddChildren is changed to work in parallel;
7728
      # currently it doesn't since parallel invocations of
7729
      # FindUnusedMinor will conflict
7730
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7731
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7732

    
7733
    else:
7734
      self.needed_locks[locking.LEVEL_NODE] = []
7735
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7736

    
7737
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7738
                                   self.op.iallocator, self.op.remote_node,
7739
                                   self.op.disks, False, self.op.early_release)
7740

    
7741
    self.tasklets = [self.replacer]
7742

    
7743
  def DeclareLocks(self, level):
7744
    # If we're not already locking all nodes in the set we have to declare the
7745
    # instance's primary/secondary nodes.
7746
    if (level == locking.LEVEL_NODE and
7747
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7748
      self._LockInstancesNodes()
7749

    
7750
  def BuildHooksEnv(self):
7751
    """Build hooks env.
7752

7753
    This runs on the master, the primary and all the secondaries.
7754

7755
    """
7756
    instance = self.replacer.instance
7757
    env = {
7758
      "MODE": self.op.mode,
7759
      "NEW_SECONDARY": self.op.remote_node,
7760
      "OLD_SECONDARY": instance.secondary_nodes[0],
7761
      }
7762
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7763
    nl = [
7764
      self.cfg.GetMasterNode(),
7765
      instance.primary_node,
7766
      ]
7767
    if self.op.remote_node is not None:
7768
      nl.append(self.op.remote_node)
7769
    return env, nl, nl
7770

    
7771

    
7772
class TLReplaceDisks(Tasklet):
7773
  """Replaces disks for an instance.
7774

7775
  Note: Locking is not within the scope of this class.
7776

7777
  """
7778
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7779
               disks, delay_iallocator, early_release):
7780
    """Initializes this class.
7781

7782
    """
7783
    Tasklet.__init__(self, lu)
7784

    
7785
    # Parameters
7786
    self.instance_name = instance_name
7787
    self.mode = mode
7788
    self.iallocator_name = iallocator_name
7789
    self.remote_node = remote_node
7790
    self.disks = disks
7791
    self.delay_iallocator = delay_iallocator
7792
    self.early_release = early_release
7793

    
7794
    # Runtime data
7795
    self.instance = None
7796
    self.new_node = None
7797
    self.target_node = None
7798
    self.other_node = None
7799
    self.remote_node_info = None
7800
    self.node_secondary_ip = None
7801

    
7802
  @staticmethod
7803
  def CheckArguments(mode, remote_node, iallocator):
7804
    """Helper function for users of this class.
7805

7806
    """
7807
    # check for valid parameter combination
7808
    if mode == constants.REPLACE_DISK_CHG:
7809
      if remote_node is None and iallocator is None:
7810
        raise errors.OpPrereqError("When changing the secondary either an"
7811
                                   " iallocator script must be used or the"
7812
                                   " new node given", errors.ECODE_INVAL)
7813

    
7814
      if remote_node is not None and iallocator is not None:
7815
        raise errors.OpPrereqError("Give either the iallocator or the new"
7816
                                   " secondary, not both", errors.ECODE_INVAL)
7817

    
7818
    elif remote_node is not None or iallocator is not None:
7819
      # Not replacing the secondary
7820
      raise errors.OpPrereqError("The iallocator and new node options can"
7821
                                 " only be used when changing the"
7822
                                 " secondary node", errors.ECODE_INVAL)
7823

    
7824
  @staticmethod
7825
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7826
    """Compute a new secondary node using an IAllocator.
7827

7828
    """
7829
    ial = IAllocator(lu.cfg, lu.rpc,
7830
                     mode=constants.IALLOCATOR_MODE_RELOC,
7831
                     name=instance_name,
7832
                     relocate_from=relocate_from)
7833

    
7834
    ial.Run(iallocator_name)
7835

    
7836
    if not ial.success:
7837
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7838
                                 " %s" % (iallocator_name, ial.info),
7839
                                 errors.ECODE_NORES)
7840

    
7841
    if len(ial.result) != ial.required_nodes:
7842
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7843
                                 " of nodes (%s), required %s" %
7844
                                 (iallocator_name,
7845
                                  len(ial.result), ial.required_nodes),
7846
                                 errors.ECODE_FAULT)
7847

    
7848
    remote_node_name = ial.result[0]
7849

    
7850
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7851
               instance_name, remote_node_name)
7852

    
7853
    return remote_node_name
7854

    
7855
  def _FindFaultyDisks(self, node_name):
7856
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7857
                                    node_name, True)
7858

    
7859
  def CheckPrereq(self):
7860
    """Check prerequisites.
7861

7862
    This checks that the instance is in the cluster.
7863

7864
    """
7865
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7866
    assert instance is not None, \
7867
      "Cannot retrieve locked instance %s" % self.instance_name
7868

    
7869
    if instance.disk_template != constants.DT_DRBD8:
7870
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7871
                                 " instances", errors.ECODE_INVAL)
7872

    
7873
    if len(instance.secondary_nodes) != 1:
7874
      raise errors.OpPrereqError("The instance has a strange layout,"
7875
                                 " expected one secondary but found %d" %
7876
                                 len(instance.secondary_nodes),
7877
                                 errors.ECODE_FAULT)
7878

    
7879
    if not self.delay_iallocator:
7880
      self._CheckPrereq2()
7881

    
7882
  def _CheckPrereq2(self):
7883
    """Check prerequisites, second part.
7884

7885
    This function should always be part of CheckPrereq. It was separated and is
7886
    now called from Exec because during node evacuation iallocator was only
7887
    called with an unmodified cluster model, not taking planned changes into
7888
    account.
7889

7890
    """
7891
    instance = self.instance
7892
    secondary_node = instance.secondary_nodes[0]
7893

    
7894
    if self.iallocator_name is None:
7895
      remote_node = self.remote_node
7896
    else:
7897
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
7898
                                       instance.name, instance.secondary_nodes)
7899

    
7900
    if remote_node is not None:
7901
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
7902
      assert self.remote_node_info is not None, \
7903
        "Cannot retrieve locked node %s" % remote_node
7904
    else:
7905
      self.remote_node_info = None
7906

    
7907
    if remote_node == self.instance.primary_node:
7908
      raise errors.OpPrereqError("The specified node is the primary node of"
7909
                                 " the instance.", errors.ECODE_INVAL)
7910

    
7911
    if remote_node == secondary_node:
7912
      raise errors.OpPrereqError("The specified node is already the"
7913
                                 " secondary node of the instance.",
7914
                                 errors.ECODE_INVAL)
7915

    
7916
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
7917
                                    constants.REPLACE_DISK_CHG):
7918
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
7919
                                 errors.ECODE_INVAL)
7920

    
7921
    if self.mode == constants.REPLACE_DISK_AUTO:
7922
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
7923
      faulty_secondary = self._FindFaultyDisks(secondary_node)
7924

    
7925
      if faulty_primary and faulty_secondary:
7926
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
7927
                                   " one node and can not be repaired"
7928
                                   " automatically" % self.instance_name,
7929
                                   errors.ECODE_STATE)
7930

    
7931
      if faulty_primary:
7932
        self.disks = faulty_primary
7933
        self.target_node = instance.primary_node
7934
        self.other_node = secondary_node
7935
        check_nodes = [self.target_node, self.other_node]
7936
      elif faulty_secondary:
7937
        self.disks = faulty_secondary
7938
        self.target_node = secondary_node
7939
        self.other_node = instance.primary_node
7940
        check_nodes = [self.target_node, self.other_node]
7941
      else:
7942
        self.disks = []
7943
        check_nodes = []
7944

    
7945
    else:
7946
      # Non-automatic modes
7947
      if self.mode == constants.REPLACE_DISK_PRI:
7948
        self.target_node = instance.primary_node
7949
        self.other_node = secondary_node
7950
        check_nodes = [self.target_node, self.other_node]
7951

    
7952
      elif self.mode == constants.REPLACE_DISK_SEC:
7953
        self.target_node = secondary_node
7954
        self.other_node = instance.primary_node
7955
        check_nodes = [self.target_node, self.other_node]
7956

    
7957
      elif self.mode == constants.REPLACE_DISK_CHG:
7958
        self.new_node = remote_node
7959
        self.other_node = instance.primary_node
7960
        self.target_node = secondary_node
7961
        check_nodes = [self.new_node, self.other_node]
7962

    
7963
        _CheckNodeNotDrained(self.lu, remote_node)
7964
        _CheckNodeVmCapable(self.lu, remote_node)
7965

    
7966
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
7967
        assert old_node_info is not None
7968
        if old_node_info.offline and not self.early_release:
7969
          # doesn't make sense to delay the release
7970
          self.early_release = True
7971
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
7972
                          " early-release mode", secondary_node)
7973

    
7974
      else:
7975
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
7976
                                     self.mode)
7977

    
7978
      # If not specified all disks should be replaced
7979
      if not self.disks:
7980
        self.disks = range(len(self.instance.disks))
7981

    
7982
    for node in check_nodes:
7983
      _CheckNodeOnline(self.lu, node)
7984

    
7985
    # Check whether disks are valid
7986
    for disk_idx in self.disks:
7987
      instance.FindDisk(disk_idx)
7988

    
7989
    # Get secondary node IP addresses
7990
    node_2nd_ip = {}
7991

    
7992
    for node_name in [self.target_node, self.other_node, self.new_node]:
7993
      if node_name is not None:
7994
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
7995

    
7996
    self.node_secondary_ip = node_2nd_ip
7997

    
7998
  def Exec(self, feedback_fn):
7999
    """Execute disk replacement.
8000

8001
    This dispatches the disk replacement to the appropriate handler.
8002

8003
    """
8004
    if self.delay_iallocator:
8005
      self._CheckPrereq2()
8006

    
8007
    if not self.disks:
8008
      feedback_fn("No disks need replacement")
8009
      return
8010

    
8011
    feedback_fn("Replacing disk(s) %s for %s" %
8012
                (utils.CommaJoin(self.disks), self.instance.name))
8013

    
8014
    activate_disks = (not self.instance.admin_up)
8015

    
8016
    # Activate the instance disks if we're replacing them on a down instance
8017
    if activate_disks:
8018
      _StartInstanceDisks(self.lu, self.instance, True)
8019

    
8020
    try:
8021
      # Should we replace the secondary node?
8022
      if self.new_node is not None:
8023
        fn = self._ExecDrbd8Secondary
8024
      else:
8025
        fn = self._ExecDrbd8DiskOnly
8026

    
8027
      return fn(feedback_fn)
8028

    
8029
    finally:
8030
      # Deactivate the instance disks if we're replacing them on a
8031
      # down instance
8032
      if activate_disks:
8033
        _SafeShutdownInstanceDisks(self.lu, self.instance)
8034

    
8035
  def _CheckVolumeGroup(self, nodes):
8036
    self.lu.LogInfo("Checking volume groups")
8037

    
8038
    vgname = self.cfg.GetVGName()
8039

    
8040
    # Make sure volume group exists on all involved nodes
8041
    results = self.rpc.call_vg_list(nodes)
8042
    if not results:
8043
      raise errors.OpExecError("Can't list volume groups on the nodes")
8044

    
8045
    for node in nodes:
8046
      res = results[node]
8047
      res.Raise("Error checking node %s" % node)
8048
      if vgname not in res.payload:
8049
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
8050
                                 (vgname, node))
8051

    
8052
  def _CheckDisksExistence(self, nodes):
8053
    # Check disk existence
8054
    for idx, dev in enumerate(self.instance.disks):
8055
      if idx not in self.disks:
8056
        continue
8057

    
8058
      for node in nodes:
8059
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
8060
        self.cfg.SetDiskID(dev, node)
8061

    
8062
        result = self.rpc.call_blockdev_find(node, dev)
8063

    
8064
        msg = result.fail_msg
8065
        if msg or not result.payload:
8066
          if not msg:
8067
            msg = "disk not found"
8068
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
8069
                                   (idx, node, msg))
8070

    
8071
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
8072
    for idx, dev in enumerate(self.instance.disks):
8073
      if idx not in self.disks:
8074
        continue
8075

    
8076
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
8077
                      (idx, node_name))
8078

    
8079
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
8080
                                   ldisk=ldisk):
8081
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
8082
                                 " replace disks for instance %s" %
8083
                                 (node_name, self.instance.name))
8084

    
8085
  def _CreateNewStorage(self, node_name):
8086
    vgname = self.cfg.GetVGName()
8087
    iv_names = {}
8088

    
8089
    for idx, dev in enumerate(self.instance.disks):
8090
      if idx not in self.disks:
8091
        continue
8092

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

    
8095
      self.cfg.SetDiskID(dev, node_name)
8096

    
8097
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
8098
      names = _GenerateUniqueNames(self.lu, lv_names)
8099

    
8100
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
8101
                             logical_id=(vgname, names[0]))
8102
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
8103
                             logical_id=(vgname, names[1]))
8104

    
8105
      new_lvs = [lv_data, lv_meta]
8106
      old_lvs = dev.children
8107
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
8108

    
8109
      # we pass force_create=True to force the LVM creation
8110
      for new_lv in new_lvs:
8111
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
8112
                        _GetInstanceInfoText(self.instance), False)
8113

    
8114
    return iv_names
8115

    
8116
  def _CheckDevices(self, node_name, iv_names):
8117
    for name, (dev, _, _) in iv_names.iteritems():
8118
      self.cfg.SetDiskID(dev, node_name)
8119

    
8120
      result = self.rpc.call_blockdev_find(node_name, dev)
8121

    
8122
      msg = result.fail_msg
8123
      if msg or not result.payload:
8124
        if not msg:
8125
          msg = "disk not found"
8126
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
8127
                                 (name, msg))
8128

    
8129
      if result.payload.is_degraded:
8130
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
8131

    
8132
  def _RemoveOldStorage(self, node_name, iv_names):
8133
    for name, (_, old_lvs, _) in iv_names.iteritems():
8134
      self.lu.LogInfo("Remove logical volumes for %s" % name)
8135

    
8136
      for lv in old_lvs:
8137
        self.cfg.SetDiskID(lv, node_name)
8138

    
8139
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
8140
        if msg:
8141
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
8142
                             hint="remove unused LVs manually")
8143

    
8144
  def _ReleaseNodeLock(self, node_name):
8145
    """Releases the lock for a given node."""
8146
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
8147

    
8148
  def _ExecDrbd8DiskOnly(self, feedback_fn):
8149
    """Replace a disk on the primary or secondary for DRBD 8.
8150

8151
    The algorithm for replace is quite complicated:
8152

8153
      1. for each disk to be replaced:
8154

8155
        1. create new LVs on the target node with unique names
8156
        1. detach old LVs from the drbd device
8157
        1. rename old LVs to name_replaced.<time_t>
8158
        1. rename new LVs to old LVs
8159
        1. attach the new LVs (with the old names now) to the drbd device
8160

8161
      1. wait for sync across all devices
8162

8163
      1. for each modified disk:
8164

8165
        1. remove old LVs (which have the name name_replaces.<time_t>)
8166

8167
    Failures are not very well handled.
8168

8169
    """
8170
    steps_total = 6
8171

    
8172
    # Step: check device activation
8173
    self.lu.LogStep(1, steps_total, "Check device existence")
8174
    self._CheckDisksExistence([self.other_node, self.target_node])
8175
    self._CheckVolumeGroup([self.target_node, self.other_node])
8176

    
8177
    # Step: check other node consistency
8178
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8179
    self._CheckDisksConsistency(self.other_node,
8180
                                self.other_node == self.instance.primary_node,
8181
                                False)
8182

    
8183
    # Step: create new storage
8184
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8185
    iv_names = self._CreateNewStorage(self.target_node)
8186

    
8187
    # Step: for each lv, detach+rename*2+attach
8188
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8189
    for dev, old_lvs, new_lvs in iv_names.itervalues():
8190
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
8191

    
8192
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
8193
                                                     old_lvs)
8194
      result.Raise("Can't detach drbd from local storage on node"
8195
                   " %s for device %s" % (self.target_node, dev.iv_name))
8196
      #dev.children = []
8197
      #cfg.Update(instance)
8198

    
8199
      # ok, we created the new LVs, so now we know we have the needed
8200
      # storage; as such, we proceed on the target node to rename
8201
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
8202
      # using the assumption that logical_id == physical_id (which in
8203
      # turn is the unique_id on that node)
8204

    
8205
      # FIXME(iustin): use a better name for the replaced LVs
8206
      temp_suffix = int(time.time())
8207
      ren_fn = lambda d, suff: (d.physical_id[0],
8208
                                d.physical_id[1] + "_replaced-%s" % suff)
8209

    
8210
      # Build the rename list based on what LVs exist on the node
8211
      rename_old_to_new = []
8212
      for to_ren in old_lvs:
8213
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
8214
        if not result.fail_msg and result.payload:
8215
          # device exists
8216
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
8217

    
8218
      self.lu.LogInfo("Renaming the old LVs on the target node")
8219
      result = self.rpc.call_blockdev_rename(self.target_node,
8220
                                             rename_old_to_new)
8221
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
8222

    
8223
      # Now we rename the new LVs to the old LVs
8224
      self.lu.LogInfo("Renaming the new LVs on the target node")
8225
      rename_new_to_old = [(new, old.physical_id)
8226
                           for old, new in zip(old_lvs, new_lvs)]
8227
      result = self.rpc.call_blockdev_rename(self.target_node,
8228
                                             rename_new_to_old)
8229
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
8230

    
8231
      for old, new in zip(old_lvs, new_lvs):
8232
        new.logical_id = old.logical_id
8233
        self.cfg.SetDiskID(new, self.target_node)
8234

    
8235
      for disk in old_lvs:
8236
        disk.logical_id = ren_fn(disk, temp_suffix)
8237
        self.cfg.SetDiskID(disk, self.target_node)
8238

    
8239
      # Now that the new lvs have the old name, we can add them to the device
8240
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
8241
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
8242
                                                  new_lvs)
8243
      msg = result.fail_msg
8244
      if msg:
8245
        for new_lv in new_lvs:
8246
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
8247
                                               new_lv).fail_msg
8248
          if msg2:
8249
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
8250
                               hint=("cleanup manually the unused logical"
8251
                                     "volumes"))
8252
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8253

    
8254
      dev.children = new_lvs
8255

    
8256
      self.cfg.Update(self.instance, feedback_fn)
8257

    
8258
    cstep = 5
8259
    if self.early_release:
8260
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8261
      cstep += 1
8262
      self._RemoveOldStorage(self.target_node, iv_names)
8263
      # WARNING: we release both node locks here, do not do other RPCs
8264
      # than WaitForSync to the primary node
8265
      self._ReleaseNodeLock([self.target_node, self.other_node])
8266

    
8267
    # Wait for sync
8268
    # This can fail as the old devices are degraded and _WaitForSync
8269
    # does a combined result over all disks, so we don't check its return value
8270
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8271
    cstep += 1
8272
    _WaitForSync(self.lu, self.instance)
8273

    
8274
    # Check all devices manually
8275
    self._CheckDevices(self.instance.primary_node, iv_names)
8276

    
8277
    # Step: remove old storage
8278
    if not self.early_release:
8279
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8280
      cstep += 1
8281
      self._RemoveOldStorage(self.target_node, iv_names)
8282

    
8283
  def _ExecDrbd8Secondary(self, feedback_fn):
8284
    """Replace the secondary node for DRBD 8.
8285

8286
    The algorithm for replace is quite complicated:
8287
      - for all disks of the instance:
8288
        - create new LVs on the new node with same names
8289
        - shutdown the drbd device on the old secondary
8290
        - disconnect the drbd network on the primary
8291
        - create the drbd device on the new secondary
8292
        - network attach the drbd on the primary, using an artifice:
8293
          the drbd code for Attach() will connect to the network if it
8294
          finds a device which is connected to the good local disks but
8295
          not network enabled
8296
      - wait for sync across all devices
8297
      - remove all disks from the old secondary
8298

8299
    Failures are not very well handled.
8300

8301
    """
8302
    steps_total = 6
8303

    
8304
    # Step: check device activation
8305
    self.lu.LogStep(1, steps_total, "Check device existence")
8306
    self._CheckDisksExistence([self.instance.primary_node])
8307
    self._CheckVolumeGroup([self.instance.primary_node])
8308

    
8309
    # Step: check other node consistency
8310
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8311
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8312

    
8313
    # Step: create new storage
8314
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8315
    for idx, dev in enumerate(self.instance.disks):
8316
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8317
                      (self.new_node, idx))
8318
      # we pass force_create=True to force LVM creation
8319
      for new_lv in dev.children:
8320
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8321
                        _GetInstanceInfoText(self.instance), False)
8322

    
8323
    # Step 4: dbrd minors and drbd setups changes
8324
    # after this, we must manually remove the drbd minors on both the
8325
    # error and the success paths
8326
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8327
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8328
                                         for dev in self.instance.disks],
8329
                                        self.instance.name)
8330
    logging.debug("Allocated minors %r", minors)
8331

    
8332
    iv_names = {}
8333
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8334
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8335
                      (self.new_node, idx))
8336
      # create new devices on new_node; note that we create two IDs:
8337
      # one without port, so the drbd will be activated without
8338
      # networking information on the new node at this stage, and one
8339
      # with network, for the latter activation in step 4
8340
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8341
      if self.instance.primary_node == o_node1:
8342
        p_minor = o_minor1
8343
      else:
8344
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8345
        p_minor = o_minor2
8346

    
8347
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8348
                      p_minor, new_minor, o_secret)
8349
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8350
                    p_minor, new_minor, o_secret)
8351

    
8352
      iv_names[idx] = (dev, dev.children, new_net_id)
8353
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8354
                    new_net_id)
8355
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8356
                              logical_id=new_alone_id,
8357
                              children=dev.children,
8358
                              size=dev.size)
8359
      try:
8360
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8361
                              _GetInstanceInfoText(self.instance), False)
8362
      except errors.GenericError:
8363
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8364
        raise
8365

    
8366
    # We have new devices, shutdown the drbd on the old secondary
8367
    for idx, dev in enumerate(self.instance.disks):
8368
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8369
      self.cfg.SetDiskID(dev, self.target_node)
8370
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8371
      if msg:
8372
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8373
                           "node: %s" % (idx, msg),
8374
                           hint=("Please cleanup this device manually as"
8375
                                 " soon as possible"))
8376

    
8377
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8378
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8379
                                               self.node_secondary_ip,
8380
                                               self.instance.disks)\
8381
                                              [self.instance.primary_node]
8382

    
8383
    msg = result.fail_msg
8384
    if msg:
8385
      # detaches didn't succeed (unlikely)
8386
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8387
      raise errors.OpExecError("Can't detach the disks from the network on"
8388
                               " old node: %s" % (msg,))
8389

    
8390
    # if we managed to detach at least one, we update all the disks of
8391
    # the instance to point to the new secondary
8392
    self.lu.LogInfo("Updating instance configuration")
8393
    for dev, _, new_logical_id in iv_names.itervalues():
8394
      dev.logical_id = new_logical_id
8395
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8396

    
8397
    self.cfg.Update(self.instance, feedback_fn)
8398

    
8399
    # and now perform the drbd attach
8400
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8401
                    " (standalone => connected)")
8402
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8403
                                            self.new_node],
8404
                                           self.node_secondary_ip,
8405
                                           self.instance.disks,
8406
                                           self.instance.name,
8407
                                           False)
8408
    for to_node, to_result in result.items():
8409
      msg = to_result.fail_msg
8410
      if msg:
8411
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8412
                           to_node, msg,
8413
                           hint=("please do a gnt-instance info to see the"
8414
                                 " status of disks"))
8415
    cstep = 5
8416
    if self.early_release:
8417
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8418
      cstep += 1
8419
      self._RemoveOldStorage(self.target_node, iv_names)
8420
      # WARNING: we release all node locks here, do not do other RPCs
8421
      # than WaitForSync to the primary node
8422
      self._ReleaseNodeLock([self.instance.primary_node,
8423
                             self.target_node,
8424
                             self.new_node])
8425

    
8426
    # Wait for sync
8427
    # This can fail as the old devices are degraded and _WaitForSync
8428
    # does a combined result over all disks, so we don't check its return value
8429
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8430
    cstep += 1
8431
    _WaitForSync(self.lu, self.instance)
8432

    
8433
    # Check all devices manually
8434
    self._CheckDevices(self.instance.primary_node, iv_names)
8435

    
8436
    # Step: remove old storage
8437
    if not self.early_release:
8438
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8439
      self._RemoveOldStorage(self.target_node, iv_names)
8440

    
8441

    
8442
class LURepairNodeStorage(NoHooksLU):
8443
  """Repairs the volume group on a node.
8444

8445
  """
8446
  _OP_PARAMS = [
8447
    _PNodeName,
8448
    ("storage_type", ht.NoDefault, _CheckStorageType),
8449
    ("name", ht.NoDefault, ht.TNonEmptyString),
8450
    ("ignore_consistency", False, ht.TBool),
8451
    ]
8452
  REQ_BGL = False
8453

    
8454
  def CheckArguments(self):
8455
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8456

    
8457
    storage_type = self.op.storage_type
8458

    
8459
    if (constants.SO_FIX_CONSISTENCY not in
8460
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8461
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8462
                                 " repaired" % storage_type,
8463
                                 errors.ECODE_INVAL)
8464

    
8465
  def ExpandNames(self):
8466
    self.needed_locks = {
8467
      locking.LEVEL_NODE: [self.op.node_name],
8468
      }
8469

    
8470
  def _CheckFaultyDisks(self, instance, node_name):
8471
    """Ensure faulty disks abort the opcode or at least warn."""
8472
    try:
8473
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8474
                                  node_name, True):
8475
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8476
                                   " node '%s'" % (instance.name, node_name),
8477
                                   errors.ECODE_STATE)
8478
    except errors.OpPrereqError, err:
8479
      if self.op.ignore_consistency:
8480
        self.proc.LogWarning(str(err.args[0]))
8481
      else:
8482
        raise
8483

    
8484
  def CheckPrereq(self):
8485
    """Check prerequisites.
8486

8487
    """
8488
    # Check whether any instance on this node has faulty disks
8489
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8490
      if not inst.admin_up:
8491
        continue
8492
      check_nodes = set(inst.all_nodes)
8493
      check_nodes.discard(self.op.node_name)
8494
      for inst_node_name in check_nodes:
8495
        self._CheckFaultyDisks(inst, inst_node_name)
8496

    
8497
  def Exec(self, feedback_fn):
8498
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8499
                (self.op.name, self.op.node_name))
8500

    
8501
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8502
    result = self.rpc.call_storage_execute(self.op.node_name,
8503
                                           self.op.storage_type, st_args,
8504
                                           self.op.name,
8505
                                           constants.SO_FIX_CONSISTENCY)
8506
    result.Raise("Failed to repair storage unit '%s' on %s" %
8507
                 (self.op.name, self.op.node_name))
8508

    
8509

    
8510
class LUNodeEvacuationStrategy(NoHooksLU):
8511
  """Computes the node evacuation strategy.
8512

8513
  """
8514
  _OP_PARAMS = [
8515
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
8516
    ("remote_node", None, ht.TMaybeString),
8517
    ("iallocator", None, ht.TMaybeString),
8518
    ]
8519
  REQ_BGL = False
8520

    
8521
  def CheckArguments(self):
8522
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8523

    
8524
  def ExpandNames(self):
8525
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8526
    self.needed_locks = locks = {}
8527
    if self.op.remote_node is None:
8528
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8529
    else:
8530
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8531
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8532

    
8533
  def Exec(self, feedback_fn):
8534
    if self.op.remote_node is not None:
8535
      instances = []
8536
      for node in self.op.nodes:
8537
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8538
      result = []
8539
      for i in instances:
8540
        if i.primary_node == self.op.remote_node:
8541
          raise errors.OpPrereqError("Node %s is the primary node of"
8542
                                     " instance %s, cannot use it as"
8543
                                     " secondary" %
8544
                                     (self.op.remote_node, i.name),
8545
                                     errors.ECODE_INVAL)
8546
        result.append([i.name, self.op.remote_node])
8547
    else:
8548
      ial = IAllocator(self.cfg, self.rpc,
8549
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8550
                       evac_nodes=self.op.nodes)
8551
      ial.Run(self.op.iallocator, validate=True)
8552
      if not ial.success:
8553
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8554
                                 errors.ECODE_NORES)
8555
      result = ial.result
8556
    return result
8557

    
8558

    
8559
class LUGrowDisk(LogicalUnit):
8560
  """Grow a disk of an instance.
8561

8562
  """
8563
  HPATH = "disk-grow"
8564
  HTYPE = constants.HTYPE_INSTANCE
8565
  _OP_PARAMS = [
8566
    _PInstanceName,
8567
    ("disk", ht.NoDefault, ht.TInt),
8568
    ("amount", ht.NoDefault, ht.TInt),
8569
    ("wait_for_sync", True, ht.TBool),
8570
    ]
8571
  REQ_BGL = False
8572

    
8573
  def ExpandNames(self):
8574
    self._ExpandAndLockInstance()
8575
    self.needed_locks[locking.LEVEL_NODE] = []
8576
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8577

    
8578
  def DeclareLocks(self, level):
8579
    if level == locking.LEVEL_NODE:
8580
      self._LockInstancesNodes()
8581

    
8582
  def BuildHooksEnv(self):
8583
    """Build hooks env.
8584

8585
    This runs on the master, the primary and all the secondaries.
8586

8587
    """
8588
    env = {
8589
      "DISK": self.op.disk,
8590
      "AMOUNT": self.op.amount,
8591
      }
8592
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8593
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8594
    return env, nl, nl
8595

    
8596
  def CheckPrereq(self):
8597
    """Check prerequisites.
8598

8599
    This checks that the instance is in the cluster.
8600

8601
    """
8602
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8603
    assert instance is not None, \
8604
      "Cannot retrieve locked instance %s" % self.op.instance_name
8605
    nodenames = list(instance.all_nodes)
8606
    for node in nodenames:
8607
      _CheckNodeOnline(self, node)
8608

    
8609
    self.instance = instance
8610

    
8611
    if instance.disk_template not in constants.DTS_GROWABLE:
8612
      raise errors.OpPrereqError("Instance's disk layout does not support"
8613
                                 " growing.", errors.ECODE_INVAL)
8614

    
8615
    self.disk = instance.FindDisk(self.op.disk)
8616

    
8617
    if instance.disk_template != constants.DT_FILE:
8618
      # TODO: check the free disk space for file, when that feature will be
8619
      # supported
8620
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
8621

    
8622
  def Exec(self, feedback_fn):
8623
    """Execute disk grow.
8624

8625
    """
8626
    instance = self.instance
8627
    disk = self.disk
8628

    
8629
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8630
    if not disks_ok:
8631
      raise errors.OpExecError("Cannot activate block device to grow")
8632

    
8633
    for node in instance.all_nodes:
8634
      self.cfg.SetDiskID(disk, node)
8635
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8636
      result.Raise("Grow request failed to node %s" % node)
8637

    
8638
      # TODO: Rewrite code to work properly
8639
      # DRBD goes into sync mode for a short amount of time after executing the
8640
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8641
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8642
      # time is a work-around.
8643
      time.sleep(5)
8644

    
8645
    disk.RecordGrow(self.op.amount)
8646
    self.cfg.Update(instance, feedback_fn)
8647
    if self.op.wait_for_sync:
8648
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8649
      if disk_abort:
8650
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8651
                             " status.\nPlease check the instance.")
8652
      if not instance.admin_up:
8653
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8654
    elif not instance.admin_up:
8655
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8656
                           " not supposed to be running because no wait for"
8657
                           " sync mode was requested.")
8658

    
8659

    
8660
class LUQueryInstanceData(NoHooksLU):
8661
  """Query runtime instance data.
8662

8663
  """
8664
  _OP_PARAMS = [
8665
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
8666
    ("static", False, ht.TBool),
8667
    ]
8668
  REQ_BGL = False
8669

    
8670
  def ExpandNames(self):
8671
    self.needed_locks = {}
8672
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8673

    
8674
    if self.op.instances:
8675
      self.wanted_names = []
8676
      for name in self.op.instances:
8677
        full_name = _ExpandInstanceName(self.cfg, name)
8678
        self.wanted_names.append(full_name)
8679
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8680
    else:
8681
      self.wanted_names = None
8682
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8683

    
8684
    self.needed_locks[locking.LEVEL_NODE] = []
8685
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8686

    
8687
  def DeclareLocks(self, level):
8688
    if level == locking.LEVEL_NODE:
8689
      self._LockInstancesNodes()
8690

    
8691
  def CheckPrereq(self):
8692
    """Check prerequisites.
8693

8694
    This only checks the optional instance list against the existing names.
8695

8696
    """
8697
    if self.wanted_names is None:
8698
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8699

    
8700
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8701
                             in self.wanted_names]
8702

    
8703
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8704
    """Returns the status of a block device
8705

8706
    """
8707
    if self.op.static or not node:
8708
      return None
8709

    
8710
    self.cfg.SetDiskID(dev, node)
8711

    
8712
    result = self.rpc.call_blockdev_find(node, dev)
8713
    if result.offline:
8714
      return None
8715

    
8716
    result.Raise("Can't compute disk status for %s" % instance_name)
8717

    
8718
    status = result.payload
8719
    if status is None:
8720
      return None
8721

    
8722
    return (status.dev_path, status.major, status.minor,
8723
            status.sync_percent, status.estimated_time,
8724
            status.is_degraded, status.ldisk_status)
8725

    
8726
  def _ComputeDiskStatus(self, instance, snode, dev):
8727
    """Compute block device status.
8728

8729
    """
8730
    if dev.dev_type in constants.LDS_DRBD:
8731
      # we change the snode then (otherwise we use the one passed in)
8732
      if dev.logical_id[0] == instance.primary_node:
8733
        snode = dev.logical_id[1]
8734
      else:
8735
        snode = dev.logical_id[0]
8736

    
8737
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8738
                                              instance.name, dev)
8739
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8740

    
8741
    if dev.children:
8742
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8743
                      for child in dev.children]
8744
    else:
8745
      dev_children = []
8746

    
8747
    data = {
8748
      "iv_name": dev.iv_name,
8749
      "dev_type": dev.dev_type,
8750
      "logical_id": dev.logical_id,
8751
      "physical_id": dev.physical_id,
8752
      "pstatus": dev_pstatus,
8753
      "sstatus": dev_sstatus,
8754
      "children": dev_children,
8755
      "mode": dev.mode,
8756
      "size": dev.size,
8757
      }
8758

    
8759
    return data
8760

    
8761
  def Exec(self, feedback_fn):
8762
    """Gather and return data"""
8763
    result = {}
8764

    
8765
    cluster = self.cfg.GetClusterInfo()
8766

    
8767
    for instance in self.wanted_instances:
8768
      if not self.op.static:
8769
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8770
                                                  instance.name,
8771
                                                  instance.hypervisor)
8772
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8773
        remote_info = remote_info.payload
8774
        if remote_info and "state" in remote_info:
8775
          remote_state = "up"
8776
        else:
8777
          remote_state = "down"
8778
      else:
8779
        remote_state = None
8780
      if instance.admin_up:
8781
        config_state = "up"
8782
      else:
8783
        config_state = "down"
8784

    
8785
      disks = [self._ComputeDiskStatus(instance, None, device)
8786
               for device in instance.disks]
8787

    
8788
      idict = {
8789
        "name": instance.name,
8790
        "config_state": config_state,
8791
        "run_state": remote_state,
8792
        "pnode": instance.primary_node,
8793
        "snodes": instance.secondary_nodes,
8794
        "os": instance.os,
8795
        # this happens to be the same format used for hooks
8796
        "nics": _NICListToTuple(self, instance.nics),
8797
        "disk_template": instance.disk_template,
8798
        "disks": disks,
8799
        "hypervisor": instance.hypervisor,
8800
        "network_port": instance.network_port,
8801
        "hv_instance": instance.hvparams,
8802
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8803
        "be_instance": instance.beparams,
8804
        "be_actual": cluster.FillBE(instance),
8805
        "os_instance": instance.osparams,
8806
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8807
        "serial_no": instance.serial_no,
8808
        "mtime": instance.mtime,
8809
        "ctime": instance.ctime,
8810
        "uuid": instance.uuid,
8811
        }
8812

    
8813
      result[instance.name] = idict
8814

    
8815
    return result
8816

    
8817

    
8818
class LUSetInstanceParams(LogicalUnit):
8819
  """Modifies an instances's parameters.
8820

8821
  """
8822
  HPATH = "instance-modify"
8823
  HTYPE = constants.HTYPE_INSTANCE
8824
  _OP_PARAMS = [
8825
    _PInstanceName,
8826
    ("nics", ht.EmptyList, ht.TList),
8827
    ("disks", ht.EmptyList, ht.TList),
8828
    ("beparams", ht.EmptyDict, ht.TDict),
8829
    ("hvparams", ht.EmptyDict, ht.TDict),
8830
    ("disk_template", None, ht.TMaybeString),
8831
    ("remote_node", None, ht.TMaybeString),
8832
    ("os_name", None, ht.TMaybeString),
8833
    ("force_variant", False, ht.TBool),
8834
    ("osparams", None, ht.TOr(ht.TDict, ht.TNone)),
8835
    _PForce,
8836
    ]
8837
  REQ_BGL = False
8838

    
8839
  def CheckArguments(self):
8840
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8841
            self.op.hvparams or self.op.beparams or self.op.os_name):
8842
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8843

    
8844
    if self.op.hvparams:
8845
      _CheckGlobalHvParams(self.op.hvparams)
8846

    
8847
    # Disk validation
8848
    disk_addremove = 0
8849
    for disk_op, disk_dict in self.op.disks:
8850
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8851
      if disk_op == constants.DDM_REMOVE:
8852
        disk_addremove += 1
8853
        continue
8854
      elif disk_op == constants.DDM_ADD:
8855
        disk_addremove += 1
8856
      else:
8857
        if not isinstance(disk_op, int):
8858
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8859
        if not isinstance(disk_dict, dict):
8860
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8861
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8862

    
8863
      if disk_op == constants.DDM_ADD:
8864
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8865
        if mode not in constants.DISK_ACCESS_SET:
8866
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8867
                                     errors.ECODE_INVAL)
8868
        size = disk_dict.get('size', None)
8869
        if size is None:
8870
          raise errors.OpPrereqError("Required disk parameter size missing",
8871
                                     errors.ECODE_INVAL)
8872
        try:
8873
          size = int(size)
8874
        except (TypeError, ValueError), err:
8875
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8876
                                     str(err), errors.ECODE_INVAL)
8877
        disk_dict['size'] = size
8878
      else:
8879
        # modification of disk
8880
        if 'size' in disk_dict:
8881
          raise errors.OpPrereqError("Disk size change not possible, use"
8882
                                     " grow-disk", errors.ECODE_INVAL)
8883

    
8884
    if disk_addremove > 1:
8885
      raise errors.OpPrereqError("Only one disk add or remove operation"
8886
                                 " supported at a time", errors.ECODE_INVAL)
8887

    
8888
    if self.op.disks and self.op.disk_template is not None:
8889
      raise errors.OpPrereqError("Disk template conversion and other disk"
8890
                                 " changes not supported at the same time",
8891
                                 errors.ECODE_INVAL)
8892

    
8893
    if self.op.disk_template:
8894
      _CheckDiskTemplate(self.op.disk_template)
8895
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
8896
          self.op.remote_node is None):
8897
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
8898
                                   " one requires specifying a secondary node",
8899
                                   errors.ECODE_INVAL)
8900

    
8901
    # NIC validation
8902
    nic_addremove = 0
8903
    for nic_op, nic_dict in self.op.nics:
8904
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
8905
      if nic_op == constants.DDM_REMOVE:
8906
        nic_addremove += 1
8907
        continue
8908
      elif nic_op == constants.DDM_ADD:
8909
        nic_addremove += 1
8910
      else:
8911
        if not isinstance(nic_op, int):
8912
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
8913
        if not isinstance(nic_dict, dict):
8914
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
8915
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8916

    
8917
      # nic_dict should be a dict
8918
      nic_ip = nic_dict.get('ip', None)
8919
      if nic_ip is not None:
8920
        if nic_ip.lower() == constants.VALUE_NONE:
8921
          nic_dict['ip'] = None
8922
        else:
8923
          if not netutils.IPAddress.IsValid(nic_ip):
8924
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
8925
                                       errors.ECODE_INVAL)
8926

    
8927
      nic_bridge = nic_dict.get('bridge', None)
8928
      nic_link = nic_dict.get('link', None)
8929
      if nic_bridge and nic_link:
8930
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
8931
                                   " at the same time", errors.ECODE_INVAL)
8932
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
8933
        nic_dict['bridge'] = None
8934
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
8935
        nic_dict['link'] = None
8936

    
8937
      if nic_op == constants.DDM_ADD:
8938
        nic_mac = nic_dict.get('mac', None)
8939
        if nic_mac is None:
8940
          nic_dict['mac'] = constants.VALUE_AUTO
8941

    
8942
      if 'mac' in nic_dict:
8943
        nic_mac = nic_dict['mac']
8944
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8945
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
8946

    
8947
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
8948
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
8949
                                     " modifying an existing nic",
8950
                                     errors.ECODE_INVAL)
8951

    
8952
    if nic_addremove > 1:
8953
      raise errors.OpPrereqError("Only one NIC add or remove operation"
8954
                                 " supported at a time", errors.ECODE_INVAL)
8955

    
8956
  def ExpandNames(self):
8957
    self._ExpandAndLockInstance()
8958
    self.needed_locks[locking.LEVEL_NODE] = []
8959
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8960

    
8961
  def DeclareLocks(self, level):
8962
    if level == locking.LEVEL_NODE:
8963
      self._LockInstancesNodes()
8964
      if self.op.disk_template and self.op.remote_node:
8965
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8966
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
8967

    
8968
  def BuildHooksEnv(self):
8969
    """Build hooks env.
8970

8971
    This runs on the master, primary and secondaries.
8972

8973
    """
8974
    args = dict()
8975
    if constants.BE_MEMORY in self.be_new:
8976
      args['memory'] = self.be_new[constants.BE_MEMORY]
8977
    if constants.BE_VCPUS in self.be_new:
8978
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
8979
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
8980
    # information at all.
8981
    if self.op.nics:
8982
      args['nics'] = []
8983
      nic_override = dict(self.op.nics)
8984
      for idx, nic in enumerate(self.instance.nics):
8985
        if idx in nic_override:
8986
          this_nic_override = nic_override[idx]
8987
        else:
8988
          this_nic_override = {}
8989
        if 'ip' in this_nic_override:
8990
          ip = this_nic_override['ip']
8991
        else:
8992
          ip = nic.ip
8993
        if 'mac' in this_nic_override:
8994
          mac = this_nic_override['mac']
8995
        else:
8996
          mac = nic.mac
8997
        if idx in self.nic_pnew:
8998
          nicparams = self.nic_pnew[idx]
8999
        else:
9000
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
9001
        mode = nicparams[constants.NIC_MODE]
9002
        link = nicparams[constants.NIC_LINK]
9003
        args['nics'].append((ip, mac, mode, link))
9004
      if constants.DDM_ADD in nic_override:
9005
        ip = nic_override[constants.DDM_ADD].get('ip', None)
9006
        mac = nic_override[constants.DDM_ADD]['mac']
9007
        nicparams = self.nic_pnew[constants.DDM_ADD]
9008
        mode = nicparams[constants.NIC_MODE]
9009
        link = nicparams[constants.NIC_LINK]
9010
        args['nics'].append((ip, mac, mode, link))
9011
      elif constants.DDM_REMOVE in nic_override:
9012
        del args['nics'][-1]
9013

    
9014
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
9015
    if self.op.disk_template:
9016
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
9017
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9018
    return env, nl, nl
9019

    
9020
  def CheckPrereq(self):
9021
    """Check prerequisites.
9022

9023
    This only checks the instance list against the existing names.
9024

9025
    """
9026
    # checking the new params on the primary/secondary nodes
9027

    
9028
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9029
    cluster = self.cluster = self.cfg.GetClusterInfo()
9030
    assert self.instance is not None, \
9031
      "Cannot retrieve locked instance %s" % self.op.instance_name
9032
    pnode = instance.primary_node
9033
    nodelist = list(instance.all_nodes)
9034

    
9035
    # OS change
9036
    if self.op.os_name and not self.op.force:
9037
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
9038
                      self.op.force_variant)
9039
      instance_os = self.op.os_name
9040
    else:
9041
      instance_os = instance.os
9042

    
9043
    if self.op.disk_template:
9044
      if instance.disk_template == self.op.disk_template:
9045
        raise errors.OpPrereqError("Instance already has disk template %s" %
9046
                                   instance.disk_template, errors.ECODE_INVAL)
9047

    
9048
      if (instance.disk_template,
9049
          self.op.disk_template) not in self._DISK_CONVERSIONS:
9050
        raise errors.OpPrereqError("Unsupported disk template conversion from"
9051
                                   " %s to %s" % (instance.disk_template,
9052
                                                  self.op.disk_template),
9053
                                   errors.ECODE_INVAL)
9054
      _CheckInstanceDown(self, instance, "cannot change disk template")
9055
      if self.op.disk_template in constants.DTS_NET_MIRROR:
9056
        if self.op.remote_node == pnode:
9057
          raise errors.OpPrereqError("Given new secondary node %s is the same"
9058
                                     " as the primary node of the instance" %
9059
                                     self.op.remote_node, errors.ECODE_STATE)
9060
        _CheckNodeOnline(self, self.op.remote_node)
9061
        _CheckNodeNotDrained(self, self.op.remote_node)
9062
        disks = [{"size": d.size} for d in instance.disks]
9063
        required = _ComputeDiskSize(self.op.disk_template, disks)
9064
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
9065

    
9066
    # hvparams processing
9067
    if self.op.hvparams:
9068
      hv_type = instance.hypervisor
9069
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
9070
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
9071
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
9072

    
9073
      # local check
9074
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
9075
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
9076
      self.hv_new = hv_new # the new actual values
9077
      self.hv_inst = i_hvdict # the new dict (without defaults)
9078
    else:
9079
      self.hv_new = self.hv_inst = {}
9080

    
9081
    # beparams processing
9082
    if self.op.beparams:
9083
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
9084
                                   use_none=True)
9085
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
9086
      be_new = cluster.SimpleFillBE(i_bedict)
9087
      self.be_new = be_new # the new actual values
9088
      self.be_inst = i_bedict # the new dict (without defaults)
9089
    else:
9090
      self.be_new = self.be_inst = {}
9091

    
9092
    # osparams processing
9093
    if self.op.osparams:
9094
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
9095
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
9096
      self.os_inst = i_osdict # the new dict (without defaults)
9097
    else:
9098
      self.os_inst = {}
9099

    
9100
    self.warn = []
9101

    
9102
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
9103
      mem_check_list = [pnode]
9104
      if be_new[constants.BE_AUTO_BALANCE]:
9105
        # either we changed auto_balance to yes or it was from before
9106
        mem_check_list.extend(instance.secondary_nodes)
9107
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
9108
                                                  instance.hypervisor)
9109
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
9110
                                         instance.hypervisor)
9111
      pninfo = nodeinfo[pnode]
9112
      msg = pninfo.fail_msg
9113
      if msg:
9114
        # Assume the primary node is unreachable and go ahead
9115
        self.warn.append("Can't get info from primary node %s: %s" %
9116
                         (pnode,  msg))
9117
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
9118
        self.warn.append("Node data from primary node %s doesn't contain"
9119
                         " free memory information" % pnode)
9120
      elif instance_info.fail_msg:
9121
        self.warn.append("Can't get instance runtime information: %s" %
9122
                        instance_info.fail_msg)
9123
      else:
9124
        if instance_info.payload:
9125
          current_mem = int(instance_info.payload['memory'])
9126
        else:
9127
          # Assume instance not running
9128
          # (there is a slight race condition here, but it's not very probable,
9129
          # and we have no other way to check)
9130
          current_mem = 0
9131
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
9132
                    pninfo.payload['memory_free'])
9133
        if miss_mem > 0:
9134
          raise errors.OpPrereqError("This change will prevent the instance"
9135
                                     " from starting, due to %d MB of memory"
9136
                                     " missing on its primary node" % miss_mem,
9137
                                     errors.ECODE_NORES)
9138

    
9139
      if be_new[constants.BE_AUTO_BALANCE]:
9140
        for node, nres in nodeinfo.items():
9141
          if node not in instance.secondary_nodes:
9142
            continue
9143
          msg = nres.fail_msg
9144
          if msg:
9145
            self.warn.append("Can't get info from secondary node %s: %s" %
9146
                             (node, msg))
9147
          elif not isinstance(nres.payload.get('memory_free', None), int):
9148
            self.warn.append("Secondary node %s didn't return free"
9149
                             " memory information" % node)
9150
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
9151
            self.warn.append("Not enough memory to failover instance to"
9152
                             " secondary node %s" % node)
9153

    
9154
    # NIC processing
9155
    self.nic_pnew = {}
9156
    self.nic_pinst = {}
9157
    for nic_op, nic_dict in self.op.nics:
9158
      if nic_op == constants.DDM_REMOVE:
9159
        if not instance.nics:
9160
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
9161
                                     errors.ECODE_INVAL)
9162
        continue
9163
      if nic_op != constants.DDM_ADD:
9164
        # an existing nic
9165
        if not instance.nics:
9166
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
9167
                                     " no NICs" % nic_op,
9168
                                     errors.ECODE_INVAL)
9169
        if nic_op < 0 or nic_op >= len(instance.nics):
9170
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
9171
                                     " are 0 to %d" %
9172
                                     (nic_op, len(instance.nics) - 1),
9173
                                     errors.ECODE_INVAL)
9174
        old_nic_params = instance.nics[nic_op].nicparams
9175
        old_nic_ip = instance.nics[nic_op].ip
9176
      else:
9177
        old_nic_params = {}
9178
        old_nic_ip = None
9179

    
9180
      update_params_dict = dict([(key, nic_dict[key])
9181
                                 for key in constants.NICS_PARAMETERS
9182
                                 if key in nic_dict])
9183

    
9184
      if 'bridge' in nic_dict:
9185
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
9186

    
9187
      new_nic_params = _GetUpdatedParams(old_nic_params,
9188
                                         update_params_dict)
9189
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
9190
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
9191
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
9192
      self.nic_pinst[nic_op] = new_nic_params
9193
      self.nic_pnew[nic_op] = new_filled_nic_params
9194
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
9195

    
9196
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
9197
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
9198
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
9199
        if msg:
9200
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
9201
          if self.op.force:
9202
            self.warn.append(msg)
9203
          else:
9204
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
9205
      if new_nic_mode == constants.NIC_MODE_ROUTED:
9206
        if 'ip' in nic_dict:
9207
          nic_ip = nic_dict['ip']
9208
        else:
9209
          nic_ip = old_nic_ip
9210
        if nic_ip is None:
9211
          raise errors.OpPrereqError('Cannot set the nic ip to None'
9212
                                     ' on a routed nic', errors.ECODE_INVAL)
9213
      if 'mac' in nic_dict:
9214
        nic_mac = nic_dict['mac']
9215
        if nic_mac is None:
9216
          raise errors.OpPrereqError('Cannot set the nic mac to None',
9217
                                     errors.ECODE_INVAL)
9218
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9219
          # otherwise generate the mac
9220
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
9221
        else:
9222
          # or validate/reserve the current one
9223
          try:
9224
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
9225
          except errors.ReservationError:
9226
            raise errors.OpPrereqError("MAC address %s already in use"
9227
                                       " in cluster" % nic_mac,
9228
                                       errors.ECODE_NOTUNIQUE)
9229

    
9230
    # DISK processing
9231
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
9232
      raise errors.OpPrereqError("Disk operations not supported for"
9233
                                 " diskless instances",
9234
                                 errors.ECODE_INVAL)
9235
    for disk_op, _ in self.op.disks:
9236
      if disk_op == constants.DDM_REMOVE:
9237
        if len(instance.disks) == 1:
9238
          raise errors.OpPrereqError("Cannot remove the last disk of"
9239
                                     " an instance", errors.ECODE_INVAL)
9240
        _CheckInstanceDown(self, instance, "cannot remove disks")
9241

    
9242
      if (disk_op == constants.DDM_ADD and
9243
          len(instance.nics) >= constants.MAX_DISKS):
9244
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
9245
                                   " add more" % constants.MAX_DISKS,
9246
                                   errors.ECODE_STATE)
9247
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
9248
        # an existing disk
9249
        if disk_op < 0 or disk_op >= len(instance.disks):
9250
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9251
                                     " are 0 to %d" %
9252
                                     (disk_op, len(instance.disks)),
9253
                                     errors.ECODE_INVAL)
9254

    
9255
    return
9256

    
9257
  def _ConvertPlainToDrbd(self, feedback_fn):
9258
    """Converts an instance from plain to drbd.
9259

9260
    """
9261
    feedback_fn("Converting template to drbd")
9262
    instance = self.instance
9263
    pnode = instance.primary_node
9264
    snode = self.op.remote_node
9265

    
9266
    # create a fake disk info for _GenerateDiskTemplate
9267
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
9268
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9269
                                      instance.name, pnode, [snode],
9270
                                      disk_info, None, None, 0)
9271
    info = _GetInstanceInfoText(instance)
9272
    feedback_fn("Creating aditional volumes...")
9273
    # first, create the missing data and meta devices
9274
    for disk in new_disks:
9275
      # unfortunately this is... not too nice
9276
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9277
                            info, True)
9278
      for child in disk.children:
9279
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9280
    # at this stage, all new LVs have been created, we can rename the
9281
    # old ones
9282
    feedback_fn("Renaming original volumes...")
9283
    rename_list = [(o, n.children[0].logical_id)
9284
                   for (o, n) in zip(instance.disks, new_disks)]
9285
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9286
    result.Raise("Failed to rename original LVs")
9287

    
9288
    feedback_fn("Initializing DRBD devices...")
9289
    # all child devices are in place, we can now create the DRBD devices
9290
    for disk in new_disks:
9291
      for node in [pnode, snode]:
9292
        f_create = node == pnode
9293
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9294

    
9295
    # at this point, the instance has been modified
9296
    instance.disk_template = constants.DT_DRBD8
9297
    instance.disks = new_disks
9298
    self.cfg.Update(instance, feedback_fn)
9299

    
9300
    # disks are created, waiting for sync
9301
    disk_abort = not _WaitForSync(self, instance)
9302
    if disk_abort:
9303
      raise errors.OpExecError("There are some degraded disks for"
9304
                               " this instance, please cleanup manually")
9305

    
9306
  def _ConvertDrbdToPlain(self, feedback_fn):
9307
    """Converts an instance from drbd to plain.
9308

9309
    """
9310
    instance = self.instance
9311
    assert len(instance.secondary_nodes) == 1
9312
    pnode = instance.primary_node
9313
    snode = instance.secondary_nodes[0]
9314
    feedback_fn("Converting template to plain")
9315

    
9316
    old_disks = instance.disks
9317
    new_disks = [d.children[0] for d in old_disks]
9318

    
9319
    # copy over size and mode
9320
    for parent, child in zip(old_disks, new_disks):
9321
      child.size = parent.size
9322
      child.mode = parent.mode
9323

    
9324
    # update instance structure
9325
    instance.disks = new_disks
9326
    instance.disk_template = constants.DT_PLAIN
9327
    self.cfg.Update(instance, feedback_fn)
9328

    
9329
    feedback_fn("Removing volumes on the secondary node...")
9330
    for disk in old_disks:
9331
      self.cfg.SetDiskID(disk, snode)
9332
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9333
      if msg:
9334
        self.LogWarning("Could not remove block device %s on node %s,"
9335
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9336

    
9337
    feedback_fn("Removing unneeded volumes on the primary node...")
9338
    for idx, disk in enumerate(old_disks):
9339
      meta = disk.children[1]
9340
      self.cfg.SetDiskID(meta, pnode)
9341
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9342
      if msg:
9343
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9344
                        " continuing anyway: %s", idx, pnode, msg)
9345

    
9346

    
9347
  def Exec(self, feedback_fn):
9348
    """Modifies an instance.
9349

9350
    All parameters take effect only at the next restart of the instance.
9351

9352
    """
9353
    # Process here the warnings from CheckPrereq, as we don't have a
9354
    # feedback_fn there.
9355
    for warn in self.warn:
9356
      feedback_fn("WARNING: %s" % warn)
9357

    
9358
    result = []
9359
    instance = self.instance
9360
    # disk changes
9361
    for disk_op, disk_dict in self.op.disks:
9362
      if disk_op == constants.DDM_REMOVE:
9363
        # remove the last disk
9364
        device = instance.disks.pop()
9365
        device_idx = len(instance.disks)
9366
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9367
          self.cfg.SetDiskID(disk, node)
9368
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9369
          if msg:
9370
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9371
                            " continuing anyway", device_idx, node, msg)
9372
        result.append(("disk/%d" % device_idx, "remove"))
9373
      elif disk_op == constants.DDM_ADD:
9374
        # add a new disk
9375
        if instance.disk_template == constants.DT_FILE:
9376
          file_driver, file_path = instance.disks[0].logical_id
9377
          file_path = os.path.dirname(file_path)
9378
        else:
9379
          file_driver = file_path = None
9380
        disk_idx_base = len(instance.disks)
9381
        new_disk = _GenerateDiskTemplate(self,
9382
                                         instance.disk_template,
9383
                                         instance.name, instance.primary_node,
9384
                                         instance.secondary_nodes,
9385
                                         [disk_dict],
9386
                                         file_path,
9387
                                         file_driver,
9388
                                         disk_idx_base)[0]
9389
        instance.disks.append(new_disk)
9390
        info = _GetInstanceInfoText(instance)
9391

    
9392
        logging.info("Creating volume %s for instance %s",
9393
                     new_disk.iv_name, instance.name)
9394
        # Note: this needs to be kept in sync with _CreateDisks
9395
        #HARDCODE
9396
        for node in instance.all_nodes:
9397
          f_create = node == instance.primary_node
9398
          try:
9399
            _CreateBlockDev(self, node, instance, new_disk,
9400
                            f_create, info, f_create)
9401
          except errors.OpExecError, err:
9402
            self.LogWarning("Failed to create volume %s (%s) on"
9403
                            " node %s: %s",
9404
                            new_disk.iv_name, new_disk, node, err)
9405
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9406
                       (new_disk.size, new_disk.mode)))
9407
      else:
9408
        # change a given disk
9409
        instance.disks[disk_op].mode = disk_dict['mode']
9410
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9411

    
9412
    if self.op.disk_template:
9413
      r_shut = _ShutdownInstanceDisks(self, instance)
9414
      if not r_shut:
9415
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
9416
                                 " proceed with disk template conversion")
9417
      mode = (instance.disk_template, self.op.disk_template)
9418
      try:
9419
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9420
      except:
9421
        self.cfg.ReleaseDRBDMinors(instance.name)
9422
        raise
9423
      result.append(("disk_template", self.op.disk_template))
9424

    
9425
    # NIC changes
9426
    for nic_op, nic_dict in self.op.nics:
9427
      if nic_op == constants.DDM_REMOVE:
9428
        # remove the last nic
9429
        del instance.nics[-1]
9430
        result.append(("nic.%d" % len(instance.nics), "remove"))
9431
      elif nic_op == constants.DDM_ADD:
9432
        # mac and bridge should be set, by now
9433
        mac = nic_dict['mac']
9434
        ip = nic_dict.get('ip', None)
9435
        nicparams = self.nic_pinst[constants.DDM_ADD]
9436
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9437
        instance.nics.append(new_nic)
9438
        result.append(("nic.%d" % (len(instance.nics) - 1),
9439
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9440
                       (new_nic.mac, new_nic.ip,
9441
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9442
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9443
                       )))
9444
      else:
9445
        for key in 'mac', 'ip':
9446
          if key in nic_dict:
9447
            setattr(instance.nics[nic_op], key, nic_dict[key])
9448
        if nic_op in self.nic_pinst:
9449
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9450
        for key, val in nic_dict.iteritems():
9451
          result.append(("nic.%s/%d" % (key, nic_op), val))
9452

    
9453
    # hvparams changes
9454
    if self.op.hvparams:
9455
      instance.hvparams = self.hv_inst
9456
      for key, val in self.op.hvparams.iteritems():
9457
        result.append(("hv/%s" % key, val))
9458

    
9459
    # beparams changes
9460
    if self.op.beparams:
9461
      instance.beparams = self.be_inst
9462
      for key, val in self.op.beparams.iteritems():
9463
        result.append(("be/%s" % key, val))
9464

    
9465
    # OS change
9466
    if self.op.os_name:
9467
      instance.os = self.op.os_name
9468

    
9469
    # osparams changes
9470
    if self.op.osparams:
9471
      instance.osparams = self.os_inst
9472
      for key, val in self.op.osparams.iteritems():
9473
        result.append(("os/%s" % key, val))
9474

    
9475
    self.cfg.Update(instance, feedback_fn)
9476

    
9477
    return result
9478

    
9479
  _DISK_CONVERSIONS = {
9480
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9481
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9482
    }
9483

    
9484

    
9485
class LUQueryExports(NoHooksLU):
9486
  """Query the exports list
9487

9488
  """
9489
  _OP_PARAMS = [
9490
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
9491
    ("use_locking", False, ht.TBool),
9492
    ]
9493
  REQ_BGL = False
9494

    
9495
  def ExpandNames(self):
9496
    self.needed_locks = {}
9497
    self.share_locks[locking.LEVEL_NODE] = 1
9498
    if not self.op.nodes:
9499
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9500
    else:
9501
      self.needed_locks[locking.LEVEL_NODE] = \
9502
        _GetWantedNodes(self, self.op.nodes)
9503

    
9504
  def Exec(self, feedback_fn):
9505
    """Compute the list of all the exported system images.
9506

9507
    @rtype: dict
9508
    @return: a dictionary with the structure node->(export-list)
9509
        where export-list is a list of the instances exported on
9510
        that node.
9511

9512
    """
9513
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9514
    rpcresult = self.rpc.call_export_list(self.nodes)
9515
    result = {}
9516
    for node in rpcresult:
9517
      if rpcresult[node].fail_msg:
9518
        result[node] = False
9519
      else:
9520
        result[node] = rpcresult[node].payload
9521

    
9522
    return result
9523

    
9524

    
9525
class LUPrepareExport(NoHooksLU):
9526
  """Prepares an instance for an export and returns useful information.
9527

9528
  """
9529
  _OP_PARAMS = [
9530
    _PInstanceName,
9531
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES)),
9532
    ]
9533
  REQ_BGL = False
9534

    
9535
  def ExpandNames(self):
9536
    self._ExpandAndLockInstance()
9537

    
9538
  def CheckPrereq(self):
9539
    """Check prerequisites.
9540

9541
    """
9542
    instance_name = self.op.instance_name
9543

    
9544
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9545
    assert self.instance is not None, \
9546
          "Cannot retrieve locked instance %s" % self.op.instance_name
9547
    _CheckNodeOnline(self, self.instance.primary_node)
9548

    
9549
    self._cds = _GetClusterDomainSecret()
9550

    
9551
  def Exec(self, feedback_fn):
9552
    """Prepares an instance for an export.
9553

9554
    """
9555
    instance = self.instance
9556

    
9557
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9558
      salt = utils.GenerateSecret(8)
9559

    
9560
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9561
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9562
                                              constants.RIE_CERT_VALIDITY)
9563
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9564

    
9565
      (name, cert_pem) = result.payload
9566

    
9567
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9568
                                             cert_pem)
9569

    
9570
      return {
9571
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9572
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9573
                          salt),
9574
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9575
        }
9576

    
9577
    return None
9578

    
9579

    
9580
class LUExportInstance(LogicalUnit):
9581
  """Export an instance to an image in the cluster.
9582

9583
  """
9584
  HPATH = "instance-export"
9585
  HTYPE = constants.HTYPE_INSTANCE
9586
  _OP_PARAMS = [
9587
    _PInstanceName,
9588
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList)),
9589
    ("shutdown", True, ht.TBool),
9590
    _PShutdownTimeout,
9591
    ("remove_instance", False, ht.TBool),
9592
    ("ignore_remove_failures", False, ht.TBool),
9593
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES)),
9594
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone)),
9595
    ("destination_x509_ca", None, ht.TMaybeString),
9596
    ]
9597
  REQ_BGL = False
9598

    
9599
  def CheckArguments(self):
9600
    """Check the arguments.
9601

9602
    """
9603
    self.x509_key_name = self.op.x509_key_name
9604
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9605

    
9606
    if self.op.remove_instance and not self.op.shutdown:
9607
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9608
                                 " down before")
9609

    
9610
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9611
      if not self.x509_key_name:
9612
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9613
                                   errors.ECODE_INVAL)
9614

    
9615
      if not self.dest_x509_ca_pem:
9616
        raise errors.OpPrereqError("Missing destination X509 CA",
9617
                                   errors.ECODE_INVAL)
9618

    
9619
  def ExpandNames(self):
9620
    self._ExpandAndLockInstance()
9621

    
9622
    # Lock all nodes for local exports
9623
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9624
      # FIXME: lock only instance primary and destination node
9625
      #
9626
      # Sad but true, for now we have do lock all nodes, as we don't know where
9627
      # the previous export might be, and in this LU we search for it and
9628
      # remove it from its current node. In the future we could fix this by:
9629
      #  - making a tasklet to search (share-lock all), then create the
9630
      #    new one, then one to remove, after
9631
      #  - removing the removal operation altogether
9632
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9633

    
9634
  def DeclareLocks(self, level):
9635
    """Last minute lock declaration."""
9636
    # All nodes are locked anyway, so nothing to do here.
9637

    
9638
  def BuildHooksEnv(self):
9639
    """Build hooks env.
9640

9641
    This will run on the master, primary node and target node.
9642

9643
    """
9644
    env = {
9645
      "EXPORT_MODE": self.op.mode,
9646
      "EXPORT_NODE": self.op.target_node,
9647
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9648
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9649
      # TODO: Generic function for boolean env variables
9650
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9651
      }
9652

    
9653
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9654

    
9655
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9656

    
9657
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9658
      nl.append(self.op.target_node)
9659

    
9660
    return env, nl, nl
9661

    
9662
  def CheckPrereq(self):
9663
    """Check prerequisites.
9664

9665
    This checks that the instance and node names are valid.
9666

9667
    """
9668
    instance_name = self.op.instance_name
9669

    
9670
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9671
    assert self.instance is not None, \
9672
          "Cannot retrieve locked instance %s" % self.op.instance_name
9673
    _CheckNodeOnline(self, self.instance.primary_node)
9674

    
9675
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9676
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9677
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9678
      assert self.dst_node is not None
9679

    
9680
      _CheckNodeOnline(self, self.dst_node.name)
9681
      _CheckNodeNotDrained(self, self.dst_node.name)
9682

    
9683
      self._cds = None
9684
      self.dest_disk_info = None
9685
      self.dest_x509_ca = None
9686

    
9687
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9688
      self.dst_node = None
9689

    
9690
      if len(self.op.target_node) != len(self.instance.disks):
9691
        raise errors.OpPrereqError(("Received destination information for %s"
9692
                                    " disks, but instance %s has %s disks") %
9693
                                   (len(self.op.target_node), instance_name,
9694
                                    len(self.instance.disks)),
9695
                                   errors.ECODE_INVAL)
9696

    
9697
      cds = _GetClusterDomainSecret()
9698

    
9699
      # Check X509 key name
9700
      try:
9701
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9702
      except (TypeError, ValueError), err:
9703
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9704

    
9705
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9706
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9707
                                   errors.ECODE_INVAL)
9708

    
9709
      # Load and verify CA
9710
      try:
9711
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9712
      except OpenSSL.crypto.Error, err:
9713
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9714
                                   (err, ), errors.ECODE_INVAL)
9715

    
9716
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9717
      if errcode is not None:
9718
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9719
                                   (msg, ), errors.ECODE_INVAL)
9720

    
9721
      self.dest_x509_ca = cert
9722

    
9723
      # Verify target information
9724
      disk_info = []
9725
      for idx, disk_data in enumerate(self.op.target_node):
9726
        try:
9727
          (host, port, magic) = \
9728
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9729
        except errors.GenericError, err:
9730
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9731
                                     (idx, err), errors.ECODE_INVAL)
9732

    
9733
        disk_info.append((host, port, magic))
9734

    
9735
      assert len(disk_info) == len(self.op.target_node)
9736
      self.dest_disk_info = disk_info
9737

    
9738
    else:
9739
      raise errors.ProgrammerError("Unhandled export mode %r" %
9740
                                   self.op.mode)
9741

    
9742
    # instance disk type verification
9743
    # TODO: Implement export support for file-based disks
9744
    for disk in self.instance.disks:
9745
      if disk.dev_type == constants.LD_FILE:
9746
        raise errors.OpPrereqError("Export not supported for instances with"
9747
                                   " file-based disks", errors.ECODE_INVAL)
9748

    
9749
  def _CleanupExports(self, feedback_fn):
9750
    """Removes exports of current instance from all other nodes.
9751

9752
    If an instance in a cluster with nodes A..D was exported to node C, its
9753
    exports will be removed from the nodes A, B and D.
9754

9755
    """
9756
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9757

    
9758
    nodelist = self.cfg.GetNodeList()
9759
    nodelist.remove(self.dst_node.name)
9760

    
9761
    # on one-node clusters nodelist will be empty after the removal
9762
    # if we proceed the backup would be removed because OpQueryExports
9763
    # substitutes an empty list with the full cluster node list.
9764
    iname = self.instance.name
9765
    if nodelist:
9766
      feedback_fn("Removing old exports for instance %s" % iname)
9767
      exportlist = self.rpc.call_export_list(nodelist)
9768
      for node in exportlist:
9769
        if exportlist[node].fail_msg:
9770
          continue
9771
        if iname in exportlist[node].payload:
9772
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9773
          if msg:
9774
            self.LogWarning("Could not remove older export for instance %s"
9775
                            " on node %s: %s", iname, node, msg)
9776

    
9777
  def Exec(self, feedback_fn):
9778
    """Export an instance to an image in the cluster.
9779

9780
    """
9781
    assert self.op.mode in constants.EXPORT_MODES
9782

    
9783
    instance = self.instance
9784
    src_node = instance.primary_node
9785

    
9786
    if self.op.shutdown:
9787
      # shutdown the instance, but not the disks
9788
      feedback_fn("Shutting down instance %s" % instance.name)
9789
      result = self.rpc.call_instance_shutdown(src_node, instance,
9790
                                               self.op.shutdown_timeout)
9791
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9792
      result.Raise("Could not shutdown instance %s on"
9793
                   " node %s" % (instance.name, src_node))
9794

    
9795
    # set the disks ID correctly since call_instance_start needs the
9796
    # correct drbd minor to create the symlinks
9797
    for disk in instance.disks:
9798
      self.cfg.SetDiskID(disk, src_node)
9799

    
9800
    activate_disks = (not instance.admin_up)
9801

    
9802
    if activate_disks:
9803
      # Activate the instance disks if we'exporting a stopped instance
9804
      feedback_fn("Activating disks for %s" % instance.name)
9805
      _StartInstanceDisks(self, instance, None)
9806

    
9807
    try:
9808
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9809
                                                     instance)
9810

    
9811
      helper.CreateSnapshots()
9812
      try:
9813
        if (self.op.shutdown and instance.admin_up and
9814
            not self.op.remove_instance):
9815
          assert not activate_disks
9816
          feedback_fn("Starting instance %s" % instance.name)
9817
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9818
          msg = result.fail_msg
9819
          if msg:
9820
            feedback_fn("Failed to start instance: %s" % msg)
9821
            _ShutdownInstanceDisks(self, instance)
9822
            raise errors.OpExecError("Could not start instance: %s" % msg)
9823

    
9824
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9825
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9826
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9827
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9828
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9829

    
9830
          (key_name, _, _) = self.x509_key_name
9831

    
9832
          dest_ca_pem = \
9833
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9834
                                            self.dest_x509_ca)
9835

    
9836
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9837
                                                     key_name, dest_ca_pem,
9838
                                                     timeouts)
9839
      finally:
9840
        helper.Cleanup()
9841

    
9842
      # Check for backwards compatibility
9843
      assert len(dresults) == len(instance.disks)
9844
      assert compat.all(isinstance(i, bool) for i in dresults), \
9845
             "Not all results are boolean: %r" % dresults
9846

    
9847
    finally:
9848
      if activate_disks:
9849
        feedback_fn("Deactivating disks for %s" % instance.name)
9850
        _ShutdownInstanceDisks(self, instance)
9851

    
9852
    if not (compat.all(dresults) and fin_resu):
9853
      failures = []
9854
      if not fin_resu:
9855
        failures.append("export finalization")
9856
      if not compat.all(dresults):
9857
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
9858
                               if not dsk)
9859
        failures.append("disk export: disk(s) %s" % fdsk)
9860

    
9861
      raise errors.OpExecError("Export failed, errors in %s" %
9862
                               utils.CommaJoin(failures))
9863

    
9864
    # At this point, the export was successful, we can cleanup/finish
9865

    
9866
    # Remove instance if requested
9867
    if self.op.remove_instance:
9868
      feedback_fn("Removing instance %s" % instance.name)
9869
      _RemoveInstance(self, feedback_fn, instance,
9870
                      self.op.ignore_remove_failures)
9871

    
9872
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9873
      self._CleanupExports(feedback_fn)
9874

    
9875
    return fin_resu, dresults
9876

    
9877

    
9878
class LURemoveExport(NoHooksLU):
9879
  """Remove exports related to the named instance.
9880

9881
  """
9882
  _OP_PARAMS = [
9883
    _PInstanceName,
9884
    ]
9885
  REQ_BGL = False
9886

    
9887
  def ExpandNames(self):
9888
    self.needed_locks = {}
9889
    # We need all nodes to be locked in order for RemoveExport to work, but we
9890
    # don't need to lock the instance itself, as nothing will happen to it (and
9891
    # we can remove exports also for a removed instance)
9892
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9893

    
9894
  def Exec(self, feedback_fn):
9895
    """Remove any export.
9896

9897
    """
9898
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9899
    # If the instance was not found we'll try with the name that was passed in.
9900
    # This will only work if it was an FQDN, though.
9901
    fqdn_warn = False
9902
    if not instance_name:
9903
      fqdn_warn = True
9904
      instance_name = self.op.instance_name
9905

    
9906
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
9907
    exportlist = self.rpc.call_export_list(locked_nodes)
9908
    found = False
9909
    for node in exportlist:
9910
      msg = exportlist[node].fail_msg
9911
      if msg:
9912
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
9913
        continue
9914
      if instance_name in exportlist[node].payload:
9915
        found = True
9916
        result = self.rpc.call_export_remove(node, instance_name)
9917
        msg = result.fail_msg
9918
        if msg:
9919
          logging.error("Could not remove export for instance %s"
9920
                        " on node %s: %s", instance_name, node, msg)
9921

    
9922
    if fqdn_warn and not found:
9923
      feedback_fn("Export not found. If trying to remove an export belonging"
9924
                  " to a deleted instance please use its Fully Qualified"
9925
                  " Domain Name.")
9926

    
9927

    
9928
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
9929
  """Generic tags LU.
9930

9931
  This is an abstract class which is the parent of all the other tags LUs.
9932

9933
  """
9934

    
9935
  def ExpandNames(self):
9936
    self.needed_locks = {}
9937
    if self.op.kind == constants.TAG_NODE:
9938
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
9939
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
9940
    elif self.op.kind == constants.TAG_INSTANCE:
9941
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
9942
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
9943

    
9944
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
9945
    # not possible to acquire the BGL based on opcode parameters)
9946

    
9947
  def CheckPrereq(self):
9948
    """Check prerequisites.
9949

9950
    """
9951
    if self.op.kind == constants.TAG_CLUSTER:
9952
      self.target = self.cfg.GetClusterInfo()
9953
    elif self.op.kind == constants.TAG_NODE:
9954
      self.target = self.cfg.GetNodeInfo(self.op.name)
9955
    elif self.op.kind == constants.TAG_INSTANCE:
9956
      self.target = self.cfg.GetInstanceInfo(self.op.name)
9957
    else:
9958
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
9959
                                 str(self.op.kind), errors.ECODE_INVAL)
9960

    
9961

    
9962
class LUGetTags(TagsLU):
9963
  """Returns the tags of a given object.
9964

9965
  """
9966
  _OP_PARAMS = [
9967
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
9968
    # Name is only meaningful for nodes and instances
9969
    ("name", ht.NoDefault, ht.TMaybeString),
9970
    ]
9971
  REQ_BGL = False
9972

    
9973
  def ExpandNames(self):
9974
    TagsLU.ExpandNames(self)
9975

    
9976
    # Share locks as this is only a read operation
9977
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9978

    
9979
  def Exec(self, feedback_fn):
9980
    """Returns the tag list.
9981

9982
    """
9983
    return list(self.target.GetTags())
9984

    
9985

    
9986
class LUSearchTags(NoHooksLU):
9987
  """Searches the tags for a given pattern.
9988

9989
  """
9990
  _OP_PARAMS = [
9991
    ("pattern", ht.NoDefault, ht.TNonEmptyString),
9992
    ]
9993
  REQ_BGL = False
9994

    
9995
  def ExpandNames(self):
9996
    self.needed_locks = {}
9997

    
9998
  def CheckPrereq(self):
9999
    """Check prerequisites.
10000

10001
    This checks the pattern passed for validity by compiling it.
10002

10003
    """
10004
    try:
10005
      self.re = re.compile(self.op.pattern)
10006
    except re.error, err:
10007
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
10008
                                 (self.op.pattern, err), errors.ECODE_INVAL)
10009

    
10010
  def Exec(self, feedback_fn):
10011
    """Returns the tag list.
10012

10013
    """
10014
    cfg = self.cfg
10015
    tgts = [("/cluster", cfg.GetClusterInfo())]
10016
    ilist = cfg.GetAllInstancesInfo().values()
10017
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
10018
    nlist = cfg.GetAllNodesInfo().values()
10019
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
10020
    results = []
10021
    for path, target in tgts:
10022
      for tag in target.GetTags():
10023
        if self.re.search(tag):
10024
          results.append((path, tag))
10025
    return results
10026

    
10027

    
10028
class LUAddTags(TagsLU):
10029
  """Sets a tag on a given object.
10030

10031
  """
10032
  _OP_PARAMS = [
10033
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
10034
    # Name is only meaningful for nodes and instances
10035
    ("name", ht.NoDefault, ht.TMaybeString),
10036
    ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
10037
    ]
10038
  REQ_BGL = False
10039

    
10040
  def CheckPrereq(self):
10041
    """Check prerequisites.
10042

10043
    This checks the type and length of the tag name and value.
10044

10045
    """
10046
    TagsLU.CheckPrereq(self)
10047
    for tag in self.op.tags:
10048
      objects.TaggableObject.ValidateTag(tag)
10049

    
10050
  def Exec(self, feedback_fn):
10051
    """Sets the tag.
10052

10053
    """
10054
    try:
10055
      for tag in self.op.tags:
10056
        self.target.AddTag(tag)
10057
    except errors.TagError, err:
10058
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
10059
    self.cfg.Update(self.target, feedback_fn)
10060

    
10061

    
10062
class LUDelTags(TagsLU):
10063
  """Delete a list of tags from a given object.
10064

10065
  """
10066
  _OP_PARAMS = [
10067
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
10068
    # Name is only meaningful for nodes and instances
10069
    ("name", ht.NoDefault, ht.TMaybeString),
10070
    ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
10071
    ]
10072
  REQ_BGL = False
10073

    
10074
  def CheckPrereq(self):
10075
    """Check prerequisites.
10076

10077
    This checks that we have the given tag.
10078

10079
    """
10080
    TagsLU.CheckPrereq(self)
10081
    for tag in self.op.tags:
10082
      objects.TaggableObject.ValidateTag(tag)
10083
    del_tags = frozenset(self.op.tags)
10084
    cur_tags = self.target.GetTags()
10085

    
10086
    diff_tags = del_tags - cur_tags
10087
    if diff_tags:
10088
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
10089
      raise errors.OpPrereqError("Tag(s) %s not found" %
10090
                                 (utils.CommaJoin(diff_names), ),
10091
                                 errors.ECODE_NOENT)
10092

    
10093
  def Exec(self, feedback_fn):
10094
    """Remove the tag from the object.
10095

10096
    """
10097
    for tag in self.op.tags:
10098
      self.target.RemoveTag(tag)
10099
    self.cfg.Update(self.target, feedback_fn)
10100

    
10101

    
10102
class LUTestDelay(NoHooksLU):
10103
  """Sleep for a specified amount of time.
10104

10105
  This LU sleeps on the master and/or nodes for a specified amount of
10106
  time.
10107

10108
  """
10109
  _OP_PARAMS = [
10110
    ("duration", ht.NoDefault, ht.TFloat),
10111
    ("on_master", True, ht.TBool),
10112
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
10113
    ("repeat", 0, ht.TPositiveInt)
10114
    ]
10115
  REQ_BGL = False
10116

    
10117
  def ExpandNames(self):
10118
    """Expand names and set required locks.
10119

10120
    This expands the node list, if any.
10121

10122
    """
10123
    self.needed_locks = {}
10124
    if self.op.on_nodes:
10125
      # _GetWantedNodes can be used here, but is not always appropriate to use
10126
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
10127
      # more information.
10128
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
10129
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
10130

    
10131
  def _TestDelay(self):
10132
    """Do the actual sleep.
10133

10134
    """
10135
    if self.op.on_master:
10136
      if not utils.TestDelay(self.op.duration):
10137
        raise errors.OpExecError("Error during master delay test")
10138
    if self.op.on_nodes:
10139
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
10140
      for node, node_result in result.items():
10141
        node_result.Raise("Failure during rpc call to node %s" % node)
10142

    
10143
  def Exec(self, feedback_fn):
10144
    """Execute the test delay opcode, with the wanted repetitions.
10145

10146
    """
10147
    if self.op.repeat == 0:
10148
      self._TestDelay()
10149
    else:
10150
      top_value = self.op.repeat - 1
10151
      for i in range(self.op.repeat):
10152
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
10153
        self._TestDelay()
10154

    
10155

    
10156
class LUTestJobqueue(NoHooksLU):
10157
  """Utility LU to test some aspects of the job queue.
10158

10159
  """
10160
  _OP_PARAMS = [
10161
    ("notify_waitlock", False, ht.TBool),
10162
    ("notify_exec", False, ht.TBool),
10163
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString)),
10164
    ("fail", False, ht.TBool),
10165
    ]
10166
  REQ_BGL = False
10167

    
10168
  # Must be lower than default timeout for WaitForJobChange to see whether it
10169
  # notices changed jobs
10170
  _CLIENT_CONNECT_TIMEOUT = 20.0
10171
  _CLIENT_CONFIRM_TIMEOUT = 60.0
10172

    
10173
  @classmethod
10174
  def _NotifyUsingSocket(cls, cb, errcls):
10175
    """Opens a Unix socket and waits for another program to connect.
10176

10177
    @type cb: callable
10178
    @param cb: Callback to send socket name to client
10179
    @type errcls: class
10180
    @param errcls: Exception class to use for errors
10181

10182
    """
10183
    # Using a temporary directory as there's no easy way to create temporary
10184
    # sockets without writing a custom loop around tempfile.mktemp and
10185
    # socket.bind
10186
    tmpdir = tempfile.mkdtemp()
10187
    try:
10188
      tmpsock = utils.PathJoin(tmpdir, "sock")
10189

    
10190
      logging.debug("Creating temporary socket at %s", tmpsock)
10191
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
10192
      try:
10193
        sock.bind(tmpsock)
10194
        sock.listen(1)
10195

    
10196
        # Send details to client
10197
        cb(tmpsock)
10198

    
10199
        # Wait for client to connect before continuing
10200
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
10201
        try:
10202
          (conn, _) = sock.accept()
10203
        except socket.error, err:
10204
          raise errcls("Client didn't connect in time (%s)" % err)
10205
      finally:
10206
        sock.close()
10207
    finally:
10208
      # Remove as soon as client is connected
10209
      shutil.rmtree(tmpdir)
10210

    
10211
    # Wait for client to close
10212
    try:
10213
      try:
10214
        # pylint: disable-msg=E1101
10215
        # Instance of '_socketobject' has no ... member
10216
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
10217
        conn.recv(1)
10218
      except socket.error, err:
10219
        raise errcls("Client failed to confirm notification (%s)" % err)
10220
    finally:
10221
      conn.close()
10222

    
10223
  def _SendNotification(self, test, arg, sockname):
10224
    """Sends a notification to the client.
10225

10226
    @type test: string
10227
    @param test: Test name
10228
    @param arg: Test argument (depends on test)
10229
    @type sockname: string
10230
    @param sockname: Socket path
10231

10232
    """
10233
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
10234

    
10235
  def _Notify(self, prereq, test, arg):
10236
    """Notifies the client of a test.
10237

10238
    @type prereq: bool
10239
    @param prereq: Whether this is a prereq-phase test
10240
    @type test: string
10241
    @param test: Test name
10242
    @param arg: Test argument (depends on test)
10243

10244
    """
10245
    if prereq:
10246
      errcls = errors.OpPrereqError
10247
    else:
10248
      errcls = errors.OpExecError
10249

    
10250
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
10251
                                                  test, arg),
10252
                                   errcls)
10253

    
10254
  def CheckArguments(self):
10255
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
10256
    self.expandnames_calls = 0
10257

    
10258
  def ExpandNames(self):
10259
    checkargs_calls = getattr(self, "checkargs_calls", 0)
10260
    if checkargs_calls < 1:
10261
      raise errors.ProgrammerError("CheckArguments was not called")
10262

    
10263
    self.expandnames_calls += 1
10264

    
10265
    if self.op.notify_waitlock:
10266
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
10267

    
10268
    self.LogInfo("Expanding names")
10269

    
10270
    # Get lock on master node (just to get a lock, not for a particular reason)
10271
    self.needed_locks = {
10272
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
10273
      }
10274

    
10275
  def Exec(self, feedback_fn):
10276
    if self.expandnames_calls < 1:
10277
      raise errors.ProgrammerError("ExpandNames was not called")
10278

    
10279
    if self.op.notify_exec:
10280
      self._Notify(False, constants.JQT_EXEC, None)
10281

    
10282
    self.LogInfo("Executing")
10283

    
10284
    if self.op.log_messages:
10285
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
10286
      for idx, msg in enumerate(self.op.log_messages):
10287
        self.LogInfo("Sending log message %s", idx + 1)
10288
        feedback_fn(constants.JQT_MSGPREFIX + msg)
10289
        # Report how many test messages have been sent
10290
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
10291

    
10292
    if self.op.fail:
10293
      raise errors.OpExecError("Opcode failure was requested")
10294

    
10295
    return True
10296

    
10297

    
10298
class IAllocator(object):
10299
  """IAllocator framework.
10300

10301
  An IAllocator instance has three sets of attributes:
10302
    - cfg that is needed to query the cluster
10303
    - input data (all members of the _KEYS class attribute are required)
10304
    - four buffer attributes (in|out_data|text), that represent the
10305
      input (to the external script) in text and data structure format,
10306
      and the output from it, again in two formats
10307
    - the result variables from the script (success, info, nodes) for
10308
      easy usage
10309

10310
  """
10311
  # pylint: disable-msg=R0902
10312
  # lots of instance attributes
10313
  _ALLO_KEYS = [
10314
    "name", "mem_size", "disks", "disk_template",
10315
    "os", "tags", "nics", "vcpus", "hypervisor",
10316
    ]
10317
  _RELO_KEYS = [
10318
    "name", "relocate_from",
10319
    ]
10320
  _EVAC_KEYS = [
10321
    "evac_nodes",
10322
    ]
10323

    
10324
  def __init__(self, cfg, rpc, mode, **kwargs):
10325
    self.cfg = cfg
10326
    self.rpc = rpc
10327
    # init buffer variables
10328
    self.in_text = self.out_text = self.in_data = self.out_data = None
10329
    # init all input fields so that pylint is happy
10330
    self.mode = mode
10331
    self.mem_size = self.disks = self.disk_template = None
10332
    self.os = self.tags = self.nics = self.vcpus = None
10333
    self.hypervisor = None
10334
    self.relocate_from = None
10335
    self.name = None
10336
    self.evac_nodes = None
10337
    # computed fields
10338
    self.required_nodes = None
10339
    # init result fields
10340
    self.success = self.info = self.result = None
10341
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10342
      keyset = self._ALLO_KEYS
10343
      fn = self._AddNewInstance
10344
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10345
      keyset = self._RELO_KEYS
10346
      fn = self._AddRelocateInstance
10347
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10348
      keyset = self._EVAC_KEYS
10349
      fn = self._AddEvacuateNodes
10350
    else:
10351
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
10352
                                   " IAllocator" % self.mode)
10353
    for key in kwargs:
10354
      if key not in keyset:
10355
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
10356
                                     " IAllocator" % key)
10357
      setattr(self, key, kwargs[key])
10358

    
10359
    for key in keyset:
10360
      if key not in kwargs:
10361
        raise errors.ProgrammerError("Missing input parameter '%s' to"
10362
                                     " IAllocator" % key)
10363
    self._BuildInputData(fn)
10364

    
10365
  def _ComputeClusterData(self):
10366
    """Compute the generic allocator input data.
10367

10368
    This is the data that is independent of the actual operation.
10369

10370
    """
10371
    cfg = self.cfg
10372
    cluster_info = cfg.GetClusterInfo()
10373
    # cluster data
10374
    data = {
10375
      "version": constants.IALLOCATOR_VERSION,
10376
      "cluster_name": cfg.GetClusterName(),
10377
      "cluster_tags": list(cluster_info.GetTags()),
10378
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
10379
      # we don't have job IDs
10380
      }
10381
    iinfo = cfg.GetAllInstancesInfo().values()
10382
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
10383

    
10384
    # node data
10385
    node_list = cfg.GetNodeList()
10386

    
10387
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10388
      hypervisor_name = self.hypervisor
10389
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10390
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
10391
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10392
      hypervisor_name = cluster_info.enabled_hypervisors[0]
10393

    
10394
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
10395
                                        hypervisor_name)
10396
    node_iinfo = \
10397
      self.rpc.call_all_instances_info(node_list,
10398
                                       cluster_info.enabled_hypervisors)
10399

    
10400
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
10401

    
10402
    data["nodes"] = self._ComputeNodeData(cfg, node_data, node_iinfo, i_list)
10403

    
10404
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
10405

    
10406
    self.in_data = data
10407

    
10408
  @staticmethod
10409
  def _ComputeNodeGroupData(cfg):
10410
    """Compute node groups data.
10411

10412
    """
10413
    ng = {}
10414
    for guuid, gdata in cfg.GetAllNodeGroupsInfo().items():
10415
      ng[guuid] = { "name": gdata.name }
10416
    return ng
10417

    
10418
  @staticmethod
10419
  def _ComputeNodeData(cfg, node_data, node_iinfo, i_list):
10420
    """Compute global node data.
10421

10422
    """
10423
    node_results = {}
10424
    for nname, nresult in node_data.items():
10425
      # first fill in static (config-based) values
10426
      ninfo = cfg.GetNodeInfo(nname)
10427
      pnr = {
10428
        "tags": list(ninfo.GetTags()),
10429
        "primary_ip": ninfo.primary_ip,
10430
        "secondary_ip": ninfo.secondary_ip,
10431
        "offline": ninfo.offline,
10432
        "drained": ninfo.drained,
10433
        "master_candidate": ninfo.master_candidate,
10434
        "group": ninfo.group,
10435
        "master_capable": ninfo.master_capable,
10436
        "vm_capable": ninfo.vm_capable,
10437
        }
10438

    
10439
      if not (ninfo.offline or ninfo.drained):
10440
        nresult.Raise("Can't get data for node %s" % nname)
10441
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
10442
                                nname)
10443
        remote_info = nresult.payload
10444

    
10445
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
10446
                     'vg_size', 'vg_free', 'cpu_total']:
10447
          if attr not in remote_info:
10448
            raise errors.OpExecError("Node '%s' didn't return attribute"
10449
                                     " '%s'" % (nname, attr))
10450
          if not isinstance(remote_info[attr], int):
10451
            raise errors.OpExecError("Node '%s' returned invalid value"
10452
                                     " for '%s': %s" %
10453
                                     (nname, attr, remote_info[attr]))
10454
        # compute memory used by primary instances
10455
        i_p_mem = i_p_up_mem = 0
10456
        for iinfo, beinfo in i_list:
10457
          if iinfo.primary_node == nname:
10458
            i_p_mem += beinfo[constants.BE_MEMORY]
10459
            if iinfo.name not in node_iinfo[nname].payload:
10460
              i_used_mem = 0
10461
            else:
10462
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
10463
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
10464
            remote_info['memory_free'] -= max(0, i_mem_diff)
10465

    
10466
            if iinfo.admin_up:
10467
              i_p_up_mem += beinfo[constants.BE_MEMORY]
10468

    
10469
        # compute memory used by instances
10470
        pnr_dyn = {
10471
          "total_memory": remote_info['memory_total'],
10472
          "reserved_memory": remote_info['memory_dom0'],
10473
          "free_memory": remote_info['memory_free'],
10474
          "total_disk": remote_info['vg_size'],
10475
          "free_disk": remote_info['vg_free'],
10476
          "total_cpus": remote_info['cpu_total'],
10477
          "i_pri_memory": i_p_mem,
10478
          "i_pri_up_memory": i_p_up_mem,
10479
          }
10480
        pnr.update(pnr_dyn)
10481

    
10482
      node_results[nname] = pnr
10483

    
10484
    return node_results
10485

    
10486
  @staticmethod
10487
  def _ComputeInstanceData(cluster_info, i_list):
10488
    """Compute global instance data.
10489

10490
    """
10491
    instance_data = {}
10492
    for iinfo, beinfo in i_list:
10493
      nic_data = []
10494
      for nic in iinfo.nics:
10495
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
10496
        nic_dict = {"mac": nic.mac,
10497
                    "ip": nic.ip,
10498
                    "mode": filled_params[constants.NIC_MODE],
10499
                    "link": filled_params[constants.NIC_LINK],
10500
                   }
10501
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
10502
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
10503
        nic_data.append(nic_dict)
10504
      pir = {
10505
        "tags": list(iinfo.GetTags()),
10506
        "admin_up": iinfo.admin_up,
10507
        "vcpus": beinfo[constants.BE_VCPUS],
10508
        "memory": beinfo[constants.BE_MEMORY],
10509
        "os": iinfo.os,
10510
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
10511
        "nics": nic_data,
10512
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
10513
        "disk_template": iinfo.disk_template,
10514
        "hypervisor": iinfo.hypervisor,
10515
        }
10516
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
10517
                                                 pir["disks"])
10518
      instance_data[iinfo.name] = pir
10519

    
10520
    return instance_data
10521

    
10522
  def _AddNewInstance(self):
10523
    """Add new instance data to allocator structure.
10524

10525
    This in combination with _AllocatorGetClusterData will create the
10526
    correct structure needed as input for the allocator.
10527

10528
    The checks for the completeness of the opcode must have already been
10529
    done.
10530

10531
    """
10532
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
10533

    
10534
    if self.disk_template in constants.DTS_NET_MIRROR:
10535
      self.required_nodes = 2
10536
    else:
10537
      self.required_nodes = 1
10538
    request = {
10539
      "name": self.name,
10540
      "disk_template": self.disk_template,
10541
      "tags": self.tags,
10542
      "os": self.os,
10543
      "vcpus": self.vcpus,
10544
      "memory": self.mem_size,
10545
      "disks": self.disks,
10546
      "disk_space_total": disk_space,
10547
      "nics": self.nics,
10548
      "required_nodes": self.required_nodes,
10549
      }
10550
    return request
10551

    
10552
  def _AddRelocateInstance(self):
10553
    """Add relocate instance data to allocator structure.
10554

10555
    This in combination with _IAllocatorGetClusterData will create the
10556
    correct structure needed as input for the allocator.
10557

10558
    The checks for the completeness of the opcode must have already been
10559
    done.
10560

10561
    """
10562
    instance = self.cfg.GetInstanceInfo(self.name)
10563
    if instance is None:
10564
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
10565
                                   " IAllocator" % self.name)
10566

    
10567
    if instance.disk_template not in constants.DTS_NET_MIRROR:
10568
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
10569
                                 errors.ECODE_INVAL)
10570

    
10571
    if len(instance.secondary_nodes) != 1:
10572
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
10573
                                 errors.ECODE_STATE)
10574

    
10575
    self.required_nodes = 1
10576
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
10577
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
10578

    
10579
    request = {
10580
      "name": self.name,
10581
      "disk_space_total": disk_space,
10582
      "required_nodes": self.required_nodes,
10583
      "relocate_from": self.relocate_from,
10584
      }
10585
    return request
10586

    
10587
  def _AddEvacuateNodes(self):
10588
    """Add evacuate nodes data to allocator structure.
10589

10590
    """
10591
    request = {
10592
      "evac_nodes": self.evac_nodes
10593
      }
10594
    return request
10595

    
10596
  def _BuildInputData(self, fn):
10597
    """Build input data structures.
10598

10599
    """
10600
    self._ComputeClusterData()
10601

    
10602
    request = fn()
10603
    request["type"] = self.mode
10604
    self.in_data["request"] = request
10605

    
10606
    self.in_text = serializer.Dump(self.in_data)
10607

    
10608
  def Run(self, name, validate=True, call_fn=None):
10609
    """Run an instance allocator and return the results.
10610

10611
    """
10612
    if call_fn is None:
10613
      call_fn = self.rpc.call_iallocator_runner
10614

    
10615
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
10616
    result.Raise("Failure while running the iallocator script")
10617

    
10618
    self.out_text = result.payload
10619
    if validate:
10620
      self._ValidateResult()
10621

    
10622
  def _ValidateResult(self):
10623
    """Process the allocator results.
10624

10625
    This will process and if successful save the result in
10626
    self.out_data and the other parameters.
10627

10628
    """
10629
    try:
10630
      rdict = serializer.Load(self.out_text)
10631
    except Exception, err:
10632
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
10633

    
10634
    if not isinstance(rdict, dict):
10635
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
10636

    
10637
    # TODO: remove backwards compatiblity in later versions
10638
    if "nodes" in rdict and "result" not in rdict:
10639
      rdict["result"] = rdict["nodes"]
10640
      del rdict["nodes"]
10641

    
10642
    for key in "success", "info", "result":
10643
      if key not in rdict:
10644
        raise errors.OpExecError("Can't parse iallocator results:"
10645
                                 " missing key '%s'" % key)
10646
      setattr(self, key, rdict[key])
10647

    
10648
    if not isinstance(rdict["result"], list):
10649
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
10650
                               " is not a list")
10651
    self.out_data = rdict
10652

    
10653

    
10654
class LUTestAllocator(NoHooksLU):
10655
  """Run allocator tests.
10656

10657
  This LU runs the allocator tests
10658

10659
  """
10660
  _OP_PARAMS = [
10661
    ("direction", ht.NoDefault,
10662
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS)),
10663
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES)),
10664
    ("name", ht.NoDefault, ht.TNonEmptyString),
10665
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
10666
      ht.TDictOf(ht.TElemOf(["mac", "ip", "bridge"]),
10667
               ht.TOr(ht.TNone, ht.TNonEmptyString))))),
10668
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList)),
10669
    ("hypervisor", None, ht.TMaybeString),
10670
    ("allocator", None, ht.TMaybeString),
10671
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
10672
    ("mem_size", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
10673
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
10674
    ("os", None, ht.TMaybeString),
10675
    ("disk_template", None, ht.TMaybeString),
10676
    ("evac_nodes", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString))),
10677
    ]
10678

    
10679
  def CheckPrereq(self):
10680
    """Check prerequisites.
10681

10682
    This checks the opcode parameters depending on the director and mode test.
10683

10684
    """
10685
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10686
      for attr in ["mem_size", "disks", "disk_template",
10687
                   "os", "tags", "nics", "vcpus"]:
10688
        if not hasattr(self.op, attr):
10689
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
10690
                                     attr, errors.ECODE_INVAL)
10691
      iname = self.cfg.ExpandInstanceName(self.op.name)
10692
      if iname is not None:
10693
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
10694
                                   iname, errors.ECODE_EXISTS)
10695
      if not isinstance(self.op.nics, list):
10696
        raise errors.OpPrereqError("Invalid parameter 'nics'",
10697
                                   errors.ECODE_INVAL)
10698
      if not isinstance(self.op.disks, list):
10699
        raise errors.OpPrereqError("Invalid parameter 'disks'",
10700
                                   errors.ECODE_INVAL)
10701
      for row in self.op.disks:
10702
        if (not isinstance(row, dict) or
10703
            "size" not in row or
10704
            not isinstance(row["size"], int) or
10705
            "mode" not in row or
10706
            row["mode"] not in ['r', 'w']):
10707
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
10708
                                     " parameter", errors.ECODE_INVAL)
10709
      if self.op.hypervisor is None:
10710
        self.op.hypervisor = self.cfg.GetHypervisorType()
10711
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10712
      fname = _ExpandInstanceName(self.cfg, self.op.name)
10713
      self.op.name = fname
10714
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
10715
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10716
      if not hasattr(self.op, "evac_nodes"):
10717
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
10718
                                   " opcode input", errors.ECODE_INVAL)
10719
    else:
10720
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
10721
                                 self.op.mode, errors.ECODE_INVAL)
10722

    
10723
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
10724
      if self.op.allocator is None:
10725
        raise errors.OpPrereqError("Missing allocator name",
10726
                                   errors.ECODE_INVAL)
10727
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
10728
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
10729
                                 self.op.direction, errors.ECODE_INVAL)
10730

    
10731
  def Exec(self, feedback_fn):
10732
    """Run the allocator test.
10733

10734
    """
10735
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10736
      ial = IAllocator(self.cfg, self.rpc,
10737
                       mode=self.op.mode,
10738
                       name=self.op.name,
10739
                       mem_size=self.op.mem_size,
10740
                       disks=self.op.disks,
10741
                       disk_template=self.op.disk_template,
10742
                       os=self.op.os,
10743
                       tags=self.op.tags,
10744
                       nics=self.op.nics,
10745
                       vcpus=self.op.vcpus,
10746
                       hypervisor=self.op.hypervisor,
10747
                       )
10748
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10749
      ial = IAllocator(self.cfg, self.rpc,
10750
                       mode=self.op.mode,
10751
                       name=self.op.name,
10752
                       relocate_from=list(self.relocate_from),
10753
                       )
10754
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10755
      ial = IAllocator(self.cfg, self.rpc,
10756
                       mode=self.op.mode,
10757
                       evac_nodes=self.op.evac_nodes)
10758
    else:
10759
      raise errors.ProgrammerError("Uncatched mode %s in"
10760
                                   " LUTestAllocator.Exec", self.op.mode)
10761

    
10762
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
10763
      result = ial.in_text
10764
    else:
10765
      ial.Run(self.op.allocator, validate=False)
10766
      result = ial.out_text
10767
    return result