Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 18e63b75

History | View | Annotate | Download (384.5 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, msg=None):
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
  @param msg: if passed, should be a message to replace the default one
602
  @raise errors.OpPrereqError: if the node is offline
603

604
  """
605
  if msg is None:
606
    msg = "Can't use offline node"
607
  if lu.cfg.GetNodeInfo(node).offline:
608
    raise errors.OpPrereqError("%s: %s" % (msg, node), errors.ECODE_STATE)
609

    
610

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

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

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

    
623

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

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

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

    
636

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

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

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

    
654

    
655
def _CheckNodeHasSecondaryIP(lu, node, secondary_ip, prereq):
656
  """Ensure that a node has the given secondary ip.
657

658
  @type lu: L{LogicalUnit}
659
  @param lu: the LU on behalf of which we make the check
660
  @type node: string
661
  @param node: the node to check
662
  @type secondary_ip: string
663
  @param secondary_ip: the ip to check
664
  @type prereq: boolean
665
  @param prereq: whether to throw a prerequisite or an execute error
666
  @raise errors.OpPrereqError: if the node doesn't have the ip, and prereq=True
667
  @raise errors.OpExecError: if the node doesn't have the ip, and prereq=False
668

669
  """
670
  result = lu.rpc.call_node_has_ip_address(node, secondary_ip)
671
  result.Raise("Failure checking secondary ip on node %s" % node,
672
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
673
  if not result.payload:
674
    msg = ("Node claims it doesn't have the secondary ip you gave (%s),"
675
           " please fix and re-run this command" % secondary_ip)
676
    if prereq:
677
      raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
678
    else:
679
      raise errors.OpExecError(msg)
680

    
681

    
682
def _RequireFileStorage():
683
  """Checks that file storage is enabled.
684

685
  @raise errors.OpPrereqError: when file storage is disabled
686

687
  """
688
  if not constants.ENABLE_FILE_STORAGE:
689
    raise errors.OpPrereqError("File storage disabled at configure time",
690
                               errors.ECODE_INVAL)
691

    
692

    
693
def _CheckDiskTemplate(template):
694
  """Ensure a given disk template is valid.
695

696
  """
697
  if template not in constants.DISK_TEMPLATES:
698
    msg = ("Invalid disk template name '%s', valid templates are: %s" %
699
           (template, utils.CommaJoin(constants.DISK_TEMPLATES)))
700
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
701
  if template == constants.DT_FILE:
702
    _RequireFileStorage()
703
  return True
704

    
705

    
706
def _CheckStorageType(storage_type):
707
  """Ensure a given storage type is valid.
708

709
  """
710
  if storage_type not in constants.VALID_STORAGE_TYPES:
711
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
712
                               errors.ECODE_INVAL)
713
  if storage_type == constants.ST_FILE:
714
    _RequireFileStorage()
715
  return True
716

    
717

    
718
def _GetClusterDomainSecret():
719
  """Reads the cluster domain secret.
720

721
  """
722
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
723
                               strict=True)
724

    
725

    
726
def _CheckInstanceDown(lu, instance, reason):
727
  """Ensure that an instance is not running."""
728
  if instance.admin_up:
729
    raise errors.OpPrereqError("Instance %s is marked to be up, %s" %
730
                               (instance.name, reason), errors.ECODE_STATE)
731

    
732
  pnode = instance.primary_node
733
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
734
  ins_l.Raise("Can't contact node %s for instance information" % pnode,
735
              prereq=True, ecode=errors.ECODE_ENVIRON)
736

    
737
  if instance.name in ins_l.payload:
738
    raise errors.OpPrereqError("Instance %s is running, %s" %
739
                               (instance.name, reason), errors.ECODE_STATE)
740

    
741

    
742
def _ExpandItemName(fn, name, kind):
743
  """Expand an item name.
744

745
  @param fn: the function to use for expansion
746
  @param name: requested item name
747
  @param kind: text description ('Node' or 'Instance')
748
  @return: the resolved (full) name
749
  @raise errors.OpPrereqError: if the item is not found
750

751
  """
752
  full_name = fn(name)
753
  if full_name is None:
754
    raise errors.OpPrereqError("%s '%s' not known" % (kind, name),
755
                               errors.ECODE_NOENT)
756
  return full_name
757

    
758

    
759
def _ExpandNodeName(cfg, name):
760
  """Wrapper over L{_ExpandItemName} for nodes."""
761
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
762

    
763

    
764
def _ExpandInstanceName(cfg, name):
765
  """Wrapper over L{_ExpandItemName} for instance."""
766
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
767

    
768

    
769
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
770
                          memory, vcpus, nics, disk_template, disks,
771
                          bep, hvp, hypervisor_name):
772
  """Builds instance related env variables for hooks
773

774
  This builds the hook environment from individual variables.
775

776
  @type name: string
777
  @param name: the name of the instance
778
  @type primary_node: string
779
  @param primary_node: the name of the instance's primary node
780
  @type secondary_nodes: list
781
  @param secondary_nodes: list of secondary nodes as strings
782
  @type os_type: string
783
  @param os_type: the name of the instance's OS
784
  @type status: boolean
785
  @param status: the should_run status of the instance
786
  @type memory: string
787
  @param memory: the memory size of the instance
788
  @type vcpus: string
789
  @param vcpus: the count of VCPUs the instance has
790
  @type nics: list
791
  @param nics: list of tuples (ip, mac, mode, link) representing
792
      the NICs the instance has
793
  @type disk_template: string
794
  @param disk_template: the disk template of the instance
795
  @type disks: list
796
  @param disks: the list of (size, mode) pairs
797
  @type bep: dict
798
  @param bep: the backend parameters for the instance
799
  @type hvp: dict
800
  @param hvp: the hypervisor parameters for the instance
801
  @type hypervisor_name: string
802
  @param hypervisor_name: the hypervisor for the instance
803
  @rtype: dict
804
  @return: the hook environment for this instance
805

806
  """
807
  if status:
808
    str_status = "up"
809
  else:
810
    str_status = "down"
811
  env = {
812
    "OP_TARGET": name,
813
    "INSTANCE_NAME": name,
814
    "INSTANCE_PRIMARY": primary_node,
815
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
816
    "INSTANCE_OS_TYPE": os_type,
817
    "INSTANCE_STATUS": str_status,
818
    "INSTANCE_MEMORY": memory,
819
    "INSTANCE_VCPUS": vcpus,
820
    "INSTANCE_DISK_TEMPLATE": disk_template,
821
    "INSTANCE_HYPERVISOR": hypervisor_name,
822
  }
823

    
824
  if nics:
825
    nic_count = len(nics)
826
    for idx, (ip, mac, mode, link) in enumerate(nics):
827
      if ip is None:
828
        ip = ""
829
      env["INSTANCE_NIC%d_IP" % idx] = ip
830
      env["INSTANCE_NIC%d_MAC" % idx] = mac
831
      env["INSTANCE_NIC%d_MODE" % idx] = mode
832
      env["INSTANCE_NIC%d_LINK" % idx] = link
833
      if mode == constants.NIC_MODE_BRIDGED:
834
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
835
  else:
836
    nic_count = 0
837

    
838
  env["INSTANCE_NIC_COUNT"] = nic_count
839

    
840
  if disks:
841
    disk_count = len(disks)
842
    for idx, (size, mode) in enumerate(disks):
843
      env["INSTANCE_DISK%d_SIZE" % idx] = size
844
      env["INSTANCE_DISK%d_MODE" % idx] = mode
845
  else:
846
    disk_count = 0
847

    
848
  env["INSTANCE_DISK_COUNT"] = disk_count
849

    
850
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
851
    for key, value in source.items():
852
      env["INSTANCE_%s_%s" % (kind, key)] = value
853

    
854
  return env
855

    
856

    
857
def _NICListToTuple(lu, nics):
858
  """Build a list of nic information tuples.
859

860
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
861
  value in LUQueryInstanceData.
862

863
  @type lu:  L{LogicalUnit}
864
  @param lu: the logical unit on whose behalf we execute
865
  @type nics: list of L{objects.NIC}
866
  @param nics: list of nics to convert to hooks tuples
867

868
  """
869
  hooks_nics = []
870
  cluster = lu.cfg.GetClusterInfo()
871
  for nic in nics:
872
    ip = nic.ip
873
    mac = nic.mac
874
    filled_params = cluster.SimpleFillNIC(nic.nicparams)
875
    mode = filled_params[constants.NIC_MODE]
876
    link = filled_params[constants.NIC_LINK]
877
    hooks_nics.append((ip, mac, mode, link))
878
  return hooks_nics
879

    
880

    
881
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
882
  """Builds instance related env variables for hooks from an object.
883

884
  @type lu: L{LogicalUnit}
885
  @param lu: the logical unit on whose behalf we execute
886
  @type instance: L{objects.Instance}
887
  @param instance: the instance for which we should build the
888
      environment
889
  @type override: dict
890
  @param override: dictionary with key/values that will override
891
      our values
892
  @rtype: dict
893
  @return: the hook environment dictionary
894

895
  """
896
  cluster = lu.cfg.GetClusterInfo()
897
  bep = cluster.FillBE(instance)
898
  hvp = cluster.FillHV(instance)
899
  args = {
900
    'name': instance.name,
901
    'primary_node': instance.primary_node,
902
    'secondary_nodes': instance.secondary_nodes,
903
    'os_type': instance.os,
904
    'status': instance.admin_up,
905
    'memory': bep[constants.BE_MEMORY],
906
    'vcpus': bep[constants.BE_VCPUS],
907
    'nics': _NICListToTuple(lu, instance.nics),
908
    'disk_template': instance.disk_template,
909
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
910
    'bep': bep,
911
    'hvp': hvp,
912
    'hypervisor_name': instance.hypervisor,
913
  }
914
  if override:
915
    args.update(override)
916
  return _BuildInstanceHookEnv(**args) # pylint: disable-msg=W0142
917

    
918

    
919
def _AdjustCandidatePool(lu, exceptions):
920
  """Adjust the candidate pool after node operations.
921

922
  """
923
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
924
  if mod_list:
925
    lu.LogInfo("Promoted nodes to master candidate role: %s",
926
               utils.CommaJoin(node.name for node in mod_list))
927
    for name in mod_list:
928
      lu.context.ReaddNode(name)
929
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
930
  if mc_now > mc_max:
931
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
932
               (mc_now, mc_max))
933

    
934

    
935
def _DecideSelfPromotion(lu, exceptions=None):
936
  """Decide whether I should promote myself as a master candidate.
937

938
  """
939
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
940
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
941
  # the new node will increase mc_max with one, so:
942
  mc_should = min(mc_should + 1, cp_size)
943
  return mc_now < mc_should
944

    
945

    
946
def _CheckNicsBridgesExist(lu, target_nics, target_node):
947
  """Check that the brigdes needed by a list of nics exist.
948

949
  """
950
  cluster = lu.cfg.GetClusterInfo()
951
  paramslist = [cluster.SimpleFillNIC(nic.nicparams) for nic in target_nics]
952
  brlist = [params[constants.NIC_LINK] for params in paramslist
953
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
954
  if brlist:
955
    result = lu.rpc.call_bridges_exist(target_node, brlist)
956
    result.Raise("Error checking bridges on destination node '%s'" %
957
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
958

    
959

    
960
def _CheckInstanceBridgesExist(lu, instance, node=None):
961
  """Check that the brigdes needed by an instance exist.
962

963
  """
964
  if node is None:
965
    node = instance.primary_node
966
  _CheckNicsBridgesExist(lu, instance.nics, node)
967

    
968

    
969
def _CheckOSVariant(os_obj, name):
970
  """Check whether an OS name conforms to the os variants specification.
971

972
  @type os_obj: L{objects.OS}
973
  @param os_obj: OS object to check
974
  @type name: string
975
  @param name: OS name passed by the user, to check for validity
976

977
  """
978
  if not os_obj.supported_variants:
979
    return
980
  variant = objects.OS.GetVariant(name)
981
  if not variant:
982
    raise errors.OpPrereqError("OS name must include a variant",
983
                               errors.ECODE_INVAL)
984

    
985
  if variant not in os_obj.supported_variants:
986
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
987

    
988

    
989
def _GetNodeInstancesInner(cfg, fn):
990
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
991

    
992

    
993
def _GetNodeInstances(cfg, node_name):
994
  """Returns a list of all primary and secondary instances on a node.
995

996
  """
997

    
998
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
999

    
1000

    
1001
def _GetNodePrimaryInstances(cfg, node_name):
1002
  """Returns primary instances on a node.
1003

1004
  """
1005
  return _GetNodeInstancesInner(cfg,
1006
                                lambda inst: node_name == inst.primary_node)
1007

    
1008

    
1009
def _GetNodeSecondaryInstances(cfg, node_name):
1010
  """Returns secondary instances on a node.
1011

1012
  """
1013
  return _GetNodeInstancesInner(cfg,
1014
                                lambda inst: node_name in inst.secondary_nodes)
1015

    
1016

    
1017
def _GetStorageTypeArgs(cfg, storage_type):
1018
  """Returns the arguments for a storage type.
1019

1020
  """
1021
  # Special case for file storage
1022
  if storage_type == constants.ST_FILE:
1023
    # storage.FileStorage wants a list of storage directories
1024
    return [[cfg.GetFileStorageDir()]]
1025

    
1026
  return []
1027

    
1028

    
1029
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
1030
  faulty = []
1031

    
1032
  for dev in instance.disks:
1033
    cfg.SetDiskID(dev, node_name)
1034

    
1035
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
1036
  result.Raise("Failed to get disk status from node %s" % node_name,
1037
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
1038

    
1039
  for idx, bdev_status in enumerate(result.payload):
1040
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
1041
      faulty.append(idx)
1042

    
1043
  return faulty
1044

    
1045

    
1046
def _CheckIAllocatorOrNode(lu, iallocator_slot, node_slot):
1047
  """Check the sanity of iallocator and node arguments and use the
1048
  cluster-wide iallocator if appropriate.
1049

1050
  Check that at most one of (iallocator, node) is specified. If none is
1051
  specified, then the LU's opcode's iallocator slot is filled with the
1052
  cluster-wide default iallocator.
1053

1054
  @type iallocator_slot: string
1055
  @param iallocator_slot: the name of the opcode iallocator slot
1056
  @type node_slot: string
1057
  @param node_slot: the name of the opcode target node slot
1058

1059
  """
1060
  node = getattr(lu.op, node_slot, None)
1061
  iallocator = getattr(lu.op, iallocator_slot, None)
1062

    
1063
  if node is not None and iallocator is not None:
1064
    raise errors.OpPrereqError("Do not specify both, iallocator and node.",
1065
                               errors.ECODE_INVAL)
1066
  elif node is None and iallocator is None:
1067
    default_iallocator = lu.cfg.GetDefaultIAllocator()
1068
    if default_iallocator:
1069
      setattr(lu.op, iallocator_slot, default_iallocator)
1070
    else:
1071
      raise errors.OpPrereqError("No iallocator or node given and no"
1072
                                 " cluster-wide default iallocator found."
1073
                                 " Please specify either an iallocator or a"
1074
                                 " node, or set a cluster-wide default"
1075
                                 " iallocator.")
1076

    
1077

    
1078
class LUPostInitCluster(LogicalUnit):
1079
  """Logical unit for running hooks after cluster initialization.
1080

1081
  """
1082
  HPATH = "cluster-init"
1083
  HTYPE = constants.HTYPE_CLUSTER
1084

    
1085
  def BuildHooksEnv(self):
1086
    """Build hooks env.
1087

1088
    """
1089
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1090
    mn = self.cfg.GetMasterNode()
1091
    return env, [], [mn]
1092

    
1093
  def Exec(self, feedback_fn):
1094
    """Nothing to do.
1095

1096
    """
1097
    return True
1098

    
1099

    
1100
class LUDestroyCluster(LogicalUnit):
1101
  """Logical unit for destroying the cluster.
1102

1103
  """
1104
  HPATH = "cluster-destroy"
1105
  HTYPE = constants.HTYPE_CLUSTER
1106

    
1107
  def BuildHooksEnv(self):
1108
    """Build hooks env.
1109

1110
    """
1111
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1112
    return env, [], []
1113

    
1114
  def CheckPrereq(self):
1115
    """Check prerequisites.
1116

1117
    This checks whether the cluster is empty.
1118

1119
    Any errors are signaled by raising errors.OpPrereqError.
1120

1121
    """
1122
    master = self.cfg.GetMasterNode()
1123

    
1124
    nodelist = self.cfg.GetNodeList()
1125
    if len(nodelist) != 1 or nodelist[0] != master:
1126
      raise errors.OpPrereqError("There are still %d node(s) in"
1127
                                 " this cluster." % (len(nodelist) - 1),
1128
                                 errors.ECODE_INVAL)
1129
    instancelist = self.cfg.GetInstanceList()
1130
    if instancelist:
1131
      raise errors.OpPrereqError("There are still %d instance(s) in"
1132
                                 " this cluster." % len(instancelist),
1133
                                 errors.ECODE_INVAL)
1134

    
1135
  def Exec(self, feedback_fn):
1136
    """Destroys the cluster.
1137

1138
    """
1139
    master = self.cfg.GetMasterNode()
1140

    
1141
    # Run post hooks on master node before it's removed
1142
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
1143
    try:
1144
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
1145
    except:
1146
      # pylint: disable-msg=W0702
1147
      self.LogWarning("Errors occurred running hooks on %s" % master)
1148

    
1149
    result = self.rpc.call_node_stop_master(master, False)
1150
    result.Raise("Could not disable the master role")
1151

    
1152
    return master
1153

    
1154

    
1155
def _VerifyCertificate(filename):
1156
  """Verifies a certificate for LUVerifyCluster.
1157

1158
  @type filename: string
1159
  @param filename: Path to PEM file
1160

1161
  """
1162
  try:
1163
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1164
                                           utils.ReadFile(filename))
1165
  except Exception, err: # pylint: disable-msg=W0703
1166
    return (LUVerifyCluster.ETYPE_ERROR,
1167
            "Failed to load X509 certificate %s: %s" % (filename, err))
1168

    
1169
  (errcode, msg) = \
1170
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1171
                                constants.SSL_CERT_EXPIRATION_ERROR)
1172

    
1173
  if msg:
1174
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1175
  else:
1176
    fnamemsg = None
1177

    
1178
  if errcode is None:
1179
    return (None, fnamemsg)
1180
  elif errcode == utils.CERT_WARNING:
1181
    return (LUVerifyCluster.ETYPE_WARNING, fnamemsg)
1182
  elif errcode == utils.CERT_ERROR:
1183
    return (LUVerifyCluster.ETYPE_ERROR, fnamemsg)
1184

    
1185
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1186

    
1187

    
1188
class LUVerifyCluster(LogicalUnit):
1189
  """Verifies the cluster status.
1190

1191
  """
1192
  HPATH = "cluster-verify"
1193
  HTYPE = constants.HTYPE_CLUSTER
1194
  _OP_PARAMS = [
1195
    ("skip_checks", ht.EmptyList,
1196
     ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS))),
1197
    ("verbose", False, ht.TBool),
1198
    ("error_codes", False, ht.TBool),
1199
    ("debug_simulate_errors", False, ht.TBool),
1200
    ]
1201
  REQ_BGL = False
1202

    
1203
  TCLUSTER = "cluster"
1204
  TNODE = "node"
1205
  TINSTANCE = "instance"
1206

    
1207
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1208
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1209
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1210
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1211
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1212
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1213
  EINSTANCEFAULTYDISK = (TINSTANCE, "EINSTANCEFAULTYDISK")
1214
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1215
  ENODEDRBD = (TNODE, "ENODEDRBD")
1216
  ENODEDRBDHELPER = (TNODE, "ENODEDRBDHELPER")
1217
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1218
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1219
  ENODEHV = (TNODE, "ENODEHV")
1220
  ENODELVM = (TNODE, "ENODELVM")
1221
  ENODEN1 = (TNODE, "ENODEN1")
1222
  ENODENET = (TNODE, "ENODENET")
1223
  ENODEOS = (TNODE, "ENODEOS")
1224
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1225
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1226
  ENODERPC = (TNODE, "ENODERPC")
1227
  ENODESSH = (TNODE, "ENODESSH")
1228
  ENODEVERSION = (TNODE, "ENODEVERSION")
1229
  ENODESETUP = (TNODE, "ENODESETUP")
1230
  ENODETIME = (TNODE, "ENODETIME")
1231

    
1232
  ETYPE_FIELD = "code"
1233
  ETYPE_ERROR = "ERROR"
1234
  ETYPE_WARNING = "WARNING"
1235

    
1236
  class NodeImage(object):
1237
    """A class representing the logical and physical status of a node.
1238

1239
    @type name: string
1240
    @ivar name: the node name to which this object refers
1241
    @ivar volumes: a structure as returned from
1242
        L{ganeti.backend.GetVolumeList} (runtime)
1243
    @ivar instances: a list of running instances (runtime)
1244
    @ivar pinst: list of configured primary instances (config)
1245
    @ivar sinst: list of configured secondary instances (config)
1246
    @ivar sbp: diction of {secondary-node: list of instances} of all peers
1247
        of this node (config)
1248
    @ivar mfree: free memory, as reported by hypervisor (runtime)
1249
    @ivar dfree: free disk, as reported by the node (runtime)
1250
    @ivar offline: the offline status (config)
1251
    @type rpc_fail: boolean
1252
    @ivar rpc_fail: whether the RPC verify call was successfull (overall,
1253
        not whether the individual keys were correct) (runtime)
1254
    @type lvm_fail: boolean
1255
    @ivar lvm_fail: whether the RPC call didn't return valid LVM data
1256
    @type hyp_fail: boolean
1257
    @ivar hyp_fail: whether the RPC call didn't return the instance list
1258
    @type ghost: boolean
1259
    @ivar ghost: whether this is a known node or not (config)
1260
    @type os_fail: boolean
1261
    @ivar os_fail: whether the RPC call didn't return valid OS data
1262
    @type oslist: list
1263
    @ivar oslist: list of OSes as diagnosed by DiagnoseOS
1264
    @type vm_capable: boolean
1265
    @ivar vm_capable: whether the node can host instances
1266

1267
    """
1268
    def __init__(self, offline=False, name=None, vm_capable=True):
1269
      self.name = name
1270
      self.volumes = {}
1271
      self.instances = []
1272
      self.pinst = []
1273
      self.sinst = []
1274
      self.sbp = {}
1275
      self.mfree = 0
1276
      self.dfree = 0
1277
      self.offline = offline
1278
      self.vm_capable = vm_capable
1279
      self.rpc_fail = False
1280
      self.lvm_fail = False
1281
      self.hyp_fail = False
1282
      self.ghost = False
1283
      self.os_fail = False
1284
      self.oslist = {}
1285

    
1286
  def ExpandNames(self):
1287
    self.needed_locks = {
1288
      locking.LEVEL_NODE: locking.ALL_SET,
1289
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1290
    }
1291
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1292

    
1293
  def _Error(self, ecode, item, msg, *args, **kwargs):
1294
    """Format an error message.
1295

1296
    Based on the opcode's error_codes parameter, either format a
1297
    parseable error code, or a simpler error string.
1298

1299
    This must be called only from Exec and functions called from Exec.
1300

1301
    """
1302
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1303
    itype, etxt = ecode
1304
    # first complete the msg
1305
    if args:
1306
      msg = msg % args
1307
    # then format the whole message
1308
    if self.op.error_codes:
1309
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1310
    else:
1311
      if item:
1312
        item = " " + item
1313
      else:
1314
        item = ""
1315
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1316
    # and finally report it via the feedback_fn
1317
    self._feedback_fn("  - %s" % msg)
1318

    
1319
  def _ErrorIf(self, cond, *args, **kwargs):
1320
    """Log an error message if the passed condition is True.
1321

1322
    """
1323
    cond = bool(cond) or self.op.debug_simulate_errors
1324
    if cond:
1325
      self._Error(*args, **kwargs)
1326
    # do not mark the operation as failed for WARN cases only
1327
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1328
      self.bad = self.bad or cond
1329

    
1330
  def _VerifyNode(self, ninfo, nresult):
1331
    """Perform some basic validation on data returned from a node.
1332

1333
      - check the result data structure is well formed and has all the
1334
        mandatory fields
1335
      - check ganeti version
1336

1337
    @type ninfo: L{objects.Node}
1338
    @param ninfo: the node to check
1339
    @param nresult: the results from the node
1340
    @rtype: boolean
1341
    @return: whether overall this call was successful (and we can expect
1342
         reasonable values in the respose)
1343

1344
    """
1345
    node = ninfo.name
1346
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1347

    
1348
    # main result, nresult should be a non-empty dict
1349
    test = not nresult or not isinstance(nresult, dict)
1350
    _ErrorIf(test, self.ENODERPC, node,
1351
                  "unable to verify node: no data returned")
1352
    if test:
1353
      return False
1354

    
1355
    # compares ganeti version
1356
    local_version = constants.PROTOCOL_VERSION
1357
    remote_version = nresult.get("version", None)
1358
    test = not (remote_version and
1359
                isinstance(remote_version, (list, tuple)) and
1360
                len(remote_version) == 2)
1361
    _ErrorIf(test, self.ENODERPC, node,
1362
             "connection to node returned invalid data")
1363
    if test:
1364
      return False
1365

    
1366
    test = local_version != remote_version[0]
1367
    _ErrorIf(test, self.ENODEVERSION, node,
1368
             "incompatible protocol versions: master %s,"
1369
             " node %s", local_version, remote_version[0])
1370
    if test:
1371
      return False
1372

    
1373
    # node seems compatible, we can actually try to look into its results
1374

    
1375
    # full package version
1376
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1377
                  self.ENODEVERSION, node,
1378
                  "software version mismatch: master %s, node %s",
1379
                  constants.RELEASE_VERSION, remote_version[1],
1380
                  code=self.ETYPE_WARNING)
1381

    
1382
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1383
    if ninfo.vm_capable and isinstance(hyp_result, dict):
1384
      for hv_name, hv_result in hyp_result.iteritems():
1385
        test = hv_result is not None
1386
        _ErrorIf(test, self.ENODEHV, node,
1387
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1388

    
1389
    test = nresult.get(constants.NV_NODESETUP,
1390
                           ["Missing NODESETUP results"])
1391
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1392
             "; ".join(test))
1393

    
1394
    return True
1395

    
1396
  def _VerifyNodeTime(self, ninfo, nresult,
1397
                      nvinfo_starttime, nvinfo_endtime):
1398
    """Check the node time.
1399

1400
    @type ninfo: L{objects.Node}
1401
    @param ninfo: the node to check
1402
    @param nresult: the remote results for the node
1403
    @param nvinfo_starttime: the start time of the RPC call
1404
    @param nvinfo_endtime: the end time of the RPC call
1405

1406
    """
1407
    node = ninfo.name
1408
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1409

    
1410
    ntime = nresult.get(constants.NV_TIME, None)
1411
    try:
1412
      ntime_merged = utils.MergeTime(ntime)
1413
    except (ValueError, TypeError):
1414
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1415
      return
1416

    
1417
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1418
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1419
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1420
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1421
    else:
1422
      ntime_diff = None
1423

    
1424
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1425
             "Node time diverges by at least %s from master node time",
1426
             ntime_diff)
1427

    
1428
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1429
    """Check the node time.
1430

1431
    @type ninfo: L{objects.Node}
1432
    @param ninfo: the node to check
1433
    @param nresult: the remote results for the node
1434
    @param vg_name: the configured VG name
1435

1436
    """
1437
    if vg_name is None:
1438
      return
1439

    
1440
    node = ninfo.name
1441
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1442

    
1443
    # checks vg existence and size > 20G
1444
    vglist = nresult.get(constants.NV_VGLIST, None)
1445
    test = not vglist
1446
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1447
    if not test:
1448
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1449
                                            constants.MIN_VG_SIZE)
1450
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1451

    
1452
    # check pv names
1453
    pvlist = nresult.get(constants.NV_PVLIST, None)
1454
    test = pvlist is None
1455
    _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1456
    if not test:
1457
      # check that ':' is not present in PV names, since it's a
1458
      # special character for lvcreate (denotes the range of PEs to
1459
      # use on the PV)
1460
      for _, pvname, owner_vg in pvlist:
1461
        test = ":" in pvname
1462
        _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1463
                 " '%s' of VG '%s'", pvname, owner_vg)
1464

    
1465
  def _VerifyNodeNetwork(self, ninfo, nresult):
1466
    """Check the node time.
1467

1468
    @type ninfo: L{objects.Node}
1469
    @param ninfo: the node to check
1470
    @param nresult: the remote results for the node
1471

1472
    """
1473
    node = ninfo.name
1474
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1475

    
1476
    test = constants.NV_NODELIST not in nresult
1477
    _ErrorIf(test, self.ENODESSH, node,
1478
             "node hasn't returned node ssh connectivity data")
1479
    if not test:
1480
      if nresult[constants.NV_NODELIST]:
1481
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1482
          _ErrorIf(True, self.ENODESSH, node,
1483
                   "ssh communication with node '%s': %s", a_node, a_msg)
1484

    
1485
    test = constants.NV_NODENETTEST not in nresult
1486
    _ErrorIf(test, self.ENODENET, node,
1487
             "node hasn't returned node tcp connectivity data")
1488
    if not test:
1489
      if nresult[constants.NV_NODENETTEST]:
1490
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1491
        for anode in nlist:
1492
          _ErrorIf(True, self.ENODENET, node,
1493
                   "tcp communication with node '%s': %s",
1494
                   anode, nresult[constants.NV_NODENETTEST][anode])
1495

    
1496
    test = constants.NV_MASTERIP not in nresult
1497
    _ErrorIf(test, self.ENODENET, node,
1498
             "node hasn't returned node master IP reachability data")
1499
    if not test:
1500
      if not nresult[constants.NV_MASTERIP]:
1501
        if node == self.master_node:
1502
          msg = "the master node cannot reach the master IP (not configured?)"
1503
        else:
1504
          msg = "cannot reach the master IP"
1505
        _ErrorIf(True, self.ENODENET, node, msg)
1506

    
1507
  def _VerifyInstance(self, instance, instanceconfig, node_image,
1508
                      diskstatus):
1509
    """Verify an instance.
1510

1511
    This function checks to see if the required block devices are
1512
    available on the instance's node.
1513

1514
    """
1515
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1516
    node_current = instanceconfig.primary_node
1517

    
1518
    node_vol_should = {}
1519
    instanceconfig.MapLVsByNode(node_vol_should)
1520

    
1521
    for node in node_vol_should:
1522
      n_img = node_image[node]
1523
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1524
        # ignore missing volumes on offline or broken nodes
1525
        continue
1526
      for volume in node_vol_should[node]:
1527
        test = volume not in n_img.volumes
1528
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1529
                 "volume %s missing on node %s", volume, node)
1530

    
1531
    if instanceconfig.admin_up:
1532
      pri_img = node_image[node_current]
1533
      test = instance not in pri_img.instances and not pri_img.offline
1534
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1535
               "instance not running on its primary node %s",
1536
               node_current)
1537

    
1538
    for node, n_img in node_image.items():
1539
      if (not node == node_current):
1540
        test = instance in n_img.instances
1541
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1542
                 "instance should not run on node %s", node)
1543

    
1544
    diskdata = [(nname, success, status, idx)
1545
                for (nname, disks) in diskstatus.items()
1546
                for idx, (success, status) in enumerate(disks)]
1547

    
1548
    for nname, success, bdev_status, idx in diskdata:
1549
      _ErrorIf(instanceconfig.admin_up and not success,
1550
               self.EINSTANCEFAULTYDISK, instance,
1551
               "couldn't retrieve status for disk/%s on %s: %s",
1552
               idx, nname, bdev_status)
1553
      _ErrorIf((instanceconfig.admin_up and success and
1554
                bdev_status.ldisk_status == constants.LDS_FAULTY),
1555
               self.EINSTANCEFAULTYDISK, instance,
1556
               "disk/%s on %s is faulty", idx, nname)
1557

    
1558
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1559
    """Verify if there are any unknown volumes in the cluster.
1560

1561
    The .os, .swap and backup volumes are ignored. All other volumes are
1562
    reported as unknown.
1563

1564
    @type reserved: L{ganeti.utils.FieldSet}
1565
    @param reserved: a FieldSet of reserved volume names
1566

1567
    """
1568
    for node, n_img in node_image.items():
1569
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1570
        # skip non-healthy nodes
1571
        continue
1572
      for volume in n_img.volumes:
1573
        test = ((node not in node_vol_should or
1574
                volume not in node_vol_should[node]) and
1575
                not reserved.Matches(volume))
1576
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1577
                      "volume %s is unknown", volume)
1578

    
1579
  def _VerifyOrphanInstances(self, instancelist, node_image):
1580
    """Verify the list of running instances.
1581

1582
    This checks what instances are running but unknown to the cluster.
1583

1584
    """
1585
    for node, n_img in node_image.items():
1586
      for o_inst in n_img.instances:
1587
        test = o_inst not in instancelist
1588
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1589
                      "instance %s on node %s should not exist", o_inst, node)
1590

    
1591
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1592
    """Verify N+1 Memory Resilience.
1593

1594
    Check that if one single node dies we can still start all the
1595
    instances it was primary for.
1596

1597
    """
1598
    for node, n_img in node_image.items():
1599
      # This code checks that every node which is now listed as
1600
      # secondary has enough memory to host all instances it is
1601
      # supposed to should a single other node in the cluster fail.
1602
      # FIXME: not ready for failover to an arbitrary node
1603
      # FIXME: does not support file-backed instances
1604
      # WARNING: we currently take into account down instances as well
1605
      # as up ones, considering that even if they're down someone
1606
      # might want to start them even in the event of a node failure.
1607
      for prinode, instances in n_img.sbp.items():
1608
        needed_mem = 0
1609
        for instance in instances:
1610
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1611
          if bep[constants.BE_AUTO_BALANCE]:
1612
            needed_mem += bep[constants.BE_MEMORY]
1613
        test = n_img.mfree < needed_mem
1614
        self._ErrorIf(test, self.ENODEN1, node,
1615
                      "not enough memory on to accommodate"
1616
                      " failovers should peer node %s fail", prinode)
1617

    
1618
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1619
                       master_files):
1620
    """Verifies and computes the node required file checksums.
1621

1622
    @type ninfo: L{objects.Node}
1623
    @param ninfo: the node to check
1624
    @param nresult: the remote results for the node
1625
    @param file_list: required list of files
1626
    @param local_cksum: dictionary of local files and their checksums
1627
    @param master_files: list of files that only masters should have
1628

1629
    """
1630
    node = ninfo.name
1631
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1632

    
1633
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1634
    test = not isinstance(remote_cksum, dict)
1635
    _ErrorIf(test, self.ENODEFILECHECK, node,
1636
             "node hasn't returned file checksum data")
1637
    if test:
1638
      return
1639

    
1640
    for file_name in file_list:
1641
      node_is_mc = ninfo.master_candidate
1642
      must_have = (file_name not in master_files) or node_is_mc
1643
      # missing
1644
      test1 = file_name not in remote_cksum
1645
      # invalid checksum
1646
      test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1647
      # existing and good
1648
      test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1649
      _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1650
               "file '%s' missing", file_name)
1651
      _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1652
               "file '%s' has wrong checksum", file_name)
1653
      # not candidate and this is not a must-have file
1654
      _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1655
               "file '%s' should not exist on non master"
1656
               " candidates (and the file is outdated)", file_name)
1657
      # all good, except non-master/non-must have combination
1658
      _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1659
               "file '%s' should not exist"
1660
               " on non master candidates", file_name)
1661

    
1662
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1663
                      drbd_map):
1664
    """Verifies and the node DRBD status.
1665

1666
    @type ninfo: L{objects.Node}
1667
    @param ninfo: the node to check
1668
    @param nresult: the remote results for the node
1669
    @param instanceinfo: the dict of instances
1670
    @param drbd_helper: the configured DRBD usermode helper
1671
    @param drbd_map: the DRBD map as returned by
1672
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1673

1674
    """
1675
    node = ninfo.name
1676
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1677

    
1678
    if drbd_helper:
1679
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1680
      test = (helper_result == None)
1681
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1682
               "no drbd usermode helper returned")
1683
      if helper_result:
1684
        status, payload = helper_result
1685
        test = not status
1686
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1687
                 "drbd usermode helper check unsuccessful: %s", payload)
1688
        test = status and (payload != drbd_helper)
1689
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1690
                 "wrong drbd usermode helper: %s", payload)
1691

    
1692
    # compute the DRBD minors
1693
    node_drbd = {}
1694
    for minor, instance in drbd_map[node].items():
1695
      test = instance not in instanceinfo
1696
      _ErrorIf(test, self.ECLUSTERCFG, None,
1697
               "ghost instance '%s' in temporary DRBD map", instance)
1698
        # ghost instance should not be running, but otherwise we
1699
        # don't give double warnings (both ghost instance and
1700
        # unallocated minor in use)
1701
      if test:
1702
        node_drbd[minor] = (instance, False)
1703
      else:
1704
        instance = instanceinfo[instance]
1705
        node_drbd[minor] = (instance.name, instance.admin_up)
1706

    
1707
    # and now check them
1708
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1709
    test = not isinstance(used_minors, (tuple, list))
1710
    _ErrorIf(test, self.ENODEDRBD, node,
1711
             "cannot parse drbd status file: %s", str(used_minors))
1712
    if test:
1713
      # we cannot check drbd status
1714
      return
1715

    
1716
    for minor, (iname, must_exist) in node_drbd.items():
1717
      test = minor not in used_minors and must_exist
1718
      _ErrorIf(test, self.ENODEDRBD, node,
1719
               "drbd minor %d of instance %s is not active", minor, iname)
1720
    for minor in used_minors:
1721
      test = minor not in node_drbd
1722
      _ErrorIf(test, self.ENODEDRBD, node,
1723
               "unallocated drbd minor %d is in use", minor)
1724

    
1725
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1726
    """Builds the node OS structures.
1727

1728
    @type ninfo: L{objects.Node}
1729
    @param ninfo: the node to check
1730
    @param nresult: the remote results for the node
1731
    @param nimg: the node image object
1732

1733
    """
1734
    node = ninfo.name
1735
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1736

    
1737
    remote_os = nresult.get(constants.NV_OSLIST, None)
1738
    test = (not isinstance(remote_os, list) or
1739
            not compat.all(isinstance(v, list) and len(v) == 7
1740
                           for v in remote_os))
1741

    
1742
    _ErrorIf(test, self.ENODEOS, node,
1743
             "node hasn't returned valid OS data")
1744

    
1745
    nimg.os_fail = test
1746

    
1747
    if test:
1748
      return
1749

    
1750
    os_dict = {}
1751

    
1752
    for (name, os_path, status, diagnose,
1753
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1754

    
1755
      if name not in os_dict:
1756
        os_dict[name] = []
1757

    
1758
      # parameters is a list of lists instead of list of tuples due to
1759
      # JSON lacking a real tuple type, fix it:
1760
      parameters = [tuple(v) for v in parameters]
1761
      os_dict[name].append((os_path, status, diagnose,
1762
                            set(variants), set(parameters), set(api_ver)))
1763

    
1764
    nimg.oslist = os_dict
1765

    
1766
  def _VerifyNodeOS(self, ninfo, nimg, base):
1767
    """Verifies the node OS list.
1768

1769
    @type ninfo: L{objects.Node}
1770
    @param ninfo: the node to check
1771
    @param nimg: the node image object
1772
    @param base: the 'template' node we match against (e.g. from the master)
1773

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

    
1778
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1779

    
1780
    for os_name, os_data in nimg.oslist.items():
1781
      assert os_data, "Empty OS status for OS %s?!" % os_name
1782
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
1783
      _ErrorIf(not f_status, self.ENODEOS, node,
1784
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
1785
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
1786
               "OS '%s' has multiple entries (first one shadows the rest): %s",
1787
               os_name, utils.CommaJoin([v[0] for v in os_data]))
1788
      # this will catched in backend too
1789
      _ErrorIf(compat.any(v >= constants.OS_API_V15 for v in f_api)
1790
               and not f_var, self.ENODEOS, node,
1791
               "OS %s with API at least %d does not declare any variant",
1792
               os_name, constants.OS_API_V15)
1793
      # comparisons with the 'base' image
1794
      test = os_name not in base.oslist
1795
      _ErrorIf(test, self.ENODEOS, node,
1796
               "Extra OS %s not present on reference node (%s)",
1797
               os_name, base.name)
1798
      if test:
1799
        continue
1800
      assert base.oslist[os_name], "Base node has empty OS status?"
1801
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
1802
      if not b_status:
1803
        # base OS is invalid, skipping
1804
        continue
1805
      for kind, a, b in [("API version", f_api, b_api),
1806
                         ("variants list", f_var, b_var),
1807
                         ("parameters", f_param, b_param)]:
1808
        _ErrorIf(a != b, self.ENODEOS, node,
1809
                 "OS %s %s differs from reference node %s: %s vs. %s",
1810
                 kind, os_name, base.name,
1811
                 utils.CommaJoin(a), utils.CommaJoin(b))
1812

    
1813
    # check any missing OSes
1814
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
1815
    _ErrorIf(missing, self.ENODEOS, node,
1816
             "OSes present on reference node %s but missing on this node: %s",
1817
             base.name, utils.CommaJoin(missing))
1818

    
1819
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1820
    """Verifies and updates the node volume data.
1821

1822
    This function will update a L{NodeImage}'s internal structures
1823
    with data from the remote call.
1824

1825
    @type ninfo: L{objects.Node}
1826
    @param ninfo: the node to check
1827
    @param nresult: the remote results for the node
1828
    @param nimg: the node image object
1829
    @param vg_name: the configured VG name
1830

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

    
1835
    nimg.lvm_fail = True
1836
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1837
    if vg_name is None:
1838
      pass
1839
    elif isinstance(lvdata, basestring):
1840
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1841
               utils.SafeEncode(lvdata))
1842
    elif not isinstance(lvdata, dict):
1843
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1844
    else:
1845
      nimg.volumes = lvdata
1846
      nimg.lvm_fail = False
1847

    
1848
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1849
    """Verifies and updates the node instance list.
1850

1851
    If the listing was successful, then updates this node's instance
1852
    list. Otherwise, it marks the RPC call as failed for the instance
1853
    list key.
1854

1855
    @type ninfo: L{objects.Node}
1856
    @param ninfo: the node to check
1857
    @param nresult: the remote results for the node
1858
    @param nimg: the node image object
1859

1860
    """
1861
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1862
    test = not isinstance(idata, list)
1863
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1864
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1865
    if test:
1866
      nimg.hyp_fail = True
1867
    else:
1868
      nimg.instances = idata
1869

    
1870
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1871
    """Verifies and computes a node information map
1872

1873
    @type ninfo: L{objects.Node}
1874
    @param ninfo: the node to check
1875
    @param nresult: the remote results for the node
1876
    @param nimg: the node image object
1877
    @param vg_name: the configured VG name
1878

1879
    """
1880
    node = ninfo.name
1881
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1882

    
1883
    # try to read free memory (from the hypervisor)
1884
    hv_info = nresult.get(constants.NV_HVINFO, None)
1885
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
1886
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1887
    if not test:
1888
      try:
1889
        nimg.mfree = int(hv_info["memory_free"])
1890
      except (ValueError, TypeError):
1891
        _ErrorIf(True, self.ENODERPC, node,
1892
                 "node returned invalid nodeinfo, check hypervisor")
1893

    
1894
    # FIXME: devise a free space model for file based instances as well
1895
    if vg_name is not None:
1896
      test = (constants.NV_VGLIST not in nresult or
1897
              vg_name not in nresult[constants.NV_VGLIST])
1898
      _ErrorIf(test, self.ENODELVM, node,
1899
               "node didn't return data for the volume group '%s'"
1900
               " - it is either missing or broken", vg_name)
1901
      if not test:
1902
        try:
1903
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
1904
        except (ValueError, TypeError):
1905
          _ErrorIf(True, self.ENODERPC, node,
1906
                   "node returned invalid LVM info, check LVM status")
1907

    
1908
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
1909
    """Gets per-disk status information for all instances.
1910

1911
    @type nodelist: list of strings
1912
    @param nodelist: Node names
1913
    @type node_image: dict of (name, L{objects.Node})
1914
    @param node_image: Node objects
1915
    @type instanceinfo: dict of (name, L{objects.Instance})
1916
    @param instanceinfo: Instance objects
1917

1918
    """
1919
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1920

    
1921
    node_disks = {}
1922
    node_disks_devonly = {}
1923

    
1924
    for nname in nodelist:
1925
      disks = [(inst, disk)
1926
               for instlist in [node_image[nname].pinst,
1927
                                node_image[nname].sinst]
1928
               for inst in instlist
1929
               for disk in instanceinfo[inst].disks]
1930

    
1931
      if not disks:
1932
        # No need to collect data
1933
        continue
1934

    
1935
      node_disks[nname] = disks
1936

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

    
1941
      for dev in devonly:
1942
        self.cfg.SetDiskID(dev, nname)
1943

    
1944
      node_disks_devonly[nname] = devonly
1945

    
1946
    assert len(node_disks) == len(node_disks_devonly)
1947

    
1948
    # Collect data from all nodes with disks
1949
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
1950
                                                          node_disks_devonly)
1951

    
1952
    assert len(result) == len(node_disks)
1953

    
1954
    instdisk = {}
1955

    
1956
    for (nname, nres) in result.items():
1957
      if nres.offline:
1958
        # Ignore offline node
1959
        continue
1960

    
1961
      disks = node_disks[nname]
1962

    
1963
      msg = nres.fail_msg
1964
      _ErrorIf(msg, self.ENODERPC, nname,
1965
               "while getting disk information: %s", nres.fail_msg)
1966
      if msg:
1967
        # No data from this node
1968
        data = len(disks) * [None]
1969
      else:
1970
        data = nres.payload
1971

    
1972
      for ((inst, _), status) in zip(disks, data):
1973
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
1974

    
1975
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
1976
                      len(nnames) <= len(instanceinfo[inst].all_nodes)
1977
                      for inst, nnames in instdisk.items()
1978
                      for nname, statuses in nnames.items())
1979

    
1980
    return instdisk
1981

    
1982
  def BuildHooksEnv(self):
1983
    """Build hooks env.
1984

1985
    Cluster-Verify hooks just ran in the post phase and their failure makes
1986
    the output be logged in the verify output and the verification to fail.
1987

1988
    """
1989
    all_nodes = self.cfg.GetNodeList()
1990
    env = {
1991
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
1992
      }
1993
    for node in self.cfg.GetAllNodesInfo().values():
1994
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
1995

    
1996
    return env, [], all_nodes
1997

    
1998
  def Exec(self, feedback_fn):
1999
    """Verify integrity of cluster, performing various test on nodes.
2000

2001
    """
2002
    self.bad = False
2003
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2004
    verbose = self.op.verbose
2005
    self._feedback_fn = feedback_fn
2006
    feedback_fn("* Verifying global settings")
2007
    for msg in self.cfg.VerifyConfig():
2008
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
2009

    
2010
    # Check the cluster certificates
2011
    for cert_filename in constants.ALL_CERT_FILES:
2012
      (errcode, msg) = _VerifyCertificate(cert_filename)
2013
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
2014

    
2015
    vg_name = self.cfg.GetVGName()
2016
    drbd_helper = self.cfg.GetDRBDHelper()
2017
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
2018
    cluster = self.cfg.GetClusterInfo()
2019
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
2020
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
2021
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
2022
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
2023
                        for iname in instancelist)
2024
    i_non_redundant = [] # Non redundant instances
2025
    i_non_a_balanced = [] # Non auto-balanced instances
2026
    n_offline = 0 # Count of offline nodes
2027
    n_drained = 0 # Count of nodes being drained
2028
    node_vol_should = {}
2029

    
2030
    # FIXME: verify OS list
2031
    # do local checksums
2032
    master_files = [constants.CLUSTER_CONF_FILE]
2033
    master_node = self.master_node = self.cfg.GetMasterNode()
2034
    master_ip = self.cfg.GetMasterIP()
2035

    
2036
    file_names = ssconf.SimpleStore().GetFileList()
2037
    file_names.extend(constants.ALL_CERT_FILES)
2038
    file_names.extend(master_files)
2039
    if cluster.modify_etc_hosts:
2040
      file_names.append(constants.ETC_HOSTS)
2041

    
2042
    local_checksums = utils.FingerprintFiles(file_names)
2043

    
2044
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
2045
    node_verify_param = {
2046
      constants.NV_FILELIST: file_names,
2047
      constants.NV_NODELIST: [node.name for node in nodeinfo
2048
                              if not node.offline],
2049
      constants.NV_HYPERVISOR: hypervisors,
2050
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
2051
                                  node.secondary_ip) for node in nodeinfo
2052
                                 if not node.offline],
2053
      constants.NV_INSTANCELIST: hypervisors,
2054
      constants.NV_VERSION: None,
2055
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2056
      constants.NV_NODESETUP: None,
2057
      constants.NV_TIME: None,
2058
      constants.NV_MASTERIP: (master_node, master_ip),
2059
      constants.NV_OSLIST: None,
2060
      constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2061
      }
2062

    
2063
    if vg_name is not None:
2064
      node_verify_param[constants.NV_VGLIST] = None
2065
      node_verify_param[constants.NV_LVLIST] = vg_name
2066
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2067
      node_verify_param[constants.NV_DRBDLIST] = None
2068

    
2069
    if drbd_helper:
2070
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2071

    
2072
    # Build our expected cluster state
2073
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2074
                                                 name=node.name,
2075
                                                 vm_capable=node.vm_capable))
2076
                      for node in nodeinfo)
2077

    
2078
    for instance in instancelist:
2079
      inst_config = instanceinfo[instance]
2080

    
2081
      for nname in inst_config.all_nodes:
2082
        if nname not in node_image:
2083
          # ghost node
2084
          gnode = self.NodeImage(name=nname)
2085
          gnode.ghost = True
2086
          node_image[nname] = gnode
2087

    
2088
      inst_config.MapLVsByNode(node_vol_should)
2089

    
2090
      pnode = inst_config.primary_node
2091
      node_image[pnode].pinst.append(instance)
2092

    
2093
      for snode in inst_config.secondary_nodes:
2094
        nimg = node_image[snode]
2095
        nimg.sinst.append(instance)
2096
        if pnode not in nimg.sbp:
2097
          nimg.sbp[pnode] = []
2098
        nimg.sbp[pnode].append(instance)
2099

    
2100
    # At this point, we have the in-memory data structures complete,
2101
    # except for the runtime information, which we'll gather next
2102

    
2103
    # Due to the way our RPC system works, exact response times cannot be
2104
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2105
    # time before and after executing the request, we can at least have a time
2106
    # window.
2107
    nvinfo_starttime = time.time()
2108
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
2109
                                           self.cfg.GetClusterName())
2110
    nvinfo_endtime = time.time()
2111

    
2112
    all_drbd_map = self.cfg.ComputeDRBDMap()
2113

    
2114
    feedback_fn("* Gathering disk information (%s nodes)" % len(nodelist))
2115
    instdisk = self._CollectDiskInfo(nodelist, node_image, instanceinfo)
2116

    
2117
    feedback_fn("* Verifying node status")
2118

    
2119
    refos_img = None
2120

    
2121
    for node_i in nodeinfo:
2122
      node = node_i.name
2123
      nimg = node_image[node]
2124

    
2125
      if node_i.offline:
2126
        if verbose:
2127
          feedback_fn("* Skipping offline node %s" % (node,))
2128
        n_offline += 1
2129
        continue
2130

    
2131
      if node == master_node:
2132
        ntype = "master"
2133
      elif node_i.master_candidate:
2134
        ntype = "master candidate"
2135
      elif node_i.drained:
2136
        ntype = "drained"
2137
        n_drained += 1
2138
      else:
2139
        ntype = "regular"
2140
      if verbose:
2141
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2142

    
2143
      msg = all_nvinfo[node].fail_msg
2144
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2145
      if msg:
2146
        nimg.rpc_fail = True
2147
        continue
2148

    
2149
      nresult = all_nvinfo[node].payload
2150

    
2151
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2152
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2153
      self._VerifyNodeNetwork(node_i, nresult)
2154
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2155
                            master_files)
2156

    
2157
      if nimg.vm_capable:
2158
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2159
        self._VerifyNodeDrbd(node_i, nresult, instanceinfo, drbd_helper,
2160
                             all_drbd_map)
2161

    
2162
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2163
        self._UpdateNodeInstances(node_i, nresult, nimg)
2164
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2165
        self._UpdateNodeOS(node_i, nresult, nimg)
2166
        if not nimg.os_fail:
2167
          if refos_img is None:
2168
            refos_img = nimg
2169
          self._VerifyNodeOS(node_i, nimg, refos_img)
2170

    
2171
    feedback_fn("* Verifying instance status")
2172
    for instance in instancelist:
2173
      if verbose:
2174
        feedback_fn("* Verifying instance %s" % instance)
2175
      inst_config = instanceinfo[instance]
2176
      self._VerifyInstance(instance, inst_config, node_image,
2177
                           instdisk[instance])
2178
      inst_nodes_offline = []
2179

    
2180
      pnode = inst_config.primary_node
2181
      pnode_img = node_image[pnode]
2182
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2183
               self.ENODERPC, pnode, "instance %s, connection to"
2184
               " primary node failed", instance)
2185

    
2186
      if pnode_img.offline:
2187
        inst_nodes_offline.append(pnode)
2188

    
2189
      # If the instance is non-redundant we cannot survive losing its primary
2190
      # node, so we are not N+1 compliant. On the other hand we have no disk
2191
      # templates with more than one secondary so that situation is not well
2192
      # supported either.
2193
      # FIXME: does not support file-backed instances
2194
      if not inst_config.secondary_nodes:
2195
        i_non_redundant.append(instance)
2196
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2197
               instance, "instance has multiple secondary nodes: %s",
2198
               utils.CommaJoin(inst_config.secondary_nodes),
2199
               code=self.ETYPE_WARNING)
2200

    
2201
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2202
        i_non_a_balanced.append(instance)
2203

    
2204
      for snode in inst_config.secondary_nodes:
2205
        s_img = node_image[snode]
2206
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2207
                 "instance %s, connection to secondary node failed", instance)
2208

    
2209
        if s_img.offline:
2210
          inst_nodes_offline.append(snode)
2211

    
2212
      # warn that the instance lives on offline nodes
2213
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2214
               "instance lives on offline node(s) %s",
2215
               utils.CommaJoin(inst_nodes_offline))
2216
      # ... or ghost/non-vm_capable nodes
2217
      for node in inst_config.all_nodes:
2218
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2219
                 "instance lives on ghost node %s", node)
2220
        _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2221
                 instance, "instance lives on non-vm_capable node %s", node)
2222

    
2223
    feedback_fn("* Verifying orphan volumes")
2224
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2225
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2226

    
2227
    feedback_fn("* Verifying orphan instances")
2228
    self._VerifyOrphanInstances(instancelist, node_image)
2229

    
2230
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2231
      feedback_fn("* Verifying N+1 Memory redundancy")
2232
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2233

    
2234
    feedback_fn("* Other Notes")
2235
    if i_non_redundant:
2236
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2237
                  % len(i_non_redundant))
2238

    
2239
    if i_non_a_balanced:
2240
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2241
                  % len(i_non_a_balanced))
2242

    
2243
    if n_offline:
2244
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2245

    
2246
    if n_drained:
2247
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2248

    
2249
    return not self.bad
2250

    
2251
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2252
    """Analyze the post-hooks' result
2253

2254
    This method analyses the hook result, handles it, and sends some
2255
    nicely-formatted feedback back to the user.
2256

2257
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2258
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2259
    @param hooks_results: the results of the multi-node hooks rpc call
2260
    @param feedback_fn: function used send feedback back to the caller
2261
    @param lu_result: previous Exec result
2262
    @return: the new Exec result, based on the previous result
2263
        and hook results
2264

2265
    """
2266
    # We only really run POST phase hooks, and are only interested in
2267
    # their results
2268
    if phase == constants.HOOKS_PHASE_POST:
2269
      # Used to change hooks' output to proper indentation
2270
      indent_re = re.compile('^', re.M)
2271
      feedback_fn("* Hooks Results")
2272
      assert hooks_results, "invalid result from hooks"
2273

    
2274
      for node_name in hooks_results:
2275
        res = hooks_results[node_name]
2276
        msg = res.fail_msg
2277
        test = msg and not res.offline
2278
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2279
                      "Communication failure in hooks execution: %s", msg)
2280
        if res.offline or msg:
2281
          # No need to investigate payload if node is offline or gave an error.
2282
          # override manually lu_result here as _ErrorIf only
2283
          # overrides self.bad
2284
          lu_result = 1
2285
          continue
2286
        for script, hkr, output in res.payload:
2287
          test = hkr == constants.HKR_FAIL
2288
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2289
                        "Script %s failed, output:", script)
2290
          if test:
2291
            output = indent_re.sub('      ', output)
2292
            feedback_fn("%s" % output)
2293
            lu_result = 0
2294

    
2295
      return lu_result
2296

    
2297

    
2298
class LUVerifyDisks(NoHooksLU):
2299
  """Verifies the cluster disks status.
2300

2301
  """
2302
  REQ_BGL = False
2303

    
2304
  def ExpandNames(self):
2305
    self.needed_locks = {
2306
      locking.LEVEL_NODE: locking.ALL_SET,
2307
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2308
    }
2309
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2310

    
2311
  def Exec(self, feedback_fn):
2312
    """Verify integrity of cluster disks.
2313

2314
    @rtype: tuple of three items
2315
    @return: a tuple of (dict of node-to-node_error, list of instances
2316
        which need activate-disks, dict of instance: (node, volume) for
2317
        missing volumes
2318

2319
    """
2320
    result = res_nodes, res_instances, res_missing = {}, [], {}
2321

    
2322
    vg_name = self.cfg.GetVGName()
2323
    nodes = utils.NiceSort(self.cfg.GetNodeList())
2324
    instances = [self.cfg.GetInstanceInfo(name)
2325
                 for name in self.cfg.GetInstanceList()]
2326

    
2327
    nv_dict = {}
2328
    for inst in instances:
2329
      inst_lvs = {}
2330
      if (not inst.admin_up or
2331
          inst.disk_template not in constants.DTS_NET_MIRROR):
2332
        continue
2333
      inst.MapLVsByNode(inst_lvs)
2334
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2335
      for node, vol_list in inst_lvs.iteritems():
2336
        for vol in vol_list:
2337
          nv_dict[(node, vol)] = inst
2338

    
2339
    if not nv_dict:
2340
      return result
2341

    
2342
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
2343

    
2344
    for node in nodes:
2345
      # node_volume
2346
      node_res = node_lvs[node]
2347
      if node_res.offline:
2348
        continue
2349
      msg = node_res.fail_msg
2350
      if msg:
2351
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2352
        res_nodes[node] = msg
2353
        continue
2354

    
2355
      lvs = node_res.payload
2356
      for lv_name, (_, _, lv_online) in lvs.items():
2357
        inst = nv_dict.pop((node, lv_name), None)
2358
        if (not lv_online and inst is not None
2359
            and inst.name not in res_instances):
2360
          res_instances.append(inst.name)
2361

    
2362
    # any leftover items in nv_dict are missing LVs, let's arrange the
2363
    # data better
2364
    for key, inst in nv_dict.iteritems():
2365
      if inst.name not in res_missing:
2366
        res_missing[inst.name] = []
2367
      res_missing[inst.name].append(key)
2368

    
2369
    return result
2370

    
2371

    
2372
class LURepairDiskSizes(NoHooksLU):
2373
  """Verifies the cluster disks sizes.
2374

2375
  """
2376
  _OP_PARAMS = [("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString))]
2377
  REQ_BGL = False
2378

    
2379
  def ExpandNames(self):
2380
    if self.op.instances:
2381
      self.wanted_names = []
2382
      for name in self.op.instances:
2383
        full_name = _ExpandInstanceName(self.cfg, name)
2384
        self.wanted_names.append(full_name)
2385
      self.needed_locks = {
2386
        locking.LEVEL_NODE: [],
2387
        locking.LEVEL_INSTANCE: self.wanted_names,
2388
        }
2389
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2390
    else:
2391
      self.wanted_names = None
2392
      self.needed_locks = {
2393
        locking.LEVEL_NODE: locking.ALL_SET,
2394
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2395
        }
2396
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2397

    
2398
  def DeclareLocks(self, level):
2399
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2400
      self._LockInstancesNodes(primary_only=True)
2401

    
2402
  def CheckPrereq(self):
2403
    """Check prerequisites.
2404

2405
    This only checks the optional instance list against the existing names.
2406

2407
    """
2408
    if self.wanted_names is None:
2409
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2410

    
2411
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2412
                             in self.wanted_names]
2413

    
2414
  def _EnsureChildSizes(self, disk):
2415
    """Ensure children of the disk have the needed disk size.
2416

2417
    This is valid mainly for DRBD8 and fixes an issue where the
2418
    children have smaller disk size.
2419

2420
    @param disk: an L{ganeti.objects.Disk} object
2421

2422
    """
2423
    if disk.dev_type == constants.LD_DRBD8:
2424
      assert disk.children, "Empty children for DRBD8?"
2425
      fchild = disk.children[0]
2426
      mismatch = fchild.size < disk.size
2427
      if mismatch:
2428
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2429
                     fchild.size, disk.size)
2430
        fchild.size = disk.size
2431

    
2432
      # and we recurse on this child only, not on the metadev
2433
      return self._EnsureChildSizes(fchild) or mismatch
2434
    else:
2435
      return False
2436

    
2437
  def Exec(self, feedback_fn):
2438
    """Verify the size of cluster disks.
2439

2440
    """
2441
    # TODO: check child disks too
2442
    # TODO: check differences in size between primary/secondary nodes
2443
    per_node_disks = {}
2444
    for instance in self.wanted_instances:
2445
      pnode = instance.primary_node
2446
      if pnode not in per_node_disks:
2447
        per_node_disks[pnode] = []
2448
      for idx, disk in enumerate(instance.disks):
2449
        per_node_disks[pnode].append((instance, idx, disk))
2450

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

    
2487

    
2488
class LURenameCluster(LogicalUnit):
2489
  """Rename the cluster.
2490

2491
  """
2492
  HPATH = "cluster-rename"
2493
  HTYPE = constants.HTYPE_CLUSTER
2494
  _OP_PARAMS = [("name", ht.NoDefault, ht.TNonEmptyString)]
2495

    
2496
  def BuildHooksEnv(self):
2497
    """Build hooks env.
2498

2499
    """
2500
    env = {
2501
      "OP_TARGET": self.cfg.GetClusterName(),
2502
      "NEW_NAME": self.op.name,
2503
      }
2504
    mn = self.cfg.GetMasterNode()
2505
    all_nodes = self.cfg.GetNodeList()
2506
    return env, [mn], all_nodes
2507

    
2508
  def CheckPrereq(self):
2509
    """Verify that the passed name is a valid one.
2510

2511
    """
2512
    hostname = netutils.GetHostname(name=self.op.name,
2513
                                    family=self.cfg.GetPrimaryIPFamily())
2514

    
2515
    new_name = hostname.name
2516
    self.ip = new_ip = hostname.ip
2517
    old_name = self.cfg.GetClusterName()
2518
    old_ip = self.cfg.GetMasterIP()
2519
    if new_name == old_name and new_ip == old_ip:
2520
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2521
                                 " cluster has changed",
2522
                                 errors.ECODE_INVAL)
2523
    if new_ip != old_ip:
2524
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2525
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2526
                                   " reachable on the network" %
2527
                                   new_ip, errors.ECODE_NOTUNIQUE)
2528

    
2529
    self.op.name = new_name
2530

    
2531
  def Exec(self, feedback_fn):
2532
    """Rename the cluster.
2533

2534
    """
2535
    clustername = self.op.name
2536
    ip = self.ip
2537

    
2538
    # shutdown the master IP
2539
    master = self.cfg.GetMasterNode()
2540
    result = self.rpc.call_node_stop_master(master, False)
2541
    result.Raise("Could not disable the master role")
2542

    
2543
    try:
2544
      cluster = self.cfg.GetClusterInfo()
2545
      cluster.cluster_name = clustername
2546
      cluster.master_ip = ip
2547
      self.cfg.Update(cluster, feedback_fn)
2548

    
2549
      # update the known hosts file
2550
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2551
      node_list = self.cfg.GetNodeList()
2552
      try:
2553
        node_list.remove(master)
2554
      except ValueError:
2555
        pass
2556
      _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
2557
    finally:
2558
      result = self.rpc.call_node_start_master(master, False, False)
2559
      msg = result.fail_msg
2560
      if msg:
2561
        self.LogWarning("Could not re-enable the master role on"
2562
                        " the master, please restart manually: %s", msg)
2563

    
2564
    return clustername
2565

    
2566

    
2567
class LUSetClusterParams(LogicalUnit):
2568
  """Change the parameters of the cluster.
2569

2570
  """
2571
  HPATH = "cluster-modify"
2572
  HTYPE = constants.HTYPE_CLUSTER
2573
  _OP_PARAMS = [
2574
    ("vg_name", None, ht.TMaybeString),
2575
    ("enabled_hypervisors", None,
2576
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
2577
            ht.TNone)),
2578
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2579
                              ht.TNone)),
2580
    ("beparams", None, ht.TOr(ht.TDict, ht.TNone)),
2581
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2582
                            ht.TNone)),
2583
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2584
                              ht.TNone)),
2585
    ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone)),
2586
    ("uid_pool", None, ht.NoType),
2587
    ("add_uids", None, ht.NoType),
2588
    ("remove_uids", None, ht.NoType),
2589
    ("maintain_node_health", None, ht.TMaybeBool),
2590
    ("prealloc_wipe_disks", None, ht.TMaybeBool),
2591
    ("nicparams", None, ht.TOr(ht.TDict, ht.TNone)),
2592
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone)),
2593
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone)),
2594
    ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone)),
2595
    ("hidden_os", None, ht.TOr(ht.TListOf(\
2596
          ht.TAnd(ht.TList,
2597
                ht.TIsLength(2),
2598
                ht.TMap(lambda v: v[0], ht.TElemOf(constants.DDMS_VALUES)))),
2599
          ht.TNone)),
2600
    ("blacklisted_os", None, ht.TOr(ht.TListOf(\
2601
          ht.TAnd(ht.TList,
2602
                ht.TIsLength(2),
2603
                ht.TMap(lambda v: v[0], ht.TElemOf(constants.DDMS_VALUES)))),
2604
          ht.TNone)),
2605
    ]
2606
  REQ_BGL = False
2607

    
2608
  def CheckArguments(self):
2609
    """Check parameters
2610

2611
    """
2612
    if self.op.uid_pool:
2613
      uidpool.CheckUidPool(self.op.uid_pool)
2614

    
2615
    if self.op.add_uids:
2616
      uidpool.CheckUidPool(self.op.add_uids)
2617

    
2618
    if self.op.remove_uids:
2619
      uidpool.CheckUidPool(self.op.remove_uids)
2620

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

    
2629
  def BuildHooksEnv(self):
2630
    """Build hooks env.
2631

2632
    """
2633
    env = {
2634
      "OP_TARGET": self.cfg.GetClusterName(),
2635
      "NEW_VG_NAME": self.op.vg_name,
2636
      }
2637
    mn = self.cfg.GetMasterNode()
2638
    return env, [mn], [mn]
2639

    
2640
  def CheckPrereq(self):
2641
    """Check prerequisites.
2642

2643
    This checks whether the given params don't conflict and
2644
    if the given volume group is valid.
2645

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

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

    
2658
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2659

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

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

    
2695
    self.cluster = cluster = self.cfg.GetClusterInfo()
2696
    # validate params changes
2697
    if self.op.beparams:
2698
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2699
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2700

    
2701
    if self.op.nicparams:
2702
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2703
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2704
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2705
      nic_errors = []
2706

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

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

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

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

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

    
2751
    # os parameters
2752
    self.new_osp = objects.FillDict(cluster.osparams, {})
2753
    if self.op.osparams:
2754
      for os_name, osp in self.op.osparams.items():
2755
        if os_name not in self.new_osp:
2756
          self.new_osp[os_name] = {}
2757

    
2758
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2759
                                                  use_none=True)
2760

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

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

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

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

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

    
2819
  def Exec(self, feedback_fn):
2820
    """Change the parameters of the cluster.
2821

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

    
2855
    if self.op.candidate_pool_size is not None:
2856
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2857
      # we need to update the pool size here, otherwise the save will fail
2858
      _AdjustCandidatePool(self, [])
2859

    
2860
    if self.op.maintain_node_health is not None:
2861
      self.cluster.maintain_node_health = self.op.maintain_node_health
2862

    
2863
    if self.op.prealloc_wipe_disks is not None:
2864
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
2865

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

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

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

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

    
2878
    if self.op.reserved_lvs is not None:
2879
      self.cluster.reserved_lvs = self.op.reserved_lvs
2880

    
2881
    def helper_os(aname, mods, desc):
2882
      desc += " OS list"
2883
      lst = getattr(self.cluster, aname)
2884
      for key, val in mods:
2885
        if key == constants.DDM_ADD:
2886
          if val in lst:
2887
            feedback_fn("OS %s already in %s, ignoring" % (val, desc))
2888
          else:
2889
            lst.append(val)
2890
        elif key == constants.DDM_REMOVE:
2891
          if val in lst:
2892
            lst.remove(val)
2893
          else:
2894
            feedback_fn("OS %s not found in %s, ignoring" % (val, desc))
2895
        else:
2896
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
2897

    
2898
    if self.op.hidden_os:
2899
      helper_os("hidden_os", self.op.hidden_os, "hidden")
2900

    
2901
    if self.op.blacklisted_os:
2902
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
2903

    
2904
    self.cfg.Update(self.cluster, feedback_fn)
2905

    
2906

    
2907
def _UploadHelper(lu, nodes, fname):
2908
  """Helper for uploading a file and showing warnings.
2909

2910
  """
2911
  if os.path.exists(fname):
2912
    result = lu.rpc.call_upload_file(nodes, fname)
2913
    for to_node, to_result in result.items():
2914
      msg = to_result.fail_msg
2915
      if msg:
2916
        msg = ("Copy of file %s to node %s failed: %s" %
2917
               (fname, to_node, msg))
2918
        lu.proc.LogWarning(msg)
2919

    
2920

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

2924
  ConfigWriter takes care of distributing the config and ssconf files, but
2925
  there are more files which should be distributed to all nodes. This function
2926
  makes sure those are copied.
2927

2928
  @param lu: calling logical unit
2929
  @param additional_nodes: list of nodes not in the config to distribute to
2930
  @type additional_vm: boolean
2931
  @param additional_vm: whether the additional nodes are vm-capable or not
2932

2933
  """
2934
  # 1. Gather target nodes
2935
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2936
  dist_nodes = lu.cfg.GetOnlineNodeList()
2937
  nvm_nodes = lu.cfg.GetNonVmCapableNodeList()
2938
  vm_nodes = [name for name in dist_nodes if name not in nvm_nodes]
2939
  if additional_nodes is not None:
2940
    dist_nodes.extend(additional_nodes)
2941
    if additional_vm:
2942
      vm_nodes.extend(additional_nodes)
2943
  if myself.name in dist_nodes:
2944
    dist_nodes.remove(myself.name)
2945
  if myself.name in vm_nodes:
2946
    vm_nodes.remove(myself.name)
2947

    
2948
  # 2. Gather files to distribute
2949
  dist_files = set([constants.ETC_HOSTS,
2950
                    constants.SSH_KNOWN_HOSTS_FILE,
2951
                    constants.RAPI_CERT_FILE,
2952
                    constants.RAPI_USERS_FILE,
2953
                    constants.CONFD_HMAC_KEY,
2954
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
2955
                   ])
2956

    
2957
  vm_files = set()
2958
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2959
  for hv_name in enabled_hypervisors:
2960
    hv_class = hypervisor.GetHypervisor(hv_name)
2961
    vm_files.update(hv_class.GetAncillaryFiles())
2962

    
2963
  # 3. Perform the files upload
2964
  for fname in dist_files:
2965
    _UploadHelper(lu, dist_nodes, fname)
2966
  for fname in vm_files:
2967
    _UploadHelper(lu, vm_nodes, fname)
2968

    
2969

    
2970
class LURedistributeConfig(NoHooksLU):
2971
  """Force the redistribution of cluster configuration.
2972

2973
  This is a very simple LU.
2974

2975
  """
2976
  REQ_BGL = False
2977

    
2978
  def ExpandNames(self):
2979
    self.needed_locks = {
2980
      locking.LEVEL_NODE: locking.ALL_SET,
2981
    }
2982
    self.share_locks[locking.LEVEL_NODE] = 1
2983

    
2984
  def Exec(self, feedback_fn):
2985
    """Redistribute the configuration.
2986

2987
    """
2988
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2989
    _RedistributeAncillaryFiles(self)
2990

    
2991

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

2995
  """
2996
  if not instance.disks or disks is not None and not disks:
2997
    return True
2998

    
2999
  disks = _ExpandCheckDisks(instance, disks)
3000

    
3001
  if not oneshot:
3002
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
3003

    
3004
  node = instance.primary_node
3005

    
3006
  for dev in disks:
3007
    lu.cfg.SetDiskID(dev, node)
3008

    
3009
  # TODO: Convert to utils.Retry
3010

    
3011
  retries = 0
3012
  degr_retries = 10 # in seconds, as we sleep 1 second each time
3013
  while True:
3014
    max_time = 0
3015
    done = True
3016
    cumul_degraded = False
3017
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
3018
    msg = rstats.fail_msg
3019
    if msg:
3020
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
3021
      retries += 1
3022
      if retries >= 10:
3023
        raise errors.RemoteError("Can't contact node %s for mirror data,"
3024
                                 " aborting." % node)
3025
      time.sleep(6)
3026
      continue
3027
    rstats = rstats.payload
3028
    retries = 0
3029
    for i, mstat in enumerate(rstats):
3030
      if mstat is None:
3031
        lu.LogWarning("Can't compute data for node %s/%s",
3032
                           node, disks[i].iv_name)
3033
        continue
3034

    
3035
      cumul_degraded = (cumul_degraded or
3036
                        (mstat.is_degraded and mstat.sync_percent is None))
3037
      if mstat.sync_percent is not None:
3038
        done = False
3039
        if mstat.estimated_time is not None:
3040
          rem_time = ("%s remaining (estimated)" %
3041
                      utils.FormatSeconds(mstat.estimated_time))
3042
          max_time = mstat.estimated_time
3043
        else:
3044
          rem_time = "no time estimate"
3045
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3046
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3047

    
3048
    # if we're done but degraded, let's do a few small retries, to
3049
    # make sure we see a stable and not transient situation; therefore
3050
    # we force restart of the loop
3051
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3052
      logging.info("Degraded disks found, %d retries left", degr_retries)
3053
      degr_retries -= 1
3054
      time.sleep(1)
3055
      continue
3056

    
3057
    if done or oneshot:
3058
      break
3059

    
3060
    time.sleep(min(60, max_time))
3061

    
3062
  if done:
3063
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3064
  return not cumul_degraded
3065

    
3066

    
3067
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3068
  """Check that mirrors are not degraded.
3069

3070
  The ldisk parameter, if True, will change the test from the
3071
  is_degraded attribute (which represents overall non-ok status for
3072
  the device(s)) to the ldisk (representing the local storage status).
3073

3074
  """
3075
  lu.cfg.SetDiskID(dev, node)
3076

    
3077
  result = True
3078

    
3079
  if on_primary or dev.AssembleOnSecondary():
3080
    rstats = lu.rpc.call_blockdev_find(node, dev)
3081
    msg = rstats.fail_msg
3082
    if msg:
3083
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3084
      result = False
3085
    elif not rstats.payload:
3086
      lu.LogWarning("Can't find disk on node %s", node)
3087
      result = False
3088
    else:
3089
      if ldisk:
3090
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3091
      else:
3092
        result = result and not rstats.payload.is_degraded
3093

    
3094
  if dev.children:
3095
    for child in dev.children:
3096
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3097

    
3098
  return result
3099

    
3100

    
3101
class LUDiagnoseOS(NoHooksLU):
3102
  """Logical unit for OS diagnose/query.
3103

3104
  """
3105
  _OP_PARAMS = [
3106
    _POutputFields,
3107
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3108
    ]
3109
  REQ_BGL = False
3110
  _HID = "hidden"
3111
  _BLK = "blacklisted"
3112
  _VLD = "valid"
3113
  _FIELDS_STATIC = utils.FieldSet()
3114
  _FIELDS_DYNAMIC = utils.FieldSet("name", _VLD, "node_status", "variants",
3115
                                   "parameters", "api_versions", _HID, _BLK)
3116

    
3117
  def CheckArguments(self):
3118
    if self.op.names:
3119
      raise errors.OpPrereqError("Selective OS query not supported",
3120
                                 errors.ECODE_INVAL)
3121

    
3122
    _CheckOutputFields(static=self._FIELDS_STATIC,
3123
                       dynamic=self._FIELDS_DYNAMIC,
3124
                       selected=self.op.output_fields)
3125

    
3126
  def ExpandNames(self):
3127
    # Lock all nodes, in shared mode
3128
    # Temporary removal of locks, should be reverted later
3129
    # TODO: reintroduce locks when they are lighter-weight
3130
    self.needed_locks = {}
3131
    #self.share_locks[locking.LEVEL_NODE] = 1
3132
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3133

    
3134
  @staticmethod
3135
  def _DiagnoseByOS(rlist):
3136
    """Remaps a per-node return list into an a per-os per-node dictionary
3137

3138
    @param rlist: a map with node names as keys and OS objects as values
3139

3140
    @rtype: dict
3141
    @return: a dictionary with osnames as keys and as value another
3142
        map, with nodes as keys and tuples of (path, status, diagnose,
3143
        variants, parameters, api_versions) as values, eg::
3144

3145
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3146
                                     (/srv/..., False, "invalid api")],
3147
                           "node2": [(/srv/..., True, "", [], [])]}
3148
          }
3149

3150
    """
3151
    all_os = {}
3152
    # we build here the list of nodes that didn't fail the RPC (at RPC
3153
    # level), so that nodes with a non-responding node daemon don't
3154
    # make all OSes invalid
3155
    good_nodes = [node_name for node_name in rlist
3156
                  if not rlist[node_name].fail_msg]
3157
    for node_name, nr in rlist.items():
3158
      if nr.fail_msg or not nr.payload:
3159
        continue
3160
      for (name, path, status, diagnose, variants,
3161
           params, api_versions) in nr.payload:
3162
        if name not in all_os:
3163
          # build a list of nodes for this os containing empty lists
3164
          # for each node in node_list
3165
          all_os[name] = {}
3166
          for nname in good_nodes:
3167
            all_os[name][nname] = []
3168
        # convert params from [name, help] to (name, help)
3169
        params = [tuple(v) for v in params]
3170
        all_os[name][node_name].append((path, status, diagnose,
3171
                                        variants, params, api_versions))
3172
    return all_os
3173

    
3174
  def Exec(self, feedback_fn):
3175
    """Compute the list of OSes.
3176

3177
    """
3178
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
3179
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3180
    pol = self._DiagnoseByOS(node_data)
3181
    output = []
3182
    cluster = self.cfg.GetClusterInfo()
3183

    
3184
    for os_name in utils.NiceSort(pol.keys()):
3185
      os_data = pol[os_name]
3186
      row = []
3187
      valid = True
3188
      (variants, params, api_versions) = null_state = (set(), set(), set())
3189
      for idx, osl in enumerate(os_data.values()):
3190
        valid = bool(valid and osl and osl[0][1])
3191
        if not valid:
3192
          (variants, params, api_versions) = null_state
3193
          break
3194
        node_variants, node_params, node_api = osl[0][3:6]
3195
        if idx == 0: # first entry
3196
          variants = set(node_variants)
3197
          params = set(node_params)
3198
          api_versions = set(node_api)
3199
        else: # keep consistency
3200
          variants.intersection_update(node_variants)
3201
          params.intersection_update(node_params)
3202
          api_versions.intersection_update(node_api)
3203

    
3204
      is_hid = os_name in cluster.hidden_os
3205
      is_blk = os_name in cluster.blacklisted_os
3206
      if ((self._HID not in self.op.output_fields and is_hid) or
3207
          (self._BLK not in self.op.output_fields and is_blk) or
3208
          (self._VLD not in self.op.output_fields and not valid)):
3209
        continue
3210

    
3211
      for field in self.op.output_fields:
3212
        if field == "name":
3213
          val = os_name
3214
        elif field == self._VLD:
3215
          val = valid
3216
        elif field == "node_status":
3217
          # this is just a copy of the dict
3218
          val = {}
3219
          for node_name, nos_list in os_data.items():
3220
            val[node_name] = nos_list
3221
        elif field == "variants":
3222
          val = utils.NiceSort(list(variants))
3223
        elif field == "parameters":
3224
          val = list(params)
3225
        elif field == "api_versions":
3226
          val = list(api_versions)
3227
        elif field == self._HID:
3228
          val = is_hid
3229
        elif field == self._BLK:
3230
          val = is_blk
3231
        else:
3232
          raise errors.ParameterError(field)
3233
        row.append(val)
3234
      output.append(row)
3235

    
3236
    return output
3237

    
3238

    
3239
class LURemoveNode(LogicalUnit):
3240
  """Logical unit for removing a node.
3241

3242
  """
3243
  HPATH = "node-remove"
3244
  HTYPE = constants.HTYPE_NODE
3245
  _OP_PARAMS = [
3246
    _PNodeName,
3247
    ]
3248

    
3249
  def BuildHooksEnv(self):
3250
    """Build hooks env.
3251

3252
    This doesn't run on the target node in the pre phase as a failed
3253
    node would then be impossible to remove.
3254

3255
    """
3256
    env = {
3257
      "OP_TARGET": self.op.node_name,
3258
      "NODE_NAME": self.op.node_name,
3259
      }
3260
    all_nodes = self.cfg.GetNodeList()
3261
    try:
3262
      all_nodes.remove(self.op.node_name)
3263
    except ValueError:
3264
      logging.warning("Node %s which is about to be removed not found"
3265
                      " in the all nodes list", self.op.node_name)
3266
    return env, all_nodes, all_nodes
3267

    
3268
  def CheckPrereq(self):
3269
    """Check prerequisites.
3270

3271
    This checks:
3272
     - the node exists in the configuration
3273
     - it does not have primary or secondary instances
3274
     - it's not the master
3275

3276
    Any errors are signaled by raising errors.OpPrereqError.
3277

3278
    """
3279
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3280
    node = self.cfg.GetNodeInfo(self.op.node_name)
3281
    assert node is not None
3282

    
3283
    instance_list = self.cfg.GetInstanceList()
3284

    
3285
    masternode = self.cfg.GetMasterNode()
3286
    if node.name == masternode:
3287
      raise errors.OpPrereqError("Node is the master node,"
3288
                                 " you need to failover first.",
3289
                                 errors.ECODE_INVAL)
3290

    
3291
    for instance_name in instance_list:
3292
      instance = self.cfg.GetInstanceInfo(instance_name)
3293
      if node.name in instance.all_nodes:
3294
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3295
                                   " please remove first." % instance_name,
3296
                                   errors.ECODE_INVAL)
3297
    self.op.node_name = node.name
3298
    self.node = node
3299

    
3300
  def Exec(self, feedback_fn):
3301
    """Removes the node from the cluster.
3302

3303
    """
3304
    node = self.node
3305
    logging.info("Stopping the node daemon and removing configs from node %s",
3306
                 node.name)
3307

    
3308
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3309

    
3310
    # Promote nodes to master candidate as needed
3311
    _AdjustCandidatePool(self, exceptions=[node.name])
3312
    self.context.RemoveNode(node.name)
3313

    
3314
    # Run post hooks on the node before it's removed
3315
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3316
    try:
3317
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3318
    except:
3319
      # pylint: disable-msg=W0702
3320
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3321

    
3322
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3323
    msg = result.fail_msg
3324
    if msg:
3325
      self.LogWarning("Errors encountered on the remote node while leaving"
3326
                      " the cluster: %s", msg)
3327

    
3328
    # Remove node from our /etc/hosts
3329
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3330
      master_node = self.cfg.GetMasterNode()
3331
      result = self.rpc.call_etc_hosts_modify(master_node,
3332
                                              constants.ETC_HOSTS_REMOVE,
3333
                                              node.name, None)
3334
      result.Raise("Can't update hosts file with new host data")
3335
      _RedistributeAncillaryFiles(self)
3336

    
3337

    
3338
class LUQueryNodes(NoHooksLU):
3339
  """Logical unit for querying nodes.
3340

3341
  """
3342
  # pylint: disable-msg=W0142
3343
  _OP_PARAMS = [
3344
    _POutputFields,
3345
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3346
    ("use_locking", False, ht.TBool),
3347
    ]
3348
  REQ_BGL = False
3349

    
3350
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
3351
                    "master_candidate", "offline", "drained",
3352
                    "master_capable", "vm_capable"]
3353

    
3354
  _FIELDS_DYNAMIC = utils.FieldSet(
3355
    "dtotal", "dfree",
3356
    "mtotal", "mnode", "mfree",
3357
    "bootid",
3358
    "ctotal", "cnodes", "csockets",
3359
    )
3360

    
3361
  _FIELDS_STATIC = utils.FieldSet(*[
3362
    "pinst_cnt", "sinst_cnt",
3363
    "pinst_list", "sinst_list",
3364
    "pip", "sip", "tags",
3365
    "master", "role",
3366
    "group.uuid", "group",
3367
    ] + _SIMPLE_FIELDS
3368
    )
3369

    
3370
  def CheckArguments(self):
3371
    _CheckOutputFields(static=self._FIELDS_STATIC,
3372
                       dynamic=self._FIELDS_DYNAMIC,
3373
                       selected=self.op.output_fields)
3374

    
3375
  def ExpandNames(self):
3376
    self.needed_locks = {}
3377
    self.share_locks[locking.LEVEL_NODE] = 1
3378

    
3379
    if self.op.names:
3380
      self.wanted = _GetWantedNodes(self, self.op.names)
3381
    else:
3382
      self.wanted = locking.ALL_SET
3383

    
3384
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3385
    self.do_locking = self.do_node_query and self.op.use_locking
3386
    if self.do_locking:
3387
      # if we don't request only static fields, we need to lock the nodes
3388
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
3389

    
3390
  def Exec(self, feedback_fn):
3391
    """Computes the list of nodes and their attributes.
3392

3393
    """
3394
    all_info = self.cfg.GetAllNodesInfo()
3395
    if self.do_locking:
3396
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
3397
    elif self.wanted != locking.ALL_SET:
3398
      nodenames = self.wanted
3399
      missing = set(nodenames).difference(all_info.keys())
3400
      if missing:
3401
        raise errors.OpExecError(
3402
          "Some nodes were removed before retrieving their data: %s" % missing)
3403
    else:
3404
      nodenames = all_info.keys()
3405

    
3406
    nodenames = utils.NiceSort(nodenames)
3407
    nodelist = [all_info[name] for name in nodenames]
3408

    
3409
    if "group" in self.op.output_fields:
3410
      groups = self.cfg.GetAllNodeGroupsInfo()
3411
    else:
3412
      groups = {}
3413

    
3414
    # begin data gathering
3415

    
3416
    if self.do_node_query:
3417
      live_data = {}
3418
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
3419
                                          self.cfg.GetHypervisorType())
3420
      for name in nodenames:
3421
        nodeinfo = node_data[name]
3422
        if not nodeinfo.fail_msg and nodeinfo.payload:
3423
          nodeinfo = nodeinfo.payload
3424
          fn = utils.TryConvert
3425
          live_data[name] = {
3426
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
3427
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
3428
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
3429
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
3430
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
3431
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
3432
            "bootid": nodeinfo.get('bootid', None),
3433
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
3434
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
3435
            }
3436
        else:
3437
          live_data[name] = {}
3438
    else:
3439
      live_data = dict.fromkeys(nodenames, {})
3440

    
3441
    node_to_primary = dict([(name, set()) for name in nodenames])
3442
    node_to_secondary = dict([(name, set()) for name in nodenames])
3443

    
3444
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
3445
                             "sinst_cnt", "sinst_list"))
3446
    if inst_fields & frozenset(self.op.output_fields):
3447
      inst_data = self.cfg.GetAllInstancesInfo()
3448

    
3449
      for inst in inst_data.values():
3450
        if inst.primary_node in node_to_primary:
3451
          node_to_primary[inst.primary_node].add(inst.name)
3452
        for secnode in inst.secondary_nodes:
3453
          if secnode in node_to_secondary:
3454
            node_to_secondary[secnode].add(inst.name)
3455

    
3456
    master_node = self.cfg.GetMasterNode()
3457

    
3458
    # end data gathering
3459

    
3460
    output = []
3461
    for node in nodelist:
3462
      node_output = []
3463
      for field in self.op.output_fields:
3464
        if field in self._SIMPLE_FIELDS:
3465
          val = getattr(node, field)
3466
        elif field == "pinst_list":
3467
          val = list(node_to_primary[node.name])
3468
        elif field == "sinst_list":
3469
          val = list(node_to_secondary[node.name])
3470
        elif field == "pinst_cnt":
3471
          val = len(node_to_primary[node.name])
3472
        elif field == "sinst_cnt":
3473
          val = len(node_to_secondary[node.name])
3474
        elif field == "pip":
3475
          val = node.primary_ip
3476
        elif field == "sip":
3477
          val = node.secondary_ip
3478
        elif field == "tags":
3479
          val = list(node.GetTags())
3480
        elif field == "master":
3481
          val = node.name == master_node
3482
        elif self._FIELDS_DYNAMIC.Matches(field):
3483
          val = live_data[node.name].get(field, None)
3484
        elif field == "role":
3485
          if node.name == master_node:
3486
            val = "M"
3487
          elif node.master_candidate:
3488
            val = "C"
3489
          elif node.drained:
3490
            val = "D"
3491
          elif node.offline:
3492
            val = "O"
3493
          else:
3494
            val = "R"
3495
        elif field == "group.uuid":
3496
          val = node.group
3497
        elif field == "group":
3498
          ng = groups.get(node.group, None)
3499
          if ng is None:
3500
            val = "<unknown>"
3501
          else:
3502
            val = ng.name
3503
        else:
3504
          raise errors.ParameterError(field)
3505
        node_output.append(val)
3506
      output.append(node_output)
3507

    
3508
    return output
3509

    
3510

    
3511
class LUQueryNodeVolumes(NoHooksLU):
3512
  """Logical unit for getting volumes on node(s).
3513

3514
  """
3515
  _OP_PARAMS = [
3516
    _POutputFields,
3517
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3518
    ]
3519
  REQ_BGL = False
3520
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3521
  _FIELDS_STATIC = utils.FieldSet("node")
3522

    
3523
  def CheckArguments(self):
3524
    _CheckOutputFields(static=self._FIELDS_STATIC,
3525
                       dynamic=self._FIELDS_DYNAMIC,
3526
                       selected=self.op.output_fields)
3527

    
3528
  def ExpandNames(self):
3529
    self.needed_locks = {}
3530
    self.share_locks[locking.LEVEL_NODE] = 1
3531
    if not self.op.nodes:
3532
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3533
    else:
3534
      self.needed_locks[locking.LEVEL_NODE] = \
3535
        _GetWantedNodes(self, self.op.nodes)
3536

    
3537
  def Exec(self, feedback_fn):
3538
    """Computes the list of nodes and their attributes.
3539

3540
    """
3541
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3542
    volumes = self.rpc.call_node_volumes(nodenames)
3543

    
3544
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3545
             in self.cfg.GetInstanceList()]
3546

    
3547
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3548

    
3549
    output = []
3550
    for node in nodenames:
3551
      nresult = volumes[node]
3552
      if nresult.offline:
3553
        continue
3554
      msg = nresult.fail_msg
3555
      if msg:
3556
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3557
        continue
3558

    
3559
      node_vols = nresult.payload[:]
3560
      node_vols.sort(key=lambda vol: vol['dev'])
3561

    
3562
      for vol in node_vols:
3563
        node_output = []
3564
        for field in self.op.output_fields:
3565
          if field == "node":
3566
            val = node
3567
          elif field == "phys":
3568
            val = vol['dev']
3569
          elif field == "vg":
3570
            val = vol['vg']
3571
          elif field == "name":
3572
            val = vol['name']
3573
          elif field == "size":
3574
            val = int(float(vol['size']))
3575
          elif field == "instance":
3576
            for inst in ilist:
3577
              if node not in lv_by_node[inst]:
3578
                continue
3579
              if vol['name'] in lv_by_node[inst][node]:
3580
                val = inst.name
3581
                break
3582
            else:
3583
              val = '-'
3584
          else:
3585
            raise errors.ParameterError(field)
3586
          node_output.append(str(val))
3587

    
3588
        output.append(node_output)
3589

    
3590
    return output
3591

    
3592

    
3593
class LUQueryNodeStorage(NoHooksLU):
3594
  """Logical unit for getting information on storage units on node(s).
3595

3596
  """
3597
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3598
  _OP_PARAMS = [
3599
    _POutputFields,
3600
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3601
    ("storage_type", ht.NoDefault, _CheckStorageType),
3602
    ("name", None, ht.TMaybeString),
3603
    ]
3604
  REQ_BGL = False
3605

    
3606
  def CheckArguments(self):
3607
    _CheckOutputFields(static=self._FIELDS_STATIC,
3608
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3609
                       selected=self.op.output_fields)
3610

    
3611
  def ExpandNames(self):
3612
    self.needed_locks = {}
3613
    self.share_locks[locking.LEVEL_NODE] = 1
3614

    
3615
    if self.op.nodes:
3616
      self.needed_locks[locking.LEVEL_NODE] = \
3617
        _GetWantedNodes(self, self.op.nodes)
3618
    else:
3619
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3620

    
3621
  def Exec(self, feedback_fn):
3622
    """Computes the list of nodes and their attributes.
3623

3624
    """
3625
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3626

    
3627
    # Always get name to sort by
3628
    if constants.SF_NAME in self.op.output_fields:
3629
      fields = self.op.output_fields[:]
3630
    else:
3631
      fields = [constants.SF_NAME] + self.op.output_fields
3632

    
3633
    # Never ask for node or type as it's only known to the LU
3634
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3635
      while extra in fields:
3636
        fields.remove(extra)
3637

    
3638
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3639
    name_idx = field_idx[constants.SF_NAME]
3640

    
3641
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3642
    data = self.rpc.call_storage_list(self.nodes,
3643
                                      self.op.storage_type, st_args,
3644
                                      self.op.name, fields)
3645

    
3646
    result = []
3647

    
3648
    for node in utils.NiceSort(self.nodes):
3649
      nresult = data[node]
3650
      if nresult.offline:
3651
        continue
3652

    
3653
      msg = nresult.fail_msg
3654
      if msg:
3655
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3656
        continue
3657

    
3658
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3659

    
3660
      for name in utils.NiceSort(rows.keys()):
3661
        row = rows[name]
3662

    
3663
        out = []
3664

    
3665
        for field in self.op.output_fields:
3666
          if field == constants.SF_NODE:
3667
            val = node
3668
          elif field == constants.SF_TYPE:
3669
            val = self.op.storage_type
3670
          elif field in field_idx:
3671
            val = row[field_idx[field]]
3672
          else:
3673
            raise errors.ParameterError(field)
3674

    
3675
          out.append(val)
3676

    
3677
        result.append(out)
3678

    
3679
    return result
3680

    
3681

    
3682
class LUModifyNodeStorage(NoHooksLU):
3683
  """Logical unit for modifying a storage volume on a node.
3684

3685
  """
3686
  _OP_PARAMS = [
3687
    _PNodeName,
3688
    ("storage_type", ht.NoDefault, _CheckStorageType),
3689
    ("name", ht.NoDefault, ht.TNonEmptyString),
3690
    ("changes", ht.NoDefault, ht.TDict),
3691
    ]
3692
  REQ_BGL = False
3693

    
3694
  def CheckArguments(self):
3695
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3696

    
3697
    storage_type = self.op.storage_type
3698

    
3699
    try:
3700
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3701
    except KeyError:
3702
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3703
                                 " modified" % storage_type,
3704
                                 errors.ECODE_INVAL)
3705

    
3706
    diff = set(self.op.changes.keys()) - modifiable
3707
    if diff:
3708
      raise errors.OpPrereqError("The following fields can not be modified for"
3709
                                 " storage units of type '%s': %r" %
3710
                                 (storage_type, list(diff)),
3711
                                 errors.ECODE_INVAL)
3712

    
3713
  def ExpandNames(self):
3714
    self.needed_locks = {
3715
      locking.LEVEL_NODE: self.op.node_name,
3716
      }
3717

    
3718
  def Exec(self, feedback_fn):
3719
    """Computes the list of nodes and their attributes.
3720

3721
    """
3722
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3723
    result = self.rpc.call_storage_modify(self.op.node_name,
3724
                                          self.op.storage_type, st_args,
3725
                                          self.op.name, self.op.changes)
3726
    result.Raise("Failed to modify storage unit '%s' on %s" %
3727
                 (self.op.name, self.op.node_name))
3728

    
3729

    
3730
class LUAddNode(LogicalUnit):
3731
  """Logical unit for adding node to the cluster.
3732

3733
  """
3734
  HPATH = "node-add"
3735
  HTYPE = constants.HTYPE_NODE
3736
  _OP_PARAMS = [
3737
    _PNodeName,
3738
    ("primary_ip", None, ht.NoType),
3739
    ("secondary_ip", None, ht.TMaybeString),
3740
    ("readd", False, ht.TBool),
3741
    ("group", None, ht.TMaybeString),
3742
    ("master_capable", None, ht.TMaybeBool),
3743
    ("vm_capable", None, ht.TMaybeBool),
3744
    ]
3745
  _NFLAGS = ["master_capable", "vm_capable"]
3746

    
3747
  def CheckArguments(self):
3748
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
3749
    # validate/normalize the node name
3750
    self.hostname = netutils.GetHostname(name=self.op.node_name,
3751
                                         family=self.primary_ip_family)
3752
    self.op.node_name = self.hostname.name
3753
    if self.op.readd and self.op.group:
3754
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
3755
                                 " being readded", errors.ECODE_INVAL)
3756

    
3757
  def BuildHooksEnv(self):
3758
    """Build hooks env.
3759

3760
    This will run on all nodes before, and on all nodes + the new node after.
3761

3762
    """
3763
    env = {
3764
      "OP_TARGET": self.op.node_name,
3765
      "NODE_NAME": self.op.node_name,
3766
      "NODE_PIP": self.op.primary_ip,
3767
      "NODE_SIP": self.op.secondary_ip,
3768
      "MASTER_CAPABLE": str(self.op.master_capable),
3769
      "VM_CAPABLE": str(self.op.vm_capable),
3770
      }
3771
    nodes_0 = self.cfg.GetNodeList()
3772
    nodes_1 = nodes_0 + [self.op.node_name, ]
3773
    return env, nodes_0, nodes_1
3774

    
3775
  def CheckPrereq(self):
3776
    """Check prerequisites.
3777

3778
    This checks:
3779
     - the new node is not already in the config
3780
     - it is resolvable
3781
     - its parameters (single/dual homed) matches the cluster
3782

3783
    Any errors are signaled by raising errors.OpPrereqError.
3784

3785
    """
3786
    cfg = self.cfg
3787
    hostname = self.hostname
3788
    node = hostname.name
3789
    primary_ip = self.op.primary_ip = hostname.ip
3790
    if self.op.secondary_ip is None:
3791
      if self.primary_ip_family == netutils.IP6Address.family:
3792
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
3793
                                   " IPv4 address must be given as secondary",
3794
                                   errors.ECODE_INVAL)
3795
      self.op.secondary_ip = primary_ip
3796

    
3797
    secondary_ip = self.op.secondary_ip
3798
    if not netutils.IP4Address.IsValid(secondary_ip):
3799
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
3800
                                 " address" % secondary_ip, errors.ECODE_INVAL)
3801

    
3802
    node_list = cfg.GetNodeList()
3803
    if not self.op.readd and node in node_list:
3804
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3805
                                 node, errors.ECODE_EXISTS)
3806
    elif self.op.readd and node not in node_list:
3807
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3808
                                 errors.ECODE_NOENT)
3809

    
3810
    self.changed_primary_ip = False
3811

    
3812
    for existing_node_name in node_list:
3813
      existing_node = cfg.GetNodeInfo(existing_node_name)
3814

    
3815
      if self.op.readd and node == existing_node_name:
3816
        if existing_node.secondary_ip != secondary_ip:
3817
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3818
                                     " address configuration as before",
3819
                                     errors.ECODE_INVAL)
3820
        if existing_node.primary_ip != primary_ip:
3821
          self.changed_primary_ip = True
3822

    
3823
        continue
3824

    
3825
      if (existing_node.primary_ip == primary_ip or
3826
          existing_node.secondary_ip == primary_ip or
3827
          existing_node.primary_ip == secondary_ip or
3828
          existing_node.secondary_ip == secondary_ip):
3829
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3830
                                   " existing node %s" % existing_node.name,
3831
                                   errors.ECODE_NOTUNIQUE)
3832

    
3833
    # After this 'if' block, None is no longer a valid value for the
3834
    # _capable op attributes
3835
    if self.op.readd:
3836
      old_node = self.cfg.GetNodeInfo(node)
3837
      assert old_node is not None, "Can't retrieve locked node %s" % node
3838
      for attr in self._NFLAGS:
3839
        if getattr(self.op, attr) is None:
3840
          setattr(self.op, attr, getattr(old_node, attr))
3841
    else:
3842
      for attr in self._NFLAGS:
3843
        if getattr(self.op, attr) is None:
3844
          setattr(self.op, attr, True)
3845

    
3846
    if self.op.readd and not self.op.vm_capable:
3847
      pri, sec = cfg.GetNodeInstances(node)
3848
      if pri or sec:
3849
        raise errors.OpPrereqError("Node %s being re-added with vm_capable"
3850
                                   " flag set to false, but it already holds"
3851
                                   " instances" % node,
3852
                                   errors.ECODE_STATE)
3853

    
3854
    # check that the type of the node (single versus dual homed) is the
3855
    # same as for the master
3856
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
3857
    master_singlehomed = myself.secondary_ip == myself.primary_ip
3858
    newbie_singlehomed = secondary_ip == primary_ip
3859
    if master_singlehomed != newbie_singlehomed:
3860
      if master_singlehomed:
3861
        raise errors.OpPrereqError("The master has no secondary ip but the"
3862
                                   " new node has one",
3863
                                   errors.ECODE_INVAL)
3864
      else:
3865
        raise errors.OpPrereqError("The master has a secondary ip but the"
3866
                                   " new node doesn't have one",
3867
                                   errors.ECODE_INVAL)
3868

    
3869
    # checks reachability
3870
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3871
      raise errors.OpPrereqError("Node not reachable by ping",
3872
                                 errors.ECODE_ENVIRON)
3873

    
3874
    if not newbie_singlehomed:
3875
      # check reachability from my secondary ip to newbie's secondary ip
3876
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3877
                           source=myself.secondary_ip):
3878
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3879
                                   " based ping to node daemon port",
3880
                                   errors.ECODE_ENVIRON)
3881

    
3882
    if self.op.readd:
3883
      exceptions = [node]
3884
    else:
3885
      exceptions = []
3886

    
3887
    if self.op.master_capable:
3888
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3889
    else:
3890
      self.master_candidate = False
3891

    
3892
    if self.op.readd:
3893
      self.new_node = old_node
3894
    else:
3895
      node_group = cfg.LookupNodeGroup(self.op.group)
3896
      self.new_node = objects.Node(name=node,
3897
                                   primary_ip=primary_ip,
3898
                                   secondary_ip=secondary_ip,
3899
                                   master_candidate=self.master_candidate,
3900
                                   offline=False, drained=False,
3901
                                   group=node_group)
3902

    
3903
  def Exec(self, feedback_fn):
3904
    """Adds the new node to the cluster.
3905

3906
    """
3907
    new_node = self.new_node
3908
    node = new_node.name
3909

    
3910
    # for re-adds, reset the offline/drained/master-candidate flags;
3911
    # we need to reset here, otherwise offline would prevent RPC calls
3912
    # later in the procedure; this also means that if the re-add
3913
    # fails, we are left with a non-offlined, broken node
3914
    if self.op.readd:
3915
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3916
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3917
      # if we demote the node, we do cleanup later in the procedure
3918
      new_node.master_candidate = self.master_candidate
3919
      if self.changed_primary_ip:
3920
        new_node.primary_ip = self.op.primary_ip
3921

    
3922
    # copy the master/vm_capable flags
3923
    for attr in self._NFLAGS:
3924
      setattr(new_node, attr, getattr(self.op, attr))
3925

    
3926
    # notify the user about any possible mc promotion
3927
    if new_node.master_candidate:
3928
      self.LogInfo("Node will be a master candidate")
3929

    
3930
    # check connectivity
3931
    result = self.rpc.call_version([node])[node]
3932
    result.Raise("Can't get version information from node %s" % node)
3933
    if constants.PROTOCOL_VERSION == result.payload:
3934
      logging.info("Communication to node %s fine, sw version %s match",
3935
                   node, result.payload)
3936
    else:
3937
      raise errors.OpExecError("Version mismatch master version %s,"
3938
                               " node version %s" %
3939
                               (constants.PROTOCOL_VERSION, result.payload))
3940

    
3941
    # Add node to our /etc/hosts, and add key to known_hosts
3942
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3943
      master_node = self.cfg.GetMasterNode()
3944
      result = self.rpc.call_etc_hosts_modify(master_node,
3945
                                              constants.ETC_HOSTS_ADD,
3946
                                              self.hostname.name,
3947
                                              self.hostname.ip)
3948
      result.Raise("Can't update hosts file with new host data")
3949

    
3950
    if new_node.secondary_ip != new_node.primary_ip:
3951
      _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
3952
                               False)
3953

    
3954
    node_verify_list = [self.cfg.GetMasterNode()]
3955
    node_verify_param = {
3956
      constants.NV_NODELIST: [node],
3957
      # TODO: do a node-net-test as well?
3958
    }
3959

    
3960
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3961
                                       self.cfg.GetClusterName())
3962
    for verifier in node_verify_list:
3963
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3964
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3965
      if nl_payload:
3966
        for failed in nl_payload:
3967
          feedback_fn("ssh/hostname verification failed"
3968
                      " (checking from %s): %s" %
3969
                      (verifier, nl_payload[failed]))
3970
        raise errors.OpExecError("ssh/hostname verification failed.")
3971

    
3972
    if self.op.readd:
3973
      _RedistributeAncillaryFiles(self)
3974
      self.context.ReaddNode(new_node)
3975
      # make sure we redistribute the config
3976
      self.cfg.Update(new_node, feedback_fn)
3977
      # and make sure the new node will not have old files around
3978
      if not new_node.master_candidate:
3979
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3980
        msg = result.fail_msg
3981
        if msg:
3982
          self.LogWarning("Node failed to demote itself from master"
3983
                          " candidate status: %s" % msg)
3984
    else:
3985
      _RedistributeAncillaryFiles(self, additional_nodes=[node],
3986
                                  additional_vm=self.op.vm_capable)
3987
      self.context.AddNode(new_node, self.proc.GetECId())
3988

    
3989

    
3990
class LUSetNodeParams(LogicalUnit):
3991
  """Modifies the parameters of a node.
3992

3993
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
3994
      to the node role (as _ROLE_*)
3995
  @cvar _R2F: a dictionary from node role to tuples of flags
3996
  @cvar _FLAGS: a list of attribute names corresponding to the flags
3997

3998
  """
3999
  HPATH = "node-modify"
4000
  HTYPE = constants.HTYPE_NODE
4001
  _OP_PARAMS = [
4002
    _PNodeName,
4003
    ("master_candidate", None, ht.TMaybeBool),
4004
    ("offline", None, ht.TMaybeBool),
4005
    ("drained", None, ht.TMaybeBool),
4006
    ("auto_promote", False, ht.TBool),
4007
    ("master_capable", None, ht.TMaybeBool),
4008
    ("vm_capable", None, ht.TMaybeBool),
4009
    ("secondary_ip", None, ht.TMaybeString),
4010
    _PForce,
4011
    ]
4012
  REQ_BGL = False
4013
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
4014
  _F2R = {
4015
    (True, False, False): _ROLE_CANDIDATE,
4016
    (False, True, False): _ROLE_DRAINED,
4017
    (False, False, True): _ROLE_OFFLINE,
4018
    (False, False, False): _ROLE_REGULAR,
4019
    }
4020
  _R2F = dict((v, k) for k, v in _F2R.items())
4021
  _FLAGS = ["master_candidate", "drained", "offline"]
4022

    
4023
  def CheckArguments(self):
4024
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4025
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
4026
                self.op.master_capable, self.op.vm_capable,
4027
                self.op.secondary_ip]
4028
    if all_mods.count(None) == len(all_mods):
4029
      raise errors.OpPrereqError("Please pass at least one modification",
4030
                                 errors.ECODE_INVAL)
4031
    if all_mods.count(True) > 1:
4032
      raise errors.OpPrereqError("Can't set the node into more than one"
4033
                                 " state at the same time",
4034
                                 errors.ECODE_INVAL)
4035

    
4036
    # Boolean value that tells us whether we might be demoting from MC
4037
    self.might_demote = (self.op.master_candidate == False or
4038
                         self.op.offline == True or
4039
                         self.op.drained == True or
4040
                         self.op.master_capable == False)
4041

    
4042
    if self.op.secondary_ip:
4043
      if not netutils.IP4Address.IsValid(self.op.secondary_ip):
4044
        raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4045
                                   " address" % self.op.secondary_ip,
4046
                                   errors.ECODE_INVAL)
4047

    
4048
    self.lock_all = self.op.auto_promote and self.might_demote
4049
    self.lock_instances = self.op.secondary_ip is not None
4050

    
4051
  def ExpandNames(self):
4052
    if self.lock_all:
4053
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
4054
    else:
4055
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
4056

    
4057
    if self.lock_instances:
4058
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4059

    
4060
  def DeclareLocks(self, level):
4061
    # If we have locked all instances, before waiting to lock nodes, release
4062
    # all the ones living on nodes unrelated to the current operation.
4063
    if level == locking.LEVEL_NODE and self.lock_instances:
4064
      instances_release = []
4065
      instances_keep = []
4066
      self.affected_instances = []
4067
      if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4068
        for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
4069
          instance = self.context.cfg.GetInstanceInfo(instance_name)
4070
          i_mirrored = instance.disk_template in constants.DTS_NET_MIRROR
4071
          if i_mirrored and self.op.node_name in instance.all_nodes:
4072
            instances_keep.append(instance_name)
4073
            self.affected_instances.append(instance)
4074
          else:
4075
            instances_release.append(instance_name)
4076
        if instances_release:
4077
          self.context.glm.release(locking.LEVEL_INSTANCE, instances_release)
4078
          self.acquired_locks[locking.LEVEL_INSTANCE] = instances_keep
4079

    
4080
  def BuildHooksEnv(self):
4081
    """Build hooks env.
4082

4083
    This runs on the master node.
4084

4085
    """
4086
    env = {
4087
      "OP_TARGET": self.op.node_name,
4088
      "MASTER_CANDIDATE": str(self.op.master_candidate),
4089
      "OFFLINE": str(self.op.offline),
4090
      "DRAINED": str(self.op.drained),
4091
      "MASTER_CAPABLE": str(self.op.master_capable),
4092
      "VM_CAPABLE": str(self.op.vm_capable),
4093
      }
4094
    nl = [self.cfg.GetMasterNode(),
4095
          self.op.node_name]
4096
    return env, nl, nl
4097

    
4098
  def CheckPrereq(self):
4099
    """Check prerequisites.
4100

4101
    This only checks the instance list against the existing names.
4102

4103
    """
4104
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
4105

    
4106
    if (self.op.master_candidate is not None or
4107
        self.op.drained is not None or
4108
        self.op.offline is not None):
4109
      # we can't change the master's node flags
4110
      if self.op.node_name == self.cfg.GetMasterNode():
4111
        raise errors.OpPrereqError("The master role can be changed"
4112
                                   " only via master-failover",
4113
                                   errors.ECODE_INVAL)
4114

    
4115
    if self.op.master_candidate and not node.master_capable:
4116
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4117
                                 " it a master candidate" % node.name,
4118
                                 errors.ECODE_STATE)
4119

    
4120
    if self.op.vm_capable == False:
4121
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
4122
      if ipri or isec:
4123
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
4124
                                   " the vm_capable flag" % node.name,
4125
                                   errors.ECODE_STATE)
4126

    
4127
    if node.master_candidate and self.might_demote and not self.lock_all:
4128
      assert not self.op.auto_promote, "auto-promote set but lock_all not"
4129
      # check if after removing the current node, we're missing master
4130
      # candidates
4131
      (mc_remaining, mc_should, _) = \
4132
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
4133
      if mc_remaining < mc_should:
4134
        raise errors.OpPrereqError("Not enough master candidates, please"
4135
                                   " pass auto_promote to allow promotion",
4136
                                   errors.ECODE_STATE)
4137

    
4138
    self.old_flags = old_flags = (node.master_candidate,
4139
                                  node.drained, node.offline)
4140
    assert old_flags in self._F2R, "Un-handled old flags  %s" % str(old_flags)
4141
    self.old_role = old_role = self._F2R[old_flags]
4142

    
4143
    # Check for ineffective changes
4144
    for attr in self._FLAGS:
4145
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
4146
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
4147
        setattr(self.op, attr, None)
4148

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

    
4152
    # If we're being deofflined/drained, we'll MC ourself if needed
4153
    if (self.op.drained == False or self.op.offline == False or
4154
        (self.op.master_capable and not node.master_capable)):
4155
      if _DecideSelfPromotion(self):
4156
        self.op.master_candidate = True
4157
        self.LogInfo("Auto-promoting node to master candidate")
4158

    
4159
    # If we're no longer master capable, we'll demote ourselves from MC
4160
    if self.op.master_capable == False and node.master_candidate:
4161
      self.LogInfo("Demoting from master candidate")
4162
      self.op.master_candidate = False
4163

    
4164
    # Compute new role
4165
    assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
4166
    if self.op.master_candidate:
4167
      new_role = self._ROLE_CANDIDATE
4168
    elif self.op.drained:
4169
      new_role = self._ROLE_DRAINED
4170
    elif self.op.offline:
4171
      new_role = self._ROLE_OFFLINE
4172
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
4173
      # False is still in new flags, which means we're un-setting (the
4174
      # only) True flag
4175
      new_role = self._ROLE_REGULAR
4176
    else: # no new flags, nothing, keep old role
4177
      new_role = old_role
4178

    
4179
    self.new_role = new_role
4180

    
4181
    if old_role == self._ROLE_OFFLINE and new_role != old_role:
4182
      # Trying to transition out of offline status
4183
      result = self.rpc.call_version([node.name])[node.name]
4184
      if result.fail_msg:
4185
        raise errors.OpPrereqError("Node %s is being de-offlined but fails"
4186
                                   " to report its version: %s" %
4187
                                   (node.name, result.fail_msg),
4188
                                   errors.ECODE_STATE)
4189
      else:
4190
        self.LogWarning("Transitioning node from offline to online state"
4191
                        " without using re-add. Please make sure the node"
4192
                        " is healthy!")
4193

    
4194
    if self.op.secondary_ip:
4195
      # Ok even without locking, because this can't be changed by any LU
4196
      master = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
4197
      master_singlehomed = master.secondary_ip == master.primary_ip
4198
      if master_singlehomed and self.op.secondary_ip:
4199
        raise errors.OpPrereqError("Cannot change the secondary ip on a single"
4200
                                   " homed cluster", errors.ECODE_INVAL)
4201

    
4202
      if node.offline:
4203
        if self.affected_instances:
4204
          raise errors.OpPrereqError("Cannot change secondary ip: offline"
4205
                                     " node has instances (%s) configured"
4206
                                     " to use it" % self.affected_instances)
4207
      else:
4208
        # On online nodes, check that no instances are running, and that
4209
        # the node has the new ip and we can reach it.
4210
        for instance in self.affected_instances:
4211
          _CheckInstanceDown(self, instance, "cannot change secondary ip")
4212

    
4213
        _CheckNodeHasSecondaryIP(self, node.name, self.op.secondary_ip, True)
4214
        if master.name != node.name:
4215
          # check reachability from master secondary ip to new secondary ip
4216
          if not netutils.TcpPing(self.op.secondary_ip,
4217
                                  constants.DEFAULT_NODED_PORT,
4218
                                  source=master.secondary_ip):
4219
            raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4220
                                       " based ping to node daemon port",
4221
                                       errors.ECODE_ENVIRON)
4222

    
4223
  def Exec(self, feedback_fn):
4224
    """Modifies a node.
4225

4226
    """
4227
    node = self.node
4228
    old_role = self.old_role
4229
    new_role = self.new_role
4230

    
4231
    result = []
4232

    
4233
    for attr in ["master_capable", "vm_capable"]:
4234
      val = getattr(self.op, attr)
4235
      if val is not None:
4236
        setattr(node, attr, val)
4237
        result.append((attr, str(val)))
4238

    
4239
    if new_role != old_role:
4240
      # Tell the node to demote itself, if no longer MC and not offline
4241
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
4242
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
4243
        if msg:
4244
          self.LogWarning("Node failed to demote itself: %s", msg)
4245

    
4246
      new_flags = self._R2F[new_role]
4247
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
4248
        if of != nf:
4249
          result.append((desc, str(nf)))
4250
      (node.master_candidate, node.drained, node.offline) = new_flags
4251

    
4252
      # we locked all nodes, we adjust the CP before updating this node
4253
      if self.lock_all:
4254
        _AdjustCandidatePool(self, [node.name])
4255

    
4256
    if self.op.secondary_ip:
4257
      node.secondary_ip = self.op.secondary_ip
4258
      result.append(("secondary_ip", self.op.secondary_ip))
4259

    
4260
    # this will trigger configuration file update, if needed
4261
    self.cfg.Update(node, feedback_fn)
4262

    
4263
    # this will trigger job queue propagation or cleanup if the mc
4264
    # flag changed
4265
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
4266
      self.context.ReaddNode(node)
4267

    
4268
    return result
4269

    
4270

    
4271
class LUPowercycleNode(NoHooksLU):
4272
  """Powercycles a node.
4273

4274
  """
4275
  _OP_PARAMS = [
4276
    _PNodeName,
4277
    _PForce,
4278
    ]
4279
  REQ_BGL = False
4280

    
4281
  def CheckArguments(self):
4282
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4283
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4284
      raise errors.OpPrereqError("The node is the master and the force"
4285
                                 " parameter was not set",
4286
                                 errors.ECODE_INVAL)
4287

    
4288
  def ExpandNames(self):
4289
    """Locking for PowercycleNode.
4290

4291
    This is a last-resort option and shouldn't block on other
4292
    jobs. Therefore, we grab no locks.
4293

4294
    """
4295
    self.needed_locks = {}
4296

    
4297
  def Exec(self, feedback_fn):
4298
    """Reboots a node.
4299

4300
    """
4301
    result = self.rpc.call_node_powercycle(self.op.node_name,
4302
                                           self.cfg.GetHypervisorType())
4303
    result.Raise("Failed to schedule the reboot")
4304
    return result.payload
4305

    
4306

    
4307
class LUQueryClusterInfo(NoHooksLU):
4308
  """Query cluster configuration.
4309

4310
  """
4311
  REQ_BGL = False
4312

    
4313
  def ExpandNames(self):
4314
    self.needed_locks = {}
4315

    
4316
  def Exec(self, feedback_fn):
4317
    """Return cluster config.
4318

4319
    """
4320
    cluster = self.cfg.GetClusterInfo()
4321
    os_hvp = {}
4322

    
4323
    # Filter just for enabled hypervisors
4324
    for os_name, hv_dict in cluster.os_hvp.items():
4325
      os_hvp[os_name] = {}
4326
      for hv_name, hv_params in hv_dict.items():
4327
        if hv_name in cluster.enabled_hypervisors:
4328
          os_hvp[os_name][hv_name] = hv_params
4329

    
4330
    # Convert ip_family to ip_version
4331
    primary_ip_version = constants.IP4_VERSION
4332
    if cluster.primary_ip_family == netutils.IP6Address.family:
4333
      primary_ip_version = constants.IP6_VERSION
4334

    
4335
    result = {
4336
      "software_version": constants.RELEASE_VERSION,
4337
      "protocol_version": constants.PROTOCOL_VERSION,
4338
      "config_version": constants.CONFIG_VERSION,
4339
      "os_api_version": max(constants.OS_API_VERSIONS),
4340
      "export_version": constants.EXPORT_VERSION,
4341
      "architecture": (platform.architecture()[0], platform.machine()),
4342
      "name": cluster.cluster_name,
4343
      "master": cluster.master_node,
4344
      "default_hypervisor": cluster.enabled_hypervisors[0],
4345
      "enabled_hypervisors": cluster.enabled_hypervisors,
4346
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4347
                        for hypervisor_name in cluster.enabled_hypervisors]),
4348
      "os_hvp": os_hvp,
4349
      "beparams": cluster.beparams,
4350
      "osparams": cluster.osparams,
4351
      "nicparams": cluster.nicparams,
4352
      "candidate_pool_size": cluster.candidate_pool_size,
4353
      "master_netdev": cluster.master_netdev,
4354
      "volume_group_name": cluster.volume_group_name,
4355
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
4356
      "file_storage_dir": cluster.file_storage_dir,
4357
      "maintain_node_health": cluster.maintain_node_health,
4358
      "ctime": cluster.ctime,
4359
      "mtime": cluster.mtime,
4360
      "uuid": cluster.uuid,
4361
      "tags": list(cluster.GetTags()),
4362
      "uid_pool": cluster.uid_pool,
4363
      "default_iallocator": cluster.default_iallocator,
4364
      "reserved_lvs": cluster.reserved_lvs,
4365
      "primary_ip_version": primary_ip_version,
4366
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
4367
      }
4368

    
4369
    return result
4370

    
4371

    
4372
class LUQueryConfigValues(NoHooksLU):
4373
  """Return configuration values.
4374

4375
  """
4376
  _OP_PARAMS = [_POutputFields]
4377
  REQ_BGL = False
4378
  _FIELDS_DYNAMIC = utils.FieldSet()
4379
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4380
                                  "watcher_pause", "volume_group_name")
4381

    
4382
  def CheckArguments(self):
4383
    _CheckOutputFields(static=self._FIELDS_STATIC,
4384
                       dynamic=self._FIELDS_DYNAMIC,
4385
                       selected=self.op.output_fields)
4386

    
4387
  def ExpandNames(self):
4388
    self.needed_locks = {}
4389

    
4390
  def Exec(self, feedback_fn):
4391
    """Dump a representation of the cluster config to the standard output.
4392

4393
    """
4394
    values = []
4395
    for field in self.op.output_fields:
4396
      if field == "cluster_name":
4397
        entry = self.cfg.GetClusterName()
4398
      elif field == "master_node":
4399
        entry = self.cfg.GetMasterNode()
4400
      elif field == "drain_flag":
4401
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4402
      elif field == "watcher_pause":
4403
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4404
      elif field == "volume_group_name":
4405
        entry = self.cfg.GetVGName()
4406
      else:
4407
        raise errors.ParameterError(field)
4408
      values.append(entry)
4409
    return values
4410

    
4411

    
4412
class LUActivateInstanceDisks(NoHooksLU):
4413
  """Bring up an instance's disks.
4414

4415
  """
4416
  _OP_PARAMS = [
4417
    _PInstanceName,
4418
    ("ignore_size", False, ht.TBool),
4419
    ]
4420
  REQ_BGL = False
4421

    
4422
  def ExpandNames(self):
4423
    self._ExpandAndLockInstance()
4424
    self.needed_locks[locking.LEVEL_NODE] = []
4425
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4426

    
4427
  def DeclareLocks(self, level):
4428
    if level == locking.LEVEL_NODE:
4429
      self._LockInstancesNodes()
4430

    
4431
  def CheckPrereq(self):
4432
    """Check prerequisites.
4433

4434
    This checks that the instance is in the cluster.
4435

4436
    """
4437
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4438
    assert self.instance is not None, \
4439
      "Cannot retrieve locked instance %s" % self.op.instance_name
4440
    _CheckNodeOnline(self, self.instance.primary_node)
4441

    
4442
  def Exec(self, feedback_fn):
4443
    """Activate the disks.
4444

4445
    """
4446
    disks_ok, disks_info = \
4447
              _AssembleInstanceDisks(self, self.instance,
4448
                                     ignore_size=self.op.ignore_size)
4449
    if not disks_ok:
4450
      raise errors.OpExecError("Cannot activate block devices")
4451

    
4452
    return disks_info
4453

    
4454

    
4455
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4456
                           ignore_size=False):
4457
  """Prepare the block devices for an instance.
4458

4459
  This sets up the block devices on all nodes.
4460

4461
  @type lu: L{LogicalUnit}
4462
  @param lu: the logical unit on whose behalf we execute
4463
  @type instance: L{objects.Instance}
4464
  @param instance: the instance for whose disks we assemble
4465
  @type disks: list of L{objects.Disk} or None
4466
  @param disks: which disks to assemble (or all, if None)
4467
  @type ignore_secondaries: boolean
4468
  @param ignore_secondaries: if true, errors on secondary nodes
4469
      won't result in an error return from the function
4470
  @type ignore_size: boolean
4471
  @param ignore_size: if true, the current known size of the disk
4472
      will not be used during the disk activation, useful for cases
4473
      when the size is wrong
4474
  @return: False if the operation failed, otherwise a list of
4475
      (host, instance_visible_name, node_visible_name)
4476
      with the mapping from node devices to instance devices
4477

4478
  """
4479
  device_info = []
4480
  disks_ok = True
4481
  iname = instance.name
4482
  disks = _ExpandCheckDisks(instance, disks)
4483

    
4484
  # With the two passes mechanism we try to reduce the window of
4485
  # opportunity for the race condition of switching DRBD to primary
4486
  # before handshaking occured, but we do not eliminate it
4487

    
4488
  # The proper fix would be to wait (with some limits) until the
4489
  # connection has been made and drbd transitions from WFConnection
4490
  # into any other network-connected state (Connected, SyncTarget,
4491
  # SyncSource, etc.)
4492

    
4493
  # 1st pass, assemble on all nodes in secondary mode
4494
  for inst_disk in disks:
4495
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4496
      if ignore_size:
4497
        node_disk = node_disk.Copy()
4498
        node_disk.UnsetSize()
4499
      lu.cfg.SetDiskID(node_disk, node)
4500
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
4501
      msg = result.fail_msg
4502
      if msg:
4503
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4504
                           " (is_primary=False, pass=1): %s",
4505
                           inst_disk.iv_name, node, msg)
4506
        if not ignore_secondaries:
4507
          disks_ok = False
4508

    
4509
  # FIXME: race condition on drbd migration to primary
4510

    
4511
  # 2nd pass, do only the primary node
4512
  for inst_disk in disks:
4513
    dev_path = None
4514

    
4515
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4516
      if node != instance.primary_node:
4517
        continue
4518
      if ignore_size:
4519
        node_disk = node_disk.Copy()
4520
        node_disk.UnsetSize()
4521
      lu.cfg.SetDiskID(node_disk, node)
4522
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
4523
      msg = result.fail_msg
4524
      if msg:
4525
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4526
                           " (is_primary=True, pass=2): %s",
4527
                           inst_disk.iv_name, node, msg)
4528
        disks_ok = False
4529
      else:
4530
        dev_path = result.payload
4531

    
4532
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4533

    
4534
  # leave the disks configured for the primary node
4535
  # this is a workaround that would be fixed better by
4536
  # improving the logical/physical id handling
4537
  for disk in disks:
4538
    lu.cfg.SetDiskID(disk, instance.primary_node)
4539

    
4540
  return disks_ok, device_info
4541

    
4542

    
4543
def _StartInstanceDisks(lu, instance, force):
4544
  """Start the disks of an instance.
4545

4546
  """
4547
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4548
                                           ignore_secondaries=force)
4549
  if not disks_ok:
4550
    _ShutdownInstanceDisks(lu, instance)
4551
    if force is not None and not force:
4552
      lu.proc.LogWarning("", hint="If the message above refers to a"
4553
                         " secondary node,"
4554
                         " you can retry the operation using '--force'.")
4555
    raise errors.OpExecError("Disk consistency error")
4556

    
4557

    
4558
class LUDeactivateInstanceDisks(NoHooksLU):
4559
  """Shutdown an instance's disks.
4560

4561
  """
4562
  _OP_PARAMS = [
4563
    _PInstanceName,
4564
    ]
4565
  REQ_BGL = False
4566

    
4567
  def ExpandNames(self):
4568
    self._ExpandAndLockInstance()
4569
    self.needed_locks[locking.LEVEL_NODE] = []
4570
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4571

    
4572
  def DeclareLocks(self, level):
4573
    if level == locking.LEVEL_NODE:
4574
      self._LockInstancesNodes()
4575

    
4576
  def CheckPrereq(self):
4577
    """Check prerequisites.
4578

4579
    This checks that the instance is in the cluster.
4580

4581
    """
4582
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4583
    assert self.instance is not None, \
4584
      "Cannot retrieve locked instance %s" % self.op.instance_name
4585

    
4586
  def Exec(self, feedback_fn):
4587
    """Deactivate the disks
4588

4589
    """
4590
    instance = self.instance
4591
    _SafeShutdownInstanceDisks(self, instance)
4592

    
4593

    
4594
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4595
  """Shutdown block devices of an instance.
4596

4597
  This function checks if an instance is running, before calling
4598
  _ShutdownInstanceDisks.
4599

4600
  """
4601
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4602
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4603

    
4604

    
4605
def _ExpandCheckDisks(instance, disks):
4606
  """Return the instance disks selected by the disks list
4607

4608
  @type disks: list of L{objects.Disk} or None
4609
  @param disks: selected disks
4610
  @rtype: list of L{objects.Disk}
4611
  @return: selected instance disks to act on
4612

4613
  """
4614
  if disks is None:
4615
    return instance.disks
4616
  else:
4617
    if not set(disks).issubset(instance.disks):
4618
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4619
                                   " target instance")
4620
    return disks
4621

    
4622

    
4623
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4624
  """Shutdown block devices of an instance.
4625

4626
  This does the shutdown on all nodes of the instance.
4627

4628
  If the ignore_primary is false, errors on the primary node are
4629
  ignored.
4630

4631
  """
4632
  all_result = True
4633
  disks = _ExpandCheckDisks(instance, disks)
4634

    
4635
  for disk in disks:
4636
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4637
      lu.cfg.SetDiskID(top_disk, node)
4638
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4639
      msg = result.fail_msg
4640
      if msg:
4641
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4642
                      disk.iv_name, node, msg)
4643
        if not ignore_primary or node != instance.primary_node:
4644
          all_result = False
4645
  return all_result
4646

    
4647

    
4648
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4649
  """Checks if a node has enough free memory.
4650

4651
  This function check if a given node has the needed amount of free
4652
  memory. In case the node has less memory or we cannot get the
4653
  information from the node, this function raise an OpPrereqError
4654
  exception.
4655

4656
  @type lu: C{LogicalUnit}
4657
  @param lu: a logical unit from which we get configuration data
4658
  @type node: C{str}
4659
  @param node: the node to check
4660
  @type reason: C{str}
4661
  @param reason: string to use in the error message
4662
  @type requested: C{int}
4663
  @param requested: the amount of memory in MiB to check for
4664
  @type hypervisor_name: C{str}
4665
  @param hypervisor_name: the hypervisor to ask for memory stats
4666
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4667
      we cannot check the node
4668

4669
  """
4670
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
4671
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4672
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4673
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4674
  if not isinstance(free_mem, int):
4675
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4676
                               " was '%s'" % (node, free_mem),
4677
                               errors.ECODE_ENVIRON)
4678
  if requested > free_mem:
4679
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
4680
                               " needed %s MiB, available %s MiB" %
4681
                               (node, reason, requested, free_mem),
4682
                               errors.ECODE_NORES)
4683

    
4684

    
4685
def _CheckNodesFreeDisk(lu, nodenames, requested):
4686
  """Checks if nodes have enough free disk space in the default VG.
4687

4688
  This function check if all given nodes have the needed amount of
4689
  free disk. In case any node has less disk or we cannot get the
4690
  information from the node, this function raise an OpPrereqError
4691
  exception.
4692

4693
  @type lu: C{LogicalUnit}
4694
  @param lu: a logical unit from which we get configuration data
4695
  @type nodenames: C{list}
4696
  @param nodenames: the list of node names to check
4697
  @type requested: C{int}
4698
  @param requested: the amount of disk in MiB to check for
4699
  @raise errors.OpPrereqError: if the node doesn't have enough disk, or
4700
      we cannot check the node
4701

4702
  """
4703
  nodeinfo = lu.rpc.call_node_info(nodenames, lu.cfg.GetVGName(),
4704
                                   lu.cfg.GetHypervisorType())
4705
  for node in nodenames:
4706
    info = nodeinfo[node]
4707
    info.Raise("Cannot get current information from node %s" % node,
4708
               prereq=True, ecode=errors.ECODE_ENVIRON)
4709
    vg_free = info.payload.get("vg_free", None)
4710
    if not isinstance(vg_free, int):
4711
      raise errors.OpPrereqError("Can't compute free disk space on node %s,"
4712
                                 " result was '%s'" % (node, vg_free),
4713
                                 errors.ECODE_ENVIRON)
4714
    if requested > vg_free:
4715
      raise errors.OpPrereqError("Not enough disk space on target node %s:"
4716
                                 " required %d MiB, available %d MiB" %
4717
                                 (node, requested, vg_free),
4718
                                 errors.ECODE_NORES)
4719

    
4720

    
4721
class LUStartupInstance(LogicalUnit):
4722
  """Starts an instance.
4723

4724
  """
4725
  HPATH = "instance-start"
4726
  HTYPE = constants.HTYPE_INSTANCE
4727
  _OP_PARAMS = [
4728
    _PInstanceName,
4729
    _PForce,
4730
    _PIgnoreOfflineNodes,
4731
    ("hvparams", ht.EmptyDict, ht.TDict),
4732
    ("beparams", ht.EmptyDict, ht.TDict),
4733
    ]
4734
  REQ_BGL = False
4735

    
4736
  def CheckArguments(self):
4737
    # extra beparams
4738
    if self.op.beparams:
4739
      # fill the beparams dict
4740
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
4741

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

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

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

4750
    """
4751
    env = {
4752
      "FORCE": self.op.force,
4753
      }
4754
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4755
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4756
    return env, nl, nl
4757

    
4758
  def CheckPrereq(self):
4759
    """Check prerequisites.
4760

4761
    This checks that the instance is in the cluster.
4762

4763
    """
4764
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4765
    assert self.instance is not None, \
4766
      "Cannot retrieve locked instance %s" % self.op.instance_name
4767

    
4768
    # extra hvparams
4769
    if self.op.hvparams:
4770
      # check hypervisor parameter syntax (locally)
4771
      cluster = self.cfg.GetClusterInfo()
4772
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
4773
      filled_hvp = cluster.FillHV(instance)
4774
      filled_hvp.update(self.op.hvparams)
4775
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
4776
      hv_type.CheckParameterSyntax(filled_hvp)
4777
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
4778

    
4779
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
4780

    
4781
    if self.primary_offline and self.op.ignore_offline_nodes:
4782
      self.proc.LogWarning("Ignoring offline primary node")
4783

    
4784
      if self.op.hvparams or self.op.beparams:
4785
        self.proc.LogWarning("Overridden parameters are ignored")
4786
    else:
4787
      _CheckNodeOnline(self, instance.primary_node)
4788

    
4789
      bep = self.cfg.GetClusterInfo().FillBE(instance)
4790

    
4791
      # check bridges existence
4792
      _CheckInstanceBridgesExist(self, instance)
4793

    
4794
      remote_info = self.rpc.call_instance_info(instance.primary_node,
4795
                                                instance.name,
4796
                                                instance.hypervisor)
4797
      remote_info.Raise("Error checking node %s" % instance.primary_node,
4798
                        prereq=True, ecode=errors.ECODE_ENVIRON)
4799
      if not remote_info.payload: # not running already
4800
        _CheckNodeFreeMemory(self, instance.primary_node,
4801
                             "starting instance %s" % instance.name,
4802
                             bep[constants.BE_MEMORY], instance.hypervisor)
4803

    
4804
  def Exec(self, feedback_fn):
4805
    """Start the instance.
4806

4807
    """
4808
    instance = self.instance
4809
    force = self.op.force
4810

    
4811
    self.cfg.MarkInstanceUp(instance.name)
4812

    
4813
    if self.primary_offline:
4814
      assert self.op.ignore_offline_nodes
4815
      self.proc.LogInfo("Primary node offline, marked instance as started")
4816
    else:
4817
      node_current = instance.primary_node
4818

    
4819
      _StartInstanceDisks(self, instance, force)
4820

    
4821
      result = self.rpc.call_instance_start(node_current, instance,
4822
                                            self.op.hvparams, self.op.beparams)
4823
      msg = result.fail_msg
4824
      if msg:
4825
        _ShutdownInstanceDisks(self, instance)
4826
        raise errors.OpExecError("Could not start instance: %s" % msg)
4827

    
4828

    
4829
class LURebootInstance(LogicalUnit):
4830
  """Reboot an instance.
4831

4832
  """
4833
  HPATH = "instance-reboot"
4834
  HTYPE = constants.HTYPE_INSTANCE
4835
  _OP_PARAMS = [
4836
    _PInstanceName,
4837
    ("ignore_secondaries", False, ht.TBool),
4838
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES)),
4839
    _PShutdownTimeout,
4840
    ]
4841
  REQ_BGL = False
4842

    
4843
  def ExpandNames(self):
4844
    self._ExpandAndLockInstance()
4845

    
4846
  def BuildHooksEnv(self):
4847
    """Build hooks env.
4848

4849
    This runs on master, primary and secondary nodes of the instance.
4850

4851
    """
4852
    env = {
4853
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
4854
      "REBOOT_TYPE": self.op.reboot_type,
4855
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
4856
      }
4857
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4858
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4859
    return env, nl, nl
4860

    
4861
  def CheckPrereq(self):
4862
    """Check prerequisites.
4863

4864
    This checks that the instance is in the cluster.
4865

4866
    """
4867
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4868
    assert self.instance is not None, \
4869
      "Cannot retrieve locked instance %s" % self.op.instance_name
4870

    
4871
    _CheckNodeOnline(self, instance.primary_node)
4872

    
4873
    # check bridges existence
4874
    _CheckInstanceBridgesExist(self, instance)
4875

    
4876
  def Exec(self, feedback_fn):
4877
    """Reboot the instance.
4878

4879
    """
4880
    instance = self.instance
4881
    ignore_secondaries = self.op.ignore_secondaries
4882
    reboot_type = self.op.reboot_type
4883

    
4884
    node_current = instance.primary_node
4885

    
4886
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
4887
                       constants.INSTANCE_REBOOT_HARD]:
4888
      for disk in instance.disks:
4889
        self.cfg.SetDiskID(disk, node_current)
4890
      result = self.rpc.call_instance_reboot(node_current, instance,
4891
                                             reboot_type,
4892
                                             self.op.shutdown_timeout)
4893
      result.Raise("Could not reboot instance")
4894
    else:
4895
      result = self.rpc.call_instance_shutdown(node_current, instance,
4896
                                               self.op.shutdown_timeout)
4897
      result.Raise("Could not shutdown instance for full reboot")
4898
      _ShutdownInstanceDisks(self, instance)
4899
      _StartInstanceDisks(self, instance, ignore_secondaries)
4900
      result = self.rpc.call_instance_start(node_current, instance, None, None)
4901
      msg = result.fail_msg
4902
      if msg:
4903
        _ShutdownInstanceDisks(self, instance)
4904
        raise errors.OpExecError("Could not start instance for"
4905
                                 " full reboot: %s" % msg)
4906

    
4907
    self.cfg.MarkInstanceUp(instance.name)
4908

    
4909

    
4910
class LUShutdownInstance(LogicalUnit):
4911
  """Shutdown an instance.
4912

4913
  """
4914
  HPATH = "instance-stop"
4915
  HTYPE = constants.HTYPE_INSTANCE
4916
  _OP_PARAMS = [
4917
    _PInstanceName,
4918
    _PIgnoreOfflineNodes,
4919
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt),
4920
    ]
4921
  REQ_BGL = False
4922

    
4923
  def ExpandNames(self):
4924
    self._ExpandAndLockInstance()
4925

    
4926
  def BuildHooksEnv(self):
4927
    """Build hooks env.
4928

4929
    This runs on master, primary and secondary nodes of the instance.
4930

4931
    """
4932
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4933
    env["TIMEOUT"] = self.op.timeout
4934
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4935
    return env, nl, nl
4936

    
4937
  def CheckPrereq(self):
4938
    """Check prerequisites.
4939

4940
    This checks that the instance is in the cluster.
4941

4942
    """
4943
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4944
    assert self.instance is not None, \
4945
      "Cannot retrieve locked instance %s" % self.op.instance_name
4946

    
4947
    self.primary_offline = \
4948
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
4949

    
4950
    if self.primary_offline and self.op.ignore_offline_nodes:
4951
      self.proc.LogWarning("Ignoring offline primary node")
4952
    else:
4953
      _CheckNodeOnline(self, self.instance.primary_node)
4954

    
4955
  def Exec(self, feedback_fn):
4956
    """Shutdown the instance.
4957

4958
    """
4959
    instance = self.instance
4960
    node_current = instance.primary_node
4961
    timeout = self.op.timeout
4962

    
4963
    self.cfg.MarkInstanceDown(instance.name)
4964

    
4965
    if self.primary_offline:
4966
      assert self.op.ignore_offline_nodes
4967
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
4968
    else:
4969
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
4970
      msg = result.fail_msg
4971
      if msg:
4972
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
4973

    
4974
      _ShutdownInstanceDisks(self, instance)
4975

    
4976

    
4977
class LUReinstallInstance(LogicalUnit):
4978
  """Reinstall an instance.
4979

4980
  """
4981
  HPATH = "instance-reinstall"
4982
  HTYPE = constants.HTYPE_INSTANCE
4983
  _OP_PARAMS = [
4984
    _PInstanceName,
4985
    ("os_type", None, ht.TMaybeString),
4986
    ("force_variant", False, ht.TBool),
4987
    ("osparams", None, ht.TOr(ht.TDict, ht.TNone)),
4988
    ]
4989
  REQ_BGL = False
4990

    
4991
  def ExpandNames(self):
4992
    self._ExpandAndLockInstance()
4993

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

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

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

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

5007
    This checks that the instance is in the cluster and is not running.
5008

5009
    """
5010
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5011
    assert instance is not None, \
5012
      "Cannot retrieve locked instance %s" % self.op.instance_name
5013
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
5014
                     " offline, cannot reinstall")
5015
    for node in instance.secondary_nodes:
5016
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
5017
                       " cannot reinstall")
5018

    
5019
    if instance.disk_template == constants.DT_DISKLESS:
5020
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5021
                                 self.op.instance_name,
5022
                                 errors.ECODE_INVAL)
5023
    _CheckInstanceDown(self, instance, "cannot reinstall")
5024

    
5025
    if self.op.os_type is not None:
5026
      # OS verification
5027
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
5028
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
5029
      instance_os = self.op.os_type
5030
    else:
5031
      instance_os = instance.os
5032

    
5033
    nodelist = list(instance.all_nodes)
5034

    
5035
    if self.op.osparams:
5036
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
5037
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
5038
      self.os_inst = i_osdict # the new dict (without defaults)
5039
    else:
5040
      self.os_inst = None
5041

    
5042
    self.instance = instance
5043

    
5044
  def Exec(self, feedback_fn):
5045
    """Reinstall the instance.
5046

5047
    """
5048
    inst = self.instance
5049

    
5050
    if self.op.os_type is not None:
5051
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
5052
      inst.os = self.op.os_type
5053
      # Write to configuration
5054
      self.cfg.Update(inst, feedback_fn)
5055

    
5056
    _StartInstanceDisks(self, inst, None)
5057
    try:
5058
      feedback_fn("Running the instance OS create scripts...")
5059
      # FIXME: pass debug option from opcode to backend
5060
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
5061
                                             self.op.debug_level,
5062
                                             osparams=self.os_inst)
5063
      result.Raise("Could not install OS for instance %s on node %s" %
5064
                   (inst.name, inst.primary_node))
5065
    finally:
5066
      _ShutdownInstanceDisks(self, inst)
5067

    
5068

    
5069
class LURecreateInstanceDisks(LogicalUnit):
5070
  """Recreate an instance's missing disks.
5071

5072
  """
5073
  HPATH = "instance-recreate-disks"
5074
  HTYPE = constants.HTYPE_INSTANCE
5075
  _OP_PARAMS = [
5076
    _PInstanceName,
5077
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt)),
5078
    ]
5079
  REQ_BGL = False
5080

    
5081
  def ExpandNames(self):
5082
    self._ExpandAndLockInstance()
5083

    
5084
  def BuildHooksEnv(self):
5085
    """Build hooks env.
5086

5087
    This runs on master, primary and secondary nodes of the instance.
5088

5089
    """
5090
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5091
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5092
    return env, nl, nl
5093

    
5094
  def CheckPrereq(self):
5095
    """Check prerequisites.
5096

5097
    This checks that the instance is in the cluster and is not running.
5098

5099
    """
5100
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5101
    assert instance is not None, \
5102
      "Cannot retrieve locked instance %s" % self.op.instance_name
5103
    _CheckNodeOnline(self, instance.primary_node)
5104

    
5105
    if instance.disk_template == constants.DT_DISKLESS:
5106
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5107
                                 self.op.instance_name, errors.ECODE_INVAL)
5108
    _CheckInstanceDown(self, instance, "cannot recreate disks")
5109

    
5110
    if not self.op.disks:
5111
      self.op.disks = range(len(instance.disks))
5112
    else:
5113
      for idx in self.op.disks:
5114
        if idx >= len(instance.disks):
5115
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
5116
                                     errors.ECODE_INVAL)
5117

    
5118
    self.instance = instance
5119

    
5120
  def Exec(self, feedback_fn):
5121
    """Recreate the disks.
5122

5123
    """
5124
    to_skip = []
5125
    for idx, _ in enumerate(self.instance.disks):
5126
      if idx not in self.op.disks: # disk idx has not been passed in
5127
        to_skip.append(idx)
5128
        continue
5129

    
5130
    _CreateDisks(self, self.instance, to_skip=to_skip)
5131

    
5132

    
5133
class LURenameInstance(LogicalUnit):
5134
  """Rename an instance.
5135

5136
  """
5137
  HPATH = "instance-rename"
5138
  HTYPE = constants.HTYPE_INSTANCE
5139
  _OP_PARAMS = [
5140
    _PInstanceName,
5141
    ("new_name", ht.NoDefault, ht.TNonEmptyString),
5142
    ("ip_check", False, ht.TBool),
5143
    ("name_check", True, ht.TBool),
5144
    ]
5145

    
5146
  def CheckArguments(self):
5147
    """Check arguments.
5148

5149
    """
5150
    if self.op.ip_check and not self.op.name_check:
5151
      # TODO: make the ip check more flexible and not depend on the name check
5152
      raise errors.OpPrereqError("Cannot do ip check without a name check",
5153
                                 errors.ECODE_INVAL)
5154

    
5155
  def BuildHooksEnv(self):
5156
    """Build hooks env.
5157

5158
    This runs on master, primary and secondary nodes of the instance.
5159

5160
    """
5161
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5162
    env["INSTANCE_NEW_NAME"] = self.op.new_name
5163
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5164
    return env, nl, nl
5165

    
5166
  def CheckPrereq(self):
5167
    """Check prerequisites.
5168

5169
    This checks that the instance is in the cluster and is not running.
5170

5171
    """
5172
    self.op.instance_name = _ExpandInstanceName(self.cfg,
5173
                                                self.op.instance_name)
5174
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5175
    assert instance is not None
5176
    _CheckNodeOnline(self, instance.primary_node)
5177
    _CheckInstanceDown(self, instance, "cannot rename")
5178
    self.instance = instance
5179

    
5180
    new_name = self.op.new_name
5181
    if self.op.name_check:
5182
      hostname = netutils.GetHostname(name=new_name)
5183
      new_name = self.op.new_name = hostname.name
5184
      if (self.op.ip_check and
5185
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
5186
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
5187
                                   (hostname.ip, new_name),
5188
                                   errors.ECODE_NOTUNIQUE)
5189

    
5190
    instance_list = self.cfg.GetInstanceList()
5191
    if new_name in instance_list:
5192
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5193
                                 new_name, errors.ECODE_EXISTS)
5194

    
5195
  def Exec(self, feedback_fn):
5196
    """Reinstall the instance.
5197

5198
    """
5199
    inst = self.instance
5200
    old_name = inst.name
5201

    
5202
    if inst.disk_template == constants.DT_FILE:
5203
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5204

    
5205
    self.cfg.RenameInstance(inst.name, self.op.new_name)
5206
    # Change the instance lock. This is definitely safe while we hold the BGL
5207
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
5208
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
5209

    
5210
    # re-read the instance from the configuration after rename
5211
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
5212

    
5213
    if inst.disk_template == constants.DT_FILE:
5214
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5215
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
5216
                                                     old_file_storage_dir,
5217
                                                     new_file_storage_dir)
5218
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
5219
                   " (but the instance has been renamed in Ganeti)" %
5220
                   (inst.primary_node, old_file_storage_dir,
5221
                    new_file_storage_dir))
5222

    
5223
    _StartInstanceDisks(self, inst, None)
5224
    try:
5225
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
5226
                                                 old_name, self.op.debug_level)
5227
      msg = result.fail_msg
5228
      if msg:
5229
        msg = ("Could not run OS rename script for instance %s on node %s"
5230
               " (but the instance has been renamed in Ganeti): %s" %
5231
               (inst.name, inst.primary_node, msg))
5232
        self.proc.LogWarning(msg)
5233
    finally:
5234
      _ShutdownInstanceDisks(self, inst)
5235

    
5236
    return inst.name
5237

    
5238

    
5239
class LURemoveInstance(LogicalUnit):
5240
  """Remove an instance.
5241

5242
  """
5243
  HPATH = "instance-remove"
5244
  HTYPE = constants.HTYPE_INSTANCE
5245
  _OP_PARAMS = [
5246
    _PInstanceName,
5247
    ("ignore_failures", False, ht.TBool),
5248
    _PShutdownTimeout,
5249
    ]
5250
  REQ_BGL = False
5251

    
5252
  def ExpandNames(self):
5253
    self._ExpandAndLockInstance()
5254
    self.needed_locks[locking.LEVEL_NODE] = []
5255
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5256

    
5257
  def DeclareLocks(self, level):
5258
    if level == locking.LEVEL_NODE:
5259
      self._LockInstancesNodes()
5260

    
5261
  def BuildHooksEnv(self):
5262
    """Build hooks env.
5263

5264
    This runs on master, primary and secondary nodes of the instance.
5265

5266
    """
5267
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5268
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
5269
    nl = [self.cfg.GetMasterNode()]
5270
    nl_post = list(self.instance.all_nodes) + nl
5271
    return env, nl, nl_post
5272

    
5273
  def CheckPrereq(self):
5274
    """Check prerequisites.
5275

5276
    This checks that the instance is in the cluster.
5277

5278
    """
5279
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5280
    assert self.instance is not None, \
5281
      "Cannot retrieve locked instance %s" % self.op.instance_name
5282

    
5283
  def Exec(self, feedback_fn):
5284
    """Remove the instance.
5285

5286
    """
5287
    instance = self.instance
5288
    logging.info("Shutting down instance %s on node %s",
5289
                 instance.name, instance.primary_node)
5290

    
5291
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5292
                                             self.op.shutdown_timeout)
5293
    msg = result.fail_msg
5294
    if msg:
5295
      if self.op.ignore_failures:
5296
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5297
      else:
5298
        raise errors.OpExecError("Could not shutdown instance %s on"
5299
                                 " node %s: %s" %
5300
                                 (instance.name, instance.primary_node, msg))
5301

    
5302
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5303

    
5304

    
5305
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5306
  """Utility function to remove an instance.
5307

5308
  """
5309
  logging.info("Removing block devices for instance %s", instance.name)
5310

    
5311
  if not _RemoveDisks(lu, instance):
5312
    if not ignore_failures:
5313
      raise errors.OpExecError("Can't remove instance's disks")
5314
    feedback_fn("Warning: can't remove instance's disks")
5315

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

    
5318
  lu.cfg.RemoveInstance(instance.name)
5319

    
5320
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5321
    "Instance lock removal conflict"
5322

    
5323
  # Remove lock for the instance
5324
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5325

    
5326

    
5327
class LUQueryInstances(NoHooksLU):
5328
  """Logical unit for querying instances.
5329

5330
  """
5331
  # pylint: disable-msg=W0142
5332
  _OP_PARAMS = [
5333
    _POutputFields,
5334
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
5335
    ("use_locking", False, ht.TBool),
5336
    ]
5337
  REQ_BGL = False
5338
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
5339
                    "serial_no", "ctime", "mtime", "uuid"]
5340
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
5341
                                    "admin_state",
5342
                                    "disk_template", "ip", "mac", "bridge",
5343
                                    "nic_mode", "nic_link",
5344
                                    "sda_size", "sdb_size", "vcpus", "tags",
5345
                                    "network_port", "beparams",
5346
                                    r"(disk)\.(size)/([0-9]+)",
5347
                                    r"(disk)\.(sizes)", "disk_usage",
5348
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
5349
                                    r"(nic)\.(bridge)/([0-9]+)",
5350
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
5351
                                    r"(disk|nic)\.(count)",
5352
                                    "hvparams", "custom_hvparams",
5353
                                    "custom_beparams", "custom_nicparams",
5354
                                    ] + _SIMPLE_FIELDS +
5355
                                  ["hv/%s" % name
5356
                                   for name in constants.HVS_PARAMETERS
5357
                                   if name not in constants.HVC_GLOBALS] +
5358
                                  ["be/%s" % name
5359
                                   for name in constants.BES_PARAMETERS])
5360
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state",
5361
                                   "oper_ram",
5362
                                   "oper_vcpus",
5363
                                   "status")
5364

    
5365

    
5366
  def CheckArguments(self):
5367
    _CheckOutputFields(static=self._FIELDS_STATIC,
5368
                       dynamic=self._FIELDS_DYNAMIC,
5369
                       selected=self.op.output_fields)
5370

    
5371
  def ExpandNames(self):
5372
    self.needed_locks = {}
5373
    self.share_locks[locking.LEVEL_INSTANCE] = 1
5374
    self.share_locks[locking.LEVEL_NODE] = 1
5375

    
5376
    if self.op.names:
5377
      self.wanted = _GetWantedInstances(self, self.op.names)
5378
    else:
5379
      self.wanted = locking.ALL_SET
5380

    
5381
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
5382
    self.do_locking = self.do_node_query and self.op.use_locking
5383
    if self.do_locking:
5384
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
5385
      self.needed_locks[locking.LEVEL_NODE] = []
5386
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5387

    
5388
  def DeclareLocks(self, level):
5389
    if level == locking.LEVEL_NODE and self.do_locking:
5390
      self._LockInstancesNodes()
5391

    
5392
  def Exec(self, feedback_fn):
5393
    """Computes the list of nodes and their attributes.
5394

5395
    """
5396
    # pylint: disable-msg=R0912
5397
    # way too many branches here
5398
    all_info = self.cfg.GetAllInstancesInfo()
5399
    if self.wanted == locking.ALL_SET:
5400
      # caller didn't specify instance names, so ordering is not important
5401
      if self.do_locking:
5402
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5403
      else:
5404
        instance_names = all_info.keys()
5405
      instance_names = utils.NiceSort(instance_names)
5406
    else:
5407
      # caller did specify names, so we must keep the ordering
5408
      if self.do_locking:
5409
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
5410
      else:
5411
        tgt_set = all_info.keys()
5412
      missing = set(self.wanted).difference(tgt_set)
5413
      if missing:
5414
        raise errors.OpExecError("Some instances were removed before"
5415
                                 " retrieving their data: %s" % missing)
5416
      instance_names = self.wanted
5417

    
5418
    instance_list = [all_info[iname] for iname in instance_names]
5419

    
5420
    # begin data gathering
5421

    
5422
    nodes = frozenset([inst.primary_node for inst in instance_list])
5423
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
5424

    
5425
    bad_nodes = []
5426
    off_nodes = []
5427
    if self.do_node_query:
5428
      live_data = {}
5429
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
5430
      for name in nodes:
5431
        result = node_data[name]
5432
        if result.offline:
5433
          # offline nodes will be in both lists
5434
          off_nodes.append(name)
5435
        if result.fail_msg:
5436
          bad_nodes.append(name)
5437
        else:
5438
          if result.payload:
5439
            live_data.update(result.payload)
5440
          # else no instance is alive
5441
    else:
5442
      live_data = dict([(name, {}) for name in instance_names])
5443

    
5444
    # end data gathering
5445

    
5446
    HVPREFIX = "hv/"
5447
    BEPREFIX = "be/"
5448
    output = []
5449
    cluster = self.cfg.GetClusterInfo()
5450
    for instance in instance_list:
5451
      iout = []
5452
      i_hv = cluster.FillHV(instance, skip_globals=True)
5453
      i_be = cluster.FillBE(instance)
5454
      i_nicp = [cluster.SimpleFillNIC(nic.nicparams) for nic in instance.nics]
5455
      for field in self.op.output_fields:
5456
        st_match = self._FIELDS_STATIC.Matches(field)
5457
        if field in self._SIMPLE_FIELDS:
5458
          val = getattr(instance, field)
5459
        elif field == "pnode":
5460
          val = instance.primary_node
5461
        elif field == "snodes":
5462
          val = list(instance.secondary_nodes)
5463
        elif field == "admin_state":
5464
          val = instance.admin_up
5465
        elif field == "oper_state":
5466
          if instance.primary_node in bad_nodes:
5467
            val = None
5468
          else:
5469
            val = bool(live_data.get(instance.name))
5470
        elif field == "status":
5471
          if instance.primary_node in off_nodes:
5472
            val = "ERROR_nodeoffline"
5473
          elif instance.primary_node in bad_nodes:
5474
            val = "ERROR_nodedown"
5475
          else:
5476
            running = bool(live_data.get(instance.name))
5477
            if running:
5478
              if instance.admin_up:
5479
                val = "running"
5480
              else:
5481
                val = "ERROR_up"
5482
            else:
5483
              if instance.admin_up:
5484
                val = "ERROR_down"
5485
              else:
5486
                val = "ADMIN_down"
5487
        elif field == "oper_ram":
5488
          if instance.primary_node in bad_nodes:
5489
            val = None
5490
          elif instance.name in live_data:
5491
            val = live_data[instance.name].get("memory", "?")
5492
          else:
5493
            val = "-"
5494
        elif field == "oper_vcpus":
5495
          if instance.primary_node in bad_nodes:
5496
            val = None
5497
          elif instance.name in live_data:
5498
            val = live_data[instance.name].get("vcpus", "?")
5499
          else:
5500
            val = "-"
5501
        elif field == "vcpus":
5502
          val = i_be[constants.BE_VCPUS]
5503
        elif field == "disk_template":
5504
          val = instance.disk_template
5505
        elif field == "ip":
5506
          if instance.nics:
5507
            val = instance.nics[0].ip
5508
          else:
5509
            val = None
5510
        elif field == "nic_mode":
5511
          if instance.nics:
5512
            val = i_nicp[0][constants.NIC_MODE]
5513
          else:
5514
            val = None
5515
        elif field == "nic_link":
5516
          if instance.nics:
5517
            val = i_nicp[0][constants.NIC_LINK]
5518
          else:
5519
            val = None
5520
        elif field == "bridge":
5521
          if (instance.nics and
5522
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
5523
            val = i_nicp[0][constants.NIC_LINK]
5524
          else:
5525
            val = None
5526
        elif field == "mac":
5527
          if instance.nics:
5528
            val = instance.nics[0].mac
5529
          else:
5530
            val = None
5531
        elif field == "custom_nicparams":
5532
          val = [nic.nicparams for nic in instance.nics]
5533
        elif field == "sda_size" or field == "sdb_size":
5534
          idx = ord(field[2]) - ord('a')
5535
          try:
5536
            val = instance.FindDisk(idx).size
5537
          except errors.OpPrereqError:
5538
            val = None
5539
        elif field == "disk_usage": # total disk usage per node
5540
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
5541
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
5542
        elif field == "tags":
5543
          val = list(instance.GetTags())
5544
        elif field == "custom_hvparams":
5545
          val = instance.hvparams # not filled!
5546
        elif field == "hvparams":
5547
          val = i_hv
5548
        elif (field.startswith(HVPREFIX) and
5549
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS and
5550
              field[len(HVPREFIX):] not in constants.HVC_GLOBALS):
5551
          val = i_hv.get(field[len(HVPREFIX):], None)
5552
        elif field == "custom_beparams":
5553
          val = instance.beparams
5554
        elif field == "beparams":
5555
          val = i_be
5556
        elif (field.startswith(BEPREFIX) and
5557
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
5558
          val = i_be.get(field[len(BEPREFIX):], None)
5559
        elif st_match and st_match.groups():
5560
          # matches a variable list
5561
          st_groups = st_match.groups()
5562
          if st_groups and st_groups[0] == "disk":
5563
            if st_groups[1] == "count":
5564
              val = len(instance.disks)
5565
            elif st_groups[1] == "sizes":
5566
              val = [disk.size for disk in instance.disks]
5567
            elif st_groups[1] == "size":
5568
              try:
5569
                val = instance.FindDisk(st_groups[2]).size
5570
              except errors.OpPrereqError:
5571
                val = None
5572
            else:
5573
              assert False, "Unhandled disk parameter"
5574
          elif st_groups[0] == "nic":
5575
            if st_groups[1] == "count":
5576
              val = len(instance.nics)
5577
            elif st_groups[1] == "macs":
5578
              val = [nic.mac for nic in instance.nics]
5579
            elif st_groups[1] == "ips":
5580
              val = [nic.ip for nic in instance.nics]
5581
            elif st_groups[1] == "modes":
5582
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
5583
            elif st_groups[1] == "links":
5584
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
5585
            elif st_groups[1] == "bridges":
5586
              val = []
5587
              for nicp in i_nicp:
5588
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
5589
                  val.append(nicp[constants.NIC_LINK])
5590
                else:
5591
                  val.append(None)
5592
            else:
5593
              # index-based item
5594
              nic_idx = int(st_groups[2])
5595
              if nic_idx >= len(instance.nics):
5596
                val = None
5597
              else:
5598
                if st_groups[1] == "mac":
5599
                  val = instance.nics[nic_idx].mac
5600
                elif st_groups[1] == "ip":
5601
                  val = instance.nics[nic_idx].ip
5602
                elif st_groups[1] == "mode":
5603
                  val = i_nicp[nic_idx][constants.NIC_MODE]
5604
                elif st_groups[1] == "link":
5605
                  val = i_nicp[nic_idx][constants.NIC_LINK]
5606
                elif st_groups[1] == "bridge":
5607
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
5608
                  if nic_mode == constants.NIC_MODE_BRIDGED:
5609
                    val = i_nicp[nic_idx][constants.NIC_LINK]
5610
                  else:
5611
                    val = None
5612
                else:
5613
                  assert False, "Unhandled NIC parameter"
5614
          else:
5615
            assert False, ("Declared but unhandled variable parameter '%s'" %
5616
                           field)
5617
        else:
5618
          assert False, "Declared but unhandled parameter '%s'" % field
5619
        iout.append(val)
5620
      output.append(iout)
5621

    
5622
    return output
5623

    
5624

    
5625
class LUFailoverInstance(LogicalUnit):
5626
  """Failover an instance.
5627

5628
  """
5629
  HPATH = "instance-failover"
5630
  HTYPE = constants.HTYPE_INSTANCE
5631
  _OP_PARAMS = [
5632
    _PInstanceName,
5633
    ("ignore_consistency", False, ht.TBool),
5634
    _PShutdownTimeout,
5635
    ]
5636
  REQ_BGL = False
5637

    
5638
  def ExpandNames(self):
5639
    self._ExpandAndLockInstance()
5640
    self.needed_locks[locking.LEVEL_NODE] = []
5641
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5642

    
5643
  def DeclareLocks(self, level):
5644
    if level == locking.LEVEL_NODE:
5645
      self._LockInstancesNodes()
5646

    
5647
  def BuildHooksEnv(self):
5648
    """Build hooks env.
5649

5650
    This runs on master, primary and secondary nodes of the instance.
5651

5652
    """
5653
    instance = self.instance
5654
    source_node = instance.primary_node
5655
    target_node = instance.secondary_nodes[0]
5656
    env = {
5657
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5658
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5659
      "OLD_PRIMARY": source_node,
5660
      "OLD_SECONDARY": target_node,
5661
      "NEW_PRIMARY": target_node,
5662
      "NEW_SECONDARY": source_node,
5663
      }
5664
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5665
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5666
    nl_post = list(nl)
5667
    nl_post.append(source_node)
5668
    return env, nl, nl_post
5669

    
5670
  def CheckPrereq(self):
5671
    """Check prerequisites.
5672

5673
    This checks that the instance is in the cluster.
5674

5675
    """
5676
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5677
    assert self.instance is not None, \
5678
      "Cannot retrieve locked instance %s" % self.op.instance_name
5679

    
5680
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5681
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5682
      raise errors.OpPrereqError("Instance's disk layout is not"
5683
                                 " network mirrored, cannot failover.",
5684
                                 errors.ECODE_STATE)
5685

    
5686
    secondary_nodes = instance.secondary_nodes
5687
    if not secondary_nodes:
5688
      raise errors.ProgrammerError("no secondary node but using "
5689
                                   "a mirrored disk template")
5690

    
5691
    target_node = secondary_nodes[0]
5692
    _CheckNodeOnline(self, target_node)
5693
    _CheckNodeNotDrained(self, target_node)
5694
    if instance.admin_up:
5695
      # check memory requirements on the secondary node
5696
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5697
                           instance.name, bep[constants.BE_MEMORY],
5698
                           instance.hypervisor)
5699
    else:
5700
      self.LogInfo("Not checking memory on the secondary node as"
5701
                   " instance will not be started")
5702

    
5703
    # check bridge existance
5704
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5705

    
5706
  def Exec(self, feedback_fn):
5707
    """Failover an instance.
5708

5709
    The failover is done by shutting it down on its present node and
5710
    starting it on the secondary.
5711

5712
    """
5713
    instance = self.instance
5714
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
5715

    
5716
    source_node = instance.primary_node
5717
    target_node = instance.secondary_nodes[0]
5718

    
5719
    if instance.admin_up:
5720
      feedback_fn("* checking disk consistency between source and target")
5721
      for dev in instance.disks:
5722
        # for drbd, these are drbd over lvm
5723
        if not _CheckDiskConsistency(self, dev, target_node, False):
5724
          if not self.op.ignore_consistency:
5725
            raise errors.OpExecError("Disk %s is degraded on target node,"
5726
                                     " aborting failover." % dev.iv_name)
5727
    else:
5728
      feedback_fn("* not checking disk consistency as instance is not running")
5729

    
5730
    feedback_fn("* shutting down instance on source node")
5731
    logging.info("Shutting down instance %s on node %s",
5732
                 instance.name, source_node)
5733

    
5734
    result = self.rpc.call_instance_shutdown(source_node, instance,
5735
                                             self.op.shutdown_timeout)
5736
    msg = result.fail_msg
5737
    if msg:
5738
      if self.op.ignore_consistency or primary_node.offline:
5739
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5740
                             " Proceeding anyway. Please make sure node"
5741
                             " %s is down. Error details: %s",
5742
                             instance.name, source_node, source_node, msg)
5743
      else:
5744
        raise errors.OpExecError("Could not shutdown instance %s on"
5745
                                 " node %s: %s" %
5746
                                 (instance.name, source_node, msg))
5747

    
5748
    feedback_fn("* deactivating the instance's disks on source node")
5749
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5750
      raise errors.OpExecError("Can't shut down the instance's disks.")
5751

    
5752
    instance.primary_node = target_node
5753
    # distribute new instance config to the other nodes
5754
    self.cfg.Update(instance, feedback_fn)
5755

    
5756
    # Only start the instance if it's marked as up
5757
    if instance.admin_up:
5758
      feedback_fn("* activating the instance's disks on target node")
5759
      logging.info("Starting instance %s on node %s",
5760
                   instance.name, target_node)
5761

    
5762
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5763
                                           ignore_secondaries=True)
5764
      if not disks_ok:
5765
        _ShutdownInstanceDisks(self, instance)
5766
        raise errors.OpExecError("Can't activate the instance's disks")
5767

    
5768
      feedback_fn("* starting the instance on the target node")
5769
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5770
      msg = result.fail_msg
5771
      if msg:
5772
        _ShutdownInstanceDisks(self, instance)
5773
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5774
                                 (instance.name, target_node, msg))
5775

    
5776

    
5777
class LUMigrateInstance(LogicalUnit):
5778
  """Migrate an instance.
5779

5780
  This is migration without shutting down, compared to the failover,
5781
  which is done with shutdown.
5782

5783
  """
5784
  HPATH = "instance-migrate"
5785
  HTYPE = constants.HTYPE_INSTANCE
5786
  _OP_PARAMS = [
5787
    _PInstanceName,
5788
    _PMigrationMode,
5789
    _PMigrationLive,
5790
    ("cleanup", False, ht.TBool),
5791
    ]
5792

    
5793
  REQ_BGL = False
5794

    
5795
  def ExpandNames(self):
5796
    self._ExpandAndLockInstance()
5797

    
5798
    self.needed_locks[locking.LEVEL_NODE] = []
5799
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5800

    
5801
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5802
                                       self.op.cleanup)
5803
    self.tasklets = [self._migrater]
5804

    
5805
  def DeclareLocks(self, level):
5806
    if level == locking.LEVEL_NODE:
5807
      self._LockInstancesNodes()
5808

    
5809
  def BuildHooksEnv(self):
5810
    """Build hooks env.
5811

5812
    This runs on master, primary and secondary nodes of the instance.
5813

5814
    """
5815
    instance = self._migrater.instance
5816
    source_node = instance.primary_node
5817
    target_node = instance.secondary_nodes[0]
5818
    env = _BuildInstanceHookEnvByObject(self, instance)
5819
    env["MIGRATE_LIVE"] = self._migrater.live
5820
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5821
    env.update({
5822
        "OLD_PRIMARY": source_node,
5823
        "OLD_SECONDARY": target_node,
5824
        "NEW_PRIMARY": target_node,
5825
        "NEW_SECONDARY": source_node,
5826
        })
5827
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5828
    nl_post = list(nl)
5829
    nl_post.append(source_node)
5830
    return env, nl, nl_post
5831

    
5832

    
5833
class LUMoveInstance(LogicalUnit):
5834
  """Move an instance by data-copying.
5835

5836
  """
5837
  HPATH = "instance-move"
5838
  HTYPE = constants.HTYPE_INSTANCE
5839
  _OP_PARAMS = [
5840
    _PInstanceName,
5841
    ("target_node", ht.NoDefault, ht.TNonEmptyString),
5842
    _PShutdownTimeout,
5843
    ]
5844
  REQ_BGL = False
5845

    
5846
  def ExpandNames(self):
5847
    self._ExpandAndLockInstance()
5848
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5849
    self.op.target_node = target_node
5850
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5851
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5852

    
5853
  def DeclareLocks(self, level):
5854
    if level == locking.LEVEL_NODE:
5855
      self._LockInstancesNodes(primary_only=True)
5856

    
5857
  def BuildHooksEnv(self):
5858
    """Build hooks env.
5859

5860
    This runs on master, primary and secondary nodes of the instance.
5861

5862
    """
5863
    env = {
5864
      "TARGET_NODE": self.op.target_node,
5865
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5866
      }
5867
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5868
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5869
                                       self.op.target_node]
5870
    return env, nl, nl
5871

    
5872
  def CheckPrereq(self):
5873
    """Check prerequisites.
5874

5875
    This checks that the instance is in the cluster.
5876

5877
    """
5878
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5879
    assert self.instance is not None, \
5880
      "Cannot retrieve locked instance %s" % self.op.instance_name
5881

    
5882
    node = self.cfg.GetNodeInfo(self.op.target_node)
5883
    assert node is not None, \
5884
      "Cannot retrieve locked node %s" % self.op.target_node
5885

    
5886
    self.target_node = target_node = node.name
5887

    
5888
    if target_node == instance.primary_node:
5889
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5890
                                 (instance.name, target_node),
5891
                                 errors.ECODE_STATE)
5892

    
5893
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5894

    
5895
    for idx, dsk in enumerate(instance.disks):
5896
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5897
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5898
                                   " cannot copy" % idx, errors.ECODE_STATE)
5899

    
5900
    _CheckNodeOnline(self, target_node)
5901
    _CheckNodeNotDrained(self, target_node)
5902
    _CheckNodeVmCapable(self, target_node)
5903

    
5904
    if instance.admin_up:
5905
      # check memory requirements on the secondary node
5906
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5907
                           instance.name, bep[constants.BE_MEMORY],
5908
                           instance.hypervisor)
5909
    else:
5910
      self.LogInfo("Not checking memory on the secondary node as"
5911
                   " instance will not be started")
5912

    
5913
    # check bridge existance
5914
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5915

    
5916
  def Exec(self, feedback_fn):
5917
    """Move an instance.
5918

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

5922
    """
5923
    instance = self.instance
5924

    
5925
    source_node = instance.primary_node
5926
    target_node = self.target_node
5927

    
5928
    self.LogInfo("Shutting down instance %s on source node %s",
5929
                 instance.name, source_node)
5930

    
5931
    result = self.rpc.call_instance_shutdown(source_node, instance,
5932
                                             self.op.shutdown_timeout)
5933
    msg = result.fail_msg
5934
    if msg:
5935
      if self.op.ignore_consistency:
5936
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5937
                             " Proceeding anyway. Please make sure node"
5938
                             " %s is down. Error details: %s",
5939
                             instance.name, source_node, source_node, msg)
5940
      else:
5941
        raise errors.OpExecError("Could not shutdown instance %s on"
5942
                                 " node %s: %s" %
5943
                                 (instance.name, source_node, msg))
5944

    
5945
    # create the target disks
5946
    try:
5947
      _CreateDisks(self, instance, target_node=target_node)
5948
    except errors.OpExecError:
5949
      self.LogWarning("Device creation failed, reverting...")
5950
      try:
5951
        _RemoveDisks(self, instance, target_node=target_node)
5952
      finally:
5953
        self.cfg.ReleaseDRBDMinors(instance.name)
5954
        raise
5955

    
5956
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5957

    
5958
    errs = []
5959
    # activate, get path, copy the data over
5960
    for idx, disk in enumerate(instance.disks):
5961
      self.LogInfo("Copying data for disk %d", idx)
5962
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5963
                                               instance.name, True)
5964
      if result.fail_msg:
5965
        self.LogWarning("Can't assemble newly created disk %d: %s",
5966
                        idx, result.fail_msg)
5967
        errs.append(result.fail_msg)
5968
        break
5969
      dev_path = result.payload
5970
      result = self.rpc.call_blockdev_export(source_node, disk,
5971
                                             target_node, dev_path,
5972
                                             cluster_name)
5973
      if result.fail_msg:
5974
        self.LogWarning("Can't copy data over for disk %d: %s",
5975
                        idx, result.fail_msg)
5976
        errs.append(result.fail_msg)
5977
        break
5978

    
5979
    if errs:
5980
      self.LogWarning("Some disks failed to copy, aborting")
5981
      try:
5982
        _RemoveDisks(self, instance, target_node=target_node)
5983
      finally:
5984
        self.cfg.ReleaseDRBDMinors(instance.name)
5985
        raise errors.OpExecError("Errors during disk copy: %s" %
5986
                                 (",".join(errs),))
5987

    
5988
    instance.primary_node = target_node
5989
    self.cfg.Update(instance, feedback_fn)
5990

    
5991
    self.LogInfo("Removing the disks on the original node")
5992
    _RemoveDisks(self, instance, target_node=source_node)
5993

    
5994
    # Only start the instance if it's marked as up
5995
    if instance.admin_up:
5996
      self.LogInfo("Starting instance %s on node %s",
5997
                   instance.name, target_node)
5998

    
5999
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
6000
                                           ignore_secondaries=True)
6001
      if not disks_ok:
6002
        _ShutdownInstanceDisks(self, instance)
6003
        raise errors.OpExecError("Can't activate the instance's disks")
6004

    
6005
      result = self.rpc.call_instance_start(target_node, instance, None, None)
6006
      msg = result.fail_msg
6007
      if msg:
6008
        _ShutdownInstanceDisks(self, instance)
6009
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
6010
                                 (instance.name, target_node, msg))
6011

    
6012

    
6013
class LUMigrateNode(LogicalUnit):
6014
  """Migrate all instances from a node.
6015

6016
  """
6017
  HPATH = "node-migrate"
6018
  HTYPE = constants.HTYPE_NODE
6019
  _OP_PARAMS = [
6020
    _PNodeName,
6021
    _PMigrationMode,
6022
    _PMigrationLive,
6023
    ]
6024
  REQ_BGL = False
6025

    
6026
  def ExpandNames(self):
6027
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6028

    
6029
    self.needed_locks = {
6030
      locking.LEVEL_NODE: [self.op.node_name],
6031
      }
6032

    
6033
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6034

    
6035
    # Create tasklets for migrating instances for all instances on this node
6036
    names = []
6037
    tasklets = []
6038

    
6039
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
6040
      logging.debug("Migrating instance %s", inst.name)
6041
      names.append(inst.name)
6042

    
6043
      tasklets.append(TLMigrateInstance(self, inst.name, False))
6044

    
6045
    self.tasklets = tasklets
6046

    
6047
    # Declare instance locks
6048
    self.needed_locks[locking.LEVEL_INSTANCE] = names
6049

    
6050
  def DeclareLocks(self, level):
6051
    if level == locking.LEVEL_NODE:
6052
      self._LockInstancesNodes()
6053

    
6054
  def BuildHooksEnv(self):
6055
    """Build hooks env.
6056

6057
    This runs on the master, the primary and all the secondaries.
6058

6059
    """
6060
    env = {
6061
      "NODE_NAME": self.op.node_name,
6062
      }
6063

    
6064
    nl = [self.cfg.GetMasterNode()]
6065

    
6066
    return (env, nl, nl)
6067

    
6068

    
6069
class TLMigrateInstance(Tasklet):
6070
  """Tasklet class for instance migration.
6071

6072
  @type live: boolean
6073
  @ivar live: whether the migration will be done live or non-live;
6074
      this variable is initalized only after CheckPrereq has run
6075

6076
  """
6077
  def __init__(self, lu, instance_name, cleanup):
6078
    """Initializes this class.
6079

6080
    """
6081
    Tasklet.__init__(self, lu)
6082

    
6083
    # Parameters
6084
    self.instance_name = instance_name
6085
    self.cleanup = cleanup
6086
    self.live = False # will be overridden later
6087

    
6088
  def CheckPrereq(self):
6089
    """Check prerequisites.
6090

6091
    This checks that the instance is in the cluster.
6092

6093
    """
6094
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
6095
    instance = self.cfg.GetInstanceInfo(instance_name)
6096
    assert instance is not None
6097

    
6098
    if instance.disk_template != constants.DT_DRBD8:
6099
      raise errors.OpPrereqError("Instance's disk layout is not"
6100
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
6101

    
6102
    secondary_nodes = instance.secondary_nodes
6103
    if not secondary_nodes:
6104
      raise errors.ConfigurationError("No secondary node but using"
6105
                                      " drbd8 disk template")
6106

    
6107
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
6108

    
6109
    target_node = secondary_nodes[0]
6110
    # check memory requirements on the secondary node
6111
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
6112
                         instance.name, i_be[constants.BE_MEMORY],
6113
                         instance.hypervisor)
6114

    
6115
    # check bridge existance
6116
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
6117

    
6118
    if not self.cleanup:
6119
      _CheckNodeNotDrained(self.lu, target_node)
6120
      result = self.rpc.call_instance_migratable(instance.primary_node,
6121
                                                 instance)
6122
      result.Raise("Can't migrate, please use failover",
6123
                   prereq=True, ecode=errors.ECODE_STATE)
6124

    
6125
    self.instance = instance
6126

    
6127
    if self.lu.op.live is not None and self.lu.op.mode is not None:
6128
      raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
6129
                                 " parameters are accepted",
6130
                                 errors.ECODE_INVAL)
6131
    if self.lu.op.live is not None:
6132
      if self.lu.op.live:
6133
        self.lu.op.mode = constants.HT_MIGRATION_LIVE
6134
      else:
6135
        self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6136
      # reset the 'live' parameter to None so that repeated
6137
      # invocations of CheckPrereq do not raise an exception
6138
      self.lu.op.live = None
6139
    elif self.lu.op.mode is None:
6140
      # read the default value from the hypervisor
6141
      i_hv = self.cfg.GetClusterInfo().FillHV(instance, skip_globals=False)
6142
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6143

    
6144
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6145

    
6146
  def _WaitUntilSync(self):
6147
    """Poll with custom rpc for disk sync.
6148

6149
    This uses our own step-based rpc call.
6150

6151
    """
6152
    self.feedback_fn("* wait until resync is done")
6153
    all_done = False
6154
    while not all_done:
6155
      all_done = True
6156
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6157
                                            self.nodes_ip,
6158
                                            self.instance.disks)
6159
      min_percent = 100
6160
      for node, nres in result.items():
6161
        nres.Raise("Cannot resync disks on node %s" % node)
6162
        node_done, node_percent = nres.payload
6163
        all_done = all_done and node_done
6164
        if node_percent is not None:
6165
          min_percent = min(min_percent, node_percent)
6166
      if not all_done:
6167
        if min_percent < 100:
6168
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6169
        time.sleep(2)
6170

    
6171
  def _EnsureSecondary(self, node):
6172
    """Demote a node to secondary.
6173

6174
    """
6175
    self.feedback_fn("* switching node %s to secondary mode" % node)
6176

    
6177
    for dev in self.instance.disks:
6178
      self.cfg.SetDiskID(dev, node)
6179

    
6180
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6181
                                          self.instance.disks)
6182
    result.Raise("Cannot change disk to secondary on node %s" % node)
6183

    
6184
  def _GoStandalone(self):
6185
    """Disconnect from the network.
6186

6187
    """
6188
    self.feedback_fn("* changing into standalone mode")
6189
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6190
                                               self.instance.disks)
6191
    for node, nres in result.items():
6192
      nres.Raise("Cannot disconnect disks node %s" % node)
6193

    
6194
  def _GoReconnect(self, multimaster):
6195
    """Reconnect to the network.
6196

6197
    """
6198
    if multimaster:
6199
      msg = "dual-master"
6200
    else:
6201
      msg = "single-master"
6202
    self.feedback_fn("* changing disks into %s mode" % msg)
6203
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6204
                                           self.instance.disks,
6205
                                           self.instance.name, multimaster)
6206
    for node, nres in result.items():
6207
      nres.Raise("Cannot change disks config on node %s" % node)
6208

    
6209
  def _ExecCleanup(self):
6210
    """Try to cleanup after a failed migration.
6211

6212
    The cleanup is done by:
6213
      - check that the instance is running only on one node
6214
        (and update the config if needed)
6215
      - change disks on its secondary node to secondary
6216
      - wait until disks are fully synchronized
6217
      - disconnect from the network
6218
      - change disks into single-master mode
6219
      - wait again until disks are fully synchronized
6220

6221
    """
6222
    instance = self.instance
6223
    target_node = self.target_node
6224
    source_node = self.source_node
6225

    
6226
    # check running on only one node
6227
    self.feedback_fn("* checking where the instance actually runs"
6228
                     " (if this hangs, the hypervisor might be in"
6229
                     " a bad state)")
6230
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
6231
    for node, result in ins_l.items():
6232
      result.Raise("Can't contact node %s" % node)
6233

    
6234
    runningon_source = instance.name in ins_l[source_node].payload
6235
    runningon_target = instance.name in ins_l[target_node].payload
6236

    
6237
    if runningon_source and runningon_target:
6238
      raise errors.OpExecError("Instance seems to be running on two nodes,"
6239
                               " or the hypervisor is confused. You will have"
6240
                               " to ensure manually that it runs only on one"
6241
                               " and restart this operation.")
6242

    
6243
    if not (runningon_source or runningon_target):
6244
      raise errors.OpExecError("Instance does not seem to be running at all."
6245
                               " In this case, it's safer to repair by"
6246
                               " running 'gnt-instance stop' to ensure disk"
6247
                               " shutdown, and then restarting it.")
6248

    
6249
    if runningon_target:
6250
      # the migration has actually succeeded, we need to update the config
6251
      self.feedback_fn("* instance running on secondary node (%s),"
6252
                       " updating config" % target_node)
6253
      instance.primary_node = target_node
6254
      self.cfg.Update(instance, self.feedback_fn)
6255
      demoted_node = source_node
6256
    else:
6257
      self.feedback_fn("* instance confirmed to be running on its"
6258
                       " primary node (%s)" % source_node)
6259
      demoted_node = target_node
6260

    
6261
    self._EnsureSecondary(demoted_node)
6262
    try:
6263
      self._WaitUntilSync()
6264
    except errors.OpExecError:
6265
      # we ignore here errors, since if the device is standalone, it
6266
      # won't be able to sync
6267
      pass
6268
    self._GoStandalone()
6269
    self._GoReconnect(False)
6270
    self._WaitUntilSync()
6271

    
6272
    self.feedback_fn("* done")
6273

    
6274
  def _RevertDiskStatus(self):
6275
    """Try to revert the disk status after a failed migration.
6276

6277
    """
6278
    target_node = self.target_node
6279
    try:
6280
      self._EnsureSecondary(target_node)
6281
      self._GoStandalone()
6282
      self._GoReconnect(False)
6283
      self._WaitUntilSync()
6284
    except errors.OpExecError, err:
6285
      self.lu.LogWarning("Migration failed and I can't reconnect the"
6286
                         " drives: error '%s'\n"
6287
                         "Please look and recover the instance status" %
6288
                         str(err))
6289

    
6290
  def _AbortMigration(self):
6291
    """Call the hypervisor code to abort a started migration.
6292

6293
    """
6294
    instance = self.instance
6295
    target_node = self.target_node
6296
    migration_info = self.migration_info
6297

    
6298
    abort_result = self.rpc.call_finalize_migration(target_node,
6299
                                                    instance,
6300
                                                    migration_info,
6301
                                                    False)
6302
    abort_msg = abort_result.fail_msg
6303
    if abort_msg:
6304
      logging.error("Aborting migration failed on target node %s: %s",
6305
                    target_node, abort_msg)
6306
      # Don't raise an exception here, as we stil have to try to revert the
6307
      # disk status, even if this step failed.
6308

    
6309
  def _ExecMigration(self):
6310
    """Migrate an instance.
6311

6312
    The migrate is done by:
6313
      - change the disks into dual-master mode
6314
      - wait until disks are fully synchronized again
6315
      - migrate the instance
6316
      - change disks on the new secondary node (the old primary) to secondary
6317
      - wait until disks are fully synchronized
6318
      - change disks into single-master mode
6319

6320
    """
6321
    instance = self.instance
6322
    target_node = self.target_node
6323
    source_node = self.source_node
6324

    
6325
    self.feedback_fn("* checking disk consistency between source and target")
6326
    for dev in instance.disks:
6327
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6328
        raise errors.OpExecError("Disk %s is degraded or not fully"
6329
                                 " synchronized on target node,"
6330
                                 " aborting migrate." % dev.iv_name)
6331

    
6332
    # First get the migration information from the remote node
6333
    result = self.rpc.call_migration_info(source_node, instance)
6334
    msg = result.fail_msg
6335
    if msg:
6336
      log_err = ("Failed fetching source migration information from %s: %s" %
6337
                 (source_node, msg))
6338
      logging.error(log_err)
6339
      raise errors.OpExecError(log_err)
6340

    
6341
    self.migration_info = migration_info = result.payload
6342

    
6343
    # Then switch the disks to master/master mode
6344
    self._EnsureSecondary(target_node)
6345
    self._GoStandalone()
6346
    self._GoReconnect(True)
6347
    self._WaitUntilSync()
6348

    
6349
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6350
    result = self.rpc.call_accept_instance(target_node,
6351
                                           instance,
6352
                                           migration_info,
6353
                                           self.nodes_ip[target_node])
6354

    
6355
    msg = result.fail_msg
6356
    if msg:
6357
      logging.error("Instance pre-migration failed, trying to revert"
6358
                    " disk status: %s", msg)
6359
      self.feedback_fn("Pre-migration failed, aborting")
6360
      self._AbortMigration()
6361
      self._RevertDiskStatus()
6362
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6363
                               (instance.name, msg))
6364

    
6365
    self.feedback_fn("* migrating instance to %s" % target_node)
6366
    time.sleep(10)
6367
    result = self.rpc.call_instance_migrate(source_node, instance,
6368
                                            self.nodes_ip[target_node],
6369
                                            self.live)
6370
    msg = result.fail_msg
6371
    if msg:
6372
      logging.error("Instance migration failed, trying to revert"
6373
                    " disk status: %s", msg)
6374
      self.feedback_fn("Migration failed, aborting")
6375
      self._AbortMigration()
6376
      self._RevertDiskStatus()
6377
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6378
                               (instance.name, msg))
6379
    time.sleep(10)
6380

    
6381
    instance.primary_node = target_node
6382
    # distribute new instance config to the other nodes
6383
    self.cfg.Update(instance, self.feedback_fn)
6384

    
6385
    result = self.rpc.call_finalize_migration(target_node,
6386
                                              instance,
6387
                                              migration_info,
6388
                                              True)
6389
    msg = result.fail_msg
6390
    if msg:
6391
      logging.error("Instance migration succeeded, but finalization failed:"
6392
                    " %s", msg)
6393
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6394
                               msg)
6395

    
6396
    self._EnsureSecondary(source_node)
6397
    self._WaitUntilSync()
6398
    self._GoStandalone()
6399
    self._GoReconnect(False)
6400
    self._WaitUntilSync()
6401

    
6402
    self.feedback_fn("* done")
6403

    
6404
  def Exec(self, feedback_fn):
6405
    """Perform the migration.
6406

6407
    """
6408
    feedback_fn("Migrating instance %s" % self.instance.name)
6409

    
6410
    self.feedback_fn = feedback_fn
6411

    
6412
    self.source_node = self.instance.primary_node
6413
    self.target_node = self.instance.secondary_nodes[0]
6414
    self.all_nodes = [self.source_node, self.target_node]
6415
    self.nodes_ip = {
6416
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6417
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6418
      }
6419

    
6420
    if self.cleanup:
6421
      return self._ExecCleanup()
6422
    else:
6423
      return self._ExecMigration()
6424

    
6425

    
6426
def _CreateBlockDev(lu, node, instance, device, force_create,
6427
                    info, force_open):
6428
  """Create a tree of block devices on a given node.
6429

6430
  If this device type has to be created on secondaries, create it and
6431
  all its children.
6432

6433
  If not, just recurse to children keeping the same 'force' value.
6434

6435
  @param lu: the lu on whose behalf we execute
6436
  @param node: the node on which to create the device
6437
  @type instance: L{objects.Instance}
6438
  @param instance: the instance which owns the device
6439
  @type device: L{objects.Disk}
6440
  @param device: the device to create
6441
  @type force_create: boolean
6442
  @param force_create: whether to force creation of this device; this
6443
      will be change to True whenever we find a device which has
6444
      CreateOnSecondary() attribute
6445
  @param info: the extra 'metadata' we should attach to the device
6446
      (this will be represented as a LVM tag)
6447
  @type force_open: boolean
6448
  @param force_open: this parameter will be passes to the
6449
      L{backend.BlockdevCreate} function where it specifies
6450
      whether we run on primary or not, and it affects both
6451
      the child assembly and the device own Open() execution
6452

6453
  """
6454
  if device.CreateOnSecondary():
6455
    force_create = True
6456

    
6457
  if device.children:
6458
    for child in device.children:
6459
      _CreateBlockDev(lu, node, instance, child, force_create,
6460
                      info, force_open)
6461

    
6462
  if not force_create:
6463
    return
6464

    
6465
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6466

    
6467

    
6468
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6469
  """Create a single block device on a given node.
6470

6471
  This will not recurse over children of the device, so they must be
6472
  created in advance.
6473

6474
  @param lu: the lu on whose behalf we execute
6475
  @param node: the node on which to create the device
6476
  @type instance: L{objects.Instance}
6477
  @param instance: the instance which owns the device
6478
  @type device: L{objects.Disk}
6479
  @param device: the device to create
6480
  @param info: the extra 'metadata' we should attach to the device
6481
      (this will be represented as a LVM tag)
6482
  @type force_open: boolean
6483
  @param force_open: this parameter will be passes to the
6484
      L{backend.BlockdevCreate} function where it specifies
6485
      whether we run on primary or not, and it affects both
6486
      the child assembly and the device own Open() execution
6487

6488
  """
6489
  lu.cfg.SetDiskID(device, node)
6490
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6491
                                       instance.name, force_open, info)
6492
  result.Raise("Can't create block device %s on"
6493
               " node %s for instance %s" % (device, node, instance.name))
6494
  if device.physical_id is None:
6495
    device.physical_id = result.payload
6496

    
6497

    
6498
def _GenerateUniqueNames(lu, exts):
6499
  """Generate a suitable LV name.
6500

6501
  This will generate a logical volume name for the given instance.
6502

6503
  """
6504
  results = []
6505
  for val in exts:
6506
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6507
    results.append("%s%s" % (new_id, val))
6508
  return results
6509

    
6510

    
6511
def _GenerateDRBD8Branch(lu, primary, secondary, size, vgname, names, iv_name,
6512
                         p_minor, s_minor):
6513
  """Generate a drbd8 device complete with its children.
6514

6515
  """
6516
  port = lu.cfg.AllocatePort()
6517
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6518
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6519
                          logical_id=(vgname, names[0]))
6520
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6521
                          logical_id=(vgname, names[1]))
6522
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6523
                          logical_id=(primary, secondary, port,
6524
                                      p_minor, s_minor,
6525
                                      shared_secret),
6526
                          children=[dev_data, dev_meta],
6527
                          iv_name=iv_name)
6528
  return drbd_dev
6529

    
6530

    
6531
def _GenerateDiskTemplate(lu, template_name,
6532
                          instance_name, primary_node,
6533
                          secondary_nodes, disk_info,
6534
                          file_storage_dir, file_driver,
6535
                          base_index, feedback_fn):
6536
  """Generate the entire disk layout for a given template type.
6537

6538
  """
6539
  #TODO: compute space requirements
6540

    
6541
  vgname = lu.cfg.GetVGName()
6542
  disk_count = len(disk_info)
6543
  disks = []
6544
  if template_name == constants.DT_DISKLESS:
6545
    pass
6546
  elif template_name == constants.DT_PLAIN:
6547
    if len(secondary_nodes) != 0:
6548
      raise errors.ProgrammerError("Wrong template configuration")
6549

    
6550
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6551
                                      for i in range(disk_count)])
6552
    for idx, disk in enumerate(disk_info):
6553
      disk_index = idx + base_index
6554
      vg = disk.get("vg", vgname)
6555
      feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
6556
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6557
                              logical_id=(vg, names[idx]),
6558
                              iv_name="disk/%d" % disk_index,
6559
                              mode=disk["mode"])
6560
      disks.append(disk_dev)
6561
  elif template_name == constants.DT_DRBD8:
6562
    if len(secondary_nodes) != 1:
6563
      raise errors.ProgrammerError("Wrong template configuration")
6564
    remote_node = secondary_nodes[0]
6565
    minors = lu.cfg.AllocateDRBDMinor(
6566
      [primary_node, remote_node] * len(disk_info), instance_name)
6567

    
6568
    names = []
6569
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6570
                                               for i in range(disk_count)]):
6571
      names.append(lv_prefix + "_data")
6572
      names.append(lv_prefix + "_meta")
6573
    for idx, disk in enumerate(disk_info):
6574
      disk_index = idx + base_index
6575
      vg = disk.get("vg", vgname)
6576
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6577
                                      disk["size"], vg, names[idx*2:idx*2+2],
6578
                                      "disk/%d" % disk_index,
6579
                                      minors[idx*2], minors[idx*2+1])
6580
      disk_dev.mode = disk["mode"]
6581
      disks.append(disk_dev)
6582
  elif template_name == constants.DT_FILE:
6583
    if len(secondary_nodes) != 0:
6584
      raise errors.ProgrammerError("Wrong template configuration")
6585

    
6586
    _RequireFileStorage()
6587

    
6588
    for idx, disk in enumerate(disk_info):
6589
      disk_index = idx + base_index
6590
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6591
                              iv_name="disk/%d" % disk_index,
6592
                              logical_id=(file_driver,
6593
                                          "%s/disk%d" % (file_storage_dir,
6594
                                                         disk_index)),
6595
                              mode=disk["mode"])
6596
      disks.append(disk_dev)
6597
  else:
6598
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6599
  return disks
6600

    
6601

    
6602
def _GetInstanceInfoText(instance):
6603
  """Compute that text that should be added to the disk's metadata.
6604

6605
  """
6606
  return "originstname+%s" % instance.name
6607

    
6608

    
6609
def _CalcEta(time_taken, written, total_size):
6610
  """Calculates the ETA based on size written and total size.
6611

6612
  @param time_taken: The time taken so far
6613
  @param written: amount written so far
6614
  @param total_size: The total size of data to be written
6615
  @return: The remaining time in seconds
6616

6617
  """
6618
  avg_time = time_taken / float(written)
6619
  return (total_size - written) * avg_time
6620

    
6621

    
6622
def _WipeDisks(lu, instance):
6623
  """Wipes instance disks.
6624

6625
  @type lu: L{LogicalUnit}
6626
  @param lu: the logical unit on whose behalf we execute
6627
  @type instance: L{objects.Instance}
6628
  @param instance: the instance whose disks we should create
6629
  @return: the success of the wipe
6630

6631
  """
6632
  node = instance.primary_node
6633
  for idx, device in enumerate(instance.disks):
6634
    lu.LogInfo("* Wiping disk %d", idx)
6635
    logging.info("Wiping disk %d for instance %s", idx, instance.name)
6636

    
6637
    # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
6638
    # MAX_WIPE_CHUNK at max
6639
    wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
6640
                          constants.MIN_WIPE_CHUNK_PERCENT)
6641

    
6642
    offset = 0
6643
    size = device.size
6644
    last_output = 0
6645
    start_time = time.time()
6646

    
6647
    while offset < size:
6648
      wipe_size = min(wipe_chunk_size, size - offset)
6649
      result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
6650
      result.Raise("Could not wipe disk %d at offset %d for size %d" %
6651
                   (idx, offset, wipe_size))
6652
      now = time.time()
6653
      offset += wipe_size
6654
      if now - last_output >= 60:
6655
        eta = _CalcEta(now - start_time, offset, size)
6656
        lu.LogInfo(" - done: %.1f%% ETA: %s" %
6657
                   (offset / float(size) * 100, utils.FormatSeconds(eta)))
6658
        last_output = now
6659

    
6660

    
6661
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6662
  """Create all disks for an instance.
6663

6664
  This abstracts away some work from AddInstance.
6665

6666
  @type lu: L{LogicalUnit}
6667
  @param lu: the logical unit on whose behalf we execute
6668
  @type instance: L{objects.Instance}
6669
  @param instance: the instance whose disks we should create
6670
  @type to_skip: list
6671
  @param to_skip: list of indices to skip
6672
  @type target_node: string
6673
  @param target_node: if passed, overrides the target node for creation
6674
  @rtype: boolean
6675
  @return: the success of the creation
6676

6677
  """
6678
  info = _GetInstanceInfoText(instance)
6679
  if target_node is None:
6680
    pnode = instance.primary_node
6681
    all_nodes = instance.all_nodes
6682
  else:
6683
    pnode = target_node
6684
    all_nodes = [pnode]
6685

    
6686
  if instance.disk_template == constants.DT_FILE:
6687
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6688
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6689

    
6690
    result.Raise("Failed to create directory '%s' on"
6691
                 " node %s" % (file_storage_dir, pnode))
6692

    
6693
  # Note: this needs to be kept in sync with adding of disks in
6694
  # LUSetInstanceParams
6695
  for idx, device in enumerate(instance.disks):
6696
    if to_skip and idx in to_skip:
6697
      continue
6698
    logging.info("Creating volume %s for instance %s",
6699
                 device.iv_name, instance.name)
6700
    #HARDCODE
6701
    for node in all_nodes:
6702
      f_create = node == pnode
6703
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6704

    
6705

    
6706
def _RemoveDisks(lu, instance, target_node=None):
6707
  """Remove all disks for an instance.
6708

6709
  This abstracts away some work from `AddInstance()` and
6710
  `RemoveInstance()`. Note that in case some of the devices couldn't
6711
  be removed, the removal will continue with the other ones (compare
6712
  with `_CreateDisks()`).
6713

6714
  @type lu: L{LogicalUnit}
6715
  @param lu: the logical unit on whose behalf we execute
6716
  @type instance: L{objects.Instance}
6717
  @param instance: the instance whose disks we should remove
6718
  @type target_node: string
6719
  @param target_node: used to override the node on which to remove the disks
6720
  @rtype: boolean
6721
  @return: the success of the removal
6722

6723
  """
6724
  logging.info("Removing block devices for instance %s", instance.name)
6725

    
6726
  all_result = True
6727
  for device in instance.disks:
6728
    if target_node:
6729
      edata = [(target_node, device)]
6730
    else:
6731
      edata = device.ComputeNodeTree(instance.primary_node)
6732
    for node, disk in edata:
6733
      lu.cfg.SetDiskID(disk, node)
6734
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6735
      if msg:
6736
        lu.LogWarning("Could not remove block device %s on node %s,"
6737
                      " continuing anyway: %s", device.iv_name, node, msg)
6738
        all_result = False
6739

    
6740
  if instance.disk_template == constants.DT_FILE:
6741
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6742
    if target_node:
6743
      tgt = target_node
6744
    else:
6745
      tgt = instance.primary_node
6746
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6747
    if result.fail_msg:
6748
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6749
                    file_storage_dir, instance.primary_node, result.fail_msg)
6750
      all_result = False
6751

    
6752
  return all_result
6753

    
6754

    
6755
def _ComputeDiskSize(disk_template, disks):
6756
  """Compute disk size requirements in the volume group
6757

6758
  """
6759
  # Required free disk space as a function of disk and swap space
6760
  req_size_dict = {
6761
    constants.DT_DISKLESS: None,
6762
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6763
    # 128 MB are added for drbd metadata for each disk
6764
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6765
    constants.DT_FILE: None,
6766
  }
6767

    
6768
  if disk_template not in req_size_dict:
6769
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6770
                                 " is unknown" %  disk_template)
6771

    
6772
  return req_size_dict[disk_template]
6773

    
6774

    
6775
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6776
  """Hypervisor parameter validation.
6777

6778
  This function abstract the hypervisor parameter validation to be
6779
  used in both instance create and instance modify.
6780

6781
  @type lu: L{LogicalUnit}
6782
  @param lu: the logical unit for which we check
6783
  @type nodenames: list
6784
  @param nodenames: the list of nodes on which we should check
6785
  @type hvname: string
6786
  @param hvname: the name of the hypervisor we should use
6787
  @type hvparams: dict
6788
  @param hvparams: the parameters which we need to check
6789
  @raise errors.OpPrereqError: if the parameters are not valid
6790

6791
  """
6792
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6793
                                                  hvname,
6794
                                                  hvparams)
6795
  for node in nodenames:
6796
    info = hvinfo[node]
6797
    if info.offline:
6798
      continue
6799
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6800

    
6801

    
6802
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6803
  """OS parameters validation.
6804

6805
  @type lu: L{LogicalUnit}
6806
  @param lu: the logical unit for which we check
6807
  @type required: boolean
6808
  @param required: whether the validation should fail if the OS is not
6809
      found
6810
  @type nodenames: list
6811
  @param nodenames: the list of nodes on which we should check
6812
  @type osname: string
6813
  @param osname: the name of the hypervisor we should use
6814
  @type osparams: dict
6815
  @param osparams: the parameters which we need to check
6816
  @raise errors.OpPrereqError: if the parameters are not valid
6817

6818
  """
6819
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6820
                                   [constants.OS_VALIDATE_PARAMETERS],
6821
                                   osparams)
6822
  for node, nres in result.items():
6823
    # we don't check for offline cases since this should be run only
6824
    # against the master node and/or an instance's nodes
6825
    nres.Raise("OS Parameters validation failed on node %s" % node)
6826
    if not nres.payload:
6827
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6828
                 osname, node)
6829

    
6830

    
6831
class LUCreateInstance(LogicalUnit):
6832
  """Create an instance.
6833

6834
  """
6835
  HPATH = "instance-add"
6836
  HTYPE = constants.HTYPE_INSTANCE
6837
  _OP_PARAMS = [
6838
    _PInstanceName,
6839
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES)),
6840
    ("start", True, ht.TBool),
6841
    ("wait_for_sync", True, ht.TBool),
6842
    ("ip_check", True, ht.TBool),
6843
    ("name_check", True, ht.TBool),
6844
    ("disks", ht.NoDefault, ht.TListOf(ht.TDict)),
6845
    ("nics", ht.NoDefault, ht.TListOf(ht.TDict)),
6846
    ("hvparams", ht.EmptyDict, ht.TDict),
6847
    ("beparams", ht.EmptyDict, ht.TDict),
6848
    ("osparams", ht.EmptyDict, ht.TDict),
6849
    ("no_install", None, ht.TMaybeBool),
6850
    ("os_type", None, ht.TMaybeString),
6851
    ("force_variant", False, ht.TBool),
6852
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone)),
6853
    ("source_x509_ca", None, ht.TMaybeString),
6854
    ("source_instance_name", None, ht.TMaybeString),
6855
    ("src_node", None, ht.TMaybeString),
6856
    ("src_path", None, ht.TMaybeString),
6857
    ("pnode", None, ht.TMaybeString),
6858
    ("snode", None, ht.TMaybeString),
6859
    ("iallocator", None, ht.TMaybeString),
6860
    ("hypervisor", None, ht.TMaybeString),
6861
    ("disk_template", ht.NoDefault, _CheckDiskTemplate),
6862
    ("identify_defaults", False, ht.TBool),
6863
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER))),
6864
    ("file_storage_dir", None, ht.TMaybeString),
6865
    ]
6866
  REQ_BGL = False
6867

    
6868
  def CheckArguments(self):
6869
    """Check arguments.
6870

6871
    """
6872
    # do not require name_check to ease forward/backward compatibility
6873
    # for tools
6874
    if self.op.no_install and self.op.start:
6875
      self.LogInfo("No-installation mode selected, disabling startup")
6876
      self.op.start = False
6877
    # validate/normalize the instance name
6878
    self.op.instance_name = \
6879
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
6880

    
6881
    if self.op.ip_check and not self.op.name_check:
6882
      # TODO: make the ip check more flexible and not depend on the name check
6883
      raise errors.OpPrereqError("Cannot do ip check without a name check",
6884
                                 errors.ECODE_INVAL)
6885

    
6886
    # check nics' parameter names
6887
    for nic in self.op.nics:
6888
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6889

    
6890
    # check disks. parameter names and consistent adopt/no-adopt strategy
6891
    has_adopt = has_no_adopt = False
6892
    for disk in self.op.disks:
6893
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6894
      if "adopt" in disk:
6895
        has_adopt = True
6896
      else:
6897
        has_no_adopt = True
6898
    if has_adopt and has_no_adopt:
6899
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6900
                                 errors.ECODE_INVAL)
6901
    if has_adopt:
6902
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6903
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6904
                                   " '%s' disk template" %
6905
                                   self.op.disk_template,
6906
                                   errors.ECODE_INVAL)
6907
      if self.op.iallocator is not None:
6908
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6909
                                   " iallocator script", errors.ECODE_INVAL)
6910
      if self.op.mode == constants.INSTANCE_IMPORT:
6911
        raise errors.OpPrereqError("Disk adoption not allowed for"
6912
                                   " instance import", errors.ECODE_INVAL)
6913

    
6914
    self.adopt_disks = has_adopt
6915

    
6916
    # instance name verification
6917
    if self.op.name_check:
6918
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
6919
      self.op.instance_name = self.hostname1.name
6920
      # used in CheckPrereq for ip ping check
6921
      self.check_ip = self.hostname1.ip
6922
    else:
6923
      self.check_ip = None
6924

    
6925
    # file storage checks
6926
    if (self.op.file_driver and
6927
        not self.op.file_driver in constants.FILE_DRIVER):
6928
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6929
                                 self.op.file_driver, errors.ECODE_INVAL)
6930

    
6931
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6932
      raise errors.OpPrereqError("File storage directory path not absolute",
6933
                                 errors.ECODE_INVAL)
6934

    
6935
    ### Node/iallocator related checks
6936
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
6937

    
6938
    if self.op.pnode is not None:
6939
      if self.op.disk_template in constants.DTS_NET_MIRROR:
6940
        if self.op.snode is None:
6941
          raise errors.OpPrereqError("The networked disk templates need"
6942
                                     " a mirror node", errors.ECODE_INVAL)
6943
      elif self.op.snode:
6944
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
6945
                        " template")
6946
        self.op.snode = None
6947

    
6948
    self._cds = _GetClusterDomainSecret()
6949

    
6950
    if self.op.mode == constants.INSTANCE_IMPORT:
6951
      # On import force_variant must be True, because if we forced it at
6952
      # initial install, our only chance when importing it back is that it
6953
      # works again!
6954
      self.op.force_variant = True
6955

    
6956
      if self.op.no_install:
6957
        self.LogInfo("No-installation mode has no effect during import")
6958

    
6959
    elif self.op.mode == constants.INSTANCE_CREATE:
6960
      if self.op.os_type is None:
6961
        raise errors.OpPrereqError("No guest OS specified",
6962
                                   errors.ECODE_INVAL)
6963
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
6964
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
6965
                                   " installation" % self.op.os_type,
6966
                                   errors.ECODE_STATE)
6967
      if self.op.disk_template is None:
6968
        raise errors.OpPrereqError("No disk template specified",
6969
                                   errors.ECODE_INVAL)
6970

    
6971
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6972
      # Check handshake to ensure both clusters have the same domain secret
6973
      src_handshake = self.op.source_handshake
6974
      if not src_handshake:
6975
        raise errors.OpPrereqError("Missing source handshake",
6976
                                   errors.ECODE_INVAL)
6977

    
6978
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6979
                                                           src_handshake)
6980
      if errmsg:
6981
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6982
                                   errors.ECODE_INVAL)
6983

    
6984
      # Load and check source CA
6985
      self.source_x509_ca_pem = self.op.source_x509_ca
6986
      if not self.source_x509_ca_pem:
6987
        raise errors.OpPrereqError("Missing source X509 CA",
6988
                                   errors.ECODE_INVAL)
6989

    
6990
      try:
6991
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
6992
                                                    self._cds)
6993
      except OpenSSL.crypto.Error, err:
6994
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
6995
                                   (err, ), errors.ECODE_INVAL)
6996

    
6997
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
6998
      if errcode is not None:
6999
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
7000
                                   errors.ECODE_INVAL)
7001

    
7002
      self.source_x509_ca = cert
7003

    
7004
      src_instance_name = self.op.source_instance_name
7005
      if not src_instance_name:
7006
        raise errors.OpPrereqError("Missing source instance name",
7007
                                   errors.ECODE_INVAL)
7008

    
7009
      self.source_instance_name = \
7010
          netutils.GetHostname(name=src_instance_name).name
7011

    
7012
    else:
7013
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
7014
                                 self.op.mode, errors.ECODE_INVAL)
7015

    
7016
  def ExpandNames(self):
7017
    """ExpandNames for CreateInstance.
7018

7019
    Figure out the right locks for instance creation.
7020

7021
    """
7022
    self.needed_locks = {}
7023

    
7024
    instance_name = self.op.instance_name
7025
    # this is just a preventive check, but someone might still add this
7026
    # instance in the meantime, and creation will fail at lock-add time
7027
    if instance_name in self.cfg.GetInstanceList():
7028
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
7029
                                 instance_name, errors.ECODE_EXISTS)
7030

    
7031
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
7032

    
7033
    if self.op.iallocator:
7034
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7035
    else:
7036
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
7037
      nodelist = [self.op.pnode]
7038
      if self.op.snode is not None:
7039
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
7040
        nodelist.append(self.op.snode)
7041
      self.needed_locks[locking.LEVEL_NODE] = nodelist
7042

    
7043
    # in case of import lock the source node too
7044
    if self.op.mode == constants.INSTANCE_IMPORT:
7045
      src_node = self.op.src_node
7046
      src_path = self.op.src_path
7047

    
7048
      if src_path is None:
7049
        self.op.src_path = src_path = self.op.instance_name
7050

    
7051
      if src_node is None:
7052
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7053
        self.op.src_node = None
7054
        if os.path.isabs(src_path):
7055
          raise errors.OpPrereqError("Importing an instance from an absolute"
7056
                                     " path requires a source node option.",
7057
                                     errors.ECODE_INVAL)
7058
      else:
7059
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
7060
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
7061
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
7062
        if not os.path.isabs(src_path):
7063
          self.op.src_path = src_path = \
7064
            utils.PathJoin(constants.EXPORT_DIR, src_path)
7065

    
7066
  def _RunAllocator(self):
7067
    """Run the allocator based on input opcode.
7068

7069
    """
7070
    nics = [n.ToDict() for n in self.nics]
7071
    ial = IAllocator(self.cfg, self.rpc,
7072
                     mode=constants.IALLOCATOR_MODE_ALLOC,
7073
                     name=self.op.instance_name,
7074
                     disk_template=self.op.disk_template,
7075
                     tags=[],
7076
                     os=self.op.os_type,
7077
                     vcpus=self.be_full[constants.BE_VCPUS],
7078
                     mem_size=self.be_full[constants.BE_MEMORY],
7079
                     disks=self.disks,
7080
                     nics=nics,
7081
                     hypervisor=self.op.hypervisor,
7082
                     )
7083

    
7084
    ial.Run(self.op.iallocator)
7085

    
7086
    if not ial.success:
7087
      raise errors.OpPrereqError("Can't compute nodes using"
7088
                                 " iallocator '%s': %s" %
7089
                                 (self.op.iallocator, ial.info),
7090
                                 errors.ECODE_NORES)
7091
    if len(ial.result) != ial.required_nodes:
7092
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7093
                                 " of nodes (%s), required %s" %
7094
                                 (self.op.iallocator, len(ial.result),
7095
                                  ial.required_nodes), errors.ECODE_FAULT)
7096
    self.op.pnode = ial.result[0]
7097
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
7098
                 self.op.instance_name, self.op.iallocator,
7099
                 utils.CommaJoin(ial.result))
7100
    if ial.required_nodes == 2:
7101
      self.op.snode = ial.result[1]
7102

    
7103
  def BuildHooksEnv(self):
7104
    """Build hooks env.
7105

7106
    This runs on master, primary and secondary nodes of the instance.
7107

7108
    """
7109
    env = {
7110
      "ADD_MODE": self.op.mode,
7111
      }
7112
    if self.op.mode == constants.INSTANCE_IMPORT:
7113
      env["SRC_NODE"] = self.op.src_node
7114
      env["SRC_PATH"] = self.op.src_path
7115
      env["SRC_IMAGES"] = self.src_images
7116

    
7117
    env.update(_BuildInstanceHookEnv(
7118
      name=self.op.instance_name,
7119
      primary_node=self.op.pnode,
7120
      secondary_nodes=self.secondaries,
7121
      status=self.op.start,
7122
      os_type=self.op.os_type,
7123
      memory=self.be_full[constants.BE_MEMORY],
7124
      vcpus=self.be_full[constants.BE_VCPUS],
7125
      nics=_NICListToTuple(self, self.nics),
7126
      disk_template=self.op.disk_template,
7127
      disks=[(d["size"], d["mode"]) for d in self.disks],
7128
      bep=self.be_full,
7129
      hvp=self.hv_full,
7130
      hypervisor_name=self.op.hypervisor,
7131
    ))
7132

    
7133
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
7134
          self.secondaries)
7135
    return env, nl, nl
7136

    
7137
  def _ReadExportInfo(self):
7138
    """Reads the export information from disk.
7139

7140
    It will override the opcode source node and path with the actual
7141
    information, if these two were not specified before.
7142

7143
    @return: the export information
7144

7145
    """
7146
    assert self.op.mode == constants.INSTANCE_IMPORT
7147

    
7148
    src_node = self.op.src_node
7149
    src_path = self.op.src_path
7150

    
7151
    if src_node is None:
7152
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
7153
      exp_list = self.rpc.call_export_list(locked_nodes)
7154
      found = False
7155
      for node in exp_list:
7156
        if exp_list[node].fail_msg:
7157
          continue
7158
        if src_path in exp_list[node].payload:
7159
          found = True
7160
          self.op.src_node = src_node = node
7161
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
7162
                                                       src_path)
7163
          break
7164
      if not found:
7165
        raise errors.OpPrereqError("No export found for relative path %s" %
7166
                                    src_path, errors.ECODE_INVAL)
7167

    
7168
    _CheckNodeOnline(self, src_node)
7169
    result = self.rpc.call_export_info(src_node, src_path)
7170
    result.Raise("No export or invalid export found in dir %s" % src_path)
7171

    
7172
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
7173
    if not export_info.has_section(constants.INISECT_EXP):
7174
      raise errors.ProgrammerError("Corrupted export config",
7175
                                   errors.ECODE_ENVIRON)
7176

    
7177
    ei_version = export_info.get(constants.INISECT_EXP, "version")
7178
    if (int(ei_version) != constants.EXPORT_VERSION):
7179
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
7180
                                 (ei_version, constants.EXPORT_VERSION),
7181
                                 errors.ECODE_ENVIRON)
7182
    return export_info
7183

    
7184
  def _ReadExportParams(self, einfo):
7185
    """Use export parameters as defaults.
7186

7187
    In case the opcode doesn't specify (as in override) some instance
7188
    parameters, then try to use them from the export information, if
7189
    that declares them.
7190

7191
    """
7192
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
7193

    
7194
    if self.op.disk_template is None:
7195
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
7196
        self.op.disk_template = einfo.get(constants.INISECT_INS,
7197
                                          "disk_template")
7198
      else:
7199
        raise errors.OpPrereqError("No disk template specified and the export"
7200
                                   " is missing the disk_template information",
7201
                                   errors.ECODE_INVAL)
7202

    
7203
    if not self.op.disks:
7204
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
7205
        disks = []
7206
        # TODO: import the disk iv_name too
7207
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
7208
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
7209
          disks.append({"size": disk_sz})
7210
        self.op.disks = disks
7211
      else:
7212
        raise errors.OpPrereqError("No disk info specified and the export"
7213
                                   " is missing the disk information",
7214
                                   errors.ECODE_INVAL)
7215

    
7216
    if (not self.op.nics and
7217
        einfo.has_option(constants.INISECT_INS, "nic_count")):
7218
      nics = []
7219
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
7220
        ndict = {}
7221
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
7222
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
7223
          ndict[name] = v
7224
        nics.append(ndict)
7225
      self.op.nics = nics
7226

    
7227
    if (self.op.hypervisor is None and
7228
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
7229
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
7230
    if einfo.has_section(constants.INISECT_HYP):
7231
      # use the export parameters but do not override the ones
7232
      # specified by the user
7233
      for name, value in einfo.items(constants.INISECT_HYP):
7234
        if name not in self.op.hvparams:
7235
          self.op.hvparams[name] = value
7236

    
7237
    if einfo.has_section(constants.INISECT_BEP):
7238
      # use the parameters, without overriding
7239
      for name, value in einfo.items(constants.INISECT_BEP):
7240
        if name not in self.op.beparams:
7241
          self.op.beparams[name] = value
7242
    else:
7243
      # try to read the parameters old style, from the main section
7244
      for name in constants.BES_PARAMETERS:
7245
        if (name not in self.op.beparams and
7246
            einfo.has_option(constants.INISECT_INS, name)):
7247
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
7248

    
7249
    if einfo.has_section(constants.INISECT_OSP):
7250
      # use the parameters, without overriding
7251
      for name, value in einfo.items(constants.INISECT_OSP):
7252
        if name not in self.op.osparams:
7253
          self.op.osparams[name] = value
7254

    
7255
  def _RevertToDefaults(self, cluster):
7256
    """Revert the instance parameters to the default values.
7257

7258
    """
7259
    # hvparams
7260
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
7261
    for name in self.op.hvparams.keys():
7262
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
7263
        del self.op.hvparams[name]
7264
    # beparams
7265
    be_defs = cluster.SimpleFillBE({})
7266
    for name in self.op.beparams.keys():
7267
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
7268
        del self.op.beparams[name]
7269
    # nic params
7270
    nic_defs = cluster.SimpleFillNIC({})
7271
    for nic in self.op.nics:
7272
      for name in constants.NICS_PARAMETERS:
7273
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
7274
          del nic[name]
7275
    # osparams
7276
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
7277
    for name in self.op.osparams.keys():
7278
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
7279
        del self.op.osparams[name]
7280

    
7281
  def CheckPrereq(self):
7282
    """Check prerequisites.
7283

7284
    """
7285
    if self.op.mode == constants.INSTANCE_IMPORT:
7286
      export_info = self._ReadExportInfo()
7287
      self._ReadExportParams(export_info)
7288

    
7289
    _CheckDiskTemplate(self.op.disk_template)
7290

    
7291
    if (not self.cfg.GetVGName() and
7292
        self.op.disk_template not in constants.DTS_NOT_LVM):
7293
      raise errors.OpPrereqError("Cluster does not support lvm-based"
7294
                                 " instances", errors.ECODE_STATE)
7295

    
7296
    if self.op.hypervisor is None:
7297
      self.op.hypervisor = self.cfg.GetHypervisorType()
7298

    
7299
    cluster = self.cfg.GetClusterInfo()
7300
    enabled_hvs = cluster.enabled_hypervisors
7301
    if self.op.hypervisor not in enabled_hvs:
7302
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
7303
                                 " cluster (%s)" % (self.op.hypervisor,
7304
                                  ",".join(enabled_hvs)),
7305
                                 errors.ECODE_STATE)
7306

    
7307
    # check hypervisor parameter syntax (locally)
7308
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
7309
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
7310
                                      self.op.hvparams)
7311
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
7312
    hv_type.CheckParameterSyntax(filled_hvp)
7313
    self.hv_full = filled_hvp
7314
    # check that we don't specify global parameters on an instance
7315
    _CheckGlobalHvParams(self.op.hvparams)
7316

    
7317
    # fill and remember the beparams dict
7318
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
7319
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
7320

    
7321
    # build os parameters
7322
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
7323

    
7324
    # now that hvp/bep are in final format, let's reset to defaults,
7325
    # if told to do so
7326
    if self.op.identify_defaults:
7327
      self._RevertToDefaults(cluster)
7328

    
7329
    # NIC buildup
7330
    self.nics = []
7331
    for idx, nic in enumerate(self.op.nics):
7332
      nic_mode_req = nic.get("mode", None)
7333
      nic_mode = nic_mode_req
7334
      if nic_mode is None:
7335
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
7336

    
7337
      # in routed mode, for the first nic, the default ip is 'auto'
7338
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
7339
        default_ip_mode = constants.VALUE_AUTO
7340
      else:
7341
        default_ip_mode = constants.VALUE_NONE
7342

    
7343
      # ip validity checks
7344
      ip = nic.get("ip", default_ip_mode)
7345
      if ip is None or ip.lower() == constants.VALUE_NONE:
7346
        nic_ip = None
7347
      elif ip.lower() == constants.VALUE_AUTO:
7348
        if not self.op.name_check:
7349
          raise errors.OpPrereqError("IP address set to auto but name checks"
7350
                                     " have been skipped",
7351
                                     errors.ECODE_INVAL)
7352
        nic_ip = self.hostname1.ip
7353
      else:
7354
        if not netutils.IPAddress.IsValid(ip):
7355
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
7356
                                     errors.ECODE_INVAL)
7357
        nic_ip = ip
7358

    
7359
      # TODO: check the ip address for uniqueness
7360
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7361
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7362
                                   errors.ECODE_INVAL)
7363

    
7364
      # MAC address verification
7365
      mac = nic.get("mac", constants.VALUE_AUTO)
7366
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7367
        mac = utils.NormalizeAndValidateMac(mac)
7368

    
7369
        try:
7370
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7371
        except errors.ReservationError:
7372
          raise errors.OpPrereqError("MAC address %s already in use"
7373
                                     " in cluster" % mac,
7374
                                     errors.ECODE_NOTUNIQUE)
7375

    
7376
      # bridge verification
7377
      bridge = nic.get("bridge", None)
7378
      link = nic.get("link", None)
7379
      if bridge and link:
7380
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7381
                                   " at the same time", errors.ECODE_INVAL)
7382
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7383
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7384
                                   errors.ECODE_INVAL)
7385
      elif bridge:
7386
        link = bridge
7387

    
7388
      nicparams = {}
7389
      if nic_mode_req:
7390
        nicparams[constants.NIC_MODE] = nic_mode_req
7391
      if link:
7392
        nicparams[constants.NIC_LINK] = link
7393

    
7394
      check_params = cluster.SimpleFillNIC(nicparams)
7395
      objects.NIC.CheckParameterSyntax(check_params)
7396
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7397

    
7398
    # disk checks/pre-build
7399
    self.disks = []
7400
    for disk in self.op.disks:
7401
      mode = disk.get("mode", constants.DISK_RDWR)
7402
      if mode not in constants.DISK_ACCESS_SET:
7403
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7404
                                   mode, errors.ECODE_INVAL)
7405
      size = disk.get("size", None)
7406
      if size is None:
7407
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7408
      try:
7409
        size = int(size)
7410
      except (TypeError, ValueError):
7411
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7412
                                   errors.ECODE_INVAL)
7413
      vg = disk.get("vg", self.cfg.GetVGName())
7414
      new_disk = {"size": size, "mode": mode, "vg": vg}
7415
      if "adopt" in disk:
7416
        new_disk["adopt"] = disk["adopt"]
7417
      self.disks.append(new_disk)
7418

    
7419
    if self.op.mode == constants.INSTANCE_IMPORT:
7420

    
7421
      # Check that the new instance doesn't have less disks than the export
7422
      instance_disks = len(self.disks)
7423
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7424
      if instance_disks < export_disks:
7425
        raise errors.OpPrereqError("Not enough disks to import."
7426
                                   " (instance: %d, export: %d)" %
7427
                                   (instance_disks, export_disks),
7428
                                   errors.ECODE_INVAL)
7429

    
7430
      disk_images = []
7431
      for idx in range(export_disks):
7432
        option = 'disk%d_dump' % idx
7433
        if export_info.has_option(constants.INISECT_INS, option):
7434
          # FIXME: are the old os-es, disk sizes, etc. useful?
7435
          export_name = export_info.get(constants.INISECT_INS, option)
7436
          image = utils.PathJoin(self.op.src_path, export_name)
7437
          disk_images.append(image)
7438
        else:
7439
          disk_images.append(False)
7440

    
7441
      self.src_images = disk_images
7442

    
7443
      old_name = export_info.get(constants.INISECT_INS, 'name')
7444
      try:
7445
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7446
      except (TypeError, ValueError), err:
7447
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7448
                                   " an integer: %s" % str(err),
7449
                                   errors.ECODE_STATE)
7450
      if self.op.instance_name == old_name:
7451
        for idx, nic in enumerate(self.nics):
7452
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7453
            nic_mac_ini = 'nic%d_mac' % idx
7454
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7455

    
7456
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7457

    
7458
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7459
    if self.op.ip_check:
7460
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7461
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7462
                                   (self.check_ip, self.op.instance_name),
7463
                                   errors.ECODE_NOTUNIQUE)
7464

    
7465
    #### mac address generation
7466
    # By generating here the mac address both the allocator and the hooks get
7467
    # the real final mac address rather than the 'auto' or 'generate' value.
7468
    # There is a race condition between the generation and the instance object
7469
    # creation, which means that we know the mac is valid now, but we're not
7470
    # sure it will be when we actually add the instance. If things go bad
7471
    # adding the instance will abort because of a duplicate mac, and the
7472
    # creation job will fail.
7473
    for nic in self.nics:
7474
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7475
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7476

    
7477
    #### allocator run
7478

    
7479
    if self.op.iallocator is not None:
7480
      self._RunAllocator()
7481

    
7482
    #### node related checks
7483

    
7484
    # check primary node
7485
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7486
    assert self.pnode is not None, \
7487
      "Cannot retrieve locked node %s" % self.op.pnode
7488
    if pnode.offline:
7489
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7490
                                 pnode.name, errors.ECODE_STATE)
7491
    if pnode.drained:
7492
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7493
                                 pnode.name, errors.ECODE_STATE)
7494
    if not pnode.vm_capable:
7495
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
7496
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
7497

    
7498
    self.secondaries = []
7499

    
7500
    # mirror node verification
7501
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7502
      if self.op.snode == pnode.name:
7503
        raise errors.OpPrereqError("The secondary node cannot be the"
7504
                                   " primary node.", errors.ECODE_INVAL)
7505
      _CheckNodeOnline(self, self.op.snode)
7506
      _CheckNodeNotDrained(self, self.op.snode)
7507
      _CheckNodeVmCapable(self, self.op.snode)
7508
      self.secondaries.append(self.op.snode)
7509

    
7510
    nodenames = [pnode.name] + self.secondaries
7511

    
7512
    req_size = _ComputeDiskSize(self.op.disk_template,
7513
                                self.disks)
7514

    
7515
    # Check lv size requirements, if not adopting
7516
    if req_size is not None and not self.adopt_disks:
7517
      _CheckNodesFreeDisk(self, nodenames, req_size)
7518

    
7519
    if self.adopt_disks: # instead, we must check the adoption data
7520
      all_lvs = set([i["adopt"] for i in self.disks])
7521
      if len(all_lvs) != len(self.disks):
7522
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7523
                                   errors.ECODE_INVAL)
7524
      for lv_name in all_lvs:
7525
        try:
7526
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7527
        except errors.ReservationError:
7528
          raise errors.OpPrereqError("LV named %s used by another instance" %
7529
                                     lv_name, errors.ECODE_NOTUNIQUE)
7530

    
7531
      node_lvs = self.rpc.call_lv_list([pnode.name],
7532
                                       self.cfg.GetVGName())[pnode.name]
7533
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7534
      node_lvs = node_lvs.payload
7535
      delta = all_lvs.difference(node_lvs.keys())
7536
      if delta:
7537
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7538
                                   utils.CommaJoin(delta),
7539
                                   errors.ECODE_INVAL)
7540
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7541
      if online_lvs:
7542
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7543
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7544
                                   errors.ECODE_STATE)
7545
      # update the size of disk based on what is found
7546
      for dsk in self.disks:
7547
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
7548

    
7549
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7550

    
7551
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7552
    # check OS parameters (remotely)
7553
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7554

    
7555
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7556

    
7557
    # memory check on primary node
7558
    if self.op.start:
7559
      _CheckNodeFreeMemory(self, self.pnode.name,
7560
                           "creating instance %s" % self.op.instance_name,
7561
                           self.be_full[constants.BE_MEMORY],
7562
                           self.op.hypervisor)
7563

    
7564
    self.dry_run_result = list(nodenames)
7565

    
7566
  def Exec(self, feedback_fn):
7567
    """Create and add the instance to the cluster.
7568

7569
    """
7570
    instance = self.op.instance_name
7571
    pnode_name = self.pnode.name
7572

    
7573
    ht_kind = self.op.hypervisor
7574
    if ht_kind in constants.HTS_REQ_PORT:
7575
      network_port = self.cfg.AllocatePort()
7576
    else:
7577
      network_port = None
7578

    
7579
    if constants.ENABLE_FILE_STORAGE:
7580
      # this is needed because os.path.join does not accept None arguments
7581
      if self.op.file_storage_dir is None:
7582
        string_file_storage_dir = ""
7583
      else:
7584
        string_file_storage_dir = self.op.file_storage_dir
7585

    
7586
      # build the full file storage dir path
7587
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7588
                                        string_file_storage_dir, instance)
7589
    else:
7590
      file_storage_dir = ""
7591

    
7592
    disks = _GenerateDiskTemplate(self,
7593
                                  self.op.disk_template,
7594
                                  instance, pnode_name,
7595
                                  self.secondaries,
7596
                                  self.disks,
7597
                                  file_storage_dir,
7598
                                  self.op.file_driver,
7599
                                  0,
7600
                                  feedback_fn)
7601

    
7602
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7603
                            primary_node=pnode_name,
7604
                            nics=self.nics, disks=disks,
7605
                            disk_template=self.op.disk_template,
7606
                            admin_up=False,
7607
                            network_port=network_port,
7608
                            beparams=self.op.beparams,
7609
                            hvparams=self.op.hvparams,
7610
                            hypervisor=self.op.hypervisor,
7611
                            osparams=self.op.osparams,
7612
                            )
7613

    
7614
    if self.adopt_disks:
7615
      # rename LVs to the newly-generated names; we need to construct
7616
      # 'fake' LV disks with the old data, plus the new unique_id
7617
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7618
      rename_to = []
7619
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7620
        rename_to.append(t_dsk.logical_id)
7621
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7622
        self.cfg.SetDiskID(t_dsk, pnode_name)
7623
      result = self.rpc.call_blockdev_rename(pnode_name,
7624
                                             zip(tmp_disks, rename_to))
7625
      result.Raise("Failed to rename adoped LVs")
7626
    else:
7627
      feedback_fn("* creating instance disks...")
7628
      try:
7629
        _CreateDisks(self, iobj)
7630
      except errors.OpExecError:
7631
        self.LogWarning("Device creation failed, reverting...")
7632
        try:
7633
          _RemoveDisks(self, iobj)
7634
        finally:
7635
          self.cfg.ReleaseDRBDMinors(instance)
7636
          raise
7637

    
7638
      if self.cfg.GetClusterInfo().prealloc_wipe_disks:
7639
        feedback_fn("* wiping instance disks...")
7640
        try:
7641
          _WipeDisks(self, iobj)
7642
        except errors.OpExecError:
7643
          self.LogWarning("Device wiping failed, reverting...")
7644
          try:
7645
            _RemoveDisks(self, iobj)
7646
          finally:
7647
            self.cfg.ReleaseDRBDMinors(instance)
7648
            raise
7649

    
7650
    feedback_fn("adding instance %s to cluster config" % instance)
7651

    
7652
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7653

    
7654
    # Declare that we don't want to remove the instance lock anymore, as we've
7655
    # added the instance to the config
7656
    del self.remove_locks[locking.LEVEL_INSTANCE]
7657
    # Unlock all the nodes
7658
    if self.op.mode == constants.INSTANCE_IMPORT:
7659
      nodes_keep = [self.op.src_node]
7660
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7661
                       if node != self.op.src_node]
7662
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7663
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7664
    else:
7665
      self.context.glm.release(locking.LEVEL_NODE)
7666
      del self.acquired_locks[locking.LEVEL_NODE]
7667

    
7668
    if self.op.wait_for_sync:
7669
      disk_abort = not _WaitForSync(self, iobj)
7670
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7671
      # make sure the disks are not degraded (still sync-ing is ok)
7672
      time.sleep(15)
7673
      feedback_fn("* checking mirrors status")
7674
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7675
    else:
7676
      disk_abort = False
7677

    
7678
    if disk_abort:
7679
      _RemoveDisks(self, iobj)
7680
      self.cfg.RemoveInstance(iobj.name)
7681
      # Make sure the instance lock gets removed
7682
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7683
      raise errors.OpExecError("There are some degraded disks for"
7684
                               " this instance")
7685

    
7686
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7687
      if self.op.mode == constants.INSTANCE_CREATE:
7688
        if not self.op.no_install:
7689
          feedback_fn("* running the instance OS create scripts...")
7690
          # FIXME: pass debug option from opcode to backend
7691
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7692
                                                 self.op.debug_level)
7693
          result.Raise("Could not add os for instance %s"
7694
                       " on node %s" % (instance, pnode_name))
7695

    
7696
      elif self.op.mode == constants.INSTANCE_IMPORT:
7697
        feedback_fn("* running the instance OS import scripts...")
7698

    
7699
        transfers = []
7700

    
7701
        for idx, image in enumerate(self.src_images):
7702
          if not image:
7703
            continue
7704

    
7705
          # FIXME: pass debug option from opcode to backend
7706
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7707
                                             constants.IEIO_FILE, (image, ),
7708
                                             constants.IEIO_SCRIPT,
7709
                                             (iobj.disks[idx], idx),
7710
                                             None)
7711
          transfers.append(dt)
7712

    
7713
        import_result = \
7714
          masterd.instance.TransferInstanceData(self, feedback_fn,
7715
                                                self.op.src_node, pnode_name,
7716
                                                self.pnode.secondary_ip,
7717
                                                iobj, transfers)
7718
        if not compat.all(import_result):
7719
          self.LogWarning("Some disks for instance %s on node %s were not"
7720
                          " imported successfully" % (instance, pnode_name))
7721

    
7722
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7723
        feedback_fn("* preparing remote import...")
7724
        connect_timeout = constants.RIE_CONNECT_TIMEOUT
7725
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7726

    
7727
        disk_results = masterd.instance.RemoteImport(self, feedback_fn, iobj,
7728
                                                     self.source_x509_ca,
7729
                                                     self._cds, timeouts)
7730
        if not compat.all(disk_results):
7731
          # TODO: Should the instance still be started, even if some disks
7732
          # failed to import (valid for local imports, too)?
7733
          self.LogWarning("Some disks for instance %s on node %s were not"
7734
                          " imported successfully" % (instance, pnode_name))
7735

    
7736
        # Run rename script on newly imported instance
7737
        assert iobj.name == instance
7738
        feedback_fn("Running rename script for %s" % instance)
7739
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7740
                                                   self.source_instance_name,
7741
                                                   self.op.debug_level)
7742
        if result.fail_msg:
7743
          self.LogWarning("Failed to run rename script for %s on node"
7744
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7745

    
7746
      else:
7747
        # also checked in the prereq part
7748
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7749
                                     % self.op.mode)
7750

    
7751
    if self.op.start:
7752
      iobj.admin_up = True
7753
      self.cfg.Update(iobj, feedback_fn)
7754
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7755
      feedback_fn("* starting instance...")
7756
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7757
      result.Raise("Could not start instance")
7758

    
7759
    return list(iobj.all_nodes)
7760

    
7761

    
7762
class LUConnectConsole(NoHooksLU):
7763
  """Connect to an instance's console.
7764

7765
  This is somewhat special in that it returns the command line that
7766
  you need to run on the master node in order to connect to the
7767
  console.
7768

7769
  """
7770
  _OP_PARAMS = [
7771
    _PInstanceName
7772
    ]
7773
  REQ_BGL = False
7774

    
7775
  def ExpandNames(self):
7776
    self._ExpandAndLockInstance()
7777

    
7778
  def CheckPrereq(self):
7779
    """Check prerequisites.
7780

7781
    This checks that the instance is in the cluster.
7782

7783
    """
7784
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7785
    assert self.instance is not None, \
7786
      "Cannot retrieve locked instance %s" % self.op.instance_name
7787
    _CheckNodeOnline(self, self.instance.primary_node)
7788

    
7789
  def Exec(self, feedback_fn):
7790
    """Connect to the console of an instance
7791

7792
    """
7793
    instance = self.instance
7794
    node = instance.primary_node
7795

    
7796
    node_insts = self.rpc.call_instance_list([node],
7797
                                             [instance.hypervisor])[node]
7798
    node_insts.Raise("Can't get node information from %s" % node)
7799

    
7800
    if instance.name not in node_insts.payload:
7801
      if instance.admin_up:
7802
        state = "ERROR_down"
7803
      else:
7804
        state = "ADMIN_down"
7805
      raise errors.OpExecError("Instance %s is not running (state %s)" %
7806
                               (instance.name, state))
7807

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

    
7810
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
7811
    cluster = self.cfg.GetClusterInfo()
7812
    # beparams and hvparams are passed separately, to avoid editing the
7813
    # instance and then saving the defaults in the instance itself.
7814
    hvparams = cluster.FillHV(instance)
7815
    beparams = cluster.FillBE(instance)
7816
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
7817

    
7818
    # build ssh cmdline
7819
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
7820

    
7821

    
7822
class LUReplaceDisks(LogicalUnit):
7823
  """Replace the disks of an instance.
7824

7825
  """
7826
  HPATH = "mirrors-replace"
7827
  HTYPE = constants.HTYPE_INSTANCE
7828
  _OP_PARAMS = [
7829
    _PInstanceName,
7830
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES)),
7831
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt)),
7832
    ("remote_node", None, ht.TMaybeString),
7833
    ("iallocator", None, ht.TMaybeString),
7834
    ("early_release", False, ht.TBool),
7835
    ]
7836
  REQ_BGL = False
7837

    
7838
  def CheckArguments(self):
7839
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7840
                                  self.op.iallocator)
7841

    
7842
  def ExpandNames(self):
7843
    self._ExpandAndLockInstance()
7844

    
7845
    if self.op.iallocator is not None:
7846
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7847

    
7848
    elif self.op.remote_node is not None:
7849
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7850
      self.op.remote_node = remote_node
7851

    
7852
      # Warning: do not remove the locking of the new secondary here
7853
      # unless DRBD8.AddChildren is changed to work in parallel;
7854
      # currently it doesn't since parallel invocations of
7855
      # FindUnusedMinor will conflict
7856
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7857
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7858

    
7859
    else:
7860
      self.needed_locks[locking.LEVEL_NODE] = []
7861
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7862

    
7863
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7864
                                   self.op.iallocator, self.op.remote_node,
7865
                                   self.op.disks, False, self.op.early_release)
7866

    
7867
    self.tasklets = [self.replacer]
7868

    
7869
  def DeclareLocks(self, level):
7870
    # If we're not already locking all nodes in the set we have to declare the
7871
    # instance's primary/secondary nodes.
7872
    if (level == locking.LEVEL_NODE and
7873
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7874
      self._LockInstancesNodes()
7875

    
7876
  def BuildHooksEnv(self):
7877
    """Build hooks env.
7878

7879
    This runs on the master, the primary and all the secondaries.
7880

7881
    """
7882
    instance = self.replacer.instance
7883
    env = {
7884
      "MODE": self.op.mode,
7885
      "NEW_SECONDARY": self.op.remote_node,
7886
      "OLD_SECONDARY": instance.secondary_nodes[0],
7887
      }
7888
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7889
    nl = [
7890
      self.cfg.GetMasterNode(),
7891
      instance.primary_node,
7892
      ]
7893
    if self.op.remote_node is not None:
7894
      nl.append(self.op.remote_node)
7895
    return env, nl, nl
7896

    
7897

    
7898
class TLReplaceDisks(Tasklet):
7899
  """Replaces disks for an instance.
7900

7901
  Note: Locking is not within the scope of this class.
7902

7903
  """
7904
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7905
               disks, delay_iallocator, early_release):
7906
    """Initializes this class.
7907

7908
    """
7909
    Tasklet.__init__(self, lu)
7910

    
7911
    # Parameters
7912
    self.instance_name = instance_name
7913
    self.mode = mode
7914
    self.iallocator_name = iallocator_name
7915
    self.remote_node = remote_node
7916
    self.disks = disks
7917
    self.delay_iallocator = delay_iallocator
7918
    self.early_release = early_release
7919

    
7920
    # Runtime data
7921
    self.instance = None
7922
    self.new_node = None
7923
    self.target_node = None
7924
    self.other_node = None
7925
    self.remote_node_info = None
7926
    self.node_secondary_ip = None
7927

    
7928
  @staticmethod
7929
  def CheckArguments(mode, remote_node, iallocator):
7930
    """Helper function for users of this class.
7931

7932
    """
7933
    # check for valid parameter combination
7934
    if mode == constants.REPLACE_DISK_CHG:
7935
      if remote_node is None and iallocator is None:
7936
        raise errors.OpPrereqError("When changing the secondary either an"
7937
                                   " iallocator script must be used or the"
7938
                                   " new node given", errors.ECODE_INVAL)
7939

    
7940
      if remote_node is not None and iallocator is not None:
7941
        raise errors.OpPrereqError("Give either the iallocator or the new"
7942
                                   " secondary, not both", errors.ECODE_INVAL)
7943

    
7944
    elif remote_node is not None or iallocator is not None:
7945
      # Not replacing the secondary
7946
      raise errors.OpPrereqError("The iallocator and new node options can"
7947
                                 " only be used when changing the"
7948
                                 " secondary node", errors.ECODE_INVAL)
7949

    
7950
  @staticmethod
7951
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7952
    """Compute a new secondary node using an IAllocator.
7953

7954
    """
7955
    ial = IAllocator(lu.cfg, lu.rpc,
7956
                     mode=constants.IALLOCATOR_MODE_RELOC,
7957
                     name=instance_name,
7958
                     relocate_from=relocate_from)
7959

    
7960
    ial.Run(iallocator_name)
7961

    
7962
    if not ial.success:
7963
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7964
                                 " %s" % (iallocator_name, ial.info),
7965
                                 errors.ECODE_NORES)
7966

    
7967
    if len(ial.result) != ial.required_nodes:
7968
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7969
                                 " of nodes (%s), required %s" %
7970
                                 (iallocator_name,
7971
                                  len(ial.result), ial.required_nodes),
7972
                                 errors.ECODE_FAULT)
7973

    
7974
    remote_node_name = ial.result[0]
7975

    
7976
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7977
               instance_name, remote_node_name)
7978

    
7979
    return remote_node_name
7980

    
7981
  def _FindFaultyDisks(self, node_name):
7982
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7983
                                    node_name, True)
7984

    
7985
  def CheckPrereq(self):
7986
    """Check prerequisites.
7987

7988
    This checks that the instance is in the cluster.
7989

7990
    """
7991
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7992
    assert instance is not None, \
7993
      "Cannot retrieve locked instance %s" % self.instance_name
7994

    
7995
    if instance.disk_template != constants.DT_DRBD8:
7996
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7997
                                 " instances", errors.ECODE_INVAL)
7998

    
7999
    if len(instance.secondary_nodes) != 1:
8000
      raise errors.OpPrereqError("The instance has a strange layout,"
8001
                                 " expected one secondary but found %d" %
8002
                                 len(instance.secondary_nodes),
8003
                                 errors.ECODE_FAULT)
8004

    
8005
    if not self.delay_iallocator:
8006
      self._CheckPrereq2()
8007

    
8008
  def _CheckPrereq2(self):
8009
    """Check prerequisites, second part.
8010

8011
    This function should always be part of CheckPrereq. It was separated and is
8012
    now called from Exec because during node evacuation iallocator was only
8013
    called with an unmodified cluster model, not taking planned changes into
8014
    account.
8015

8016
    """
8017
    instance = self.instance
8018
    secondary_node = instance.secondary_nodes[0]
8019

    
8020
    if self.iallocator_name is None:
8021
      remote_node = self.remote_node
8022
    else:
8023
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
8024
                                       instance.name, instance.secondary_nodes)
8025

    
8026
    if remote_node is not None:
8027
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
8028
      assert self.remote_node_info is not None, \
8029
        "Cannot retrieve locked node %s" % remote_node
8030
    else:
8031
      self.remote_node_info = None
8032

    
8033
    if remote_node == self.instance.primary_node:
8034
      raise errors.OpPrereqError("The specified node is the primary node of"
8035
                                 " the instance.", errors.ECODE_INVAL)
8036

    
8037
    if remote_node == secondary_node:
8038
      raise errors.OpPrereqError("The specified node is already the"
8039
                                 " secondary node of the instance.",
8040
                                 errors.ECODE_INVAL)
8041

    
8042
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
8043
                                    constants.REPLACE_DISK_CHG):
8044
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
8045
                                 errors.ECODE_INVAL)
8046

    
8047
    if self.mode == constants.REPLACE_DISK_AUTO:
8048
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
8049
      faulty_secondary = self._FindFaultyDisks(secondary_node)
8050

    
8051
      if faulty_primary and faulty_secondary:
8052
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
8053
                                   " one node and can not be repaired"
8054
                                   " automatically" % self.instance_name,
8055
                                   errors.ECODE_STATE)
8056

    
8057
      if faulty_primary:
8058
        self.disks = faulty_primary
8059
        self.target_node = instance.primary_node
8060
        self.other_node = secondary_node
8061
        check_nodes = [self.target_node, self.other_node]
8062
      elif faulty_secondary:
8063
        self.disks = faulty_secondary
8064
        self.target_node = secondary_node
8065
        self.other_node = instance.primary_node
8066
        check_nodes = [self.target_node, self.other_node]
8067
      else:
8068
        self.disks = []
8069
        check_nodes = []
8070

    
8071
    else:
8072
      # Non-automatic modes
8073
      if self.mode == constants.REPLACE_DISK_PRI:
8074
        self.target_node = instance.primary_node
8075
        self.other_node = secondary_node
8076
        check_nodes = [self.target_node, self.other_node]
8077

    
8078
      elif self.mode == constants.REPLACE_DISK_SEC:
8079
        self.target_node = secondary_node
8080
        self.other_node = instance.primary_node
8081
        check_nodes = [self.target_node, self.other_node]
8082

    
8083
      elif self.mode == constants.REPLACE_DISK_CHG:
8084
        self.new_node = remote_node
8085
        self.other_node = instance.primary_node
8086
        self.target_node = secondary_node
8087
        check_nodes = [self.new_node, self.other_node]
8088

    
8089
        _CheckNodeNotDrained(self.lu, remote_node)
8090
        _CheckNodeVmCapable(self.lu, remote_node)
8091

    
8092
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
8093
        assert old_node_info is not None
8094
        if old_node_info.offline and not self.early_release:
8095
          # doesn't make sense to delay the release
8096
          self.early_release = True
8097
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
8098
                          " early-release mode", secondary_node)
8099

    
8100
      else:
8101
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
8102
                                     self.mode)
8103

    
8104
      # If not specified all disks should be replaced
8105
      if not self.disks:
8106
        self.disks = range(len(self.instance.disks))
8107

    
8108
    for node in check_nodes:
8109
      _CheckNodeOnline(self.lu, node)
8110

    
8111
    # Check whether disks are valid
8112
    for disk_idx in self.disks:
8113
      instance.FindDisk(disk_idx)
8114

    
8115
    # Get secondary node IP addresses
8116
    node_2nd_ip = {}
8117

    
8118
    for node_name in [self.target_node, self.other_node, self.new_node]:
8119
      if node_name is not None:
8120
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
8121

    
8122
    self.node_secondary_ip = node_2nd_ip
8123

    
8124
  def Exec(self, feedback_fn):
8125
    """Execute disk replacement.
8126

8127
    This dispatches the disk replacement to the appropriate handler.
8128

8129
    """
8130
    if self.delay_iallocator:
8131
      self._CheckPrereq2()
8132

    
8133
    if not self.disks:
8134
      feedback_fn("No disks need replacement")
8135
      return
8136

    
8137
    feedback_fn("Replacing disk(s) %s for %s" %
8138
                (utils.CommaJoin(self.disks), self.instance.name))
8139

    
8140
    activate_disks = (not self.instance.admin_up)
8141

    
8142
    # Activate the instance disks if we're replacing them on a down instance
8143
    if activate_disks:
8144
      _StartInstanceDisks(self.lu, self.instance, True)
8145

    
8146
    try:
8147
      # Should we replace the secondary node?
8148
      if self.new_node is not None:
8149
        fn = self._ExecDrbd8Secondary
8150
      else:
8151
        fn = self._ExecDrbd8DiskOnly
8152

    
8153
      return fn(feedback_fn)
8154

    
8155
    finally:
8156
      # Deactivate the instance disks if we're replacing them on a
8157
      # down instance
8158
      if activate_disks:
8159
        _SafeShutdownInstanceDisks(self.lu, self.instance)
8160

    
8161
  def _CheckVolumeGroup(self, nodes):
8162
    self.lu.LogInfo("Checking volume groups")
8163

    
8164
    vgname = self.cfg.GetVGName()
8165

    
8166
    # Make sure volume group exists on all involved nodes
8167
    results = self.rpc.call_vg_list(nodes)
8168
    if not results:
8169
      raise errors.OpExecError("Can't list volume groups on the nodes")
8170

    
8171
    for node in nodes:
8172
      res = results[node]
8173
      res.Raise("Error checking node %s" % node)
8174
      if vgname not in res.payload:
8175
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
8176
                                 (vgname, node))
8177

    
8178
  def _CheckDisksExistence(self, nodes):
8179
    # Check disk existence
8180
    for idx, dev in enumerate(self.instance.disks):
8181
      if idx not in self.disks:
8182
        continue
8183

    
8184
      for node in nodes:
8185
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
8186
        self.cfg.SetDiskID(dev, node)
8187

    
8188
        result = self.rpc.call_blockdev_find(node, dev)
8189

    
8190
        msg = result.fail_msg
8191
        if msg or not result.payload:
8192
          if not msg:
8193
            msg = "disk not found"
8194
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
8195
                                   (idx, node, msg))
8196

    
8197
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
8198
    for idx, dev in enumerate(self.instance.disks):
8199
      if idx not in self.disks:
8200
        continue
8201

    
8202
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
8203
                      (idx, node_name))
8204

    
8205
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
8206
                                   ldisk=ldisk):
8207
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
8208
                                 " replace disks for instance %s" %
8209
                                 (node_name, self.instance.name))
8210

    
8211
  def _CreateNewStorage(self, node_name):
8212
    vgname = self.cfg.GetVGName()
8213
    iv_names = {}
8214

    
8215
    for idx, dev in enumerate(self.instance.disks):
8216
      if idx not in self.disks:
8217
        continue
8218

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

    
8221
      self.cfg.SetDiskID(dev, node_name)
8222

    
8223
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
8224
      names = _GenerateUniqueNames(self.lu, lv_names)
8225

    
8226
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
8227
                             logical_id=(vgname, names[0]))
8228
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
8229
                             logical_id=(vgname, names[1]))
8230

    
8231
      new_lvs = [lv_data, lv_meta]
8232
      old_lvs = dev.children
8233
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
8234

    
8235
      # we pass force_create=True to force the LVM creation
8236
      for new_lv in new_lvs:
8237
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
8238
                        _GetInstanceInfoText(self.instance), False)
8239

    
8240
    return iv_names
8241

    
8242
  def _CheckDevices(self, node_name, iv_names):
8243
    for name, (dev, _, _) in iv_names.iteritems():
8244
      self.cfg.SetDiskID(dev, node_name)
8245

    
8246
      result = self.rpc.call_blockdev_find(node_name, dev)
8247

    
8248
      msg = result.fail_msg
8249
      if msg or not result.payload:
8250
        if not msg:
8251
          msg = "disk not found"
8252
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
8253
                                 (name, msg))
8254

    
8255
      if result.payload.is_degraded:
8256
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
8257

    
8258
  def _RemoveOldStorage(self, node_name, iv_names):
8259
    for name, (_, old_lvs, _) in iv_names.iteritems():
8260
      self.lu.LogInfo("Remove logical volumes for %s" % name)
8261

    
8262
      for lv in old_lvs:
8263
        self.cfg.SetDiskID(lv, node_name)
8264

    
8265
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
8266
        if msg:
8267
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
8268
                             hint="remove unused LVs manually")
8269

    
8270
  def _ReleaseNodeLock(self, node_name):
8271
    """Releases the lock for a given node."""
8272
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
8273

    
8274
  def _ExecDrbd8DiskOnly(self, feedback_fn):
8275
    """Replace a disk on the primary or secondary for DRBD 8.
8276

8277
    The algorithm for replace is quite complicated:
8278

8279
      1. for each disk to be replaced:
8280

8281
        1. create new LVs on the target node with unique names
8282
        1. detach old LVs from the drbd device
8283
        1. rename old LVs to name_replaced.<time_t>
8284
        1. rename new LVs to old LVs
8285
        1. attach the new LVs (with the old names now) to the drbd device
8286

8287
      1. wait for sync across all devices
8288

8289
      1. for each modified disk:
8290

8291
        1. remove old LVs (which have the name name_replaces.<time_t>)
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.other_node, self.target_node])
8301
    self._CheckVolumeGroup([self.target_node, self.other_node])
8302

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

    
8309
    # Step: create new storage
8310
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8311
    iv_names = self._CreateNewStorage(self.target_node)
8312

    
8313
    # Step: for each lv, detach+rename*2+attach
8314
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8315
    for dev, old_lvs, new_lvs in iv_names.itervalues():
8316
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
8317

    
8318
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
8319
                                                     old_lvs)
8320
      result.Raise("Can't detach drbd from local storage on node"
8321
                   " %s for device %s" % (self.target_node, dev.iv_name))
8322
      #dev.children = []
8323
      #cfg.Update(instance)
8324

    
8325
      # ok, we created the new LVs, so now we know we have the needed
8326
      # storage; as such, we proceed on the target node to rename
8327
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
8328
      # using the assumption that logical_id == physical_id (which in
8329
      # turn is the unique_id on that node)
8330

    
8331
      # FIXME(iustin): use a better name for the replaced LVs
8332
      temp_suffix = int(time.time())
8333
      ren_fn = lambda d, suff: (d.physical_id[0],
8334
                                d.physical_id[1] + "_replaced-%s" % suff)
8335

    
8336
      # Build the rename list based on what LVs exist on the node
8337
      rename_old_to_new = []
8338
      for to_ren in old_lvs:
8339
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
8340
        if not result.fail_msg and result.payload:
8341
          # device exists
8342
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
8343

    
8344
      self.lu.LogInfo("Renaming the old LVs on the target node")
8345
      result = self.rpc.call_blockdev_rename(self.target_node,
8346
                                             rename_old_to_new)
8347
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
8348

    
8349
      # Now we rename the new LVs to the old LVs
8350
      self.lu.LogInfo("Renaming the new LVs on the target node")
8351
      rename_new_to_old = [(new, old.physical_id)
8352
                           for old, new in zip(old_lvs, new_lvs)]
8353
      result = self.rpc.call_blockdev_rename(self.target_node,
8354
                                             rename_new_to_old)
8355
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
8356

    
8357
      for old, new in zip(old_lvs, new_lvs):
8358
        new.logical_id = old.logical_id
8359
        self.cfg.SetDiskID(new, self.target_node)
8360

    
8361
      for disk in old_lvs:
8362
        disk.logical_id = ren_fn(disk, temp_suffix)
8363
        self.cfg.SetDiskID(disk, self.target_node)
8364

    
8365
      # Now that the new lvs have the old name, we can add them to the device
8366
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
8367
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
8368
                                                  new_lvs)
8369
      msg = result.fail_msg
8370
      if msg:
8371
        for new_lv in new_lvs:
8372
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
8373
                                               new_lv).fail_msg
8374
          if msg2:
8375
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
8376
                               hint=("cleanup manually the unused logical"
8377
                                     "volumes"))
8378
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8379

    
8380
      dev.children = new_lvs
8381

    
8382
      self.cfg.Update(self.instance, feedback_fn)
8383

    
8384
    cstep = 5
8385
    if self.early_release:
8386
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8387
      cstep += 1
8388
      self._RemoveOldStorage(self.target_node, iv_names)
8389
      # WARNING: we release both node locks here, do not do other RPCs
8390
      # than WaitForSync to the primary node
8391
      self._ReleaseNodeLock([self.target_node, self.other_node])
8392

    
8393
    # Wait for sync
8394
    # This can fail as the old devices are degraded and _WaitForSync
8395
    # does a combined result over all disks, so we don't check its return value
8396
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8397
    cstep += 1
8398
    _WaitForSync(self.lu, self.instance)
8399

    
8400
    # Check all devices manually
8401
    self._CheckDevices(self.instance.primary_node, iv_names)
8402

    
8403
    # Step: remove old storage
8404
    if not self.early_release:
8405
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8406
      cstep += 1
8407
      self._RemoveOldStorage(self.target_node, iv_names)
8408

    
8409
  def _ExecDrbd8Secondary(self, feedback_fn):
8410
    """Replace the secondary node for DRBD 8.
8411

8412
    The algorithm for replace is quite complicated:
8413
      - for all disks of the instance:
8414
        - create new LVs on the new node with same names
8415
        - shutdown the drbd device on the old secondary
8416
        - disconnect the drbd network on the primary
8417
        - create the drbd device on the new secondary
8418
        - network attach the drbd on the primary, using an artifice:
8419
          the drbd code for Attach() will connect to the network if it
8420
          finds a device which is connected to the good local disks but
8421
          not network enabled
8422
      - wait for sync across all devices
8423
      - remove all disks from the old secondary
8424

8425
    Failures are not very well handled.
8426

8427
    """
8428
    steps_total = 6
8429

    
8430
    # Step: check device activation
8431
    self.lu.LogStep(1, steps_total, "Check device existence")
8432
    self._CheckDisksExistence([self.instance.primary_node])
8433
    self._CheckVolumeGroup([self.instance.primary_node])
8434

    
8435
    # Step: check other node consistency
8436
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8437
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8438

    
8439
    # Step: create new storage
8440
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8441
    for idx, dev in enumerate(self.instance.disks):
8442
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8443
                      (self.new_node, idx))
8444
      # we pass force_create=True to force LVM creation
8445
      for new_lv in dev.children:
8446
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8447
                        _GetInstanceInfoText(self.instance), False)
8448

    
8449
    # Step 4: dbrd minors and drbd setups changes
8450
    # after this, we must manually remove the drbd minors on both the
8451
    # error and the success paths
8452
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8453
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8454
                                         for dev in self.instance.disks],
8455
                                        self.instance.name)
8456
    logging.debug("Allocated minors %r", minors)
8457

    
8458
    iv_names = {}
8459
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8460
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8461
                      (self.new_node, idx))
8462
      # create new devices on new_node; note that we create two IDs:
8463
      # one without port, so the drbd will be activated without
8464
      # networking information on the new node at this stage, and one
8465
      # with network, for the latter activation in step 4
8466
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8467
      if self.instance.primary_node == o_node1:
8468
        p_minor = o_minor1
8469
      else:
8470
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8471
        p_minor = o_minor2
8472

    
8473
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8474
                      p_minor, new_minor, o_secret)
8475
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8476
                    p_minor, new_minor, o_secret)
8477

    
8478
      iv_names[idx] = (dev, dev.children, new_net_id)
8479
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8480
                    new_net_id)
8481
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8482
                              logical_id=new_alone_id,
8483
                              children=dev.children,
8484
                              size=dev.size)
8485
      try:
8486
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8487
                              _GetInstanceInfoText(self.instance), False)
8488
      except errors.GenericError:
8489
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8490
        raise
8491

    
8492
    # We have new devices, shutdown the drbd on the old secondary
8493
    for idx, dev in enumerate(self.instance.disks):
8494
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8495
      self.cfg.SetDiskID(dev, self.target_node)
8496
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8497
      if msg:
8498
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8499
                           "node: %s" % (idx, msg),
8500
                           hint=("Please cleanup this device manually as"
8501
                                 " soon as possible"))
8502

    
8503
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8504
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8505
                                               self.node_secondary_ip,
8506
                                               self.instance.disks)\
8507
                                              [self.instance.primary_node]
8508

    
8509
    msg = result.fail_msg
8510
    if msg:
8511
      # detaches didn't succeed (unlikely)
8512
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8513
      raise errors.OpExecError("Can't detach the disks from the network on"
8514
                               " old node: %s" % (msg,))
8515

    
8516
    # if we managed to detach at least one, we update all the disks of
8517
    # the instance to point to the new secondary
8518
    self.lu.LogInfo("Updating instance configuration")
8519
    for dev, _, new_logical_id in iv_names.itervalues():
8520
      dev.logical_id = new_logical_id
8521
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8522

    
8523
    self.cfg.Update(self.instance, feedback_fn)
8524

    
8525
    # and now perform the drbd attach
8526
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8527
                    " (standalone => connected)")
8528
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8529
                                            self.new_node],
8530
                                           self.node_secondary_ip,
8531
                                           self.instance.disks,
8532
                                           self.instance.name,
8533
                                           False)
8534
    for to_node, to_result in result.items():
8535
      msg = to_result.fail_msg
8536
      if msg:
8537
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8538
                           to_node, msg,
8539
                           hint=("please do a gnt-instance info to see the"
8540
                                 " status of disks"))
8541
    cstep = 5
8542
    if self.early_release:
8543
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8544
      cstep += 1
8545
      self._RemoveOldStorage(self.target_node, iv_names)
8546
      # WARNING: we release all node locks here, do not do other RPCs
8547
      # than WaitForSync to the primary node
8548
      self._ReleaseNodeLock([self.instance.primary_node,
8549
                             self.target_node,
8550
                             self.new_node])
8551

    
8552
    # Wait for sync
8553
    # This can fail as the old devices are degraded and _WaitForSync
8554
    # does a combined result over all disks, so we don't check its return value
8555
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8556
    cstep += 1
8557
    _WaitForSync(self.lu, self.instance)
8558

    
8559
    # Check all devices manually
8560
    self._CheckDevices(self.instance.primary_node, iv_names)
8561

    
8562
    # Step: remove old storage
8563
    if not self.early_release:
8564
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8565
      self._RemoveOldStorage(self.target_node, iv_names)
8566

    
8567

    
8568
class LURepairNodeStorage(NoHooksLU):
8569
  """Repairs the volume group on a node.
8570

8571
  """
8572
  _OP_PARAMS = [
8573
    _PNodeName,
8574
    ("storage_type", ht.NoDefault, _CheckStorageType),
8575
    ("name", ht.NoDefault, ht.TNonEmptyString),
8576
    ("ignore_consistency", False, ht.TBool),
8577
    ]
8578
  REQ_BGL = False
8579

    
8580
  def CheckArguments(self):
8581
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8582

    
8583
    storage_type = self.op.storage_type
8584

    
8585
    if (constants.SO_FIX_CONSISTENCY not in
8586
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8587
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8588
                                 " repaired" % storage_type,
8589
                                 errors.ECODE_INVAL)
8590

    
8591
  def ExpandNames(self):
8592
    self.needed_locks = {
8593
      locking.LEVEL_NODE: [self.op.node_name],
8594
      }
8595

    
8596
  def _CheckFaultyDisks(self, instance, node_name):
8597
    """Ensure faulty disks abort the opcode or at least warn."""
8598
    try:
8599
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8600
                                  node_name, True):
8601
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8602
                                   " node '%s'" % (instance.name, node_name),
8603
                                   errors.ECODE_STATE)
8604
    except errors.OpPrereqError, err:
8605
      if self.op.ignore_consistency:
8606
        self.proc.LogWarning(str(err.args[0]))
8607
      else:
8608
        raise
8609

    
8610
  def CheckPrereq(self):
8611
    """Check prerequisites.
8612

8613
    """
8614
    # Check whether any instance on this node has faulty disks
8615
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8616
      if not inst.admin_up:
8617
        continue
8618
      check_nodes = set(inst.all_nodes)
8619
      check_nodes.discard(self.op.node_name)
8620
      for inst_node_name in check_nodes:
8621
        self._CheckFaultyDisks(inst, inst_node_name)
8622

    
8623
  def Exec(self, feedback_fn):
8624
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8625
                (self.op.name, self.op.node_name))
8626

    
8627
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8628
    result = self.rpc.call_storage_execute(self.op.node_name,
8629
                                           self.op.storage_type, st_args,
8630
                                           self.op.name,
8631
                                           constants.SO_FIX_CONSISTENCY)
8632
    result.Raise("Failed to repair storage unit '%s' on %s" %
8633
                 (self.op.name, self.op.node_name))
8634

    
8635

    
8636
class LUNodeEvacuationStrategy(NoHooksLU):
8637
  """Computes the node evacuation strategy.
8638

8639
  """
8640
  _OP_PARAMS = [
8641
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
8642
    ("remote_node", None, ht.TMaybeString),
8643
    ("iallocator", None, ht.TMaybeString),
8644
    ]
8645
  REQ_BGL = False
8646

    
8647
  def CheckArguments(self):
8648
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8649

    
8650
  def ExpandNames(self):
8651
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8652
    self.needed_locks = locks = {}
8653
    if self.op.remote_node is None:
8654
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8655
    else:
8656
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8657
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8658

    
8659
  def Exec(self, feedback_fn):
8660
    if self.op.remote_node is not None:
8661
      instances = []
8662
      for node in self.op.nodes:
8663
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8664
      result = []
8665
      for i in instances:
8666
        if i.primary_node == self.op.remote_node:
8667
          raise errors.OpPrereqError("Node %s is the primary node of"
8668
                                     " instance %s, cannot use it as"
8669
                                     " secondary" %
8670
                                     (self.op.remote_node, i.name),
8671
                                     errors.ECODE_INVAL)
8672
        result.append([i.name, self.op.remote_node])
8673
    else:
8674
      ial = IAllocator(self.cfg, self.rpc,
8675
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8676
                       evac_nodes=self.op.nodes)
8677
      ial.Run(self.op.iallocator, validate=True)
8678
      if not ial.success:
8679
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8680
                                 errors.ECODE_NORES)
8681
      result = ial.result
8682
    return result
8683

    
8684

    
8685
class LUGrowDisk(LogicalUnit):
8686
  """Grow a disk of an instance.
8687

8688
  """
8689
  HPATH = "disk-grow"
8690
  HTYPE = constants.HTYPE_INSTANCE
8691
  _OP_PARAMS = [
8692
    _PInstanceName,
8693
    ("disk", ht.NoDefault, ht.TInt),
8694
    ("amount", ht.NoDefault, ht.TInt),
8695
    ("wait_for_sync", True, ht.TBool),
8696
    ]
8697
  REQ_BGL = False
8698

    
8699
  def ExpandNames(self):
8700
    self._ExpandAndLockInstance()
8701
    self.needed_locks[locking.LEVEL_NODE] = []
8702
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8703

    
8704
  def DeclareLocks(self, level):
8705
    if level == locking.LEVEL_NODE:
8706
      self._LockInstancesNodes()
8707

    
8708
  def BuildHooksEnv(self):
8709
    """Build hooks env.
8710

8711
    This runs on the master, the primary and all the secondaries.
8712

8713
    """
8714
    env = {
8715
      "DISK": self.op.disk,
8716
      "AMOUNT": self.op.amount,
8717
      }
8718
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8719
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8720
    return env, nl, nl
8721

    
8722
  def CheckPrereq(self):
8723
    """Check prerequisites.
8724

8725
    This checks that the instance is in the cluster.
8726

8727
    """
8728
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8729
    assert instance is not None, \
8730
      "Cannot retrieve locked instance %s" % self.op.instance_name
8731
    nodenames = list(instance.all_nodes)
8732
    for node in nodenames:
8733
      _CheckNodeOnline(self, node)
8734

    
8735
    self.instance = instance
8736

    
8737
    if instance.disk_template not in constants.DTS_GROWABLE:
8738
      raise errors.OpPrereqError("Instance's disk layout does not support"
8739
                                 " growing.", errors.ECODE_INVAL)
8740

    
8741
    self.disk = instance.FindDisk(self.op.disk)
8742

    
8743
    if instance.disk_template != constants.DT_FILE:
8744
      # TODO: check the free disk space for file, when that feature will be
8745
      # supported
8746
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
8747

    
8748
  def Exec(self, feedback_fn):
8749
    """Execute disk grow.
8750

8751
    """
8752
    instance = self.instance
8753
    disk = self.disk
8754

    
8755
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8756
    if not disks_ok:
8757
      raise errors.OpExecError("Cannot activate block device to grow")
8758

    
8759
    for node in instance.all_nodes:
8760
      self.cfg.SetDiskID(disk, node)
8761
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8762
      result.Raise("Grow request failed to node %s" % node)
8763

    
8764
      # TODO: Rewrite code to work properly
8765
      # DRBD goes into sync mode for a short amount of time after executing the
8766
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8767
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8768
      # time is a work-around.
8769
      time.sleep(5)
8770

    
8771
    disk.RecordGrow(self.op.amount)
8772
    self.cfg.Update(instance, feedback_fn)
8773
    if self.op.wait_for_sync:
8774
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8775
      if disk_abort:
8776
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8777
                             " status.\nPlease check the instance.")
8778
      if not instance.admin_up:
8779
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8780
    elif not instance.admin_up:
8781
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8782
                           " not supposed to be running because no wait for"
8783
                           " sync mode was requested.")
8784

    
8785

    
8786
class LUQueryInstanceData(NoHooksLU):
8787
  """Query runtime instance data.
8788

8789
  """
8790
  _OP_PARAMS = [
8791
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
8792
    ("static", False, ht.TBool),
8793
    ]
8794
  REQ_BGL = False
8795

    
8796
  def ExpandNames(self):
8797
    self.needed_locks = {}
8798
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8799

    
8800
    if self.op.instances:
8801
      self.wanted_names = []
8802
      for name in self.op.instances:
8803
        full_name = _ExpandInstanceName(self.cfg, name)
8804
        self.wanted_names.append(full_name)
8805
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8806
    else:
8807
      self.wanted_names = None
8808
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8809

    
8810
    self.needed_locks[locking.LEVEL_NODE] = []
8811
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8812

    
8813
  def DeclareLocks(self, level):
8814
    if level == locking.LEVEL_NODE:
8815
      self._LockInstancesNodes()
8816

    
8817
  def CheckPrereq(self):
8818
    """Check prerequisites.
8819

8820
    This only checks the optional instance list against the existing names.
8821

8822
    """
8823
    if self.wanted_names is None:
8824
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8825

    
8826
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8827
                             in self.wanted_names]
8828

    
8829
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8830
    """Returns the status of a block device
8831

8832
    """
8833
    if self.op.static or not node:
8834
      return None
8835

    
8836
    self.cfg.SetDiskID(dev, node)
8837

    
8838
    result = self.rpc.call_blockdev_find(node, dev)
8839
    if result.offline:
8840
      return None
8841

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

    
8844
    status = result.payload
8845
    if status is None:
8846
      return None
8847

    
8848
    return (status.dev_path, status.major, status.minor,
8849
            status.sync_percent, status.estimated_time,
8850
            status.is_degraded, status.ldisk_status)
8851

    
8852
  def _ComputeDiskStatus(self, instance, snode, dev):
8853
    """Compute block device status.
8854

8855
    """
8856
    if dev.dev_type in constants.LDS_DRBD:
8857
      # we change the snode then (otherwise we use the one passed in)
8858
      if dev.logical_id[0] == instance.primary_node:
8859
        snode = dev.logical_id[1]
8860
      else:
8861
        snode = dev.logical_id[0]
8862

    
8863
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8864
                                              instance.name, dev)
8865
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8866

    
8867
    if dev.children:
8868
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8869
                      for child in dev.children]
8870
    else:
8871
      dev_children = []
8872

    
8873
    data = {
8874
      "iv_name": dev.iv_name,
8875
      "dev_type": dev.dev_type,
8876
      "logical_id": dev.logical_id,
8877
      "physical_id": dev.physical_id,
8878
      "pstatus": dev_pstatus,
8879
      "sstatus": dev_sstatus,
8880
      "children": dev_children,
8881
      "mode": dev.mode,
8882
      "size": dev.size,
8883
      }
8884

    
8885
    return data
8886

    
8887
  def Exec(self, feedback_fn):
8888
    """Gather and return data"""
8889
    result = {}
8890

    
8891
    cluster = self.cfg.GetClusterInfo()
8892

    
8893
    for instance in self.wanted_instances:
8894
      if not self.op.static:
8895
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8896
                                                  instance.name,
8897
                                                  instance.hypervisor)
8898
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8899
        remote_info = remote_info.payload
8900
        if remote_info and "state" in remote_info:
8901
          remote_state = "up"
8902
        else:
8903
          remote_state = "down"
8904
      else:
8905
        remote_state = None
8906
      if instance.admin_up:
8907
        config_state = "up"
8908
      else:
8909
        config_state = "down"
8910

    
8911
      disks = [self._ComputeDiskStatus(instance, None, device)
8912
               for device in instance.disks]
8913

    
8914
      idict = {
8915
        "name": instance.name,
8916
        "config_state": config_state,
8917
        "run_state": remote_state,
8918
        "pnode": instance.primary_node,
8919
        "snodes": instance.secondary_nodes,
8920
        "os": instance.os,
8921
        # this happens to be the same format used for hooks
8922
        "nics": _NICListToTuple(self, instance.nics),
8923
        "disk_template": instance.disk_template,
8924
        "disks": disks,
8925
        "hypervisor": instance.hypervisor,
8926
        "network_port": instance.network_port,
8927
        "hv_instance": instance.hvparams,
8928
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8929
        "be_instance": instance.beparams,
8930
        "be_actual": cluster.FillBE(instance),
8931
        "os_instance": instance.osparams,
8932
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8933
        "serial_no": instance.serial_no,
8934
        "mtime": instance.mtime,
8935
        "ctime": instance.ctime,
8936
        "uuid": instance.uuid,
8937
        }
8938

    
8939
      result[instance.name] = idict
8940

    
8941
    return result
8942

    
8943

    
8944
class LUSetInstanceParams(LogicalUnit):
8945
  """Modifies an instances's parameters.
8946

8947
  """
8948
  HPATH = "instance-modify"
8949
  HTYPE = constants.HTYPE_INSTANCE
8950
  _OP_PARAMS = [
8951
    _PInstanceName,
8952
    ("nics", ht.EmptyList, ht.TList),
8953
    ("disks", ht.EmptyList, ht.TList),
8954
    ("beparams", ht.EmptyDict, ht.TDict),
8955
    ("hvparams", ht.EmptyDict, ht.TDict),
8956
    ("disk_template", None, ht.TMaybeString),
8957
    ("remote_node", None, ht.TMaybeString),
8958
    ("os_name", None, ht.TMaybeString),
8959
    ("force_variant", False, ht.TBool),
8960
    ("osparams", None, ht.TOr(ht.TDict, ht.TNone)),
8961
    _PForce,
8962
    ]
8963
  REQ_BGL = False
8964

    
8965
  def CheckArguments(self):
8966
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8967
            self.op.hvparams or self.op.beparams or self.op.os_name):
8968
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8969

    
8970
    if self.op.hvparams:
8971
      _CheckGlobalHvParams(self.op.hvparams)
8972

    
8973
    # Disk validation
8974
    disk_addremove = 0
8975
    for disk_op, disk_dict in self.op.disks:
8976
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8977
      if disk_op == constants.DDM_REMOVE:
8978
        disk_addremove += 1
8979
        continue
8980
      elif disk_op == constants.DDM_ADD:
8981
        disk_addremove += 1
8982
      else:
8983
        if not isinstance(disk_op, int):
8984
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8985
        if not isinstance(disk_dict, dict):
8986
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8987
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8988

    
8989
      if disk_op == constants.DDM_ADD:
8990
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8991
        if mode not in constants.DISK_ACCESS_SET:
8992
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8993
                                     errors.ECODE_INVAL)
8994
        size = disk_dict.get('size', None)
8995
        if size is None:
8996
          raise errors.OpPrereqError("Required disk parameter size missing",
8997
                                     errors.ECODE_INVAL)
8998
        try:
8999
          size = int(size)
9000
        except (TypeError, ValueError), err:
9001
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
9002
                                     str(err), errors.ECODE_INVAL)
9003
        disk_dict['size'] = size
9004
      else:
9005
        # modification of disk
9006
        if 'size' in disk_dict:
9007
          raise errors.OpPrereqError("Disk size change not possible, use"
9008
                                     " grow-disk", errors.ECODE_INVAL)
9009

    
9010
    if disk_addremove > 1:
9011
      raise errors.OpPrereqError("Only one disk add or remove operation"
9012
                                 " supported at a time", errors.ECODE_INVAL)
9013

    
9014
    if self.op.disks and self.op.disk_template is not None:
9015
      raise errors.OpPrereqError("Disk template conversion and other disk"
9016
                                 " changes not supported at the same time",
9017
                                 errors.ECODE_INVAL)
9018

    
9019
    if self.op.disk_template:
9020
      _CheckDiskTemplate(self.op.disk_template)
9021
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
9022
          self.op.remote_node is None):
9023
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
9024
                                   " one requires specifying a secondary node",
9025
                                   errors.ECODE_INVAL)
9026

    
9027
    # NIC validation
9028
    nic_addremove = 0
9029
    for nic_op, nic_dict in self.op.nics:
9030
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
9031
      if nic_op == constants.DDM_REMOVE:
9032
        nic_addremove += 1
9033
        continue
9034
      elif nic_op == constants.DDM_ADD:
9035
        nic_addremove += 1
9036
      else:
9037
        if not isinstance(nic_op, int):
9038
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
9039
        if not isinstance(nic_dict, dict):
9040
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
9041
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9042

    
9043
      # nic_dict should be a dict
9044
      nic_ip = nic_dict.get('ip', None)
9045
      if nic_ip is not None:
9046
        if nic_ip.lower() == constants.VALUE_NONE:
9047
          nic_dict['ip'] = None
9048
        else:
9049
          if not netutils.IPAddress.IsValid(nic_ip):
9050
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
9051
                                       errors.ECODE_INVAL)
9052

    
9053
      nic_bridge = nic_dict.get('bridge', None)
9054
      nic_link = nic_dict.get('link', None)
9055
      if nic_bridge and nic_link:
9056
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
9057
                                   " at the same time", errors.ECODE_INVAL)
9058
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
9059
        nic_dict['bridge'] = None
9060
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
9061
        nic_dict['link'] = None
9062

    
9063
      if nic_op == constants.DDM_ADD:
9064
        nic_mac = nic_dict.get('mac', None)
9065
        if nic_mac is None:
9066
          nic_dict['mac'] = constants.VALUE_AUTO
9067

    
9068
      if 'mac' in nic_dict:
9069
        nic_mac = nic_dict['mac']
9070
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9071
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
9072

    
9073
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
9074
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
9075
                                     " modifying an existing nic",
9076
                                     errors.ECODE_INVAL)
9077

    
9078
    if nic_addremove > 1:
9079
      raise errors.OpPrereqError("Only one NIC add or remove operation"
9080
                                 " supported at a time", errors.ECODE_INVAL)
9081

    
9082
  def ExpandNames(self):
9083
    self._ExpandAndLockInstance()
9084
    self.needed_locks[locking.LEVEL_NODE] = []
9085
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9086

    
9087
  def DeclareLocks(self, level):
9088
    if level == locking.LEVEL_NODE:
9089
      self._LockInstancesNodes()
9090
      if self.op.disk_template and self.op.remote_node:
9091
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9092
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
9093

    
9094
  def BuildHooksEnv(self):
9095
    """Build hooks env.
9096

9097
    This runs on the master, primary and secondaries.
9098

9099
    """
9100
    args = dict()
9101
    if constants.BE_MEMORY in self.be_new:
9102
      args['memory'] = self.be_new[constants.BE_MEMORY]
9103
    if constants.BE_VCPUS in self.be_new:
9104
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
9105
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
9106
    # information at all.
9107
    if self.op.nics:
9108
      args['nics'] = []
9109
      nic_override = dict(self.op.nics)
9110
      for idx, nic in enumerate(self.instance.nics):
9111
        if idx in nic_override:
9112
          this_nic_override = nic_override[idx]
9113
        else:
9114
          this_nic_override = {}
9115
        if 'ip' in this_nic_override:
9116
          ip = this_nic_override['ip']
9117
        else:
9118
          ip = nic.ip
9119
        if 'mac' in this_nic_override:
9120
          mac = this_nic_override['mac']
9121
        else:
9122
          mac = nic.mac
9123
        if idx in self.nic_pnew:
9124
          nicparams = self.nic_pnew[idx]
9125
        else:
9126
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
9127
        mode = nicparams[constants.NIC_MODE]
9128
        link = nicparams[constants.NIC_LINK]
9129
        args['nics'].append((ip, mac, mode, link))
9130
      if constants.DDM_ADD in nic_override:
9131
        ip = nic_override[constants.DDM_ADD].get('ip', None)
9132
        mac = nic_override[constants.DDM_ADD]['mac']
9133
        nicparams = self.nic_pnew[constants.DDM_ADD]
9134
        mode = nicparams[constants.NIC_MODE]
9135
        link = nicparams[constants.NIC_LINK]
9136
        args['nics'].append((ip, mac, mode, link))
9137
      elif constants.DDM_REMOVE in nic_override:
9138
        del args['nics'][-1]
9139

    
9140
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
9141
    if self.op.disk_template:
9142
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
9143
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9144
    return env, nl, nl
9145

    
9146
  def CheckPrereq(self):
9147
    """Check prerequisites.
9148

9149
    This only checks the instance list against the existing names.
9150

9151
    """
9152
    # checking the new params on the primary/secondary nodes
9153

    
9154
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9155
    cluster = self.cluster = self.cfg.GetClusterInfo()
9156
    assert self.instance is not None, \
9157
      "Cannot retrieve locked instance %s" % self.op.instance_name
9158
    pnode = instance.primary_node
9159
    nodelist = list(instance.all_nodes)
9160

    
9161
    # OS change
9162
    if self.op.os_name and not self.op.force:
9163
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
9164
                      self.op.force_variant)
9165
      instance_os = self.op.os_name
9166
    else:
9167
      instance_os = instance.os
9168

    
9169
    if self.op.disk_template:
9170
      if instance.disk_template == self.op.disk_template:
9171
        raise errors.OpPrereqError("Instance already has disk template %s" %
9172
                                   instance.disk_template, errors.ECODE_INVAL)
9173

    
9174
      if (instance.disk_template,
9175
          self.op.disk_template) not in self._DISK_CONVERSIONS:
9176
        raise errors.OpPrereqError("Unsupported disk template conversion from"
9177
                                   " %s to %s" % (instance.disk_template,
9178
                                                  self.op.disk_template),
9179
                                   errors.ECODE_INVAL)
9180
      _CheckInstanceDown(self, instance, "cannot change disk template")
9181
      if self.op.disk_template in constants.DTS_NET_MIRROR:
9182
        if self.op.remote_node == pnode:
9183
          raise errors.OpPrereqError("Given new secondary node %s is the same"
9184
                                     " as the primary node of the instance" %
9185
                                     self.op.remote_node, errors.ECODE_STATE)
9186
        _CheckNodeOnline(self, self.op.remote_node)
9187
        _CheckNodeNotDrained(self, self.op.remote_node)
9188
        disks = [{"size": d.size} for d in instance.disks]
9189
        required = _ComputeDiskSize(self.op.disk_template, disks)
9190
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
9191

    
9192
    # hvparams processing
9193
    if self.op.hvparams:
9194
      hv_type = instance.hypervisor
9195
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
9196
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
9197
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
9198

    
9199
      # local check
9200
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
9201
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
9202
      self.hv_new = hv_new # the new actual values
9203
      self.hv_inst = i_hvdict # the new dict (without defaults)
9204
    else:
9205
      self.hv_new = self.hv_inst = {}
9206

    
9207
    # beparams processing
9208
    if self.op.beparams:
9209
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
9210
                                   use_none=True)
9211
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
9212
      be_new = cluster.SimpleFillBE(i_bedict)
9213
      self.be_new = be_new # the new actual values
9214
      self.be_inst = i_bedict # the new dict (without defaults)
9215
    else:
9216
      self.be_new = self.be_inst = {}
9217

    
9218
    # osparams processing
9219
    if self.op.osparams:
9220
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
9221
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
9222
      self.os_inst = i_osdict # the new dict (without defaults)
9223
    else:
9224
      self.os_inst = {}
9225

    
9226
    self.warn = []
9227

    
9228
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
9229
      mem_check_list = [pnode]
9230
      if be_new[constants.BE_AUTO_BALANCE]:
9231
        # either we changed auto_balance to yes or it was from before
9232
        mem_check_list.extend(instance.secondary_nodes)
9233
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
9234
                                                  instance.hypervisor)
9235
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
9236
                                         instance.hypervisor)
9237
      pninfo = nodeinfo[pnode]
9238
      msg = pninfo.fail_msg
9239
      if msg:
9240
        # Assume the primary node is unreachable and go ahead
9241
        self.warn.append("Can't get info from primary node %s: %s" %
9242
                         (pnode,  msg))
9243
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
9244
        self.warn.append("Node data from primary node %s doesn't contain"
9245
                         " free memory information" % pnode)
9246
      elif instance_info.fail_msg:
9247
        self.warn.append("Can't get instance runtime information: %s" %
9248
                        instance_info.fail_msg)
9249
      else:
9250
        if instance_info.payload:
9251
          current_mem = int(instance_info.payload['memory'])
9252
        else:
9253
          # Assume instance not running
9254
          # (there is a slight race condition here, but it's not very probable,
9255
          # and we have no other way to check)
9256
          current_mem = 0
9257
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
9258
                    pninfo.payload['memory_free'])
9259
        if miss_mem > 0:
9260
          raise errors.OpPrereqError("This change will prevent the instance"
9261
                                     " from starting, due to %d MB of memory"
9262
                                     " missing on its primary node" % miss_mem,
9263
                                     errors.ECODE_NORES)
9264

    
9265
      if be_new[constants.BE_AUTO_BALANCE]:
9266
        for node, nres in nodeinfo.items():
9267
          if node not in instance.secondary_nodes:
9268
            continue
9269
          msg = nres.fail_msg
9270
          if msg:
9271
            self.warn.append("Can't get info from secondary node %s: %s" %
9272
                             (node, msg))
9273
          elif not isinstance(nres.payload.get('memory_free', None), int):
9274
            self.warn.append("Secondary node %s didn't return free"
9275
                             " memory information" % node)
9276
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
9277
            self.warn.append("Not enough memory to failover instance to"
9278
                             " secondary node %s" % node)
9279

    
9280
    # NIC processing
9281
    self.nic_pnew = {}
9282
    self.nic_pinst = {}
9283
    for nic_op, nic_dict in self.op.nics:
9284
      if nic_op == constants.DDM_REMOVE:
9285
        if not instance.nics:
9286
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
9287
                                     errors.ECODE_INVAL)
9288
        continue
9289
      if nic_op != constants.DDM_ADD:
9290
        # an existing nic
9291
        if not instance.nics:
9292
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
9293
                                     " no NICs" % nic_op,
9294
                                     errors.ECODE_INVAL)
9295
        if nic_op < 0 or nic_op >= len(instance.nics):
9296
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
9297
                                     " are 0 to %d" %
9298
                                     (nic_op, len(instance.nics) - 1),
9299
                                     errors.ECODE_INVAL)
9300
        old_nic_params = instance.nics[nic_op].nicparams
9301
        old_nic_ip = instance.nics[nic_op].ip
9302
      else:
9303
        old_nic_params = {}
9304
        old_nic_ip = None
9305

    
9306
      update_params_dict = dict([(key, nic_dict[key])
9307
                                 for key in constants.NICS_PARAMETERS
9308
                                 if key in nic_dict])
9309

    
9310
      if 'bridge' in nic_dict:
9311
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
9312

    
9313
      new_nic_params = _GetUpdatedParams(old_nic_params,
9314
                                         update_params_dict)
9315
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
9316
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
9317
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
9318
      self.nic_pinst[nic_op] = new_nic_params
9319
      self.nic_pnew[nic_op] = new_filled_nic_params
9320
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
9321

    
9322
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
9323
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
9324
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
9325
        if msg:
9326
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
9327
          if self.op.force:
9328
            self.warn.append(msg)
9329
          else:
9330
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
9331
      if new_nic_mode == constants.NIC_MODE_ROUTED:
9332
        if 'ip' in nic_dict:
9333
          nic_ip = nic_dict['ip']
9334
        else:
9335
          nic_ip = old_nic_ip
9336
        if nic_ip is None:
9337
          raise errors.OpPrereqError('Cannot set the nic ip to None'
9338
                                     ' on a routed nic', errors.ECODE_INVAL)
9339
      if 'mac' in nic_dict:
9340
        nic_mac = nic_dict['mac']
9341
        if nic_mac is None:
9342
          raise errors.OpPrereqError('Cannot set the nic mac to None',
9343
                                     errors.ECODE_INVAL)
9344
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9345
          # otherwise generate the mac
9346
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
9347
        else:
9348
          # or validate/reserve the current one
9349
          try:
9350
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
9351
          except errors.ReservationError:
9352
            raise errors.OpPrereqError("MAC address %s already in use"
9353
                                       " in cluster" % nic_mac,
9354
                                       errors.ECODE_NOTUNIQUE)
9355

    
9356
    # DISK processing
9357
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
9358
      raise errors.OpPrereqError("Disk operations not supported for"
9359
                                 " diskless instances",
9360
                                 errors.ECODE_INVAL)
9361
    for disk_op, _ in self.op.disks:
9362
      if disk_op == constants.DDM_REMOVE:
9363
        if len(instance.disks) == 1:
9364
          raise errors.OpPrereqError("Cannot remove the last disk of"
9365
                                     " an instance", errors.ECODE_INVAL)
9366
        _CheckInstanceDown(self, instance, "cannot remove disks")
9367

    
9368
      if (disk_op == constants.DDM_ADD and
9369
          len(instance.nics) >= constants.MAX_DISKS):
9370
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
9371
                                   " add more" % constants.MAX_DISKS,
9372
                                   errors.ECODE_STATE)
9373
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
9374
        # an existing disk
9375
        if disk_op < 0 or disk_op >= len(instance.disks):
9376
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9377
                                     " are 0 to %d" %
9378
                                     (disk_op, len(instance.disks)),
9379
                                     errors.ECODE_INVAL)
9380

    
9381
    return
9382

    
9383
  def _ConvertPlainToDrbd(self, feedback_fn):
9384
    """Converts an instance from plain to drbd.
9385

9386
    """
9387
    feedback_fn("Converting template to drbd")
9388
    instance = self.instance
9389
    pnode = instance.primary_node
9390
    snode = self.op.remote_node
9391

    
9392
    # create a fake disk info for _GenerateDiskTemplate
9393
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
9394
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9395
                                      instance.name, pnode, [snode],
9396
                                      disk_info, None, None, 0, feedback_fn)
9397
    info = _GetInstanceInfoText(instance)
9398
    feedback_fn("Creating aditional volumes...")
9399
    # first, create the missing data and meta devices
9400
    for disk in new_disks:
9401
      # unfortunately this is... not too nice
9402
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9403
                            info, True)
9404
      for child in disk.children:
9405
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9406
    # at this stage, all new LVs have been created, we can rename the
9407
    # old ones
9408
    feedback_fn("Renaming original volumes...")
9409
    rename_list = [(o, n.children[0].logical_id)
9410
                   for (o, n) in zip(instance.disks, new_disks)]
9411
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9412
    result.Raise("Failed to rename original LVs")
9413

    
9414
    feedback_fn("Initializing DRBD devices...")
9415
    # all child devices are in place, we can now create the DRBD devices
9416
    for disk in new_disks:
9417
      for node in [pnode, snode]:
9418
        f_create = node == pnode
9419
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9420

    
9421
    # at this point, the instance has been modified
9422
    instance.disk_template = constants.DT_DRBD8
9423
    instance.disks = new_disks
9424
    self.cfg.Update(instance, feedback_fn)
9425

    
9426
    # disks are created, waiting for sync
9427
    disk_abort = not _WaitForSync(self, instance)
9428
    if disk_abort:
9429
      raise errors.OpExecError("There are some degraded disks for"
9430
                               " this instance, please cleanup manually")
9431

    
9432
  def _ConvertDrbdToPlain(self, feedback_fn):
9433
    """Converts an instance from drbd to plain.
9434

9435
    """
9436
    instance = self.instance
9437
    assert len(instance.secondary_nodes) == 1
9438
    pnode = instance.primary_node
9439
    snode = instance.secondary_nodes[0]
9440
    feedback_fn("Converting template to plain")
9441

    
9442
    old_disks = instance.disks
9443
    new_disks = [d.children[0] for d in old_disks]
9444

    
9445
    # copy over size and mode
9446
    for parent, child in zip(old_disks, new_disks):
9447
      child.size = parent.size
9448
      child.mode = parent.mode
9449

    
9450
    # update instance structure
9451
    instance.disks = new_disks
9452
    instance.disk_template = constants.DT_PLAIN
9453
    self.cfg.Update(instance, feedback_fn)
9454

    
9455
    feedback_fn("Removing volumes on the secondary node...")
9456
    for disk in old_disks:
9457
      self.cfg.SetDiskID(disk, snode)
9458
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9459
      if msg:
9460
        self.LogWarning("Could not remove block device %s on node %s,"
9461
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9462

    
9463
    feedback_fn("Removing unneeded volumes on the primary node...")
9464
    for idx, disk in enumerate(old_disks):
9465
      meta = disk.children[1]
9466
      self.cfg.SetDiskID(meta, pnode)
9467
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9468
      if msg:
9469
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9470
                        " continuing anyway: %s", idx, pnode, msg)
9471

    
9472

    
9473
  def Exec(self, feedback_fn):
9474
    """Modifies an instance.
9475

9476
    All parameters take effect only at the next restart of the instance.
9477

9478
    """
9479
    # Process here the warnings from CheckPrereq, as we don't have a
9480
    # feedback_fn there.
9481
    for warn in self.warn:
9482
      feedback_fn("WARNING: %s" % warn)
9483

    
9484
    result = []
9485
    instance = self.instance
9486
    # disk changes
9487
    for disk_op, disk_dict in self.op.disks:
9488
      if disk_op == constants.DDM_REMOVE:
9489
        # remove the last disk
9490
        device = instance.disks.pop()
9491
        device_idx = len(instance.disks)
9492
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9493
          self.cfg.SetDiskID(disk, node)
9494
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9495
          if msg:
9496
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9497
                            " continuing anyway", device_idx, node, msg)
9498
        result.append(("disk/%d" % device_idx, "remove"))
9499
      elif disk_op == constants.DDM_ADD:
9500
        # add a new disk
9501
        if instance.disk_template == constants.DT_FILE:
9502
          file_driver, file_path = instance.disks[0].logical_id
9503
          file_path = os.path.dirname(file_path)
9504
        else:
9505
          file_driver = file_path = None
9506
        disk_idx_base = len(instance.disks)
9507
        new_disk = _GenerateDiskTemplate(self,
9508
                                         instance.disk_template,
9509
                                         instance.name, instance.primary_node,
9510
                                         instance.secondary_nodes,
9511
                                         [disk_dict],
9512
                                         file_path,
9513
                                         file_driver,
9514
                                         disk_idx_base, feedback_fn)[0]
9515
        instance.disks.append(new_disk)
9516
        info = _GetInstanceInfoText(instance)
9517

    
9518
        logging.info("Creating volume %s for instance %s",
9519
                     new_disk.iv_name, instance.name)
9520
        # Note: this needs to be kept in sync with _CreateDisks
9521
        #HARDCODE
9522
        for node in instance.all_nodes:
9523
          f_create = node == instance.primary_node
9524
          try:
9525
            _CreateBlockDev(self, node, instance, new_disk,
9526
                            f_create, info, f_create)
9527
          except errors.OpExecError, err:
9528
            self.LogWarning("Failed to create volume %s (%s) on"
9529
                            " node %s: %s",
9530
                            new_disk.iv_name, new_disk, node, err)
9531
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9532
                       (new_disk.size, new_disk.mode)))
9533
      else:
9534
        # change a given disk
9535
        instance.disks[disk_op].mode = disk_dict['mode']
9536
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9537

    
9538
    if self.op.disk_template:
9539
      r_shut = _ShutdownInstanceDisks(self, instance)
9540
      if not r_shut:
9541
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
9542
                                 " proceed with disk template conversion")
9543
      mode = (instance.disk_template, self.op.disk_template)
9544
      try:
9545
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9546
      except:
9547
        self.cfg.ReleaseDRBDMinors(instance.name)
9548
        raise
9549
      result.append(("disk_template", self.op.disk_template))
9550

    
9551
    # NIC changes
9552
    for nic_op, nic_dict in self.op.nics:
9553
      if nic_op == constants.DDM_REMOVE:
9554
        # remove the last nic
9555
        del instance.nics[-1]
9556
        result.append(("nic.%d" % len(instance.nics), "remove"))
9557
      elif nic_op == constants.DDM_ADD:
9558
        # mac and bridge should be set, by now
9559
        mac = nic_dict['mac']
9560
        ip = nic_dict.get('ip', None)
9561
        nicparams = self.nic_pinst[constants.DDM_ADD]
9562
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9563
        instance.nics.append(new_nic)
9564
        result.append(("nic.%d" % (len(instance.nics) - 1),
9565
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9566
                       (new_nic.mac, new_nic.ip,
9567
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9568
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9569
                       )))
9570
      else:
9571
        for key in 'mac', 'ip':
9572
          if key in nic_dict:
9573
            setattr(instance.nics[nic_op], key, nic_dict[key])
9574
        if nic_op in self.nic_pinst:
9575
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9576
        for key, val in nic_dict.iteritems():
9577
          result.append(("nic.%s/%d" % (key, nic_op), val))
9578

    
9579
    # hvparams changes
9580
    if self.op.hvparams:
9581
      instance.hvparams = self.hv_inst
9582
      for key, val in self.op.hvparams.iteritems():
9583
        result.append(("hv/%s" % key, val))
9584

    
9585
    # beparams changes
9586
    if self.op.beparams:
9587
      instance.beparams = self.be_inst
9588
      for key, val in self.op.beparams.iteritems():
9589
        result.append(("be/%s" % key, val))
9590

    
9591
    # OS change
9592
    if self.op.os_name:
9593
      instance.os = self.op.os_name
9594

    
9595
    # osparams changes
9596
    if self.op.osparams:
9597
      instance.osparams = self.os_inst
9598
      for key, val in self.op.osparams.iteritems():
9599
        result.append(("os/%s" % key, val))
9600

    
9601
    self.cfg.Update(instance, feedback_fn)
9602

    
9603
    return result
9604

    
9605
  _DISK_CONVERSIONS = {
9606
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9607
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9608
    }
9609

    
9610

    
9611
class LUQueryExports(NoHooksLU):
9612
  """Query the exports list
9613

9614
  """
9615
  _OP_PARAMS = [
9616
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
9617
    ("use_locking", False, ht.TBool),
9618
    ]
9619
  REQ_BGL = False
9620

    
9621
  def ExpandNames(self):
9622
    self.needed_locks = {}
9623
    self.share_locks[locking.LEVEL_NODE] = 1
9624
    if not self.op.nodes:
9625
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9626
    else:
9627
      self.needed_locks[locking.LEVEL_NODE] = \
9628
        _GetWantedNodes(self, self.op.nodes)
9629

    
9630
  def Exec(self, feedback_fn):
9631
    """Compute the list of all the exported system images.
9632

9633
    @rtype: dict
9634
    @return: a dictionary with the structure node->(export-list)
9635
        where export-list is a list of the instances exported on
9636
        that node.
9637

9638
    """
9639
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9640
    rpcresult = self.rpc.call_export_list(self.nodes)
9641
    result = {}
9642
    for node in rpcresult:
9643
      if rpcresult[node].fail_msg:
9644
        result[node] = False
9645
      else:
9646
        result[node] = rpcresult[node].payload
9647

    
9648
    return result
9649

    
9650

    
9651
class LUPrepareExport(NoHooksLU):
9652
  """Prepares an instance for an export and returns useful information.
9653

9654
  """
9655
  _OP_PARAMS = [
9656
    _PInstanceName,
9657
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES)),
9658
    ]
9659
  REQ_BGL = False
9660

    
9661
  def ExpandNames(self):
9662
    self._ExpandAndLockInstance()
9663

    
9664
  def CheckPrereq(self):
9665
    """Check prerequisites.
9666

9667
    """
9668
    instance_name = self.op.instance_name
9669

    
9670
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9671
    assert self.instance is not None, \
9672
          "Cannot retrieve locked instance %s" % self.op.instance_name
9673
    _CheckNodeOnline(self, self.instance.primary_node)
9674

    
9675
    self._cds = _GetClusterDomainSecret()
9676

    
9677
  def Exec(self, feedback_fn):
9678
    """Prepares an instance for an export.
9679

9680
    """
9681
    instance = self.instance
9682

    
9683
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9684
      salt = utils.GenerateSecret(8)
9685

    
9686
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9687
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9688
                                              constants.RIE_CERT_VALIDITY)
9689
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9690

    
9691
      (name, cert_pem) = result.payload
9692

    
9693
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9694
                                             cert_pem)
9695

    
9696
      return {
9697
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9698
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9699
                          salt),
9700
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9701
        }
9702

    
9703
    return None
9704

    
9705

    
9706
class LUExportInstance(LogicalUnit):
9707
  """Export an instance to an image in the cluster.
9708

9709
  """
9710
  HPATH = "instance-export"
9711
  HTYPE = constants.HTYPE_INSTANCE
9712
  _OP_PARAMS = [
9713
    _PInstanceName,
9714
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList)),
9715
    ("shutdown", True, ht.TBool),
9716
    _PShutdownTimeout,
9717
    ("remove_instance", False, ht.TBool),
9718
    ("ignore_remove_failures", False, ht.TBool),
9719
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES)),
9720
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone)),
9721
    ("destination_x509_ca", None, ht.TMaybeString),
9722
    ]
9723
  REQ_BGL = False
9724

    
9725
  def CheckArguments(self):
9726
    """Check the arguments.
9727

9728
    """
9729
    self.x509_key_name = self.op.x509_key_name
9730
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9731

    
9732
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9733
      if not self.x509_key_name:
9734
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9735
                                   errors.ECODE_INVAL)
9736

    
9737
      if not self.dest_x509_ca_pem:
9738
        raise errors.OpPrereqError("Missing destination X509 CA",
9739
                                   errors.ECODE_INVAL)
9740

    
9741
  def ExpandNames(self):
9742
    self._ExpandAndLockInstance()
9743

    
9744
    # Lock all nodes for local exports
9745
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9746
      # FIXME: lock only instance primary and destination node
9747
      #
9748
      # Sad but true, for now we have do lock all nodes, as we don't know where
9749
      # the previous export might be, and in this LU we search for it and
9750
      # remove it from its current node. In the future we could fix this by:
9751
      #  - making a tasklet to search (share-lock all), then create the
9752
      #    new one, then one to remove, after
9753
      #  - removing the removal operation altogether
9754
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9755

    
9756
  def DeclareLocks(self, level):
9757
    """Last minute lock declaration."""
9758
    # All nodes are locked anyway, so nothing to do here.
9759

    
9760
  def BuildHooksEnv(self):
9761
    """Build hooks env.
9762

9763
    This will run on the master, primary node and target node.
9764

9765
    """
9766
    env = {
9767
      "EXPORT_MODE": self.op.mode,
9768
      "EXPORT_NODE": self.op.target_node,
9769
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9770
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9771
      # TODO: Generic function for boolean env variables
9772
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9773
      }
9774

    
9775
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9776

    
9777
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9778

    
9779
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9780
      nl.append(self.op.target_node)
9781

    
9782
    return env, nl, nl
9783

    
9784
  def CheckPrereq(self):
9785
    """Check prerequisites.
9786

9787
    This checks that the instance and node names are valid.
9788

9789
    """
9790
    instance_name = self.op.instance_name
9791

    
9792
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9793
    assert self.instance is not None, \
9794
          "Cannot retrieve locked instance %s" % self.op.instance_name
9795
    _CheckNodeOnline(self, self.instance.primary_node)
9796

    
9797
    if (self.op.remove_instance and self.instance.admin_up and
9798
        not self.op.shutdown):
9799
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9800
                                 " down before")
9801

    
9802
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9803
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9804
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9805
      assert self.dst_node is not None
9806

    
9807
      _CheckNodeOnline(self, self.dst_node.name)
9808
      _CheckNodeNotDrained(self, self.dst_node.name)
9809

    
9810
      self._cds = None
9811
      self.dest_disk_info = None
9812
      self.dest_x509_ca = None
9813

    
9814
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9815
      self.dst_node = None
9816

    
9817
      if len(self.op.target_node) != len(self.instance.disks):
9818
        raise errors.OpPrereqError(("Received destination information for %s"
9819
                                    " disks, but instance %s has %s disks") %
9820
                                   (len(self.op.target_node), instance_name,
9821
                                    len(self.instance.disks)),
9822
                                   errors.ECODE_INVAL)
9823

    
9824
      cds = _GetClusterDomainSecret()
9825

    
9826
      # Check X509 key name
9827
      try:
9828
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9829
      except (TypeError, ValueError), err:
9830
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9831

    
9832
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9833
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9834
                                   errors.ECODE_INVAL)
9835

    
9836
      # Load and verify CA
9837
      try:
9838
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9839
      except OpenSSL.crypto.Error, err:
9840
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9841
                                   (err, ), errors.ECODE_INVAL)
9842

    
9843
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9844
      if errcode is not None:
9845
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9846
                                   (msg, ), errors.ECODE_INVAL)
9847

    
9848
      self.dest_x509_ca = cert
9849

    
9850
      # Verify target information
9851
      disk_info = []
9852
      for idx, disk_data in enumerate(self.op.target_node):
9853
        try:
9854
          (host, port, magic) = \
9855
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9856
        except errors.GenericError, err:
9857
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9858
                                     (idx, err), errors.ECODE_INVAL)
9859

    
9860
        disk_info.append((host, port, magic))
9861

    
9862
      assert len(disk_info) == len(self.op.target_node)
9863
      self.dest_disk_info = disk_info
9864

    
9865
    else:
9866
      raise errors.ProgrammerError("Unhandled export mode %r" %
9867
                                   self.op.mode)
9868

    
9869
    # instance disk type verification
9870
    # TODO: Implement export support for file-based disks
9871
    for disk in self.instance.disks:
9872
      if disk.dev_type == constants.LD_FILE:
9873
        raise errors.OpPrereqError("Export not supported for instances with"
9874
                                   " file-based disks", errors.ECODE_INVAL)
9875

    
9876
  def _CleanupExports(self, feedback_fn):
9877
    """Removes exports of current instance from all other nodes.
9878

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

9882
    """
9883
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9884

    
9885
    nodelist = self.cfg.GetNodeList()
9886
    nodelist.remove(self.dst_node.name)
9887

    
9888
    # on one-node clusters nodelist will be empty after the removal
9889
    # if we proceed the backup would be removed because OpQueryExports
9890
    # substitutes an empty list with the full cluster node list.
9891
    iname = self.instance.name
9892
    if nodelist:
9893
      feedback_fn("Removing old exports for instance %s" % iname)
9894
      exportlist = self.rpc.call_export_list(nodelist)
9895
      for node in exportlist:
9896
        if exportlist[node].fail_msg:
9897
          continue
9898
        if iname in exportlist[node].payload:
9899
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9900
          if msg:
9901
            self.LogWarning("Could not remove older export for instance %s"
9902
                            " on node %s: %s", iname, node, msg)
9903

    
9904
  def Exec(self, feedback_fn):
9905
    """Export an instance to an image in the cluster.
9906

9907
    """
9908
    assert self.op.mode in constants.EXPORT_MODES
9909

    
9910
    instance = self.instance
9911
    src_node = instance.primary_node
9912

    
9913
    if self.op.shutdown:
9914
      # shutdown the instance, but not the disks
9915
      feedback_fn("Shutting down instance %s" % instance.name)
9916
      result = self.rpc.call_instance_shutdown(src_node, instance,
9917
                                               self.op.shutdown_timeout)
9918
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9919
      result.Raise("Could not shutdown instance %s on"
9920
                   " node %s" % (instance.name, src_node))
9921

    
9922
    # set the disks ID correctly since call_instance_start needs the
9923
    # correct drbd minor to create the symlinks
9924
    for disk in instance.disks:
9925
      self.cfg.SetDiskID(disk, src_node)
9926

    
9927
    activate_disks = (not instance.admin_up)
9928

    
9929
    if activate_disks:
9930
      # Activate the instance disks if we'exporting a stopped instance
9931
      feedback_fn("Activating disks for %s" % instance.name)
9932
      _StartInstanceDisks(self, instance, None)
9933

    
9934
    try:
9935
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9936
                                                     instance)
9937

    
9938
      helper.CreateSnapshots()
9939
      try:
9940
        if (self.op.shutdown and instance.admin_up and
9941
            not self.op.remove_instance):
9942
          assert not activate_disks
9943
          feedback_fn("Starting instance %s" % instance.name)
9944
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9945
          msg = result.fail_msg
9946
          if msg:
9947
            feedback_fn("Failed to start instance: %s" % msg)
9948
            _ShutdownInstanceDisks(self, instance)
9949
            raise errors.OpExecError("Could not start instance: %s" % msg)
9950

    
9951
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9952
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9953
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9954
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9955
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9956

    
9957
          (key_name, _, _) = self.x509_key_name
9958

    
9959
          dest_ca_pem = \
9960
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9961
                                            self.dest_x509_ca)
9962

    
9963
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9964
                                                     key_name, dest_ca_pem,
9965
                                                     timeouts)
9966
      finally:
9967
        helper.Cleanup()
9968

    
9969
      # Check for backwards compatibility
9970
      assert len(dresults) == len(instance.disks)
9971
      assert compat.all(isinstance(i, bool) for i in dresults), \
9972
             "Not all results are boolean: %r" % dresults
9973

    
9974
    finally:
9975
      if activate_disks:
9976
        feedback_fn("Deactivating disks for %s" % instance.name)
9977
        _ShutdownInstanceDisks(self, instance)
9978

    
9979
    if not (compat.all(dresults) and fin_resu):
9980
      failures = []
9981
      if not fin_resu:
9982
        failures.append("export finalization")
9983
      if not compat.all(dresults):
9984
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
9985
                               if not dsk)
9986
        failures.append("disk export: disk(s) %s" % fdsk)
9987

    
9988
      raise errors.OpExecError("Export failed, errors in %s" %
9989
                               utils.CommaJoin(failures))
9990

    
9991
    # At this point, the export was successful, we can cleanup/finish
9992

    
9993
    # Remove instance if requested
9994
    if self.op.remove_instance:
9995
      feedback_fn("Removing instance %s" % instance.name)
9996
      _RemoveInstance(self, feedback_fn, instance,
9997
                      self.op.ignore_remove_failures)
9998

    
9999
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10000
      self._CleanupExports(feedback_fn)
10001

    
10002
    return fin_resu, dresults
10003

    
10004

    
10005
class LURemoveExport(NoHooksLU):
10006
  """Remove exports related to the named instance.
10007

10008
  """
10009
  _OP_PARAMS = [
10010
    _PInstanceName,
10011
    ]
10012
  REQ_BGL = False
10013

    
10014
  def ExpandNames(self):
10015
    self.needed_locks = {}
10016
    # We need all nodes to be locked in order for RemoveExport to work, but we
10017
    # don't need to lock the instance itself, as nothing will happen to it (and
10018
    # we can remove exports also for a removed instance)
10019
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10020

    
10021
  def Exec(self, feedback_fn):
10022
    """Remove any export.
10023

10024
    """
10025
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
10026
    # If the instance was not found we'll try with the name that was passed in.
10027
    # This will only work if it was an FQDN, though.
10028
    fqdn_warn = False
10029
    if not instance_name:
10030
      fqdn_warn = True
10031
      instance_name = self.op.instance_name
10032

    
10033
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
10034
    exportlist = self.rpc.call_export_list(locked_nodes)
10035
    found = False
10036
    for node in exportlist:
10037
      msg = exportlist[node].fail_msg
10038
      if msg:
10039
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
10040
        continue
10041
      if instance_name in exportlist[node].payload:
10042
        found = True
10043
        result = self.rpc.call_export_remove(node, instance_name)
10044
        msg = result.fail_msg
10045
        if msg:
10046
          logging.error("Could not remove export for instance %s"
10047
                        " on node %s: %s", instance_name, node, msg)
10048

    
10049
    if fqdn_warn and not found:
10050
      feedback_fn("Export not found. If trying to remove an export belonging"
10051
                  " to a deleted instance please use its Fully Qualified"
10052
                  " Domain Name.")
10053

    
10054

    
10055
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
10056
  """Generic tags LU.
10057

10058
  This is an abstract class which is the parent of all the other tags LUs.
10059

10060
  """
10061

    
10062
  def ExpandNames(self):
10063
    self.needed_locks = {}
10064
    if self.op.kind == constants.TAG_NODE:
10065
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
10066
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
10067
    elif self.op.kind == constants.TAG_INSTANCE:
10068
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
10069
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
10070

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

    
10074
  def CheckPrereq(self):
10075
    """Check prerequisites.
10076

10077
    """
10078
    if self.op.kind == constants.TAG_CLUSTER:
10079
      self.target = self.cfg.GetClusterInfo()
10080
    elif self.op.kind == constants.TAG_NODE:
10081
      self.target = self.cfg.GetNodeInfo(self.op.name)
10082
    elif self.op.kind == constants.TAG_INSTANCE:
10083
      self.target = self.cfg.GetInstanceInfo(self.op.name)
10084
    else:
10085
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
10086
                                 str(self.op.kind), errors.ECODE_INVAL)
10087

    
10088

    
10089
class LUGetTags(TagsLU):
10090
  """Returns the tags of a given object.
10091

10092
  """
10093
  _OP_PARAMS = [
10094
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
10095
    # Name is only meaningful for nodes and instances
10096
    ("name", ht.NoDefault, ht.TMaybeString),
10097
    ]
10098
  REQ_BGL = False
10099

    
10100
  def ExpandNames(self):
10101
    TagsLU.ExpandNames(self)
10102

    
10103
    # Share locks as this is only a read operation
10104
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
10105

    
10106
  def Exec(self, feedback_fn):
10107
    """Returns the tag list.
10108

10109
    """
10110
    return list(self.target.GetTags())
10111

    
10112

    
10113
class LUSearchTags(NoHooksLU):
10114
  """Searches the tags for a given pattern.
10115

10116
  """
10117
  _OP_PARAMS = [
10118
    ("pattern", ht.NoDefault, ht.TNonEmptyString),
10119
    ]
10120
  REQ_BGL = False
10121

    
10122
  def ExpandNames(self):
10123
    self.needed_locks = {}
10124

    
10125
  def CheckPrereq(self):
10126
    """Check prerequisites.
10127

10128
    This checks the pattern passed for validity by compiling it.
10129

10130
    """
10131
    try:
10132
      self.re = re.compile(self.op.pattern)
10133
    except re.error, err:
10134
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
10135
                                 (self.op.pattern, err), errors.ECODE_INVAL)
10136

    
10137
  def Exec(self, feedback_fn):
10138
    """Returns the tag list.
10139

10140
    """
10141
    cfg = self.cfg
10142
    tgts = [("/cluster", cfg.GetClusterInfo())]
10143
    ilist = cfg.GetAllInstancesInfo().values()
10144
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
10145
    nlist = cfg.GetAllNodesInfo().values()
10146
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
10147
    results = []
10148
    for path, target in tgts:
10149
      for tag in target.GetTags():
10150
        if self.re.search(tag):
10151
          results.append((path, tag))
10152
    return results
10153

    
10154

    
10155
class LUAddTags(TagsLU):
10156
  """Sets a tag on a given object.
10157

10158
  """
10159
  _OP_PARAMS = [
10160
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
10161
    # Name is only meaningful for nodes and instances
10162
    ("name", ht.NoDefault, ht.TMaybeString),
10163
    ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
10164
    ]
10165
  REQ_BGL = False
10166

    
10167
  def CheckPrereq(self):
10168
    """Check prerequisites.
10169

10170
    This checks the type and length of the tag name and value.
10171

10172
    """
10173
    TagsLU.CheckPrereq(self)
10174
    for tag in self.op.tags:
10175
      objects.TaggableObject.ValidateTag(tag)
10176

    
10177
  def Exec(self, feedback_fn):
10178
    """Sets the tag.
10179

10180
    """
10181
    try:
10182
      for tag in self.op.tags:
10183
        self.target.AddTag(tag)
10184
    except errors.TagError, err:
10185
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
10186
    self.cfg.Update(self.target, feedback_fn)
10187

    
10188

    
10189
class LUDelTags(TagsLU):
10190
  """Delete a list of tags from a given object.
10191

10192
  """
10193
  _OP_PARAMS = [
10194
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
10195
    # Name is only meaningful for nodes and instances
10196
    ("name", ht.NoDefault, ht.TMaybeString),
10197
    ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
10198
    ]
10199
  REQ_BGL = False
10200

    
10201
  def CheckPrereq(self):
10202
    """Check prerequisites.
10203

10204
    This checks that we have the given tag.
10205

10206
    """
10207
    TagsLU.CheckPrereq(self)
10208
    for tag in self.op.tags:
10209
      objects.TaggableObject.ValidateTag(tag)
10210
    del_tags = frozenset(self.op.tags)
10211
    cur_tags = self.target.GetTags()
10212

    
10213
    diff_tags = del_tags - cur_tags
10214
    if diff_tags:
10215
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
10216
      raise errors.OpPrereqError("Tag(s) %s not found" %
10217
                                 (utils.CommaJoin(diff_names), ),
10218
                                 errors.ECODE_NOENT)
10219

    
10220
  def Exec(self, feedback_fn):
10221
    """Remove the tag from the object.
10222

10223
    """
10224
    for tag in self.op.tags:
10225
      self.target.RemoveTag(tag)
10226
    self.cfg.Update(self.target, feedback_fn)
10227

    
10228

    
10229
class LUTestDelay(NoHooksLU):
10230
  """Sleep for a specified amount of time.
10231

10232
  This LU sleeps on the master and/or nodes for a specified amount of
10233
  time.
10234

10235
  """
10236
  _OP_PARAMS = [
10237
    ("duration", ht.NoDefault, ht.TFloat),
10238
    ("on_master", True, ht.TBool),
10239
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
10240
    ("repeat", 0, ht.TPositiveInt)
10241
    ]
10242
  REQ_BGL = False
10243

    
10244
  def ExpandNames(self):
10245
    """Expand names and set required locks.
10246

10247
    This expands the node list, if any.
10248

10249
    """
10250
    self.needed_locks = {}
10251
    if self.op.on_nodes:
10252
      # _GetWantedNodes can be used here, but is not always appropriate to use
10253
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
10254
      # more information.
10255
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
10256
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
10257

    
10258
  def _TestDelay(self):
10259
    """Do the actual sleep.
10260

10261
    """
10262
    if self.op.on_master:
10263
      if not utils.TestDelay(self.op.duration):
10264
        raise errors.OpExecError("Error during master delay test")
10265
    if self.op.on_nodes:
10266
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
10267
      for node, node_result in result.items():
10268
        node_result.Raise("Failure during rpc call to node %s" % node)
10269

    
10270
  def Exec(self, feedback_fn):
10271
    """Execute the test delay opcode, with the wanted repetitions.
10272

10273
    """
10274
    if self.op.repeat == 0:
10275
      self._TestDelay()
10276
    else:
10277
      top_value = self.op.repeat - 1
10278
      for i in range(self.op.repeat):
10279
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
10280
        self._TestDelay()
10281

    
10282

    
10283
class LUTestJobqueue(NoHooksLU):
10284
  """Utility LU to test some aspects of the job queue.
10285

10286
  """
10287
  _OP_PARAMS = [
10288
    ("notify_waitlock", False, ht.TBool),
10289
    ("notify_exec", False, ht.TBool),
10290
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString)),
10291
    ("fail", False, ht.TBool),
10292
    ]
10293
  REQ_BGL = False
10294

    
10295
  # Must be lower than default timeout for WaitForJobChange to see whether it
10296
  # notices changed jobs
10297
  _CLIENT_CONNECT_TIMEOUT = 20.0
10298
  _CLIENT_CONFIRM_TIMEOUT = 60.0
10299

    
10300
  @classmethod
10301
  def _NotifyUsingSocket(cls, cb, errcls):
10302
    """Opens a Unix socket and waits for another program to connect.
10303

10304
    @type cb: callable
10305
    @param cb: Callback to send socket name to client
10306
    @type errcls: class
10307
    @param errcls: Exception class to use for errors
10308

10309
    """
10310
    # Using a temporary directory as there's no easy way to create temporary
10311
    # sockets without writing a custom loop around tempfile.mktemp and
10312
    # socket.bind
10313
    tmpdir = tempfile.mkdtemp()
10314
    try:
10315
      tmpsock = utils.PathJoin(tmpdir, "sock")
10316

    
10317
      logging.debug("Creating temporary socket at %s", tmpsock)
10318
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
10319
      try:
10320
        sock.bind(tmpsock)
10321
        sock.listen(1)
10322

    
10323
        # Send details to client
10324
        cb(tmpsock)
10325

    
10326
        # Wait for client to connect before continuing
10327
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
10328
        try:
10329
          (conn, _) = sock.accept()
10330
        except socket.error, err:
10331
          raise errcls("Client didn't connect in time (%s)" % err)
10332
      finally:
10333
        sock.close()
10334
    finally:
10335
      # Remove as soon as client is connected
10336
      shutil.rmtree(tmpdir)
10337

    
10338
    # Wait for client to close
10339
    try:
10340
      try:
10341
        # pylint: disable-msg=E1101
10342
        # Instance of '_socketobject' has no ... member
10343
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
10344
        conn.recv(1)
10345
      except socket.error, err:
10346
        raise errcls("Client failed to confirm notification (%s)" % err)
10347
    finally:
10348
      conn.close()
10349

    
10350
  def _SendNotification(self, test, arg, sockname):
10351
    """Sends a notification to the client.
10352

10353
    @type test: string
10354
    @param test: Test name
10355
    @param arg: Test argument (depends on test)
10356
    @type sockname: string
10357
    @param sockname: Socket path
10358

10359
    """
10360
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
10361

    
10362
  def _Notify(self, prereq, test, arg):
10363
    """Notifies the client of a test.
10364

10365
    @type prereq: bool
10366
    @param prereq: Whether this is a prereq-phase test
10367
    @type test: string
10368
    @param test: Test name
10369
    @param arg: Test argument (depends on test)
10370

10371
    """
10372
    if prereq:
10373
      errcls = errors.OpPrereqError
10374
    else:
10375
      errcls = errors.OpExecError
10376

    
10377
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
10378
                                                  test, arg),
10379
                                   errcls)
10380

    
10381
  def CheckArguments(self):
10382
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
10383
    self.expandnames_calls = 0
10384

    
10385
  def ExpandNames(self):
10386
    checkargs_calls = getattr(self, "checkargs_calls", 0)
10387
    if checkargs_calls < 1:
10388
      raise errors.ProgrammerError("CheckArguments was not called")
10389

    
10390
    self.expandnames_calls += 1
10391

    
10392
    if self.op.notify_waitlock:
10393
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
10394

    
10395
    self.LogInfo("Expanding names")
10396

    
10397
    # Get lock on master node (just to get a lock, not for a particular reason)
10398
    self.needed_locks = {
10399
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
10400
      }
10401

    
10402
  def Exec(self, feedback_fn):
10403
    if self.expandnames_calls < 1:
10404
      raise errors.ProgrammerError("ExpandNames was not called")
10405

    
10406
    if self.op.notify_exec:
10407
      self._Notify(False, constants.JQT_EXEC, None)
10408

    
10409
    self.LogInfo("Executing")
10410

    
10411
    if self.op.log_messages:
10412
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
10413
      for idx, msg in enumerate(self.op.log_messages):
10414
        self.LogInfo("Sending log message %s", idx + 1)
10415
        feedback_fn(constants.JQT_MSGPREFIX + msg)
10416
        # Report how many test messages have been sent
10417
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
10418

    
10419
    if self.op.fail:
10420
      raise errors.OpExecError("Opcode failure was requested")
10421

    
10422
    return True
10423

    
10424

    
10425
class IAllocator(object):
10426
  """IAllocator framework.
10427

10428
  An IAllocator instance has three sets of attributes:
10429
    - cfg that is needed to query the cluster
10430
    - input data (all members of the _KEYS class attribute are required)
10431
    - four buffer attributes (in|out_data|text), that represent the
10432
      input (to the external script) in text and data structure format,
10433
      and the output from it, again in two formats
10434
    - the result variables from the script (success, info, nodes) for
10435
      easy usage
10436

10437
  """
10438
  # pylint: disable-msg=R0902
10439
  # lots of instance attributes
10440
  _ALLO_KEYS = [
10441
    "name", "mem_size", "disks", "disk_template",
10442
    "os", "tags", "nics", "vcpus", "hypervisor",
10443
    ]
10444
  _RELO_KEYS = [
10445
    "name", "relocate_from",
10446
    ]
10447
  _EVAC_KEYS = [
10448
    "evac_nodes",
10449
    ]
10450

    
10451
  def __init__(self, cfg, rpc, mode, **kwargs):
10452
    self.cfg = cfg
10453
    self.rpc = rpc
10454
    # init buffer variables
10455
    self.in_text = self.out_text = self.in_data = self.out_data = None
10456
    # init all input fields so that pylint is happy
10457
    self.mode = mode
10458
    self.mem_size = self.disks = self.disk_template = None
10459
    self.os = self.tags = self.nics = self.vcpus = None
10460
    self.hypervisor = None
10461
    self.relocate_from = None
10462
    self.name = None
10463
    self.evac_nodes = None
10464
    # computed fields
10465
    self.required_nodes = None
10466
    # init result fields
10467
    self.success = self.info = self.result = None
10468
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10469
      keyset = self._ALLO_KEYS
10470
      fn = self._AddNewInstance
10471
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10472
      keyset = self._RELO_KEYS
10473
      fn = self._AddRelocateInstance
10474
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10475
      keyset = self._EVAC_KEYS
10476
      fn = self._AddEvacuateNodes
10477
    else:
10478
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
10479
                                   " IAllocator" % self.mode)
10480
    for key in kwargs:
10481
      if key not in keyset:
10482
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
10483
                                     " IAllocator" % key)
10484
      setattr(self, key, kwargs[key])
10485

    
10486
    for key in keyset:
10487
      if key not in kwargs:
10488
        raise errors.ProgrammerError("Missing input parameter '%s' to"
10489
                                     " IAllocator" % key)
10490
    self._BuildInputData(fn)
10491

    
10492
  def _ComputeClusterData(self):
10493
    """Compute the generic allocator input data.
10494

10495
    This is the data that is independent of the actual operation.
10496

10497
    """
10498
    cfg = self.cfg
10499
    cluster_info = cfg.GetClusterInfo()
10500
    # cluster data
10501
    data = {
10502
      "version": constants.IALLOCATOR_VERSION,
10503
      "cluster_name": cfg.GetClusterName(),
10504
      "cluster_tags": list(cluster_info.GetTags()),
10505
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
10506
      # we don't have job IDs
10507
      }
10508
    iinfo = cfg.GetAllInstancesInfo().values()
10509
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
10510

    
10511
    # node data
10512
    node_list = cfg.GetNodeList()
10513

    
10514
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10515
      hypervisor_name = self.hypervisor
10516
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10517
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
10518
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10519
      hypervisor_name = cluster_info.enabled_hypervisors[0]
10520

    
10521
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
10522
                                        hypervisor_name)
10523
    node_iinfo = \
10524
      self.rpc.call_all_instances_info(node_list,
10525
                                       cluster_info.enabled_hypervisors)
10526

    
10527
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
10528

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

    
10531
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
10532

    
10533
    self.in_data = data
10534

    
10535
  @staticmethod
10536
  def _ComputeNodeGroupData(cfg):
10537
    """Compute node groups data.
10538

10539
    """
10540
    ng = {}
10541
    for guuid, gdata in cfg.GetAllNodeGroupsInfo().items():
10542
      ng[guuid] = { "name": gdata.name }
10543
    return ng
10544

    
10545
  @staticmethod
10546
  def _ComputeNodeData(cfg, node_data, node_iinfo, i_list):
10547
    """Compute global node data.
10548

10549
    """
10550
    node_results = {}
10551
    for nname, nresult in node_data.items():
10552
      # first fill in static (config-based) values
10553
      ninfo = cfg.GetNodeInfo(nname)
10554
      pnr = {
10555
        "tags": list(ninfo.GetTags()),
10556
        "primary_ip": ninfo.primary_ip,
10557
        "secondary_ip": ninfo.secondary_ip,
10558
        "offline": ninfo.offline,
10559
        "drained": ninfo.drained,
10560
        "master_candidate": ninfo.master_candidate,
10561
        "group": ninfo.group,
10562
        "master_capable": ninfo.master_capable,
10563
        "vm_capable": ninfo.vm_capable,
10564
        }
10565

    
10566
      if not (ninfo.offline or ninfo.drained):
10567
        nresult.Raise("Can't get data for node %s" % nname)
10568
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
10569
                                nname)
10570
        remote_info = nresult.payload
10571

    
10572
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
10573
                     'vg_size', 'vg_free', 'cpu_total']:
10574
          if attr not in remote_info:
10575
            raise errors.OpExecError("Node '%s' didn't return attribute"
10576
                                     " '%s'" % (nname, attr))
10577
          if not isinstance(remote_info[attr], int):
10578
            raise errors.OpExecError("Node '%s' returned invalid value"
10579
                                     " for '%s': %s" %
10580
                                     (nname, attr, remote_info[attr]))
10581
        # compute memory used by primary instances
10582
        i_p_mem = i_p_up_mem = 0
10583
        for iinfo, beinfo in i_list:
10584
          if iinfo.primary_node == nname:
10585
            i_p_mem += beinfo[constants.BE_MEMORY]
10586
            if iinfo.name not in node_iinfo[nname].payload:
10587
              i_used_mem = 0
10588
            else:
10589
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
10590
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
10591
            remote_info['memory_free'] -= max(0, i_mem_diff)
10592

    
10593
            if iinfo.admin_up:
10594
              i_p_up_mem += beinfo[constants.BE_MEMORY]
10595

    
10596
        # compute memory used by instances
10597
        pnr_dyn = {
10598
          "total_memory": remote_info['memory_total'],
10599
          "reserved_memory": remote_info['memory_dom0'],
10600
          "free_memory": remote_info['memory_free'],
10601
          "total_disk": remote_info['vg_size'],
10602
          "free_disk": remote_info['vg_free'],
10603
          "total_cpus": remote_info['cpu_total'],
10604
          "i_pri_memory": i_p_mem,
10605
          "i_pri_up_memory": i_p_up_mem,
10606
          }
10607
        pnr.update(pnr_dyn)
10608

    
10609
      node_results[nname] = pnr
10610

    
10611
    return node_results
10612

    
10613
  @staticmethod
10614
  def _ComputeInstanceData(cluster_info, i_list):
10615
    """Compute global instance data.
10616

10617
    """
10618
    instance_data = {}
10619
    for iinfo, beinfo in i_list:
10620
      nic_data = []
10621
      for nic in iinfo.nics:
10622
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
10623
        nic_dict = {"mac": nic.mac,
10624
                    "ip": nic.ip,
10625
                    "mode": filled_params[constants.NIC_MODE],
10626
                    "link": filled_params[constants.NIC_LINK],
10627
                   }
10628
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
10629
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
10630
        nic_data.append(nic_dict)
10631
      pir = {
10632
        "tags": list(iinfo.GetTags()),
10633
        "admin_up": iinfo.admin_up,
10634
        "vcpus": beinfo[constants.BE_VCPUS],
10635
        "memory": beinfo[constants.BE_MEMORY],
10636
        "os": iinfo.os,
10637
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
10638
        "nics": nic_data,
10639
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
10640
        "disk_template": iinfo.disk_template,
10641
        "hypervisor": iinfo.hypervisor,
10642
        }
10643
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
10644
                                                 pir["disks"])
10645
      instance_data[iinfo.name] = pir
10646

    
10647
    return instance_data
10648

    
10649
  def _AddNewInstance(self):
10650
    """Add new instance data to allocator structure.
10651

10652
    This in combination with _AllocatorGetClusterData will create the
10653
    correct structure needed as input for the allocator.
10654

10655
    The checks for the completeness of the opcode must have already been
10656
    done.
10657

10658
    """
10659
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
10660

    
10661
    if self.disk_template in constants.DTS_NET_MIRROR:
10662
      self.required_nodes = 2
10663
    else:
10664
      self.required_nodes = 1
10665
    request = {
10666
      "name": self.name,
10667
      "disk_template": self.disk_template,
10668
      "tags": self.tags,
10669
      "os": self.os,
10670
      "vcpus": self.vcpus,
10671
      "memory": self.mem_size,
10672
      "disks": self.disks,
10673
      "disk_space_total": disk_space,
10674
      "nics": self.nics,
10675
      "required_nodes": self.required_nodes,
10676
      }
10677
    return request
10678

    
10679
  def _AddRelocateInstance(self):
10680
    """Add relocate instance data to allocator structure.
10681

10682
    This in combination with _IAllocatorGetClusterData will create the
10683
    correct structure needed as input for the allocator.
10684

10685
    The checks for the completeness of the opcode must have already been
10686
    done.
10687

10688
    """
10689
    instance = self.cfg.GetInstanceInfo(self.name)
10690
    if instance is None:
10691
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
10692
                                   " IAllocator" % self.name)
10693

    
10694
    if instance.disk_template not in constants.DTS_NET_MIRROR:
10695
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
10696
                                 errors.ECODE_INVAL)
10697

    
10698
    if len(instance.secondary_nodes) != 1:
10699
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
10700
                                 errors.ECODE_STATE)
10701

    
10702
    self.required_nodes = 1
10703
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
10704
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
10705

    
10706
    request = {
10707
      "name": self.name,
10708
      "disk_space_total": disk_space,
10709
      "required_nodes": self.required_nodes,
10710
      "relocate_from": self.relocate_from,
10711
      }
10712
    return request
10713

    
10714
  def _AddEvacuateNodes(self):
10715
    """Add evacuate nodes data to allocator structure.
10716

10717
    """
10718
    request = {
10719
      "evac_nodes": self.evac_nodes
10720
      }
10721
    return request
10722

    
10723
  def _BuildInputData(self, fn):
10724
    """Build input data structures.
10725

10726
    """
10727
    self._ComputeClusterData()
10728

    
10729
    request = fn()
10730
    request["type"] = self.mode
10731
    self.in_data["request"] = request
10732

    
10733
    self.in_text = serializer.Dump(self.in_data)
10734

    
10735
  def Run(self, name, validate=True, call_fn=None):
10736
    """Run an instance allocator and return the results.
10737

10738
    """
10739
    if call_fn is None:
10740
      call_fn = self.rpc.call_iallocator_runner
10741

    
10742
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
10743
    result.Raise("Failure while running the iallocator script")
10744

    
10745
    self.out_text = result.payload
10746
    if validate:
10747
      self._ValidateResult()
10748

    
10749
  def _ValidateResult(self):
10750
    """Process the allocator results.
10751

10752
    This will process and if successful save the result in
10753
    self.out_data and the other parameters.
10754

10755
    """
10756
    try:
10757
      rdict = serializer.Load(self.out_text)
10758
    except Exception, err:
10759
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
10760

    
10761
    if not isinstance(rdict, dict):
10762
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
10763

    
10764
    # TODO: remove backwards compatiblity in later versions
10765
    if "nodes" in rdict and "result" not in rdict:
10766
      rdict["result"] = rdict["nodes"]
10767
      del rdict["nodes"]
10768

    
10769
    for key in "success", "info", "result":
10770
      if key not in rdict:
10771
        raise errors.OpExecError("Can't parse iallocator results:"
10772
                                 " missing key '%s'" % key)
10773
      setattr(self, key, rdict[key])
10774

    
10775
    if not isinstance(rdict["result"], list):
10776
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
10777
                               " is not a list")
10778
    self.out_data = rdict
10779

    
10780

    
10781
class LUTestAllocator(NoHooksLU):
10782
  """Run allocator tests.
10783

10784
  This LU runs the allocator tests
10785

10786
  """
10787
  _OP_PARAMS = [
10788
    ("direction", ht.NoDefault,
10789
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS)),
10790
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES)),
10791
    ("name", ht.NoDefault, ht.TNonEmptyString),
10792
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
10793
      ht.TDictOf(ht.TElemOf(["mac", "ip", "bridge"]),
10794
               ht.TOr(ht.TNone, ht.TNonEmptyString))))),
10795
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList)),
10796
    ("hypervisor", None, ht.TMaybeString),
10797
    ("allocator", None, ht.TMaybeString),
10798
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
10799
    ("mem_size", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
10800
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
10801
    ("os", None, ht.TMaybeString),
10802
    ("disk_template", None, ht.TMaybeString),
10803
    ("evac_nodes", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString))),
10804
    ]
10805

    
10806
  def CheckPrereq(self):
10807
    """Check prerequisites.
10808

10809
    This checks the opcode parameters depending on the director and mode test.
10810

10811
    """
10812
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10813
      for attr in ["mem_size", "disks", "disk_template",
10814
                   "os", "tags", "nics", "vcpus"]:
10815
        if not hasattr(self.op, attr):
10816
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
10817
                                     attr, errors.ECODE_INVAL)
10818
      iname = self.cfg.ExpandInstanceName(self.op.name)
10819
      if iname is not None:
10820
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
10821
                                   iname, errors.ECODE_EXISTS)
10822
      if not isinstance(self.op.nics, list):
10823
        raise errors.OpPrereqError("Invalid parameter 'nics'",
10824
                                   errors.ECODE_INVAL)
10825
      if not isinstance(self.op.disks, list):
10826
        raise errors.OpPrereqError("Invalid parameter 'disks'",
10827
                                   errors.ECODE_INVAL)
10828
      for row in self.op.disks:
10829
        if (not isinstance(row, dict) or
10830
            "size" not in row or
10831
            not isinstance(row["size"], int) or
10832
            "mode" not in row or
10833
            row["mode"] not in ['r', 'w']):
10834
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
10835
                                     " parameter", errors.ECODE_INVAL)
10836
      if self.op.hypervisor is None:
10837
        self.op.hypervisor = self.cfg.GetHypervisorType()
10838
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10839
      fname = _ExpandInstanceName(self.cfg, self.op.name)
10840
      self.op.name = fname
10841
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
10842
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10843
      if not hasattr(self.op, "evac_nodes"):
10844
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
10845
                                   " opcode input", errors.ECODE_INVAL)
10846
    else:
10847
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
10848
                                 self.op.mode, errors.ECODE_INVAL)
10849

    
10850
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
10851
      if self.op.allocator is None:
10852
        raise errors.OpPrereqError("Missing allocator name",
10853
                                   errors.ECODE_INVAL)
10854
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
10855
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
10856
                                 self.op.direction, errors.ECODE_INVAL)
10857

    
10858
  def Exec(self, feedback_fn):
10859
    """Run the allocator test.
10860

10861
    """
10862
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10863
      ial = IAllocator(self.cfg, self.rpc,
10864
                       mode=self.op.mode,
10865
                       name=self.op.name,
10866
                       mem_size=self.op.mem_size,
10867
                       disks=self.op.disks,
10868
                       disk_template=self.op.disk_template,
10869
                       os=self.op.os,
10870
                       tags=self.op.tags,
10871
                       nics=self.op.nics,
10872
                       vcpus=self.op.vcpus,
10873
                       hypervisor=self.op.hypervisor,
10874
                       )
10875
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10876
      ial = IAllocator(self.cfg, self.rpc,
10877
                       mode=self.op.mode,
10878
                       name=self.op.name,
10879
                       relocate_from=list(self.relocate_from),
10880
                       )
10881
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10882
      ial = IAllocator(self.cfg, self.rpc,
10883
                       mode=self.op.mode,
10884
                       evac_nodes=self.op.evac_nodes)
10885
    else:
10886
      raise errors.ProgrammerError("Uncatched mode %s in"
10887
                                   " LUTestAllocator.Exec", self.op.mode)
10888

    
10889
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
10890
      result = ial.in_text
10891
    else:
10892
      ial.Run(self.op.allocator, validate=False)
10893
      result = ial.out_text
10894
    return result