Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 614e7e26

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

    
5781
    if instance.admin_up:
5782
      # check memory requirements on the secondary node
5783
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5784
                           instance.name, bep[constants.BE_MEMORY],
5785
                           instance.hypervisor)
5786
    else:
5787
      self.LogInfo("Not checking memory on the secondary node as"
5788
                   " instance will not be started")
5789

    
5790
    # check bridge existance
5791
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5792

    
5793
  def Exec(self, feedback_fn):
5794
    """Move an instance.
5795

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

5799
    """
5800
    instance = self.instance
5801

    
5802
    source_node = instance.primary_node
5803
    target_node = self.target_node
5804

    
5805
    self.LogInfo("Shutting down instance %s on source node %s",
5806
                 instance.name, source_node)
5807

    
5808
    result = self.rpc.call_instance_shutdown(source_node, instance,
5809
                                             self.op.shutdown_timeout)
5810
    msg = result.fail_msg
5811
    if msg:
5812
      if self.op.ignore_consistency:
5813
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5814
                             " Proceeding anyway. Please make sure node"
5815
                             " %s is down. Error details: %s",
5816
                             instance.name, source_node, source_node, msg)
5817
      else:
5818
        raise errors.OpExecError("Could not shutdown instance %s on"
5819
                                 " node %s: %s" %
5820
                                 (instance.name, source_node, msg))
5821

    
5822
    # create the target disks
5823
    try:
5824
      _CreateDisks(self, instance, target_node=target_node)
5825
    except errors.OpExecError:
5826
      self.LogWarning("Device creation failed, reverting...")
5827
      try:
5828
        _RemoveDisks(self, instance, target_node=target_node)
5829
      finally:
5830
        self.cfg.ReleaseDRBDMinors(instance.name)
5831
        raise
5832

    
5833
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5834

    
5835
    errs = []
5836
    # activate, get path, copy the data over
5837
    for idx, disk in enumerate(instance.disks):
5838
      self.LogInfo("Copying data for disk %d", idx)
5839
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5840
                                               instance.name, True)
5841
      if result.fail_msg:
5842
        self.LogWarning("Can't assemble newly created disk %d: %s",
5843
                        idx, result.fail_msg)
5844
        errs.append(result.fail_msg)
5845
        break
5846
      dev_path = result.payload
5847
      result = self.rpc.call_blockdev_export(source_node, disk,
5848
                                             target_node, dev_path,
5849
                                             cluster_name)
5850
      if result.fail_msg:
5851
        self.LogWarning("Can't copy data over for disk %d: %s",
5852
                        idx, result.fail_msg)
5853
        errs.append(result.fail_msg)
5854
        break
5855

    
5856
    if errs:
5857
      self.LogWarning("Some disks failed to copy, aborting")
5858
      try:
5859
        _RemoveDisks(self, instance, target_node=target_node)
5860
      finally:
5861
        self.cfg.ReleaseDRBDMinors(instance.name)
5862
        raise errors.OpExecError("Errors during disk copy: %s" %
5863
                                 (",".join(errs),))
5864

    
5865
    instance.primary_node = target_node
5866
    self.cfg.Update(instance, feedback_fn)
5867

    
5868
    self.LogInfo("Removing the disks on the original node")
5869
    _RemoveDisks(self, instance, target_node=source_node)
5870

    
5871
    # Only start the instance if it's marked as up
5872
    if instance.admin_up:
5873
      self.LogInfo("Starting instance %s on node %s",
5874
                   instance.name, target_node)
5875

    
5876
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5877
                                           ignore_secondaries=True)
5878
      if not disks_ok:
5879
        _ShutdownInstanceDisks(self, instance)
5880
        raise errors.OpExecError("Can't activate the instance's disks")
5881

    
5882
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5883
      msg = result.fail_msg
5884
      if msg:
5885
        _ShutdownInstanceDisks(self, instance)
5886
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5887
                                 (instance.name, target_node, msg))
5888

    
5889

    
5890
class LUMigrateNode(LogicalUnit):
5891
  """Migrate all instances from a node.
5892

5893
  """
5894
  HPATH = "node-migrate"
5895
  HTYPE = constants.HTYPE_NODE
5896
  _OP_PARAMS = [
5897
    _PNodeName,
5898
    _PMigrationMode,
5899
    _PMigrationLive,
5900
    ]
5901
  REQ_BGL = False
5902

    
5903
  def ExpandNames(self):
5904
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5905

    
5906
    self.needed_locks = {
5907
      locking.LEVEL_NODE: [self.op.node_name],
5908
      }
5909

    
5910
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5911

    
5912
    # Create tasklets for migrating instances for all instances on this node
5913
    names = []
5914
    tasklets = []
5915

    
5916
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5917
      logging.debug("Migrating instance %s", inst.name)
5918
      names.append(inst.name)
5919

    
5920
      tasklets.append(TLMigrateInstance(self, inst.name, False))
5921

    
5922
    self.tasklets = tasklets
5923

    
5924
    # Declare instance locks
5925
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5926

    
5927
  def DeclareLocks(self, level):
5928
    if level == locking.LEVEL_NODE:
5929
      self._LockInstancesNodes()
5930

    
5931
  def BuildHooksEnv(self):
5932
    """Build hooks env.
5933

5934
    This runs on the master, the primary and all the secondaries.
5935

5936
    """
5937
    env = {
5938
      "NODE_NAME": self.op.node_name,
5939
      }
5940

    
5941
    nl = [self.cfg.GetMasterNode()]
5942

    
5943
    return (env, nl, nl)
5944

    
5945

    
5946
class TLMigrateInstance(Tasklet):
5947
  """Tasklet class for instance migration.
5948

5949
  @type live: boolean
5950
  @ivar live: whether the migration will be done live or non-live;
5951
      this variable is initalized only after CheckPrereq has run
5952

5953
  """
5954
  def __init__(self, lu, instance_name, cleanup):
5955
    """Initializes this class.
5956

5957
    """
5958
    Tasklet.__init__(self, lu)
5959

    
5960
    # Parameters
5961
    self.instance_name = instance_name
5962
    self.cleanup = cleanup
5963
    self.live = False # will be overridden later
5964

    
5965
  def CheckPrereq(self):
5966
    """Check prerequisites.
5967

5968
    This checks that the instance is in the cluster.
5969

5970
    """
5971
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
5972
    instance = self.cfg.GetInstanceInfo(instance_name)
5973
    assert instance is not None
5974

    
5975
    if instance.disk_template != constants.DT_DRBD8:
5976
      raise errors.OpPrereqError("Instance's disk layout is not"
5977
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5978

    
5979
    secondary_nodes = instance.secondary_nodes
5980
    if not secondary_nodes:
5981
      raise errors.ConfigurationError("No secondary node but using"
5982
                                      " drbd8 disk template")
5983

    
5984
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5985

    
5986
    target_node = secondary_nodes[0]
5987
    # check memory requirements on the secondary node
5988
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
5989
                         instance.name, i_be[constants.BE_MEMORY],
5990
                         instance.hypervisor)
5991

    
5992
    # check bridge existance
5993
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
5994

    
5995
    if not self.cleanup:
5996
      _CheckNodeNotDrained(self.lu, target_node)
5997
      result = self.rpc.call_instance_migratable(instance.primary_node,
5998
                                                 instance)
5999
      result.Raise("Can't migrate, please use failover",
6000
                   prereq=True, ecode=errors.ECODE_STATE)
6001

    
6002
    self.instance = instance
6003

    
6004
    if self.lu.op.live is not None and self.lu.op.mode is not None:
6005
      raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
6006
                                 " parameters are accepted",
6007
                                 errors.ECODE_INVAL)
6008
    if self.lu.op.live is not None:
6009
      if self.lu.op.live:
6010
        self.lu.op.mode = constants.HT_MIGRATION_LIVE
6011
      else:
6012
        self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6013
      # reset the 'live' parameter to None so that repeated
6014
      # invocations of CheckPrereq do not raise an exception
6015
      self.lu.op.live = None
6016
    elif self.lu.op.mode is None:
6017
      # read the default value from the hypervisor
6018
      i_hv = self.cfg.GetClusterInfo().FillHV(instance, skip_globals=False)
6019
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6020

    
6021
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6022

    
6023
  def _WaitUntilSync(self):
6024
    """Poll with custom rpc for disk sync.
6025

6026
    This uses our own step-based rpc call.
6027

6028
    """
6029
    self.feedback_fn("* wait until resync is done")
6030
    all_done = False
6031
    while not all_done:
6032
      all_done = True
6033
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6034
                                            self.nodes_ip,
6035
                                            self.instance.disks)
6036
      min_percent = 100
6037
      for node, nres in result.items():
6038
        nres.Raise("Cannot resync disks on node %s" % node)
6039
        node_done, node_percent = nres.payload
6040
        all_done = all_done and node_done
6041
        if node_percent is not None:
6042
          min_percent = min(min_percent, node_percent)
6043
      if not all_done:
6044
        if min_percent < 100:
6045
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6046
        time.sleep(2)
6047

    
6048
  def _EnsureSecondary(self, node):
6049
    """Demote a node to secondary.
6050

6051
    """
6052
    self.feedback_fn("* switching node %s to secondary mode" % node)
6053

    
6054
    for dev in self.instance.disks:
6055
      self.cfg.SetDiskID(dev, node)
6056

    
6057
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6058
                                          self.instance.disks)
6059
    result.Raise("Cannot change disk to secondary on node %s" % node)
6060

    
6061
  def _GoStandalone(self):
6062
    """Disconnect from the network.
6063

6064
    """
6065
    self.feedback_fn("* changing into standalone mode")
6066
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6067
                                               self.instance.disks)
6068
    for node, nres in result.items():
6069
      nres.Raise("Cannot disconnect disks node %s" % node)
6070

    
6071
  def _GoReconnect(self, multimaster):
6072
    """Reconnect to the network.
6073

6074
    """
6075
    if multimaster:
6076
      msg = "dual-master"
6077
    else:
6078
      msg = "single-master"
6079
    self.feedback_fn("* changing disks into %s mode" % msg)
6080
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6081
                                           self.instance.disks,
6082
                                           self.instance.name, multimaster)
6083
    for node, nres in result.items():
6084
      nres.Raise("Cannot change disks config on node %s" % node)
6085

    
6086
  def _ExecCleanup(self):
6087
    """Try to cleanup after a failed migration.
6088

6089
    The cleanup is done by:
6090
      - check that the instance is running only on one node
6091
        (and update the config if needed)
6092
      - change disks on its secondary node to secondary
6093
      - wait until disks are fully synchronized
6094
      - disconnect from the network
6095
      - change disks into single-master mode
6096
      - wait again until disks are fully synchronized
6097

6098
    """
6099
    instance = self.instance
6100
    target_node = self.target_node
6101
    source_node = self.source_node
6102

    
6103
    # check running on only one node
6104
    self.feedback_fn("* checking where the instance actually runs"
6105
                     " (if this hangs, the hypervisor might be in"
6106
                     " a bad state)")
6107
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
6108
    for node, result in ins_l.items():
6109
      result.Raise("Can't contact node %s" % node)
6110

    
6111
    runningon_source = instance.name in ins_l[source_node].payload
6112
    runningon_target = instance.name in ins_l[target_node].payload
6113

    
6114
    if runningon_source and runningon_target:
6115
      raise errors.OpExecError("Instance seems to be running on two nodes,"
6116
                               " or the hypervisor is confused. You will have"
6117
                               " to ensure manually that it runs only on one"
6118
                               " and restart this operation.")
6119

    
6120
    if not (runningon_source or runningon_target):
6121
      raise errors.OpExecError("Instance does not seem to be running at all."
6122
                               " In this case, it's safer to repair by"
6123
                               " running 'gnt-instance stop' to ensure disk"
6124
                               " shutdown, and then restarting it.")
6125

    
6126
    if runningon_target:
6127
      # the migration has actually succeeded, we need to update the config
6128
      self.feedback_fn("* instance running on secondary node (%s),"
6129
                       " updating config" % target_node)
6130
      instance.primary_node = target_node
6131
      self.cfg.Update(instance, self.feedback_fn)
6132
      demoted_node = source_node
6133
    else:
6134
      self.feedback_fn("* instance confirmed to be running on its"
6135
                       " primary node (%s)" % source_node)
6136
      demoted_node = target_node
6137

    
6138
    self._EnsureSecondary(demoted_node)
6139
    try:
6140
      self._WaitUntilSync()
6141
    except errors.OpExecError:
6142
      # we ignore here errors, since if the device is standalone, it
6143
      # won't be able to sync
6144
      pass
6145
    self._GoStandalone()
6146
    self._GoReconnect(False)
6147
    self._WaitUntilSync()
6148

    
6149
    self.feedback_fn("* done")
6150

    
6151
  def _RevertDiskStatus(self):
6152
    """Try to revert the disk status after a failed migration.
6153

6154
    """
6155
    target_node = self.target_node
6156
    try:
6157
      self._EnsureSecondary(target_node)
6158
      self._GoStandalone()
6159
      self._GoReconnect(False)
6160
      self._WaitUntilSync()
6161
    except errors.OpExecError, err:
6162
      self.lu.LogWarning("Migration failed and I can't reconnect the"
6163
                         " drives: error '%s'\n"
6164
                         "Please look and recover the instance status" %
6165
                         str(err))
6166

    
6167
  def _AbortMigration(self):
6168
    """Call the hypervisor code to abort a started migration.
6169

6170
    """
6171
    instance = self.instance
6172
    target_node = self.target_node
6173
    migration_info = self.migration_info
6174

    
6175
    abort_result = self.rpc.call_finalize_migration(target_node,
6176
                                                    instance,
6177
                                                    migration_info,
6178
                                                    False)
6179
    abort_msg = abort_result.fail_msg
6180
    if abort_msg:
6181
      logging.error("Aborting migration failed on target node %s: %s",
6182
                    target_node, abort_msg)
6183
      # Don't raise an exception here, as we stil have to try to revert the
6184
      # disk status, even if this step failed.
6185

    
6186
  def _ExecMigration(self):
6187
    """Migrate an instance.
6188

6189
    The migrate is done by:
6190
      - change the disks into dual-master mode
6191
      - wait until disks are fully synchronized again
6192
      - migrate the instance
6193
      - change disks on the new secondary node (the old primary) to secondary
6194
      - wait until disks are fully synchronized
6195
      - change disks into single-master mode
6196

6197
    """
6198
    instance = self.instance
6199
    target_node = self.target_node
6200
    source_node = self.source_node
6201

    
6202
    self.feedback_fn("* checking disk consistency between source and target")
6203
    for dev in instance.disks:
6204
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6205
        raise errors.OpExecError("Disk %s is degraded or not fully"
6206
                                 " synchronized on target node,"
6207
                                 " aborting migrate." % dev.iv_name)
6208

    
6209
    # First get the migration information from the remote node
6210
    result = self.rpc.call_migration_info(source_node, instance)
6211
    msg = result.fail_msg
6212
    if msg:
6213
      log_err = ("Failed fetching source migration information from %s: %s" %
6214
                 (source_node, msg))
6215
      logging.error(log_err)
6216
      raise errors.OpExecError(log_err)
6217

    
6218
    self.migration_info = migration_info = result.payload
6219

    
6220
    # Then switch the disks to master/master mode
6221
    self._EnsureSecondary(target_node)
6222
    self._GoStandalone()
6223
    self._GoReconnect(True)
6224
    self._WaitUntilSync()
6225

    
6226
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6227
    result = self.rpc.call_accept_instance(target_node,
6228
                                           instance,
6229
                                           migration_info,
6230
                                           self.nodes_ip[target_node])
6231

    
6232
    msg = result.fail_msg
6233
    if msg:
6234
      logging.error("Instance pre-migration failed, trying to revert"
6235
                    " disk status: %s", msg)
6236
      self.feedback_fn("Pre-migration failed, aborting")
6237
      self._AbortMigration()
6238
      self._RevertDiskStatus()
6239
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6240
                               (instance.name, msg))
6241

    
6242
    self.feedback_fn("* migrating instance to %s" % target_node)
6243
    time.sleep(10)
6244
    result = self.rpc.call_instance_migrate(source_node, instance,
6245
                                            self.nodes_ip[target_node],
6246
                                            self.live)
6247
    msg = result.fail_msg
6248
    if msg:
6249
      logging.error("Instance migration failed, trying to revert"
6250
                    " disk status: %s", msg)
6251
      self.feedback_fn("Migration failed, aborting")
6252
      self._AbortMigration()
6253
      self._RevertDiskStatus()
6254
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6255
                               (instance.name, msg))
6256
    time.sleep(10)
6257

    
6258
    instance.primary_node = target_node
6259
    # distribute new instance config to the other nodes
6260
    self.cfg.Update(instance, self.feedback_fn)
6261

    
6262
    result = self.rpc.call_finalize_migration(target_node,
6263
                                              instance,
6264
                                              migration_info,
6265
                                              True)
6266
    msg = result.fail_msg
6267
    if msg:
6268
      logging.error("Instance migration succeeded, but finalization failed:"
6269
                    " %s", msg)
6270
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6271
                               msg)
6272

    
6273
    self._EnsureSecondary(source_node)
6274
    self._WaitUntilSync()
6275
    self._GoStandalone()
6276
    self._GoReconnect(False)
6277
    self._WaitUntilSync()
6278

    
6279
    self.feedback_fn("* done")
6280

    
6281
  def Exec(self, feedback_fn):
6282
    """Perform the migration.
6283

6284
    """
6285
    feedback_fn("Migrating instance %s" % self.instance.name)
6286

    
6287
    self.feedback_fn = feedback_fn
6288

    
6289
    self.source_node = self.instance.primary_node
6290
    self.target_node = self.instance.secondary_nodes[0]
6291
    self.all_nodes = [self.source_node, self.target_node]
6292
    self.nodes_ip = {
6293
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6294
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6295
      }
6296

    
6297
    if self.cleanup:
6298
      return self._ExecCleanup()
6299
    else:
6300
      return self._ExecMigration()
6301

    
6302

    
6303
def _CreateBlockDev(lu, node, instance, device, force_create,
6304
                    info, force_open):
6305
  """Create a tree of block devices on a given node.
6306

6307
  If this device type has to be created on secondaries, create it and
6308
  all its children.
6309

6310
  If not, just recurse to children keeping the same 'force' value.
6311

6312
  @param lu: the lu on whose behalf we execute
6313
  @param node: the node on which to create the device
6314
  @type instance: L{objects.Instance}
6315
  @param instance: the instance which owns the device
6316
  @type device: L{objects.Disk}
6317
  @param device: the device to create
6318
  @type force_create: boolean
6319
  @param force_create: whether to force creation of this device; this
6320
      will be change to True whenever we find a device which has
6321
      CreateOnSecondary() attribute
6322
  @param info: the extra 'metadata' we should attach to the device
6323
      (this will be represented as a LVM tag)
6324
  @type force_open: boolean
6325
  @param force_open: this parameter will be passes to the
6326
      L{backend.BlockdevCreate} function where it specifies
6327
      whether we run on primary or not, and it affects both
6328
      the child assembly and the device own Open() execution
6329

6330
  """
6331
  if device.CreateOnSecondary():
6332
    force_create = True
6333

    
6334
  if device.children:
6335
    for child in device.children:
6336
      _CreateBlockDev(lu, node, instance, child, force_create,
6337
                      info, force_open)
6338

    
6339
  if not force_create:
6340
    return
6341

    
6342
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6343

    
6344

    
6345
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6346
  """Create a single block device on a given node.
6347

6348
  This will not recurse over children of the device, so they must be
6349
  created in advance.
6350

6351
  @param lu: the lu on whose behalf we execute
6352
  @param node: the node on which to create the device
6353
  @type instance: L{objects.Instance}
6354
  @param instance: the instance which owns the device
6355
  @type device: L{objects.Disk}
6356
  @param device: the device to create
6357
  @param info: the extra 'metadata' we should attach to the device
6358
      (this will be represented as a LVM tag)
6359
  @type force_open: boolean
6360
  @param force_open: this parameter will be passes to the
6361
      L{backend.BlockdevCreate} function where it specifies
6362
      whether we run on primary or not, and it affects both
6363
      the child assembly and the device own Open() execution
6364

6365
  """
6366
  lu.cfg.SetDiskID(device, node)
6367
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6368
                                       instance.name, force_open, info)
6369
  result.Raise("Can't create block device %s on"
6370
               " node %s for instance %s" % (device, node, instance.name))
6371
  if device.physical_id is None:
6372
    device.physical_id = result.payload
6373

    
6374

    
6375
def _GenerateUniqueNames(lu, exts):
6376
  """Generate a suitable LV name.
6377

6378
  This will generate a logical volume name for the given instance.
6379

6380
  """
6381
  results = []
6382
  for val in exts:
6383
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6384
    results.append("%s%s" % (new_id, val))
6385
  return results
6386

    
6387

    
6388
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
6389
                         p_minor, s_minor):
6390
  """Generate a drbd8 device complete with its children.
6391

6392
  """
6393
  port = lu.cfg.AllocatePort()
6394
  vgname = lu.cfg.GetVGName()
6395
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6396
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6397
                          logical_id=(vgname, names[0]))
6398
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6399
                          logical_id=(vgname, names[1]))
6400
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6401
                          logical_id=(primary, secondary, port,
6402
                                      p_minor, s_minor,
6403
                                      shared_secret),
6404
                          children=[dev_data, dev_meta],
6405
                          iv_name=iv_name)
6406
  return drbd_dev
6407

    
6408

    
6409
def _GenerateDiskTemplate(lu, template_name,
6410
                          instance_name, primary_node,
6411
                          secondary_nodes, disk_info,
6412
                          file_storage_dir, file_driver,
6413
                          base_index):
6414
  """Generate the entire disk layout for a given template type.
6415

6416
  """
6417
  #TODO: compute space requirements
6418

    
6419
  vgname = lu.cfg.GetVGName()
6420
  disk_count = len(disk_info)
6421
  disks = []
6422
  if template_name == constants.DT_DISKLESS:
6423
    pass
6424
  elif template_name == constants.DT_PLAIN:
6425
    if len(secondary_nodes) != 0:
6426
      raise errors.ProgrammerError("Wrong template configuration")
6427

    
6428
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6429
                                      for i in range(disk_count)])
6430
    for idx, disk in enumerate(disk_info):
6431
      disk_index = idx + base_index
6432
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6433
                              logical_id=(vgname, names[idx]),
6434
                              iv_name="disk/%d" % disk_index,
6435
                              mode=disk["mode"])
6436
      disks.append(disk_dev)
6437
  elif template_name == constants.DT_DRBD8:
6438
    if len(secondary_nodes) != 1:
6439
      raise errors.ProgrammerError("Wrong template configuration")
6440
    remote_node = secondary_nodes[0]
6441
    minors = lu.cfg.AllocateDRBDMinor(
6442
      [primary_node, remote_node] * len(disk_info), instance_name)
6443

    
6444
    names = []
6445
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6446
                                               for i in range(disk_count)]):
6447
      names.append(lv_prefix + "_data")
6448
      names.append(lv_prefix + "_meta")
6449
    for idx, disk in enumerate(disk_info):
6450
      disk_index = idx + base_index
6451
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6452
                                      disk["size"], names[idx*2:idx*2+2],
6453
                                      "disk/%d" % disk_index,
6454
                                      minors[idx*2], minors[idx*2+1])
6455
      disk_dev.mode = disk["mode"]
6456
      disks.append(disk_dev)
6457
  elif template_name == constants.DT_FILE:
6458
    if len(secondary_nodes) != 0:
6459
      raise errors.ProgrammerError("Wrong template configuration")
6460

    
6461
    _RequireFileStorage()
6462

    
6463
    for idx, disk in enumerate(disk_info):
6464
      disk_index = idx + base_index
6465
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6466
                              iv_name="disk/%d" % disk_index,
6467
                              logical_id=(file_driver,
6468
                                          "%s/disk%d" % (file_storage_dir,
6469
                                                         disk_index)),
6470
                              mode=disk["mode"])
6471
      disks.append(disk_dev)
6472
  else:
6473
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6474
  return disks
6475

    
6476

    
6477
def _GetInstanceInfoText(instance):
6478
  """Compute that text that should be added to the disk's metadata.
6479

6480
  """
6481
  return "originstname+%s" % instance.name
6482

    
6483

    
6484
def _CalcEta(time_taken, written, total_size):
6485
  """Calculates the ETA based on size written and total size.
6486

6487
  @param time_taken: The time taken so far
6488
  @param written: amount written so far
6489
  @param total_size: The total size of data to be written
6490
  @return: The remaining time in seconds
6491

6492
  """
6493
  avg_time = time_taken / float(written)
6494
  return (total_size - written) * avg_time
6495

    
6496

    
6497
def _WipeDisks(lu, instance):
6498
  """Wipes instance disks.
6499

6500
  @type lu: L{LogicalUnit}
6501
  @param lu: the logical unit on whose behalf we execute
6502
  @type instance: L{objects.Instance}
6503
  @param instance: the instance whose disks we should create
6504
  @return: the success of the wipe
6505

6506
  """
6507
  node = instance.primary_node
6508
  for idx, device in enumerate(instance.disks):
6509
    lu.LogInfo("* Wiping disk %d", idx)
6510
    logging.info("Wiping disk %d for instance %s", idx, instance.name)
6511

    
6512
    # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
6513
    # MAX_WIPE_CHUNK at max
6514
    wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
6515
                          constants.MIN_WIPE_CHUNK_PERCENT)
6516

    
6517
    offset = 0
6518
    size = device.size
6519
    last_output = 0
6520
    start_time = time.time()
6521

    
6522
    while offset < size:
6523
      wipe_size = min(wipe_chunk_size, size - offset)
6524
      result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
6525
      result.Raise("Could not wipe disk %d at offset %d for size %d" %
6526
                   (idx, offset, wipe_size))
6527
      now = time.time()
6528
      offset += wipe_size
6529
      if now - last_output >= 60:
6530
        eta = _CalcEta(now - start_time, offset, size)
6531
        lu.LogInfo(" - done: %.1f%% ETA: %s" %
6532
                   (offset / float(size) * 100, utils.FormatSeconds(eta)))
6533
        last_output = now
6534

    
6535

    
6536
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6537
  """Create all disks for an instance.
6538

6539
  This abstracts away some work from AddInstance.
6540

6541
  @type lu: L{LogicalUnit}
6542
  @param lu: the logical unit on whose behalf we execute
6543
  @type instance: L{objects.Instance}
6544
  @param instance: the instance whose disks we should create
6545
  @type to_skip: list
6546
  @param to_skip: list of indices to skip
6547
  @type target_node: string
6548
  @param target_node: if passed, overrides the target node for creation
6549
  @rtype: boolean
6550
  @return: the success of the creation
6551

6552
  """
6553
  info = _GetInstanceInfoText(instance)
6554
  if target_node is None:
6555
    pnode = instance.primary_node
6556
    all_nodes = instance.all_nodes
6557
  else:
6558
    pnode = target_node
6559
    all_nodes = [pnode]
6560

    
6561
  if instance.disk_template == constants.DT_FILE:
6562
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6563
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6564

    
6565
    result.Raise("Failed to create directory '%s' on"
6566
                 " node %s" % (file_storage_dir, pnode))
6567

    
6568
  # Note: this needs to be kept in sync with adding of disks in
6569
  # LUSetInstanceParams
6570
  for idx, device in enumerate(instance.disks):
6571
    if to_skip and idx in to_skip:
6572
      continue
6573
    logging.info("Creating volume %s for instance %s",
6574
                 device.iv_name, instance.name)
6575
    #HARDCODE
6576
    for node in all_nodes:
6577
      f_create = node == pnode
6578
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6579

    
6580

    
6581
def _RemoveDisks(lu, instance, target_node=None):
6582
  """Remove all disks for an instance.
6583

6584
  This abstracts away some work from `AddInstance()` and
6585
  `RemoveInstance()`. Note that in case some of the devices couldn't
6586
  be removed, the removal will continue with the other ones (compare
6587
  with `_CreateDisks()`).
6588

6589
  @type lu: L{LogicalUnit}
6590
  @param lu: the logical unit on whose behalf we execute
6591
  @type instance: L{objects.Instance}
6592
  @param instance: the instance whose disks we should remove
6593
  @type target_node: string
6594
  @param target_node: used to override the node on which to remove the disks
6595
  @rtype: boolean
6596
  @return: the success of the removal
6597

6598
  """
6599
  logging.info("Removing block devices for instance %s", instance.name)
6600

    
6601
  all_result = True
6602
  for device in instance.disks:
6603
    if target_node:
6604
      edata = [(target_node, device)]
6605
    else:
6606
      edata = device.ComputeNodeTree(instance.primary_node)
6607
    for node, disk in edata:
6608
      lu.cfg.SetDiskID(disk, node)
6609
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6610
      if msg:
6611
        lu.LogWarning("Could not remove block device %s on node %s,"
6612
                      " continuing anyway: %s", device.iv_name, node, msg)
6613
        all_result = False
6614

    
6615
  if instance.disk_template == constants.DT_FILE:
6616
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6617
    if target_node:
6618
      tgt = target_node
6619
    else:
6620
      tgt = instance.primary_node
6621
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6622
    if result.fail_msg:
6623
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6624
                    file_storage_dir, instance.primary_node, result.fail_msg)
6625
      all_result = False
6626

    
6627
  return all_result
6628

    
6629

    
6630
def _ComputeDiskSize(disk_template, disks):
6631
  """Compute disk size requirements in the volume group
6632

6633
  """
6634
  # Required free disk space as a function of disk and swap space
6635
  req_size_dict = {
6636
    constants.DT_DISKLESS: None,
6637
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6638
    # 128 MB are added for drbd metadata for each disk
6639
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6640
    constants.DT_FILE: None,
6641
  }
6642

    
6643
  if disk_template not in req_size_dict:
6644
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6645
                                 " is unknown" %  disk_template)
6646

    
6647
  return req_size_dict[disk_template]
6648

    
6649

    
6650
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6651
  """Hypervisor parameter validation.
6652

6653
  This function abstract the hypervisor parameter validation to be
6654
  used in both instance create and instance modify.
6655

6656
  @type lu: L{LogicalUnit}
6657
  @param lu: the logical unit for which we check
6658
  @type nodenames: list
6659
  @param nodenames: the list of nodes on which we should check
6660
  @type hvname: string
6661
  @param hvname: the name of the hypervisor we should use
6662
  @type hvparams: dict
6663
  @param hvparams: the parameters which we need to check
6664
  @raise errors.OpPrereqError: if the parameters are not valid
6665

6666
  """
6667
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6668
                                                  hvname,
6669
                                                  hvparams)
6670
  for node in nodenames:
6671
    info = hvinfo[node]
6672
    if info.offline:
6673
      continue
6674
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6675

    
6676

    
6677
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6678
  """OS parameters validation.
6679

6680
  @type lu: L{LogicalUnit}
6681
  @param lu: the logical unit for which we check
6682
  @type required: boolean
6683
  @param required: whether the validation should fail if the OS is not
6684
      found
6685
  @type nodenames: list
6686
  @param nodenames: the list of nodes on which we should check
6687
  @type osname: string
6688
  @param osname: the name of the hypervisor we should use
6689
  @type osparams: dict
6690
  @param osparams: the parameters which we need to check
6691
  @raise errors.OpPrereqError: if the parameters are not valid
6692

6693
  """
6694
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6695
                                   [constants.OS_VALIDATE_PARAMETERS],
6696
                                   osparams)
6697
  for node, nres in result.items():
6698
    # we don't check for offline cases since this should be run only
6699
    # against the master node and/or an instance's nodes
6700
    nres.Raise("OS Parameters validation failed on node %s" % node)
6701
    if not nres.payload:
6702
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6703
                 osname, node)
6704

    
6705

    
6706
class LUCreateInstance(LogicalUnit):
6707
  """Create an instance.
6708

6709
  """
6710
  HPATH = "instance-add"
6711
  HTYPE = constants.HTYPE_INSTANCE
6712
  _OP_PARAMS = [
6713
    _PInstanceName,
6714
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES)),
6715
    ("start", True, ht.TBool),
6716
    ("wait_for_sync", True, ht.TBool),
6717
    ("ip_check", True, ht.TBool),
6718
    ("name_check", True, ht.TBool),
6719
    ("disks", ht.NoDefault, ht.TListOf(ht.TDict)),
6720
    ("nics", ht.NoDefault, ht.TListOf(ht.TDict)),
6721
    ("hvparams", ht.EmptyDict, ht.TDict),
6722
    ("beparams", ht.EmptyDict, ht.TDict),
6723
    ("osparams", ht.EmptyDict, ht.TDict),
6724
    ("no_install", None, ht.TMaybeBool),
6725
    ("os_type", None, ht.TMaybeString),
6726
    ("force_variant", False, ht.TBool),
6727
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone)),
6728
    ("source_x509_ca", None, ht.TMaybeString),
6729
    ("source_instance_name", None, ht.TMaybeString),
6730
    ("src_node", None, ht.TMaybeString),
6731
    ("src_path", None, ht.TMaybeString),
6732
    ("pnode", None, ht.TMaybeString),
6733
    ("snode", None, ht.TMaybeString),
6734
    ("iallocator", None, ht.TMaybeString),
6735
    ("hypervisor", None, ht.TMaybeString),
6736
    ("disk_template", ht.NoDefault, _CheckDiskTemplate),
6737
    ("identify_defaults", False, ht.TBool),
6738
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER))),
6739
    ("file_storage_dir", None, ht.TMaybeString),
6740
    ]
6741
  REQ_BGL = False
6742

    
6743
  def CheckArguments(self):
6744
    """Check arguments.
6745

6746
    """
6747
    # do not require name_check to ease forward/backward compatibility
6748
    # for tools
6749
    if self.op.no_install and self.op.start:
6750
      self.LogInfo("No-installation mode selected, disabling startup")
6751
      self.op.start = False
6752
    # validate/normalize the instance name
6753
    self.op.instance_name = \
6754
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
6755

    
6756
    if self.op.ip_check and not self.op.name_check:
6757
      # TODO: make the ip check more flexible and not depend on the name check
6758
      raise errors.OpPrereqError("Cannot do ip check without a name check",
6759
                                 errors.ECODE_INVAL)
6760

    
6761
    # check nics' parameter names
6762
    for nic in self.op.nics:
6763
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6764

    
6765
    # check disks. parameter names and consistent adopt/no-adopt strategy
6766
    has_adopt = has_no_adopt = False
6767
    for disk in self.op.disks:
6768
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6769
      if "adopt" in disk:
6770
        has_adopt = True
6771
      else:
6772
        has_no_adopt = True
6773
    if has_adopt and has_no_adopt:
6774
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6775
                                 errors.ECODE_INVAL)
6776
    if has_adopt:
6777
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6778
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6779
                                   " '%s' disk template" %
6780
                                   self.op.disk_template,
6781
                                   errors.ECODE_INVAL)
6782
      if self.op.iallocator is not None:
6783
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6784
                                   " iallocator script", errors.ECODE_INVAL)
6785
      if self.op.mode == constants.INSTANCE_IMPORT:
6786
        raise errors.OpPrereqError("Disk adoption not allowed for"
6787
                                   " instance import", errors.ECODE_INVAL)
6788

    
6789
    self.adopt_disks = has_adopt
6790

    
6791
    # instance name verification
6792
    if self.op.name_check:
6793
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
6794
      self.op.instance_name = self.hostname1.name
6795
      # used in CheckPrereq for ip ping check
6796
      self.check_ip = self.hostname1.ip
6797
    else:
6798
      self.check_ip = None
6799

    
6800
    # file storage checks
6801
    if (self.op.file_driver and
6802
        not self.op.file_driver in constants.FILE_DRIVER):
6803
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6804
                                 self.op.file_driver, errors.ECODE_INVAL)
6805

    
6806
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6807
      raise errors.OpPrereqError("File storage directory path not absolute",
6808
                                 errors.ECODE_INVAL)
6809

    
6810
    ### Node/iallocator related checks
6811
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
6812

    
6813
    if self.op.pnode is not None:
6814
      if self.op.disk_template in constants.DTS_NET_MIRROR:
6815
        if self.op.snode is None:
6816
          raise errors.OpPrereqError("The networked disk templates need"
6817
                                     " a mirror node", errors.ECODE_INVAL)
6818
      elif self.op.snode:
6819
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
6820
                        " template")
6821
        self.op.snode = None
6822

    
6823
    self._cds = _GetClusterDomainSecret()
6824

    
6825
    if self.op.mode == constants.INSTANCE_IMPORT:
6826
      # On import force_variant must be True, because if we forced it at
6827
      # initial install, our only chance when importing it back is that it
6828
      # works again!
6829
      self.op.force_variant = True
6830

    
6831
      if self.op.no_install:
6832
        self.LogInfo("No-installation mode has no effect during import")
6833

    
6834
    elif self.op.mode == constants.INSTANCE_CREATE:
6835
      if self.op.os_type is None:
6836
        raise errors.OpPrereqError("No guest OS specified",
6837
                                   errors.ECODE_INVAL)
6838
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
6839
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
6840
                                   " installation" % self.op.os_type,
6841
                                   errors.ECODE_STATE)
6842
      if self.op.disk_template is None:
6843
        raise errors.OpPrereqError("No disk template specified",
6844
                                   errors.ECODE_INVAL)
6845

    
6846
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6847
      # Check handshake to ensure both clusters have the same domain secret
6848
      src_handshake = self.op.source_handshake
6849
      if not src_handshake:
6850
        raise errors.OpPrereqError("Missing source handshake",
6851
                                   errors.ECODE_INVAL)
6852

    
6853
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6854
                                                           src_handshake)
6855
      if errmsg:
6856
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6857
                                   errors.ECODE_INVAL)
6858

    
6859
      # Load and check source CA
6860
      self.source_x509_ca_pem = self.op.source_x509_ca
6861
      if not self.source_x509_ca_pem:
6862
        raise errors.OpPrereqError("Missing source X509 CA",
6863
                                   errors.ECODE_INVAL)
6864

    
6865
      try:
6866
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
6867
                                                    self._cds)
6868
      except OpenSSL.crypto.Error, err:
6869
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
6870
                                   (err, ), errors.ECODE_INVAL)
6871

    
6872
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
6873
      if errcode is not None:
6874
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
6875
                                   errors.ECODE_INVAL)
6876

    
6877
      self.source_x509_ca = cert
6878

    
6879
      src_instance_name = self.op.source_instance_name
6880
      if not src_instance_name:
6881
        raise errors.OpPrereqError("Missing source instance name",
6882
                                   errors.ECODE_INVAL)
6883

    
6884
      self.source_instance_name = \
6885
          netutils.GetHostname(name=src_instance_name).name
6886

    
6887
    else:
6888
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
6889
                                 self.op.mode, errors.ECODE_INVAL)
6890

    
6891
  def ExpandNames(self):
6892
    """ExpandNames for CreateInstance.
6893

6894
    Figure out the right locks for instance creation.
6895

6896
    """
6897
    self.needed_locks = {}
6898

    
6899
    instance_name = self.op.instance_name
6900
    # this is just a preventive check, but someone might still add this
6901
    # instance in the meantime, and creation will fail at lock-add time
6902
    if instance_name in self.cfg.GetInstanceList():
6903
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6904
                                 instance_name, errors.ECODE_EXISTS)
6905

    
6906
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
6907

    
6908
    if self.op.iallocator:
6909
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6910
    else:
6911
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
6912
      nodelist = [self.op.pnode]
6913
      if self.op.snode is not None:
6914
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
6915
        nodelist.append(self.op.snode)
6916
      self.needed_locks[locking.LEVEL_NODE] = nodelist
6917

    
6918
    # in case of import lock the source node too
6919
    if self.op.mode == constants.INSTANCE_IMPORT:
6920
      src_node = self.op.src_node
6921
      src_path = self.op.src_path
6922

    
6923
      if src_path is None:
6924
        self.op.src_path = src_path = self.op.instance_name
6925

    
6926
      if src_node is None:
6927
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6928
        self.op.src_node = None
6929
        if os.path.isabs(src_path):
6930
          raise errors.OpPrereqError("Importing an instance from an absolute"
6931
                                     " path requires a source node option.",
6932
                                     errors.ECODE_INVAL)
6933
      else:
6934
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
6935
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
6936
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
6937
        if not os.path.isabs(src_path):
6938
          self.op.src_path = src_path = \
6939
            utils.PathJoin(constants.EXPORT_DIR, src_path)
6940

    
6941
  def _RunAllocator(self):
6942
    """Run the allocator based on input opcode.
6943

6944
    """
6945
    nics = [n.ToDict() for n in self.nics]
6946
    ial = IAllocator(self.cfg, self.rpc,
6947
                     mode=constants.IALLOCATOR_MODE_ALLOC,
6948
                     name=self.op.instance_name,
6949
                     disk_template=self.op.disk_template,
6950
                     tags=[],
6951
                     os=self.op.os_type,
6952
                     vcpus=self.be_full[constants.BE_VCPUS],
6953
                     mem_size=self.be_full[constants.BE_MEMORY],
6954
                     disks=self.disks,
6955
                     nics=nics,
6956
                     hypervisor=self.op.hypervisor,
6957
                     )
6958

    
6959
    ial.Run(self.op.iallocator)
6960

    
6961
    if not ial.success:
6962
      raise errors.OpPrereqError("Can't compute nodes using"
6963
                                 " iallocator '%s': %s" %
6964
                                 (self.op.iallocator, ial.info),
6965
                                 errors.ECODE_NORES)
6966
    if len(ial.result) != ial.required_nodes:
6967
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6968
                                 " of nodes (%s), required %s" %
6969
                                 (self.op.iallocator, len(ial.result),
6970
                                  ial.required_nodes), errors.ECODE_FAULT)
6971
    self.op.pnode = ial.result[0]
6972
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6973
                 self.op.instance_name, self.op.iallocator,
6974
                 utils.CommaJoin(ial.result))
6975
    if ial.required_nodes == 2:
6976
      self.op.snode = ial.result[1]
6977

    
6978
  def BuildHooksEnv(self):
6979
    """Build hooks env.
6980

6981
    This runs on master, primary and secondary nodes of the instance.
6982

6983
    """
6984
    env = {
6985
      "ADD_MODE": self.op.mode,
6986
      }
6987
    if self.op.mode == constants.INSTANCE_IMPORT:
6988
      env["SRC_NODE"] = self.op.src_node
6989
      env["SRC_PATH"] = self.op.src_path
6990
      env["SRC_IMAGES"] = self.src_images
6991

    
6992
    env.update(_BuildInstanceHookEnv(
6993
      name=self.op.instance_name,
6994
      primary_node=self.op.pnode,
6995
      secondary_nodes=self.secondaries,
6996
      status=self.op.start,
6997
      os_type=self.op.os_type,
6998
      memory=self.be_full[constants.BE_MEMORY],
6999
      vcpus=self.be_full[constants.BE_VCPUS],
7000
      nics=_NICListToTuple(self, self.nics),
7001
      disk_template=self.op.disk_template,
7002
      disks=[(d["size"], d["mode"]) for d in self.disks],
7003
      bep=self.be_full,
7004
      hvp=self.hv_full,
7005
      hypervisor_name=self.op.hypervisor,
7006
    ))
7007

    
7008
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
7009
          self.secondaries)
7010
    return env, nl, nl
7011

    
7012
  def _ReadExportInfo(self):
7013
    """Reads the export information from disk.
7014

7015
    It will override the opcode source node and path with the actual
7016
    information, if these two were not specified before.
7017

7018
    @return: the export information
7019

7020
    """
7021
    assert self.op.mode == constants.INSTANCE_IMPORT
7022

    
7023
    src_node = self.op.src_node
7024
    src_path = self.op.src_path
7025

    
7026
    if src_node is None:
7027
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
7028
      exp_list = self.rpc.call_export_list(locked_nodes)
7029
      found = False
7030
      for node in exp_list:
7031
        if exp_list[node].fail_msg:
7032
          continue
7033
        if src_path in exp_list[node].payload:
7034
          found = True
7035
          self.op.src_node = src_node = node
7036
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
7037
                                                       src_path)
7038
          break
7039
      if not found:
7040
        raise errors.OpPrereqError("No export found for relative path %s" %
7041
                                    src_path, errors.ECODE_INVAL)
7042

    
7043
    _CheckNodeOnline(self, src_node)
7044
    result = self.rpc.call_export_info(src_node, src_path)
7045
    result.Raise("No export or invalid export found in dir %s" % src_path)
7046

    
7047
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
7048
    if not export_info.has_section(constants.INISECT_EXP):
7049
      raise errors.ProgrammerError("Corrupted export config",
7050
                                   errors.ECODE_ENVIRON)
7051

    
7052
    ei_version = export_info.get(constants.INISECT_EXP, "version")
7053
    if (int(ei_version) != constants.EXPORT_VERSION):
7054
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
7055
                                 (ei_version, constants.EXPORT_VERSION),
7056
                                 errors.ECODE_ENVIRON)
7057
    return export_info
7058

    
7059
  def _ReadExportParams(self, einfo):
7060
    """Use export parameters as defaults.
7061

7062
    In case the opcode doesn't specify (as in override) some instance
7063
    parameters, then try to use them from the export information, if
7064
    that declares them.
7065

7066
    """
7067
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
7068

    
7069
    if self.op.disk_template is None:
7070
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
7071
        self.op.disk_template = einfo.get(constants.INISECT_INS,
7072
                                          "disk_template")
7073
      else:
7074
        raise errors.OpPrereqError("No disk template specified and the export"
7075
                                   " is missing the disk_template information",
7076
                                   errors.ECODE_INVAL)
7077

    
7078
    if not self.op.disks:
7079
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
7080
        disks = []
7081
        # TODO: import the disk iv_name too
7082
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
7083
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
7084
          disks.append({"size": disk_sz})
7085
        self.op.disks = disks
7086
      else:
7087
        raise errors.OpPrereqError("No disk info specified and the export"
7088
                                   " is missing the disk information",
7089
                                   errors.ECODE_INVAL)
7090

    
7091
    if (not self.op.nics and
7092
        einfo.has_option(constants.INISECT_INS, "nic_count")):
7093
      nics = []
7094
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
7095
        ndict = {}
7096
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
7097
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
7098
          ndict[name] = v
7099
        nics.append(ndict)
7100
      self.op.nics = nics
7101

    
7102
    if (self.op.hypervisor is None and
7103
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
7104
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
7105
    if einfo.has_section(constants.INISECT_HYP):
7106
      # use the export parameters but do not override the ones
7107
      # specified by the user
7108
      for name, value in einfo.items(constants.INISECT_HYP):
7109
        if name not in self.op.hvparams:
7110
          self.op.hvparams[name] = value
7111

    
7112
    if einfo.has_section(constants.INISECT_BEP):
7113
      # use the parameters, without overriding
7114
      for name, value in einfo.items(constants.INISECT_BEP):
7115
        if name not in self.op.beparams:
7116
          self.op.beparams[name] = value
7117
    else:
7118
      # try to read the parameters old style, from the main section
7119
      for name in constants.BES_PARAMETERS:
7120
        if (name not in self.op.beparams and
7121
            einfo.has_option(constants.INISECT_INS, name)):
7122
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
7123

    
7124
    if einfo.has_section(constants.INISECT_OSP):
7125
      # use the parameters, without overriding
7126
      for name, value in einfo.items(constants.INISECT_OSP):
7127
        if name not in self.op.osparams:
7128
          self.op.osparams[name] = value
7129

    
7130
  def _RevertToDefaults(self, cluster):
7131
    """Revert the instance parameters to the default values.
7132

7133
    """
7134
    # hvparams
7135
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
7136
    for name in self.op.hvparams.keys():
7137
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
7138
        del self.op.hvparams[name]
7139
    # beparams
7140
    be_defs = cluster.SimpleFillBE({})
7141
    for name in self.op.beparams.keys():
7142
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
7143
        del self.op.beparams[name]
7144
    # nic params
7145
    nic_defs = cluster.SimpleFillNIC({})
7146
    for nic in self.op.nics:
7147
      for name in constants.NICS_PARAMETERS:
7148
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
7149
          del nic[name]
7150
    # osparams
7151
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
7152
    for name in self.op.osparams.keys():
7153
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
7154
        del self.op.osparams[name]
7155

    
7156
  def CheckPrereq(self):
7157
    """Check prerequisites.
7158

7159
    """
7160
    if self.op.mode == constants.INSTANCE_IMPORT:
7161
      export_info = self._ReadExportInfo()
7162
      self._ReadExportParams(export_info)
7163

    
7164
    _CheckDiskTemplate(self.op.disk_template)
7165

    
7166
    if (not self.cfg.GetVGName() and
7167
        self.op.disk_template not in constants.DTS_NOT_LVM):
7168
      raise errors.OpPrereqError("Cluster does not support lvm-based"
7169
                                 " instances", errors.ECODE_STATE)
7170

    
7171
    if self.op.hypervisor is None:
7172
      self.op.hypervisor = self.cfg.GetHypervisorType()
7173

    
7174
    cluster = self.cfg.GetClusterInfo()
7175
    enabled_hvs = cluster.enabled_hypervisors
7176
    if self.op.hypervisor not in enabled_hvs:
7177
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
7178
                                 " cluster (%s)" % (self.op.hypervisor,
7179
                                  ",".join(enabled_hvs)),
7180
                                 errors.ECODE_STATE)
7181

    
7182
    # check hypervisor parameter syntax (locally)
7183
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
7184
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
7185
                                      self.op.hvparams)
7186
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
7187
    hv_type.CheckParameterSyntax(filled_hvp)
7188
    self.hv_full = filled_hvp
7189
    # check that we don't specify global parameters on an instance
7190
    _CheckGlobalHvParams(self.op.hvparams)
7191

    
7192
    # fill and remember the beparams dict
7193
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
7194
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
7195

    
7196
    # build os parameters
7197
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
7198

    
7199
    # now that hvp/bep are in final format, let's reset to defaults,
7200
    # if told to do so
7201
    if self.op.identify_defaults:
7202
      self._RevertToDefaults(cluster)
7203

    
7204
    # NIC buildup
7205
    self.nics = []
7206
    for idx, nic in enumerate(self.op.nics):
7207
      nic_mode_req = nic.get("mode", None)
7208
      nic_mode = nic_mode_req
7209
      if nic_mode is None:
7210
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
7211

    
7212
      # in routed mode, for the first nic, the default ip is 'auto'
7213
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
7214
        default_ip_mode = constants.VALUE_AUTO
7215
      else:
7216
        default_ip_mode = constants.VALUE_NONE
7217

    
7218
      # ip validity checks
7219
      ip = nic.get("ip", default_ip_mode)
7220
      if ip is None or ip.lower() == constants.VALUE_NONE:
7221
        nic_ip = None
7222
      elif ip.lower() == constants.VALUE_AUTO:
7223
        if not self.op.name_check:
7224
          raise errors.OpPrereqError("IP address set to auto but name checks"
7225
                                     " have been skipped",
7226
                                     errors.ECODE_INVAL)
7227
        nic_ip = self.hostname1.ip
7228
      else:
7229
        if not netutils.IPAddress.IsValid(ip):
7230
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
7231
                                     errors.ECODE_INVAL)
7232
        nic_ip = ip
7233

    
7234
      # TODO: check the ip address for uniqueness
7235
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7236
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7237
                                   errors.ECODE_INVAL)
7238

    
7239
      # MAC address verification
7240
      mac = nic.get("mac", constants.VALUE_AUTO)
7241
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7242
        mac = utils.NormalizeAndValidateMac(mac)
7243

    
7244
        try:
7245
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7246
        except errors.ReservationError:
7247
          raise errors.OpPrereqError("MAC address %s already in use"
7248
                                     " in cluster" % mac,
7249
                                     errors.ECODE_NOTUNIQUE)
7250

    
7251
      # bridge verification
7252
      bridge = nic.get("bridge", None)
7253
      link = nic.get("link", None)
7254
      if bridge and link:
7255
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7256
                                   " at the same time", errors.ECODE_INVAL)
7257
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7258
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7259
                                   errors.ECODE_INVAL)
7260
      elif bridge:
7261
        link = bridge
7262

    
7263
      nicparams = {}
7264
      if nic_mode_req:
7265
        nicparams[constants.NIC_MODE] = nic_mode_req
7266
      if link:
7267
        nicparams[constants.NIC_LINK] = link
7268

    
7269
      check_params = cluster.SimpleFillNIC(nicparams)
7270
      objects.NIC.CheckParameterSyntax(check_params)
7271
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7272

    
7273
    # disk checks/pre-build
7274
    self.disks = []
7275
    for disk in self.op.disks:
7276
      mode = disk.get("mode", constants.DISK_RDWR)
7277
      if mode not in constants.DISK_ACCESS_SET:
7278
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7279
                                   mode, errors.ECODE_INVAL)
7280
      size = disk.get("size", None)
7281
      if size is None:
7282
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7283
      try:
7284
        size = int(size)
7285
      except (TypeError, ValueError):
7286
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7287
                                   errors.ECODE_INVAL)
7288
      new_disk = {"size": size, "mode": mode}
7289
      if "adopt" in disk:
7290
        new_disk["adopt"] = disk["adopt"]
7291
      self.disks.append(new_disk)
7292

    
7293
    if self.op.mode == constants.INSTANCE_IMPORT:
7294

    
7295
      # Check that the new instance doesn't have less disks than the export
7296
      instance_disks = len(self.disks)
7297
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7298
      if instance_disks < export_disks:
7299
        raise errors.OpPrereqError("Not enough disks to import."
7300
                                   " (instance: %d, export: %d)" %
7301
                                   (instance_disks, export_disks),
7302
                                   errors.ECODE_INVAL)
7303

    
7304
      disk_images = []
7305
      for idx in range(export_disks):
7306
        option = 'disk%d_dump' % idx
7307
        if export_info.has_option(constants.INISECT_INS, option):
7308
          # FIXME: are the old os-es, disk sizes, etc. useful?
7309
          export_name = export_info.get(constants.INISECT_INS, option)
7310
          image = utils.PathJoin(self.op.src_path, export_name)
7311
          disk_images.append(image)
7312
        else:
7313
          disk_images.append(False)
7314

    
7315
      self.src_images = disk_images
7316

    
7317
      old_name = export_info.get(constants.INISECT_INS, 'name')
7318
      try:
7319
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7320
      except (TypeError, ValueError), err:
7321
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7322
                                   " an integer: %s" % str(err),
7323
                                   errors.ECODE_STATE)
7324
      if self.op.instance_name == old_name:
7325
        for idx, nic in enumerate(self.nics):
7326
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7327
            nic_mac_ini = 'nic%d_mac' % idx
7328
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7329

    
7330
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7331

    
7332
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7333
    if self.op.ip_check:
7334
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7335
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7336
                                   (self.check_ip, self.op.instance_name),
7337
                                   errors.ECODE_NOTUNIQUE)
7338

    
7339
    #### mac address generation
7340
    # By generating here the mac address both the allocator and the hooks get
7341
    # the real final mac address rather than the 'auto' or 'generate' value.
7342
    # There is a race condition between the generation and the instance object
7343
    # creation, which means that we know the mac is valid now, but we're not
7344
    # sure it will be when we actually add the instance. If things go bad
7345
    # adding the instance will abort because of a duplicate mac, and the
7346
    # creation job will fail.
7347
    for nic in self.nics:
7348
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7349
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7350

    
7351
    #### allocator run
7352

    
7353
    if self.op.iallocator is not None:
7354
      self._RunAllocator()
7355

    
7356
    #### node related checks
7357

    
7358
    # check primary node
7359
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7360
    assert self.pnode is not None, \
7361
      "Cannot retrieve locked node %s" % self.op.pnode
7362
    if pnode.offline:
7363
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7364
                                 pnode.name, errors.ECODE_STATE)
7365
    if pnode.drained:
7366
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7367
                                 pnode.name, errors.ECODE_STATE)
7368

    
7369
    self.secondaries = []
7370

    
7371
    # mirror node verification
7372
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7373
      if self.op.snode == pnode.name:
7374
        raise errors.OpPrereqError("The secondary node cannot be the"
7375
                                   " primary node.", errors.ECODE_INVAL)
7376
      _CheckNodeOnline(self, self.op.snode)
7377
      _CheckNodeNotDrained(self, self.op.snode)
7378
      self.secondaries.append(self.op.snode)
7379

    
7380
    nodenames = [pnode.name] + self.secondaries
7381

    
7382
    req_size = _ComputeDiskSize(self.op.disk_template,
7383
                                self.disks)
7384

    
7385
    # Check lv size requirements, if not adopting
7386
    if req_size is not None and not self.adopt_disks:
7387
      _CheckNodesFreeDisk(self, nodenames, req_size)
7388

    
7389
    if self.adopt_disks: # instead, we must check the adoption data
7390
      all_lvs = set([i["adopt"] for i in self.disks])
7391
      if len(all_lvs) != len(self.disks):
7392
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7393
                                   errors.ECODE_INVAL)
7394
      for lv_name in all_lvs:
7395
        try:
7396
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7397
        except errors.ReservationError:
7398
          raise errors.OpPrereqError("LV named %s used by another instance" %
7399
                                     lv_name, errors.ECODE_NOTUNIQUE)
7400

    
7401
      node_lvs = self.rpc.call_lv_list([pnode.name],
7402
                                       self.cfg.GetVGName())[pnode.name]
7403
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7404
      node_lvs = node_lvs.payload
7405
      delta = all_lvs.difference(node_lvs.keys())
7406
      if delta:
7407
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7408
                                   utils.CommaJoin(delta),
7409
                                   errors.ECODE_INVAL)
7410
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7411
      if online_lvs:
7412
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7413
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7414
                                   errors.ECODE_STATE)
7415
      # update the size of disk based on what is found
7416
      for dsk in self.disks:
7417
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
7418

    
7419
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7420

    
7421
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7422
    # check OS parameters (remotely)
7423
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7424

    
7425
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7426

    
7427
    # memory check on primary node
7428
    if self.op.start:
7429
      _CheckNodeFreeMemory(self, self.pnode.name,
7430
                           "creating instance %s" % self.op.instance_name,
7431
                           self.be_full[constants.BE_MEMORY],
7432
                           self.op.hypervisor)
7433

    
7434
    self.dry_run_result = list(nodenames)
7435

    
7436
  def Exec(self, feedback_fn):
7437
    """Create and add the instance to the cluster.
7438

7439
    """
7440
    instance = self.op.instance_name
7441
    pnode_name = self.pnode.name
7442

    
7443
    ht_kind = self.op.hypervisor
7444
    if ht_kind in constants.HTS_REQ_PORT:
7445
      network_port = self.cfg.AllocatePort()
7446
    else:
7447
      network_port = None
7448

    
7449
    if constants.ENABLE_FILE_STORAGE:
7450
      # this is needed because os.path.join does not accept None arguments
7451
      if self.op.file_storage_dir is None:
7452
        string_file_storage_dir = ""
7453
      else:
7454
        string_file_storage_dir = self.op.file_storage_dir
7455

    
7456
      # build the full file storage dir path
7457
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7458
                                        string_file_storage_dir, instance)
7459
    else:
7460
      file_storage_dir = ""
7461

    
7462
    disks = _GenerateDiskTemplate(self,
7463
                                  self.op.disk_template,
7464
                                  instance, pnode_name,
7465
                                  self.secondaries,
7466
                                  self.disks,
7467
                                  file_storage_dir,
7468
                                  self.op.file_driver,
7469
                                  0)
7470

    
7471
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7472
                            primary_node=pnode_name,
7473
                            nics=self.nics, disks=disks,
7474
                            disk_template=self.op.disk_template,
7475
                            admin_up=False,
7476
                            network_port=network_port,
7477
                            beparams=self.op.beparams,
7478
                            hvparams=self.op.hvparams,
7479
                            hypervisor=self.op.hypervisor,
7480
                            osparams=self.op.osparams,
7481
                            )
7482

    
7483
    if self.adopt_disks:
7484
      # rename LVs to the newly-generated names; we need to construct
7485
      # 'fake' LV disks with the old data, plus the new unique_id
7486
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7487
      rename_to = []
7488
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7489
        rename_to.append(t_dsk.logical_id)
7490
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7491
        self.cfg.SetDiskID(t_dsk, pnode_name)
7492
      result = self.rpc.call_blockdev_rename(pnode_name,
7493
                                             zip(tmp_disks, rename_to))
7494
      result.Raise("Failed to rename adoped LVs")
7495
    else:
7496
      feedback_fn("* creating instance disks...")
7497
      try:
7498
        _CreateDisks(self, iobj)
7499
      except errors.OpExecError:
7500
        self.LogWarning("Device creation failed, reverting...")
7501
        try:
7502
          _RemoveDisks(self, iobj)
7503
        finally:
7504
          self.cfg.ReleaseDRBDMinors(instance)
7505
          raise
7506

    
7507
      if self.cfg.GetClusterInfo().prealloc_wipe_disks:
7508
        feedback_fn("* wiping instance disks...")
7509
        try:
7510
          _WipeDisks(self, iobj)
7511
        except errors.OpExecError:
7512
          self.LogWarning("Device wiping failed, reverting...")
7513
          try:
7514
            _RemoveDisks(self, iobj)
7515
          finally:
7516
            self.cfg.ReleaseDRBDMinors(instance)
7517
            raise
7518

    
7519
    feedback_fn("adding instance %s to cluster config" % instance)
7520

    
7521
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7522

    
7523
    # Declare that we don't want to remove the instance lock anymore, as we've
7524
    # added the instance to the config
7525
    del self.remove_locks[locking.LEVEL_INSTANCE]
7526
    # Unlock all the nodes
7527
    if self.op.mode == constants.INSTANCE_IMPORT:
7528
      nodes_keep = [self.op.src_node]
7529
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7530
                       if node != self.op.src_node]
7531
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7532
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7533
    else:
7534
      self.context.glm.release(locking.LEVEL_NODE)
7535
      del self.acquired_locks[locking.LEVEL_NODE]
7536

    
7537
    if self.op.wait_for_sync:
7538
      disk_abort = not _WaitForSync(self, iobj)
7539
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7540
      # make sure the disks are not degraded (still sync-ing is ok)
7541
      time.sleep(15)
7542
      feedback_fn("* checking mirrors status")
7543
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7544
    else:
7545
      disk_abort = False
7546

    
7547
    if disk_abort:
7548
      _RemoveDisks(self, iobj)
7549
      self.cfg.RemoveInstance(iobj.name)
7550
      # Make sure the instance lock gets removed
7551
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7552
      raise errors.OpExecError("There are some degraded disks for"
7553
                               " this instance")
7554

    
7555
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7556
      if self.op.mode == constants.INSTANCE_CREATE:
7557
        if not self.op.no_install:
7558
          feedback_fn("* running the instance OS create scripts...")
7559
          # FIXME: pass debug option from opcode to backend
7560
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7561
                                                 self.op.debug_level)
7562
          result.Raise("Could not add os for instance %s"
7563
                       " on node %s" % (instance, pnode_name))
7564

    
7565
      elif self.op.mode == constants.INSTANCE_IMPORT:
7566
        feedback_fn("* running the instance OS import scripts...")
7567

    
7568
        transfers = []
7569

    
7570
        for idx, image in enumerate(self.src_images):
7571
          if not image:
7572
            continue
7573

    
7574
          # FIXME: pass debug option from opcode to backend
7575
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7576
                                             constants.IEIO_FILE, (image, ),
7577
                                             constants.IEIO_SCRIPT,
7578
                                             (iobj.disks[idx], idx),
7579
                                             None)
7580
          transfers.append(dt)
7581

    
7582
        import_result = \
7583
          masterd.instance.TransferInstanceData(self, feedback_fn,
7584
                                                self.op.src_node, pnode_name,
7585
                                                self.pnode.secondary_ip,
7586
                                                iobj, transfers)
7587
        if not compat.all(import_result):
7588
          self.LogWarning("Some disks for instance %s on node %s were not"
7589
                          " imported successfully" % (instance, pnode_name))
7590

    
7591
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7592
        feedback_fn("* preparing remote import...")
7593
        connect_timeout = constants.RIE_CONNECT_TIMEOUT
7594
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7595

    
7596
        disk_results = masterd.instance.RemoteImport(self, feedback_fn, iobj,
7597
                                                     self.source_x509_ca,
7598
                                                     self._cds, timeouts)
7599
        if not compat.all(disk_results):
7600
          # TODO: Should the instance still be started, even if some disks
7601
          # failed to import (valid for local imports, too)?
7602
          self.LogWarning("Some disks for instance %s on node %s were not"
7603
                          " imported successfully" % (instance, pnode_name))
7604

    
7605
        # Run rename script on newly imported instance
7606
        assert iobj.name == instance
7607
        feedback_fn("Running rename script for %s" % instance)
7608
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7609
                                                   self.source_instance_name,
7610
                                                   self.op.debug_level)
7611
        if result.fail_msg:
7612
          self.LogWarning("Failed to run rename script for %s on node"
7613
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7614

    
7615
      else:
7616
        # also checked in the prereq part
7617
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7618
                                     % self.op.mode)
7619

    
7620
    if self.op.start:
7621
      iobj.admin_up = True
7622
      self.cfg.Update(iobj, feedback_fn)
7623
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7624
      feedback_fn("* starting instance...")
7625
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7626
      result.Raise("Could not start instance")
7627

    
7628
    return list(iobj.all_nodes)
7629

    
7630

    
7631
class LUConnectConsole(NoHooksLU):
7632
  """Connect to an instance's console.
7633

7634
  This is somewhat special in that it returns the command line that
7635
  you need to run on the master node in order to connect to the
7636
  console.
7637

7638
  """
7639
  _OP_PARAMS = [
7640
    _PInstanceName
7641
    ]
7642
  REQ_BGL = False
7643

    
7644
  def ExpandNames(self):
7645
    self._ExpandAndLockInstance()
7646

    
7647
  def CheckPrereq(self):
7648
    """Check prerequisites.
7649

7650
    This checks that the instance is in the cluster.
7651

7652
    """
7653
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7654
    assert self.instance is not None, \
7655
      "Cannot retrieve locked instance %s" % self.op.instance_name
7656
    _CheckNodeOnline(self, self.instance.primary_node)
7657

    
7658
  def Exec(self, feedback_fn):
7659
    """Connect to the console of an instance
7660

7661
    """
7662
    instance = self.instance
7663
    node = instance.primary_node
7664

    
7665
    node_insts = self.rpc.call_instance_list([node],
7666
                                             [instance.hypervisor])[node]
7667
    node_insts.Raise("Can't get node information from %s" % node)
7668

    
7669
    if instance.name not in node_insts.payload:
7670
      if instance.admin_up:
7671
        state = "ERROR_down"
7672
      else:
7673
        state = "ADMIN_down"
7674
      raise errors.OpExecError("Instance %s is not running (state %s)" %
7675
                               (instance.name, state))
7676

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

    
7679
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
7680
    cluster = self.cfg.GetClusterInfo()
7681
    # beparams and hvparams are passed separately, to avoid editing the
7682
    # instance and then saving the defaults in the instance itself.
7683
    hvparams = cluster.FillHV(instance)
7684
    beparams = cluster.FillBE(instance)
7685
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
7686

    
7687
    # build ssh cmdline
7688
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
7689

    
7690

    
7691
class LUReplaceDisks(LogicalUnit):
7692
  """Replace the disks of an instance.
7693

7694
  """
7695
  HPATH = "mirrors-replace"
7696
  HTYPE = constants.HTYPE_INSTANCE
7697
  _OP_PARAMS = [
7698
    _PInstanceName,
7699
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES)),
7700
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt)),
7701
    ("remote_node", None, ht.TMaybeString),
7702
    ("iallocator", None, ht.TMaybeString),
7703
    ("early_release", False, ht.TBool),
7704
    ]
7705
  REQ_BGL = False
7706

    
7707
  def CheckArguments(self):
7708
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7709
                                  self.op.iallocator)
7710

    
7711
  def ExpandNames(self):
7712
    self._ExpandAndLockInstance()
7713

    
7714
    if self.op.iallocator is not None:
7715
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7716

    
7717
    elif self.op.remote_node is not None:
7718
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7719
      self.op.remote_node = remote_node
7720

    
7721
      # Warning: do not remove the locking of the new secondary here
7722
      # unless DRBD8.AddChildren is changed to work in parallel;
7723
      # currently it doesn't since parallel invocations of
7724
      # FindUnusedMinor will conflict
7725
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7726
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7727

    
7728
    else:
7729
      self.needed_locks[locking.LEVEL_NODE] = []
7730
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7731

    
7732
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7733
                                   self.op.iallocator, self.op.remote_node,
7734
                                   self.op.disks, False, self.op.early_release)
7735

    
7736
    self.tasklets = [self.replacer]
7737

    
7738
  def DeclareLocks(self, level):
7739
    # If we're not already locking all nodes in the set we have to declare the
7740
    # instance's primary/secondary nodes.
7741
    if (level == locking.LEVEL_NODE and
7742
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7743
      self._LockInstancesNodes()
7744

    
7745
  def BuildHooksEnv(self):
7746
    """Build hooks env.
7747

7748
    This runs on the master, the primary and all the secondaries.
7749

7750
    """
7751
    instance = self.replacer.instance
7752
    env = {
7753
      "MODE": self.op.mode,
7754
      "NEW_SECONDARY": self.op.remote_node,
7755
      "OLD_SECONDARY": instance.secondary_nodes[0],
7756
      }
7757
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7758
    nl = [
7759
      self.cfg.GetMasterNode(),
7760
      instance.primary_node,
7761
      ]
7762
    if self.op.remote_node is not None:
7763
      nl.append(self.op.remote_node)
7764
    return env, nl, nl
7765

    
7766

    
7767
class TLReplaceDisks(Tasklet):
7768
  """Replaces disks for an instance.
7769

7770
  Note: Locking is not within the scope of this class.
7771

7772
  """
7773
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7774
               disks, delay_iallocator, early_release):
7775
    """Initializes this class.
7776

7777
    """
7778
    Tasklet.__init__(self, lu)
7779

    
7780
    # Parameters
7781
    self.instance_name = instance_name
7782
    self.mode = mode
7783
    self.iallocator_name = iallocator_name
7784
    self.remote_node = remote_node
7785
    self.disks = disks
7786
    self.delay_iallocator = delay_iallocator
7787
    self.early_release = early_release
7788

    
7789
    # Runtime data
7790
    self.instance = None
7791
    self.new_node = None
7792
    self.target_node = None
7793
    self.other_node = None
7794
    self.remote_node_info = None
7795
    self.node_secondary_ip = None
7796

    
7797
  @staticmethod
7798
  def CheckArguments(mode, remote_node, iallocator):
7799
    """Helper function for users of this class.
7800

7801
    """
7802
    # check for valid parameter combination
7803
    if mode == constants.REPLACE_DISK_CHG:
7804
      if remote_node is None and iallocator is None:
7805
        raise errors.OpPrereqError("When changing the secondary either an"
7806
                                   " iallocator script must be used or the"
7807
                                   " new node given", errors.ECODE_INVAL)
7808

    
7809
      if remote_node is not None and iallocator is not None:
7810
        raise errors.OpPrereqError("Give either the iallocator or the new"
7811
                                   " secondary, not both", errors.ECODE_INVAL)
7812

    
7813
    elif remote_node is not None or iallocator is not None:
7814
      # Not replacing the secondary
7815
      raise errors.OpPrereqError("The iallocator and new node options can"
7816
                                 " only be used when changing the"
7817
                                 " secondary node", errors.ECODE_INVAL)
7818

    
7819
  @staticmethod
7820
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7821
    """Compute a new secondary node using an IAllocator.
7822

7823
    """
7824
    ial = IAllocator(lu.cfg, lu.rpc,
7825
                     mode=constants.IALLOCATOR_MODE_RELOC,
7826
                     name=instance_name,
7827
                     relocate_from=relocate_from)
7828

    
7829
    ial.Run(iallocator_name)
7830

    
7831
    if not ial.success:
7832
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7833
                                 " %s" % (iallocator_name, ial.info),
7834
                                 errors.ECODE_NORES)
7835

    
7836
    if len(ial.result) != ial.required_nodes:
7837
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7838
                                 " of nodes (%s), required %s" %
7839
                                 (iallocator_name,
7840
                                  len(ial.result), ial.required_nodes),
7841
                                 errors.ECODE_FAULT)
7842

    
7843
    remote_node_name = ial.result[0]
7844

    
7845
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7846
               instance_name, remote_node_name)
7847

    
7848
    return remote_node_name
7849

    
7850
  def _FindFaultyDisks(self, node_name):
7851
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7852
                                    node_name, True)
7853

    
7854
  def CheckPrereq(self):
7855
    """Check prerequisites.
7856

7857
    This checks that the instance is in the cluster.
7858

7859
    """
7860
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7861
    assert instance is not None, \
7862
      "Cannot retrieve locked instance %s" % self.instance_name
7863

    
7864
    if instance.disk_template != constants.DT_DRBD8:
7865
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7866
                                 " instances", errors.ECODE_INVAL)
7867

    
7868
    if len(instance.secondary_nodes) != 1:
7869
      raise errors.OpPrereqError("The instance has a strange layout,"
7870
                                 " expected one secondary but found %d" %
7871
                                 len(instance.secondary_nodes),
7872
                                 errors.ECODE_FAULT)
7873

    
7874
    if not self.delay_iallocator:
7875
      self._CheckPrereq2()
7876

    
7877
  def _CheckPrereq2(self):
7878
    """Check prerequisites, second part.
7879

7880
    This function should always be part of CheckPrereq. It was separated and is
7881
    now called from Exec because during node evacuation iallocator was only
7882
    called with an unmodified cluster model, not taking planned changes into
7883
    account.
7884

7885
    """
7886
    instance = self.instance
7887
    secondary_node = instance.secondary_nodes[0]
7888

    
7889
    if self.iallocator_name is None:
7890
      remote_node = self.remote_node
7891
    else:
7892
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
7893
                                       instance.name, instance.secondary_nodes)
7894

    
7895
    if remote_node is not None:
7896
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
7897
      assert self.remote_node_info is not None, \
7898
        "Cannot retrieve locked node %s" % remote_node
7899
    else:
7900
      self.remote_node_info = None
7901

    
7902
    if remote_node == self.instance.primary_node:
7903
      raise errors.OpPrereqError("The specified node is the primary node of"
7904
                                 " the instance.", errors.ECODE_INVAL)
7905

    
7906
    if remote_node == secondary_node:
7907
      raise errors.OpPrereqError("The specified node is already the"
7908
                                 " secondary node of the instance.",
7909
                                 errors.ECODE_INVAL)
7910

    
7911
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
7912
                                    constants.REPLACE_DISK_CHG):
7913
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
7914
                                 errors.ECODE_INVAL)
7915

    
7916
    if self.mode == constants.REPLACE_DISK_AUTO:
7917
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
7918
      faulty_secondary = self._FindFaultyDisks(secondary_node)
7919

    
7920
      if faulty_primary and faulty_secondary:
7921
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
7922
                                   " one node and can not be repaired"
7923
                                   " automatically" % self.instance_name,
7924
                                   errors.ECODE_STATE)
7925

    
7926
      if faulty_primary:
7927
        self.disks = faulty_primary
7928
        self.target_node = instance.primary_node
7929
        self.other_node = secondary_node
7930
        check_nodes = [self.target_node, self.other_node]
7931
      elif faulty_secondary:
7932
        self.disks = faulty_secondary
7933
        self.target_node = secondary_node
7934
        self.other_node = instance.primary_node
7935
        check_nodes = [self.target_node, self.other_node]
7936
      else:
7937
        self.disks = []
7938
        check_nodes = []
7939

    
7940
    else:
7941
      # Non-automatic modes
7942
      if self.mode == constants.REPLACE_DISK_PRI:
7943
        self.target_node = instance.primary_node
7944
        self.other_node = secondary_node
7945
        check_nodes = [self.target_node, self.other_node]
7946

    
7947
      elif self.mode == constants.REPLACE_DISK_SEC:
7948
        self.target_node = secondary_node
7949
        self.other_node = instance.primary_node
7950
        check_nodes = [self.target_node, self.other_node]
7951

    
7952
      elif self.mode == constants.REPLACE_DISK_CHG:
7953
        self.new_node = remote_node
7954
        self.other_node = instance.primary_node
7955
        self.target_node = secondary_node
7956
        check_nodes = [self.new_node, self.other_node]
7957

    
7958
        _CheckNodeNotDrained(self.lu, remote_node)
7959

    
7960
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
7961
        assert old_node_info is not None
7962
        if old_node_info.offline and not self.early_release:
7963
          # doesn't make sense to delay the release
7964
          self.early_release = True
7965
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
7966
                          " early-release mode", secondary_node)
7967

    
7968
      else:
7969
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
7970
                                     self.mode)
7971

    
7972
      # If not specified all disks should be replaced
7973
      if not self.disks:
7974
        self.disks = range(len(self.instance.disks))
7975

    
7976
    for node in check_nodes:
7977
      _CheckNodeOnline(self.lu, node)
7978

    
7979
    # Check whether disks are valid
7980
    for disk_idx in self.disks:
7981
      instance.FindDisk(disk_idx)
7982

    
7983
    # Get secondary node IP addresses
7984
    node_2nd_ip = {}
7985

    
7986
    for node_name in [self.target_node, self.other_node, self.new_node]:
7987
      if node_name is not None:
7988
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
7989

    
7990
    self.node_secondary_ip = node_2nd_ip
7991

    
7992
  def Exec(self, feedback_fn):
7993
    """Execute disk replacement.
7994

7995
    This dispatches the disk replacement to the appropriate handler.
7996

7997
    """
7998
    if self.delay_iallocator:
7999
      self._CheckPrereq2()
8000

    
8001
    if not self.disks:
8002
      feedback_fn("No disks need replacement")
8003
      return
8004

    
8005
    feedback_fn("Replacing disk(s) %s for %s" %
8006
                (utils.CommaJoin(self.disks), self.instance.name))
8007

    
8008
    activate_disks = (not self.instance.admin_up)
8009

    
8010
    # Activate the instance disks if we're replacing them on a down instance
8011
    if activate_disks:
8012
      _StartInstanceDisks(self.lu, self.instance, True)
8013

    
8014
    try:
8015
      # Should we replace the secondary node?
8016
      if self.new_node is not None:
8017
        fn = self._ExecDrbd8Secondary
8018
      else:
8019
        fn = self._ExecDrbd8DiskOnly
8020

    
8021
      return fn(feedback_fn)
8022

    
8023
    finally:
8024
      # Deactivate the instance disks if we're replacing them on a
8025
      # down instance
8026
      if activate_disks:
8027
        _SafeShutdownInstanceDisks(self.lu, self.instance)
8028

    
8029
  def _CheckVolumeGroup(self, nodes):
8030
    self.lu.LogInfo("Checking volume groups")
8031

    
8032
    vgname = self.cfg.GetVGName()
8033

    
8034
    # Make sure volume group exists on all involved nodes
8035
    results = self.rpc.call_vg_list(nodes)
8036
    if not results:
8037
      raise errors.OpExecError("Can't list volume groups on the nodes")
8038

    
8039
    for node in nodes:
8040
      res = results[node]
8041
      res.Raise("Error checking node %s" % node)
8042
      if vgname not in res.payload:
8043
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
8044
                                 (vgname, node))
8045

    
8046
  def _CheckDisksExistence(self, nodes):
8047
    # Check disk existence
8048
    for idx, dev in enumerate(self.instance.disks):
8049
      if idx not in self.disks:
8050
        continue
8051

    
8052
      for node in nodes:
8053
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
8054
        self.cfg.SetDiskID(dev, node)
8055

    
8056
        result = self.rpc.call_blockdev_find(node, dev)
8057

    
8058
        msg = result.fail_msg
8059
        if msg or not result.payload:
8060
          if not msg:
8061
            msg = "disk not found"
8062
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
8063
                                   (idx, node, msg))
8064

    
8065
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
8066
    for idx, dev in enumerate(self.instance.disks):
8067
      if idx not in self.disks:
8068
        continue
8069

    
8070
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
8071
                      (idx, node_name))
8072

    
8073
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
8074
                                   ldisk=ldisk):
8075
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
8076
                                 " replace disks for instance %s" %
8077
                                 (node_name, self.instance.name))
8078

    
8079
  def _CreateNewStorage(self, node_name):
8080
    vgname = self.cfg.GetVGName()
8081
    iv_names = {}
8082

    
8083
    for idx, dev in enumerate(self.instance.disks):
8084
      if idx not in self.disks:
8085
        continue
8086

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

    
8089
      self.cfg.SetDiskID(dev, node_name)
8090

    
8091
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
8092
      names = _GenerateUniqueNames(self.lu, lv_names)
8093

    
8094
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
8095
                             logical_id=(vgname, names[0]))
8096
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
8097
                             logical_id=(vgname, names[1]))
8098

    
8099
      new_lvs = [lv_data, lv_meta]
8100
      old_lvs = dev.children
8101
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
8102

    
8103
      # we pass force_create=True to force the LVM creation
8104
      for new_lv in new_lvs:
8105
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
8106
                        _GetInstanceInfoText(self.instance), False)
8107

    
8108
    return iv_names
8109

    
8110
  def _CheckDevices(self, node_name, iv_names):
8111
    for name, (dev, _, _) in iv_names.iteritems():
8112
      self.cfg.SetDiskID(dev, node_name)
8113

    
8114
      result = self.rpc.call_blockdev_find(node_name, dev)
8115

    
8116
      msg = result.fail_msg
8117
      if msg or not result.payload:
8118
        if not msg:
8119
          msg = "disk not found"
8120
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
8121
                                 (name, msg))
8122

    
8123
      if result.payload.is_degraded:
8124
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
8125

    
8126
  def _RemoveOldStorage(self, node_name, iv_names):
8127
    for name, (_, old_lvs, _) in iv_names.iteritems():
8128
      self.lu.LogInfo("Remove logical volumes for %s" % name)
8129

    
8130
      for lv in old_lvs:
8131
        self.cfg.SetDiskID(lv, node_name)
8132

    
8133
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
8134
        if msg:
8135
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
8136
                             hint="remove unused LVs manually")
8137

    
8138
  def _ReleaseNodeLock(self, node_name):
8139
    """Releases the lock for a given node."""
8140
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
8141

    
8142
  def _ExecDrbd8DiskOnly(self, feedback_fn):
8143
    """Replace a disk on the primary or secondary for DRBD 8.
8144

8145
    The algorithm for replace is quite complicated:
8146

8147
      1. for each disk to be replaced:
8148

8149
        1. create new LVs on the target node with unique names
8150
        1. detach old LVs from the drbd device
8151
        1. rename old LVs to name_replaced.<time_t>
8152
        1. rename new LVs to old LVs
8153
        1. attach the new LVs (with the old names now) to the drbd device
8154

8155
      1. wait for sync across all devices
8156

8157
      1. for each modified disk:
8158

8159
        1. remove old LVs (which have the name name_replaces.<time_t>)
8160

8161
    Failures are not very well handled.
8162

8163
    """
8164
    steps_total = 6
8165

    
8166
    # Step: check device activation
8167
    self.lu.LogStep(1, steps_total, "Check device existence")
8168
    self._CheckDisksExistence([self.other_node, self.target_node])
8169
    self._CheckVolumeGroup([self.target_node, self.other_node])
8170

    
8171
    # Step: check other node consistency
8172
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8173
    self._CheckDisksConsistency(self.other_node,
8174
                                self.other_node == self.instance.primary_node,
8175
                                False)
8176

    
8177
    # Step: create new storage
8178
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8179
    iv_names = self._CreateNewStorage(self.target_node)
8180

    
8181
    # Step: for each lv, detach+rename*2+attach
8182
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8183
    for dev, old_lvs, new_lvs in iv_names.itervalues():
8184
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
8185

    
8186
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
8187
                                                     old_lvs)
8188
      result.Raise("Can't detach drbd from local storage on node"
8189
                   " %s for device %s" % (self.target_node, dev.iv_name))
8190
      #dev.children = []
8191
      #cfg.Update(instance)
8192

    
8193
      # ok, we created the new LVs, so now we know we have the needed
8194
      # storage; as such, we proceed on the target node to rename
8195
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
8196
      # using the assumption that logical_id == physical_id (which in
8197
      # turn is the unique_id on that node)
8198

    
8199
      # FIXME(iustin): use a better name for the replaced LVs
8200
      temp_suffix = int(time.time())
8201
      ren_fn = lambda d, suff: (d.physical_id[0],
8202
                                d.physical_id[1] + "_replaced-%s" % suff)
8203

    
8204
      # Build the rename list based on what LVs exist on the node
8205
      rename_old_to_new = []
8206
      for to_ren in old_lvs:
8207
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
8208
        if not result.fail_msg and result.payload:
8209
          # device exists
8210
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
8211

    
8212
      self.lu.LogInfo("Renaming the old LVs on the target node")
8213
      result = self.rpc.call_blockdev_rename(self.target_node,
8214
                                             rename_old_to_new)
8215
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
8216

    
8217
      # Now we rename the new LVs to the old LVs
8218
      self.lu.LogInfo("Renaming the new LVs on the target node")
8219
      rename_new_to_old = [(new, old.physical_id)
8220
                           for old, new in zip(old_lvs, new_lvs)]
8221
      result = self.rpc.call_blockdev_rename(self.target_node,
8222
                                             rename_new_to_old)
8223
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
8224

    
8225
      for old, new in zip(old_lvs, new_lvs):
8226
        new.logical_id = old.logical_id
8227
        self.cfg.SetDiskID(new, self.target_node)
8228

    
8229
      for disk in old_lvs:
8230
        disk.logical_id = ren_fn(disk, temp_suffix)
8231
        self.cfg.SetDiskID(disk, self.target_node)
8232

    
8233
      # Now that the new lvs have the old name, we can add them to the device
8234
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
8235
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
8236
                                                  new_lvs)
8237
      msg = result.fail_msg
8238
      if msg:
8239
        for new_lv in new_lvs:
8240
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
8241
                                               new_lv).fail_msg
8242
          if msg2:
8243
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
8244
                               hint=("cleanup manually the unused logical"
8245
                                     "volumes"))
8246
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8247

    
8248
      dev.children = new_lvs
8249

    
8250
      self.cfg.Update(self.instance, feedback_fn)
8251

    
8252
    cstep = 5
8253
    if self.early_release:
8254
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8255
      cstep += 1
8256
      self._RemoveOldStorage(self.target_node, iv_names)
8257
      # WARNING: we release both node locks here, do not do other RPCs
8258
      # than WaitForSync to the primary node
8259
      self._ReleaseNodeLock([self.target_node, self.other_node])
8260

    
8261
    # Wait for sync
8262
    # This can fail as the old devices are degraded and _WaitForSync
8263
    # does a combined result over all disks, so we don't check its return value
8264
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8265
    cstep += 1
8266
    _WaitForSync(self.lu, self.instance)
8267

    
8268
    # Check all devices manually
8269
    self._CheckDevices(self.instance.primary_node, iv_names)
8270

    
8271
    # Step: remove old storage
8272
    if not self.early_release:
8273
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8274
      cstep += 1
8275
      self._RemoveOldStorage(self.target_node, iv_names)
8276

    
8277
  def _ExecDrbd8Secondary(self, feedback_fn):
8278
    """Replace the secondary node for DRBD 8.
8279

8280
    The algorithm for replace is quite complicated:
8281
      - for all disks of the instance:
8282
        - create new LVs on the new node with same names
8283
        - shutdown the drbd device on the old secondary
8284
        - disconnect the drbd network on the primary
8285
        - create the drbd device on the new secondary
8286
        - network attach the drbd on the primary, using an artifice:
8287
          the drbd code for Attach() will connect to the network if it
8288
          finds a device which is connected to the good local disks but
8289
          not network enabled
8290
      - wait for sync across all devices
8291
      - remove all disks from the old secondary
8292

8293
    Failures are not very well handled.
8294

8295
    """
8296
    steps_total = 6
8297

    
8298
    # Step: check device activation
8299
    self.lu.LogStep(1, steps_total, "Check device existence")
8300
    self._CheckDisksExistence([self.instance.primary_node])
8301
    self._CheckVolumeGroup([self.instance.primary_node])
8302

    
8303
    # Step: check other node consistency
8304
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8305
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8306

    
8307
    # Step: create new storage
8308
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8309
    for idx, dev in enumerate(self.instance.disks):
8310
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8311
                      (self.new_node, idx))
8312
      # we pass force_create=True to force LVM creation
8313
      for new_lv in dev.children:
8314
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8315
                        _GetInstanceInfoText(self.instance), False)
8316

    
8317
    # Step 4: dbrd minors and drbd setups changes
8318
    # after this, we must manually remove the drbd minors on both the
8319
    # error and the success paths
8320
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8321
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8322
                                         for dev in self.instance.disks],
8323
                                        self.instance.name)
8324
    logging.debug("Allocated minors %r", minors)
8325

    
8326
    iv_names = {}
8327
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8328
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8329
                      (self.new_node, idx))
8330
      # create new devices on new_node; note that we create two IDs:
8331
      # one without port, so the drbd will be activated without
8332
      # networking information on the new node at this stage, and one
8333
      # with network, for the latter activation in step 4
8334
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8335
      if self.instance.primary_node == o_node1:
8336
        p_minor = o_minor1
8337
      else:
8338
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8339
        p_minor = o_minor2
8340

    
8341
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8342
                      p_minor, new_minor, o_secret)
8343
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8344
                    p_minor, new_minor, o_secret)
8345

    
8346
      iv_names[idx] = (dev, dev.children, new_net_id)
8347
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8348
                    new_net_id)
8349
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8350
                              logical_id=new_alone_id,
8351
                              children=dev.children,
8352
                              size=dev.size)
8353
      try:
8354
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8355
                              _GetInstanceInfoText(self.instance), False)
8356
      except errors.GenericError:
8357
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8358
        raise
8359

    
8360
    # We have new devices, shutdown the drbd on the old secondary
8361
    for idx, dev in enumerate(self.instance.disks):
8362
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8363
      self.cfg.SetDiskID(dev, self.target_node)
8364
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8365
      if msg:
8366
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8367
                           "node: %s" % (idx, msg),
8368
                           hint=("Please cleanup this device manually as"
8369
                                 " soon as possible"))
8370

    
8371
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8372
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8373
                                               self.node_secondary_ip,
8374
                                               self.instance.disks)\
8375
                                              [self.instance.primary_node]
8376

    
8377
    msg = result.fail_msg
8378
    if msg:
8379
      # detaches didn't succeed (unlikely)
8380
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8381
      raise errors.OpExecError("Can't detach the disks from the network on"
8382
                               " old node: %s" % (msg,))
8383

    
8384
    # if we managed to detach at least one, we update all the disks of
8385
    # the instance to point to the new secondary
8386
    self.lu.LogInfo("Updating instance configuration")
8387
    for dev, _, new_logical_id in iv_names.itervalues():
8388
      dev.logical_id = new_logical_id
8389
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8390

    
8391
    self.cfg.Update(self.instance, feedback_fn)
8392

    
8393
    # and now perform the drbd attach
8394
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8395
                    " (standalone => connected)")
8396
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8397
                                            self.new_node],
8398
                                           self.node_secondary_ip,
8399
                                           self.instance.disks,
8400
                                           self.instance.name,
8401
                                           False)
8402
    for to_node, to_result in result.items():
8403
      msg = to_result.fail_msg
8404
      if msg:
8405
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8406
                           to_node, msg,
8407
                           hint=("please do a gnt-instance info to see the"
8408
                                 " status of disks"))
8409
    cstep = 5
8410
    if self.early_release:
8411
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8412
      cstep += 1
8413
      self._RemoveOldStorage(self.target_node, iv_names)
8414
      # WARNING: we release all node locks here, do not do other RPCs
8415
      # than WaitForSync to the primary node
8416
      self._ReleaseNodeLock([self.instance.primary_node,
8417
                             self.target_node,
8418
                             self.new_node])
8419

    
8420
    # Wait for sync
8421
    # This can fail as the old devices are degraded and _WaitForSync
8422
    # does a combined result over all disks, so we don't check its return value
8423
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8424
    cstep += 1
8425
    _WaitForSync(self.lu, self.instance)
8426

    
8427
    # Check all devices manually
8428
    self._CheckDevices(self.instance.primary_node, iv_names)
8429

    
8430
    # Step: remove old storage
8431
    if not self.early_release:
8432
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8433
      self._RemoveOldStorage(self.target_node, iv_names)
8434

    
8435

    
8436
class LURepairNodeStorage(NoHooksLU):
8437
  """Repairs the volume group on a node.
8438

8439
  """
8440
  _OP_PARAMS = [
8441
    _PNodeName,
8442
    ("storage_type", ht.NoDefault, _CheckStorageType),
8443
    ("name", ht.NoDefault, ht.TNonEmptyString),
8444
    ("ignore_consistency", False, ht.TBool),
8445
    ]
8446
  REQ_BGL = False
8447

    
8448
  def CheckArguments(self):
8449
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8450

    
8451
    storage_type = self.op.storage_type
8452

    
8453
    if (constants.SO_FIX_CONSISTENCY not in
8454
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8455
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8456
                                 " repaired" % storage_type,
8457
                                 errors.ECODE_INVAL)
8458

    
8459
  def ExpandNames(self):
8460
    self.needed_locks = {
8461
      locking.LEVEL_NODE: [self.op.node_name],
8462
      }
8463

    
8464
  def _CheckFaultyDisks(self, instance, node_name):
8465
    """Ensure faulty disks abort the opcode or at least warn."""
8466
    try:
8467
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8468
                                  node_name, True):
8469
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8470
                                   " node '%s'" % (instance.name, node_name),
8471
                                   errors.ECODE_STATE)
8472
    except errors.OpPrereqError, err:
8473
      if self.op.ignore_consistency:
8474
        self.proc.LogWarning(str(err.args[0]))
8475
      else:
8476
        raise
8477

    
8478
  def CheckPrereq(self):
8479
    """Check prerequisites.
8480

8481
    """
8482
    # Check whether any instance on this node has faulty disks
8483
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8484
      if not inst.admin_up:
8485
        continue
8486
      check_nodes = set(inst.all_nodes)
8487
      check_nodes.discard(self.op.node_name)
8488
      for inst_node_name in check_nodes:
8489
        self._CheckFaultyDisks(inst, inst_node_name)
8490

    
8491
  def Exec(self, feedback_fn):
8492
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8493
                (self.op.name, self.op.node_name))
8494

    
8495
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8496
    result = self.rpc.call_storage_execute(self.op.node_name,
8497
                                           self.op.storage_type, st_args,
8498
                                           self.op.name,
8499
                                           constants.SO_FIX_CONSISTENCY)
8500
    result.Raise("Failed to repair storage unit '%s' on %s" %
8501
                 (self.op.name, self.op.node_name))
8502

    
8503

    
8504
class LUNodeEvacuationStrategy(NoHooksLU):
8505
  """Computes the node evacuation strategy.
8506

8507
  """
8508
  _OP_PARAMS = [
8509
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
8510
    ("remote_node", None, ht.TMaybeString),
8511
    ("iallocator", None, ht.TMaybeString),
8512
    ]
8513
  REQ_BGL = False
8514

    
8515
  def CheckArguments(self):
8516
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8517

    
8518
  def ExpandNames(self):
8519
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8520
    self.needed_locks = locks = {}
8521
    if self.op.remote_node is None:
8522
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8523
    else:
8524
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8525
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8526

    
8527
  def Exec(self, feedback_fn):
8528
    if self.op.remote_node is not None:
8529
      instances = []
8530
      for node in self.op.nodes:
8531
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8532
      result = []
8533
      for i in instances:
8534
        if i.primary_node == self.op.remote_node:
8535
          raise errors.OpPrereqError("Node %s is the primary node of"
8536
                                     " instance %s, cannot use it as"
8537
                                     " secondary" %
8538
                                     (self.op.remote_node, i.name),
8539
                                     errors.ECODE_INVAL)
8540
        result.append([i.name, self.op.remote_node])
8541
    else:
8542
      ial = IAllocator(self.cfg, self.rpc,
8543
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8544
                       evac_nodes=self.op.nodes)
8545
      ial.Run(self.op.iallocator, validate=True)
8546
      if not ial.success:
8547
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8548
                                 errors.ECODE_NORES)
8549
      result = ial.result
8550
    return result
8551

    
8552

    
8553
class LUGrowDisk(LogicalUnit):
8554
  """Grow a disk of an instance.
8555

8556
  """
8557
  HPATH = "disk-grow"
8558
  HTYPE = constants.HTYPE_INSTANCE
8559
  _OP_PARAMS = [
8560
    _PInstanceName,
8561
    ("disk", ht.NoDefault, ht.TInt),
8562
    ("amount", ht.NoDefault, ht.TInt),
8563
    ("wait_for_sync", True, ht.TBool),
8564
    ]
8565
  REQ_BGL = False
8566

    
8567
  def ExpandNames(self):
8568
    self._ExpandAndLockInstance()
8569
    self.needed_locks[locking.LEVEL_NODE] = []
8570
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8571

    
8572
  def DeclareLocks(self, level):
8573
    if level == locking.LEVEL_NODE:
8574
      self._LockInstancesNodes()
8575

    
8576
  def BuildHooksEnv(self):
8577
    """Build hooks env.
8578

8579
    This runs on the master, the primary and all the secondaries.
8580

8581
    """
8582
    env = {
8583
      "DISK": self.op.disk,
8584
      "AMOUNT": self.op.amount,
8585
      }
8586
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8587
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8588
    return env, nl, nl
8589

    
8590
  def CheckPrereq(self):
8591
    """Check prerequisites.
8592

8593
    This checks that the instance is in the cluster.
8594

8595
    """
8596
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8597
    assert instance is not None, \
8598
      "Cannot retrieve locked instance %s" % self.op.instance_name
8599
    nodenames = list(instance.all_nodes)
8600
    for node in nodenames:
8601
      _CheckNodeOnline(self, node)
8602

    
8603
    self.instance = instance
8604

    
8605
    if instance.disk_template not in constants.DTS_GROWABLE:
8606
      raise errors.OpPrereqError("Instance's disk layout does not support"
8607
                                 " growing.", errors.ECODE_INVAL)
8608

    
8609
    self.disk = instance.FindDisk(self.op.disk)
8610

    
8611
    if instance.disk_template != constants.DT_FILE:
8612
      # TODO: check the free disk space for file, when that feature will be
8613
      # supported
8614
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
8615

    
8616
  def Exec(self, feedback_fn):
8617
    """Execute disk grow.
8618

8619
    """
8620
    instance = self.instance
8621
    disk = self.disk
8622

    
8623
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8624
    if not disks_ok:
8625
      raise errors.OpExecError("Cannot activate block device to grow")
8626

    
8627
    for node in instance.all_nodes:
8628
      self.cfg.SetDiskID(disk, node)
8629
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8630
      result.Raise("Grow request failed to node %s" % node)
8631

    
8632
      # TODO: Rewrite code to work properly
8633
      # DRBD goes into sync mode for a short amount of time after executing the
8634
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8635
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8636
      # time is a work-around.
8637
      time.sleep(5)
8638

    
8639
    disk.RecordGrow(self.op.amount)
8640
    self.cfg.Update(instance, feedback_fn)
8641
    if self.op.wait_for_sync:
8642
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8643
      if disk_abort:
8644
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8645
                             " status.\nPlease check the instance.")
8646
      if not instance.admin_up:
8647
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8648
    elif not instance.admin_up:
8649
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8650
                           " not supposed to be running because no wait for"
8651
                           " sync mode was requested.")
8652

    
8653

    
8654
class LUQueryInstanceData(NoHooksLU):
8655
  """Query runtime instance data.
8656

8657
  """
8658
  _OP_PARAMS = [
8659
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
8660
    ("static", False, ht.TBool),
8661
    ]
8662
  REQ_BGL = False
8663

    
8664
  def ExpandNames(self):
8665
    self.needed_locks = {}
8666
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8667

    
8668
    if self.op.instances:
8669
      self.wanted_names = []
8670
      for name in self.op.instances:
8671
        full_name = _ExpandInstanceName(self.cfg, name)
8672
        self.wanted_names.append(full_name)
8673
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8674
    else:
8675
      self.wanted_names = None
8676
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8677

    
8678
    self.needed_locks[locking.LEVEL_NODE] = []
8679
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8680

    
8681
  def DeclareLocks(self, level):
8682
    if level == locking.LEVEL_NODE:
8683
      self._LockInstancesNodes()
8684

    
8685
  def CheckPrereq(self):
8686
    """Check prerequisites.
8687

8688
    This only checks the optional instance list against the existing names.
8689

8690
    """
8691
    if self.wanted_names is None:
8692
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8693

    
8694
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8695
                             in self.wanted_names]
8696

    
8697
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8698
    """Returns the status of a block device
8699

8700
    """
8701
    if self.op.static or not node:
8702
      return None
8703

    
8704
    self.cfg.SetDiskID(dev, node)
8705

    
8706
    result = self.rpc.call_blockdev_find(node, dev)
8707
    if result.offline:
8708
      return None
8709

    
8710
    result.Raise("Can't compute disk status for %s" % instance_name)
8711

    
8712
    status = result.payload
8713
    if status is None:
8714
      return None
8715

    
8716
    return (status.dev_path, status.major, status.minor,
8717
            status.sync_percent, status.estimated_time,
8718
            status.is_degraded, status.ldisk_status)
8719

    
8720
  def _ComputeDiskStatus(self, instance, snode, dev):
8721
    """Compute block device status.
8722

8723
    """
8724
    if dev.dev_type in constants.LDS_DRBD:
8725
      # we change the snode then (otherwise we use the one passed in)
8726
      if dev.logical_id[0] == instance.primary_node:
8727
        snode = dev.logical_id[1]
8728
      else:
8729
        snode = dev.logical_id[0]
8730

    
8731
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8732
                                              instance.name, dev)
8733
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8734

    
8735
    if dev.children:
8736
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8737
                      for child in dev.children]
8738
    else:
8739
      dev_children = []
8740

    
8741
    data = {
8742
      "iv_name": dev.iv_name,
8743
      "dev_type": dev.dev_type,
8744
      "logical_id": dev.logical_id,
8745
      "physical_id": dev.physical_id,
8746
      "pstatus": dev_pstatus,
8747
      "sstatus": dev_sstatus,
8748
      "children": dev_children,
8749
      "mode": dev.mode,
8750
      "size": dev.size,
8751
      }
8752

    
8753
    return data
8754

    
8755
  def Exec(self, feedback_fn):
8756
    """Gather and return data"""
8757
    result = {}
8758

    
8759
    cluster = self.cfg.GetClusterInfo()
8760

    
8761
    for instance in self.wanted_instances:
8762
      if not self.op.static:
8763
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8764
                                                  instance.name,
8765
                                                  instance.hypervisor)
8766
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8767
        remote_info = remote_info.payload
8768
        if remote_info and "state" in remote_info:
8769
          remote_state = "up"
8770
        else:
8771
          remote_state = "down"
8772
      else:
8773
        remote_state = None
8774
      if instance.admin_up:
8775
        config_state = "up"
8776
      else:
8777
        config_state = "down"
8778

    
8779
      disks = [self._ComputeDiskStatus(instance, None, device)
8780
               for device in instance.disks]
8781

    
8782
      idict = {
8783
        "name": instance.name,
8784
        "config_state": config_state,
8785
        "run_state": remote_state,
8786
        "pnode": instance.primary_node,
8787
        "snodes": instance.secondary_nodes,
8788
        "os": instance.os,
8789
        # this happens to be the same format used for hooks
8790
        "nics": _NICListToTuple(self, instance.nics),
8791
        "disk_template": instance.disk_template,
8792
        "disks": disks,
8793
        "hypervisor": instance.hypervisor,
8794
        "network_port": instance.network_port,
8795
        "hv_instance": instance.hvparams,
8796
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8797
        "be_instance": instance.beparams,
8798
        "be_actual": cluster.FillBE(instance),
8799
        "os_instance": instance.osparams,
8800
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8801
        "serial_no": instance.serial_no,
8802
        "mtime": instance.mtime,
8803
        "ctime": instance.ctime,
8804
        "uuid": instance.uuid,
8805
        }
8806

    
8807
      result[instance.name] = idict
8808

    
8809
    return result
8810

    
8811

    
8812
class LUSetInstanceParams(LogicalUnit):
8813
  """Modifies an instances's parameters.
8814

8815
  """
8816
  HPATH = "instance-modify"
8817
  HTYPE = constants.HTYPE_INSTANCE
8818
  _OP_PARAMS = [
8819
    _PInstanceName,
8820
    ("nics", ht.EmptyList, ht.TList),
8821
    ("disks", ht.EmptyList, ht.TList),
8822
    ("beparams", ht.EmptyDict, ht.TDict),
8823
    ("hvparams", ht.EmptyDict, ht.TDict),
8824
    ("disk_template", None, ht.TMaybeString),
8825
    ("remote_node", None, ht.TMaybeString),
8826
    ("os_name", None, ht.TMaybeString),
8827
    ("force_variant", False, ht.TBool),
8828
    ("osparams", None, ht.TOr(ht.TDict, ht.TNone)),
8829
    _PForce,
8830
    ]
8831
  REQ_BGL = False
8832

    
8833
  def CheckArguments(self):
8834
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8835
            self.op.hvparams or self.op.beparams or self.op.os_name):
8836
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8837

    
8838
    if self.op.hvparams:
8839
      _CheckGlobalHvParams(self.op.hvparams)
8840

    
8841
    # Disk validation
8842
    disk_addremove = 0
8843
    for disk_op, disk_dict in self.op.disks:
8844
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8845
      if disk_op == constants.DDM_REMOVE:
8846
        disk_addremove += 1
8847
        continue
8848
      elif disk_op == constants.DDM_ADD:
8849
        disk_addremove += 1
8850
      else:
8851
        if not isinstance(disk_op, int):
8852
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8853
        if not isinstance(disk_dict, dict):
8854
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8855
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8856

    
8857
      if disk_op == constants.DDM_ADD:
8858
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8859
        if mode not in constants.DISK_ACCESS_SET:
8860
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8861
                                     errors.ECODE_INVAL)
8862
        size = disk_dict.get('size', None)
8863
        if size is None:
8864
          raise errors.OpPrereqError("Required disk parameter size missing",
8865
                                     errors.ECODE_INVAL)
8866
        try:
8867
          size = int(size)
8868
        except (TypeError, ValueError), err:
8869
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8870
                                     str(err), errors.ECODE_INVAL)
8871
        disk_dict['size'] = size
8872
      else:
8873
        # modification of disk
8874
        if 'size' in disk_dict:
8875
          raise errors.OpPrereqError("Disk size change not possible, use"
8876
                                     " grow-disk", errors.ECODE_INVAL)
8877

    
8878
    if disk_addremove > 1:
8879
      raise errors.OpPrereqError("Only one disk add or remove operation"
8880
                                 " supported at a time", errors.ECODE_INVAL)
8881

    
8882
    if self.op.disks and self.op.disk_template is not None:
8883
      raise errors.OpPrereqError("Disk template conversion and other disk"
8884
                                 " changes not supported at the same time",
8885
                                 errors.ECODE_INVAL)
8886

    
8887
    if self.op.disk_template:
8888
      _CheckDiskTemplate(self.op.disk_template)
8889
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
8890
          self.op.remote_node is None):
8891
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
8892
                                   " one requires specifying a secondary node",
8893
                                   errors.ECODE_INVAL)
8894

    
8895
    # NIC validation
8896
    nic_addremove = 0
8897
    for nic_op, nic_dict in self.op.nics:
8898
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
8899
      if nic_op == constants.DDM_REMOVE:
8900
        nic_addremove += 1
8901
        continue
8902
      elif nic_op == constants.DDM_ADD:
8903
        nic_addremove += 1
8904
      else:
8905
        if not isinstance(nic_op, int):
8906
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
8907
        if not isinstance(nic_dict, dict):
8908
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
8909
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8910

    
8911
      # nic_dict should be a dict
8912
      nic_ip = nic_dict.get('ip', None)
8913
      if nic_ip is not None:
8914
        if nic_ip.lower() == constants.VALUE_NONE:
8915
          nic_dict['ip'] = None
8916
        else:
8917
          if not netutils.IPAddress.IsValid(nic_ip):
8918
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
8919
                                       errors.ECODE_INVAL)
8920

    
8921
      nic_bridge = nic_dict.get('bridge', None)
8922
      nic_link = nic_dict.get('link', None)
8923
      if nic_bridge and nic_link:
8924
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
8925
                                   " at the same time", errors.ECODE_INVAL)
8926
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
8927
        nic_dict['bridge'] = None
8928
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
8929
        nic_dict['link'] = None
8930

    
8931
      if nic_op == constants.DDM_ADD:
8932
        nic_mac = nic_dict.get('mac', None)
8933
        if nic_mac is None:
8934
          nic_dict['mac'] = constants.VALUE_AUTO
8935

    
8936
      if 'mac' in nic_dict:
8937
        nic_mac = nic_dict['mac']
8938
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8939
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
8940

    
8941
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
8942
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
8943
                                     " modifying an existing nic",
8944
                                     errors.ECODE_INVAL)
8945

    
8946
    if nic_addremove > 1:
8947
      raise errors.OpPrereqError("Only one NIC add or remove operation"
8948
                                 " supported at a time", errors.ECODE_INVAL)
8949

    
8950
  def ExpandNames(self):
8951
    self._ExpandAndLockInstance()
8952
    self.needed_locks[locking.LEVEL_NODE] = []
8953
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8954

    
8955
  def DeclareLocks(self, level):
8956
    if level == locking.LEVEL_NODE:
8957
      self._LockInstancesNodes()
8958
      if self.op.disk_template and self.op.remote_node:
8959
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8960
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
8961

    
8962
  def BuildHooksEnv(self):
8963
    """Build hooks env.
8964

8965
    This runs on the master, primary and secondaries.
8966

8967
    """
8968
    args = dict()
8969
    if constants.BE_MEMORY in self.be_new:
8970
      args['memory'] = self.be_new[constants.BE_MEMORY]
8971
    if constants.BE_VCPUS in self.be_new:
8972
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
8973
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
8974
    # information at all.
8975
    if self.op.nics:
8976
      args['nics'] = []
8977
      nic_override = dict(self.op.nics)
8978
      for idx, nic in enumerate(self.instance.nics):
8979
        if idx in nic_override:
8980
          this_nic_override = nic_override[idx]
8981
        else:
8982
          this_nic_override = {}
8983
        if 'ip' in this_nic_override:
8984
          ip = this_nic_override['ip']
8985
        else:
8986
          ip = nic.ip
8987
        if 'mac' in this_nic_override:
8988
          mac = this_nic_override['mac']
8989
        else:
8990
          mac = nic.mac
8991
        if idx in self.nic_pnew:
8992
          nicparams = self.nic_pnew[idx]
8993
        else:
8994
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
8995
        mode = nicparams[constants.NIC_MODE]
8996
        link = nicparams[constants.NIC_LINK]
8997
        args['nics'].append((ip, mac, mode, link))
8998
      if constants.DDM_ADD in nic_override:
8999
        ip = nic_override[constants.DDM_ADD].get('ip', None)
9000
        mac = nic_override[constants.DDM_ADD]['mac']
9001
        nicparams = self.nic_pnew[constants.DDM_ADD]
9002
        mode = nicparams[constants.NIC_MODE]
9003
        link = nicparams[constants.NIC_LINK]
9004
        args['nics'].append((ip, mac, mode, link))
9005
      elif constants.DDM_REMOVE in nic_override:
9006
        del args['nics'][-1]
9007

    
9008
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
9009
    if self.op.disk_template:
9010
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
9011
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9012
    return env, nl, nl
9013

    
9014
  def CheckPrereq(self):
9015
    """Check prerequisites.
9016

9017
    This only checks the instance list against the existing names.
9018

9019
    """
9020
    # checking the new params on the primary/secondary nodes
9021

    
9022
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9023
    cluster = self.cluster = self.cfg.GetClusterInfo()
9024
    assert self.instance is not None, \
9025
      "Cannot retrieve locked instance %s" % self.op.instance_name
9026
    pnode = instance.primary_node
9027
    nodelist = list(instance.all_nodes)
9028

    
9029
    # OS change
9030
    if self.op.os_name and not self.op.force:
9031
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
9032
                      self.op.force_variant)
9033
      instance_os = self.op.os_name
9034
    else:
9035
      instance_os = instance.os
9036

    
9037
    if self.op.disk_template:
9038
      if instance.disk_template == self.op.disk_template:
9039
        raise errors.OpPrereqError("Instance already has disk template %s" %
9040
                                   instance.disk_template, errors.ECODE_INVAL)
9041

    
9042
      if (instance.disk_template,
9043
          self.op.disk_template) not in self._DISK_CONVERSIONS:
9044
        raise errors.OpPrereqError("Unsupported disk template conversion from"
9045
                                   " %s to %s" % (instance.disk_template,
9046
                                                  self.op.disk_template),
9047
                                   errors.ECODE_INVAL)
9048
      _CheckInstanceDown(self, instance, "cannot change disk template")
9049
      if self.op.disk_template in constants.DTS_NET_MIRROR:
9050
        if self.op.remote_node == pnode:
9051
          raise errors.OpPrereqError("Given new secondary node %s is the same"
9052
                                     " as the primary node of the instance" %
9053
                                     self.op.remote_node, errors.ECODE_STATE)
9054
        _CheckNodeOnline(self, self.op.remote_node)
9055
        _CheckNodeNotDrained(self, self.op.remote_node)
9056
        disks = [{"size": d.size} for d in instance.disks]
9057
        required = _ComputeDiskSize(self.op.disk_template, disks)
9058
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
9059

    
9060
    # hvparams processing
9061
    if self.op.hvparams:
9062
      hv_type = instance.hypervisor
9063
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
9064
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
9065
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
9066

    
9067
      # local check
9068
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
9069
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
9070
      self.hv_new = hv_new # the new actual values
9071
      self.hv_inst = i_hvdict # the new dict (without defaults)
9072
    else:
9073
      self.hv_new = self.hv_inst = {}
9074

    
9075
    # beparams processing
9076
    if self.op.beparams:
9077
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
9078
                                   use_none=True)
9079
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
9080
      be_new = cluster.SimpleFillBE(i_bedict)
9081
      self.be_new = be_new # the new actual values
9082
      self.be_inst = i_bedict # the new dict (without defaults)
9083
    else:
9084
      self.be_new = self.be_inst = {}
9085

    
9086
    # osparams processing
9087
    if self.op.osparams:
9088
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
9089
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
9090
      self.os_inst = i_osdict # the new dict (without defaults)
9091
    else:
9092
      self.os_inst = {}
9093

    
9094
    self.warn = []
9095

    
9096
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
9097
      mem_check_list = [pnode]
9098
      if be_new[constants.BE_AUTO_BALANCE]:
9099
        # either we changed auto_balance to yes or it was from before
9100
        mem_check_list.extend(instance.secondary_nodes)
9101
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
9102
                                                  instance.hypervisor)
9103
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
9104
                                         instance.hypervisor)
9105
      pninfo = nodeinfo[pnode]
9106
      msg = pninfo.fail_msg
9107
      if msg:
9108
        # Assume the primary node is unreachable and go ahead
9109
        self.warn.append("Can't get info from primary node %s: %s" %
9110
                         (pnode,  msg))
9111
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
9112
        self.warn.append("Node data from primary node %s doesn't contain"
9113
                         " free memory information" % pnode)
9114
      elif instance_info.fail_msg:
9115
        self.warn.append("Can't get instance runtime information: %s" %
9116
                        instance_info.fail_msg)
9117
      else:
9118
        if instance_info.payload:
9119
          current_mem = int(instance_info.payload['memory'])
9120
        else:
9121
          # Assume instance not running
9122
          # (there is a slight race condition here, but it's not very probable,
9123
          # and we have no other way to check)
9124
          current_mem = 0
9125
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
9126
                    pninfo.payload['memory_free'])
9127
        if miss_mem > 0:
9128
          raise errors.OpPrereqError("This change will prevent the instance"
9129
                                     " from starting, due to %d MB of memory"
9130
                                     " missing on its primary node" % miss_mem,
9131
                                     errors.ECODE_NORES)
9132

    
9133
      if be_new[constants.BE_AUTO_BALANCE]:
9134
        for node, nres in nodeinfo.items():
9135
          if node not in instance.secondary_nodes:
9136
            continue
9137
          msg = nres.fail_msg
9138
          if msg:
9139
            self.warn.append("Can't get info from secondary node %s: %s" %
9140
                             (node, msg))
9141
          elif not isinstance(nres.payload.get('memory_free', None), int):
9142
            self.warn.append("Secondary node %s didn't return free"
9143
                             " memory information" % node)
9144
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
9145
            self.warn.append("Not enough memory to failover instance to"
9146
                             " secondary node %s" % node)
9147

    
9148
    # NIC processing
9149
    self.nic_pnew = {}
9150
    self.nic_pinst = {}
9151
    for nic_op, nic_dict in self.op.nics:
9152
      if nic_op == constants.DDM_REMOVE:
9153
        if not instance.nics:
9154
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
9155
                                     errors.ECODE_INVAL)
9156
        continue
9157
      if nic_op != constants.DDM_ADD:
9158
        # an existing nic
9159
        if not instance.nics:
9160
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
9161
                                     " no NICs" % nic_op,
9162
                                     errors.ECODE_INVAL)
9163
        if nic_op < 0 or nic_op >= len(instance.nics):
9164
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
9165
                                     " are 0 to %d" %
9166
                                     (nic_op, len(instance.nics) - 1),
9167
                                     errors.ECODE_INVAL)
9168
        old_nic_params = instance.nics[nic_op].nicparams
9169
        old_nic_ip = instance.nics[nic_op].ip
9170
      else:
9171
        old_nic_params = {}
9172
        old_nic_ip = None
9173

    
9174
      update_params_dict = dict([(key, nic_dict[key])
9175
                                 for key in constants.NICS_PARAMETERS
9176
                                 if key in nic_dict])
9177

    
9178
      if 'bridge' in nic_dict:
9179
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
9180

    
9181
      new_nic_params = _GetUpdatedParams(old_nic_params,
9182
                                         update_params_dict)
9183
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
9184
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
9185
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
9186
      self.nic_pinst[nic_op] = new_nic_params
9187
      self.nic_pnew[nic_op] = new_filled_nic_params
9188
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
9189

    
9190
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
9191
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
9192
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
9193
        if msg:
9194
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
9195
          if self.op.force:
9196
            self.warn.append(msg)
9197
          else:
9198
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
9199
      if new_nic_mode == constants.NIC_MODE_ROUTED:
9200
        if 'ip' in nic_dict:
9201
          nic_ip = nic_dict['ip']
9202
        else:
9203
          nic_ip = old_nic_ip
9204
        if nic_ip is None:
9205
          raise errors.OpPrereqError('Cannot set the nic ip to None'
9206
                                     ' on a routed nic', errors.ECODE_INVAL)
9207
      if 'mac' in nic_dict:
9208
        nic_mac = nic_dict['mac']
9209
        if nic_mac is None:
9210
          raise errors.OpPrereqError('Cannot set the nic mac to None',
9211
                                     errors.ECODE_INVAL)
9212
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9213
          # otherwise generate the mac
9214
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
9215
        else:
9216
          # or validate/reserve the current one
9217
          try:
9218
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
9219
          except errors.ReservationError:
9220
            raise errors.OpPrereqError("MAC address %s already in use"
9221
                                       " in cluster" % nic_mac,
9222
                                       errors.ECODE_NOTUNIQUE)
9223

    
9224
    # DISK processing
9225
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
9226
      raise errors.OpPrereqError("Disk operations not supported for"
9227
                                 " diskless instances",
9228
                                 errors.ECODE_INVAL)
9229
    for disk_op, _ in self.op.disks:
9230
      if disk_op == constants.DDM_REMOVE:
9231
        if len(instance.disks) == 1:
9232
          raise errors.OpPrereqError("Cannot remove the last disk of"
9233
                                     " an instance", errors.ECODE_INVAL)
9234
        _CheckInstanceDown(self, instance, "cannot remove disks")
9235

    
9236
      if (disk_op == constants.DDM_ADD and
9237
          len(instance.nics) >= constants.MAX_DISKS):
9238
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
9239
                                   " add more" % constants.MAX_DISKS,
9240
                                   errors.ECODE_STATE)
9241
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
9242
        # an existing disk
9243
        if disk_op < 0 or disk_op >= len(instance.disks):
9244
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9245
                                     " are 0 to %d" %
9246
                                     (disk_op, len(instance.disks)),
9247
                                     errors.ECODE_INVAL)
9248

    
9249
    return
9250

    
9251
  def _ConvertPlainToDrbd(self, feedback_fn):
9252
    """Converts an instance from plain to drbd.
9253

9254
    """
9255
    feedback_fn("Converting template to drbd")
9256
    instance = self.instance
9257
    pnode = instance.primary_node
9258
    snode = self.op.remote_node
9259

    
9260
    # create a fake disk info for _GenerateDiskTemplate
9261
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
9262
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9263
                                      instance.name, pnode, [snode],
9264
                                      disk_info, None, None, 0)
9265
    info = _GetInstanceInfoText(instance)
9266
    feedback_fn("Creating aditional volumes...")
9267
    # first, create the missing data and meta devices
9268
    for disk in new_disks:
9269
      # unfortunately this is... not too nice
9270
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9271
                            info, True)
9272
      for child in disk.children:
9273
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9274
    # at this stage, all new LVs have been created, we can rename the
9275
    # old ones
9276
    feedback_fn("Renaming original volumes...")
9277
    rename_list = [(o, n.children[0].logical_id)
9278
                   for (o, n) in zip(instance.disks, new_disks)]
9279
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9280
    result.Raise("Failed to rename original LVs")
9281

    
9282
    feedback_fn("Initializing DRBD devices...")
9283
    # all child devices are in place, we can now create the DRBD devices
9284
    for disk in new_disks:
9285
      for node in [pnode, snode]:
9286
        f_create = node == pnode
9287
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9288

    
9289
    # at this point, the instance has been modified
9290
    instance.disk_template = constants.DT_DRBD8
9291
    instance.disks = new_disks
9292
    self.cfg.Update(instance, feedback_fn)
9293

    
9294
    # disks are created, waiting for sync
9295
    disk_abort = not _WaitForSync(self, instance)
9296
    if disk_abort:
9297
      raise errors.OpExecError("There are some degraded disks for"
9298
                               " this instance, please cleanup manually")
9299

    
9300
  def _ConvertDrbdToPlain(self, feedback_fn):
9301
    """Converts an instance from drbd to plain.
9302

9303
    """
9304
    instance = self.instance
9305
    assert len(instance.secondary_nodes) == 1
9306
    pnode = instance.primary_node
9307
    snode = instance.secondary_nodes[0]
9308
    feedback_fn("Converting template to plain")
9309

    
9310
    old_disks = instance.disks
9311
    new_disks = [d.children[0] for d in old_disks]
9312

    
9313
    # copy over size and mode
9314
    for parent, child in zip(old_disks, new_disks):
9315
      child.size = parent.size
9316
      child.mode = parent.mode
9317

    
9318
    # update instance structure
9319
    instance.disks = new_disks
9320
    instance.disk_template = constants.DT_PLAIN
9321
    self.cfg.Update(instance, feedback_fn)
9322

    
9323
    feedback_fn("Removing volumes on the secondary node...")
9324
    for disk in old_disks:
9325
      self.cfg.SetDiskID(disk, snode)
9326
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9327
      if msg:
9328
        self.LogWarning("Could not remove block device %s on node %s,"
9329
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9330

    
9331
    feedback_fn("Removing unneeded volumes on the primary node...")
9332
    for idx, disk in enumerate(old_disks):
9333
      meta = disk.children[1]
9334
      self.cfg.SetDiskID(meta, pnode)
9335
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9336
      if msg:
9337
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9338
                        " continuing anyway: %s", idx, pnode, msg)
9339

    
9340

    
9341
  def Exec(self, feedback_fn):
9342
    """Modifies an instance.
9343

9344
    All parameters take effect only at the next restart of the instance.
9345

9346
    """
9347
    # Process here the warnings from CheckPrereq, as we don't have a
9348
    # feedback_fn there.
9349
    for warn in self.warn:
9350
      feedback_fn("WARNING: %s" % warn)
9351

    
9352
    result = []
9353
    instance = self.instance
9354
    # disk changes
9355
    for disk_op, disk_dict in self.op.disks:
9356
      if disk_op == constants.DDM_REMOVE:
9357
        # remove the last disk
9358
        device = instance.disks.pop()
9359
        device_idx = len(instance.disks)
9360
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9361
          self.cfg.SetDiskID(disk, node)
9362
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9363
          if msg:
9364
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9365
                            " continuing anyway", device_idx, node, msg)
9366
        result.append(("disk/%d" % device_idx, "remove"))
9367
      elif disk_op == constants.DDM_ADD:
9368
        # add a new disk
9369
        if instance.disk_template == constants.DT_FILE:
9370
          file_driver, file_path = instance.disks[0].logical_id
9371
          file_path = os.path.dirname(file_path)
9372
        else:
9373
          file_driver = file_path = None
9374
        disk_idx_base = len(instance.disks)
9375
        new_disk = _GenerateDiskTemplate(self,
9376
                                         instance.disk_template,
9377
                                         instance.name, instance.primary_node,
9378
                                         instance.secondary_nodes,
9379
                                         [disk_dict],
9380
                                         file_path,
9381
                                         file_driver,
9382
                                         disk_idx_base)[0]
9383
        instance.disks.append(new_disk)
9384
        info = _GetInstanceInfoText(instance)
9385

    
9386
        logging.info("Creating volume %s for instance %s",
9387
                     new_disk.iv_name, instance.name)
9388
        # Note: this needs to be kept in sync with _CreateDisks
9389
        #HARDCODE
9390
        for node in instance.all_nodes:
9391
          f_create = node == instance.primary_node
9392
          try:
9393
            _CreateBlockDev(self, node, instance, new_disk,
9394
                            f_create, info, f_create)
9395
          except errors.OpExecError, err:
9396
            self.LogWarning("Failed to create volume %s (%s) on"
9397
                            " node %s: %s",
9398
                            new_disk.iv_name, new_disk, node, err)
9399
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9400
                       (new_disk.size, new_disk.mode)))
9401
      else:
9402
        # change a given disk
9403
        instance.disks[disk_op].mode = disk_dict['mode']
9404
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9405

    
9406
    if self.op.disk_template:
9407
      r_shut = _ShutdownInstanceDisks(self, instance)
9408
      if not r_shut:
9409
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
9410
                                 " proceed with disk template conversion")
9411
      mode = (instance.disk_template, self.op.disk_template)
9412
      try:
9413
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9414
      except:
9415
        self.cfg.ReleaseDRBDMinors(instance.name)
9416
        raise
9417
      result.append(("disk_template", self.op.disk_template))
9418

    
9419
    # NIC changes
9420
    for nic_op, nic_dict in self.op.nics:
9421
      if nic_op == constants.DDM_REMOVE:
9422
        # remove the last nic
9423
        del instance.nics[-1]
9424
        result.append(("nic.%d" % len(instance.nics), "remove"))
9425
      elif nic_op == constants.DDM_ADD:
9426
        # mac and bridge should be set, by now
9427
        mac = nic_dict['mac']
9428
        ip = nic_dict.get('ip', None)
9429
        nicparams = self.nic_pinst[constants.DDM_ADD]
9430
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9431
        instance.nics.append(new_nic)
9432
        result.append(("nic.%d" % (len(instance.nics) - 1),
9433
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9434
                       (new_nic.mac, new_nic.ip,
9435
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9436
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9437
                       )))
9438
      else:
9439
        for key in 'mac', 'ip':
9440
          if key in nic_dict:
9441
            setattr(instance.nics[nic_op], key, nic_dict[key])
9442
        if nic_op in self.nic_pinst:
9443
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9444
        for key, val in nic_dict.iteritems():
9445
          result.append(("nic.%s/%d" % (key, nic_op), val))
9446

    
9447
    # hvparams changes
9448
    if self.op.hvparams:
9449
      instance.hvparams = self.hv_inst
9450
      for key, val in self.op.hvparams.iteritems():
9451
        result.append(("hv/%s" % key, val))
9452

    
9453
    # beparams changes
9454
    if self.op.beparams:
9455
      instance.beparams = self.be_inst
9456
      for key, val in self.op.beparams.iteritems():
9457
        result.append(("be/%s" % key, val))
9458

    
9459
    # OS change
9460
    if self.op.os_name:
9461
      instance.os = self.op.os_name
9462

    
9463
    # osparams changes
9464
    if self.op.osparams:
9465
      instance.osparams = self.os_inst
9466
      for key, val in self.op.osparams.iteritems():
9467
        result.append(("os/%s" % key, val))
9468

    
9469
    self.cfg.Update(instance, feedback_fn)
9470

    
9471
    return result
9472

    
9473
  _DISK_CONVERSIONS = {
9474
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9475
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9476
    }
9477

    
9478

    
9479
class LUQueryExports(NoHooksLU):
9480
  """Query the exports list
9481

9482
  """
9483
  _OP_PARAMS = [
9484
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
9485
    ("use_locking", False, ht.TBool),
9486
    ]
9487
  REQ_BGL = False
9488

    
9489
  def ExpandNames(self):
9490
    self.needed_locks = {}
9491
    self.share_locks[locking.LEVEL_NODE] = 1
9492
    if not self.op.nodes:
9493
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9494
    else:
9495
      self.needed_locks[locking.LEVEL_NODE] = \
9496
        _GetWantedNodes(self, self.op.nodes)
9497

    
9498
  def Exec(self, feedback_fn):
9499
    """Compute the list of all the exported system images.
9500

9501
    @rtype: dict
9502
    @return: a dictionary with the structure node->(export-list)
9503
        where export-list is a list of the instances exported on
9504
        that node.
9505

9506
    """
9507
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9508
    rpcresult = self.rpc.call_export_list(self.nodes)
9509
    result = {}
9510
    for node in rpcresult:
9511
      if rpcresult[node].fail_msg:
9512
        result[node] = False
9513
      else:
9514
        result[node] = rpcresult[node].payload
9515

    
9516
    return result
9517

    
9518

    
9519
class LUPrepareExport(NoHooksLU):
9520
  """Prepares an instance for an export and returns useful information.
9521

9522
  """
9523
  _OP_PARAMS = [
9524
    _PInstanceName,
9525
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES)),
9526
    ]
9527
  REQ_BGL = False
9528

    
9529
  def ExpandNames(self):
9530
    self._ExpandAndLockInstance()
9531

    
9532
  def CheckPrereq(self):
9533
    """Check prerequisites.
9534

9535
    """
9536
    instance_name = self.op.instance_name
9537

    
9538
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9539
    assert self.instance is not None, \
9540
          "Cannot retrieve locked instance %s" % self.op.instance_name
9541
    _CheckNodeOnline(self, self.instance.primary_node)
9542

    
9543
    self._cds = _GetClusterDomainSecret()
9544

    
9545
  def Exec(self, feedback_fn):
9546
    """Prepares an instance for an export.
9547

9548
    """
9549
    instance = self.instance
9550

    
9551
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9552
      salt = utils.GenerateSecret(8)
9553

    
9554
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9555
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9556
                                              constants.RIE_CERT_VALIDITY)
9557
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9558

    
9559
      (name, cert_pem) = result.payload
9560

    
9561
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9562
                                             cert_pem)
9563

    
9564
      return {
9565
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9566
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9567
                          salt),
9568
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9569
        }
9570

    
9571
    return None
9572

    
9573

    
9574
class LUExportInstance(LogicalUnit):
9575
  """Export an instance to an image in the cluster.
9576

9577
  """
9578
  HPATH = "instance-export"
9579
  HTYPE = constants.HTYPE_INSTANCE
9580
  _OP_PARAMS = [
9581
    _PInstanceName,
9582
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList)),
9583
    ("shutdown", True, ht.TBool),
9584
    _PShutdownTimeout,
9585
    ("remove_instance", False, ht.TBool),
9586
    ("ignore_remove_failures", False, ht.TBool),
9587
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES)),
9588
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone)),
9589
    ("destination_x509_ca", None, ht.TMaybeString),
9590
    ]
9591
  REQ_BGL = False
9592

    
9593
  def CheckArguments(self):
9594
    """Check the arguments.
9595

9596
    """
9597
    self.x509_key_name = self.op.x509_key_name
9598
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9599

    
9600
    if self.op.remove_instance and not self.op.shutdown:
9601
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9602
                                 " down before")
9603

    
9604
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9605
      if not self.x509_key_name:
9606
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9607
                                   errors.ECODE_INVAL)
9608

    
9609
      if not self.dest_x509_ca_pem:
9610
        raise errors.OpPrereqError("Missing destination X509 CA",
9611
                                   errors.ECODE_INVAL)
9612

    
9613
  def ExpandNames(self):
9614
    self._ExpandAndLockInstance()
9615

    
9616
    # Lock all nodes for local exports
9617
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9618
      # FIXME: lock only instance primary and destination node
9619
      #
9620
      # Sad but true, for now we have do lock all nodes, as we don't know where
9621
      # the previous export might be, and in this LU we search for it and
9622
      # remove it from its current node. In the future we could fix this by:
9623
      #  - making a tasklet to search (share-lock all), then create the
9624
      #    new one, then one to remove, after
9625
      #  - removing the removal operation altogether
9626
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9627

    
9628
  def DeclareLocks(self, level):
9629
    """Last minute lock declaration."""
9630
    # All nodes are locked anyway, so nothing to do here.
9631

    
9632
  def BuildHooksEnv(self):
9633
    """Build hooks env.
9634

9635
    This will run on the master, primary node and target node.
9636

9637
    """
9638
    env = {
9639
      "EXPORT_MODE": self.op.mode,
9640
      "EXPORT_NODE": self.op.target_node,
9641
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9642
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9643
      # TODO: Generic function for boolean env variables
9644
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9645
      }
9646

    
9647
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9648

    
9649
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9650

    
9651
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9652
      nl.append(self.op.target_node)
9653

    
9654
    return env, nl, nl
9655

    
9656
  def CheckPrereq(self):
9657
    """Check prerequisites.
9658

9659
    This checks that the instance and node names are valid.
9660

9661
    """
9662
    instance_name = self.op.instance_name
9663

    
9664
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9665
    assert self.instance is not None, \
9666
          "Cannot retrieve locked instance %s" % self.op.instance_name
9667
    _CheckNodeOnline(self, self.instance.primary_node)
9668

    
9669
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9670
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9671
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9672
      assert self.dst_node is not None
9673

    
9674
      _CheckNodeOnline(self, self.dst_node.name)
9675
      _CheckNodeNotDrained(self, self.dst_node.name)
9676

    
9677
      self._cds = None
9678
      self.dest_disk_info = None
9679
      self.dest_x509_ca = None
9680

    
9681
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9682
      self.dst_node = None
9683

    
9684
      if len(self.op.target_node) != len(self.instance.disks):
9685
        raise errors.OpPrereqError(("Received destination information for %s"
9686
                                    " disks, but instance %s has %s disks") %
9687
                                   (len(self.op.target_node), instance_name,
9688
                                    len(self.instance.disks)),
9689
                                   errors.ECODE_INVAL)
9690

    
9691
      cds = _GetClusterDomainSecret()
9692

    
9693
      # Check X509 key name
9694
      try:
9695
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9696
      except (TypeError, ValueError), err:
9697
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9698

    
9699
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9700
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9701
                                   errors.ECODE_INVAL)
9702

    
9703
      # Load and verify CA
9704
      try:
9705
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9706
      except OpenSSL.crypto.Error, err:
9707
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9708
                                   (err, ), errors.ECODE_INVAL)
9709

    
9710
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9711
      if errcode is not None:
9712
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9713
                                   (msg, ), errors.ECODE_INVAL)
9714

    
9715
      self.dest_x509_ca = cert
9716

    
9717
      # Verify target information
9718
      disk_info = []
9719
      for idx, disk_data in enumerate(self.op.target_node):
9720
        try:
9721
          (host, port, magic) = \
9722
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9723
        except errors.GenericError, err:
9724
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9725
                                     (idx, err), errors.ECODE_INVAL)
9726

    
9727
        disk_info.append((host, port, magic))
9728

    
9729
      assert len(disk_info) == len(self.op.target_node)
9730
      self.dest_disk_info = disk_info
9731

    
9732
    else:
9733
      raise errors.ProgrammerError("Unhandled export mode %r" %
9734
                                   self.op.mode)
9735

    
9736
    # instance disk type verification
9737
    # TODO: Implement export support for file-based disks
9738
    for disk in self.instance.disks:
9739
      if disk.dev_type == constants.LD_FILE:
9740
        raise errors.OpPrereqError("Export not supported for instances with"
9741
                                   " file-based disks", errors.ECODE_INVAL)
9742

    
9743
  def _CleanupExports(self, feedback_fn):
9744
    """Removes exports of current instance from all other nodes.
9745

9746
    If an instance in a cluster with nodes A..D was exported to node C, its
9747
    exports will be removed from the nodes A, B and D.
9748

9749
    """
9750
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9751

    
9752
    nodelist = self.cfg.GetNodeList()
9753
    nodelist.remove(self.dst_node.name)
9754

    
9755
    # on one-node clusters nodelist will be empty after the removal
9756
    # if we proceed the backup would be removed because OpQueryExports
9757
    # substitutes an empty list with the full cluster node list.
9758
    iname = self.instance.name
9759
    if nodelist:
9760
      feedback_fn("Removing old exports for instance %s" % iname)
9761
      exportlist = self.rpc.call_export_list(nodelist)
9762
      for node in exportlist:
9763
        if exportlist[node].fail_msg:
9764
          continue
9765
        if iname in exportlist[node].payload:
9766
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9767
          if msg:
9768
            self.LogWarning("Could not remove older export for instance %s"
9769
                            " on node %s: %s", iname, node, msg)
9770

    
9771
  def Exec(self, feedback_fn):
9772
    """Export an instance to an image in the cluster.
9773

9774
    """
9775
    assert self.op.mode in constants.EXPORT_MODES
9776

    
9777
    instance = self.instance
9778
    src_node = instance.primary_node
9779

    
9780
    if self.op.shutdown:
9781
      # shutdown the instance, but not the disks
9782
      feedback_fn("Shutting down instance %s" % instance.name)
9783
      result = self.rpc.call_instance_shutdown(src_node, instance,
9784
                                               self.op.shutdown_timeout)
9785
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9786
      result.Raise("Could not shutdown instance %s on"
9787
                   " node %s" % (instance.name, src_node))
9788

    
9789
    # set the disks ID correctly since call_instance_start needs the
9790
    # correct drbd minor to create the symlinks
9791
    for disk in instance.disks:
9792
      self.cfg.SetDiskID(disk, src_node)
9793

    
9794
    activate_disks = (not instance.admin_up)
9795

    
9796
    if activate_disks:
9797
      # Activate the instance disks if we'exporting a stopped instance
9798
      feedback_fn("Activating disks for %s" % instance.name)
9799
      _StartInstanceDisks(self, instance, None)
9800

    
9801
    try:
9802
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9803
                                                     instance)
9804

    
9805
      helper.CreateSnapshots()
9806
      try:
9807
        if (self.op.shutdown and instance.admin_up and
9808
            not self.op.remove_instance):
9809
          assert not activate_disks
9810
          feedback_fn("Starting instance %s" % instance.name)
9811
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9812
          msg = result.fail_msg
9813
          if msg:
9814
            feedback_fn("Failed to start instance: %s" % msg)
9815
            _ShutdownInstanceDisks(self, instance)
9816
            raise errors.OpExecError("Could not start instance: %s" % msg)
9817

    
9818
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9819
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9820
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9821
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9822
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9823

    
9824
          (key_name, _, _) = self.x509_key_name
9825

    
9826
          dest_ca_pem = \
9827
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9828
                                            self.dest_x509_ca)
9829

    
9830
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9831
                                                     key_name, dest_ca_pem,
9832
                                                     timeouts)
9833
      finally:
9834
        helper.Cleanup()
9835

    
9836
      # Check for backwards compatibility
9837
      assert len(dresults) == len(instance.disks)
9838
      assert compat.all(isinstance(i, bool) for i in dresults), \
9839
             "Not all results are boolean: %r" % dresults
9840

    
9841
    finally:
9842
      if activate_disks:
9843
        feedback_fn("Deactivating disks for %s" % instance.name)
9844
        _ShutdownInstanceDisks(self, instance)
9845

    
9846
    if not (compat.all(dresults) and fin_resu):
9847
      failures = []
9848
      if not fin_resu:
9849
        failures.append("export finalization")
9850
      if not compat.all(dresults):
9851
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
9852
                               if not dsk)
9853
        failures.append("disk export: disk(s) %s" % fdsk)
9854

    
9855
      raise errors.OpExecError("Export failed, errors in %s" %
9856
                               utils.CommaJoin(failures))
9857

    
9858
    # At this point, the export was successful, we can cleanup/finish
9859

    
9860
    # Remove instance if requested
9861
    if self.op.remove_instance:
9862
      feedback_fn("Removing instance %s" % instance.name)
9863
      _RemoveInstance(self, feedback_fn, instance,
9864
                      self.op.ignore_remove_failures)
9865

    
9866
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9867
      self._CleanupExports(feedback_fn)
9868

    
9869
    return fin_resu, dresults
9870

    
9871

    
9872
class LURemoveExport(NoHooksLU):
9873
  """Remove exports related to the named instance.
9874

9875
  """
9876
  _OP_PARAMS = [
9877
    _PInstanceName,
9878
    ]
9879
  REQ_BGL = False
9880

    
9881
  def ExpandNames(self):
9882
    self.needed_locks = {}
9883
    # We need all nodes to be locked in order for RemoveExport to work, but we
9884
    # don't need to lock the instance itself, as nothing will happen to it (and
9885
    # we can remove exports also for a removed instance)
9886
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9887

    
9888
  def Exec(self, feedback_fn):
9889
    """Remove any export.
9890

9891
    """
9892
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9893
    # If the instance was not found we'll try with the name that was passed in.
9894
    # This will only work if it was an FQDN, though.
9895
    fqdn_warn = False
9896
    if not instance_name:
9897
      fqdn_warn = True
9898
      instance_name = self.op.instance_name
9899

    
9900
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
9901
    exportlist = self.rpc.call_export_list(locked_nodes)
9902
    found = False
9903
    for node in exportlist:
9904
      msg = exportlist[node].fail_msg
9905
      if msg:
9906
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
9907
        continue
9908
      if instance_name in exportlist[node].payload:
9909
        found = True
9910
        result = self.rpc.call_export_remove(node, instance_name)
9911
        msg = result.fail_msg
9912
        if msg:
9913
          logging.error("Could not remove export for instance %s"
9914
                        " on node %s: %s", instance_name, node, msg)
9915

    
9916
    if fqdn_warn and not found:
9917
      feedback_fn("Export not found. If trying to remove an export belonging"
9918
                  " to a deleted instance please use its Fully Qualified"
9919
                  " Domain Name.")
9920

    
9921

    
9922
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
9923
  """Generic tags LU.
9924

9925
  This is an abstract class which is the parent of all the other tags LUs.
9926

9927
  """
9928

    
9929
  def ExpandNames(self):
9930
    self.needed_locks = {}
9931
    if self.op.kind == constants.TAG_NODE:
9932
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
9933
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
9934
    elif self.op.kind == constants.TAG_INSTANCE:
9935
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
9936
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
9937

    
9938
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
9939
    # not possible to acquire the BGL based on opcode parameters)
9940

    
9941
  def CheckPrereq(self):
9942
    """Check prerequisites.
9943

9944
    """
9945
    if self.op.kind == constants.TAG_CLUSTER:
9946
      self.target = self.cfg.GetClusterInfo()
9947
    elif self.op.kind == constants.TAG_NODE:
9948
      self.target = self.cfg.GetNodeInfo(self.op.name)
9949
    elif self.op.kind == constants.TAG_INSTANCE:
9950
      self.target = self.cfg.GetInstanceInfo(self.op.name)
9951
    else:
9952
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
9953
                                 str(self.op.kind), errors.ECODE_INVAL)
9954

    
9955

    
9956
class LUGetTags(TagsLU):
9957
  """Returns the tags of a given object.
9958

9959
  """
9960
  _OP_PARAMS = [
9961
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
9962
    # Name is only meaningful for nodes and instances
9963
    ("name", ht.NoDefault, ht.TMaybeString),
9964
    ]
9965
  REQ_BGL = False
9966

    
9967
  def ExpandNames(self):
9968
    TagsLU.ExpandNames(self)
9969

    
9970
    # Share locks as this is only a read operation
9971
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9972

    
9973
  def Exec(self, feedback_fn):
9974
    """Returns the tag list.
9975

9976
    """
9977
    return list(self.target.GetTags())
9978

    
9979

    
9980
class LUSearchTags(NoHooksLU):
9981
  """Searches the tags for a given pattern.
9982

9983
  """
9984
  _OP_PARAMS = [
9985
    ("pattern", ht.NoDefault, ht.TNonEmptyString),
9986
    ]
9987
  REQ_BGL = False
9988

    
9989
  def ExpandNames(self):
9990
    self.needed_locks = {}
9991

    
9992
  def CheckPrereq(self):
9993
    """Check prerequisites.
9994

9995
    This checks the pattern passed for validity by compiling it.
9996

9997
    """
9998
    try:
9999
      self.re = re.compile(self.op.pattern)
10000
    except re.error, err:
10001
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
10002
                                 (self.op.pattern, err), errors.ECODE_INVAL)
10003

    
10004
  def Exec(self, feedback_fn):
10005
    """Returns the tag list.
10006

10007
    """
10008
    cfg = self.cfg
10009
    tgts = [("/cluster", cfg.GetClusterInfo())]
10010
    ilist = cfg.GetAllInstancesInfo().values()
10011
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
10012
    nlist = cfg.GetAllNodesInfo().values()
10013
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
10014
    results = []
10015
    for path, target in tgts:
10016
      for tag in target.GetTags():
10017
        if self.re.search(tag):
10018
          results.append((path, tag))
10019
    return results
10020

    
10021

    
10022
class LUAddTags(TagsLU):
10023
  """Sets a tag on a given object.
10024

10025
  """
10026
  _OP_PARAMS = [
10027
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
10028
    # Name is only meaningful for nodes and instances
10029
    ("name", ht.NoDefault, ht.TMaybeString),
10030
    ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
10031
    ]
10032
  REQ_BGL = False
10033

    
10034
  def CheckPrereq(self):
10035
    """Check prerequisites.
10036

10037
    This checks the type and length of the tag name and value.
10038

10039
    """
10040
    TagsLU.CheckPrereq(self)
10041
    for tag in self.op.tags:
10042
      objects.TaggableObject.ValidateTag(tag)
10043

    
10044
  def Exec(self, feedback_fn):
10045
    """Sets the tag.
10046

10047
    """
10048
    try:
10049
      for tag in self.op.tags:
10050
        self.target.AddTag(tag)
10051
    except errors.TagError, err:
10052
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
10053
    self.cfg.Update(self.target, feedback_fn)
10054

    
10055

    
10056
class LUDelTags(TagsLU):
10057
  """Delete a list of tags from a given object.
10058

10059
  """
10060
  _OP_PARAMS = [
10061
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
10062
    # Name is only meaningful for nodes and instances
10063
    ("name", ht.NoDefault, ht.TMaybeString),
10064
    ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
10065
    ]
10066
  REQ_BGL = False
10067

    
10068
  def CheckPrereq(self):
10069
    """Check prerequisites.
10070

10071
    This checks that we have the given tag.
10072

10073
    """
10074
    TagsLU.CheckPrereq(self)
10075
    for tag in self.op.tags:
10076
      objects.TaggableObject.ValidateTag(tag)
10077
    del_tags = frozenset(self.op.tags)
10078
    cur_tags = self.target.GetTags()
10079

    
10080
    diff_tags = del_tags - cur_tags
10081
    if diff_tags:
10082
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
10083
      raise errors.OpPrereqError("Tag(s) %s not found" %
10084
                                 (utils.CommaJoin(diff_names), ),
10085
                                 errors.ECODE_NOENT)
10086

    
10087
  def Exec(self, feedback_fn):
10088
    """Remove the tag from the object.
10089

10090
    """
10091
    for tag in self.op.tags:
10092
      self.target.RemoveTag(tag)
10093
    self.cfg.Update(self.target, feedback_fn)
10094

    
10095

    
10096
class LUTestDelay(NoHooksLU):
10097
  """Sleep for a specified amount of time.
10098

10099
  This LU sleeps on the master and/or nodes for a specified amount of
10100
  time.
10101

10102
  """
10103
  _OP_PARAMS = [
10104
    ("duration", ht.NoDefault, ht.TFloat),
10105
    ("on_master", True, ht.TBool),
10106
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
10107
    ("repeat", 0, ht.TPositiveInt)
10108
    ]
10109
  REQ_BGL = False
10110

    
10111
  def ExpandNames(self):
10112
    """Expand names and set required locks.
10113

10114
    This expands the node list, if any.
10115

10116
    """
10117
    self.needed_locks = {}
10118
    if self.op.on_nodes:
10119
      # _GetWantedNodes can be used here, but is not always appropriate to use
10120
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
10121
      # more information.
10122
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
10123
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
10124

    
10125
  def _TestDelay(self):
10126
    """Do the actual sleep.
10127

10128
    """
10129
    if self.op.on_master:
10130
      if not utils.TestDelay(self.op.duration):
10131
        raise errors.OpExecError("Error during master delay test")
10132
    if self.op.on_nodes:
10133
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
10134
      for node, node_result in result.items():
10135
        node_result.Raise("Failure during rpc call to node %s" % node)
10136

    
10137
  def Exec(self, feedback_fn):
10138
    """Execute the test delay opcode, with the wanted repetitions.
10139

10140
    """
10141
    if self.op.repeat == 0:
10142
      self._TestDelay()
10143
    else:
10144
      top_value = self.op.repeat - 1
10145
      for i in range(self.op.repeat):
10146
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
10147
        self._TestDelay()
10148

    
10149

    
10150
class LUTestJobqueue(NoHooksLU):
10151
  """Utility LU to test some aspects of the job queue.
10152

10153
  """
10154
  _OP_PARAMS = [
10155
    ("notify_waitlock", False, ht.TBool),
10156
    ("notify_exec", False, ht.TBool),
10157
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString)),
10158
    ("fail", False, ht.TBool),
10159
    ]
10160
  REQ_BGL = False
10161

    
10162
  # Must be lower than default timeout for WaitForJobChange to see whether it
10163
  # notices changed jobs
10164
  _CLIENT_CONNECT_TIMEOUT = 20.0
10165
  _CLIENT_CONFIRM_TIMEOUT = 60.0
10166

    
10167
  @classmethod
10168
  def _NotifyUsingSocket(cls, cb, errcls):
10169
    """Opens a Unix socket and waits for another program to connect.
10170

10171
    @type cb: callable
10172
    @param cb: Callback to send socket name to client
10173
    @type errcls: class
10174
    @param errcls: Exception class to use for errors
10175

10176
    """
10177
    # Using a temporary directory as there's no easy way to create temporary
10178
    # sockets without writing a custom loop around tempfile.mktemp and
10179
    # socket.bind
10180
    tmpdir = tempfile.mkdtemp()
10181
    try:
10182
      tmpsock = utils.PathJoin(tmpdir, "sock")
10183

    
10184
      logging.debug("Creating temporary socket at %s", tmpsock)
10185
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
10186
      try:
10187
        sock.bind(tmpsock)
10188
        sock.listen(1)
10189

    
10190
        # Send details to client
10191
        cb(tmpsock)
10192

    
10193
        # Wait for client to connect before continuing
10194
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
10195
        try:
10196
          (conn, _) = sock.accept()
10197
        except socket.error, err:
10198
          raise errcls("Client didn't connect in time (%s)" % err)
10199
      finally:
10200
        sock.close()
10201
    finally:
10202
      # Remove as soon as client is connected
10203
      shutil.rmtree(tmpdir)
10204

    
10205
    # Wait for client to close
10206
    try:
10207
      try:
10208
        # pylint: disable-msg=E1101
10209
        # Instance of '_socketobject' has no ... member
10210
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
10211
        conn.recv(1)
10212
      except socket.error, err:
10213
        raise errcls("Client failed to confirm notification (%s)" % err)
10214
    finally:
10215
      conn.close()
10216

    
10217
  def _SendNotification(self, test, arg, sockname):
10218
    """Sends a notification to the client.
10219

10220
    @type test: string
10221
    @param test: Test name
10222
    @param arg: Test argument (depends on test)
10223
    @type sockname: string
10224
    @param sockname: Socket path
10225

10226
    """
10227
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
10228

    
10229
  def _Notify(self, prereq, test, arg):
10230
    """Notifies the client of a test.
10231

10232
    @type prereq: bool
10233
    @param prereq: Whether this is a prereq-phase test
10234
    @type test: string
10235
    @param test: Test name
10236
    @param arg: Test argument (depends on test)
10237

10238
    """
10239
    if prereq:
10240
      errcls = errors.OpPrereqError
10241
    else:
10242
      errcls = errors.OpExecError
10243

    
10244
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
10245
                                                  test, arg),
10246
                                   errcls)
10247

    
10248
  def CheckArguments(self):
10249
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
10250
    self.expandnames_calls = 0
10251

    
10252
  def ExpandNames(self):
10253
    checkargs_calls = getattr(self, "checkargs_calls", 0)
10254
    if checkargs_calls < 1:
10255
      raise errors.ProgrammerError("CheckArguments was not called")
10256

    
10257
    self.expandnames_calls += 1
10258

    
10259
    if self.op.notify_waitlock:
10260
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
10261

    
10262
    self.LogInfo("Expanding names")
10263

    
10264
    # Get lock on master node (just to get a lock, not for a particular reason)
10265
    self.needed_locks = {
10266
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
10267
      }
10268

    
10269
  def Exec(self, feedback_fn):
10270
    if self.expandnames_calls < 1:
10271
      raise errors.ProgrammerError("ExpandNames was not called")
10272

    
10273
    if self.op.notify_exec:
10274
      self._Notify(False, constants.JQT_EXEC, None)
10275

    
10276
    self.LogInfo("Executing")
10277

    
10278
    if self.op.log_messages:
10279
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
10280
      for idx, msg in enumerate(self.op.log_messages):
10281
        self.LogInfo("Sending log message %s", idx + 1)
10282
        feedback_fn(constants.JQT_MSGPREFIX + msg)
10283
        # Report how many test messages have been sent
10284
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
10285

    
10286
    if self.op.fail:
10287
      raise errors.OpExecError("Opcode failure was requested")
10288

    
10289
    return True
10290

    
10291

    
10292
class IAllocator(object):
10293
  """IAllocator framework.
10294

10295
  An IAllocator instance has three sets of attributes:
10296
    - cfg that is needed to query the cluster
10297
    - input data (all members of the _KEYS class attribute are required)
10298
    - four buffer attributes (in|out_data|text), that represent the
10299
      input (to the external script) in text and data structure format,
10300
      and the output from it, again in two formats
10301
    - the result variables from the script (success, info, nodes) for
10302
      easy usage
10303

10304
  """
10305
  # pylint: disable-msg=R0902
10306
  # lots of instance attributes
10307
  _ALLO_KEYS = [
10308
    "name", "mem_size", "disks", "disk_template",
10309
    "os", "tags", "nics", "vcpus", "hypervisor",
10310
    ]
10311
  _RELO_KEYS = [
10312
    "name", "relocate_from",
10313
    ]
10314
  _EVAC_KEYS = [
10315
    "evac_nodes",
10316
    ]
10317

    
10318
  def __init__(self, cfg, rpc, mode, **kwargs):
10319
    self.cfg = cfg
10320
    self.rpc = rpc
10321
    # init buffer variables
10322
    self.in_text = self.out_text = self.in_data = self.out_data = None
10323
    # init all input fields so that pylint is happy
10324
    self.mode = mode
10325
    self.mem_size = self.disks = self.disk_template = None
10326
    self.os = self.tags = self.nics = self.vcpus = None
10327
    self.hypervisor = None
10328
    self.relocate_from = None
10329
    self.name = None
10330
    self.evac_nodes = None
10331
    # computed fields
10332
    self.required_nodes = None
10333
    # init result fields
10334
    self.success = self.info = self.result = None
10335
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10336
      keyset = self._ALLO_KEYS
10337
      fn = self._AddNewInstance
10338
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10339
      keyset = self._RELO_KEYS
10340
      fn = self._AddRelocateInstance
10341
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10342
      keyset = self._EVAC_KEYS
10343
      fn = self._AddEvacuateNodes
10344
    else:
10345
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
10346
                                   " IAllocator" % self.mode)
10347
    for key in kwargs:
10348
      if key not in keyset:
10349
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
10350
                                     " IAllocator" % key)
10351
      setattr(self, key, kwargs[key])
10352

    
10353
    for key in keyset:
10354
      if key not in kwargs:
10355
        raise errors.ProgrammerError("Missing input parameter '%s' to"
10356
                                     " IAllocator" % key)
10357
    self._BuildInputData(fn)
10358

    
10359
  def _ComputeClusterData(self):
10360
    """Compute the generic allocator input data.
10361

10362
    This is the data that is independent of the actual operation.
10363

10364
    """
10365
    cfg = self.cfg
10366
    cluster_info = cfg.GetClusterInfo()
10367
    # cluster data
10368
    data = {
10369
      "version": constants.IALLOCATOR_VERSION,
10370
      "cluster_name": cfg.GetClusterName(),
10371
      "cluster_tags": list(cluster_info.GetTags()),
10372
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
10373
      # we don't have job IDs
10374
      }
10375
    iinfo = cfg.GetAllInstancesInfo().values()
10376
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
10377

    
10378
    # node data
10379
    node_list = cfg.GetNodeList()
10380

    
10381
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10382
      hypervisor_name = self.hypervisor
10383
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10384
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
10385
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10386
      hypervisor_name = cluster_info.enabled_hypervisors[0]
10387

    
10388
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
10389
                                        hypervisor_name)
10390
    node_iinfo = \
10391
      self.rpc.call_all_instances_info(node_list,
10392
                                       cluster_info.enabled_hypervisors)
10393

    
10394
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
10395

    
10396
    data["nodes"] = self._ComputeNodeData(cfg, node_data, node_iinfo, i_list)
10397

    
10398
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
10399

    
10400
    self.in_data = data
10401

    
10402
  @staticmethod
10403
  def _ComputeNodeGroupData(cfg):
10404
    """Compute node groups data.
10405

10406
    """
10407
    ng = {}
10408
    for guuid, gdata in cfg.GetAllNodeGroupsInfo().items():
10409
      ng[guuid] = { "name": gdata.name }
10410
    return ng
10411

    
10412
  @staticmethod
10413
  def _ComputeNodeData(cfg, node_data, node_iinfo, i_list):
10414
    """Compute global node data.
10415

10416
    """
10417
    node_results = {}
10418
    for nname, nresult in node_data.items():
10419
      # first fill in static (config-based) values
10420
      ninfo = cfg.GetNodeInfo(nname)
10421
      pnr = {
10422
        "tags": list(ninfo.GetTags()),
10423
        "primary_ip": ninfo.primary_ip,
10424
        "secondary_ip": ninfo.secondary_ip,
10425
        "offline": ninfo.offline,
10426
        "drained": ninfo.drained,
10427
        "master_candidate": ninfo.master_candidate,
10428
        "group": ninfo.group,
10429
        "master_capable": ninfo.master_capable,
10430
        "vm_capable": ninfo.vm_capable,
10431
        }
10432

    
10433
      if not (ninfo.offline or ninfo.drained):
10434
        nresult.Raise("Can't get data for node %s" % nname)
10435
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
10436
                                nname)
10437
        remote_info = nresult.payload
10438

    
10439
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
10440
                     'vg_size', 'vg_free', 'cpu_total']:
10441
          if attr not in remote_info:
10442
            raise errors.OpExecError("Node '%s' didn't return attribute"
10443
                                     " '%s'" % (nname, attr))
10444
          if not isinstance(remote_info[attr], int):
10445
            raise errors.OpExecError("Node '%s' returned invalid value"
10446
                                     " for '%s': %s" %
10447
                                     (nname, attr, remote_info[attr]))
10448
        # compute memory used by primary instances
10449
        i_p_mem = i_p_up_mem = 0
10450
        for iinfo, beinfo in i_list:
10451
          if iinfo.primary_node == nname:
10452
            i_p_mem += beinfo[constants.BE_MEMORY]
10453
            if iinfo.name not in node_iinfo[nname].payload:
10454
              i_used_mem = 0
10455
            else:
10456
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
10457
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
10458
            remote_info['memory_free'] -= max(0, i_mem_diff)
10459

    
10460
            if iinfo.admin_up:
10461
              i_p_up_mem += beinfo[constants.BE_MEMORY]
10462

    
10463
        # compute memory used by instances
10464
        pnr_dyn = {
10465
          "total_memory": remote_info['memory_total'],
10466
          "reserved_memory": remote_info['memory_dom0'],
10467
          "free_memory": remote_info['memory_free'],
10468
          "total_disk": remote_info['vg_size'],
10469
          "free_disk": remote_info['vg_free'],
10470
          "total_cpus": remote_info['cpu_total'],
10471
          "i_pri_memory": i_p_mem,
10472
          "i_pri_up_memory": i_p_up_mem,
10473
          }
10474
        pnr.update(pnr_dyn)
10475

    
10476
      node_results[nname] = pnr
10477

    
10478
    return node_results
10479

    
10480
  @staticmethod
10481
  def _ComputeInstanceData(cluster_info, i_list):
10482
    """Compute global instance data.
10483

10484
    """
10485
    instance_data = {}
10486
    for iinfo, beinfo in i_list:
10487
      nic_data = []
10488
      for nic in iinfo.nics:
10489
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
10490
        nic_dict = {"mac": nic.mac,
10491
                    "ip": nic.ip,
10492
                    "mode": filled_params[constants.NIC_MODE],
10493
                    "link": filled_params[constants.NIC_LINK],
10494
                   }
10495
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
10496
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
10497
        nic_data.append(nic_dict)
10498
      pir = {
10499
        "tags": list(iinfo.GetTags()),
10500
        "admin_up": iinfo.admin_up,
10501
        "vcpus": beinfo[constants.BE_VCPUS],
10502
        "memory": beinfo[constants.BE_MEMORY],
10503
        "os": iinfo.os,
10504
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
10505
        "nics": nic_data,
10506
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
10507
        "disk_template": iinfo.disk_template,
10508
        "hypervisor": iinfo.hypervisor,
10509
        }
10510
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
10511
                                                 pir["disks"])
10512
      instance_data[iinfo.name] = pir
10513

    
10514
    return instance_data
10515

    
10516
  def _AddNewInstance(self):
10517
    """Add new instance data to allocator structure.
10518

10519
    This in combination with _AllocatorGetClusterData will create the
10520
    correct structure needed as input for the allocator.
10521

10522
    The checks for the completeness of the opcode must have already been
10523
    done.
10524

10525
    """
10526
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
10527

    
10528
    if self.disk_template in constants.DTS_NET_MIRROR:
10529
      self.required_nodes = 2
10530
    else:
10531
      self.required_nodes = 1
10532
    request = {
10533
      "name": self.name,
10534
      "disk_template": self.disk_template,
10535
      "tags": self.tags,
10536
      "os": self.os,
10537
      "vcpus": self.vcpus,
10538
      "memory": self.mem_size,
10539
      "disks": self.disks,
10540
      "disk_space_total": disk_space,
10541
      "nics": self.nics,
10542
      "required_nodes": self.required_nodes,
10543
      }
10544
    return request
10545

    
10546
  def _AddRelocateInstance(self):
10547
    """Add relocate instance data to allocator structure.
10548

10549
    This in combination with _IAllocatorGetClusterData will create the
10550
    correct structure needed as input for the allocator.
10551

10552
    The checks for the completeness of the opcode must have already been
10553
    done.
10554

10555
    """
10556
    instance = self.cfg.GetInstanceInfo(self.name)
10557
    if instance is None:
10558
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
10559
                                   " IAllocator" % self.name)
10560

    
10561
    if instance.disk_template not in constants.DTS_NET_MIRROR:
10562
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
10563
                                 errors.ECODE_INVAL)
10564

    
10565
    if len(instance.secondary_nodes) != 1:
10566
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
10567
                                 errors.ECODE_STATE)
10568

    
10569
    self.required_nodes = 1
10570
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
10571
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
10572

    
10573
    request = {
10574
      "name": self.name,
10575
      "disk_space_total": disk_space,
10576
      "required_nodes": self.required_nodes,
10577
      "relocate_from": self.relocate_from,
10578
      }
10579
    return request
10580

    
10581
  def _AddEvacuateNodes(self):
10582
    """Add evacuate nodes data to allocator structure.
10583

10584
    """
10585
    request = {
10586
      "evac_nodes": self.evac_nodes
10587
      }
10588
    return request
10589

    
10590
  def _BuildInputData(self, fn):
10591
    """Build input data structures.
10592

10593
    """
10594
    self._ComputeClusterData()
10595

    
10596
    request = fn()
10597
    request["type"] = self.mode
10598
    self.in_data["request"] = request
10599

    
10600
    self.in_text = serializer.Dump(self.in_data)
10601

    
10602
  def Run(self, name, validate=True, call_fn=None):
10603
    """Run an instance allocator and return the results.
10604

10605
    """
10606
    if call_fn is None:
10607
      call_fn = self.rpc.call_iallocator_runner
10608

    
10609
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
10610
    result.Raise("Failure while running the iallocator script")
10611

    
10612
    self.out_text = result.payload
10613
    if validate:
10614
      self._ValidateResult()
10615

    
10616
  def _ValidateResult(self):
10617
    """Process the allocator results.
10618

10619
    This will process and if successful save the result in
10620
    self.out_data and the other parameters.
10621

10622
    """
10623
    try:
10624
      rdict = serializer.Load(self.out_text)
10625
    except Exception, err:
10626
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
10627

    
10628
    if not isinstance(rdict, dict):
10629
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
10630

    
10631
    # TODO: remove backwards compatiblity in later versions
10632
    if "nodes" in rdict and "result" not in rdict:
10633
      rdict["result"] = rdict["nodes"]
10634
      del rdict["nodes"]
10635

    
10636
    for key in "success", "info", "result":
10637
      if key not in rdict:
10638
        raise errors.OpExecError("Can't parse iallocator results:"
10639
                                 " missing key '%s'" % key)
10640
      setattr(self, key, rdict[key])
10641

    
10642
    if not isinstance(rdict["result"], list):
10643
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
10644
                               " is not a list")
10645
    self.out_data = rdict
10646

    
10647

    
10648
class LUTestAllocator(NoHooksLU):
10649
  """Run allocator tests.
10650

10651
  This LU runs the allocator tests
10652

10653
  """
10654
  _OP_PARAMS = [
10655
    ("direction", ht.NoDefault,
10656
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS)),
10657
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES)),
10658
    ("name", ht.NoDefault, ht.TNonEmptyString),
10659
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
10660
      ht.TDictOf(ht.TElemOf(["mac", "ip", "bridge"]),
10661
               ht.TOr(ht.TNone, ht.TNonEmptyString))))),
10662
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList)),
10663
    ("hypervisor", None, ht.TMaybeString),
10664
    ("allocator", None, ht.TMaybeString),
10665
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
10666
    ("mem_size", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
10667
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
10668
    ("os", None, ht.TMaybeString),
10669
    ("disk_template", None, ht.TMaybeString),
10670
    ("evac_nodes", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString))),
10671
    ]
10672

    
10673
  def CheckPrereq(self):
10674
    """Check prerequisites.
10675

10676
    This checks the opcode parameters depending on the director and mode test.
10677

10678
    """
10679
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10680
      for attr in ["mem_size", "disks", "disk_template",
10681
                   "os", "tags", "nics", "vcpus"]:
10682
        if not hasattr(self.op, attr):
10683
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
10684
                                     attr, errors.ECODE_INVAL)
10685
      iname = self.cfg.ExpandInstanceName(self.op.name)
10686
      if iname is not None:
10687
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
10688
                                   iname, errors.ECODE_EXISTS)
10689
      if not isinstance(self.op.nics, list):
10690
        raise errors.OpPrereqError("Invalid parameter 'nics'",
10691
                                   errors.ECODE_INVAL)
10692
      if not isinstance(self.op.disks, list):
10693
        raise errors.OpPrereqError("Invalid parameter 'disks'",
10694
                                   errors.ECODE_INVAL)
10695
      for row in self.op.disks:
10696
        if (not isinstance(row, dict) or
10697
            "size" not in row or
10698
            not isinstance(row["size"], int) or
10699
            "mode" not in row or
10700
            row["mode"] not in ['r', 'w']):
10701
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
10702
                                     " parameter", errors.ECODE_INVAL)
10703
      if self.op.hypervisor is None:
10704
        self.op.hypervisor = self.cfg.GetHypervisorType()
10705
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10706
      fname = _ExpandInstanceName(self.cfg, self.op.name)
10707
      self.op.name = fname
10708
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
10709
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10710
      if not hasattr(self.op, "evac_nodes"):
10711
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
10712
                                   " opcode input", errors.ECODE_INVAL)
10713
    else:
10714
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
10715
                                 self.op.mode, errors.ECODE_INVAL)
10716

    
10717
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
10718
      if self.op.allocator is None:
10719
        raise errors.OpPrereqError("Missing allocator name",
10720
                                   errors.ECODE_INVAL)
10721
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
10722
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
10723
                                 self.op.direction, errors.ECODE_INVAL)
10724

    
10725
  def Exec(self, feedback_fn):
10726
    """Run the allocator test.
10727

10728
    """
10729
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10730
      ial = IAllocator(self.cfg, self.rpc,
10731
                       mode=self.op.mode,
10732
                       name=self.op.name,
10733
                       mem_size=self.op.mem_size,
10734
                       disks=self.op.disks,
10735
                       disk_template=self.op.disk_template,
10736
                       os=self.op.os,
10737
                       tags=self.op.tags,
10738
                       nics=self.op.nics,
10739
                       vcpus=self.op.vcpus,
10740
                       hypervisor=self.op.hypervisor,
10741
                       )
10742
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10743
      ial = IAllocator(self.cfg, self.rpc,
10744
                       mode=self.op.mode,
10745
                       name=self.op.name,
10746
                       relocate_from=list(self.relocate_from),
10747
                       )
10748
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10749
      ial = IAllocator(self.cfg, self.rpc,
10750
                       mode=self.op.mode,
10751
                       evac_nodes=self.op.evac_nodes)
10752
    else:
10753
      raise errors.ProgrammerError("Uncatched mode %s in"
10754
                                   " LUTestAllocator.Exec", self.op.mode)
10755

    
10756
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
10757
      result = ial.in_text
10758
    else:
10759
      ial.Run(self.op.allocator, validate=False)
10760
      result = ial.out_text
10761
    return result