Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 5ca09268

History | View | Annotate | Download (385.7 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010 Google Inc.
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful, but
12
# WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
# General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19
# 02110-1301, USA.
20

    
21

    
22
"""Module implementing the master-side code."""
23

    
24
# pylint: disable-msg=W0201,C0302
25

    
26
# W0201 since most LU attributes are defined in CheckPrereq or similar
27
# functions
28

    
29
# C0302: since we have waaaay to many lines in this module
30

    
31
import os
32
import os.path
33
import time
34
import re
35
import platform
36
import logging
37
import copy
38
import OpenSSL
39
import socket
40
import tempfile
41
import shutil
42
import itertools
43

    
44
from ganeti import ssh
45
from ganeti import utils
46
from ganeti import errors
47
from ganeti import hypervisor
48
from ganeti import locking
49
from ganeti import constants
50
from ganeti import objects
51
from ganeti import serializer
52
from ganeti import ssconf
53
from ganeti import uidpool
54
from ganeti import compat
55
from ganeti import masterd
56
from ganeti import netutils
57
from ganeti import ht
58

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

    
61
# Common opcode attributes
62

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

    
66

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

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

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

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

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

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

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

    
90

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

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

104
  Note that all commands require root permissions.
105

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

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

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

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

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

    
150
    # Tasklets
151
    self.tasklets = None
152

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

    
180
    self.CheckArguments()
181

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

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

    
190
  ssh = property(fget=__GetSSH)
191

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

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

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

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

207
    """
208
    pass
209

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

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

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

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

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

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

235
    Examples::
236

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

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

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

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

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

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

274
    """
275

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

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

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

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

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

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

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

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

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

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

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

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

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

333
    """
334
    raise NotImplementedError
335

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
422
    del self.recalculate_locks[locking.LEVEL_NODE]
423

    
424

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

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

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

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

438
    This just raises an error.
439

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

    
443

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

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

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

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

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

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

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

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

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

476
    """
477
    pass
478

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

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

486
    """
487
    raise NotImplementedError
488

    
489

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

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

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

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

    
509

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

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

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

    
529

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

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

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

    
562

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

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

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

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

    
581

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

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

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

    
596

    
597
def _CheckNodeOnline(lu, node, msg=None):
598
  """Ensure that a given node is online.
599

600
  @param lu: the LU on behalf of which we make the check
601
  @param node: the node to check
602
  @param msg: if passed, should be a message to replace the default one
603
  @raise errors.OpPrereqError: if the node is offline
604

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

    
611

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

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

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

    
624

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

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

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

    
637

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

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

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

    
655

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

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

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

    
682

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

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

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

    
693

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

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

    
706

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

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

    
718

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

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

    
726

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

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

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

    
742

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

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

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

    
759

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

    
764

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

    
769

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

775
  This builds the hook environment from individual variables.
776

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

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

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

    
839
  env["INSTANCE_NIC_COUNT"] = nic_count
840

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

    
849
  env["INSTANCE_DISK_COUNT"] = disk_count
850

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

    
855
  return env
856

    
857

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

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

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

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

    
881

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

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

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

    
919

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

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

    
935

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

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

    
946

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

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

    
960

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

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

    
969

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

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

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

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

    
989

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

    
993

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

997
  """
998

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

    
1001

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

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

    
1009

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

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

    
1017

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

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

    
1027
  return []
1028

    
1029

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

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

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

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

    
1044
  return faulty
1045

    
1046

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

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

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

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

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

    
1078

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

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

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

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

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

1097
    """
1098
    return True
1099

    
1100

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

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

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

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

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

1118
    This checks whether the cluster is empty.
1119

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

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

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

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

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

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

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

    
1153
    return master
1154

    
1155

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

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

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

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

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

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

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

    
1188

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1395
    return True
1396

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1746
    nimg.os_fail = test
1747

    
1748
    if test:
1749
      return
1750

    
1751
    os_dict = {}
1752

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

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

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

    
1765
    nimg.oslist = os_dict
1766

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1912
    @type nodelist: list of strings
1913
    @param nodelist: Node names
1914
    @type node_image: dict of (name, L{objects.Node})
1915
    @param node_image: Node objects
1916
    @type instanceinfo: dict of (name, L{objects.Instance})
1917
    @param instanceinfo: Instance objects
1918
    @rtype: {instance: {node: [(succes, payload)]}}
1919
    @return: a dictionary of per-instance dictionaries with nodes as
1920
        keys and disk information as values; the disk information is a
1921
        list of tuples (success, payload)
1922

1923
    """
1924
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1925

    
1926
    node_disks = {}
1927
    node_disks_devonly = {}
1928
    diskless_instances = set()
1929
    diskless = constants.DT_DISKLESS
1930

    
1931
    for nname in nodelist:
1932
      node_instances = list(itertools.chain(node_image[nname].pinst,
1933
                                            node_image[nname].sinst))
1934
      diskless_instances.update(inst for inst in node_instances
1935
                                if instanceinfo[inst].disk_template == diskless)
1936
      disks = [(inst, disk)
1937
               for inst in node_instances
1938
               for disk in instanceinfo[inst].disks]
1939

    
1940
      if not disks:
1941
        # No need to collect data
1942
        continue
1943

    
1944
      node_disks[nname] = disks
1945

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

    
1950
      for dev in devonly:
1951
        self.cfg.SetDiskID(dev, nname)
1952

    
1953
      node_disks_devonly[nname] = devonly
1954

    
1955
    assert len(node_disks) == len(node_disks_devonly)
1956

    
1957
    # Collect data from all nodes with disks
1958
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
1959
                                                          node_disks_devonly)
1960

    
1961
    assert len(result) == len(node_disks)
1962

    
1963
    instdisk = {}
1964

    
1965
    for (nname, nres) in result.items():
1966
      disks = node_disks[nname]
1967

    
1968
      if nres.offline:
1969
        # No data from this node
1970
        data = len(disks) * [(False, "node offline")]
1971
      else:
1972
        msg = nres.fail_msg
1973
        _ErrorIf(msg, self.ENODERPC, nname,
1974
                 "while getting disk information: %s", msg)
1975
        if msg:
1976
          # No data from this node
1977
          data = len(disks) * [(False, msg)]
1978
        else:
1979
          data = []
1980
          for idx, i in enumerate(nres.payload):
1981
            if isinstance(i, (tuple, list)) and len(i) == 2:
1982
              data.append(i)
1983
            else:
1984
              logging.warning("Invalid result from node %s, entry %d: %s",
1985
                              nname, idx, i)
1986
              data.append((False, "Invalid result from the remote node"))
1987

    
1988
      for ((inst, _), status) in zip(disks, data):
1989
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
1990

    
1991
    # Add empty entries for diskless instances.
1992
    for inst in diskless_instances:
1993
      assert inst not in instdisk
1994
      instdisk[inst] = {}
1995

    
1996
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
1997
                      len(nnames) <= len(instanceinfo[inst].all_nodes) and
1998
                      compat.all(isinstance(s, (tuple, list)) and
1999
                                 len(s) == 2 for s in statuses)
2000
                      for inst, nnames in instdisk.items()
2001
                      for nname, statuses in nnames.items())
2002
    assert set(instdisk) == set(instanceinfo), "instdisk consistency failure"
2003

    
2004
    return instdisk
2005

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

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

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

    
2020
    return env, [], all_nodes
2021

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

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

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

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

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

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

    
2066
    local_checksums = utils.FingerprintFiles(file_names)
2067

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

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

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

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

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

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

    
2112
      inst_config.MapLVsByNode(node_vol_should)
2113

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

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

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

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

    
2136
    all_drbd_map = self.cfg.ComputeDRBDMap()
2137

    
2138
    feedback_fn("* Gathering disk information (%s nodes)" % len(nodelist))
2139
    instdisk = self._CollectDiskInfo(nodelist, node_image, instanceinfo)
2140

    
2141
    feedback_fn("* Verifying node status")
2142

    
2143
    refos_img = None
2144

    
2145
    for node_i in nodeinfo:
2146
      node = node_i.name
2147
      nimg = node_image[node]
2148

    
2149
      if node_i.offline:
2150
        if verbose:
2151
          feedback_fn("* Skipping offline node %s" % (node,))
2152
        n_offline += 1
2153
        continue
2154

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

    
2167
      msg = all_nvinfo[node].fail_msg
2168
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2169
      if msg:
2170
        nimg.rpc_fail = True
2171
        continue
2172

    
2173
      nresult = all_nvinfo[node].payload
2174

    
2175
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2176
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2177
      self._VerifyNodeNetwork(node_i, nresult)
2178
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2179
                            master_files)
2180

    
2181
      if nimg.vm_capable:
2182
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2183
        self._VerifyNodeDrbd(node_i, nresult, instanceinfo, drbd_helper,
2184
                             all_drbd_map)
2185

    
2186
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2187
        self._UpdateNodeInstances(node_i, nresult, nimg)
2188
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2189
        self._UpdateNodeOS(node_i, nresult, nimg)
2190
        if not nimg.os_fail:
2191
          if refos_img is None:
2192
            refos_img = nimg
2193
          self._VerifyNodeOS(node_i, nimg, refos_img)
2194

    
2195
    feedback_fn("* Verifying instance status")
2196
    for instance in instancelist:
2197
      if verbose:
2198
        feedback_fn("* Verifying instance %s" % instance)
2199
      inst_config = instanceinfo[instance]
2200
      self._VerifyInstance(instance, inst_config, node_image,
2201
                           instdisk[instance])
2202
      inst_nodes_offline = []
2203

    
2204
      pnode = inst_config.primary_node
2205
      pnode_img = node_image[pnode]
2206
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2207
               self.ENODERPC, pnode, "instance %s, connection to"
2208
               " primary node failed", instance)
2209

    
2210
      if pnode_img.offline:
2211
        inst_nodes_offline.append(pnode)
2212

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

    
2225
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2226
        i_non_a_balanced.append(instance)
2227

    
2228
      for snode in inst_config.secondary_nodes:
2229
        s_img = node_image[snode]
2230
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2231
                 "instance %s, connection to secondary node failed", instance)
2232

    
2233
        if s_img.offline:
2234
          inst_nodes_offline.append(snode)
2235

    
2236
      # warn that the instance lives on offline nodes
2237
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2238
               "instance lives on offline node(s) %s",
2239
               utils.CommaJoin(inst_nodes_offline))
2240
      # ... or ghost/non-vm_capable nodes
2241
      for node in inst_config.all_nodes:
2242
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2243
                 "instance lives on ghost node %s", node)
2244
        _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2245
                 instance, "instance lives on non-vm_capable node %s", node)
2246

    
2247
    feedback_fn("* Verifying orphan volumes")
2248
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2249
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2250

    
2251
    feedback_fn("* Verifying orphan instances")
2252
    self._VerifyOrphanInstances(instancelist, node_image)
2253

    
2254
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2255
      feedback_fn("* Verifying N+1 Memory redundancy")
2256
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2257

    
2258
    feedback_fn("* Other Notes")
2259
    if i_non_redundant:
2260
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2261
                  % len(i_non_redundant))
2262

    
2263
    if i_non_a_balanced:
2264
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2265
                  % len(i_non_a_balanced))
2266

    
2267
    if n_offline:
2268
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2269

    
2270
    if n_drained:
2271
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2272

    
2273
    return not self.bad
2274

    
2275
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2276
    """Analyze the post-hooks' result
2277

2278
    This method analyses the hook result, handles it, and sends some
2279
    nicely-formatted feedback back to the user.
2280

2281
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2282
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2283
    @param hooks_results: the results of the multi-node hooks rpc call
2284
    @param feedback_fn: function used send feedback back to the caller
2285
    @param lu_result: previous Exec result
2286
    @return: the new Exec result, based on the previous result
2287
        and hook results
2288

2289
    """
2290
    # We only really run POST phase hooks, and are only interested in
2291
    # their results
2292
    if phase == constants.HOOKS_PHASE_POST:
2293
      # Used to change hooks' output to proper indentation
2294
      indent_re = re.compile('^', re.M)
2295
      feedback_fn("* Hooks Results")
2296
      assert hooks_results, "invalid result from hooks"
2297

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

    
2319
      return lu_result
2320

    
2321

    
2322
class LUVerifyDisks(NoHooksLU):
2323
  """Verifies the cluster disks status.
2324

2325
  """
2326
  REQ_BGL = False
2327

    
2328
  def ExpandNames(self):
2329
    self.needed_locks = {
2330
      locking.LEVEL_NODE: locking.ALL_SET,
2331
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2332
    }
2333
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2334

    
2335
  def Exec(self, feedback_fn):
2336
    """Verify integrity of cluster disks.
2337

2338
    @rtype: tuple of three items
2339
    @return: a tuple of (dict of node-to-node_error, list of instances
2340
        which need activate-disks, dict of instance: (node, volume) for
2341
        missing volumes
2342

2343
    """
2344
    result = res_nodes, res_instances, res_missing = {}, [], {}
2345

    
2346
    vg_name = self.cfg.GetVGName()
2347
    nodes = utils.NiceSort(self.cfg.GetNodeList())
2348
    instances = [self.cfg.GetInstanceInfo(name)
2349
                 for name in self.cfg.GetInstanceList()]
2350

    
2351
    nv_dict = {}
2352
    for inst in instances:
2353
      inst_lvs = {}
2354
      if (not inst.admin_up or
2355
          inst.disk_template not in constants.DTS_NET_MIRROR):
2356
        continue
2357
      inst.MapLVsByNode(inst_lvs)
2358
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2359
      for node, vol_list in inst_lvs.iteritems():
2360
        for vol in vol_list:
2361
          nv_dict[(node, vol)] = inst
2362

    
2363
    if not nv_dict:
2364
      return result
2365

    
2366
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
2367

    
2368
    for node in nodes:
2369
      # node_volume
2370
      node_res = node_lvs[node]
2371
      if node_res.offline:
2372
        continue
2373
      msg = node_res.fail_msg
2374
      if msg:
2375
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2376
        res_nodes[node] = msg
2377
        continue
2378

    
2379
      lvs = node_res.payload
2380
      for lv_name, (_, _, lv_online) in lvs.items():
2381
        inst = nv_dict.pop((node, lv_name), None)
2382
        if (not lv_online and inst is not None
2383
            and inst.name not in res_instances):
2384
          res_instances.append(inst.name)
2385

    
2386
    # any leftover items in nv_dict are missing LVs, let's arrange the
2387
    # data better
2388
    for key, inst in nv_dict.iteritems():
2389
      if inst.name not in res_missing:
2390
        res_missing[inst.name] = []
2391
      res_missing[inst.name].append(key)
2392

    
2393
    return result
2394

    
2395

    
2396
class LURepairDiskSizes(NoHooksLU):
2397
  """Verifies the cluster disks sizes.
2398

2399
  """
2400
  _OP_PARAMS = [("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString))]
2401
  REQ_BGL = False
2402

    
2403
  def ExpandNames(self):
2404
    if self.op.instances:
2405
      self.wanted_names = []
2406
      for name in self.op.instances:
2407
        full_name = _ExpandInstanceName(self.cfg, name)
2408
        self.wanted_names.append(full_name)
2409
      self.needed_locks = {
2410
        locking.LEVEL_NODE: [],
2411
        locking.LEVEL_INSTANCE: self.wanted_names,
2412
        }
2413
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2414
    else:
2415
      self.wanted_names = None
2416
      self.needed_locks = {
2417
        locking.LEVEL_NODE: locking.ALL_SET,
2418
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2419
        }
2420
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2421

    
2422
  def DeclareLocks(self, level):
2423
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2424
      self._LockInstancesNodes(primary_only=True)
2425

    
2426
  def CheckPrereq(self):
2427
    """Check prerequisites.
2428

2429
    This only checks the optional instance list against the existing names.
2430

2431
    """
2432
    if self.wanted_names is None:
2433
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2434

    
2435
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2436
                             in self.wanted_names]
2437

    
2438
  def _EnsureChildSizes(self, disk):
2439
    """Ensure children of the disk have the needed disk size.
2440

2441
    This is valid mainly for DRBD8 and fixes an issue where the
2442
    children have smaller disk size.
2443

2444
    @param disk: an L{ganeti.objects.Disk} object
2445

2446
    """
2447
    if disk.dev_type == constants.LD_DRBD8:
2448
      assert disk.children, "Empty children for DRBD8?"
2449
      fchild = disk.children[0]
2450
      mismatch = fchild.size < disk.size
2451
      if mismatch:
2452
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2453
                     fchild.size, disk.size)
2454
        fchild.size = disk.size
2455

    
2456
      # and we recurse on this child only, not on the metadev
2457
      return self._EnsureChildSizes(fchild) or mismatch
2458
    else:
2459
      return False
2460

    
2461
  def Exec(self, feedback_fn):
2462
    """Verify the size of cluster disks.
2463

2464
    """
2465
    # TODO: check child disks too
2466
    # TODO: check differences in size between primary/secondary nodes
2467
    per_node_disks = {}
2468
    for instance in self.wanted_instances:
2469
      pnode = instance.primary_node
2470
      if pnode not in per_node_disks:
2471
        per_node_disks[pnode] = []
2472
      for idx, disk in enumerate(instance.disks):
2473
        per_node_disks[pnode].append((instance, idx, disk))
2474

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

    
2511

    
2512
class LURenameCluster(LogicalUnit):
2513
  """Rename the cluster.
2514

2515
  """
2516
  HPATH = "cluster-rename"
2517
  HTYPE = constants.HTYPE_CLUSTER
2518
  _OP_PARAMS = [("name", ht.NoDefault, ht.TNonEmptyString)]
2519

    
2520
  def BuildHooksEnv(self):
2521
    """Build hooks env.
2522

2523
    """
2524
    env = {
2525
      "OP_TARGET": self.cfg.GetClusterName(),
2526
      "NEW_NAME": self.op.name,
2527
      }
2528
    mn = self.cfg.GetMasterNode()
2529
    all_nodes = self.cfg.GetNodeList()
2530
    return env, [mn], all_nodes
2531

    
2532
  def CheckPrereq(self):
2533
    """Verify that the passed name is a valid one.
2534

2535
    """
2536
    hostname = netutils.GetHostname(name=self.op.name,
2537
                                    family=self.cfg.GetPrimaryIPFamily())
2538

    
2539
    new_name = hostname.name
2540
    self.ip = new_ip = hostname.ip
2541
    old_name = self.cfg.GetClusterName()
2542
    old_ip = self.cfg.GetMasterIP()
2543
    if new_name == old_name and new_ip == old_ip:
2544
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2545
                                 " cluster has changed",
2546
                                 errors.ECODE_INVAL)
2547
    if new_ip != old_ip:
2548
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2549
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2550
                                   " reachable on the network" %
2551
                                   new_ip, errors.ECODE_NOTUNIQUE)
2552

    
2553
    self.op.name = new_name
2554

    
2555
  def Exec(self, feedback_fn):
2556
    """Rename the cluster.
2557

2558
    """
2559
    clustername = self.op.name
2560
    ip = self.ip
2561

    
2562
    # shutdown the master IP
2563
    master = self.cfg.GetMasterNode()
2564
    result = self.rpc.call_node_stop_master(master, False)
2565
    result.Raise("Could not disable the master role")
2566

    
2567
    try:
2568
      cluster = self.cfg.GetClusterInfo()
2569
      cluster.cluster_name = clustername
2570
      cluster.master_ip = ip
2571
      self.cfg.Update(cluster, feedback_fn)
2572

    
2573
      # update the known hosts file
2574
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2575
      node_list = self.cfg.GetNodeList()
2576
      try:
2577
        node_list.remove(master)
2578
      except ValueError:
2579
        pass
2580
      _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
2581
    finally:
2582
      result = self.rpc.call_node_start_master(master, False, False)
2583
      msg = result.fail_msg
2584
      if msg:
2585
        self.LogWarning("Could not re-enable the master role on"
2586
                        " the master, please restart manually: %s", msg)
2587

    
2588
    return clustername
2589

    
2590

    
2591
class LUSetClusterParams(LogicalUnit):
2592
  """Change the parameters of the cluster.
2593

2594
  """
2595
  HPATH = "cluster-modify"
2596
  HTYPE = constants.HTYPE_CLUSTER
2597
  _OP_PARAMS = [
2598
    ("vg_name", None, ht.TMaybeString),
2599
    ("enabled_hypervisors", None,
2600
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
2601
            ht.TNone)),
2602
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2603
                              ht.TNone)),
2604
    ("beparams", None, ht.TOr(ht.TDict, ht.TNone)),
2605
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2606
                            ht.TNone)),
2607
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2608
                              ht.TNone)),
2609
    ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone)),
2610
    ("uid_pool", None, ht.NoType),
2611
    ("add_uids", None, ht.NoType),
2612
    ("remove_uids", None, ht.NoType),
2613
    ("maintain_node_health", None, ht.TMaybeBool),
2614
    ("prealloc_wipe_disks", None, ht.TMaybeBool),
2615
    ("nicparams", None, ht.TOr(ht.TDict, ht.TNone)),
2616
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone)),
2617
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone)),
2618
    ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone)),
2619
    ("hidden_os", None, ht.TOr(ht.TListOf(\
2620
          ht.TAnd(ht.TList,
2621
                ht.TIsLength(2),
2622
                ht.TMap(lambda v: v[0], ht.TElemOf(constants.DDMS_VALUES)))),
2623
          ht.TNone)),
2624
    ("blacklisted_os", None, ht.TOr(ht.TListOf(\
2625
          ht.TAnd(ht.TList,
2626
                ht.TIsLength(2),
2627
                ht.TMap(lambda v: v[0], ht.TElemOf(constants.DDMS_VALUES)))),
2628
          ht.TNone)),
2629
    ]
2630
  REQ_BGL = False
2631

    
2632
  def CheckArguments(self):
2633
    """Check parameters
2634

2635
    """
2636
    if self.op.uid_pool:
2637
      uidpool.CheckUidPool(self.op.uid_pool)
2638

    
2639
    if self.op.add_uids:
2640
      uidpool.CheckUidPool(self.op.add_uids)
2641

    
2642
    if self.op.remove_uids:
2643
      uidpool.CheckUidPool(self.op.remove_uids)
2644

    
2645
  def ExpandNames(self):
2646
    # FIXME: in the future maybe other cluster params won't require checking on
2647
    # all nodes to be modified.
2648
    self.needed_locks = {
2649
      locking.LEVEL_NODE: locking.ALL_SET,
2650
    }
2651
    self.share_locks[locking.LEVEL_NODE] = 1
2652

    
2653
  def BuildHooksEnv(self):
2654
    """Build hooks env.
2655

2656
    """
2657
    env = {
2658
      "OP_TARGET": self.cfg.GetClusterName(),
2659
      "NEW_VG_NAME": self.op.vg_name,
2660
      }
2661
    mn = self.cfg.GetMasterNode()
2662
    return env, [mn], [mn]
2663

    
2664
  def CheckPrereq(self):
2665
    """Check prerequisites.
2666

2667
    This checks whether the given params don't conflict and
2668
    if the given volume group is valid.
2669

2670
    """
2671
    if self.op.vg_name is not None and not self.op.vg_name:
2672
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2673
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2674
                                   " instances exist", errors.ECODE_INVAL)
2675

    
2676
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
2677
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
2678
        raise errors.OpPrereqError("Cannot disable drbd helper while"
2679
                                   " drbd-based instances exist",
2680
                                   errors.ECODE_INVAL)
2681

    
2682
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2683

    
2684
    # if vg_name not None, checks given volume group on all nodes
2685
    if self.op.vg_name:
2686
      vglist = self.rpc.call_vg_list(node_list)
2687
      for node in node_list:
2688
        msg = vglist[node].fail_msg
2689
        if msg:
2690
          # ignoring down node
2691
          self.LogWarning("Error while gathering data on node %s"
2692
                          " (ignoring node): %s", node, msg)
2693
          continue
2694
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2695
                                              self.op.vg_name,
2696
                                              constants.MIN_VG_SIZE)
2697
        if vgstatus:
2698
          raise errors.OpPrereqError("Error on node '%s': %s" %
2699
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2700

    
2701
    if self.op.drbd_helper:
2702
      # checks given drbd helper on all nodes
2703
      helpers = self.rpc.call_drbd_helper(node_list)
2704
      for node in node_list:
2705
        ninfo = self.cfg.GetNodeInfo(node)
2706
        if ninfo.offline:
2707
          self.LogInfo("Not checking drbd helper on offline node %s", node)
2708
          continue
2709
        msg = helpers[node].fail_msg
2710
        if msg:
2711
          raise errors.OpPrereqError("Error checking drbd helper on node"
2712
                                     " '%s': %s" % (node, msg),
2713
                                     errors.ECODE_ENVIRON)
2714
        node_helper = helpers[node].payload
2715
        if node_helper != self.op.drbd_helper:
2716
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
2717
                                     (node, node_helper), errors.ECODE_ENVIRON)
2718

    
2719
    self.cluster = cluster = self.cfg.GetClusterInfo()
2720
    # validate params changes
2721
    if self.op.beparams:
2722
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2723
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2724

    
2725
    if self.op.nicparams:
2726
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2727
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2728
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2729
      nic_errors = []
2730

    
2731
      # check all instances for consistency
2732
      for instance in self.cfg.GetAllInstancesInfo().values():
2733
        for nic_idx, nic in enumerate(instance.nics):
2734
          params_copy = copy.deepcopy(nic.nicparams)
2735
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2736

    
2737
          # check parameter syntax
2738
          try:
2739
            objects.NIC.CheckParameterSyntax(params_filled)
2740
          except errors.ConfigurationError, err:
2741
            nic_errors.append("Instance %s, nic/%d: %s" %
2742
                              (instance.name, nic_idx, err))
2743

    
2744
          # if we're moving instances to routed, check that they have an ip
2745
          target_mode = params_filled[constants.NIC_MODE]
2746
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2747
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2748
                              (instance.name, nic_idx))
2749
      if nic_errors:
2750
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2751
                                   "\n".join(nic_errors))
2752

    
2753
    # hypervisor list/parameters
2754
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2755
    if self.op.hvparams:
2756
      for hv_name, hv_dict in self.op.hvparams.items():
2757
        if hv_name not in self.new_hvparams:
2758
          self.new_hvparams[hv_name] = hv_dict
2759
        else:
2760
          self.new_hvparams[hv_name].update(hv_dict)
2761

    
2762
    # os hypervisor parameters
2763
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2764
    if self.op.os_hvp:
2765
      for os_name, hvs in self.op.os_hvp.items():
2766
        if os_name not in self.new_os_hvp:
2767
          self.new_os_hvp[os_name] = hvs
2768
        else:
2769
          for hv_name, hv_dict in hvs.items():
2770
            if hv_name not in self.new_os_hvp[os_name]:
2771
              self.new_os_hvp[os_name][hv_name] = hv_dict
2772
            else:
2773
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2774

    
2775
    # os parameters
2776
    self.new_osp = objects.FillDict(cluster.osparams, {})
2777
    if self.op.osparams:
2778
      for os_name, osp in self.op.osparams.items():
2779
        if os_name not in self.new_osp:
2780
          self.new_osp[os_name] = {}
2781

    
2782
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2783
                                                  use_none=True)
2784

    
2785
        if not self.new_osp[os_name]:
2786
          # we removed all parameters
2787
          del self.new_osp[os_name]
2788
        else:
2789
          # check the parameter validity (remote check)
2790
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
2791
                         os_name, self.new_osp[os_name])
2792

    
2793
    # changes to the hypervisor list
2794
    if self.op.enabled_hypervisors is not None:
2795
      self.hv_list = self.op.enabled_hypervisors
2796
      for hv in self.hv_list:
2797
        # if the hypervisor doesn't already exist in the cluster
2798
        # hvparams, we initialize it to empty, and then (in both
2799
        # cases) we make sure to fill the defaults, as we might not
2800
        # have a complete defaults list if the hypervisor wasn't
2801
        # enabled before
2802
        if hv not in new_hvp:
2803
          new_hvp[hv] = {}
2804
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2805
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2806
    else:
2807
      self.hv_list = cluster.enabled_hypervisors
2808

    
2809
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2810
      # either the enabled list has changed, or the parameters have, validate
2811
      for hv_name, hv_params in self.new_hvparams.items():
2812
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2813
            (self.op.enabled_hypervisors and
2814
             hv_name in self.op.enabled_hypervisors)):
2815
          # either this is a new hypervisor, or its parameters have changed
2816
          hv_class = hypervisor.GetHypervisor(hv_name)
2817
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2818
          hv_class.CheckParameterSyntax(hv_params)
2819
          _CheckHVParams(self, node_list, hv_name, hv_params)
2820

    
2821
    if self.op.os_hvp:
2822
      # no need to check any newly-enabled hypervisors, since the
2823
      # defaults have already been checked in the above code-block
2824
      for os_name, os_hvp in self.new_os_hvp.items():
2825
        for hv_name, hv_params in os_hvp.items():
2826
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2827
          # we need to fill in the new os_hvp on top of the actual hv_p
2828
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2829
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2830
          hv_class = hypervisor.GetHypervisor(hv_name)
2831
          hv_class.CheckParameterSyntax(new_osp)
2832
          _CheckHVParams(self, node_list, hv_name, new_osp)
2833

    
2834
    if self.op.default_iallocator:
2835
      alloc_script = utils.FindFile(self.op.default_iallocator,
2836
                                    constants.IALLOCATOR_SEARCH_PATH,
2837
                                    os.path.isfile)
2838
      if alloc_script is None:
2839
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
2840
                                   " specified" % self.op.default_iallocator,
2841
                                   errors.ECODE_INVAL)
2842

    
2843
  def Exec(self, feedback_fn):
2844
    """Change the parameters of the cluster.
2845

2846
    """
2847
    if self.op.vg_name is not None:
2848
      new_volume = self.op.vg_name
2849
      if not new_volume:
2850
        new_volume = None
2851
      if new_volume != self.cfg.GetVGName():
2852
        self.cfg.SetVGName(new_volume)
2853
      else:
2854
        feedback_fn("Cluster LVM configuration already in desired"
2855
                    " state, not changing")
2856
    if self.op.drbd_helper is not None:
2857
      new_helper = self.op.drbd_helper
2858
      if not new_helper:
2859
        new_helper = None
2860
      if new_helper != self.cfg.GetDRBDHelper():
2861
        self.cfg.SetDRBDHelper(new_helper)
2862
      else:
2863
        feedback_fn("Cluster DRBD helper already in desired state,"
2864
                    " not changing")
2865
    if self.op.hvparams:
2866
      self.cluster.hvparams = self.new_hvparams
2867
    if self.op.os_hvp:
2868
      self.cluster.os_hvp = self.new_os_hvp
2869
    if self.op.enabled_hypervisors is not None:
2870
      self.cluster.hvparams = self.new_hvparams
2871
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2872
    if self.op.beparams:
2873
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2874
    if self.op.nicparams:
2875
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2876
    if self.op.osparams:
2877
      self.cluster.osparams = self.new_osp
2878

    
2879
    if self.op.candidate_pool_size is not None:
2880
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2881
      # we need to update the pool size here, otherwise the save will fail
2882
      _AdjustCandidatePool(self, [])
2883

    
2884
    if self.op.maintain_node_health is not None:
2885
      self.cluster.maintain_node_health = self.op.maintain_node_health
2886

    
2887
    if self.op.prealloc_wipe_disks is not None:
2888
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
2889

    
2890
    if self.op.add_uids is not None:
2891
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2892

    
2893
    if self.op.remove_uids is not None:
2894
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2895

    
2896
    if self.op.uid_pool is not None:
2897
      self.cluster.uid_pool = self.op.uid_pool
2898

    
2899
    if self.op.default_iallocator is not None:
2900
      self.cluster.default_iallocator = self.op.default_iallocator
2901

    
2902
    if self.op.reserved_lvs is not None:
2903
      self.cluster.reserved_lvs = self.op.reserved_lvs
2904

    
2905
    def helper_os(aname, mods, desc):
2906
      desc += " OS list"
2907
      lst = getattr(self.cluster, aname)
2908
      for key, val in mods:
2909
        if key == constants.DDM_ADD:
2910
          if val in lst:
2911
            feedback_fn("OS %s already in %s, ignoring" % (val, desc))
2912
          else:
2913
            lst.append(val)
2914
        elif key == constants.DDM_REMOVE:
2915
          if val in lst:
2916
            lst.remove(val)
2917
          else:
2918
            feedback_fn("OS %s not found in %s, ignoring" % (val, desc))
2919
        else:
2920
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
2921

    
2922
    if self.op.hidden_os:
2923
      helper_os("hidden_os", self.op.hidden_os, "hidden")
2924

    
2925
    if self.op.blacklisted_os:
2926
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
2927

    
2928
    self.cfg.Update(self.cluster, feedback_fn)
2929

    
2930

    
2931
def _UploadHelper(lu, nodes, fname):
2932
  """Helper for uploading a file and showing warnings.
2933

2934
  """
2935
  if os.path.exists(fname):
2936
    result = lu.rpc.call_upload_file(nodes, fname)
2937
    for to_node, to_result in result.items():
2938
      msg = to_result.fail_msg
2939
      if msg:
2940
        msg = ("Copy of file %s to node %s failed: %s" %
2941
               (fname, to_node, msg))
2942
        lu.proc.LogWarning(msg)
2943

    
2944

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

2948
  ConfigWriter takes care of distributing the config and ssconf files, but
2949
  there are more files which should be distributed to all nodes. This function
2950
  makes sure those are copied.
2951

2952
  @param lu: calling logical unit
2953
  @param additional_nodes: list of nodes not in the config to distribute to
2954
  @type additional_vm: boolean
2955
  @param additional_vm: whether the additional nodes are vm-capable or not
2956

2957
  """
2958
  # 1. Gather target nodes
2959
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2960
  dist_nodes = lu.cfg.GetOnlineNodeList()
2961
  nvm_nodes = lu.cfg.GetNonVmCapableNodeList()
2962
  vm_nodes = [name for name in dist_nodes if name not in nvm_nodes]
2963
  if additional_nodes is not None:
2964
    dist_nodes.extend(additional_nodes)
2965
    if additional_vm:
2966
      vm_nodes.extend(additional_nodes)
2967
  if myself.name in dist_nodes:
2968
    dist_nodes.remove(myself.name)
2969
  if myself.name in vm_nodes:
2970
    vm_nodes.remove(myself.name)
2971

    
2972
  # 2. Gather files to distribute
2973
  dist_files = set([constants.ETC_HOSTS,
2974
                    constants.SSH_KNOWN_HOSTS_FILE,
2975
                    constants.RAPI_CERT_FILE,
2976
                    constants.RAPI_USERS_FILE,
2977
                    constants.CONFD_HMAC_KEY,
2978
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
2979
                   ])
2980

    
2981
  vm_files = set()
2982
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2983
  for hv_name in enabled_hypervisors:
2984
    hv_class = hypervisor.GetHypervisor(hv_name)
2985
    vm_files.update(hv_class.GetAncillaryFiles())
2986

    
2987
  # 3. Perform the files upload
2988
  for fname in dist_files:
2989
    _UploadHelper(lu, dist_nodes, fname)
2990
  for fname in vm_files:
2991
    _UploadHelper(lu, vm_nodes, fname)
2992

    
2993

    
2994
class LURedistributeConfig(NoHooksLU):
2995
  """Force the redistribution of cluster configuration.
2996

2997
  This is a very simple LU.
2998

2999
  """
3000
  REQ_BGL = False
3001

    
3002
  def ExpandNames(self):
3003
    self.needed_locks = {
3004
      locking.LEVEL_NODE: locking.ALL_SET,
3005
    }
3006
    self.share_locks[locking.LEVEL_NODE] = 1
3007

    
3008
  def Exec(self, feedback_fn):
3009
    """Redistribute the configuration.
3010

3011
    """
3012
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
3013
    _RedistributeAncillaryFiles(self)
3014

    
3015

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

3019
  """
3020
  if not instance.disks or disks is not None and not disks:
3021
    return True
3022

    
3023
  disks = _ExpandCheckDisks(instance, disks)
3024

    
3025
  if not oneshot:
3026
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
3027

    
3028
  node = instance.primary_node
3029

    
3030
  for dev in disks:
3031
    lu.cfg.SetDiskID(dev, node)
3032

    
3033
  # TODO: Convert to utils.Retry
3034

    
3035
  retries = 0
3036
  degr_retries = 10 # in seconds, as we sleep 1 second each time
3037
  while True:
3038
    max_time = 0
3039
    done = True
3040
    cumul_degraded = False
3041
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
3042
    msg = rstats.fail_msg
3043
    if msg:
3044
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
3045
      retries += 1
3046
      if retries >= 10:
3047
        raise errors.RemoteError("Can't contact node %s for mirror data,"
3048
                                 " aborting." % node)
3049
      time.sleep(6)
3050
      continue
3051
    rstats = rstats.payload
3052
    retries = 0
3053
    for i, mstat in enumerate(rstats):
3054
      if mstat is None:
3055
        lu.LogWarning("Can't compute data for node %s/%s",
3056
                           node, disks[i].iv_name)
3057
        continue
3058

    
3059
      cumul_degraded = (cumul_degraded or
3060
                        (mstat.is_degraded and mstat.sync_percent is None))
3061
      if mstat.sync_percent is not None:
3062
        done = False
3063
        if mstat.estimated_time is not None:
3064
          rem_time = ("%s remaining (estimated)" %
3065
                      utils.FormatSeconds(mstat.estimated_time))
3066
          max_time = mstat.estimated_time
3067
        else:
3068
          rem_time = "no time estimate"
3069
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3070
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3071

    
3072
    # if we're done but degraded, let's do a few small retries, to
3073
    # make sure we see a stable and not transient situation; therefore
3074
    # we force restart of the loop
3075
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3076
      logging.info("Degraded disks found, %d retries left", degr_retries)
3077
      degr_retries -= 1
3078
      time.sleep(1)
3079
      continue
3080

    
3081
    if done or oneshot:
3082
      break
3083

    
3084
    time.sleep(min(60, max_time))
3085

    
3086
  if done:
3087
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3088
  return not cumul_degraded
3089

    
3090

    
3091
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3092
  """Check that mirrors are not degraded.
3093

3094
  The ldisk parameter, if True, will change the test from the
3095
  is_degraded attribute (which represents overall non-ok status for
3096
  the device(s)) to the ldisk (representing the local storage status).
3097

3098
  """
3099
  lu.cfg.SetDiskID(dev, node)
3100

    
3101
  result = True
3102

    
3103
  if on_primary or dev.AssembleOnSecondary():
3104
    rstats = lu.rpc.call_blockdev_find(node, dev)
3105
    msg = rstats.fail_msg
3106
    if msg:
3107
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3108
      result = False
3109
    elif not rstats.payload:
3110
      lu.LogWarning("Can't find disk on node %s", node)
3111
      result = False
3112
    else:
3113
      if ldisk:
3114
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3115
      else:
3116
        result = result and not rstats.payload.is_degraded
3117

    
3118
  if dev.children:
3119
    for child in dev.children:
3120
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3121

    
3122
  return result
3123

    
3124

    
3125
class LUDiagnoseOS(NoHooksLU):
3126
  """Logical unit for OS diagnose/query.
3127

3128
  """
3129
  _OP_PARAMS = [
3130
    _POutputFields,
3131
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3132
    ]
3133
  REQ_BGL = False
3134
  _HID = "hidden"
3135
  _BLK = "blacklisted"
3136
  _VLD = "valid"
3137
  _FIELDS_STATIC = utils.FieldSet()
3138
  _FIELDS_DYNAMIC = utils.FieldSet("name", _VLD, "node_status", "variants",
3139
                                   "parameters", "api_versions", _HID, _BLK)
3140

    
3141
  def CheckArguments(self):
3142
    if self.op.names:
3143
      raise errors.OpPrereqError("Selective OS query not supported",
3144
                                 errors.ECODE_INVAL)
3145

    
3146
    _CheckOutputFields(static=self._FIELDS_STATIC,
3147
                       dynamic=self._FIELDS_DYNAMIC,
3148
                       selected=self.op.output_fields)
3149

    
3150
  def ExpandNames(self):
3151
    # Lock all nodes, in shared mode
3152
    # Temporary removal of locks, should be reverted later
3153
    # TODO: reintroduce locks when they are lighter-weight
3154
    self.needed_locks = {}
3155
    #self.share_locks[locking.LEVEL_NODE] = 1
3156
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3157

    
3158
  @staticmethod
3159
  def _DiagnoseByOS(rlist):
3160
    """Remaps a per-node return list into an a per-os per-node dictionary
3161

3162
    @param rlist: a map with node names as keys and OS objects as values
3163

3164
    @rtype: dict
3165
    @return: a dictionary with osnames as keys and as value another
3166
        map, with nodes as keys and tuples of (path, status, diagnose,
3167
        variants, parameters, api_versions) as values, eg::
3168

3169
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3170
                                     (/srv/..., False, "invalid api")],
3171
                           "node2": [(/srv/..., True, "", [], [])]}
3172
          }
3173

3174
    """
3175
    all_os = {}
3176
    # we build here the list of nodes that didn't fail the RPC (at RPC
3177
    # level), so that nodes with a non-responding node daemon don't
3178
    # make all OSes invalid
3179
    good_nodes = [node_name for node_name in rlist
3180
                  if not rlist[node_name].fail_msg]
3181
    for node_name, nr in rlist.items():
3182
      if nr.fail_msg or not nr.payload:
3183
        continue
3184
      for (name, path, status, diagnose, variants,
3185
           params, api_versions) in nr.payload:
3186
        if name not in all_os:
3187
          # build a list of nodes for this os containing empty lists
3188
          # for each node in node_list
3189
          all_os[name] = {}
3190
          for nname in good_nodes:
3191
            all_os[name][nname] = []
3192
        # convert params from [name, help] to (name, help)
3193
        params = [tuple(v) for v in params]
3194
        all_os[name][node_name].append((path, status, diagnose,
3195
                                        variants, params, api_versions))
3196
    return all_os
3197

    
3198
  def Exec(self, feedback_fn):
3199
    """Compute the list of OSes.
3200

3201
    """
3202
    valid_nodes = [node.name
3203
                   for node in self.cfg.GetAllNodesInfo().values()
3204
                   if not node.offline and node.vm_capable]
3205
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3206
    pol = self._DiagnoseByOS(node_data)
3207
    output = []
3208
    cluster = self.cfg.GetClusterInfo()
3209

    
3210
    for os_name in utils.NiceSort(pol.keys()):
3211
      os_data = pol[os_name]
3212
      row = []
3213
      valid = True
3214
      (variants, params, api_versions) = null_state = (set(), set(), set())
3215
      for idx, osl in enumerate(os_data.values()):
3216
        valid = bool(valid and osl and osl[0][1])
3217
        if not valid:
3218
          (variants, params, api_versions) = null_state
3219
          break
3220
        node_variants, node_params, node_api = osl[0][3:6]
3221
        if idx == 0: # first entry
3222
          variants = set(node_variants)
3223
          params = set(node_params)
3224
          api_versions = set(node_api)
3225
        else: # keep consistency
3226
          variants.intersection_update(node_variants)
3227
          params.intersection_update(node_params)
3228
          api_versions.intersection_update(node_api)
3229

    
3230
      is_hid = os_name in cluster.hidden_os
3231
      is_blk = os_name in cluster.blacklisted_os
3232
      if ((self._HID not in self.op.output_fields and is_hid) or
3233
          (self._BLK not in self.op.output_fields and is_blk) or
3234
          (self._VLD not in self.op.output_fields and not valid)):
3235
        continue
3236

    
3237
      for field in self.op.output_fields:
3238
        if field == "name":
3239
          val = os_name
3240
        elif field == self._VLD:
3241
          val = valid
3242
        elif field == "node_status":
3243
          # this is just a copy of the dict
3244
          val = {}
3245
          for node_name, nos_list in os_data.items():
3246
            val[node_name] = nos_list
3247
        elif field == "variants":
3248
          val = utils.NiceSort(list(variants))
3249
        elif field == "parameters":
3250
          val = list(params)
3251
        elif field == "api_versions":
3252
          val = list(api_versions)
3253
        elif field == self._HID:
3254
          val = is_hid
3255
        elif field == self._BLK:
3256
          val = is_blk
3257
        else:
3258
          raise errors.ParameterError(field)
3259
        row.append(val)
3260
      output.append(row)
3261

    
3262
    return output
3263

    
3264

    
3265
class LURemoveNode(LogicalUnit):
3266
  """Logical unit for removing a node.
3267

3268
  """
3269
  HPATH = "node-remove"
3270
  HTYPE = constants.HTYPE_NODE
3271
  _OP_PARAMS = [
3272
    _PNodeName,
3273
    ]
3274

    
3275
  def BuildHooksEnv(self):
3276
    """Build hooks env.
3277

3278
    This doesn't run on the target node in the pre phase as a failed
3279
    node would then be impossible to remove.
3280

3281
    """
3282
    env = {
3283
      "OP_TARGET": self.op.node_name,
3284
      "NODE_NAME": self.op.node_name,
3285
      }
3286
    all_nodes = self.cfg.GetNodeList()
3287
    try:
3288
      all_nodes.remove(self.op.node_name)
3289
    except ValueError:
3290
      logging.warning("Node %s which is about to be removed not found"
3291
                      " in the all nodes list", self.op.node_name)
3292
    return env, all_nodes, all_nodes
3293

    
3294
  def CheckPrereq(self):
3295
    """Check prerequisites.
3296

3297
    This checks:
3298
     - the node exists in the configuration
3299
     - it does not have primary or secondary instances
3300
     - it's not the master
3301

3302
    Any errors are signaled by raising errors.OpPrereqError.
3303

3304
    """
3305
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3306
    node = self.cfg.GetNodeInfo(self.op.node_name)
3307
    assert node is not None
3308

    
3309
    instance_list = self.cfg.GetInstanceList()
3310

    
3311
    masternode = self.cfg.GetMasterNode()
3312
    if node.name == masternode:
3313
      raise errors.OpPrereqError("Node is the master node,"
3314
                                 " you need to failover first.",
3315
                                 errors.ECODE_INVAL)
3316

    
3317
    for instance_name in instance_list:
3318
      instance = self.cfg.GetInstanceInfo(instance_name)
3319
      if node.name in instance.all_nodes:
3320
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3321
                                   " please remove first." % instance_name,
3322
                                   errors.ECODE_INVAL)
3323
    self.op.node_name = node.name
3324
    self.node = node
3325

    
3326
  def Exec(self, feedback_fn):
3327
    """Removes the node from the cluster.
3328

3329
    """
3330
    node = self.node
3331
    logging.info("Stopping the node daemon and removing configs from node %s",
3332
                 node.name)
3333

    
3334
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3335

    
3336
    # Promote nodes to master candidate as needed
3337
    _AdjustCandidatePool(self, exceptions=[node.name])
3338
    self.context.RemoveNode(node.name)
3339

    
3340
    # Run post hooks on the node before it's removed
3341
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3342
    try:
3343
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3344
    except:
3345
      # pylint: disable-msg=W0702
3346
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3347

    
3348
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3349
    msg = result.fail_msg
3350
    if msg:
3351
      self.LogWarning("Errors encountered on the remote node while leaving"
3352
                      " the cluster: %s", msg)
3353

    
3354
    # Remove node from our /etc/hosts
3355
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3356
      master_node = self.cfg.GetMasterNode()
3357
      result = self.rpc.call_etc_hosts_modify(master_node,
3358
                                              constants.ETC_HOSTS_REMOVE,
3359
                                              node.name, None)
3360
      result.Raise("Can't update hosts file with new host data")
3361
      _RedistributeAncillaryFiles(self)
3362

    
3363

    
3364
class LUQueryNodes(NoHooksLU):
3365
  """Logical unit for querying nodes.
3366

3367
  """
3368
  # pylint: disable-msg=W0142
3369
  _OP_PARAMS = [
3370
    _POutputFields,
3371
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3372
    ("use_locking", False, ht.TBool),
3373
    ]
3374
  REQ_BGL = False
3375

    
3376
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
3377
                    "master_candidate", "offline", "drained",
3378
                    "master_capable", "vm_capable"]
3379

    
3380
  _FIELDS_DYNAMIC = utils.FieldSet(
3381
    "dtotal", "dfree",
3382
    "mtotal", "mnode", "mfree",
3383
    "bootid",
3384
    "ctotal", "cnodes", "csockets",
3385
    )
3386

    
3387
  _FIELDS_STATIC = utils.FieldSet(*[
3388
    "pinst_cnt", "sinst_cnt",
3389
    "pinst_list", "sinst_list",
3390
    "pip", "sip", "tags",
3391
    "master",
3392
    "role"] + _SIMPLE_FIELDS
3393
    )
3394

    
3395
  def CheckArguments(self):
3396
    _CheckOutputFields(static=self._FIELDS_STATIC,
3397
                       dynamic=self._FIELDS_DYNAMIC,
3398
                       selected=self.op.output_fields)
3399

    
3400
  def ExpandNames(self):
3401
    self.needed_locks = {}
3402
    self.share_locks[locking.LEVEL_NODE] = 1
3403

    
3404
    if self.op.names:
3405
      self.wanted = _GetWantedNodes(self, self.op.names)
3406
    else:
3407
      self.wanted = locking.ALL_SET
3408

    
3409
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3410
    self.do_locking = self.do_node_query and self.op.use_locking
3411
    if self.do_locking:
3412
      # if we don't request only static fields, we need to lock the nodes
3413
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
3414

    
3415
  def Exec(self, feedback_fn):
3416
    """Computes the list of nodes and their attributes.
3417

3418
    """
3419
    all_info = self.cfg.GetAllNodesInfo()
3420
    if self.do_locking:
3421
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
3422
    elif self.wanted != locking.ALL_SET:
3423
      nodenames = self.wanted
3424
      missing = set(nodenames).difference(all_info.keys())
3425
      if missing:
3426
        raise errors.OpExecError(
3427
          "Some nodes were removed before retrieving their data: %s" % missing)
3428
    else:
3429
      nodenames = all_info.keys()
3430

    
3431
    nodenames = utils.NiceSort(nodenames)
3432
    nodelist = [all_info[name] for name in nodenames]
3433

    
3434
    # begin data gathering
3435

    
3436
    if self.do_node_query:
3437
      live_data = {}
3438
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
3439
                                          self.cfg.GetHypervisorType())
3440
      for name in nodenames:
3441
        nodeinfo = node_data[name]
3442
        if not nodeinfo.fail_msg and nodeinfo.payload:
3443
          nodeinfo = nodeinfo.payload
3444
          fn = utils.TryConvert
3445
          live_data[name] = {
3446
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
3447
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
3448
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
3449
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
3450
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
3451
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
3452
            "bootid": nodeinfo.get('bootid', None),
3453
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
3454
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
3455
            }
3456
        else:
3457
          live_data[name] = {}
3458
    else:
3459
      live_data = dict.fromkeys(nodenames, {})
3460

    
3461
    node_to_primary = dict([(name, set()) for name in nodenames])
3462
    node_to_secondary = dict([(name, set()) for name in nodenames])
3463

    
3464
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
3465
                             "sinst_cnt", "sinst_list"))
3466
    if inst_fields & frozenset(self.op.output_fields):
3467
      inst_data = self.cfg.GetAllInstancesInfo()
3468

    
3469
      for inst in inst_data.values():
3470
        if inst.primary_node in node_to_primary:
3471
          node_to_primary[inst.primary_node].add(inst.name)
3472
        for secnode in inst.secondary_nodes:
3473
          if secnode in node_to_secondary:
3474
            node_to_secondary[secnode].add(inst.name)
3475

    
3476
    master_node = self.cfg.GetMasterNode()
3477

    
3478
    # end data gathering
3479

    
3480
    output = []
3481
    for node in nodelist:
3482
      node_output = []
3483
      for field in self.op.output_fields:
3484
        if field in self._SIMPLE_FIELDS:
3485
          val = getattr(node, field)
3486
        elif field == "pinst_list":
3487
          val = list(node_to_primary[node.name])
3488
        elif field == "sinst_list":
3489
          val = list(node_to_secondary[node.name])
3490
        elif field == "pinst_cnt":
3491
          val = len(node_to_primary[node.name])
3492
        elif field == "sinst_cnt":
3493
          val = len(node_to_secondary[node.name])
3494
        elif field == "pip":
3495
          val = node.primary_ip
3496
        elif field == "sip":
3497
          val = node.secondary_ip
3498
        elif field == "tags":
3499
          val = list(node.GetTags())
3500
        elif field == "master":
3501
          val = node.name == master_node
3502
        elif self._FIELDS_DYNAMIC.Matches(field):
3503
          val = live_data[node.name].get(field, None)
3504
        elif field == "role":
3505
          if node.name == master_node:
3506
            val = "M"
3507
          elif node.master_candidate:
3508
            val = "C"
3509
          elif node.drained:
3510
            val = "D"
3511
          elif node.offline:
3512
            val = "O"
3513
          else:
3514
            val = "R"
3515
        else:
3516
          raise errors.ParameterError(field)
3517
        node_output.append(val)
3518
      output.append(node_output)
3519

    
3520
    return output
3521

    
3522

    
3523
class LUQueryNodeVolumes(NoHooksLU):
3524
  """Logical unit for getting volumes on node(s).
3525

3526
  """
3527
  _OP_PARAMS = [
3528
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3529
    ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
3530
    ]
3531
  REQ_BGL = False
3532
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3533
  _FIELDS_STATIC = utils.FieldSet("node")
3534

    
3535
  def CheckArguments(self):
3536
    _CheckOutputFields(static=self._FIELDS_STATIC,
3537
                       dynamic=self._FIELDS_DYNAMIC,
3538
                       selected=self.op.output_fields)
3539

    
3540
  def ExpandNames(self):
3541
    self.needed_locks = {}
3542
    self.share_locks[locking.LEVEL_NODE] = 1
3543
    if not self.op.nodes:
3544
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3545
    else:
3546
      self.needed_locks[locking.LEVEL_NODE] = \
3547
        _GetWantedNodes(self, self.op.nodes)
3548

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

3552
    """
3553
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3554
    volumes = self.rpc.call_node_volumes(nodenames)
3555

    
3556
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3557
             in self.cfg.GetInstanceList()]
3558

    
3559
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3560

    
3561
    output = []
3562
    for node in nodenames:
3563
      nresult = volumes[node]
3564
      if nresult.offline:
3565
        continue
3566
      msg = nresult.fail_msg
3567
      if msg:
3568
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3569
        continue
3570

    
3571
      node_vols = nresult.payload[:]
3572
      node_vols.sort(key=lambda vol: vol['dev'])
3573

    
3574
      for vol in node_vols:
3575
        node_output = []
3576
        for field in self.op.output_fields:
3577
          if field == "node":
3578
            val = node
3579
          elif field == "phys":
3580
            val = vol['dev']
3581
          elif field == "vg":
3582
            val = vol['vg']
3583
          elif field == "name":
3584
            val = vol['name']
3585
          elif field == "size":
3586
            val = int(float(vol['size']))
3587
          elif field == "instance":
3588
            for inst in ilist:
3589
              if node not in lv_by_node[inst]:
3590
                continue
3591
              if vol['name'] in lv_by_node[inst][node]:
3592
                val = inst.name
3593
                break
3594
            else:
3595
              val = '-'
3596
          else:
3597
            raise errors.ParameterError(field)
3598
          node_output.append(str(val))
3599

    
3600
        output.append(node_output)
3601

    
3602
    return output
3603

    
3604

    
3605
class LUQueryNodeStorage(NoHooksLU):
3606
  """Logical unit for getting information on storage units on node(s).
3607

3608
  """
3609
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3610
  _OP_PARAMS = [
3611
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3612
    ("storage_type", ht.NoDefault, _CheckStorageType),
3613
    ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
3614
    ("name", None, ht.TMaybeString),
3615
    ]
3616
  REQ_BGL = False
3617

    
3618
  def CheckArguments(self):
3619
    _CheckOutputFields(static=self._FIELDS_STATIC,
3620
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3621
                       selected=self.op.output_fields)
3622

    
3623
  def ExpandNames(self):
3624
    self.needed_locks = {}
3625
    self.share_locks[locking.LEVEL_NODE] = 1
3626

    
3627
    if self.op.nodes:
3628
      self.needed_locks[locking.LEVEL_NODE] = \
3629
        _GetWantedNodes(self, self.op.nodes)
3630
    else:
3631
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3632

    
3633
  def Exec(self, feedback_fn):
3634
    """Computes the list of nodes and their attributes.
3635

3636
    """
3637
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3638

    
3639
    # Always get name to sort by
3640
    if constants.SF_NAME in self.op.output_fields:
3641
      fields = self.op.output_fields[:]
3642
    else:
3643
      fields = [constants.SF_NAME] + self.op.output_fields
3644

    
3645
    # Never ask for node or type as it's only known to the LU
3646
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3647
      while extra in fields:
3648
        fields.remove(extra)
3649

    
3650
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3651
    name_idx = field_idx[constants.SF_NAME]
3652

    
3653
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3654
    data = self.rpc.call_storage_list(self.nodes,
3655
                                      self.op.storage_type, st_args,
3656
                                      self.op.name, fields)
3657

    
3658
    result = []
3659

    
3660
    for node in utils.NiceSort(self.nodes):
3661
      nresult = data[node]
3662
      if nresult.offline:
3663
        continue
3664

    
3665
      msg = nresult.fail_msg
3666
      if msg:
3667
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3668
        continue
3669

    
3670
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3671

    
3672
      for name in utils.NiceSort(rows.keys()):
3673
        row = rows[name]
3674

    
3675
        out = []
3676

    
3677
        for field in self.op.output_fields:
3678
          if field == constants.SF_NODE:
3679
            val = node
3680
          elif field == constants.SF_TYPE:
3681
            val = self.op.storage_type
3682
          elif field in field_idx:
3683
            val = row[field_idx[field]]
3684
          else:
3685
            raise errors.ParameterError(field)
3686

    
3687
          out.append(val)
3688

    
3689
        result.append(out)
3690

    
3691
    return result
3692

    
3693

    
3694
class LUModifyNodeStorage(NoHooksLU):
3695
  """Logical unit for modifying a storage volume on a node.
3696

3697
  """
3698
  _OP_PARAMS = [
3699
    _PNodeName,
3700
    ("storage_type", ht.NoDefault, _CheckStorageType),
3701
    ("name", ht.NoDefault, ht.TNonEmptyString),
3702
    ("changes", ht.NoDefault, ht.TDict),
3703
    ]
3704
  REQ_BGL = False
3705

    
3706
  def CheckArguments(self):
3707
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3708

    
3709
    storage_type = self.op.storage_type
3710

    
3711
    try:
3712
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3713
    except KeyError:
3714
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3715
                                 " modified" % storage_type,
3716
                                 errors.ECODE_INVAL)
3717

    
3718
    diff = set(self.op.changes.keys()) - modifiable
3719
    if diff:
3720
      raise errors.OpPrereqError("The following fields can not be modified for"
3721
                                 " storage units of type '%s': %r" %
3722
                                 (storage_type, list(diff)),
3723
                                 errors.ECODE_INVAL)
3724

    
3725
  def ExpandNames(self):
3726
    self.needed_locks = {
3727
      locking.LEVEL_NODE: self.op.node_name,
3728
      }
3729

    
3730
  def Exec(self, feedback_fn):
3731
    """Computes the list of nodes and their attributes.
3732

3733
    """
3734
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3735
    result = self.rpc.call_storage_modify(self.op.node_name,
3736
                                          self.op.storage_type, st_args,
3737
                                          self.op.name, self.op.changes)
3738
    result.Raise("Failed to modify storage unit '%s' on %s" %
3739
                 (self.op.name, self.op.node_name))
3740

    
3741

    
3742
class LUAddNode(LogicalUnit):
3743
  """Logical unit for adding node to the cluster.
3744

3745
  """
3746
  HPATH = "node-add"
3747
  HTYPE = constants.HTYPE_NODE
3748
  _OP_PARAMS = [
3749
    _PNodeName,
3750
    ("primary_ip", None, ht.NoType),
3751
    ("secondary_ip", None, ht.TMaybeString),
3752
    ("readd", False, ht.TBool),
3753
    ("group", None, ht.TMaybeString),
3754
    ("master_capable", None, ht.TMaybeBool),
3755
    ("vm_capable", None, ht.TMaybeBool),
3756
    ]
3757
  _NFLAGS = ["master_capable", "vm_capable"]
3758

    
3759
  def CheckArguments(self):
3760
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
3761
    # validate/normalize the node name
3762
    self.hostname = netutils.GetHostname(name=self.op.node_name,
3763
                                         family=self.primary_ip_family)
3764
    self.op.node_name = self.hostname.name
3765
    if self.op.readd and self.op.group:
3766
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
3767
                                 " being readded", errors.ECODE_INVAL)
3768

    
3769
  def BuildHooksEnv(self):
3770
    """Build hooks env.
3771

3772
    This will run on all nodes before, and on all nodes + the new node after.
3773

3774
    """
3775
    env = {
3776
      "OP_TARGET": self.op.node_name,
3777
      "NODE_NAME": self.op.node_name,
3778
      "NODE_PIP": self.op.primary_ip,
3779
      "NODE_SIP": self.op.secondary_ip,
3780
      "MASTER_CAPABLE": str(self.op.master_capable),
3781
      "VM_CAPABLE": str(self.op.vm_capable),
3782
      }
3783
    nodes_0 = self.cfg.GetNodeList()
3784
    nodes_1 = nodes_0 + [self.op.node_name, ]
3785
    return env, nodes_0, nodes_1
3786

    
3787
  def CheckPrereq(self):
3788
    """Check prerequisites.
3789

3790
    This checks:
3791
     - the new node is not already in the config
3792
     - it is resolvable
3793
     - its parameters (single/dual homed) matches the cluster
3794

3795
    Any errors are signaled by raising errors.OpPrereqError.
3796

3797
    """
3798
    cfg = self.cfg
3799
    hostname = self.hostname
3800
    node = hostname.name
3801
    primary_ip = self.op.primary_ip = hostname.ip
3802
    if self.op.secondary_ip is None:
3803
      if self.primary_ip_family == netutils.IP6Address.family:
3804
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
3805
                                   " IPv4 address must be given as secondary",
3806
                                   errors.ECODE_INVAL)
3807
      self.op.secondary_ip = primary_ip
3808

    
3809
    secondary_ip = self.op.secondary_ip
3810
    if not netutils.IP4Address.IsValid(secondary_ip):
3811
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
3812
                                 " address" % secondary_ip, errors.ECODE_INVAL)
3813

    
3814
    node_list = cfg.GetNodeList()
3815
    if not self.op.readd and node in node_list:
3816
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3817
                                 node, errors.ECODE_EXISTS)
3818
    elif self.op.readd and node not in node_list:
3819
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3820
                                 errors.ECODE_NOENT)
3821

    
3822
    self.changed_primary_ip = False
3823

    
3824
    for existing_node_name in node_list:
3825
      existing_node = cfg.GetNodeInfo(existing_node_name)
3826

    
3827
      if self.op.readd and node == existing_node_name:
3828
        if existing_node.secondary_ip != secondary_ip:
3829
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3830
                                     " address configuration as before",
3831
                                     errors.ECODE_INVAL)
3832
        if existing_node.primary_ip != primary_ip:
3833
          self.changed_primary_ip = True
3834

    
3835
        continue
3836

    
3837
      if (existing_node.primary_ip == primary_ip or
3838
          existing_node.secondary_ip == primary_ip or
3839
          existing_node.primary_ip == secondary_ip or
3840
          existing_node.secondary_ip == secondary_ip):
3841
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3842
                                   " existing node %s" % existing_node.name,
3843
                                   errors.ECODE_NOTUNIQUE)
3844

    
3845
    # After this 'if' block, None is no longer a valid value for the
3846
    # _capable op attributes
3847
    if self.op.readd:
3848
      old_node = self.cfg.GetNodeInfo(node)
3849
      assert old_node is not None, "Can't retrieve locked node %s" % node
3850
      for attr in self._NFLAGS:
3851
        if getattr(self.op, attr) is None:
3852
          setattr(self.op, attr, getattr(old_node, attr))
3853
    else:
3854
      for attr in self._NFLAGS:
3855
        if getattr(self.op, attr) is None:
3856
          setattr(self.op, attr, True)
3857

    
3858
    if self.op.readd and not self.op.vm_capable:
3859
      pri, sec = cfg.GetNodeInstances(node)
3860
      if pri or sec:
3861
        raise errors.OpPrereqError("Node %s being re-added with vm_capable"
3862
                                   " flag set to false, but it already holds"
3863
                                   " instances" % node,
3864
                                   errors.ECODE_STATE)
3865

    
3866
    # check that the type of the node (single versus dual homed) is the
3867
    # same as for the master
3868
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
3869
    master_singlehomed = myself.secondary_ip == myself.primary_ip
3870
    newbie_singlehomed = secondary_ip == primary_ip
3871
    if master_singlehomed != newbie_singlehomed:
3872
      if master_singlehomed:
3873
        raise errors.OpPrereqError("The master has no secondary ip but the"
3874
                                   " new node has one",
3875
                                   errors.ECODE_INVAL)
3876
      else:
3877
        raise errors.OpPrereqError("The master has a secondary ip but the"
3878
                                   " new node doesn't have one",
3879
                                   errors.ECODE_INVAL)
3880

    
3881
    # checks reachability
3882
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3883
      raise errors.OpPrereqError("Node not reachable by ping",
3884
                                 errors.ECODE_ENVIRON)
3885

    
3886
    if not newbie_singlehomed:
3887
      # check reachability from my secondary ip to newbie's secondary ip
3888
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3889
                           source=myself.secondary_ip):
3890
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3891
                                   " based ping to node daemon port",
3892
                                   errors.ECODE_ENVIRON)
3893

    
3894
    if self.op.readd:
3895
      exceptions = [node]
3896
    else:
3897
      exceptions = []
3898

    
3899
    if self.op.master_capable:
3900
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3901
    else:
3902
      self.master_candidate = False
3903

    
3904
    if self.op.readd:
3905
      self.new_node = old_node
3906
    else:
3907
      node_group = cfg.LookupNodeGroup(self.op.group)
3908
      self.new_node = objects.Node(name=node,
3909
                                   primary_ip=primary_ip,
3910
                                   secondary_ip=secondary_ip,
3911
                                   master_candidate=self.master_candidate,
3912
                                   offline=False, drained=False,
3913
                                   group=node_group)
3914

    
3915
  def Exec(self, feedback_fn):
3916
    """Adds the new node to the cluster.
3917

3918
    """
3919
    new_node = self.new_node
3920
    node = new_node.name
3921

    
3922
    # for re-adds, reset the offline/drained/master-candidate flags;
3923
    # we need to reset here, otherwise offline would prevent RPC calls
3924
    # later in the procedure; this also means that if the re-add
3925
    # fails, we are left with a non-offlined, broken node
3926
    if self.op.readd:
3927
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3928
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3929
      # if we demote the node, we do cleanup later in the procedure
3930
      new_node.master_candidate = self.master_candidate
3931
      if self.changed_primary_ip:
3932
        new_node.primary_ip = self.op.primary_ip
3933

    
3934
    # copy the master/vm_capable flags
3935
    for attr in self._NFLAGS:
3936
      setattr(new_node, attr, getattr(self.op, attr))
3937

    
3938
    # notify the user about any possible mc promotion
3939
    if new_node.master_candidate:
3940
      self.LogInfo("Node will be a master candidate")
3941

    
3942
    # check connectivity
3943
    result = self.rpc.call_version([node])[node]
3944
    result.Raise("Can't get version information from node %s" % node)
3945
    if constants.PROTOCOL_VERSION == result.payload:
3946
      logging.info("Communication to node %s fine, sw version %s match",
3947
                   node, result.payload)
3948
    else:
3949
      raise errors.OpExecError("Version mismatch master version %s,"
3950
                               " node version %s" %
3951
                               (constants.PROTOCOL_VERSION, result.payload))
3952

    
3953
    # Add node to our /etc/hosts, and add key to known_hosts
3954
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3955
      master_node = self.cfg.GetMasterNode()
3956
      result = self.rpc.call_etc_hosts_modify(master_node,
3957
                                              constants.ETC_HOSTS_ADD,
3958
                                              self.hostname.name,
3959
                                              self.hostname.ip)
3960
      result.Raise("Can't update hosts file with new host data")
3961

    
3962
    if new_node.secondary_ip != new_node.primary_ip:
3963
      _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
3964
                               False)
3965

    
3966
    node_verify_list = [self.cfg.GetMasterNode()]
3967
    node_verify_param = {
3968
      constants.NV_NODELIST: [node],
3969
      # TODO: do a node-net-test as well?
3970
    }
3971

    
3972
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3973
                                       self.cfg.GetClusterName())
3974
    for verifier in node_verify_list:
3975
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3976
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3977
      if nl_payload:
3978
        for failed in nl_payload:
3979
          feedback_fn("ssh/hostname verification failed"
3980
                      " (checking from %s): %s" %
3981
                      (verifier, nl_payload[failed]))
3982
        raise errors.OpExecError("ssh/hostname verification failed.")
3983

    
3984
    if self.op.readd:
3985
      _RedistributeAncillaryFiles(self)
3986
      self.context.ReaddNode(new_node)
3987
      # make sure we redistribute the config
3988
      self.cfg.Update(new_node, feedback_fn)
3989
      # and make sure the new node will not have old files around
3990
      if not new_node.master_candidate:
3991
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3992
        msg = result.fail_msg
3993
        if msg:
3994
          self.LogWarning("Node failed to demote itself from master"
3995
                          " candidate status: %s" % msg)
3996
    else:
3997
      _RedistributeAncillaryFiles(self, additional_nodes=[node],
3998
                                  additional_vm=self.op.vm_capable)
3999
      self.context.AddNode(new_node, self.proc.GetECId())
4000

    
4001

    
4002
class LUSetNodeParams(LogicalUnit):
4003
  """Modifies the parameters of a node.
4004

4005
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
4006
      to the node role (as _ROLE_*)
4007
  @cvar _R2F: a dictionary from node role to tuples of flags
4008
  @cvar _FLAGS: a list of attribute names corresponding to the flags
4009

4010
  """
4011
  HPATH = "node-modify"
4012
  HTYPE = constants.HTYPE_NODE
4013
  _OP_PARAMS = [
4014
    _PNodeName,
4015
    ("master_candidate", None, ht.TMaybeBool),
4016
    ("offline", None, ht.TMaybeBool),
4017
    ("drained", None, ht.TMaybeBool),
4018
    ("auto_promote", False, ht.TBool),
4019
    ("master_capable", None, ht.TMaybeBool),
4020
    ("vm_capable", None, ht.TMaybeBool),
4021
    ("secondary_ip", None, ht.TMaybeString),
4022
    _PForce,
4023
    ]
4024
  REQ_BGL = False
4025
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
4026
  _F2R = {
4027
    (True, False, False): _ROLE_CANDIDATE,
4028
    (False, True, False): _ROLE_DRAINED,
4029
    (False, False, True): _ROLE_OFFLINE,
4030
    (False, False, False): _ROLE_REGULAR,
4031
    }
4032
  _R2F = dict((v, k) for k, v in _F2R.items())
4033
  _FLAGS = ["master_candidate", "drained", "offline"]
4034

    
4035
  def CheckArguments(self):
4036
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4037
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
4038
                self.op.master_capable, self.op.vm_capable,
4039
                self.op.secondary_ip]
4040
    if all_mods.count(None) == len(all_mods):
4041
      raise errors.OpPrereqError("Please pass at least one modification",
4042
                                 errors.ECODE_INVAL)
4043
    if all_mods.count(True) > 1:
4044
      raise errors.OpPrereqError("Can't set the node into more than one"
4045
                                 " state at the same time",
4046
                                 errors.ECODE_INVAL)
4047

    
4048
    # Boolean value that tells us whether we might be demoting from MC
4049
    self.might_demote = (self.op.master_candidate == False or
4050
                         self.op.offline == True or
4051
                         self.op.drained == True or
4052
                         self.op.master_capable == False)
4053

    
4054
    if self.op.secondary_ip:
4055
      if not netutils.IP4Address.IsValid(self.op.secondary_ip):
4056
        raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4057
                                   " address" % self.op.secondary_ip,
4058
                                   errors.ECODE_INVAL)
4059

    
4060
    self.lock_all = self.op.auto_promote and self.might_demote
4061
    self.lock_instances = self.op.secondary_ip is not None
4062

    
4063
  def ExpandNames(self):
4064
    if self.lock_all:
4065
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
4066
    else:
4067
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
4068

    
4069
    if self.lock_instances:
4070
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4071

    
4072
  def DeclareLocks(self, level):
4073
    # If we have locked all instances, before waiting to lock nodes, release
4074
    # all the ones living on nodes unrelated to the current operation.
4075
    if level == locking.LEVEL_NODE and self.lock_instances:
4076
      instances_release = []
4077
      instances_keep = []
4078
      self.affected_instances = []
4079
      if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4080
        for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
4081
          instance = self.context.cfg.GetInstanceInfo(instance_name)
4082
          i_mirrored = instance.disk_template in constants.DTS_NET_MIRROR
4083
          if i_mirrored and self.op.node_name in instance.all_nodes:
4084
            instances_keep.append(instance_name)
4085
            self.affected_instances.append(instance)
4086
          else:
4087
            instances_release.append(instance_name)
4088
        if instances_release:
4089
          self.context.glm.release(locking.LEVEL_INSTANCE, instances_release)
4090
          self.acquired_locks[locking.LEVEL_INSTANCE] = instances_keep
4091

    
4092
  def BuildHooksEnv(self):
4093
    """Build hooks env.
4094

4095
    This runs on the master node.
4096

4097
    """
4098
    env = {
4099
      "OP_TARGET": self.op.node_name,
4100
      "MASTER_CANDIDATE": str(self.op.master_candidate),
4101
      "OFFLINE": str(self.op.offline),
4102
      "DRAINED": str(self.op.drained),
4103
      "MASTER_CAPABLE": str(self.op.master_capable),
4104
      "VM_CAPABLE": str(self.op.vm_capable),
4105
      }
4106
    nl = [self.cfg.GetMasterNode(),
4107
          self.op.node_name]
4108
    return env, nl, nl
4109

    
4110
  def CheckPrereq(self):
4111
    """Check prerequisites.
4112

4113
    This only checks the instance list against the existing names.
4114

4115
    """
4116
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
4117

    
4118
    if (self.op.master_candidate is not None or
4119
        self.op.drained is not None or
4120
        self.op.offline is not None):
4121
      # we can't change the master's node flags
4122
      if self.op.node_name == self.cfg.GetMasterNode():
4123
        raise errors.OpPrereqError("The master role can be changed"
4124
                                   " only via master-failover",
4125
                                   errors.ECODE_INVAL)
4126

    
4127
    if self.op.master_candidate and not node.master_capable:
4128
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4129
                                 " it a master candidate" % node.name,
4130
                                 errors.ECODE_STATE)
4131

    
4132
    if self.op.vm_capable == False:
4133
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
4134
      if ipri or isec:
4135
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
4136
                                   " the vm_capable flag" % node.name,
4137
                                   errors.ECODE_STATE)
4138

    
4139
    if node.master_candidate and self.might_demote and not self.lock_all:
4140
      assert not self.op.auto_promote, "auto_promote set but lock_all not"
4141
      # check if after removing the current node, we're missing master
4142
      # candidates
4143
      (mc_remaining, mc_should, _) = \
4144
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
4145
      if mc_remaining < mc_should:
4146
        raise errors.OpPrereqError("Not enough master candidates, please"
4147
                                   " pass auto promote option to allow"
4148
                                   " promotion", errors.ECODE_STATE)
4149

    
4150
    self.old_flags = old_flags = (node.master_candidate,
4151
                                  node.drained, node.offline)
4152
    assert old_flags in self._F2R, "Un-handled old flags  %s" % str(old_flags)
4153
    self.old_role = old_role = self._F2R[old_flags]
4154

    
4155
    # Check for ineffective changes
4156
    for attr in self._FLAGS:
4157
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
4158
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
4159
        setattr(self.op, attr, None)
4160

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

    
4164
    # If we're being deofflined/drained, we'll MC ourself if needed
4165
    if (self.op.drained == False or self.op.offline == False or
4166
        (self.op.master_capable and not node.master_capable)):
4167
      if _DecideSelfPromotion(self):
4168
        self.op.master_candidate = True
4169
        self.LogInfo("Auto-promoting node to master candidate")
4170

    
4171
    # If we're no longer master capable, we'll demote ourselves from MC
4172
    if self.op.master_capable == False and node.master_candidate:
4173
      self.LogInfo("Demoting from master candidate")
4174
      self.op.master_candidate = False
4175

    
4176
    # Compute new role
4177
    assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
4178
    if self.op.master_candidate:
4179
      new_role = self._ROLE_CANDIDATE
4180
    elif self.op.drained:
4181
      new_role = self._ROLE_DRAINED
4182
    elif self.op.offline:
4183
      new_role = self._ROLE_OFFLINE
4184
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
4185
      # False is still in new flags, which means we're un-setting (the
4186
      # only) True flag
4187
      new_role = self._ROLE_REGULAR
4188
    else: # no new flags, nothing, keep old role
4189
      new_role = old_role
4190

    
4191
    self.new_role = new_role
4192

    
4193
    if old_role == self._ROLE_OFFLINE and new_role != old_role:
4194
      # Trying to transition out of offline status
4195
      result = self.rpc.call_version([node.name])[node.name]
4196
      if result.fail_msg:
4197
        raise errors.OpPrereqError("Node %s is being de-offlined but fails"
4198
                                   " to report its version: %s" %
4199
                                   (node.name, result.fail_msg),
4200
                                   errors.ECODE_STATE)
4201
      else:
4202
        self.LogWarning("Transitioning node from offline to online state"
4203
                        " without using re-add. Please make sure the node"
4204
                        " is healthy!")
4205

    
4206
    if self.op.secondary_ip:
4207
      # Ok even without locking, because this can't be changed by any LU
4208
      master = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
4209
      master_singlehomed = master.secondary_ip == master.primary_ip
4210
      if master_singlehomed and self.op.secondary_ip:
4211
        raise errors.OpPrereqError("Cannot change the secondary ip on a single"
4212
                                   " homed cluster", errors.ECODE_INVAL)
4213

    
4214
      if node.offline:
4215
        if self.affected_instances:
4216
          raise errors.OpPrereqError("Cannot change secondary ip: offline"
4217
                                     " node has instances (%s) configured"
4218
                                     " to use it" % self.affected_instances)
4219
      else:
4220
        # On online nodes, check that no instances are running, and that
4221
        # the node has the new ip and we can reach it.
4222
        for instance in self.affected_instances:
4223
          _CheckInstanceDown(self, instance, "cannot change secondary ip")
4224

    
4225
        _CheckNodeHasSecondaryIP(self, node.name, self.op.secondary_ip, True)
4226
        if master.name != node.name:
4227
          # check reachability from master secondary ip to new secondary ip
4228
          if not netutils.TcpPing(self.op.secondary_ip,
4229
                                  constants.DEFAULT_NODED_PORT,
4230
                                  source=master.secondary_ip):
4231
            raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4232
                                       " based ping to node daemon port",
4233
                                       errors.ECODE_ENVIRON)
4234

    
4235
  def Exec(self, feedback_fn):
4236
    """Modifies a node.
4237

4238
    """
4239
    node = self.node
4240
    old_role = self.old_role
4241
    new_role = self.new_role
4242

    
4243
    result = []
4244

    
4245
    for attr in ["master_capable", "vm_capable"]:
4246
      val = getattr(self.op, attr)
4247
      if val is not None:
4248
        setattr(node, attr, val)
4249
        result.append((attr, str(val)))
4250

    
4251
    if new_role != old_role:
4252
      # Tell the node to demote itself, if no longer MC and not offline
4253
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
4254
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
4255
        if msg:
4256
          self.LogWarning("Node failed to demote itself: %s", msg)
4257

    
4258
      new_flags = self._R2F[new_role]
4259
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
4260
        if of != nf:
4261
          result.append((desc, str(nf)))
4262
      (node.master_candidate, node.drained, node.offline) = new_flags
4263

    
4264
      # we locked all nodes, we adjust the CP before updating this node
4265
      if self.lock_all:
4266
        _AdjustCandidatePool(self, [node.name])
4267

    
4268
    if self.op.secondary_ip:
4269
      node.secondary_ip = self.op.secondary_ip
4270
      result.append(("secondary_ip", self.op.secondary_ip))
4271

    
4272
    # this will trigger configuration file update, if needed
4273
    self.cfg.Update(node, feedback_fn)
4274

    
4275
    # this will trigger job queue propagation or cleanup if the mc
4276
    # flag changed
4277
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
4278
      self.context.ReaddNode(node)
4279

    
4280
    return result
4281

    
4282

    
4283
class LUPowercycleNode(NoHooksLU):
4284
  """Powercycles a node.
4285

4286
  """
4287
  _OP_PARAMS = [
4288
    _PNodeName,
4289
    _PForce,
4290
    ]
4291
  REQ_BGL = False
4292

    
4293
  def CheckArguments(self):
4294
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4295
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4296
      raise errors.OpPrereqError("The node is the master and the force"
4297
                                 " parameter was not set",
4298
                                 errors.ECODE_INVAL)
4299

    
4300
  def ExpandNames(self):
4301
    """Locking for PowercycleNode.
4302

4303
    This is a last-resort option and shouldn't block on other
4304
    jobs. Therefore, we grab no locks.
4305

4306
    """
4307
    self.needed_locks = {}
4308

    
4309
  def Exec(self, feedback_fn):
4310
    """Reboots a node.
4311

4312
    """
4313
    result = self.rpc.call_node_powercycle(self.op.node_name,
4314
                                           self.cfg.GetHypervisorType())
4315
    result.Raise("Failed to schedule the reboot")
4316
    return result.payload
4317

    
4318

    
4319
class LUQueryClusterInfo(NoHooksLU):
4320
  """Query cluster configuration.
4321

4322
  """
4323
  REQ_BGL = False
4324

    
4325
  def ExpandNames(self):
4326
    self.needed_locks = {}
4327

    
4328
  def Exec(self, feedback_fn):
4329
    """Return cluster config.
4330

4331
    """
4332
    cluster = self.cfg.GetClusterInfo()
4333
    os_hvp = {}
4334

    
4335
    # Filter just for enabled hypervisors
4336
    for os_name, hv_dict in cluster.os_hvp.items():
4337
      os_hvp[os_name] = {}
4338
      for hv_name, hv_params in hv_dict.items():
4339
        if hv_name in cluster.enabled_hypervisors:
4340
          os_hvp[os_name][hv_name] = hv_params
4341

    
4342
    # Convert ip_family to ip_version
4343
    primary_ip_version = constants.IP4_VERSION
4344
    if cluster.primary_ip_family == netutils.IP6Address.family:
4345
      primary_ip_version = constants.IP6_VERSION
4346

    
4347
    result = {
4348
      "software_version": constants.RELEASE_VERSION,
4349
      "protocol_version": constants.PROTOCOL_VERSION,
4350
      "config_version": constants.CONFIG_VERSION,
4351
      "os_api_version": max(constants.OS_API_VERSIONS),
4352
      "export_version": constants.EXPORT_VERSION,
4353
      "architecture": (platform.architecture()[0], platform.machine()),
4354
      "name": cluster.cluster_name,
4355
      "master": cluster.master_node,
4356
      "default_hypervisor": cluster.enabled_hypervisors[0],
4357
      "enabled_hypervisors": cluster.enabled_hypervisors,
4358
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4359
                        for hypervisor_name in cluster.enabled_hypervisors]),
4360
      "os_hvp": os_hvp,
4361
      "beparams": cluster.beparams,
4362
      "osparams": cluster.osparams,
4363
      "nicparams": cluster.nicparams,
4364
      "candidate_pool_size": cluster.candidate_pool_size,
4365
      "master_netdev": cluster.master_netdev,
4366
      "volume_group_name": cluster.volume_group_name,
4367
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
4368
      "file_storage_dir": cluster.file_storage_dir,
4369
      "maintain_node_health": cluster.maintain_node_health,
4370
      "ctime": cluster.ctime,
4371
      "mtime": cluster.mtime,
4372
      "uuid": cluster.uuid,
4373
      "tags": list(cluster.GetTags()),
4374
      "uid_pool": cluster.uid_pool,
4375
      "default_iallocator": cluster.default_iallocator,
4376
      "reserved_lvs": cluster.reserved_lvs,
4377
      "primary_ip_version": primary_ip_version,
4378
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
4379
      }
4380

    
4381
    return result
4382

    
4383

    
4384
class LUQueryConfigValues(NoHooksLU):
4385
  """Return configuration values.
4386

4387
  """
4388
  _OP_PARAMS = [_POutputFields]
4389
  REQ_BGL = False
4390
  _FIELDS_DYNAMIC = utils.FieldSet()
4391
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4392
                                  "watcher_pause", "volume_group_name")
4393

    
4394
  def CheckArguments(self):
4395
    _CheckOutputFields(static=self._FIELDS_STATIC,
4396
                       dynamic=self._FIELDS_DYNAMIC,
4397
                       selected=self.op.output_fields)
4398

    
4399
  def ExpandNames(self):
4400
    self.needed_locks = {}
4401

    
4402
  def Exec(self, feedback_fn):
4403
    """Dump a representation of the cluster config to the standard output.
4404

4405
    """
4406
    values = []
4407
    for field in self.op.output_fields:
4408
      if field == "cluster_name":
4409
        entry = self.cfg.GetClusterName()
4410
      elif field == "master_node":
4411
        entry = self.cfg.GetMasterNode()
4412
      elif field == "drain_flag":
4413
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4414
      elif field == "watcher_pause":
4415
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4416
      elif field == "volume_group_name":
4417
        entry = self.cfg.GetVGName()
4418
      else:
4419
        raise errors.ParameterError(field)
4420
      values.append(entry)
4421
    return values
4422

    
4423

    
4424
class LUActivateInstanceDisks(NoHooksLU):
4425
  """Bring up an instance's disks.
4426

4427
  """
4428
  _OP_PARAMS = [
4429
    _PInstanceName,
4430
    ("ignore_size", False, ht.TBool),
4431
    ]
4432
  REQ_BGL = False
4433

    
4434
  def ExpandNames(self):
4435
    self._ExpandAndLockInstance()
4436
    self.needed_locks[locking.LEVEL_NODE] = []
4437
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4438

    
4439
  def DeclareLocks(self, level):
4440
    if level == locking.LEVEL_NODE:
4441
      self._LockInstancesNodes()
4442

    
4443
  def CheckPrereq(self):
4444
    """Check prerequisites.
4445

4446
    This checks that the instance is in the cluster.
4447

4448
    """
4449
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4450
    assert self.instance is not None, \
4451
      "Cannot retrieve locked instance %s" % self.op.instance_name
4452
    _CheckNodeOnline(self, self.instance.primary_node)
4453

    
4454
  def Exec(self, feedback_fn):
4455
    """Activate the disks.
4456

4457
    """
4458
    disks_ok, disks_info = \
4459
              _AssembleInstanceDisks(self, self.instance,
4460
                                     ignore_size=self.op.ignore_size)
4461
    if not disks_ok:
4462
      raise errors.OpExecError("Cannot activate block devices")
4463

    
4464
    return disks_info
4465

    
4466

    
4467
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4468
                           ignore_size=False):
4469
  """Prepare the block devices for an instance.
4470

4471
  This sets up the block devices on all nodes.
4472

4473
  @type lu: L{LogicalUnit}
4474
  @param lu: the logical unit on whose behalf we execute
4475
  @type instance: L{objects.Instance}
4476
  @param instance: the instance for whose disks we assemble
4477
  @type disks: list of L{objects.Disk} or None
4478
  @param disks: which disks to assemble (or all, if None)
4479
  @type ignore_secondaries: boolean
4480
  @param ignore_secondaries: if true, errors on secondary nodes
4481
      won't result in an error return from the function
4482
  @type ignore_size: boolean
4483
  @param ignore_size: if true, the current known size of the disk
4484
      will not be used during the disk activation, useful for cases
4485
      when the size is wrong
4486
  @return: False if the operation failed, otherwise a list of
4487
      (host, instance_visible_name, node_visible_name)
4488
      with the mapping from node devices to instance devices
4489

4490
  """
4491
  device_info = []
4492
  disks_ok = True
4493
  iname = instance.name
4494
  disks = _ExpandCheckDisks(instance, disks)
4495

    
4496
  # With the two passes mechanism we try to reduce the window of
4497
  # opportunity for the race condition of switching DRBD to primary
4498
  # before handshaking occured, but we do not eliminate it
4499

    
4500
  # The proper fix would be to wait (with some limits) until the
4501
  # connection has been made and drbd transitions from WFConnection
4502
  # into any other network-connected state (Connected, SyncTarget,
4503
  # SyncSource, etc.)
4504

    
4505
  # 1st pass, assemble on all nodes in secondary mode
4506
  for inst_disk in disks:
4507
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4508
      if ignore_size:
4509
        node_disk = node_disk.Copy()
4510
        node_disk.UnsetSize()
4511
      lu.cfg.SetDiskID(node_disk, node)
4512
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
4513
      msg = result.fail_msg
4514
      if msg:
4515
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4516
                           " (is_primary=False, pass=1): %s",
4517
                           inst_disk.iv_name, node, msg)
4518
        if not ignore_secondaries:
4519
          disks_ok = False
4520

    
4521
  # FIXME: race condition on drbd migration to primary
4522

    
4523
  # 2nd pass, do only the primary node
4524
  for inst_disk in disks:
4525
    dev_path = None
4526

    
4527
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4528
      if node != instance.primary_node:
4529
        continue
4530
      if ignore_size:
4531
        node_disk = node_disk.Copy()
4532
        node_disk.UnsetSize()
4533
      lu.cfg.SetDiskID(node_disk, node)
4534
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
4535
      msg = result.fail_msg
4536
      if msg:
4537
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4538
                           " (is_primary=True, pass=2): %s",
4539
                           inst_disk.iv_name, node, msg)
4540
        disks_ok = False
4541
      else:
4542
        dev_path = result.payload
4543

    
4544
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4545

    
4546
  # leave the disks configured for the primary node
4547
  # this is a workaround that would be fixed better by
4548
  # improving the logical/physical id handling
4549
  for disk in disks:
4550
    lu.cfg.SetDiskID(disk, instance.primary_node)
4551

    
4552
  return disks_ok, device_info
4553

    
4554

    
4555
def _StartInstanceDisks(lu, instance, force):
4556
  """Start the disks of an instance.
4557

4558
  """
4559
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4560
                                           ignore_secondaries=force)
4561
  if not disks_ok:
4562
    _ShutdownInstanceDisks(lu, instance)
4563
    if force is not None and not force:
4564
      lu.proc.LogWarning("", hint="If the message above refers to a"
4565
                         " secondary node,"
4566
                         " you can retry the operation using '--force'.")
4567
    raise errors.OpExecError("Disk consistency error")
4568

    
4569

    
4570
class LUDeactivateInstanceDisks(NoHooksLU):
4571
  """Shutdown an instance's disks.
4572

4573
  """
4574
  _OP_PARAMS = [
4575
    _PInstanceName,
4576
    ]
4577
  REQ_BGL = False
4578

    
4579
  def ExpandNames(self):
4580
    self._ExpandAndLockInstance()
4581
    self.needed_locks[locking.LEVEL_NODE] = []
4582
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4583

    
4584
  def DeclareLocks(self, level):
4585
    if level == locking.LEVEL_NODE:
4586
      self._LockInstancesNodes()
4587

    
4588
  def CheckPrereq(self):
4589
    """Check prerequisites.
4590

4591
    This checks that the instance is in the cluster.
4592

4593
    """
4594
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4595
    assert self.instance is not None, \
4596
      "Cannot retrieve locked instance %s" % self.op.instance_name
4597

    
4598
  def Exec(self, feedback_fn):
4599
    """Deactivate the disks
4600

4601
    """
4602
    instance = self.instance
4603
    _SafeShutdownInstanceDisks(self, instance)
4604

    
4605

    
4606
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4607
  """Shutdown block devices of an instance.
4608

4609
  This function checks if an instance is running, before calling
4610
  _ShutdownInstanceDisks.
4611

4612
  """
4613
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4614
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4615

    
4616

    
4617
def _ExpandCheckDisks(instance, disks):
4618
  """Return the instance disks selected by the disks list
4619

4620
  @type disks: list of L{objects.Disk} or None
4621
  @param disks: selected disks
4622
  @rtype: list of L{objects.Disk}
4623
  @return: selected instance disks to act on
4624

4625
  """
4626
  if disks is None:
4627
    return instance.disks
4628
  else:
4629
    if not set(disks).issubset(instance.disks):
4630
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4631
                                   " target instance")
4632
    return disks
4633

    
4634

    
4635
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4636
  """Shutdown block devices of an instance.
4637

4638
  This does the shutdown on all nodes of the instance.
4639

4640
  If the ignore_primary is false, errors on the primary node are
4641
  ignored.
4642

4643
  """
4644
  all_result = True
4645
  disks = _ExpandCheckDisks(instance, disks)
4646

    
4647
  for disk in disks:
4648
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4649
      lu.cfg.SetDiskID(top_disk, node)
4650
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4651
      msg = result.fail_msg
4652
      if msg:
4653
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4654
                      disk.iv_name, node, msg)
4655
        if not ignore_primary or node != instance.primary_node:
4656
          all_result = False
4657
  return all_result
4658

    
4659

    
4660
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4661
  """Checks if a node has enough free memory.
4662

4663
  This function check if a given node has the needed amount of free
4664
  memory. In case the node has less memory or we cannot get the
4665
  information from the node, this function raise an OpPrereqError
4666
  exception.
4667

4668
  @type lu: C{LogicalUnit}
4669
  @param lu: a logical unit from which we get configuration data
4670
  @type node: C{str}
4671
  @param node: the node to check
4672
  @type reason: C{str}
4673
  @param reason: string to use in the error message
4674
  @type requested: C{int}
4675
  @param requested: the amount of memory in MiB to check for
4676
  @type hypervisor_name: C{str}
4677
  @param hypervisor_name: the hypervisor to ask for memory stats
4678
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4679
      we cannot check the node
4680

4681
  """
4682
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
4683
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4684
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4685
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4686
  if not isinstance(free_mem, int):
4687
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4688
                               " was '%s'" % (node, free_mem),
4689
                               errors.ECODE_ENVIRON)
4690
  if requested > free_mem:
4691
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
4692
                               " needed %s MiB, available %s MiB" %
4693
                               (node, reason, requested, free_mem),
4694
                               errors.ECODE_NORES)
4695

    
4696

    
4697
def _CheckNodesFreeDisk(lu, nodenames, requested):
4698
  """Checks if nodes have enough free disk space in the default VG.
4699

4700
  This function check if all given nodes have the needed amount of
4701
  free disk. In case any node has less disk or we cannot get the
4702
  information from the node, this function raise an OpPrereqError
4703
  exception.
4704

4705
  @type lu: C{LogicalUnit}
4706
  @param lu: a logical unit from which we get configuration data
4707
  @type nodenames: C{list}
4708
  @param nodenames: the list of node names to check
4709
  @type requested: C{int}
4710
  @param requested: the amount of disk in MiB to check for
4711
  @raise errors.OpPrereqError: if the node doesn't have enough disk, or
4712
      we cannot check the node
4713

4714
  """
4715
  nodeinfo = lu.rpc.call_node_info(nodenames, lu.cfg.GetVGName(),
4716
                                   lu.cfg.GetHypervisorType())
4717
  for node in nodenames:
4718
    info = nodeinfo[node]
4719
    info.Raise("Cannot get current information from node %s" % node,
4720
               prereq=True, ecode=errors.ECODE_ENVIRON)
4721
    vg_free = info.payload.get("vg_free", None)
4722
    if not isinstance(vg_free, int):
4723
      raise errors.OpPrereqError("Can't compute free disk space on node %s,"
4724
                                 " result was '%s'" % (node, vg_free),
4725
                                 errors.ECODE_ENVIRON)
4726
    if requested > vg_free:
4727
      raise errors.OpPrereqError("Not enough disk space on target node %s:"
4728
                                 " required %d MiB, available %d MiB" %
4729
                                 (node, requested, vg_free),
4730
                                 errors.ECODE_NORES)
4731

    
4732

    
4733
class LUStartupInstance(LogicalUnit):
4734
  """Starts an instance.
4735

4736
  """
4737
  HPATH = "instance-start"
4738
  HTYPE = constants.HTYPE_INSTANCE
4739
  _OP_PARAMS = [
4740
    _PInstanceName,
4741
    _PForce,
4742
    _PIgnoreOfflineNodes,
4743
    ("hvparams", ht.EmptyDict, ht.TDict),
4744
    ("beparams", ht.EmptyDict, ht.TDict),
4745
    ]
4746
  REQ_BGL = False
4747

    
4748
  def CheckArguments(self):
4749
    # extra beparams
4750
    if self.op.beparams:
4751
      # fill the beparams dict
4752
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
4753

    
4754
  def ExpandNames(self):
4755
    self._ExpandAndLockInstance()
4756

    
4757
  def BuildHooksEnv(self):
4758
    """Build hooks env.
4759

4760
    This runs on master, primary and secondary nodes of the instance.
4761

4762
    """
4763
    env = {
4764
      "FORCE": self.op.force,
4765
      }
4766
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4767
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4768
    return env, nl, nl
4769

    
4770
  def CheckPrereq(self):
4771
    """Check prerequisites.
4772

4773
    This checks that the instance is in the cluster.
4774

4775
    """
4776
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4777
    assert self.instance is not None, \
4778
      "Cannot retrieve locked instance %s" % self.op.instance_name
4779

    
4780
    # extra hvparams
4781
    if self.op.hvparams:
4782
      # check hypervisor parameter syntax (locally)
4783
      cluster = self.cfg.GetClusterInfo()
4784
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
4785
      filled_hvp = cluster.FillHV(instance)
4786
      filled_hvp.update(self.op.hvparams)
4787
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
4788
      hv_type.CheckParameterSyntax(filled_hvp)
4789
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
4790

    
4791
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
4792

    
4793
    if self.primary_offline and self.op.ignore_offline_nodes:
4794
      self.proc.LogWarning("Ignoring offline primary node")
4795

    
4796
      if self.op.hvparams or self.op.beparams:
4797
        self.proc.LogWarning("Overridden parameters are ignored")
4798
    else:
4799
      _CheckNodeOnline(self, instance.primary_node)
4800

    
4801
      bep = self.cfg.GetClusterInfo().FillBE(instance)
4802

    
4803
      # check bridges existence
4804
      _CheckInstanceBridgesExist(self, instance)
4805

    
4806
      remote_info = self.rpc.call_instance_info(instance.primary_node,
4807
                                                instance.name,
4808
                                                instance.hypervisor)
4809
      remote_info.Raise("Error checking node %s" % instance.primary_node,
4810
                        prereq=True, ecode=errors.ECODE_ENVIRON)
4811
      if not remote_info.payload: # not running already
4812
        _CheckNodeFreeMemory(self, instance.primary_node,
4813
                             "starting instance %s" % instance.name,
4814
                             bep[constants.BE_MEMORY], instance.hypervisor)
4815

    
4816
  def Exec(self, feedback_fn):
4817
    """Start the instance.
4818

4819
    """
4820
    instance = self.instance
4821
    force = self.op.force
4822

    
4823
    self.cfg.MarkInstanceUp(instance.name)
4824

    
4825
    if self.primary_offline:
4826
      assert self.op.ignore_offline_nodes
4827
      self.proc.LogInfo("Primary node offline, marked instance as started")
4828
    else:
4829
      node_current = instance.primary_node
4830

    
4831
      _StartInstanceDisks(self, instance, force)
4832

    
4833
      result = self.rpc.call_instance_start(node_current, instance,
4834
                                            self.op.hvparams, self.op.beparams)
4835
      msg = result.fail_msg
4836
      if msg:
4837
        _ShutdownInstanceDisks(self, instance)
4838
        raise errors.OpExecError("Could not start instance: %s" % msg)
4839

    
4840

    
4841
class LURebootInstance(LogicalUnit):
4842
  """Reboot an instance.
4843

4844
  """
4845
  HPATH = "instance-reboot"
4846
  HTYPE = constants.HTYPE_INSTANCE
4847
  _OP_PARAMS = [
4848
    _PInstanceName,
4849
    ("ignore_secondaries", False, ht.TBool),
4850
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES)),
4851
    _PShutdownTimeout,
4852
    ]
4853
  REQ_BGL = False
4854

    
4855
  def ExpandNames(self):
4856
    self._ExpandAndLockInstance()
4857

    
4858
  def BuildHooksEnv(self):
4859
    """Build hooks env.
4860

4861
    This runs on master, primary and secondary nodes of the instance.
4862

4863
    """
4864
    env = {
4865
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
4866
      "REBOOT_TYPE": self.op.reboot_type,
4867
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
4868
      }
4869
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4870
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4871
    return env, nl, nl
4872

    
4873
  def CheckPrereq(self):
4874
    """Check prerequisites.
4875

4876
    This checks that the instance is in the cluster.
4877

4878
    """
4879
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4880
    assert self.instance is not None, \
4881
      "Cannot retrieve locked instance %s" % self.op.instance_name
4882

    
4883
    _CheckNodeOnline(self, instance.primary_node)
4884

    
4885
    # check bridges existence
4886
    _CheckInstanceBridgesExist(self, instance)
4887

    
4888
  def Exec(self, feedback_fn):
4889
    """Reboot the instance.
4890

4891
    """
4892
    instance = self.instance
4893
    ignore_secondaries = self.op.ignore_secondaries
4894
    reboot_type = self.op.reboot_type
4895

    
4896
    node_current = instance.primary_node
4897

    
4898
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
4899
                       constants.INSTANCE_REBOOT_HARD]:
4900
      for disk in instance.disks:
4901
        self.cfg.SetDiskID(disk, node_current)
4902
      result = self.rpc.call_instance_reboot(node_current, instance,
4903
                                             reboot_type,
4904
                                             self.op.shutdown_timeout)
4905
      result.Raise("Could not reboot instance")
4906
    else:
4907
      result = self.rpc.call_instance_shutdown(node_current, instance,
4908
                                               self.op.shutdown_timeout)
4909
      result.Raise("Could not shutdown instance for full reboot")
4910
      _ShutdownInstanceDisks(self, instance)
4911
      _StartInstanceDisks(self, instance, ignore_secondaries)
4912
      result = self.rpc.call_instance_start(node_current, instance, None, None)
4913
      msg = result.fail_msg
4914
      if msg:
4915
        _ShutdownInstanceDisks(self, instance)
4916
        raise errors.OpExecError("Could not start instance for"
4917
                                 " full reboot: %s" % msg)
4918

    
4919
    self.cfg.MarkInstanceUp(instance.name)
4920

    
4921

    
4922
class LUShutdownInstance(LogicalUnit):
4923
  """Shutdown an instance.
4924

4925
  """
4926
  HPATH = "instance-stop"
4927
  HTYPE = constants.HTYPE_INSTANCE
4928
  _OP_PARAMS = [
4929
    _PInstanceName,
4930
    _PIgnoreOfflineNodes,
4931
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt),
4932
    ]
4933
  REQ_BGL = False
4934

    
4935
  def ExpandNames(self):
4936
    self._ExpandAndLockInstance()
4937

    
4938
  def BuildHooksEnv(self):
4939
    """Build hooks env.
4940

4941
    This runs on master, primary and secondary nodes of the instance.
4942

4943
    """
4944
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4945
    env["TIMEOUT"] = self.op.timeout
4946
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4947
    return env, nl, nl
4948

    
4949
  def CheckPrereq(self):
4950
    """Check prerequisites.
4951

4952
    This checks that the instance is in the cluster.
4953

4954
    """
4955
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4956
    assert self.instance is not None, \
4957
      "Cannot retrieve locked instance %s" % self.op.instance_name
4958

    
4959
    self.primary_offline = \
4960
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
4961

    
4962
    if self.primary_offline and self.op.ignore_offline_nodes:
4963
      self.proc.LogWarning("Ignoring offline primary node")
4964
    else:
4965
      _CheckNodeOnline(self, self.instance.primary_node)
4966

    
4967
  def Exec(self, feedback_fn):
4968
    """Shutdown the instance.
4969

4970
    """
4971
    instance = self.instance
4972
    node_current = instance.primary_node
4973
    timeout = self.op.timeout
4974

    
4975
    self.cfg.MarkInstanceDown(instance.name)
4976

    
4977
    if self.primary_offline:
4978
      assert self.op.ignore_offline_nodes
4979
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
4980
    else:
4981
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
4982
      msg = result.fail_msg
4983
      if msg:
4984
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
4985

    
4986
      _ShutdownInstanceDisks(self, instance)
4987

    
4988

    
4989
class LUReinstallInstance(LogicalUnit):
4990
  """Reinstall an instance.
4991

4992
  """
4993
  HPATH = "instance-reinstall"
4994
  HTYPE = constants.HTYPE_INSTANCE
4995
  _OP_PARAMS = [
4996
    _PInstanceName,
4997
    ("os_type", None, ht.TMaybeString),
4998
    ("force_variant", False, ht.TBool),
4999
    ("osparams", None, ht.TOr(ht.TDict, ht.TNone)),
5000
    ]
5001
  REQ_BGL = False
5002

    
5003
  def ExpandNames(self):
5004
    self._ExpandAndLockInstance()
5005

    
5006
  def BuildHooksEnv(self):
5007
    """Build hooks env.
5008

5009
    This runs on master, primary and secondary nodes of the instance.
5010

5011
    """
5012
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5013
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5014
    return env, nl, nl
5015

    
5016
  def CheckPrereq(self):
5017
    """Check prerequisites.
5018

5019
    This checks that the instance is in the cluster and is not running.
5020

5021
    """
5022
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5023
    assert instance is not None, \
5024
      "Cannot retrieve locked instance %s" % self.op.instance_name
5025
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
5026
                     " offline, cannot reinstall")
5027
    for node in instance.secondary_nodes:
5028
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
5029
                       " cannot reinstall")
5030

    
5031
    if instance.disk_template == constants.DT_DISKLESS:
5032
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5033
                                 self.op.instance_name,
5034
                                 errors.ECODE_INVAL)
5035
    _CheckInstanceDown(self, instance, "cannot reinstall")
5036

    
5037
    if self.op.os_type is not None:
5038
      # OS verification
5039
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
5040
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
5041
      instance_os = self.op.os_type
5042
    else:
5043
      instance_os = instance.os
5044

    
5045
    nodelist = list(instance.all_nodes)
5046

    
5047
    if self.op.osparams:
5048
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
5049
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
5050
      self.os_inst = i_osdict # the new dict (without defaults)
5051
    else:
5052
      self.os_inst = None
5053

    
5054
    self.instance = instance
5055

    
5056
  def Exec(self, feedback_fn):
5057
    """Reinstall the instance.
5058

5059
    """
5060
    inst = self.instance
5061

    
5062
    if self.op.os_type is not None:
5063
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
5064
      inst.os = self.op.os_type
5065
      # Write to configuration
5066
      self.cfg.Update(inst, feedback_fn)
5067

    
5068
    _StartInstanceDisks(self, inst, None)
5069
    try:
5070
      feedback_fn("Running the instance OS create scripts...")
5071
      # FIXME: pass debug option from opcode to backend
5072
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
5073
                                             self.op.debug_level,
5074
                                             osparams=self.os_inst)
5075
      result.Raise("Could not install OS for instance %s on node %s" %
5076
                   (inst.name, inst.primary_node))
5077
    finally:
5078
      _ShutdownInstanceDisks(self, inst)
5079

    
5080

    
5081
class LURecreateInstanceDisks(LogicalUnit):
5082
  """Recreate an instance's missing disks.
5083

5084
  """
5085
  HPATH = "instance-recreate-disks"
5086
  HTYPE = constants.HTYPE_INSTANCE
5087
  _OP_PARAMS = [
5088
    _PInstanceName,
5089
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt)),
5090
    ]
5091
  REQ_BGL = False
5092

    
5093
  def ExpandNames(self):
5094
    self._ExpandAndLockInstance()
5095

    
5096
  def BuildHooksEnv(self):
5097
    """Build hooks env.
5098

5099
    This runs on master, primary and secondary nodes of the instance.
5100

5101
    """
5102
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5103
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5104
    return env, nl, nl
5105

    
5106
  def CheckPrereq(self):
5107
    """Check prerequisites.
5108

5109
    This checks that the instance is in the cluster and is not running.
5110

5111
    """
5112
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5113
    assert instance is not None, \
5114
      "Cannot retrieve locked instance %s" % self.op.instance_name
5115
    _CheckNodeOnline(self, instance.primary_node)
5116

    
5117
    if instance.disk_template == constants.DT_DISKLESS:
5118
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5119
                                 self.op.instance_name, errors.ECODE_INVAL)
5120
    _CheckInstanceDown(self, instance, "cannot recreate disks")
5121

    
5122
    if not self.op.disks:
5123
      self.op.disks = range(len(instance.disks))
5124
    else:
5125
      for idx in self.op.disks:
5126
        if idx >= len(instance.disks):
5127
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
5128
                                     errors.ECODE_INVAL)
5129

    
5130
    self.instance = instance
5131

    
5132
  def Exec(self, feedback_fn):
5133
    """Recreate the disks.
5134

5135
    """
5136
    to_skip = []
5137
    for idx, _ in enumerate(self.instance.disks):
5138
      if idx not in self.op.disks: # disk idx has not been passed in
5139
        to_skip.append(idx)
5140
        continue
5141

    
5142
    _CreateDisks(self, self.instance, to_skip=to_skip)
5143

    
5144

    
5145
class LURenameInstance(LogicalUnit):
5146
  """Rename an instance.
5147

5148
  """
5149
  HPATH = "instance-rename"
5150
  HTYPE = constants.HTYPE_INSTANCE
5151
  _OP_PARAMS = [
5152
    _PInstanceName,
5153
    ("new_name", ht.NoDefault, ht.TNonEmptyString),
5154
    ("ip_check", False, ht.TBool),
5155
    ("name_check", True, ht.TBool),
5156
    ]
5157

    
5158
  def CheckArguments(self):
5159
    """Check arguments.
5160

5161
    """
5162
    if self.op.ip_check and not self.op.name_check:
5163
      # TODO: make the ip check more flexible and not depend on the name check
5164
      raise errors.OpPrereqError("Cannot do ip check without a name check",
5165
                                 errors.ECODE_INVAL)
5166

    
5167
  def BuildHooksEnv(self):
5168
    """Build hooks env.
5169

5170
    This runs on master, primary and secondary nodes of the instance.
5171

5172
    """
5173
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5174
    env["INSTANCE_NEW_NAME"] = self.op.new_name
5175
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5176
    return env, nl, nl
5177

    
5178
  def CheckPrereq(self):
5179
    """Check prerequisites.
5180

5181
    This checks that the instance is in the cluster and is not running.
5182

5183
    """
5184
    self.op.instance_name = _ExpandInstanceName(self.cfg,
5185
                                                self.op.instance_name)
5186
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5187
    assert instance is not None
5188
    _CheckNodeOnline(self, instance.primary_node)
5189
    _CheckInstanceDown(self, instance, "cannot rename")
5190
    self.instance = instance
5191

    
5192
    new_name = self.op.new_name
5193
    if self.op.name_check:
5194
      hostname = netutils.GetHostname(name=new_name)
5195
      new_name = self.op.new_name = hostname.name
5196
      if (self.op.ip_check and
5197
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
5198
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
5199
                                   (hostname.ip, new_name),
5200
                                   errors.ECODE_NOTUNIQUE)
5201

    
5202
    instance_list = self.cfg.GetInstanceList()
5203
    if new_name in instance_list:
5204
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5205
                                 new_name, errors.ECODE_EXISTS)
5206

    
5207
  def Exec(self, feedback_fn):
5208
    """Reinstall the instance.
5209

5210
    """
5211
    inst = self.instance
5212
    old_name = inst.name
5213

    
5214
    if inst.disk_template == constants.DT_FILE:
5215
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5216

    
5217
    self.cfg.RenameInstance(inst.name, self.op.new_name)
5218
    # Change the instance lock. This is definitely safe while we hold the BGL
5219
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
5220
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
5221

    
5222
    # re-read the instance from the configuration after rename
5223
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
5224

    
5225
    if inst.disk_template == constants.DT_FILE:
5226
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5227
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
5228
                                                     old_file_storage_dir,
5229
                                                     new_file_storage_dir)
5230
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
5231
                   " (but the instance has been renamed in Ganeti)" %
5232
                   (inst.primary_node, old_file_storage_dir,
5233
                    new_file_storage_dir))
5234

    
5235
    _StartInstanceDisks(self, inst, None)
5236
    try:
5237
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
5238
                                                 old_name, self.op.debug_level)
5239
      msg = result.fail_msg
5240
      if msg:
5241
        msg = ("Could not run OS rename script for instance %s on node %s"
5242
               " (but the instance has been renamed in Ganeti): %s" %
5243
               (inst.name, inst.primary_node, msg))
5244
        self.proc.LogWarning(msg)
5245
    finally:
5246
      _ShutdownInstanceDisks(self, inst)
5247

    
5248
    return inst.name
5249

    
5250

    
5251
class LURemoveInstance(LogicalUnit):
5252
  """Remove an instance.
5253

5254
  """
5255
  HPATH = "instance-remove"
5256
  HTYPE = constants.HTYPE_INSTANCE
5257
  _OP_PARAMS = [
5258
    _PInstanceName,
5259
    ("ignore_failures", False, ht.TBool),
5260
    _PShutdownTimeout,
5261
    ]
5262
  REQ_BGL = False
5263

    
5264
  def ExpandNames(self):
5265
    self._ExpandAndLockInstance()
5266
    self.needed_locks[locking.LEVEL_NODE] = []
5267
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5268

    
5269
  def DeclareLocks(self, level):
5270
    if level == locking.LEVEL_NODE:
5271
      self._LockInstancesNodes()
5272

    
5273
  def BuildHooksEnv(self):
5274
    """Build hooks env.
5275

5276
    This runs on master, primary and secondary nodes of the instance.
5277

5278
    """
5279
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5280
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
5281
    nl = [self.cfg.GetMasterNode()]
5282
    nl_post = list(self.instance.all_nodes) + nl
5283
    return env, nl, nl_post
5284

    
5285
  def CheckPrereq(self):
5286
    """Check prerequisites.
5287

5288
    This checks that the instance is in the cluster.
5289

5290
    """
5291
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5292
    assert self.instance is not None, \
5293
      "Cannot retrieve locked instance %s" % self.op.instance_name
5294

    
5295
  def Exec(self, feedback_fn):
5296
    """Remove the instance.
5297

5298
    """
5299
    instance = self.instance
5300
    logging.info("Shutting down instance %s on node %s",
5301
                 instance.name, instance.primary_node)
5302

    
5303
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5304
                                             self.op.shutdown_timeout)
5305
    msg = result.fail_msg
5306
    if msg:
5307
      if self.op.ignore_failures:
5308
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5309
      else:
5310
        raise errors.OpExecError("Could not shutdown instance %s on"
5311
                                 " node %s: %s" %
5312
                                 (instance.name, instance.primary_node, msg))
5313

    
5314
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5315

    
5316

    
5317
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5318
  """Utility function to remove an instance.
5319

5320
  """
5321
  logging.info("Removing block devices for instance %s", instance.name)
5322

    
5323
  if not _RemoveDisks(lu, instance):
5324
    if not ignore_failures:
5325
      raise errors.OpExecError("Can't remove instance's disks")
5326
    feedback_fn("Warning: can't remove instance's disks")
5327

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

    
5330
  lu.cfg.RemoveInstance(instance.name)
5331

    
5332
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5333
    "Instance lock removal conflict"
5334

    
5335
  # Remove lock for the instance
5336
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5337

    
5338

    
5339
class LUQueryInstances(NoHooksLU):
5340
  """Logical unit for querying instances.
5341

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

    
5377

    
5378
  def CheckArguments(self):
5379
    _CheckOutputFields(static=self._FIELDS_STATIC,
5380
                       dynamic=self._FIELDS_DYNAMIC,
5381
                       selected=self.op.output_fields)
5382

    
5383
  def ExpandNames(self):
5384
    self.needed_locks = {}
5385
    self.share_locks[locking.LEVEL_INSTANCE] = 1
5386
    self.share_locks[locking.LEVEL_NODE] = 1
5387

    
5388
    if self.op.names:
5389
      self.wanted = _GetWantedInstances(self, self.op.names)
5390
    else:
5391
      self.wanted = locking.ALL_SET
5392

    
5393
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
5394
    self.do_locking = self.do_node_query and self.op.use_locking
5395
    if self.do_locking:
5396
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
5397
      self.needed_locks[locking.LEVEL_NODE] = []
5398
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5399

    
5400
  def DeclareLocks(self, level):
5401
    if level == locking.LEVEL_NODE and self.do_locking:
5402
      self._LockInstancesNodes()
5403

    
5404
  def Exec(self, feedback_fn):
5405
    """Computes the list of nodes and their attributes.
5406

5407
    """
5408
    # pylint: disable-msg=R0912
5409
    # way too many branches here
5410
    all_info = self.cfg.GetAllInstancesInfo()
5411
    if self.wanted == locking.ALL_SET:
5412
      # caller didn't specify instance names, so ordering is not important
5413
      if self.do_locking:
5414
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5415
      else:
5416
        instance_names = all_info.keys()
5417
      instance_names = utils.NiceSort(instance_names)
5418
    else:
5419
      # caller did specify names, so we must keep the ordering
5420
      if self.do_locking:
5421
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
5422
      else:
5423
        tgt_set = all_info.keys()
5424
      missing = set(self.wanted).difference(tgt_set)
5425
      if missing:
5426
        raise errors.OpExecError("Some instances were removed before"
5427
                                 " retrieving their data: %s" % missing)
5428
      instance_names = self.wanted
5429

    
5430
    instance_list = [all_info[iname] for iname in instance_names]
5431

    
5432
    # begin data gathering
5433

    
5434
    nodes = frozenset([inst.primary_node for inst in instance_list])
5435
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
5436

    
5437
    bad_nodes = []
5438
    off_nodes = []
5439
    if self.do_node_query:
5440
      live_data = {}
5441
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
5442
      for name in nodes:
5443
        result = node_data[name]
5444
        if result.offline:
5445
          # offline nodes will be in both lists
5446
          off_nodes.append(name)
5447
        if result.fail_msg:
5448
          bad_nodes.append(name)
5449
        else:
5450
          if result.payload:
5451
            live_data.update(result.payload)
5452
          # else no instance is alive
5453
    else:
5454
      live_data = dict([(name, {}) for name in instance_names])
5455

    
5456
    # end data gathering
5457

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

    
5634
    return output
5635

    
5636

    
5637
class LUFailoverInstance(LogicalUnit):
5638
  """Failover an instance.
5639

5640
  """
5641
  HPATH = "instance-failover"
5642
  HTYPE = constants.HTYPE_INSTANCE
5643
  _OP_PARAMS = [
5644
    _PInstanceName,
5645
    ("ignore_consistency", False, ht.TBool),
5646
    _PShutdownTimeout,
5647
    ]
5648
  REQ_BGL = False
5649

    
5650
  def ExpandNames(self):
5651
    self._ExpandAndLockInstance()
5652
    self.needed_locks[locking.LEVEL_NODE] = []
5653
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5654

    
5655
  def DeclareLocks(self, level):
5656
    if level == locking.LEVEL_NODE:
5657
      self._LockInstancesNodes()
5658

    
5659
  def BuildHooksEnv(self):
5660
    """Build hooks env.
5661

5662
    This runs on master, primary and secondary nodes of the instance.
5663

5664
    """
5665
    instance = self.instance
5666
    source_node = instance.primary_node
5667
    target_node = instance.secondary_nodes[0]
5668
    env = {
5669
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5670
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5671
      "OLD_PRIMARY": source_node,
5672
      "OLD_SECONDARY": target_node,
5673
      "NEW_PRIMARY": target_node,
5674
      "NEW_SECONDARY": source_node,
5675
      }
5676
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5677
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5678
    nl_post = list(nl)
5679
    nl_post.append(source_node)
5680
    return env, nl, nl_post
5681

    
5682
  def CheckPrereq(self):
5683
    """Check prerequisites.
5684

5685
    This checks that the instance is in the cluster.
5686

5687
    """
5688
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5689
    assert self.instance is not None, \
5690
      "Cannot retrieve locked instance %s" % self.op.instance_name
5691

    
5692
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5693
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5694
      raise errors.OpPrereqError("Instance's disk layout is not"
5695
                                 " network mirrored, cannot failover.",
5696
                                 errors.ECODE_STATE)
5697

    
5698
    secondary_nodes = instance.secondary_nodes
5699
    if not secondary_nodes:
5700
      raise errors.ProgrammerError("no secondary node but using "
5701
                                   "a mirrored disk template")
5702

    
5703
    target_node = secondary_nodes[0]
5704
    _CheckNodeOnline(self, target_node)
5705
    _CheckNodeNotDrained(self, target_node)
5706
    if instance.admin_up:
5707
      # check memory requirements on the secondary node
5708
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5709
                           instance.name, bep[constants.BE_MEMORY],
5710
                           instance.hypervisor)
5711
    else:
5712
      self.LogInfo("Not checking memory on the secondary node as"
5713
                   " instance will not be started")
5714

    
5715
    # check bridge existance
5716
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5717

    
5718
  def Exec(self, feedback_fn):
5719
    """Failover an instance.
5720

5721
    The failover is done by shutting it down on its present node and
5722
    starting it on the secondary.
5723

5724
    """
5725
    instance = self.instance
5726
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
5727

    
5728
    source_node = instance.primary_node
5729
    target_node = instance.secondary_nodes[0]
5730

    
5731
    if instance.admin_up:
5732
      feedback_fn("* checking disk consistency between source and target")
5733
      for dev in instance.disks:
5734
        # for drbd, these are drbd over lvm
5735
        if not _CheckDiskConsistency(self, dev, target_node, False):
5736
          if not self.op.ignore_consistency:
5737
            raise errors.OpExecError("Disk %s is degraded on target node,"
5738
                                     " aborting failover." % dev.iv_name)
5739
    else:
5740
      feedback_fn("* not checking disk consistency as instance is not running")
5741

    
5742
    feedback_fn("* shutting down instance on source node")
5743
    logging.info("Shutting down instance %s on node %s",
5744
                 instance.name, source_node)
5745

    
5746
    result = self.rpc.call_instance_shutdown(source_node, instance,
5747
                                             self.op.shutdown_timeout)
5748
    msg = result.fail_msg
5749
    if msg:
5750
      if self.op.ignore_consistency or primary_node.offline:
5751
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5752
                             " Proceeding anyway. Please make sure node"
5753
                             " %s is down. Error details: %s",
5754
                             instance.name, source_node, source_node, msg)
5755
      else:
5756
        raise errors.OpExecError("Could not shutdown instance %s on"
5757
                                 " node %s: %s" %
5758
                                 (instance.name, source_node, msg))
5759

    
5760
    feedback_fn("* deactivating the instance's disks on source node")
5761
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5762
      raise errors.OpExecError("Can't shut down the instance's disks.")
5763

    
5764
    instance.primary_node = target_node
5765
    # distribute new instance config to the other nodes
5766
    self.cfg.Update(instance, feedback_fn)
5767

    
5768
    # Only start the instance if it's marked as up
5769
    if instance.admin_up:
5770
      feedback_fn("* activating the instance's disks on target node")
5771
      logging.info("Starting instance %s on node %s",
5772
                   instance.name, target_node)
5773

    
5774
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5775
                                           ignore_secondaries=True)
5776
      if not disks_ok:
5777
        _ShutdownInstanceDisks(self, instance)
5778
        raise errors.OpExecError("Can't activate the instance's disks")
5779

    
5780
      feedback_fn("* starting the instance on the target node")
5781
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5782
      msg = result.fail_msg
5783
      if msg:
5784
        _ShutdownInstanceDisks(self, instance)
5785
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5786
                                 (instance.name, target_node, msg))
5787

    
5788

    
5789
class LUMigrateInstance(LogicalUnit):
5790
  """Migrate an instance.
5791

5792
  This is migration without shutting down, compared to the failover,
5793
  which is done with shutdown.
5794

5795
  """
5796
  HPATH = "instance-migrate"
5797
  HTYPE = constants.HTYPE_INSTANCE
5798
  _OP_PARAMS = [
5799
    _PInstanceName,
5800
    _PMigrationMode,
5801
    _PMigrationLive,
5802
    ("cleanup", False, ht.TBool),
5803
    ]
5804

    
5805
  REQ_BGL = False
5806

    
5807
  def ExpandNames(self):
5808
    self._ExpandAndLockInstance()
5809

    
5810
    self.needed_locks[locking.LEVEL_NODE] = []
5811
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5812

    
5813
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5814
                                       self.op.cleanup)
5815
    self.tasklets = [self._migrater]
5816

    
5817
  def DeclareLocks(self, level):
5818
    if level == locking.LEVEL_NODE:
5819
      self._LockInstancesNodes()
5820

    
5821
  def BuildHooksEnv(self):
5822
    """Build hooks env.
5823

5824
    This runs on master, primary and secondary nodes of the instance.
5825

5826
    """
5827
    instance = self._migrater.instance
5828
    source_node = instance.primary_node
5829
    target_node = instance.secondary_nodes[0]
5830
    env = _BuildInstanceHookEnvByObject(self, instance)
5831
    env["MIGRATE_LIVE"] = self._migrater.live
5832
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5833
    env.update({
5834
        "OLD_PRIMARY": source_node,
5835
        "OLD_SECONDARY": target_node,
5836
        "NEW_PRIMARY": target_node,
5837
        "NEW_SECONDARY": source_node,
5838
        })
5839
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5840
    nl_post = list(nl)
5841
    nl_post.append(source_node)
5842
    return env, nl, nl_post
5843

    
5844

    
5845
class LUMoveInstance(LogicalUnit):
5846
  """Move an instance by data-copying.
5847

5848
  """
5849
  HPATH = "instance-move"
5850
  HTYPE = constants.HTYPE_INSTANCE
5851
  _OP_PARAMS = [
5852
    _PInstanceName,
5853
    ("target_node", ht.NoDefault, ht.TNonEmptyString),
5854
    _PShutdownTimeout,
5855
    ]
5856
  REQ_BGL = False
5857

    
5858
  def ExpandNames(self):
5859
    self._ExpandAndLockInstance()
5860
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5861
    self.op.target_node = target_node
5862
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5863
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5864

    
5865
  def DeclareLocks(self, level):
5866
    if level == locking.LEVEL_NODE:
5867
      self._LockInstancesNodes(primary_only=True)
5868

    
5869
  def BuildHooksEnv(self):
5870
    """Build hooks env.
5871

5872
    This runs on master, primary and secondary nodes of the instance.
5873

5874
    """
5875
    env = {
5876
      "TARGET_NODE": self.op.target_node,
5877
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5878
      }
5879
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5880
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5881
                                       self.op.target_node]
5882
    return env, nl, nl
5883

    
5884
  def CheckPrereq(self):
5885
    """Check prerequisites.
5886

5887
    This checks that the instance is in the cluster.
5888

5889
    """
5890
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5891
    assert self.instance is not None, \
5892
      "Cannot retrieve locked instance %s" % self.op.instance_name
5893

    
5894
    node = self.cfg.GetNodeInfo(self.op.target_node)
5895
    assert node is not None, \
5896
      "Cannot retrieve locked node %s" % self.op.target_node
5897

    
5898
    self.target_node = target_node = node.name
5899

    
5900
    if target_node == instance.primary_node:
5901
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5902
                                 (instance.name, target_node),
5903
                                 errors.ECODE_STATE)
5904

    
5905
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5906

    
5907
    for idx, dsk in enumerate(instance.disks):
5908
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5909
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5910
                                   " cannot copy" % idx, errors.ECODE_STATE)
5911

    
5912
    _CheckNodeOnline(self, target_node)
5913
    _CheckNodeNotDrained(self, target_node)
5914
    _CheckNodeVmCapable(self, target_node)
5915

    
5916
    if instance.admin_up:
5917
      # check memory requirements on the secondary node
5918
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5919
                           instance.name, bep[constants.BE_MEMORY],
5920
                           instance.hypervisor)
5921
    else:
5922
      self.LogInfo("Not checking memory on the secondary node as"
5923
                   " instance will not be started")
5924

    
5925
    # check bridge existance
5926
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5927

    
5928
  def Exec(self, feedback_fn):
5929
    """Move an instance.
5930

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

5934
    """
5935
    instance = self.instance
5936

    
5937
    source_node = instance.primary_node
5938
    target_node = self.target_node
5939

    
5940
    self.LogInfo("Shutting down instance %s on source node %s",
5941
                 instance.name, source_node)
5942

    
5943
    result = self.rpc.call_instance_shutdown(source_node, instance,
5944
                                             self.op.shutdown_timeout)
5945
    msg = result.fail_msg
5946
    if msg:
5947
      if self.op.ignore_consistency:
5948
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5949
                             " Proceeding anyway. Please make sure node"
5950
                             " %s is down. Error details: %s",
5951
                             instance.name, source_node, source_node, msg)
5952
      else:
5953
        raise errors.OpExecError("Could not shutdown instance %s on"
5954
                                 " node %s: %s" %
5955
                                 (instance.name, source_node, msg))
5956

    
5957
    # create the target disks
5958
    try:
5959
      _CreateDisks(self, instance, target_node=target_node)
5960
    except errors.OpExecError:
5961
      self.LogWarning("Device creation failed, reverting...")
5962
      try:
5963
        _RemoveDisks(self, instance, target_node=target_node)
5964
      finally:
5965
        self.cfg.ReleaseDRBDMinors(instance.name)
5966
        raise
5967

    
5968
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5969

    
5970
    errs = []
5971
    # activate, get path, copy the data over
5972
    for idx, disk in enumerate(instance.disks):
5973
      self.LogInfo("Copying data for disk %d", idx)
5974
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5975
                                               instance.name, True)
5976
      if result.fail_msg:
5977
        self.LogWarning("Can't assemble newly created disk %d: %s",
5978
                        idx, result.fail_msg)
5979
        errs.append(result.fail_msg)
5980
        break
5981
      dev_path = result.payload
5982
      result = self.rpc.call_blockdev_export(source_node, disk,
5983
                                             target_node, dev_path,
5984
                                             cluster_name)
5985
      if result.fail_msg:
5986
        self.LogWarning("Can't copy data over for disk %d: %s",
5987
                        idx, result.fail_msg)
5988
        errs.append(result.fail_msg)
5989
        break
5990

    
5991
    if errs:
5992
      self.LogWarning("Some disks failed to copy, aborting")
5993
      try:
5994
        _RemoveDisks(self, instance, target_node=target_node)
5995
      finally:
5996
        self.cfg.ReleaseDRBDMinors(instance.name)
5997
        raise errors.OpExecError("Errors during disk copy: %s" %
5998
                                 (",".join(errs),))
5999

    
6000
    instance.primary_node = target_node
6001
    self.cfg.Update(instance, feedback_fn)
6002

    
6003
    self.LogInfo("Removing the disks on the original node")
6004
    _RemoveDisks(self, instance, target_node=source_node)
6005

    
6006
    # Only start the instance if it's marked as up
6007
    if instance.admin_up:
6008
      self.LogInfo("Starting instance %s on node %s",
6009
                   instance.name, target_node)
6010

    
6011
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
6012
                                           ignore_secondaries=True)
6013
      if not disks_ok:
6014
        _ShutdownInstanceDisks(self, instance)
6015
        raise errors.OpExecError("Can't activate the instance's disks")
6016

    
6017
      result = self.rpc.call_instance_start(target_node, instance, None, None)
6018
      msg = result.fail_msg
6019
      if msg:
6020
        _ShutdownInstanceDisks(self, instance)
6021
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
6022
                                 (instance.name, target_node, msg))
6023

    
6024

    
6025
class LUMigrateNode(LogicalUnit):
6026
  """Migrate all instances from a node.
6027

6028
  """
6029
  HPATH = "node-migrate"
6030
  HTYPE = constants.HTYPE_NODE
6031
  _OP_PARAMS = [
6032
    _PNodeName,
6033
    _PMigrationMode,
6034
    _PMigrationLive,
6035
    ]
6036
  REQ_BGL = False
6037

    
6038
  def ExpandNames(self):
6039
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6040

    
6041
    self.needed_locks = {
6042
      locking.LEVEL_NODE: [self.op.node_name],
6043
      }
6044

    
6045
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6046

    
6047
    # Create tasklets for migrating instances for all instances on this node
6048
    names = []
6049
    tasklets = []
6050

    
6051
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
6052
      logging.debug("Migrating instance %s", inst.name)
6053
      names.append(inst.name)
6054

    
6055
      tasklets.append(TLMigrateInstance(self, inst.name, False))
6056

    
6057
    self.tasklets = tasklets
6058

    
6059
    # Declare instance locks
6060
    self.needed_locks[locking.LEVEL_INSTANCE] = names
6061

    
6062
  def DeclareLocks(self, level):
6063
    if level == locking.LEVEL_NODE:
6064
      self._LockInstancesNodes()
6065

    
6066
  def BuildHooksEnv(self):
6067
    """Build hooks env.
6068

6069
    This runs on the master, the primary and all the secondaries.
6070

6071
    """
6072
    env = {
6073
      "NODE_NAME": self.op.node_name,
6074
      }
6075

    
6076
    nl = [self.cfg.GetMasterNode()]
6077

    
6078
    return (env, nl, nl)
6079

    
6080

    
6081
class TLMigrateInstance(Tasklet):
6082
  """Tasklet class for instance migration.
6083

6084
  @type live: boolean
6085
  @ivar live: whether the migration will be done live or non-live;
6086
      this variable is initalized only after CheckPrereq has run
6087

6088
  """
6089
  def __init__(self, lu, instance_name, cleanup):
6090
    """Initializes this class.
6091

6092
    """
6093
    Tasklet.__init__(self, lu)
6094

    
6095
    # Parameters
6096
    self.instance_name = instance_name
6097
    self.cleanup = cleanup
6098
    self.live = False # will be overridden later
6099

    
6100
  def CheckPrereq(self):
6101
    """Check prerequisites.
6102

6103
    This checks that the instance is in the cluster.
6104

6105
    """
6106
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
6107
    instance = self.cfg.GetInstanceInfo(instance_name)
6108
    assert instance is not None
6109

    
6110
    if instance.disk_template != constants.DT_DRBD8:
6111
      raise errors.OpPrereqError("Instance's disk layout is not"
6112
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
6113

    
6114
    secondary_nodes = instance.secondary_nodes
6115
    if not secondary_nodes:
6116
      raise errors.ConfigurationError("No secondary node but using"
6117
                                      " drbd8 disk template")
6118

    
6119
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
6120

    
6121
    target_node = secondary_nodes[0]
6122
    # check memory requirements on the secondary node
6123
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
6124
                         instance.name, i_be[constants.BE_MEMORY],
6125
                         instance.hypervisor)
6126

    
6127
    # check bridge existance
6128
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
6129

    
6130
    if not self.cleanup:
6131
      _CheckNodeNotDrained(self.lu, target_node)
6132
      result = self.rpc.call_instance_migratable(instance.primary_node,
6133
                                                 instance)
6134
      result.Raise("Can't migrate, please use failover",
6135
                   prereq=True, ecode=errors.ECODE_STATE)
6136

    
6137
    self.instance = instance
6138

    
6139
    if self.lu.op.live is not None and self.lu.op.mode is not None:
6140
      raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
6141
                                 " parameters are accepted",
6142
                                 errors.ECODE_INVAL)
6143
    if self.lu.op.live is not None:
6144
      if self.lu.op.live:
6145
        self.lu.op.mode = constants.HT_MIGRATION_LIVE
6146
      else:
6147
        self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6148
      # reset the 'live' parameter to None so that repeated
6149
      # invocations of CheckPrereq do not raise an exception
6150
      self.lu.op.live = None
6151
    elif self.lu.op.mode is None:
6152
      # read the default value from the hypervisor
6153
      i_hv = self.cfg.GetClusterInfo().FillHV(instance, skip_globals=False)
6154
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6155

    
6156
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6157

    
6158
  def _WaitUntilSync(self):
6159
    """Poll with custom rpc for disk sync.
6160

6161
    This uses our own step-based rpc call.
6162

6163
    """
6164
    self.feedback_fn("* wait until resync is done")
6165
    all_done = False
6166
    while not all_done:
6167
      all_done = True
6168
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6169
                                            self.nodes_ip,
6170
                                            self.instance.disks)
6171
      min_percent = 100
6172
      for node, nres in result.items():
6173
        nres.Raise("Cannot resync disks on node %s" % node)
6174
        node_done, node_percent = nres.payload
6175
        all_done = all_done and node_done
6176
        if node_percent is not None:
6177
          min_percent = min(min_percent, node_percent)
6178
      if not all_done:
6179
        if min_percent < 100:
6180
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6181
        time.sleep(2)
6182

    
6183
  def _EnsureSecondary(self, node):
6184
    """Demote a node to secondary.
6185

6186
    """
6187
    self.feedback_fn("* switching node %s to secondary mode" % node)
6188

    
6189
    for dev in self.instance.disks:
6190
      self.cfg.SetDiskID(dev, node)
6191

    
6192
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6193
                                          self.instance.disks)
6194
    result.Raise("Cannot change disk to secondary on node %s" % node)
6195

    
6196
  def _GoStandalone(self):
6197
    """Disconnect from the network.
6198

6199
    """
6200
    self.feedback_fn("* changing into standalone mode")
6201
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6202
                                               self.instance.disks)
6203
    for node, nres in result.items():
6204
      nres.Raise("Cannot disconnect disks node %s" % node)
6205

    
6206
  def _GoReconnect(self, multimaster):
6207
    """Reconnect to the network.
6208

6209
    """
6210
    if multimaster:
6211
      msg = "dual-master"
6212
    else:
6213
      msg = "single-master"
6214
    self.feedback_fn("* changing disks into %s mode" % msg)
6215
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6216
                                           self.instance.disks,
6217
                                           self.instance.name, multimaster)
6218
    for node, nres in result.items():
6219
      nres.Raise("Cannot change disks config on node %s" % node)
6220

    
6221
  def _ExecCleanup(self):
6222
    """Try to cleanup after a failed migration.
6223

6224
    The cleanup is done by:
6225
      - check that the instance is running only on one node
6226
        (and update the config if needed)
6227
      - change disks on its secondary node to secondary
6228
      - wait until disks are fully synchronized
6229
      - disconnect from the network
6230
      - change disks into single-master mode
6231
      - wait again until disks are fully synchronized
6232

6233
    """
6234
    instance = self.instance
6235
    target_node = self.target_node
6236
    source_node = self.source_node
6237

    
6238
    # check running on only one node
6239
    self.feedback_fn("* checking where the instance actually runs"
6240
                     " (if this hangs, the hypervisor might be in"
6241
                     " a bad state)")
6242
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
6243
    for node, result in ins_l.items():
6244
      result.Raise("Can't contact node %s" % node)
6245

    
6246
    runningon_source = instance.name in ins_l[source_node].payload
6247
    runningon_target = instance.name in ins_l[target_node].payload
6248

    
6249
    if runningon_source and runningon_target:
6250
      raise errors.OpExecError("Instance seems to be running on two nodes,"
6251
                               " or the hypervisor is confused. You will have"
6252
                               " to ensure manually that it runs only on one"
6253
                               " and restart this operation.")
6254

    
6255
    if not (runningon_source or runningon_target):
6256
      raise errors.OpExecError("Instance does not seem to be running at all."
6257
                               " In this case, it's safer to repair by"
6258
                               " running 'gnt-instance stop' to ensure disk"
6259
                               " shutdown, and then restarting it.")
6260

    
6261
    if runningon_target:
6262
      # the migration has actually succeeded, we need to update the config
6263
      self.feedback_fn("* instance running on secondary node (%s),"
6264
                       " updating config" % target_node)
6265
      instance.primary_node = target_node
6266
      self.cfg.Update(instance, self.feedback_fn)
6267
      demoted_node = source_node
6268
    else:
6269
      self.feedback_fn("* instance confirmed to be running on its"
6270
                       " primary node (%s)" % source_node)
6271
      demoted_node = target_node
6272

    
6273
    self._EnsureSecondary(demoted_node)
6274
    try:
6275
      self._WaitUntilSync()
6276
    except errors.OpExecError:
6277
      # we ignore here errors, since if the device is standalone, it
6278
      # won't be able to sync
6279
      pass
6280
    self._GoStandalone()
6281
    self._GoReconnect(False)
6282
    self._WaitUntilSync()
6283

    
6284
    self.feedback_fn("* done")
6285

    
6286
  def _RevertDiskStatus(self):
6287
    """Try to revert the disk status after a failed migration.
6288

6289
    """
6290
    target_node = self.target_node
6291
    try:
6292
      self._EnsureSecondary(target_node)
6293
      self._GoStandalone()
6294
      self._GoReconnect(False)
6295
      self._WaitUntilSync()
6296
    except errors.OpExecError, err:
6297
      self.lu.LogWarning("Migration failed and I can't reconnect the"
6298
                         " drives: error '%s'\n"
6299
                         "Please look and recover the instance status" %
6300
                         str(err))
6301

    
6302
  def _AbortMigration(self):
6303
    """Call the hypervisor code to abort a started migration.
6304

6305
    """
6306
    instance = self.instance
6307
    target_node = self.target_node
6308
    migration_info = self.migration_info
6309

    
6310
    abort_result = self.rpc.call_finalize_migration(target_node,
6311
                                                    instance,
6312
                                                    migration_info,
6313
                                                    False)
6314
    abort_msg = abort_result.fail_msg
6315
    if abort_msg:
6316
      logging.error("Aborting migration failed on target node %s: %s",
6317
                    target_node, abort_msg)
6318
      # Don't raise an exception here, as we stil have to try to revert the
6319
      # disk status, even if this step failed.
6320

    
6321
  def _ExecMigration(self):
6322
    """Migrate an instance.
6323

6324
    The migrate is done by:
6325
      - change the disks into dual-master mode
6326
      - wait until disks are fully synchronized again
6327
      - migrate the instance
6328
      - change disks on the new secondary node (the old primary) to secondary
6329
      - wait until disks are fully synchronized
6330
      - change disks into single-master mode
6331

6332
    """
6333
    instance = self.instance
6334
    target_node = self.target_node
6335
    source_node = self.source_node
6336

    
6337
    self.feedback_fn("* checking disk consistency between source and target")
6338
    for dev in instance.disks:
6339
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6340
        raise errors.OpExecError("Disk %s is degraded or not fully"
6341
                                 " synchronized on target node,"
6342
                                 " aborting migrate." % dev.iv_name)
6343

    
6344
    # First get the migration information from the remote node
6345
    result = self.rpc.call_migration_info(source_node, instance)
6346
    msg = result.fail_msg
6347
    if msg:
6348
      log_err = ("Failed fetching source migration information from %s: %s" %
6349
                 (source_node, msg))
6350
      logging.error(log_err)
6351
      raise errors.OpExecError(log_err)
6352

    
6353
    self.migration_info = migration_info = result.payload
6354

    
6355
    # Then switch the disks to master/master mode
6356
    self._EnsureSecondary(target_node)
6357
    self._GoStandalone()
6358
    self._GoReconnect(True)
6359
    self._WaitUntilSync()
6360

    
6361
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6362
    result = self.rpc.call_accept_instance(target_node,
6363
                                           instance,
6364
                                           migration_info,
6365
                                           self.nodes_ip[target_node])
6366

    
6367
    msg = result.fail_msg
6368
    if msg:
6369
      logging.error("Instance pre-migration failed, trying to revert"
6370
                    " disk status: %s", msg)
6371
      self.feedback_fn("Pre-migration failed, aborting")
6372
      self._AbortMigration()
6373
      self._RevertDiskStatus()
6374
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6375
                               (instance.name, msg))
6376

    
6377
    self.feedback_fn("* migrating instance to %s" % target_node)
6378
    time.sleep(10)
6379
    result = self.rpc.call_instance_migrate(source_node, instance,
6380
                                            self.nodes_ip[target_node],
6381
                                            self.live)
6382
    msg = result.fail_msg
6383
    if msg:
6384
      logging.error("Instance migration failed, trying to revert"
6385
                    " disk status: %s", msg)
6386
      self.feedback_fn("Migration failed, aborting")
6387
      self._AbortMigration()
6388
      self._RevertDiskStatus()
6389
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6390
                               (instance.name, msg))
6391
    time.sleep(10)
6392

    
6393
    instance.primary_node = target_node
6394
    # distribute new instance config to the other nodes
6395
    self.cfg.Update(instance, self.feedback_fn)
6396

    
6397
    result = self.rpc.call_finalize_migration(target_node,
6398
                                              instance,
6399
                                              migration_info,
6400
                                              True)
6401
    msg = result.fail_msg
6402
    if msg:
6403
      logging.error("Instance migration succeeded, but finalization failed:"
6404
                    " %s", msg)
6405
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6406
                               msg)
6407

    
6408
    self._EnsureSecondary(source_node)
6409
    self._WaitUntilSync()
6410
    self._GoStandalone()
6411
    self._GoReconnect(False)
6412
    self._WaitUntilSync()
6413

    
6414
    self.feedback_fn("* done")
6415

    
6416
  def Exec(self, feedback_fn):
6417
    """Perform the migration.
6418

6419
    """
6420
    feedback_fn("Migrating instance %s" % self.instance.name)
6421

    
6422
    self.feedback_fn = feedback_fn
6423

    
6424
    self.source_node = self.instance.primary_node
6425
    self.target_node = self.instance.secondary_nodes[0]
6426
    self.all_nodes = [self.source_node, self.target_node]
6427
    self.nodes_ip = {
6428
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6429
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6430
      }
6431

    
6432
    if self.cleanup:
6433
      return self._ExecCleanup()
6434
    else:
6435
      return self._ExecMigration()
6436

    
6437

    
6438
def _CreateBlockDev(lu, node, instance, device, force_create,
6439
                    info, force_open):
6440
  """Create a tree of block devices on a given node.
6441

6442
  If this device type has to be created on secondaries, create it and
6443
  all its children.
6444

6445
  If not, just recurse to children keeping the same 'force' value.
6446

6447
  @param lu: the lu on whose behalf we execute
6448
  @param node: the node on which to create the device
6449
  @type instance: L{objects.Instance}
6450
  @param instance: the instance which owns the device
6451
  @type device: L{objects.Disk}
6452
  @param device: the device to create
6453
  @type force_create: boolean
6454
  @param force_create: whether to force creation of this device; this
6455
      will be change to True whenever we find a device which has
6456
      CreateOnSecondary() attribute
6457
  @param info: the extra 'metadata' we should attach to the device
6458
      (this will be represented as a LVM tag)
6459
  @type force_open: boolean
6460
  @param force_open: this parameter will be passes to the
6461
      L{backend.BlockdevCreate} function where it specifies
6462
      whether we run on primary or not, and it affects both
6463
      the child assembly and the device own Open() execution
6464

6465
  """
6466
  if device.CreateOnSecondary():
6467
    force_create = True
6468

    
6469
  if device.children:
6470
    for child in device.children:
6471
      _CreateBlockDev(lu, node, instance, child, force_create,
6472
                      info, force_open)
6473

    
6474
  if not force_create:
6475
    return
6476

    
6477
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6478

    
6479

    
6480
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6481
  """Create a single block device on a given node.
6482

6483
  This will not recurse over children of the device, so they must be
6484
  created in advance.
6485

6486
  @param lu: the lu on whose behalf we execute
6487
  @param node: the node on which to create the device
6488
  @type instance: L{objects.Instance}
6489
  @param instance: the instance which owns the device
6490
  @type device: L{objects.Disk}
6491
  @param device: the device to create
6492
  @param info: the extra 'metadata' we should attach to the device
6493
      (this will be represented as a LVM tag)
6494
  @type force_open: boolean
6495
  @param force_open: this parameter will be passes to the
6496
      L{backend.BlockdevCreate} function where it specifies
6497
      whether we run on primary or not, and it affects both
6498
      the child assembly and the device own Open() execution
6499

6500
  """
6501
  lu.cfg.SetDiskID(device, node)
6502
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6503
                                       instance.name, force_open, info)
6504
  result.Raise("Can't create block device %s on"
6505
               " node %s for instance %s" % (device, node, instance.name))
6506
  if device.physical_id is None:
6507
    device.physical_id = result.payload
6508

    
6509

    
6510
def _GenerateUniqueNames(lu, exts):
6511
  """Generate a suitable LV name.
6512

6513
  This will generate a logical volume name for the given instance.
6514

6515
  """
6516
  results = []
6517
  for val in exts:
6518
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6519
    results.append("%s%s" % (new_id, val))
6520
  return results
6521

    
6522

    
6523
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
6524
                         p_minor, s_minor):
6525
  """Generate a drbd8 device complete with its children.
6526

6527
  """
6528
  port = lu.cfg.AllocatePort()
6529
  vgname = lu.cfg.GetVGName()
6530
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6531
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6532
                          logical_id=(vgname, names[0]))
6533
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6534
                          logical_id=(vgname, names[1]))
6535
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6536
                          logical_id=(primary, secondary, port,
6537
                                      p_minor, s_minor,
6538
                                      shared_secret),
6539
                          children=[dev_data, dev_meta],
6540
                          iv_name=iv_name)
6541
  return drbd_dev
6542

    
6543

    
6544
def _GenerateDiskTemplate(lu, template_name,
6545
                          instance_name, primary_node,
6546
                          secondary_nodes, disk_info,
6547
                          file_storage_dir, file_driver,
6548
                          base_index):
6549
  """Generate the entire disk layout for a given template type.
6550

6551
  """
6552
  #TODO: compute space requirements
6553

    
6554
  vgname = lu.cfg.GetVGName()
6555
  disk_count = len(disk_info)
6556
  disks = []
6557
  if template_name == constants.DT_DISKLESS:
6558
    pass
6559
  elif template_name == constants.DT_PLAIN:
6560
    if len(secondary_nodes) != 0:
6561
      raise errors.ProgrammerError("Wrong template configuration")
6562

    
6563
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6564
                                      for i in range(disk_count)])
6565
    for idx, disk in enumerate(disk_info):
6566
      disk_index = idx + base_index
6567
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6568
                              logical_id=(vgname, names[idx]),
6569
                              iv_name="disk/%d" % disk_index,
6570
                              mode=disk["mode"])
6571
      disks.append(disk_dev)
6572
  elif template_name == constants.DT_DRBD8:
6573
    if len(secondary_nodes) != 1:
6574
      raise errors.ProgrammerError("Wrong template configuration")
6575
    remote_node = secondary_nodes[0]
6576
    minors = lu.cfg.AllocateDRBDMinor(
6577
      [primary_node, remote_node] * len(disk_info), instance_name)
6578

    
6579
    names = []
6580
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6581
                                               for i in range(disk_count)]):
6582
      names.append(lv_prefix + "_data")
6583
      names.append(lv_prefix + "_meta")
6584
    for idx, disk in enumerate(disk_info):
6585
      disk_index = idx + base_index
6586
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6587
                                      disk["size"], names[idx*2:idx*2+2],
6588
                                      "disk/%d" % disk_index,
6589
                                      minors[idx*2], minors[idx*2+1])
6590
      disk_dev.mode = disk["mode"]
6591
      disks.append(disk_dev)
6592
  elif template_name == constants.DT_FILE:
6593
    if len(secondary_nodes) != 0:
6594
      raise errors.ProgrammerError("Wrong template configuration")
6595

    
6596
    _RequireFileStorage()
6597

    
6598
    for idx, disk in enumerate(disk_info):
6599
      disk_index = idx + base_index
6600
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6601
                              iv_name="disk/%d" % disk_index,
6602
                              logical_id=(file_driver,
6603
                                          "%s/disk%d" % (file_storage_dir,
6604
                                                         disk_index)),
6605
                              mode=disk["mode"])
6606
      disks.append(disk_dev)
6607
  else:
6608
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6609
  return disks
6610

    
6611

    
6612
def _GetInstanceInfoText(instance):
6613
  """Compute that text that should be added to the disk's metadata.
6614

6615
  """
6616
  return "originstname+%s" % instance.name
6617

    
6618

    
6619
def _CalcEta(time_taken, written, total_size):
6620
  """Calculates the ETA based on size written and total size.
6621

6622
  @param time_taken: The time taken so far
6623
  @param written: amount written so far
6624
  @param total_size: The total size of data to be written
6625
  @return: The remaining time in seconds
6626

6627
  """
6628
  avg_time = time_taken / float(written)
6629
  return (total_size - written) * avg_time
6630

    
6631

    
6632
def _WipeDisks(lu, instance):
6633
  """Wipes instance disks.
6634

6635
  @type lu: L{LogicalUnit}
6636
  @param lu: the logical unit on whose behalf we execute
6637
  @type instance: L{objects.Instance}
6638
  @param instance: the instance whose disks we should create
6639
  @return: the success of the wipe
6640

6641
  """
6642
  node = instance.primary_node
6643
  for idx, device in enumerate(instance.disks):
6644
    lu.LogInfo("* Wiping disk %d", idx)
6645
    logging.info("Wiping disk %d for instance %s", idx, instance.name)
6646

    
6647
    # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
6648
    # MAX_WIPE_CHUNK at max
6649
    wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
6650
                          constants.MIN_WIPE_CHUNK_PERCENT)
6651

    
6652
    offset = 0
6653
    size = device.size
6654
    last_output = 0
6655
    start_time = time.time()
6656

    
6657
    while offset < size:
6658
      wipe_size = min(wipe_chunk_size, size - offset)
6659
      result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
6660
      result.Raise("Could not wipe disk %d at offset %d for size %d" %
6661
                   (idx, offset, wipe_size))
6662
      now = time.time()
6663
      offset += wipe_size
6664
      if now - last_output >= 60:
6665
        eta = _CalcEta(now - start_time, offset, size)
6666
        lu.LogInfo(" - done: %.1f%% ETA: %s" %
6667
                   (offset / float(size) * 100, utils.FormatSeconds(eta)))
6668
        last_output = now
6669

    
6670

    
6671
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6672
  """Create all disks for an instance.
6673

6674
  This abstracts away some work from AddInstance.
6675

6676
  @type lu: L{LogicalUnit}
6677
  @param lu: the logical unit on whose behalf we execute
6678
  @type instance: L{objects.Instance}
6679
  @param instance: the instance whose disks we should create
6680
  @type to_skip: list
6681
  @param to_skip: list of indices to skip
6682
  @type target_node: string
6683
  @param target_node: if passed, overrides the target node for creation
6684
  @rtype: boolean
6685
  @return: the success of the creation
6686

6687
  """
6688
  info = _GetInstanceInfoText(instance)
6689
  if target_node is None:
6690
    pnode = instance.primary_node
6691
    all_nodes = instance.all_nodes
6692
  else:
6693
    pnode = target_node
6694
    all_nodes = [pnode]
6695

    
6696
  if instance.disk_template == constants.DT_FILE:
6697
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6698
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6699

    
6700
    result.Raise("Failed to create directory '%s' on"
6701
                 " node %s" % (file_storage_dir, pnode))
6702

    
6703
  # Note: this needs to be kept in sync with adding of disks in
6704
  # LUSetInstanceParams
6705
  for idx, device in enumerate(instance.disks):
6706
    if to_skip and idx in to_skip:
6707
      continue
6708
    logging.info("Creating volume %s for instance %s",
6709
                 device.iv_name, instance.name)
6710
    #HARDCODE
6711
    for node in all_nodes:
6712
      f_create = node == pnode
6713
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6714

    
6715

    
6716
def _RemoveDisks(lu, instance, target_node=None):
6717
  """Remove all disks for an instance.
6718

6719
  This abstracts away some work from `AddInstance()` and
6720
  `RemoveInstance()`. Note that in case some of the devices couldn't
6721
  be removed, the removal will continue with the other ones (compare
6722
  with `_CreateDisks()`).
6723

6724
  @type lu: L{LogicalUnit}
6725
  @param lu: the logical unit on whose behalf we execute
6726
  @type instance: L{objects.Instance}
6727
  @param instance: the instance whose disks we should remove
6728
  @type target_node: string
6729
  @param target_node: used to override the node on which to remove the disks
6730
  @rtype: boolean
6731
  @return: the success of the removal
6732

6733
  """
6734
  logging.info("Removing block devices for instance %s", instance.name)
6735

    
6736
  all_result = True
6737
  for device in instance.disks:
6738
    if target_node:
6739
      edata = [(target_node, device)]
6740
    else:
6741
      edata = device.ComputeNodeTree(instance.primary_node)
6742
    for node, disk in edata:
6743
      lu.cfg.SetDiskID(disk, node)
6744
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6745
      if msg:
6746
        lu.LogWarning("Could not remove block device %s on node %s,"
6747
                      " continuing anyway: %s", device.iv_name, node, msg)
6748
        all_result = False
6749

    
6750
  if instance.disk_template == constants.DT_FILE:
6751
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6752
    if target_node:
6753
      tgt = target_node
6754
    else:
6755
      tgt = instance.primary_node
6756
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6757
    if result.fail_msg:
6758
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6759
                    file_storage_dir, instance.primary_node, result.fail_msg)
6760
      all_result = False
6761

    
6762
  return all_result
6763

    
6764

    
6765
def _ComputeDiskSize(disk_template, disks):
6766
  """Compute disk size requirements in the volume group
6767

6768
  """
6769
  # Required free disk space as a function of disk and swap space
6770
  req_size_dict = {
6771
    constants.DT_DISKLESS: None,
6772
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6773
    # 128 MB are added for drbd metadata for each disk
6774
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6775
    constants.DT_FILE: None,
6776
  }
6777

    
6778
  if disk_template not in req_size_dict:
6779
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6780
                                 " is unknown" %  disk_template)
6781

    
6782
  return req_size_dict[disk_template]
6783

    
6784

    
6785
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6786
  """Hypervisor parameter validation.
6787

6788
  This function abstract the hypervisor parameter validation to be
6789
  used in both instance create and instance modify.
6790

6791
  @type lu: L{LogicalUnit}
6792
  @param lu: the logical unit for which we check
6793
  @type nodenames: list
6794
  @param nodenames: the list of nodes on which we should check
6795
  @type hvname: string
6796
  @param hvname: the name of the hypervisor we should use
6797
  @type hvparams: dict
6798
  @param hvparams: the parameters which we need to check
6799
  @raise errors.OpPrereqError: if the parameters are not valid
6800

6801
  """
6802
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6803
                                                  hvname,
6804
                                                  hvparams)
6805
  for node in nodenames:
6806
    info = hvinfo[node]
6807
    if info.offline:
6808
      continue
6809
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6810

    
6811

    
6812
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6813
  """OS parameters validation.
6814

6815
  @type lu: L{LogicalUnit}
6816
  @param lu: the logical unit for which we check
6817
  @type required: boolean
6818
  @param required: whether the validation should fail if the OS is not
6819
      found
6820
  @type nodenames: list
6821
  @param nodenames: the list of nodes on which we should check
6822
  @type osname: string
6823
  @param osname: the name of the hypervisor we should use
6824
  @type osparams: dict
6825
  @param osparams: the parameters which we need to check
6826
  @raise errors.OpPrereqError: if the parameters are not valid
6827

6828
  """
6829
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6830
                                   [constants.OS_VALIDATE_PARAMETERS],
6831
                                   osparams)
6832
  for node, nres in result.items():
6833
    # we don't check for offline cases since this should be run only
6834
    # against the master node and/or an instance's nodes
6835
    nres.Raise("OS Parameters validation failed on node %s" % node)
6836
    if not nres.payload:
6837
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6838
                 osname, node)
6839

    
6840

    
6841
class LUCreateInstance(LogicalUnit):
6842
  """Create an instance.
6843

6844
  """
6845
  HPATH = "instance-add"
6846
  HTYPE = constants.HTYPE_INSTANCE
6847
  _OP_PARAMS = [
6848
    _PInstanceName,
6849
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES)),
6850
    ("start", True, ht.TBool),
6851
    ("wait_for_sync", True, ht.TBool),
6852
    ("ip_check", True, ht.TBool),
6853
    ("name_check", True, ht.TBool),
6854
    ("disks", ht.NoDefault, ht.TListOf(ht.TDict)),
6855
    ("nics", ht.NoDefault, ht.TListOf(ht.TDict)),
6856
    ("hvparams", ht.EmptyDict, ht.TDict),
6857
    ("beparams", ht.EmptyDict, ht.TDict),
6858
    ("osparams", ht.EmptyDict, ht.TDict),
6859
    ("no_install", None, ht.TMaybeBool),
6860
    ("os_type", None, ht.TMaybeString),
6861
    ("force_variant", False, ht.TBool),
6862
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone)),
6863
    ("source_x509_ca", None, ht.TMaybeString),
6864
    ("source_instance_name", None, ht.TMaybeString),
6865
    ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
6866
     ht.TPositiveInt),
6867
    ("src_node", None, ht.TMaybeString),
6868
    ("src_path", None, ht.TMaybeString),
6869
    ("pnode", None, ht.TMaybeString),
6870
    ("snode", None, ht.TMaybeString),
6871
    ("iallocator", None, ht.TMaybeString),
6872
    ("hypervisor", None, ht.TMaybeString),
6873
    ("disk_template", ht.NoDefault, _CheckDiskTemplate),
6874
    ("identify_defaults", False, ht.TBool),
6875
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER))),
6876
    ("file_storage_dir", None, ht.TMaybeString),
6877
    ]
6878
  REQ_BGL = False
6879

    
6880
  def CheckArguments(self):
6881
    """Check arguments.
6882

6883
    """
6884
    # do not require name_check to ease forward/backward compatibility
6885
    # for tools
6886
    if self.op.no_install and self.op.start:
6887
      self.LogInfo("No-installation mode selected, disabling startup")
6888
      self.op.start = False
6889
    # validate/normalize the instance name
6890
    self.op.instance_name = \
6891
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
6892

    
6893
    if self.op.ip_check and not self.op.name_check:
6894
      # TODO: make the ip check more flexible and not depend on the name check
6895
      raise errors.OpPrereqError("Cannot do ip check without a name check",
6896
                                 errors.ECODE_INVAL)
6897

    
6898
    # check nics' parameter names
6899
    for nic in self.op.nics:
6900
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6901

    
6902
    # check disks. parameter names and consistent adopt/no-adopt strategy
6903
    has_adopt = has_no_adopt = False
6904
    for disk in self.op.disks:
6905
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6906
      if "adopt" in disk:
6907
        has_adopt = True
6908
      else:
6909
        has_no_adopt = True
6910
    if has_adopt and has_no_adopt:
6911
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6912
                                 errors.ECODE_INVAL)
6913
    if has_adopt:
6914
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6915
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6916
                                   " '%s' disk template" %
6917
                                   self.op.disk_template,
6918
                                   errors.ECODE_INVAL)
6919
      if self.op.iallocator is not None:
6920
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6921
                                   " iallocator script", errors.ECODE_INVAL)
6922
      if self.op.mode == constants.INSTANCE_IMPORT:
6923
        raise errors.OpPrereqError("Disk adoption not allowed for"
6924
                                   " instance import", errors.ECODE_INVAL)
6925

    
6926
    self.adopt_disks = has_adopt
6927

    
6928
    # instance name verification
6929
    if self.op.name_check:
6930
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
6931
      self.op.instance_name = self.hostname1.name
6932
      # used in CheckPrereq for ip ping check
6933
      self.check_ip = self.hostname1.ip
6934
    else:
6935
      self.check_ip = None
6936

    
6937
    # file storage checks
6938
    if (self.op.file_driver and
6939
        not self.op.file_driver in constants.FILE_DRIVER):
6940
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6941
                                 self.op.file_driver, errors.ECODE_INVAL)
6942

    
6943
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6944
      raise errors.OpPrereqError("File storage directory path not absolute",
6945
                                 errors.ECODE_INVAL)
6946

    
6947
    ### Node/iallocator related checks
6948
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
6949

    
6950
    if self.op.pnode is not None:
6951
      if self.op.disk_template in constants.DTS_NET_MIRROR:
6952
        if self.op.snode is None:
6953
          raise errors.OpPrereqError("The networked disk templates need"
6954
                                     " a mirror node", errors.ECODE_INVAL)
6955
      elif self.op.snode:
6956
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
6957
                        " template")
6958
        self.op.snode = None
6959

    
6960
    self._cds = _GetClusterDomainSecret()
6961

    
6962
    if self.op.mode == constants.INSTANCE_IMPORT:
6963
      # On import force_variant must be True, because if we forced it at
6964
      # initial install, our only chance when importing it back is that it
6965
      # works again!
6966
      self.op.force_variant = True
6967

    
6968
      if self.op.no_install:
6969
        self.LogInfo("No-installation mode has no effect during import")
6970

    
6971
    elif self.op.mode == constants.INSTANCE_CREATE:
6972
      if self.op.os_type is None:
6973
        raise errors.OpPrereqError("No guest OS specified",
6974
                                   errors.ECODE_INVAL)
6975
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
6976
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
6977
                                   " installation" % self.op.os_type,
6978
                                   errors.ECODE_STATE)
6979
      if self.op.disk_template is None:
6980
        raise errors.OpPrereqError("No disk template specified",
6981
                                   errors.ECODE_INVAL)
6982

    
6983
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6984
      # Check handshake to ensure both clusters have the same domain secret
6985
      src_handshake = self.op.source_handshake
6986
      if not src_handshake:
6987
        raise errors.OpPrereqError("Missing source handshake",
6988
                                   errors.ECODE_INVAL)
6989

    
6990
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6991
                                                           src_handshake)
6992
      if errmsg:
6993
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6994
                                   errors.ECODE_INVAL)
6995

    
6996
      # Load and check source CA
6997
      self.source_x509_ca_pem = self.op.source_x509_ca
6998
      if not self.source_x509_ca_pem:
6999
        raise errors.OpPrereqError("Missing source X509 CA",
7000
                                   errors.ECODE_INVAL)
7001

    
7002
      try:
7003
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
7004
                                                    self._cds)
7005
      except OpenSSL.crypto.Error, err:
7006
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
7007
                                   (err, ), errors.ECODE_INVAL)
7008

    
7009
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
7010
      if errcode is not None:
7011
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
7012
                                   errors.ECODE_INVAL)
7013

    
7014
      self.source_x509_ca = cert
7015

    
7016
      src_instance_name = self.op.source_instance_name
7017
      if not src_instance_name:
7018
        raise errors.OpPrereqError("Missing source instance name",
7019
                                   errors.ECODE_INVAL)
7020

    
7021
      self.source_instance_name = \
7022
          netutils.GetHostname(name=src_instance_name).name
7023

    
7024
    else:
7025
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
7026
                                 self.op.mode, errors.ECODE_INVAL)
7027

    
7028
  def ExpandNames(self):
7029
    """ExpandNames for CreateInstance.
7030

7031
    Figure out the right locks for instance creation.
7032

7033
    """
7034
    self.needed_locks = {}
7035

    
7036
    instance_name = self.op.instance_name
7037
    # this is just a preventive check, but someone might still add this
7038
    # instance in the meantime, and creation will fail at lock-add time
7039
    if instance_name in self.cfg.GetInstanceList():
7040
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
7041
                                 instance_name, errors.ECODE_EXISTS)
7042

    
7043
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
7044

    
7045
    if self.op.iallocator:
7046
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7047
    else:
7048
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
7049
      nodelist = [self.op.pnode]
7050
      if self.op.snode is not None:
7051
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
7052
        nodelist.append(self.op.snode)
7053
      self.needed_locks[locking.LEVEL_NODE] = nodelist
7054

    
7055
    # in case of import lock the source node too
7056
    if self.op.mode == constants.INSTANCE_IMPORT:
7057
      src_node = self.op.src_node
7058
      src_path = self.op.src_path
7059

    
7060
      if src_path is None:
7061
        self.op.src_path = src_path = self.op.instance_name
7062

    
7063
      if src_node is None:
7064
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7065
        self.op.src_node = None
7066
        if os.path.isabs(src_path):
7067
          raise errors.OpPrereqError("Importing an instance from an absolute"
7068
                                     " path requires a source node option.",
7069
                                     errors.ECODE_INVAL)
7070
      else:
7071
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
7072
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
7073
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
7074
        if not os.path.isabs(src_path):
7075
          self.op.src_path = src_path = \
7076
            utils.PathJoin(constants.EXPORT_DIR, src_path)
7077

    
7078
  def _RunAllocator(self):
7079
    """Run the allocator based on input opcode.
7080

7081
    """
7082
    nics = [n.ToDict() for n in self.nics]
7083
    ial = IAllocator(self.cfg, self.rpc,
7084
                     mode=constants.IALLOCATOR_MODE_ALLOC,
7085
                     name=self.op.instance_name,
7086
                     disk_template=self.op.disk_template,
7087
                     tags=[],
7088
                     os=self.op.os_type,
7089
                     vcpus=self.be_full[constants.BE_VCPUS],
7090
                     mem_size=self.be_full[constants.BE_MEMORY],
7091
                     disks=self.disks,
7092
                     nics=nics,
7093
                     hypervisor=self.op.hypervisor,
7094
                     )
7095

    
7096
    ial.Run(self.op.iallocator)
7097

    
7098
    if not ial.success:
7099
      raise errors.OpPrereqError("Can't compute nodes using"
7100
                                 " iallocator '%s': %s" %
7101
                                 (self.op.iallocator, ial.info),
7102
                                 errors.ECODE_NORES)
7103
    if len(ial.result) != ial.required_nodes:
7104
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7105
                                 " of nodes (%s), required %s" %
7106
                                 (self.op.iallocator, len(ial.result),
7107
                                  ial.required_nodes), errors.ECODE_FAULT)
7108
    self.op.pnode = ial.result[0]
7109
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
7110
                 self.op.instance_name, self.op.iallocator,
7111
                 utils.CommaJoin(ial.result))
7112
    if ial.required_nodes == 2:
7113
      self.op.snode = ial.result[1]
7114

    
7115
  def BuildHooksEnv(self):
7116
    """Build hooks env.
7117

7118
    This runs on master, primary and secondary nodes of the instance.
7119

7120
    """
7121
    env = {
7122
      "ADD_MODE": self.op.mode,
7123
      }
7124
    if self.op.mode == constants.INSTANCE_IMPORT:
7125
      env["SRC_NODE"] = self.op.src_node
7126
      env["SRC_PATH"] = self.op.src_path
7127
      env["SRC_IMAGES"] = self.src_images
7128

    
7129
    env.update(_BuildInstanceHookEnv(
7130
      name=self.op.instance_name,
7131
      primary_node=self.op.pnode,
7132
      secondary_nodes=self.secondaries,
7133
      status=self.op.start,
7134
      os_type=self.op.os_type,
7135
      memory=self.be_full[constants.BE_MEMORY],
7136
      vcpus=self.be_full[constants.BE_VCPUS],
7137
      nics=_NICListToTuple(self, self.nics),
7138
      disk_template=self.op.disk_template,
7139
      disks=[(d["size"], d["mode"]) for d in self.disks],
7140
      bep=self.be_full,
7141
      hvp=self.hv_full,
7142
      hypervisor_name=self.op.hypervisor,
7143
    ))
7144

    
7145
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
7146
          self.secondaries)
7147
    return env, nl, nl
7148

    
7149
  def _ReadExportInfo(self):
7150
    """Reads the export information from disk.
7151

7152
    It will override the opcode source node and path with the actual
7153
    information, if these two were not specified before.
7154

7155
    @return: the export information
7156

7157
    """
7158
    assert self.op.mode == constants.INSTANCE_IMPORT
7159

    
7160
    src_node = self.op.src_node
7161
    src_path = self.op.src_path
7162

    
7163
    if src_node is None:
7164
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
7165
      exp_list = self.rpc.call_export_list(locked_nodes)
7166
      found = False
7167
      for node in exp_list:
7168
        if exp_list[node].fail_msg:
7169
          continue
7170
        if src_path in exp_list[node].payload:
7171
          found = True
7172
          self.op.src_node = src_node = node
7173
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
7174
                                                       src_path)
7175
          break
7176
      if not found:
7177
        raise errors.OpPrereqError("No export found for relative path %s" %
7178
                                    src_path, errors.ECODE_INVAL)
7179

    
7180
    _CheckNodeOnline(self, src_node)
7181
    result = self.rpc.call_export_info(src_node, src_path)
7182
    result.Raise("No export or invalid export found in dir %s" % src_path)
7183

    
7184
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
7185
    if not export_info.has_section(constants.INISECT_EXP):
7186
      raise errors.ProgrammerError("Corrupted export config",
7187
                                   errors.ECODE_ENVIRON)
7188

    
7189
    ei_version = export_info.get(constants.INISECT_EXP, "version")
7190
    if (int(ei_version) != constants.EXPORT_VERSION):
7191
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
7192
                                 (ei_version, constants.EXPORT_VERSION),
7193
                                 errors.ECODE_ENVIRON)
7194
    return export_info
7195

    
7196
  def _ReadExportParams(self, einfo):
7197
    """Use export parameters as defaults.
7198

7199
    In case the opcode doesn't specify (as in override) some instance
7200
    parameters, then try to use them from the export information, if
7201
    that declares them.
7202

7203
    """
7204
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
7205

    
7206
    if self.op.disk_template is None:
7207
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
7208
        self.op.disk_template = einfo.get(constants.INISECT_INS,
7209
                                          "disk_template")
7210
      else:
7211
        raise errors.OpPrereqError("No disk template specified and the export"
7212
                                   " is missing the disk_template information",
7213
                                   errors.ECODE_INVAL)
7214

    
7215
    if not self.op.disks:
7216
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
7217
        disks = []
7218
        # TODO: import the disk iv_name too
7219
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
7220
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
7221
          disks.append({"size": disk_sz})
7222
        self.op.disks = disks
7223
      else:
7224
        raise errors.OpPrereqError("No disk info specified and the export"
7225
                                   " is missing the disk information",
7226
                                   errors.ECODE_INVAL)
7227

    
7228
    if (not self.op.nics and
7229
        einfo.has_option(constants.INISECT_INS, "nic_count")):
7230
      nics = []
7231
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
7232
        ndict = {}
7233
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
7234
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
7235
          ndict[name] = v
7236
        nics.append(ndict)
7237
      self.op.nics = nics
7238

    
7239
    if (self.op.hypervisor is None and
7240
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
7241
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
7242
    if einfo.has_section(constants.INISECT_HYP):
7243
      # use the export parameters but do not override the ones
7244
      # specified by the user
7245
      for name, value in einfo.items(constants.INISECT_HYP):
7246
        if name not in self.op.hvparams:
7247
          self.op.hvparams[name] = value
7248

    
7249
    if einfo.has_section(constants.INISECT_BEP):
7250
      # use the parameters, without overriding
7251
      for name, value in einfo.items(constants.INISECT_BEP):
7252
        if name not in self.op.beparams:
7253
          self.op.beparams[name] = value
7254
    else:
7255
      # try to read the parameters old style, from the main section
7256
      for name in constants.BES_PARAMETERS:
7257
        if (name not in self.op.beparams and
7258
            einfo.has_option(constants.INISECT_INS, name)):
7259
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
7260

    
7261
    if einfo.has_section(constants.INISECT_OSP):
7262
      # use the parameters, without overriding
7263
      for name, value in einfo.items(constants.INISECT_OSP):
7264
        if name not in self.op.osparams:
7265
          self.op.osparams[name] = value
7266

    
7267
  def _RevertToDefaults(self, cluster):
7268
    """Revert the instance parameters to the default values.
7269

7270
    """
7271
    # hvparams
7272
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
7273
    for name in self.op.hvparams.keys():
7274
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
7275
        del self.op.hvparams[name]
7276
    # beparams
7277
    be_defs = cluster.SimpleFillBE({})
7278
    for name in self.op.beparams.keys():
7279
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
7280
        del self.op.beparams[name]
7281
    # nic params
7282
    nic_defs = cluster.SimpleFillNIC({})
7283
    for nic in self.op.nics:
7284
      for name in constants.NICS_PARAMETERS:
7285
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
7286
          del nic[name]
7287
    # osparams
7288
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
7289
    for name in self.op.osparams.keys():
7290
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
7291
        del self.op.osparams[name]
7292

    
7293
  def CheckPrereq(self):
7294
    """Check prerequisites.
7295

7296
    """
7297
    if self.op.mode == constants.INSTANCE_IMPORT:
7298
      export_info = self._ReadExportInfo()
7299
      self._ReadExportParams(export_info)
7300

    
7301
    _CheckDiskTemplate(self.op.disk_template)
7302

    
7303
    if (not self.cfg.GetVGName() and
7304
        self.op.disk_template not in constants.DTS_NOT_LVM):
7305
      raise errors.OpPrereqError("Cluster does not support lvm-based"
7306
                                 " instances", errors.ECODE_STATE)
7307

    
7308
    if self.op.hypervisor is None:
7309
      self.op.hypervisor = self.cfg.GetHypervisorType()
7310

    
7311
    cluster = self.cfg.GetClusterInfo()
7312
    enabled_hvs = cluster.enabled_hypervisors
7313
    if self.op.hypervisor not in enabled_hvs:
7314
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
7315
                                 " cluster (%s)" % (self.op.hypervisor,
7316
                                  ",".join(enabled_hvs)),
7317
                                 errors.ECODE_STATE)
7318

    
7319
    # check hypervisor parameter syntax (locally)
7320
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
7321
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
7322
                                      self.op.hvparams)
7323
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
7324
    hv_type.CheckParameterSyntax(filled_hvp)
7325
    self.hv_full = filled_hvp
7326
    # check that we don't specify global parameters on an instance
7327
    _CheckGlobalHvParams(self.op.hvparams)
7328

    
7329
    # fill and remember the beparams dict
7330
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
7331
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
7332

    
7333
    # build os parameters
7334
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
7335

    
7336
    # now that hvp/bep are in final format, let's reset to defaults,
7337
    # if told to do so
7338
    if self.op.identify_defaults:
7339
      self._RevertToDefaults(cluster)
7340

    
7341
    # NIC buildup
7342
    self.nics = []
7343
    for idx, nic in enumerate(self.op.nics):
7344
      nic_mode_req = nic.get("mode", None)
7345
      nic_mode = nic_mode_req
7346
      if nic_mode is None:
7347
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
7348

    
7349
      # in routed mode, for the first nic, the default ip is 'auto'
7350
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
7351
        default_ip_mode = constants.VALUE_AUTO
7352
      else:
7353
        default_ip_mode = constants.VALUE_NONE
7354

    
7355
      # ip validity checks
7356
      ip = nic.get("ip", default_ip_mode)
7357
      if ip is None or ip.lower() == constants.VALUE_NONE:
7358
        nic_ip = None
7359
      elif ip.lower() == constants.VALUE_AUTO:
7360
        if not self.op.name_check:
7361
          raise errors.OpPrereqError("IP address set to auto but name checks"
7362
                                     " have been skipped",
7363
                                     errors.ECODE_INVAL)
7364
        nic_ip = self.hostname1.ip
7365
      else:
7366
        if not netutils.IPAddress.IsValid(ip):
7367
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
7368
                                     errors.ECODE_INVAL)
7369
        nic_ip = ip
7370

    
7371
      # TODO: check the ip address for uniqueness
7372
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7373
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7374
                                   errors.ECODE_INVAL)
7375

    
7376
      # MAC address verification
7377
      mac = nic.get("mac", constants.VALUE_AUTO)
7378
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7379
        mac = utils.NormalizeAndValidateMac(mac)
7380

    
7381
        try:
7382
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7383
        except errors.ReservationError:
7384
          raise errors.OpPrereqError("MAC address %s already in use"
7385
                                     " in cluster" % mac,
7386
                                     errors.ECODE_NOTUNIQUE)
7387

    
7388
      # bridge verification
7389
      bridge = nic.get("bridge", None)
7390
      link = nic.get("link", None)
7391
      if bridge and link:
7392
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7393
                                   " at the same time", errors.ECODE_INVAL)
7394
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7395
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7396
                                   errors.ECODE_INVAL)
7397
      elif bridge:
7398
        link = bridge
7399

    
7400
      nicparams = {}
7401
      if nic_mode_req:
7402
        nicparams[constants.NIC_MODE] = nic_mode_req
7403
      if link:
7404
        nicparams[constants.NIC_LINK] = link
7405

    
7406
      check_params = cluster.SimpleFillNIC(nicparams)
7407
      objects.NIC.CheckParameterSyntax(check_params)
7408
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7409

    
7410
    # disk checks/pre-build
7411
    self.disks = []
7412
    for disk in self.op.disks:
7413
      mode = disk.get("mode", constants.DISK_RDWR)
7414
      if mode not in constants.DISK_ACCESS_SET:
7415
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7416
                                   mode, errors.ECODE_INVAL)
7417
      size = disk.get("size", None)
7418
      if size is None:
7419
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7420
      try:
7421
        size = int(size)
7422
      except (TypeError, ValueError):
7423
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7424
                                   errors.ECODE_INVAL)
7425
      new_disk = {"size": size, "mode": mode}
7426
      if "adopt" in disk:
7427
        new_disk["adopt"] = disk["adopt"]
7428
      self.disks.append(new_disk)
7429

    
7430
    if self.op.mode == constants.INSTANCE_IMPORT:
7431

    
7432
      # Check that the new instance doesn't have less disks than the export
7433
      instance_disks = len(self.disks)
7434
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7435
      if instance_disks < export_disks:
7436
        raise errors.OpPrereqError("Not enough disks to import."
7437
                                   " (instance: %d, export: %d)" %
7438
                                   (instance_disks, export_disks),
7439
                                   errors.ECODE_INVAL)
7440

    
7441
      disk_images = []
7442
      for idx in range(export_disks):
7443
        option = 'disk%d_dump' % idx
7444
        if export_info.has_option(constants.INISECT_INS, option):
7445
          # FIXME: are the old os-es, disk sizes, etc. useful?
7446
          export_name = export_info.get(constants.INISECT_INS, option)
7447
          image = utils.PathJoin(self.op.src_path, export_name)
7448
          disk_images.append(image)
7449
        else:
7450
          disk_images.append(False)
7451

    
7452
      self.src_images = disk_images
7453

    
7454
      old_name = export_info.get(constants.INISECT_INS, 'name')
7455
      try:
7456
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7457
      except (TypeError, ValueError), err:
7458
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7459
                                   " an integer: %s" % str(err),
7460
                                   errors.ECODE_STATE)
7461
      if self.op.instance_name == old_name:
7462
        for idx, nic in enumerate(self.nics):
7463
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7464
            nic_mac_ini = 'nic%d_mac' % idx
7465
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7466

    
7467
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7468

    
7469
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7470
    if self.op.ip_check:
7471
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7472
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7473
                                   (self.check_ip, self.op.instance_name),
7474
                                   errors.ECODE_NOTUNIQUE)
7475

    
7476
    #### mac address generation
7477
    # By generating here the mac address both the allocator and the hooks get
7478
    # the real final mac address rather than the 'auto' or 'generate' value.
7479
    # There is a race condition between the generation and the instance object
7480
    # creation, which means that we know the mac is valid now, but we're not
7481
    # sure it will be when we actually add the instance. If things go bad
7482
    # adding the instance will abort because of a duplicate mac, and the
7483
    # creation job will fail.
7484
    for nic in self.nics:
7485
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7486
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7487

    
7488
    #### allocator run
7489

    
7490
    if self.op.iallocator is not None:
7491
      self._RunAllocator()
7492

    
7493
    #### node related checks
7494

    
7495
    # check primary node
7496
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7497
    assert self.pnode is not None, \
7498
      "Cannot retrieve locked node %s" % self.op.pnode
7499
    if pnode.offline:
7500
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7501
                                 pnode.name, errors.ECODE_STATE)
7502
    if pnode.drained:
7503
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7504
                                 pnode.name, errors.ECODE_STATE)
7505
    if not pnode.vm_capable:
7506
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
7507
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
7508

    
7509
    self.secondaries = []
7510

    
7511
    # mirror node verification
7512
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7513
      if self.op.snode == pnode.name:
7514
        raise errors.OpPrereqError("The secondary node cannot be the"
7515
                                   " primary node.", errors.ECODE_INVAL)
7516
      _CheckNodeOnline(self, self.op.snode)
7517
      _CheckNodeNotDrained(self, self.op.snode)
7518
      _CheckNodeVmCapable(self, self.op.snode)
7519
      self.secondaries.append(self.op.snode)
7520

    
7521
    nodenames = [pnode.name] + self.secondaries
7522

    
7523
    req_size = _ComputeDiskSize(self.op.disk_template,
7524
                                self.disks)
7525

    
7526
    # Check lv size requirements, if not adopting
7527
    if req_size is not None and not self.adopt_disks:
7528
      _CheckNodesFreeDisk(self, nodenames, req_size)
7529

    
7530
    if self.adopt_disks: # instead, we must check the adoption data
7531
      all_lvs = set([i["adopt"] for i in self.disks])
7532
      if len(all_lvs) != len(self.disks):
7533
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7534
                                   errors.ECODE_INVAL)
7535
      for lv_name in all_lvs:
7536
        try:
7537
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7538
        except errors.ReservationError:
7539
          raise errors.OpPrereqError("LV named %s used by another instance" %
7540
                                     lv_name, errors.ECODE_NOTUNIQUE)
7541

    
7542
      node_lvs = self.rpc.call_lv_list([pnode.name],
7543
                                       self.cfg.GetVGName())[pnode.name]
7544
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7545
      node_lvs = node_lvs.payload
7546
      delta = all_lvs.difference(node_lvs.keys())
7547
      if delta:
7548
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7549
                                   utils.CommaJoin(delta),
7550
                                   errors.ECODE_INVAL)
7551
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7552
      if online_lvs:
7553
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7554
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7555
                                   errors.ECODE_STATE)
7556
      # update the size of disk based on what is found
7557
      for dsk in self.disks:
7558
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
7559

    
7560
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7561

    
7562
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7563
    # check OS parameters (remotely)
7564
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7565

    
7566
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7567

    
7568
    # memory check on primary node
7569
    if self.op.start:
7570
      _CheckNodeFreeMemory(self, self.pnode.name,
7571
                           "creating instance %s" % self.op.instance_name,
7572
                           self.be_full[constants.BE_MEMORY],
7573
                           self.op.hypervisor)
7574

    
7575
    self.dry_run_result = list(nodenames)
7576

    
7577
  def Exec(self, feedback_fn):
7578
    """Create and add the instance to the cluster.
7579

7580
    """
7581
    instance = self.op.instance_name
7582
    pnode_name = self.pnode.name
7583

    
7584
    ht_kind = self.op.hypervisor
7585
    if ht_kind in constants.HTS_REQ_PORT:
7586
      network_port = self.cfg.AllocatePort()
7587
    else:
7588
      network_port = None
7589

    
7590
    if constants.ENABLE_FILE_STORAGE:
7591
      # this is needed because os.path.join does not accept None arguments
7592
      if self.op.file_storage_dir is None:
7593
        string_file_storage_dir = ""
7594
      else:
7595
        string_file_storage_dir = self.op.file_storage_dir
7596

    
7597
      # build the full file storage dir path
7598
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7599
                                        string_file_storage_dir, instance)
7600
    else:
7601
      file_storage_dir = ""
7602

    
7603
    disks = _GenerateDiskTemplate(self,
7604
                                  self.op.disk_template,
7605
                                  instance, pnode_name,
7606
                                  self.secondaries,
7607
                                  self.disks,
7608
                                  file_storage_dir,
7609
                                  self.op.file_driver,
7610
                                  0)
7611

    
7612
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7613
                            primary_node=pnode_name,
7614
                            nics=self.nics, disks=disks,
7615
                            disk_template=self.op.disk_template,
7616
                            admin_up=False,
7617
                            network_port=network_port,
7618
                            beparams=self.op.beparams,
7619
                            hvparams=self.op.hvparams,
7620
                            hypervisor=self.op.hypervisor,
7621
                            osparams=self.op.osparams,
7622
                            )
7623

    
7624
    if self.adopt_disks:
7625
      # rename LVs to the newly-generated names; we need to construct
7626
      # 'fake' LV disks with the old data, plus the new unique_id
7627
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7628
      rename_to = []
7629
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7630
        rename_to.append(t_dsk.logical_id)
7631
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7632
        self.cfg.SetDiskID(t_dsk, pnode_name)
7633
      result = self.rpc.call_blockdev_rename(pnode_name,
7634
                                             zip(tmp_disks, rename_to))
7635
      result.Raise("Failed to rename adoped LVs")
7636
    else:
7637
      feedback_fn("* creating instance disks...")
7638
      try:
7639
        _CreateDisks(self, iobj)
7640
      except errors.OpExecError:
7641
        self.LogWarning("Device creation failed, reverting...")
7642
        try:
7643
          _RemoveDisks(self, iobj)
7644
        finally:
7645
          self.cfg.ReleaseDRBDMinors(instance)
7646
          raise
7647

    
7648
      if self.cfg.GetClusterInfo().prealloc_wipe_disks:
7649
        feedback_fn("* wiping instance disks...")
7650
        try:
7651
          _WipeDisks(self, iobj)
7652
        except errors.OpExecError:
7653
          self.LogWarning("Device wiping failed, reverting...")
7654
          try:
7655
            _RemoveDisks(self, iobj)
7656
          finally:
7657
            self.cfg.ReleaseDRBDMinors(instance)
7658
            raise
7659

    
7660
    feedback_fn("adding instance %s to cluster config" % instance)
7661

    
7662
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7663

    
7664
    # Declare that we don't want to remove the instance lock anymore, as we've
7665
    # added the instance to the config
7666
    del self.remove_locks[locking.LEVEL_INSTANCE]
7667
    # Unlock all the nodes
7668
    if self.op.mode == constants.INSTANCE_IMPORT:
7669
      nodes_keep = [self.op.src_node]
7670
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7671
                       if node != self.op.src_node]
7672
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7673
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7674
    else:
7675
      self.context.glm.release(locking.LEVEL_NODE)
7676
      del self.acquired_locks[locking.LEVEL_NODE]
7677

    
7678
    if self.op.wait_for_sync:
7679
      disk_abort = not _WaitForSync(self, iobj)
7680
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7681
      # make sure the disks are not degraded (still sync-ing is ok)
7682
      time.sleep(15)
7683
      feedback_fn("* checking mirrors status")
7684
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7685
    else:
7686
      disk_abort = False
7687

    
7688
    if disk_abort:
7689
      _RemoveDisks(self, iobj)
7690
      self.cfg.RemoveInstance(iobj.name)
7691
      # Make sure the instance lock gets removed
7692
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7693
      raise errors.OpExecError("There are some degraded disks for"
7694
                               " this instance")
7695

    
7696
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7697
      if self.op.mode == constants.INSTANCE_CREATE:
7698
        if not self.op.no_install:
7699
          feedback_fn("* running the instance OS create scripts...")
7700
          # FIXME: pass debug option from opcode to backend
7701
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7702
                                                 self.op.debug_level)
7703
          result.Raise("Could not add os for instance %s"
7704
                       " on node %s" % (instance, pnode_name))
7705

    
7706
      elif self.op.mode == constants.INSTANCE_IMPORT:
7707
        feedback_fn("* running the instance OS import scripts...")
7708

    
7709
        transfers = []
7710

    
7711
        for idx, image in enumerate(self.src_images):
7712
          if not image:
7713
            continue
7714

    
7715
          # FIXME: pass debug option from opcode to backend
7716
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7717
                                             constants.IEIO_FILE, (image, ),
7718
                                             constants.IEIO_SCRIPT,
7719
                                             (iobj.disks[idx], idx),
7720
                                             None)
7721
          transfers.append(dt)
7722

    
7723
        import_result = \
7724
          masterd.instance.TransferInstanceData(self, feedback_fn,
7725
                                                self.op.src_node, pnode_name,
7726
                                                self.pnode.secondary_ip,
7727
                                                iobj, transfers)
7728
        if not compat.all(import_result):
7729
          self.LogWarning("Some disks for instance %s on node %s were not"
7730
                          " imported successfully" % (instance, pnode_name))
7731

    
7732
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7733
        feedback_fn("* preparing remote import...")
7734
        # The source cluster will stop the instance before attempting to make a
7735
        # connection. In some cases stopping an instance can take a long time,
7736
        # hence the shutdown timeout is added to the connection timeout.
7737
        connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
7738
                           self.op.source_shutdown_timeout)
7739
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7740

    
7741
        disk_results = masterd.instance.RemoteImport(self, feedback_fn, iobj,
7742
                                                     self.source_x509_ca,
7743
                                                     self._cds, timeouts)
7744
        if not compat.all(disk_results):
7745
          # TODO: Should the instance still be started, even if some disks
7746
          # failed to import (valid for local imports, too)?
7747
          self.LogWarning("Some disks for instance %s on node %s were not"
7748
                          " imported successfully" % (instance, pnode_name))
7749

    
7750
        # Run rename script on newly imported instance
7751
        assert iobj.name == instance
7752
        feedback_fn("Running rename script for %s" % instance)
7753
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7754
                                                   self.source_instance_name,
7755
                                                   self.op.debug_level)
7756
        if result.fail_msg:
7757
          self.LogWarning("Failed to run rename script for %s on node"
7758
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7759

    
7760
      else:
7761
        # also checked in the prereq part
7762
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7763
                                     % self.op.mode)
7764

    
7765
    if self.op.start:
7766
      iobj.admin_up = True
7767
      self.cfg.Update(iobj, feedback_fn)
7768
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7769
      feedback_fn("* starting instance...")
7770
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7771
      result.Raise("Could not start instance")
7772

    
7773
    return list(iobj.all_nodes)
7774

    
7775

    
7776
class LUConnectConsole(NoHooksLU):
7777
  """Connect to an instance's console.
7778

7779
  This is somewhat special in that it returns the command line that
7780
  you need to run on the master node in order to connect to the
7781
  console.
7782

7783
  """
7784
  _OP_PARAMS = [
7785
    _PInstanceName
7786
    ]
7787
  REQ_BGL = False
7788

    
7789
  def ExpandNames(self):
7790
    self._ExpandAndLockInstance()
7791

    
7792
  def CheckPrereq(self):
7793
    """Check prerequisites.
7794

7795
    This checks that the instance is in the cluster.
7796

7797
    """
7798
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7799
    assert self.instance is not None, \
7800
      "Cannot retrieve locked instance %s" % self.op.instance_name
7801
    _CheckNodeOnline(self, self.instance.primary_node)
7802

    
7803
  def Exec(self, feedback_fn):
7804
    """Connect to the console of an instance
7805

7806
    """
7807
    instance = self.instance
7808
    node = instance.primary_node
7809

    
7810
    node_insts = self.rpc.call_instance_list([node],
7811
                                             [instance.hypervisor])[node]
7812
    node_insts.Raise("Can't get node information from %s" % node)
7813

    
7814
    if instance.name not in node_insts.payload:
7815
      if instance.admin_up:
7816
        state = "ERROR_down"
7817
      else:
7818
        state = "ADMIN_down"
7819
      raise errors.OpExecError("Instance %s is not running (state %s)" %
7820
                               (instance.name, state))
7821

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

    
7824
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
7825
    cluster = self.cfg.GetClusterInfo()
7826
    # beparams and hvparams are passed separately, to avoid editing the
7827
    # instance and then saving the defaults in the instance itself.
7828
    hvparams = cluster.FillHV(instance)
7829
    beparams = cluster.FillBE(instance)
7830
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
7831

    
7832
    # build ssh cmdline
7833
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
7834

    
7835

    
7836
class LUReplaceDisks(LogicalUnit):
7837
  """Replace the disks of an instance.
7838

7839
  """
7840
  HPATH = "mirrors-replace"
7841
  HTYPE = constants.HTYPE_INSTANCE
7842
  _OP_PARAMS = [
7843
    _PInstanceName,
7844
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES)),
7845
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt)),
7846
    ("remote_node", None, ht.TMaybeString),
7847
    ("iallocator", None, ht.TMaybeString),
7848
    ("early_release", False, ht.TBool),
7849
    ]
7850
  REQ_BGL = False
7851

    
7852
  def CheckArguments(self):
7853
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7854
                                  self.op.iallocator)
7855

    
7856
  def ExpandNames(self):
7857
    self._ExpandAndLockInstance()
7858

    
7859
    if self.op.iallocator is not None:
7860
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7861

    
7862
    elif self.op.remote_node is not None:
7863
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7864
      self.op.remote_node = remote_node
7865

    
7866
      # Warning: do not remove the locking of the new secondary here
7867
      # unless DRBD8.AddChildren is changed to work in parallel;
7868
      # currently it doesn't since parallel invocations of
7869
      # FindUnusedMinor will conflict
7870
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7871
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7872

    
7873
    else:
7874
      self.needed_locks[locking.LEVEL_NODE] = []
7875
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7876

    
7877
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7878
                                   self.op.iallocator, self.op.remote_node,
7879
                                   self.op.disks, False, self.op.early_release)
7880

    
7881
    self.tasklets = [self.replacer]
7882

    
7883
  def DeclareLocks(self, level):
7884
    # If we're not already locking all nodes in the set we have to declare the
7885
    # instance's primary/secondary nodes.
7886
    if (level == locking.LEVEL_NODE and
7887
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7888
      self._LockInstancesNodes()
7889

    
7890
  def BuildHooksEnv(self):
7891
    """Build hooks env.
7892

7893
    This runs on the master, the primary and all the secondaries.
7894

7895
    """
7896
    instance = self.replacer.instance
7897
    env = {
7898
      "MODE": self.op.mode,
7899
      "NEW_SECONDARY": self.op.remote_node,
7900
      "OLD_SECONDARY": instance.secondary_nodes[0],
7901
      }
7902
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7903
    nl = [
7904
      self.cfg.GetMasterNode(),
7905
      instance.primary_node,
7906
      ]
7907
    if self.op.remote_node is not None:
7908
      nl.append(self.op.remote_node)
7909
    return env, nl, nl
7910

    
7911

    
7912
class TLReplaceDisks(Tasklet):
7913
  """Replaces disks for an instance.
7914

7915
  Note: Locking is not within the scope of this class.
7916

7917
  """
7918
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7919
               disks, delay_iallocator, early_release):
7920
    """Initializes this class.
7921

7922
    """
7923
    Tasklet.__init__(self, lu)
7924

    
7925
    # Parameters
7926
    self.instance_name = instance_name
7927
    self.mode = mode
7928
    self.iallocator_name = iallocator_name
7929
    self.remote_node = remote_node
7930
    self.disks = disks
7931
    self.delay_iallocator = delay_iallocator
7932
    self.early_release = early_release
7933

    
7934
    # Runtime data
7935
    self.instance = None
7936
    self.new_node = None
7937
    self.target_node = None
7938
    self.other_node = None
7939
    self.remote_node_info = None
7940
    self.node_secondary_ip = None
7941

    
7942
  @staticmethod
7943
  def CheckArguments(mode, remote_node, iallocator):
7944
    """Helper function for users of this class.
7945

7946
    """
7947
    # check for valid parameter combination
7948
    if mode == constants.REPLACE_DISK_CHG:
7949
      if remote_node is None and iallocator is None:
7950
        raise errors.OpPrereqError("When changing the secondary either an"
7951
                                   " iallocator script must be used or the"
7952
                                   " new node given", errors.ECODE_INVAL)
7953

    
7954
      if remote_node is not None and iallocator is not None:
7955
        raise errors.OpPrereqError("Give either the iallocator or the new"
7956
                                   " secondary, not both", errors.ECODE_INVAL)
7957

    
7958
    elif remote_node is not None or iallocator is not None:
7959
      # Not replacing the secondary
7960
      raise errors.OpPrereqError("The iallocator and new node options can"
7961
                                 " only be used when changing the"
7962
                                 " secondary node", errors.ECODE_INVAL)
7963

    
7964
  @staticmethod
7965
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7966
    """Compute a new secondary node using an IAllocator.
7967

7968
    """
7969
    ial = IAllocator(lu.cfg, lu.rpc,
7970
                     mode=constants.IALLOCATOR_MODE_RELOC,
7971
                     name=instance_name,
7972
                     relocate_from=relocate_from)
7973

    
7974
    ial.Run(iallocator_name)
7975

    
7976
    if not ial.success:
7977
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7978
                                 " %s" % (iallocator_name, ial.info),
7979
                                 errors.ECODE_NORES)
7980

    
7981
    if len(ial.result) != ial.required_nodes:
7982
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7983
                                 " of nodes (%s), required %s" %
7984
                                 (iallocator_name,
7985
                                  len(ial.result), ial.required_nodes),
7986
                                 errors.ECODE_FAULT)
7987

    
7988
    remote_node_name = ial.result[0]
7989

    
7990
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7991
               instance_name, remote_node_name)
7992

    
7993
    return remote_node_name
7994

    
7995
  def _FindFaultyDisks(self, node_name):
7996
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7997
                                    node_name, True)
7998

    
7999
  def CheckPrereq(self):
8000
    """Check prerequisites.
8001

8002
    This checks that the instance is in the cluster.
8003

8004
    """
8005
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
8006
    assert instance is not None, \
8007
      "Cannot retrieve locked instance %s" % self.instance_name
8008

    
8009
    if instance.disk_template != constants.DT_DRBD8:
8010
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
8011
                                 " instances", errors.ECODE_INVAL)
8012

    
8013
    if len(instance.secondary_nodes) != 1:
8014
      raise errors.OpPrereqError("The instance has a strange layout,"
8015
                                 " expected one secondary but found %d" %
8016
                                 len(instance.secondary_nodes),
8017
                                 errors.ECODE_FAULT)
8018

    
8019
    if not self.delay_iallocator:
8020
      self._CheckPrereq2()
8021

    
8022
  def _CheckPrereq2(self):
8023
    """Check prerequisites, second part.
8024

8025
    This function should always be part of CheckPrereq. It was separated and is
8026
    now called from Exec because during node evacuation iallocator was only
8027
    called with an unmodified cluster model, not taking planned changes into
8028
    account.
8029

8030
    """
8031
    instance = self.instance
8032
    secondary_node = instance.secondary_nodes[0]
8033

    
8034
    if self.iallocator_name is None:
8035
      remote_node = self.remote_node
8036
    else:
8037
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
8038
                                       instance.name, instance.secondary_nodes)
8039

    
8040
    if remote_node is not None:
8041
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
8042
      assert self.remote_node_info is not None, \
8043
        "Cannot retrieve locked node %s" % remote_node
8044
    else:
8045
      self.remote_node_info = None
8046

    
8047
    if remote_node == self.instance.primary_node:
8048
      raise errors.OpPrereqError("The specified node is the primary node of"
8049
                                 " the instance.", errors.ECODE_INVAL)
8050

    
8051
    if remote_node == secondary_node:
8052
      raise errors.OpPrereqError("The specified node is already the"
8053
                                 " secondary node of the instance.",
8054
                                 errors.ECODE_INVAL)
8055

    
8056
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
8057
                                    constants.REPLACE_DISK_CHG):
8058
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
8059
                                 errors.ECODE_INVAL)
8060

    
8061
    if self.mode == constants.REPLACE_DISK_AUTO:
8062
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
8063
      faulty_secondary = self._FindFaultyDisks(secondary_node)
8064

    
8065
      if faulty_primary and faulty_secondary:
8066
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
8067
                                   " one node and can not be repaired"
8068
                                   " automatically" % self.instance_name,
8069
                                   errors.ECODE_STATE)
8070

    
8071
      if faulty_primary:
8072
        self.disks = faulty_primary
8073
        self.target_node = instance.primary_node
8074
        self.other_node = secondary_node
8075
        check_nodes = [self.target_node, self.other_node]
8076
      elif faulty_secondary:
8077
        self.disks = faulty_secondary
8078
        self.target_node = secondary_node
8079
        self.other_node = instance.primary_node
8080
        check_nodes = [self.target_node, self.other_node]
8081
      else:
8082
        self.disks = []
8083
        check_nodes = []
8084

    
8085
    else:
8086
      # Non-automatic modes
8087
      if self.mode == constants.REPLACE_DISK_PRI:
8088
        self.target_node = instance.primary_node
8089
        self.other_node = secondary_node
8090
        check_nodes = [self.target_node, self.other_node]
8091

    
8092
      elif self.mode == constants.REPLACE_DISK_SEC:
8093
        self.target_node = secondary_node
8094
        self.other_node = instance.primary_node
8095
        check_nodes = [self.target_node, self.other_node]
8096

    
8097
      elif self.mode == constants.REPLACE_DISK_CHG:
8098
        self.new_node = remote_node
8099
        self.other_node = instance.primary_node
8100
        self.target_node = secondary_node
8101
        check_nodes = [self.new_node, self.other_node]
8102

    
8103
        _CheckNodeNotDrained(self.lu, remote_node)
8104
        _CheckNodeVmCapable(self.lu, remote_node)
8105

    
8106
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
8107
        assert old_node_info is not None
8108
        if old_node_info.offline and not self.early_release:
8109
          # doesn't make sense to delay the release
8110
          self.early_release = True
8111
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
8112
                          " early-release mode", secondary_node)
8113

    
8114
      else:
8115
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
8116
                                     self.mode)
8117

    
8118
      # If not specified all disks should be replaced
8119
      if not self.disks:
8120
        self.disks = range(len(self.instance.disks))
8121

    
8122
    for node in check_nodes:
8123
      _CheckNodeOnline(self.lu, node)
8124

    
8125
    # Check whether disks are valid
8126
    for disk_idx in self.disks:
8127
      instance.FindDisk(disk_idx)
8128

    
8129
    # Get secondary node IP addresses
8130
    node_2nd_ip = {}
8131

    
8132
    for node_name in [self.target_node, self.other_node, self.new_node]:
8133
      if node_name is not None:
8134
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
8135

    
8136
    self.node_secondary_ip = node_2nd_ip
8137

    
8138
  def Exec(self, feedback_fn):
8139
    """Execute disk replacement.
8140

8141
    This dispatches the disk replacement to the appropriate handler.
8142

8143
    """
8144
    if self.delay_iallocator:
8145
      self._CheckPrereq2()
8146

    
8147
    if not self.disks:
8148
      feedback_fn("No disks need replacement")
8149
      return
8150

    
8151
    feedback_fn("Replacing disk(s) %s for %s" %
8152
                (utils.CommaJoin(self.disks), self.instance.name))
8153

    
8154
    activate_disks = (not self.instance.admin_up)
8155

    
8156
    # Activate the instance disks if we're replacing them on a down instance
8157
    if activate_disks:
8158
      _StartInstanceDisks(self.lu, self.instance, True)
8159

    
8160
    try:
8161
      # Should we replace the secondary node?
8162
      if self.new_node is not None:
8163
        fn = self._ExecDrbd8Secondary
8164
      else:
8165
        fn = self._ExecDrbd8DiskOnly
8166

    
8167
      return fn(feedback_fn)
8168

    
8169
    finally:
8170
      # Deactivate the instance disks if we're replacing them on a
8171
      # down instance
8172
      if activate_disks:
8173
        _SafeShutdownInstanceDisks(self.lu, self.instance)
8174

    
8175
  def _CheckVolumeGroup(self, nodes):
8176
    self.lu.LogInfo("Checking volume groups")
8177

    
8178
    vgname = self.cfg.GetVGName()
8179

    
8180
    # Make sure volume group exists on all involved nodes
8181
    results = self.rpc.call_vg_list(nodes)
8182
    if not results:
8183
      raise errors.OpExecError("Can't list volume groups on the nodes")
8184

    
8185
    for node in nodes:
8186
      res = results[node]
8187
      res.Raise("Error checking node %s" % node)
8188
      if vgname not in res.payload:
8189
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
8190
                                 (vgname, node))
8191

    
8192
  def _CheckDisksExistence(self, nodes):
8193
    # Check disk existence
8194
    for idx, dev in enumerate(self.instance.disks):
8195
      if idx not in self.disks:
8196
        continue
8197

    
8198
      for node in nodes:
8199
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
8200
        self.cfg.SetDiskID(dev, node)
8201

    
8202
        result = self.rpc.call_blockdev_find(node, dev)
8203

    
8204
        msg = result.fail_msg
8205
        if msg or not result.payload:
8206
          if not msg:
8207
            msg = "disk not found"
8208
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
8209
                                   (idx, node, msg))
8210

    
8211
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
8212
    for idx, dev in enumerate(self.instance.disks):
8213
      if idx not in self.disks:
8214
        continue
8215

    
8216
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
8217
                      (idx, node_name))
8218

    
8219
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
8220
                                   ldisk=ldisk):
8221
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
8222
                                 " replace disks for instance %s" %
8223
                                 (node_name, self.instance.name))
8224

    
8225
  def _CreateNewStorage(self, node_name):
8226
    vgname = self.cfg.GetVGName()
8227
    iv_names = {}
8228

    
8229
    for idx, dev in enumerate(self.instance.disks):
8230
      if idx not in self.disks:
8231
        continue
8232

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

    
8235
      self.cfg.SetDiskID(dev, node_name)
8236

    
8237
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
8238
      names = _GenerateUniqueNames(self.lu, lv_names)
8239

    
8240
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
8241
                             logical_id=(vgname, names[0]))
8242
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
8243
                             logical_id=(vgname, names[1]))
8244

    
8245
      new_lvs = [lv_data, lv_meta]
8246
      old_lvs = dev.children
8247
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
8248

    
8249
      # we pass force_create=True to force the LVM creation
8250
      for new_lv in new_lvs:
8251
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
8252
                        _GetInstanceInfoText(self.instance), False)
8253

    
8254
    return iv_names
8255

    
8256
  def _CheckDevices(self, node_name, iv_names):
8257
    for name, (dev, _, _) in iv_names.iteritems():
8258
      self.cfg.SetDiskID(dev, node_name)
8259

    
8260
      result = self.rpc.call_blockdev_find(node_name, dev)
8261

    
8262
      msg = result.fail_msg
8263
      if msg or not result.payload:
8264
        if not msg:
8265
          msg = "disk not found"
8266
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
8267
                                 (name, msg))
8268

    
8269
      if result.payload.is_degraded:
8270
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
8271

    
8272
  def _RemoveOldStorage(self, node_name, iv_names):
8273
    for name, (_, old_lvs, _) in iv_names.iteritems():
8274
      self.lu.LogInfo("Remove logical volumes for %s" % name)
8275

    
8276
      for lv in old_lvs:
8277
        self.cfg.SetDiskID(lv, node_name)
8278

    
8279
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
8280
        if msg:
8281
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
8282
                             hint="remove unused LVs manually")
8283

    
8284
  def _ReleaseNodeLock(self, node_name):
8285
    """Releases the lock for a given node."""
8286
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
8287

    
8288
  def _ExecDrbd8DiskOnly(self, feedback_fn):
8289
    """Replace a disk on the primary or secondary for DRBD 8.
8290

8291
    The algorithm for replace is quite complicated:
8292

8293
      1. for each disk to be replaced:
8294

8295
        1. create new LVs on the target node with unique names
8296
        1. detach old LVs from the drbd device
8297
        1. rename old LVs to name_replaced.<time_t>
8298
        1. rename new LVs to old LVs
8299
        1. attach the new LVs (with the old names now) to the drbd device
8300

8301
      1. wait for sync across all devices
8302

8303
      1. for each modified disk:
8304

8305
        1. remove old LVs (which have the name name_replaces.<time_t>)
8306

8307
    Failures are not very well handled.
8308

8309
    """
8310
    steps_total = 6
8311

    
8312
    # Step: check device activation
8313
    self.lu.LogStep(1, steps_total, "Check device existence")
8314
    self._CheckDisksExistence([self.other_node, self.target_node])
8315
    self._CheckVolumeGroup([self.target_node, self.other_node])
8316

    
8317
    # Step: check other node consistency
8318
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8319
    self._CheckDisksConsistency(self.other_node,
8320
                                self.other_node == self.instance.primary_node,
8321
                                False)
8322

    
8323
    # Step: create new storage
8324
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8325
    iv_names = self._CreateNewStorage(self.target_node)
8326

    
8327
    # Step: for each lv, detach+rename*2+attach
8328
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8329
    for dev, old_lvs, new_lvs in iv_names.itervalues():
8330
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
8331

    
8332
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
8333
                                                     old_lvs)
8334
      result.Raise("Can't detach drbd from local storage on node"
8335
                   " %s for device %s" % (self.target_node, dev.iv_name))
8336
      #dev.children = []
8337
      #cfg.Update(instance)
8338

    
8339
      # ok, we created the new LVs, so now we know we have the needed
8340
      # storage; as such, we proceed on the target node to rename
8341
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
8342
      # using the assumption that logical_id == physical_id (which in
8343
      # turn is the unique_id on that node)
8344

    
8345
      # FIXME(iustin): use a better name for the replaced LVs
8346
      temp_suffix = int(time.time())
8347
      ren_fn = lambda d, suff: (d.physical_id[0],
8348
                                d.physical_id[1] + "_replaced-%s" % suff)
8349

    
8350
      # Build the rename list based on what LVs exist on the node
8351
      rename_old_to_new = []
8352
      for to_ren in old_lvs:
8353
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
8354
        if not result.fail_msg and result.payload:
8355
          # device exists
8356
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
8357

    
8358
      self.lu.LogInfo("Renaming the old LVs on the target node")
8359
      result = self.rpc.call_blockdev_rename(self.target_node,
8360
                                             rename_old_to_new)
8361
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
8362

    
8363
      # Now we rename the new LVs to the old LVs
8364
      self.lu.LogInfo("Renaming the new LVs on the target node")
8365
      rename_new_to_old = [(new, old.physical_id)
8366
                           for old, new in zip(old_lvs, new_lvs)]
8367
      result = self.rpc.call_blockdev_rename(self.target_node,
8368
                                             rename_new_to_old)
8369
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
8370

    
8371
      for old, new in zip(old_lvs, new_lvs):
8372
        new.logical_id = old.logical_id
8373
        self.cfg.SetDiskID(new, self.target_node)
8374

    
8375
      for disk in old_lvs:
8376
        disk.logical_id = ren_fn(disk, temp_suffix)
8377
        self.cfg.SetDiskID(disk, self.target_node)
8378

    
8379
      # Now that the new lvs have the old name, we can add them to the device
8380
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
8381
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
8382
                                                  new_lvs)
8383
      msg = result.fail_msg
8384
      if msg:
8385
        for new_lv in new_lvs:
8386
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
8387
                                               new_lv).fail_msg
8388
          if msg2:
8389
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
8390
                               hint=("cleanup manually the unused logical"
8391
                                     "volumes"))
8392
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8393

    
8394
      dev.children = new_lvs
8395

    
8396
      self.cfg.Update(self.instance, feedback_fn)
8397

    
8398
    cstep = 5
8399
    if self.early_release:
8400
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8401
      cstep += 1
8402
      self._RemoveOldStorage(self.target_node, iv_names)
8403
      # WARNING: we release both node locks here, do not do other RPCs
8404
      # than WaitForSync to the primary node
8405
      self._ReleaseNodeLock([self.target_node, self.other_node])
8406

    
8407
    # Wait for sync
8408
    # This can fail as the old devices are degraded and _WaitForSync
8409
    # does a combined result over all disks, so we don't check its return value
8410
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8411
    cstep += 1
8412
    _WaitForSync(self.lu, self.instance)
8413

    
8414
    # Check all devices manually
8415
    self._CheckDevices(self.instance.primary_node, iv_names)
8416

    
8417
    # Step: remove old storage
8418
    if not self.early_release:
8419
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8420
      cstep += 1
8421
      self._RemoveOldStorage(self.target_node, iv_names)
8422

    
8423
  def _ExecDrbd8Secondary(self, feedback_fn):
8424
    """Replace the secondary node for DRBD 8.
8425

8426
    The algorithm for replace is quite complicated:
8427
      - for all disks of the instance:
8428
        - create new LVs on the new node with same names
8429
        - shutdown the drbd device on the old secondary
8430
        - disconnect the drbd network on the primary
8431
        - create the drbd device on the new secondary
8432
        - network attach the drbd on the primary, using an artifice:
8433
          the drbd code for Attach() will connect to the network if it
8434
          finds a device which is connected to the good local disks but
8435
          not network enabled
8436
      - wait for sync across all devices
8437
      - remove all disks from the old secondary
8438

8439
    Failures are not very well handled.
8440

8441
    """
8442
    steps_total = 6
8443

    
8444
    # Step: check device activation
8445
    self.lu.LogStep(1, steps_total, "Check device existence")
8446
    self._CheckDisksExistence([self.instance.primary_node])
8447
    self._CheckVolumeGroup([self.instance.primary_node])
8448

    
8449
    # Step: check other node consistency
8450
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8451
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8452

    
8453
    # Step: create new storage
8454
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8455
    for idx, dev in enumerate(self.instance.disks):
8456
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8457
                      (self.new_node, idx))
8458
      # we pass force_create=True to force LVM creation
8459
      for new_lv in dev.children:
8460
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8461
                        _GetInstanceInfoText(self.instance), False)
8462

    
8463
    # Step 4: dbrd minors and drbd setups changes
8464
    # after this, we must manually remove the drbd minors on both the
8465
    # error and the success paths
8466
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8467
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8468
                                         for dev in self.instance.disks],
8469
                                        self.instance.name)
8470
    logging.debug("Allocated minors %r", minors)
8471

    
8472
    iv_names = {}
8473
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8474
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8475
                      (self.new_node, idx))
8476
      # create new devices on new_node; note that we create two IDs:
8477
      # one without port, so the drbd will be activated without
8478
      # networking information on the new node at this stage, and one
8479
      # with network, for the latter activation in step 4
8480
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8481
      if self.instance.primary_node == o_node1:
8482
        p_minor = o_minor1
8483
      else:
8484
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8485
        p_minor = o_minor2
8486

    
8487
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8488
                      p_minor, new_minor, o_secret)
8489
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8490
                    p_minor, new_minor, o_secret)
8491

    
8492
      iv_names[idx] = (dev, dev.children, new_net_id)
8493
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8494
                    new_net_id)
8495
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8496
                              logical_id=new_alone_id,
8497
                              children=dev.children,
8498
                              size=dev.size)
8499
      try:
8500
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8501
                              _GetInstanceInfoText(self.instance), False)
8502
      except errors.GenericError:
8503
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8504
        raise
8505

    
8506
    # We have new devices, shutdown the drbd on the old secondary
8507
    for idx, dev in enumerate(self.instance.disks):
8508
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8509
      self.cfg.SetDiskID(dev, self.target_node)
8510
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8511
      if msg:
8512
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8513
                           "node: %s" % (idx, msg),
8514
                           hint=("Please cleanup this device manually as"
8515
                                 " soon as possible"))
8516

    
8517
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8518
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8519
                                               self.node_secondary_ip,
8520
                                               self.instance.disks)\
8521
                                              [self.instance.primary_node]
8522

    
8523
    msg = result.fail_msg
8524
    if msg:
8525
      # detaches didn't succeed (unlikely)
8526
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8527
      raise errors.OpExecError("Can't detach the disks from the network on"
8528
                               " old node: %s" % (msg,))
8529

    
8530
    # if we managed to detach at least one, we update all the disks of
8531
    # the instance to point to the new secondary
8532
    self.lu.LogInfo("Updating instance configuration")
8533
    for dev, _, new_logical_id in iv_names.itervalues():
8534
      dev.logical_id = new_logical_id
8535
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8536

    
8537
    self.cfg.Update(self.instance, feedback_fn)
8538

    
8539
    # and now perform the drbd attach
8540
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8541
                    " (standalone => connected)")
8542
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8543
                                            self.new_node],
8544
                                           self.node_secondary_ip,
8545
                                           self.instance.disks,
8546
                                           self.instance.name,
8547
                                           False)
8548
    for to_node, to_result in result.items():
8549
      msg = to_result.fail_msg
8550
      if msg:
8551
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8552
                           to_node, msg,
8553
                           hint=("please do a gnt-instance info to see the"
8554
                                 " status of disks"))
8555
    cstep = 5
8556
    if self.early_release:
8557
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8558
      cstep += 1
8559
      self._RemoveOldStorage(self.target_node, iv_names)
8560
      # WARNING: we release all node locks here, do not do other RPCs
8561
      # than WaitForSync to the primary node
8562
      self._ReleaseNodeLock([self.instance.primary_node,
8563
                             self.target_node,
8564
                             self.new_node])
8565

    
8566
    # Wait for sync
8567
    # This can fail as the old devices are degraded and _WaitForSync
8568
    # does a combined result over all disks, so we don't check its return value
8569
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8570
    cstep += 1
8571
    _WaitForSync(self.lu, self.instance)
8572

    
8573
    # Check all devices manually
8574
    self._CheckDevices(self.instance.primary_node, iv_names)
8575

    
8576
    # Step: remove old storage
8577
    if not self.early_release:
8578
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8579
      self._RemoveOldStorage(self.target_node, iv_names)
8580

    
8581

    
8582
class LURepairNodeStorage(NoHooksLU):
8583
  """Repairs the volume group on a node.
8584

8585
  """
8586
  _OP_PARAMS = [
8587
    _PNodeName,
8588
    ("storage_type", ht.NoDefault, _CheckStorageType),
8589
    ("name", ht.NoDefault, ht.TNonEmptyString),
8590
    ("ignore_consistency", False, ht.TBool),
8591
    ]
8592
  REQ_BGL = False
8593

    
8594
  def CheckArguments(self):
8595
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8596

    
8597
    storage_type = self.op.storage_type
8598

    
8599
    if (constants.SO_FIX_CONSISTENCY not in
8600
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8601
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8602
                                 " repaired" % storage_type,
8603
                                 errors.ECODE_INVAL)
8604

    
8605
  def ExpandNames(self):
8606
    self.needed_locks = {
8607
      locking.LEVEL_NODE: [self.op.node_name],
8608
      }
8609

    
8610
  def _CheckFaultyDisks(self, instance, node_name):
8611
    """Ensure faulty disks abort the opcode or at least warn."""
8612
    try:
8613
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8614
                                  node_name, True):
8615
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8616
                                   " node '%s'" % (instance.name, node_name),
8617
                                   errors.ECODE_STATE)
8618
    except errors.OpPrereqError, err:
8619
      if self.op.ignore_consistency:
8620
        self.proc.LogWarning(str(err.args[0]))
8621
      else:
8622
        raise
8623

    
8624
  def CheckPrereq(self):
8625
    """Check prerequisites.
8626

8627
    """
8628
    # Check whether any instance on this node has faulty disks
8629
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8630
      if not inst.admin_up:
8631
        continue
8632
      check_nodes = set(inst.all_nodes)
8633
      check_nodes.discard(self.op.node_name)
8634
      for inst_node_name in check_nodes:
8635
        self._CheckFaultyDisks(inst, inst_node_name)
8636

    
8637
  def Exec(self, feedback_fn):
8638
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8639
                (self.op.name, self.op.node_name))
8640

    
8641
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8642
    result = self.rpc.call_storage_execute(self.op.node_name,
8643
                                           self.op.storage_type, st_args,
8644
                                           self.op.name,
8645
                                           constants.SO_FIX_CONSISTENCY)
8646
    result.Raise("Failed to repair storage unit '%s' on %s" %
8647
                 (self.op.name, self.op.node_name))
8648

    
8649

    
8650
class LUNodeEvacuationStrategy(NoHooksLU):
8651
  """Computes the node evacuation strategy.
8652

8653
  """
8654
  _OP_PARAMS = [
8655
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
8656
    ("remote_node", None, ht.TMaybeString),
8657
    ("iallocator", None, ht.TMaybeString),
8658
    ]
8659
  REQ_BGL = False
8660

    
8661
  def CheckArguments(self):
8662
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8663

    
8664
  def ExpandNames(self):
8665
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8666
    self.needed_locks = locks = {}
8667
    if self.op.remote_node is None:
8668
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8669
    else:
8670
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8671
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8672

    
8673
  def Exec(self, feedback_fn):
8674
    if self.op.remote_node is not None:
8675
      instances = []
8676
      for node in self.op.nodes:
8677
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8678
      result = []
8679
      for i in instances:
8680
        if i.primary_node == self.op.remote_node:
8681
          raise errors.OpPrereqError("Node %s is the primary node of"
8682
                                     " instance %s, cannot use it as"
8683
                                     " secondary" %
8684
                                     (self.op.remote_node, i.name),
8685
                                     errors.ECODE_INVAL)
8686
        result.append([i.name, self.op.remote_node])
8687
    else:
8688
      ial = IAllocator(self.cfg, self.rpc,
8689
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8690
                       evac_nodes=self.op.nodes)
8691
      ial.Run(self.op.iallocator, validate=True)
8692
      if not ial.success:
8693
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8694
                                 errors.ECODE_NORES)
8695
      result = ial.result
8696
    return result
8697

    
8698

    
8699
class LUGrowDisk(LogicalUnit):
8700
  """Grow a disk of an instance.
8701

8702
  """
8703
  HPATH = "disk-grow"
8704
  HTYPE = constants.HTYPE_INSTANCE
8705
  _OP_PARAMS = [
8706
    _PInstanceName,
8707
    ("disk", ht.NoDefault, ht.TInt),
8708
    ("amount", ht.NoDefault, ht.TInt),
8709
    ("wait_for_sync", True, ht.TBool),
8710
    ]
8711
  REQ_BGL = False
8712

    
8713
  def ExpandNames(self):
8714
    self._ExpandAndLockInstance()
8715
    self.needed_locks[locking.LEVEL_NODE] = []
8716
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8717

    
8718
  def DeclareLocks(self, level):
8719
    if level == locking.LEVEL_NODE:
8720
      self._LockInstancesNodes()
8721

    
8722
  def BuildHooksEnv(self):
8723
    """Build hooks env.
8724

8725
    This runs on the master, the primary and all the secondaries.
8726

8727
    """
8728
    env = {
8729
      "DISK": self.op.disk,
8730
      "AMOUNT": self.op.amount,
8731
      }
8732
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8733
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8734
    return env, nl, nl
8735

    
8736
  def CheckPrereq(self):
8737
    """Check prerequisites.
8738

8739
    This checks that the instance is in the cluster.
8740

8741
    """
8742
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8743
    assert instance is not None, \
8744
      "Cannot retrieve locked instance %s" % self.op.instance_name
8745
    nodenames = list(instance.all_nodes)
8746
    for node in nodenames:
8747
      _CheckNodeOnline(self, node)
8748

    
8749
    self.instance = instance
8750

    
8751
    if instance.disk_template not in constants.DTS_GROWABLE:
8752
      raise errors.OpPrereqError("Instance's disk layout does not support"
8753
                                 " growing.", errors.ECODE_INVAL)
8754

    
8755
    self.disk = instance.FindDisk(self.op.disk)
8756

    
8757
    if instance.disk_template != constants.DT_FILE:
8758
      # TODO: check the free disk space for file, when that feature will be
8759
      # supported
8760
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
8761

    
8762
  def Exec(self, feedback_fn):
8763
    """Execute disk grow.
8764

8765
    """
8766
    instance = self.instance
8767
    disk = self.disk
8768

    
8769
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8770
    if not disks_ok:
8771
      raise errors.OpExecError("Cannot activate block device to grow")
8772

    
8773
    for node in instance.all_nodes:
8774
      self.cfg.SetDiskID(disk, node)
8775
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8776
      result.Raise("Grow request failed to node %s" % node)
8777

    
8778
      # TODO: Rewrite code to work properly
8779
      # DRBD goes into sync mode for a short amount of time after executing the
8780
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8781
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8782
      # time is a work-around.
8783
      time.sleep(5)
8784

    
8785
    disk.RecordGrow(self.op.amount)
8786
    self.cfg.Update(instance, feedback_fn)
8787
    if self.op.wait_for_sync:
8788
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8789
      if disk_abort:
8790
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8791
                             " status.\nPlease check the instance.")
8792
      if not instance.admin_up:
8793
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8794
    elif not instance.admin_up:
8795
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8796
                           " not supposed to be running because no wait for"
8797
                           " sync mode was requested.")
8798

    
8799

    
8800
class LUQueryInstanceData(NoHooksLU):
8801
  """Query runtime instance data.
8802

8803
  """
8804
  _OP_PARAMS = [
8805
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
8806
    ("static", False, ht.TBool),
8807
    ]
8808
  REQ_BGL = False
8809

    
8810
  def ExpandNames(self):
8811
    self.needed_locks = {}
8812
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8813

    
8814
    if self.op.instances:
8815
      self.wanted_names = []
8816
      for name in self.op.instances:
8817
        full_name = _ExpandInstanceName(self.cfg, name)
8818
        self.wanted_names.append(full_name)
8819
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8820
    else:
8821
      self.wanted_names = None
8822
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8823

    
8824
    self.needed_locks[locking.LEVEL_NODE] = []
8825
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8826

    
8827
  def DeclareLocks(self, level):
8828
    if level == locking.LEVEL_NODE:
8829
      self._LockInstancesNodes()
8830

    
8831
  def CheckPrereq(self):
8832
    """Check prerequisites.
8833

8834
    This only checks the optional instance list against the existing names.
8835

8836
    """
8837
    if self.wanted_names is None:
8838
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8839

    
8840
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8841
                             in self.wanted_names]
8842

    
8843
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8844
    """Returns the status of a block device
8845

8846
    """
8847
    if self.op.static or not node:
8848
      return None
8849

    
8850
    self.cfg.SetDiskID(dev, node)
8851

    
8852
    result = self.rpc.call_blockdev_find(node, dev)
8853
    if result.offline:
8854
      return None
8855

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

    
8858
    status = result.payload
8859
    if status is None:
8860
      return None
8861

    
8862
    return (status.dev_path, status.major, status.minor,
8863
            status.sync_percent, status.estimated_time,
8864
            status.is_degraded, status.ldisk_status)
8865

    
8866
  def _ComputeDiskStatus(self, instance, snode, dev):
8867
    """Compute block device status.
8868

8869
    """
8870
    if dev.dev_type in constants.LDS_DRBD:
8871
      # we change the snode then (otherwise we use the one passed in)
8872
      if dev.logical_id[0] == instance.primary_node:
8873
        snode = dev.logical_id[1]
8874
      else:
8875
        snode = dev.logical_id[0]
8876

    
8877
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8878
                                              instance.name, dev)
8879
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8880

    
8881
    if dev.children:
8882
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8883
                      for child in dev.children]
8884
    else:
8885
      dev_children = []
8886

    
8887
    data = {
8888
      "iv_name": dev.iv_name,
8889
      "dev_type": dev.dev_type,
8890
      "logical_id": dev.logical_id,
8891
      "physical_id": dev.physical_id,
8892
      "pstatus": dev_pstatus,
8893
      "sstatus": dev_sstatus,
8894
      "children": dev_children,
8895
      "mode": dev.mode,
8896
      "size": dev.size,
8897
      }
8898

    
8899
    return data
8900

    
8901
  def Exec(self, feedback_fn):
8902
    """Gather and return data"""
8903
    result = {}
8904

    
8905
    cluster = self.cfg.GetClusterInfo()
8906

    
8907
    for instance in self.wanted_instances:
8908
      if not self.op.static:
8909
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8910
                                                  instance.name,
8911
                                                  instance.hypervisor)
8912
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8913
        remote_info = remote_info.payload
8914
        if remote_info and "state" in remote_info:
8915
          remote_state = "up"
8916
        else:
8917
          remote_state = "down"
8918
      else:
8919
        remote_state = None
8920
      if instance.admin_up:
8921
        config_state = "up"
8922
      else:
8923
        config_state = "down"
8924

    
8925
      disks = [self._ComputeDiskStatus(instance, None, device)
8926
               for device in instance.disks]
8927

    
8928
      idict = {
8929
        "name": instance.name,
8930
        "config_state": config_state,
8931
        "run_state": remote_state,
8932
        "pnode": instance.primary_node,
8933
        "snodes": instance.secondary_nodes,
8934
        "os": instance.os,
8935
        # this happens to be the same format used for hooks
8936
        "nics": _NICListToTuple(self, instance.nics),
8937
        "disk_template": instance.disk_template,
8938
        "disks": disks,
8939
        "hypervisor": instance.hypervisor,
8940
        "network_port": instance.network_port,
8941
        "hv_instance": instance.hvparams,
8942
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8943
        "be_instance": instance.beparams,
8944
        "be_actual": cluster.FillBE(instance),
8945
        "os_instance": instance.osparams,
8946
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8947
        "serial_no": instance.serial_no,
8948
        "mtime": instance.mtime,
8949
        "ctime": instance.ctime,
8950
        "uuid": instance.uuid,
8951
        }
8952

    
8953
      result[instance.name] = idict
8954

    
8955
    return result
8956

    
8957

    
8958
class LUSetInstanceParams(LogicalUnit):
8959
  """Modifies an instances's parameters.
8960

8961
  """
8962
  HPATH = "instance-modify"
8963
  HTYPE = constants.HTYPE_INSTANCE
8964
  _OP_PARAMS = [
8965
    _PInstanceName,
8966
    ("nics", ht.EmptyList, ht.TList),
8967
    ("disks", ht.EmptyList, ht.TList),
8968
    ("beparams", ht.EmptyDict, ht.TDict),
8969
    ("hvparams", ht.EmptyDict, ht.TDict),
8970
    ("disk_template", None, ht.TMaybeString),
8971
    ("remote_node", None, ht.TMaybeString),
8972
    ("os_name", None, ht.TMaybeString),
8973
    ("force_variant", False, ht.TBool),
8974
    ("osparams", None, ht.TOr(ht.TDict, ht.TNone)),
8975
    _PForce,
8976
    ]
8977
  REQ_BGL = False
8978

    
8979
  def CheckArguments(self):
8980
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8981
            self.op.hvparams or self.op.beparams or self.op.os_name):
8982
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8983

    
8984
    if self.op.hvparams:
8985
      _CheckGlobalHvParams(self.op.hvparams)
8986

    
8987
    # Disk validation
8988
    disk_addremove = 0
8989
    for disk_op, disk_dict in self.op.disks:
8990
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8991
      if disk_op == constants.DDM_REMOVE:
8992
        disk_addremove += 1
8993
        continue
8994
      elif disk_op == constants.DDM_ADD:
8995
        disk_addremove += 1
8996
      else:
8997
        if not isinstance(disk_op, int):
8998
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8999
        if not isinstance(disk_dict, dict):
9000
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
9001
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9002

    
9003
      if disk_op == constants.DDM_ADD:
9004
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
9005
        if mode not in constants.DISK_ACCESS_SET:
9006
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
9007
                                     errors.ECODE_INVAL)
9008
        size = disk_dict.get('size', None)
9009
        if size is None:
9010
          raise errors.OpPrereqError("Required disk parameter size missing",
9011
                                     errors.ECODE_INVAL)
9012
        try:
9013
          size = int(size)
9014
        except (TypeError, ValueError), err:
9015
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
9016
                                     str(err), errors.ECODE_INVAL)
9017
        disk_dict['size'] = size
9018
      else:
9019
        # modification of disk
9020
        if 'size' in disk_dict:
9021
          raise errors.OpPrereqError("Disk size change not possible, use"
9022
                                     " grow-disk", errors.ECODE_INVAL)
9023

    
9024
    if disk_addremove > 1:
9025
      raise errors.OpPrereqError("Only one disk add or remove operation"
9026
                                 " supported at a time", errors.ECODE_INVAL)
9027

    
9028
    if self.op.disks and self.op.disk_template is not None:
9029
      raise errors.OpPrereqError("Disk template conversion and other disk"
9030
                                 " changes not supported at the same time",
9031
                                 errors.ECODE_INVAL)
9032

    
9033
    if self.op.disk_template:
9034
      _CheckDiskTemplate(self.op.disk_template)
9035
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
9036
          self.op.remote_node is None):
9037
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
9038
                                   " one requires specifying a secondary node",
9039
                                   errors.ECODE_INVAL)
9040

    
9041
    # NIC validation
9042
    nic_addremove = 0
9043
    for nic_op, nic_dict in self.op.nics:
9044
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
9045
      if nic_op == constants.DDM_REMOVE:
9046
        nic_addremove += 1
9047
        continue
9048
      elif nic_op == constants.DDM_ADD:
9049
        nic_addremove += 1
9050
      else:
9051
        if not isinstance(nic_op, int):
9052
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
9053
        if not isinstance(nic_dict, dict):
9054
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
9055
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9056

    
9057
      # nic_dict should be a dict
9058
      nic_ip = nic_dict.get('ip', None)
9059
      if nic_ip is not None:
9060
        if nic_ip.lower() == constants.VALUE_NONE:
9061
          nic_dict['ip'] = None
9062
        else:
9063
          if not netutils.IPAddress.IsValid(nic_ip):
9064
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
9065
                                       errors.ECODE_INVAL)
9066

    
9067
      nic_bridge = nic_dict.get('bridge', None)
9068
      nic_link = nic_dict.get('link', None)
9069
      if nic_bridge and nic_link:
9070
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
9071
                                   " at the same time", errors.ECODE_INVAL)
9072
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
9073
        nic_dict['bridge'] = None
9074
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
9075
        nic_dict['link'] = None
9076

    
9077
      if nic_op == constants.DDM_ADD:
9078
        nic_mac = nic_dict.get('mac', None)
9079
        if nic_mac is None:
9080
          nic_dict['mac'] = constants.VALUE_AUTO
9081

    
9082
      if 'mac' in nic_dict:
9083
        nic_mac = nic_dict['mac']
9084
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9085
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
9086

    
9087
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
9088
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
9089
                                     " modifying an existing nic",
9090
                                     errors.ECODE_INVAL)
9091

    
9092
    if nic_addremove > 1:
9093
      raise errors.OpPrereqError("Only one NIC add or remove operation"
9094
                                 " supported at a time", errors.ECODE_INVAL)
9095

    
9096
  def ExpandNames(self):
9097
    self._ExpandAndLockInstance()
9098
    self.needed_locks[locking.LEVEL_NODE] = []
9099
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9100

    
9101
  def DeclareLocks(self, level):
9102
    if level == locking.LEVEL_NODE:
9103
      self._LockInstancesNodes()
9104
      if self.op.disk_template and self.op.remote_node:
9105
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9106
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
9107

    
9108
  def BuildHooksEnv(self):
9109
    """Build hooks env.
9110

9111
    This runs on the master, primary and secondaries.
9112

9113
    """
9114
    args = dict()
9115
    if constants.BE_MEMORY in self.be_new:
9116
      args['memory'] = self.be_new[constants.BE_MEMORY]
9117
    if constants.BE_VCPUS in self.be_new:
9118
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
9119
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
9120
    # information at all.
9121
    if self.op.nics:
9122
      args['nics'] = []
9123
      nic_override = dict(self.op.nics)
9124
      for idx, nic in enumerate(self.instance.nics):
9125
        if idx in nic_override:
9126
          this_nic_override = nic_override[idx]
9127
        else:
9128
          this_nic_override = {}
9129
        if 'ip' in this_nic_override:
9130
          ip = this_nic_override['ip']
9131
        else:
9132
          ip = nic.ip
9133
        if 'mac' in this_nic_override:
9134
          mac = this_nic_override['mac']
9135
        else:
9136
          mac = nic.mac
9137
        if idx in self.nic_pnew:
9138
          nicparams = self.nic_pnew[idx]
9139
        else:
9140
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
9141
        mode = nicparams[constants.NIC_MODE]
9142
        link = nicparams[constants.NIC_LINK]
9143
        args['nics'].append((ip, mac, mode, link))
9144
      if constants.DDM_ADD in nic_override:
9145
        ip = nic_override[constants.DDM_ADD].get('ip', None)
9146
        mac = nic_override[constants.DDM_ADD]['mac']
9147
        nicparams = self.nic_pnew[constants.DDM_ADD]
9148
        mode = nicparams[constants.NIC_MODE]
9149
        link = nicparams[constants.NIC_LINK]
9150
        args['nics'].append((ip, mac, mode, link))
9151
      elif constants.DDM_REMOVE in nic_override:
9152
        del args['nics'][-1]
9153

    
9154
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
9155
    if self.op.disk_template:
9156
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
9157
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9158
    return env, nl, nl
9159

    
9160
  def CheckPrereq(self):
9161
    """Check prerequisites.
9162

9163
    This only checks the instance list against the existing names.
9164

9165
    """
9166
    # checking the new params on the primary/secondary nodes
9167

    
9168
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9169
    cluster = self.cluster = self.cfg.GetClusterInfo()
9170
    assert self.instance is not None, \
9171
      "Cannot retrieve locked instance %s" % self.op.instance_name
9172
    pnode = instance.primary_node
9173
    nodelist = list(instance.all_nodes)
9174

    
9175
    # OS change
9176
    if self.op.os_name and not self.op.force:
9177
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
9178
                      self.op.force_variant)
9179
      instance_os = self.op.os_name
9180
    else:
9181
      instance_os = instance.os
9182

    
9183
    if self.op.disk_template:
9184
      if instance.disk_template == self.op.disk_template:
9185
        raise errors.OpPrereqError("Instance already has disk template %s" %
9186
                                   instance.disk_template, errors.ECODE_INVAL)
9187

    
9188
      if (instance.disk_template,
9189
          self.op.disk_template) not in self._DISK_CONVERSIONS:
9190
        raise errors.OpPrereqError("Unsupported disk template conversion from"
9191
                                   " %s to %s" % (instance.disk_template,
9192
                                                  self.op.disk_template),
9193
                                   errors.ECODE_INVAL)
9194
      _CheckInstanceDown(self, instance, "cannot change disk template")
9195
      if self.op.disk_template in constants.DTS_NET_MIRROR:
9196
        if self.op.remote_node == pnode:
9197
          raise errors.OpPrereqError("Given new secondary node %s is the same"
9198
                                     " as the primary node of the instance" %
9199
                                     self.op.remote_node, errors.ECODE_STATE)
9200
        _CheckNodeOnline(self, self.op.remote_node)
9201
        _CheckNodeNotDrained(self, self.op.remote_node)
9202
        disks = [{"size": d.size} for d in instance.disks]
9203
        required = _ComputeDiskSize(self.op.disk_template, disks)
9204
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
9205

    
9206
    # hvparams processing
9207
    if self.op.hvparams:
9208
      hv_type = instance.hypervisor
9209
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
9210
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
9211
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
9212

    
9213
      # local check
9214
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
9215
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
9216
      self.hv_new = hv_new # the new actual values
9217
      self.hv_inst = i_hvdict # the new dict (without defaults)
9218
    else:
9219
      self.hv_new = self.hv_inst = {}
9220

    
9221
    # beparams processing
9222
    if self.op.beparams:
9223
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
9224
                                   use_none=True)
9225
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
9226
      be_new = cluster.SimpleFillBE(i_bedict)
9227
      self.be_new = be_new # the new actual values
9228
      self.be_inst = i_bedict # the new dict (without defaults)
9229
    else:
9230
      self.be_new = self.be_inst = {}
9231

    
9232
    # osparams processing
9233
    if self.op.osparams:
9234
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
9235
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
9236
      self.os_inst = i_osdict # the new dict (without defaults)
9237
    else:
9238
      self.os_inst = {}
9239

    
9240
    self.warn = []
9241

    
9242
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
9243
      mem_check_list = [pnode]
9244
      if be_new[constants.BE_AUTO_BALANCE]:
9245
        # either we changed auto_balance to yes or it was from before
9246
        mem_check_list.extend(instance.secondary_nodes)
9247
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
9248
                                                  instance.hypervisor)
9249
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
9250
                                         instance.hypervisor)
9251
      pninfo = nodeinfo[pnode]
9252
      msg = pninfo.fail_msg
9253
      if msg:
9254
        # Assume the primary node is unreachable and go ahead
9255
        self.warn.append("Can't get info from primary node %s: %s" %
9256
                         (pnode,  msg))
9257
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
9258
        self.warn.append("Node data from primary node %s doesn't contain"
9259
                         " free memory information" % pnode)
9260
      elif instance_info.fail_msg:
9261
        self.warn.append("Can't get instance runtime information: %s" %
9262
                        instance_info.fail_msg)
9263
      else:
9264
        if instance_info.payload:
9265
          current_mem = int(instance_info.payload['memory'])
9266
        else:
9267
          # Assume instance not running
9268
          # (there is a slight race condition here, but it's not very probable,
9269
          # and we have no other way to check)
9270
          current_mem = 0
9271
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
9272
                    pninfo.payload['memory_free'])
9273
        if miss_mem > 0:
9274
          raise errors.OpPrereqError("This change will prevent the instance"
9275
                                     " from starting, due to %d MB of memory"
9276
                                     " missing on its primary node" % miss_mem,
9277
                                     errors.ECODE_NORES)
9278

    
9279
      if be_new[constants.BE_AUTO_BALANCE]:
9280
        for node, nres in nodeinfo.items():
9281
          if node not in instance.secondary_nodes:
9282
            continue
9283
          msg = nres.fail_msg
9284
          if msg:
9285
            self.warn.append("Can't get info from secondary node %s: %s" %
9286
                             (node, msg))
9287
          elif not isinstance(nres.payload.get('memory_free', None), int):
9288
            self.warn.append("Secondary node %s didn't return free"
9289
                             " memory information" % node)
9290
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
9291
            self.warn.append("Not enough memory to failover instance to"
9292
                             " secondary node %s" % node)
9293

    
9294
    # NIC processing
9295
    self.nic_pnew = {}
9296
    self.nic_pinst = {}
9297
    for nic_op, nic_dict in self.op.nics:
9298
      if nic_op == constants.DDM_REMOVE:
9299
        if not instance.nics:
9300
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
9301
                                     errors.ECODE_INVAL)
9302
        continue
9303
      if nic_op != constants.DDM_ADD:
9304
        # an existing nic
9305
        if not instance.nics:
9306
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
9307
                                     " no NICs" % nic_op,
9308
                                     errors.ECODE_INVAL)
9309
        if nic_op < 0 or nic_op >= len(instance.nics):
9310
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
9311
                                     " are 0 to %d" %
9312
                                     (nic_op, len(instance.nics) - 1),
9313
                                     errors.ECODE_INVAL)
9314
        old_nic_params = instance.nics[nic_op].nicparams
9315
        old_nic_ip = instance.nics[nic_op].ip
9316
      else:
9317
        old_nic_params = {}
9318
        old_nic_ip = None
9319

    
9320
      update_params_dict = dict([(key, nic_dict[key])
9321
                                 for key in constants.NICS_PARAMETERS
9322
                                 if key in nic_dict])
9323

    
9324
      if 'bridge' in nic_dict:
9325
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
9326

    
9327
      new_nic_params = _GetUpdatedParams(old_nic_params,
9328
                                         update_params_dict)
9329
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
9330
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
9331
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
9332
      self.nic_pinst[nic_op] = new_nic_params
9333
      self.nic_pnew[nic_op] = new_filled_nic_params
9334
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
9335

    
9336
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
9337
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
9338
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
9339
        if msg:
9340
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
9341
          if self.op.force:
9342
            self.warn.append(msg)
9343
          else:
9344
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
9345
      if new_nic_mode == constants.NIC_MODE_ROUTED:
9346
        if 'ip' in nic_dict:
9347
          nic_ip = nic_dict['ip']
9348
        else:
9349
          nic_ip = old_nic_ip
9350
        if nic_ip is None:
9351
          raise errors.OpPrereqError('Cannot set the nic ip to None'
9352
                                     ' on a routed nic', errors.ECODE_INVAL)
9353
      if 'mac' in nic_dict:
9354
        nic_mac = nic_dict['mac']
9355
        if nic_mac is None:
9356
          raise errors.OpPrereqError('Cannot set the nic mac to None',
9357
                                     errors.ECODE_INVAL)
9358
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9359
          # otherwise generate the mac
9360
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
9361
        else:
9362
          # or validate/reserve the current one
9363
          try:
9364
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
9365
          except errors.ReservationError:
9366
            raise errors.OpPrereqError("MAC address %s already in use"
9367
                                       " in cluster" % nic_mac,
9368
                                       errors.ECODE_NOTUNIQUE)
9369

    
9370
    # DISK processing
9371
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
9372
      raise errors.OpPrereqError("Disk operations not supported for"
9373
                                 " diskless instances",
9374
                                 errors.ECODE_INVAL)
9375
    for disk_op, _ in self.op.disks:
9376
      if disk_op == constants.DDM_REMOVE:
9377
        if len(instance.disks) == 1:
9378
          raise errors.OpPrereqError("Cannot remove the last disk of"
9379
                                     " an instance", errors.ECODE_INVAL)
9380
        _CheckInstanceDown(self, instance, "cannot remove disks")
9381

    
9382
      if (disk_op == constants.DDM_ADD and
9383
          len(instance.nics) >= constants.MAX_DISKS):
9384
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
9385
                                   " add more" % constants.MAX_DISKS,
9386
                                   errors.ECODE_STATE)
9387
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
9388
        # an existing disk
9389
        if disk_op < 0 or disk_op >= len(instance.disks):
9390
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9391
                                     " are 0 to %d" %
9392
                                     (disk_op, len(instance.disks)),
9393
                                     errors.ECODE_INVAL)
9394

    
9395
    return
9396

    
9397
  def _ConvertPlainToDrbd(self, feedback_fn):
9398
    """Converts an instance from plain to drbd.
9399

9400
    """
9401
    feedback_fn("Converting template to drbd")
9402
    instance = self.instance
9403
    pnode = instance.primary_node
9404
    snode = self.op.remote_node
9405

    
9406
    # create a fake disk info for _GenerateDiskTemplate
9407
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
9408
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9409
                                      instance.name, pnode, [snode],
9410
                                      disk_info, None, None, 0)
9411
    info = _GetInstanceInfoText(instance)
9412
    feedback_fn("Creating aditional volumes...")
9413
    # first, create the missing data and meta devices
9414
    for disk in new_disks:
9415
      # unfortunately this is... not too nice
9416
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9417
                            info, True)
9418
      for child in disk.children:
9419
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9420
    # at this stage, all new LVs have been created, we can rename the
9421
    # old ones
9422
    feedback_fn("Renaming original volumes...")
9423
    rename_list = [(o, n.children[0].logical_id)
9424
                   for (o, n) in zip(instance.disks, new_disks)]
9425
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9426
    result.Raise("Failed to rename original LVs")
9427

    
9428
    feedback_fn("Initializing DRBD devices...")
9429
    # all child devices are in place, we can now create the DRBD devices
9430
    for disk in new_disks:
9431
      for node in [pnode, snode]:
9432
        f_create = node == pnode
9433
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9434

    
9435
    # at this point, the instance has been modified
9436
    instance.disk_template = constants.DT_DRBD8
9437
    instance.disks = new_disks
9438
    self.cfg.Update(instance, feedback_fn)
9439

    
9440
    # disks are created, waiting for sync
9441
    disk_abort = not _WaitForSync(self, instance)
9442
    if disk_abort:
9443
      raise errors.OpExecError("There are some degraded disks for"
9444
                               " this instance, please cleanup manually")
9445

    
9446
  def _ConvertDrbdToPlain(self, feedback_fn):
9447
    """Converts an instance from drbd to plain.
9448

9449
    """
9450
    instance = self.instance
9451
    assert len(instance.secondary_nodes) == 1
9452
    pnode = instance.primary_node
9453
    snode = instance.secondary_nodes[0]
9454
    feedback_fn("Converting template to plain")
9455

    
9456
    old_disks = instance.disks
9457
    new_disks = [d.children[0] for d in old_disks]
9458

    
9459
    # copy over size and mode
9460
    for parent, child in zip(old_disks, new_disks):
9461
      child.size = parent.size
9462
      child.mode = parent.mode
9463

    
9464
    # update instance structure
9465
    instance.disks = new_disks
9466
    instance.disk_template = constants.DT_PLAIN
9467
    self.cfg.Update(instance, feedback_fn)
9468

    
9469
    feedback_fn("Removing volumes on the secondary node...")
9470
    for disk in old_disks:
9471
      self.cfg.SetDiskID(disk, snode)
9472
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9473
      if msg:
9474
        self.LogWarning("Could not remove block device %s on node %s,"
9475
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9476

    
9477
    feedback_fn("Removing unneeded volumes on the primary node...")
9478
    for idx, disk in enumerate(old_disks):
9479
      meta = disk.children[1]
9480
      self.cfg.SetDiskID(meta, pnode)
9481
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9482
      if msg:
9483
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9484
                        " continuing anyway: %s", idx, pnode, msg)
9485

    
9486

    
9487
  def Exec(self, feedback_fn):
9488
    """Modifies an instance.
9489

9490
    All parameters take effect only at the next restart of the instance.
9491

9492
    """
9493
    # Process here the warnings from CheckPrereq, as we don't have a
9494
    # feedback_fn there.
9495
    for warn in self.warn:
9496
      feedback_fn("WARNING: %s" % warn)
9497

    
9498
    result = []
9499
    instance = self.instance
9500
    # disk changes
9501
    for disk_op, disk_dict in self.op.disks:
9502
      if disk_op == constants.DDM_REMOVE:
9503
        # remove the last disk
9504
        device = instance.disks.pop()
9505
        device_idx = len(instance.disks)
9506
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9507
          self.cfg.SetDiskID(disk, node)
9508
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9509
          if msg:
9510
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9511
                            " continuing anyway", device_idx, node, msg)
9512
        result.append(("disk/%d" % device_idx, "remove"))
9513
      elif disk_op == constants.DDM_ADD:
9514
        # add a new disk
9515
        if instance.disk_template == constants.DT_FILE:
9516
          file_driver, file_path = instance.disks[0].logical_id
9517
          file_path = os.path.dirname(file_path)
9518
        else:
9519
          file_driver = file_path = None
9520
        disk_idx_base = len(instance.disks)
9521
        new_disk = _GenerateDiskTemplate(self,
9522
                                         instance.disk_template,
9523
                                         instance.name, instance.primary_node,
9524
                                         instance.secondary_nodes,
9525
                                         [disk_dict],
9526
                                         file_path,
9527
                                         file_driver,
9528
                                         disk_idx_base)[0]
9529
        instance.disks.append(new_disk)
9530
        info = _GetInstanceInfoText(instance)
9531

    
9532
        logging.info("Creating volume %s for instance %s",
9533
                     new_disk.iv_name, instance.name)
9534
        # Note: this needs to be kept in sync with _CreateDisks
9535
        #HARDCODE
9536
        for node in instance.all_nodes:
9537
          f_create = node == instance.primary_node
9538
          try:
9539
            _CreateBlockDev(self, node, instance, new_disk,
9540
                            f_create, info, f_create)
9541
          except errors.OpExecError, err:
9542
            self.LogWarning("Failed to create volume %s (%s) on"
9543
                            " node %s: %s",
9544
                            new_disk.iv_name, new_disk, node, err)
9545
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9546
                       (new_disk.size, new_disk.mode)))
9547
      else:
9548
        # change a given disk
9549
        instance.disks[disk_op].mode = disk_dict['mode']
9550
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9551

    
9552
    if self.op.disk_template:
9553
      r_shut = _ShutdownInstanceDisks(self, instance)
9554
      if not r_shut:
9555
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
9556
                                 " proceed with disk template conversion")
9557
      mode = (instance.disk_template, self.op.disk_template)
9558
      try:
9559
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9560
      except:
9561
        self.cfg.ReleaseDRBDMinors(instance.name)
9562
        raise
9563
      result.append(("disk_template", self.op.disk_template))
9564

    
9565
    # NIC changes
9566
    for nic_op, nic_dict in self.op.nics:
9567
      if nic_op == constants.DDM_REMOVE:
9568
        # remove the last nic
9569
        del instance.nics[-1]
9570
        result.append(("nic.%d" % len(instance.nics), "remove"))
9571
      elif nic_op == constants.DDM_ADD:
9572
        # mac and bridge should be set, by now
9573
        mac = nic_dict['mac']
9574
        ip = nic_dict.get('ip', None)
9575
        nicparams = self.nic_pinst[constants.DDM_ADD]
9576
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9577
        instance.nics.append(new_nic)
9578
        result.append(("nic.%d" % (len(instance.nics) - 1),
9579
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9580
                       (new_nic.mac, new_nic.ip,
9581
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9582
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9583
                       )))
9584
      else:
9585
        for key in 'mac', 'ip':
9586
          if key in nic_dict:
9587
            setattr(instance.nics[nic_op], key, nic_dict[key])
9588
        if nic_op in self.nic_pinst:
9589
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9590
        for key, val in nic_dict.iteritems():
9591
          result.append(("nic.%s/%d" % (key, nic_op), val))
9592

    
9593
    # hvparams changes
9594
    if self.op.hvparams:
9595
      instance.hvparams = self.hv_inst
9596
      for key, val in self.op.hvparams.iteritems():
9597
        result.append(("hv/%s" % key, val))
9598

    
9599
    # beparams changes
9600
    if self.op.beparams:
9601
      instance.beparams = self.be_inst
9602
      for key, val in self.op.beparams.iteritems():
9603
        result.append(("be/%s" % key, val))
9604

    
9605
    # OS change
9606
    if self.op.os_name:
9607
      instance.os = self.op.os_name
9608

    
9609
    # osparams changes
9610
    if self.op.osparams:
9611
      instance.osparams = self.os_inst
9612
      for key, val in self.op.osparams.iteritems():
9613
        result.append(("os/%s" % key, val))
9614

    
9615
    self.cfg.Update(instance, feedback_fn)
9616

    
9617
    return result
9618

    
9619
  _DISK_CONVERSIONS = {
9620
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9621
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9622
    }
9623

    
9624

    
9625
class LUQueryExports(NoHooksLU):
9626
  """Query the exports list
9627

9628
  """
9629
  _OP_PARAMS = [
9630
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
9631
    ("use_locking", False, ht.TBool),
9632
    ]
9633
  REQ_BGL = False
9634

    
9635
  def ExpandNames(self):
9636
    self.needed_locks = {}
9637
    self.share_locks[locking.LEVEL_NODE] = 1
9638
    if not self.op.nodes:
9639
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9640
    else:
9641
      self.needed_locks[locking.LEVEL_NODE] = \
9642
        _GetWantedNodes(self, self.op.nodes)
9643

    
9644
  def Exec(self, feedback_fn):
9645
    """Compute the list of all the exported system images.
9646

9647
    @rtype: dict
9648
    @return: a dictionary with the structure node->(export-list)
9649
        where export-list is a list of the instances exported on
9650
        that node.
9651

9652
    """
9653
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9654
    rpcresult = self.rpc.call_export_list(self.nodes)
9655
    result = {}
9656
    for node in rpcresult:
9657
      if rpcresult[node].fail_msg:
9658
        result[node] = False
9659
      else:
9660
        result[node] = rpcresult[node].payload
9661

    
9662
    return result
9663

    
9664

    
9665
class LUPrepareExport(NoHooksLU):
9666
  """Prepares an instance for an export and returns useful information.
9667

9668
  """
9669
  _OP_PARAMS = [
9670
    _PInstanceName,
9671
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES)),
9672
    ]
9673
  REQ_BGL = False
9674

    
9675
  def ExpandNames(self):
9676
    self._ExpandAndLockInstance()
9677

    
9678
  def CheckPrereq(self):
9679
    """Check prerequisites.
9680

9681
    """
9682
    instance_name = self.op.instance_name
9683

    
9684
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9685
    assert self.instance is not None, \
9686
          "Cannot retrieve locked instance %s" % self.op.instance_name
9687
    _CheckNodeOnline(self, self.instance.primary_node)
9688

    
9689
    self._cds = _GetClusterDomainSecret()
9690

    
9691
  def Exec(self, feedback_fn):
9692
    """Prepares an instance for an export.
9693

9694
    """
9695
    instance = self.instance
9696

    
9697
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9698
      salt = utils.GenerateSecret(8)
9699

    
9700
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9701
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9702
                                              constants.RIE_CERT_VALIDITY)
9703
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9704

    
9705
      (name, cert_pem) = result.payload
9706

    
9707
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9708
                                             cert_pem)
9709

    
9710
      return {
9711
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9712
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9713
                          salt),
9714
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9715
        }
9716

    
9717
    return None
9718

    
9719

    
9720
class LUExportInstance(LogicalUnit):
9721
  """Export an instance to an image in the cluster.
9722

9723
  """
9724
  HPATH = "instance-export"
9725
  HTYPE = constants.HTYPE_INSTANCE
9726
  _OP_PARAMS = [
9727
    _PInstanceName,
9728
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList)),
9729
    ("shutdown", True, ht.TBool),
9730
    _PShutdownTimeout,
9731
    ("remove_instance", False, ht.TBool),
9732
    ("ignore_remove_failures", False, ht.TBool),
9733
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES)),
9734
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone)),
9735
    ("destination_x509_ca", None, ht.TMaybeString),
9736
    ]
9737
  REQ_BGL = False
9738

    
9739
  def CheckArguments(self):
9740
    """Check the arguments.
9741

9742
    """
9743
    self.x509_key_name = self.op.x509_key_name
9744
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9745

    
9746
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9747
      if not self.x509_key_name:
9748
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9749
                                   errors.ECODE_INVAL)
9750

    
9751
      if not self.dest_x509_ca_pem:
9752
        raise errors.OpPrereqError("Missing destination X509 CA",
9753
                                   errors.ECODE_INVAL)
9754

    
9755
  def ExpandNames(self):
9756
    self._ExpandAndLockInstance()
9757

    
9758
    # Lock all nodes for local exports
9759
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9760
      # FIXME: lock only instance primary and destination node
9761
      #
9762
      # Sad but true, for now we have do lock all nodes, as we don't know where
9763
      # the previous export might be, and in this LU we search for it and
9764
      # remove it from its current node. In the future we could fix this by:
9765
      #  - making a tasklet to search (share-lock all), then create the
9766
      #    new one, then one to remove, after
9767
      #  - removing the removal operation altogether
9768
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9769

    
9770
  def DeclareLocks(self, level):
9771
    """Last minute lock declaration."""
9772
    # All nodes are locked anyway, so nothing to do here.
9773

    
9774
  def BuildHooksEnv(self):
9775
    """Build hooks env.
9776

9777
    This will run on the master, primary node and target node.
9778

9779
    """
9780
    env = {
9781
      "EXPORT_MODE": self.op.mode,
9782
      "EXPORT_NODE": self.op.target_node,
9783
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9784
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9785
      # TODO: Generic function for boolean env variables
9786
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9787
      }
9788

    
9789
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9790

    
9791
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9792

    
9793
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9794
      nl.append(self.op.target_node)
9795

    
9796
    return env, nl, nl
9797

    
9798
  def CheckPrereq(self):
9799
    """Check prerequisites.
9800

9801
    This checks that the instance and node names are valid.
9802

9803
    """
9804
    instance_name = self.op.instance_name
9805

    
9806
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9807
    assert self.instance is not None, \
9808
          "Cannot retrieve locked instance %s" % self.op.instance_name
9809
    _CheckNodeOnline(self, self.instance.primary_node)
9810

    
9811
    if (self.op.remove_instance and self.instance.admin_up and
9812
        not self.op.shutdown):
9813
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9814
                                 " down before")
9815

    
9816
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9817
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9818
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9819
      assert self.dst_node is not None
9820

    
9821
      _CheckNodeOnline(self, self.dst_node.name)
9822
      _CheckNodeNotDrained(self, self.dst_node.name)
9823

    
9824
      self._cds = None
9825
      self.dest_disk_info = None
9826
      self.dest_x509_ca = None
9827

    
9828
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9829
      self.dst_node = None
9830

    
9831
      if len(self.op.target_node) != len(self.instance.disks):
9832
        raise errors.OpPrereqError(("Received destination information for %s"
9833
                                    " disks, but instance %s has %s disks") %
9834
                                   (len(self.op.target_node), instance_name,
9835
                                    len(self.instance.disks)),
9836
                                   errors.ECODE_INVAL)
9837

    
9838
      cds = _GetClusterDomainSecret()
9839

    
9840
      # Check X509 key name
9841
      try:
9842
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9843
      except (TypeError, ValueError), err:
9844
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9845

    
9846
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9847
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9848
                                   errors.ECODE_INVAL)
9849

    
9850
      # Load and verify CA
9851
      try:
9852
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9853
      except OpenSSL.crypto.Error, err:
9854
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9855
                                   (err, ), errors.ECODE_INVAL)
9856

    
9857
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9858
      if errcode is not None:
9859
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9860
                                   (msg, ), errors.ECODE_INVAL)
9861

    
9862
      self.dest_x509_ca = cert
9863

    
9864
      # Verify target information
9865
      disk_info = []
9866
      for idx, disk_data in enumerate(self.op.target_node):
9867
        try:
9868
          (host, port, magic) = \
9869
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9870
        except errors.GenericError, err:
9871
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9872
                                     (idx, err), errors.ECODE_INVAL)
9873

    
9874
        disk_info.append((host, port, magic))
9875

    
9876
      assert len(disk_info) == len(self.op.target_node)
9877
      self.dest_disk_info = disk_info
9878

    
9879
    else:
9880
      raise errors.ProgrammerError("Unhandled export mode %r" %
9881
                                   self.op.mode)
9882

    
9883
    # instance disk type verification
9884
    # TODO: Implement export support for file-based disks
9885
    for disk in self.instance.disks:
9886
      if disk.dev_type == constants.LD_FILE:
9887
        raise errors.OpPrereqError("Export not supported for instances with"
9888
                                   " file-based disks", errors.ECODE_INVAL)
9889

    
9890
  def _CleanupExports(self, feedback_fn):
9891
    """Removes exports of current instance from all other nodes.
9892

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

9896
    """
9897
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9898

    
9899
    nodelist = self.cfg.GetNodeList()
9900
    nodelist.remove(self.dst_node.name)
9901

    
9902
    # on one-node clusters nodelist will be empty after the removal
9903
    # if we proceed the backup would be removed because OpQueryExports
9904
    # substitutes an empty list with the full cluster node list.
9905
    iname = self.instance.name
9906
    if nodelist:
9907
      feedback_fn("Removing old exports for instance %s" % iname)
9908
      exportlist = self.rpc.call_export_list(nodelist)
9909
      for node in exportlist:
9910
        if exportlist[node].fail_msg:
9911
          continue
9912
        if iname in exportlist[node].payload:
9913
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9914
          if msg:
9915
            self.LogWarning("Could not remove older export for instance %s"
9916
                            " on node %s: %s", iname, node, msg)
9917

    
9918
  def Exec(self, feedback_fn):
9919
    """Export an instance to an image in the cluster.
9920

9921
    """
9922
    assert self.op.mode in constants.EXPORT_MODES
9923

    
9924
    instance = self.instance
9925
    src_node = instance.primary_node
9926

    
9927
    if self.op.shutdown:
9928
      # shutdown the instance, but not the disks
9929
      feedback_fn("Shutting down instance %s" % instance.name)
9930
      result = self.rpc.call_instance_shutdown(src_node, instance,
9931
                                               self.op.shutdown_timeout)
9932
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9933
      result.Raise("Could not shutdown instance %s on"
9934
                   " node %s" % (instance.name, src_node))
9935

    
9936
    # set the disks ID correctly since call_instance_start needs the
9937
    # correct drbd minor to create the symlinks
9938
    for disk in instance.disks:
9939
      self.cfg.SetDiskID(disk, src_node)
9940

    
9941
    activate_disks = (not instance.admin_up)
9942

    
9943
    if activate_disks:
9944
      # Activate the instance disks if we'exporting a stopped instance
9945
      feedback_fn("Activating disks for %s" % instance.name)
9946
      _StartInstanceDisks(self, instance, None)
9947

    
9948
    try:
9949
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9950
                                                     instance)
9951

    
9952
      helper.CreateSnapshots()
9953
      try:
9954
        if (self.op.shutdown and instance.admin_up and
9955
            not self.op.remove_instance):
9956
          assert not activate_disks
9957
          feedback_fn("Starting instance %s" % instance.name)
9958
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9959
          msg = result.fail_msg
9960
          if msg:
9961
            feedback_fn("Failed to start instance: %s" % msg)
9962
            _ShutdownInstanceDisks(self, instance)
9963
            raise errors.OpExecError("Could not start instance: %s" % msg)
9964

    
9965
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9966
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9967
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9968
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9969
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9970

    
9971
          (key_name, _, _) = self.x509_key_name
9972

    
9973
          dest_ca_pem = \
9974
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9975
                                            self.dest_x509_ca)
9976

    
9977
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9978
                                                     key_name, dest_ca_pem,
9979
                                                     timeouts)
9980
      finally:
9981
        helper.Cleanup()
9982

    
9983
      # Check for backwards compatibility
9984
      assert len(dresults) == len(instance.disks)
9985
      assert compat.all(isinstance(i, bool) for i in dresults), \
9986
             "Not all results are boolean: %r" % dresults
9987

    
9988
    finally:
9989
      if activate_disks:
9990
        feedback_fn("Deactivating disks for %s" % instance.name)
9991
        _ShutdownInstanceDisks(self, instance)
9992

    
9993
    if not (compat.all(dresults) and fin_resu):
9994
      failures = []
9995
      if not fin_resu:
9996
        failures.append("export finalization")
9997
      if not compat.all(dresults):
9998
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
9999
                               if not dsk)
10000
        failures.append("disk export: disk(s) %s" % fdsk)
10001

    
10002
      raise errors.OpExecError("Export failed, errors in %s" %
10003
                               utils.CommaJoin(failures))
10004

    
10005
    # At this point, the export was successful, we can cleanup/finish
10006

    
10007
    # Remove instance if requested
10008
    if self.op.remove_instance:
10009
      feedback_fn("Removing instance %s" % instance.name)
10010
      _RemoveInstance(self, feedback_fn, instance,
10011
                      self.op.ignore_remove_failures)
10012

    
10013
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10014
      self._CleanupExports(feedback_fn)
10015

    
10016
    return fin_resu, dresults
10017

    
10018

    
10019
class LURemoveExport(NoHooksLU):
10020
  """Remove exports related to the named instance.
10021

10022
  """
10023
  _OP_PARAMS = [
10024
    _PInstanceName,
10025
    ]
10026
  REQ_BGL = False
10027

    
10028
  def ExpandNames(self):
10029
    self.needed_locks = {}
10030
    # We need all nodes to be locked in order for RemoveExport to work, but we
10031
    # don't need to lock the instance itself, as nothing will happen to it (and
10032
    # we can remove exports also for a removed instance)
10033
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10034

    
10035
  def Exec(self, feedback_fn):
10036
    """Remove any export.
10037

10038
    """
10039
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
10040
    # If the instance was not found we'll try with the name that was passed in.
10041
    # This will only work if it was an FQDN, though.
10042
    fqdn_warn = False
10043
    if not instance_name:
10044
      fqdn_warn = True
10045
      instance_name = self.op.instance_name
10046

    
10047
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
10048
    exportlist = self.rpc.call_export_list(locked_nodes)
10049
    found = False
10050
    for node in exportlist:
10051
      msg = exportlist[node].fail_msg
10052
      if msg:
10053
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
10054
        continue
10055
      if instance_name in exportlist[node].payload:
10056
        found = True
10057
        result = self.rpc.call_export_remove(node, instance_name)
10058
        msg = result.fail_msg
10059
        if msg:
10060
          logging.error("Could not remove export for instance %s"
10061
                        " on node %s: %s", instance_name, node, msg)
10062

    
10063
    if fqdn_warn and not found:
10064
      feedback_fn("Export not found. If trying to remove an export belonging"
10065
                  " to a deleted instance please use its Fully Qualified"
10066
                  " Domain Name.")
10067

    
10068

    
10069
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
10070
  """Generic tags LU.
10071

10072
  This is an abstract class which is the parent of all the other tags LUs.
10073

10074
  """
10075

    
10076
  def ExpandNames(self):
10077
    self.needed_locks = {}
10078
    if self.op.kind == constants.TAG_NODE:
10079
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
10080
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
10081
    elif self.op.kind == constants.TAG_INSTANCE:
10082
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
10083
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
10084

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

    
10088
  def CheckPrereq(self):
10089
    """Check prerequisites.
10090

10091
    """
10092
    if self.op.kind == constants.TAG_CLUSTER:
10093
      self.target = self.cfg.GetClusterInfo()
10094
    elif self.op.kind == constants.TAG_NODE:
10095
      self.target = self.cfg.GetNodeInfo(self.op.name)
10096
    elif self.op.kind == constants.TAG_INSTANCE:
10097
      self.target = self.cfg.GetInstanceInfo(self.op.name)
10098
    else:
10099
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
10100
                                 str(self.op.kind), errors.ECODE_INVAL)
10101

    
10102

    
10103
class LUGetTags(TagsLU):
10104
  """Returns the tags of a given object.
10105

10106
  """
10107
  _OP_PARAMS = [
10108
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
10109
    # Name is only meaningful for nodes and instances
10110
    ("name", ht.NoDefault, ht.TMaybeString),
10111
    ]
10112
  REQ_BGL = False
10113

    
10114
  def ExpandNames(self):
10115
    TagsLU.ExpandNames(self)
10116

    
10117
    # Share locks as this is only a read operation
10118
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
10119

    
10120
  def Exec(self, feedback_fn):
10121
    """Returns the tag list.
10122

10123
    """
10124
    return list(self.target.GetTags())
10125

    
10126

    
10127
class LUSearchTags(NoHooksLU):
10128
  """Searches the tags for a given pattern.
10129

10130
  """
10131
  _OP_PARAMS = [
10132
    ("pattern", ht.NoDefault, ht.TNonEmptyString),
10133
    ]
10134
  REQ_BGL = False
10135

    
10136
  def ExpandNames(self):
10137
    self.needed_locks = {}
10138

    
10139
  def CheckPrereq(self):
10140
    """Check prerequisites.
10141

10142
    This checks the pattern passed for validity by compiling it.
10143

10144
    """
10145
    try:
10146
      self.re = re.compile(self.op.pattern)
10147
    except re.error, err:
10148
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
10149
                                 (self.op.pattern, err), errors.ECODE_INVAL)
10150

    
10151
  def Exec(self, feedback_fn):
10152
    """Returns the tag list.
10153

10154
    """
10155
    cfg = self.cfg
10156
    tgts = [("/cluster", cfg.GetClusterInfo())]
10157
    ilist = cfg.GetAllInstancesInfo().values()
10158
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
10159
    nlist = cfg.GetAllNodesInfo().values()
10160
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
10161
    results = []
10162
    for path, target in tgts:
10163
      for tag in target.GetTags():
10164
        if self.re.search(tag):
10165
          results.append((path, tag))
10166
    return results
10167

    
10168

    
10169
class LUAddTags(TagsLU):
10170
  """Sets a tag on a given object.
10171

10172
  """
10173
  _OP_PARAMS = [
10174
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
10175
    # Name is only meaningful for nodes and instances
10176
    ("name", ht.NoDefault, ht.TMaybeString),
10177
    ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
10178
    ]
10179
  REQ_BGL = False
10180

    
10181
  def CheckPrereq(self):
10182
    """Check prerequisites.
10183

10184
    This checks the type and length of the tag name and value.
10185

10186
    """
10187
    TagsLU.CheckPrereq(self)
10188
    for tag in self.op.tags:
10189
      objects.TaggableObject.ValidateTag(tag)
10190

    
10191
  def Exec(self, feedback_fn):
10192
    """Sets the tag.
10193

10194
    """
10195
    try:
10196
      for tag in self.op.tags:
10197
        self.target.AddTag(tag)
10198
    except errors.TagError, err:
10199
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
10200
    self.cfg.Update(self.target, feedback_fn)
10201

    
10202

    
10203
class LUDelTags(TagsLU):
10204
  """Delete a list of tags from a given object.
10205

10206
  """
10207
  _OP_PARAMS = [
10208
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
10209
    # Name is only meaningful for nodes and instances
10210
    ("name", ht.NoDefault, ht.TMaybeString),
10211
    ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
10212
    ]
10213
  REQ_BGL = False
10214

    
10215
  def CheckPrereq(self):
10216
    """Check prerequisites.
10217

10218
    This checks that we have the given tag.
10219

10220
    """
10221
    TagsLU.CheckPrereq(self)
10222
    for tag in self.op.tags:
10223
      objects.TaggableObject.ValidateTag(tag)
10224
    del_tags = frozenset(self.op.tags)
10225
    cur_tags = self.target.GetTags()
10226

    
10227
    diff_tags = del_tags - cur_tags
10228
    if diff_tags:
10229
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
10230
      raise errors.OpPrereqError("Tag(s) %s not found" %
10231
                                 (utils.CommaJoin(diff_names), ),
10232
                                 errors.ECODE_NOENT)
10233

    
10234
  def Exec(self, feedback_fn):
10235
    """Remove the tag from the object.
10236

10237
    """
10238
    for tag in self.op.tags:
10239
      self.target.RemoveTag(tag)
10240
    self.cfg.Update(self.target, feedback_fn)
10241

    
10242

    
10243
class LUTestDelay(NoHooksLU):
10244
  """Sleep for a specified amount of time.
10245

10246
  This LU sleeps on the master and/or nodes for a specified amount of
10247
  time.
10248

10249
  """
10250
  _OP_PARAMS = [
10251
    ("duration", ht.NoDefault, ht.TFloat),
10252
    ("on_master", True, ht.TBool),
10253
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
10254
    ("repeat", 0, ht.TPositiveInt)
10255
    ]
10256
  REQ_BGL = False
10257

    
10258
  def ExpandNames(self):
10259
    """Expand names and set required locks.
10260

10261
    This expands the node list, if any.
10262

10263
    """
10264
    self.needed_locks = {}
10265
    if self.op.on_nodes:
10266
      # _GetWantedNodes can be used here, but is not always appropriate to use
10267
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
10268
      # more information.
10269
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
10270
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
10271

    
10272
  def _TestDelay(self):
10273
    """Do the actual sleep.
10274

10275
    """
10276
    if self.op.on_master:
10277
      if not utils.TestDelay(self.op.duration):
10278
        raise errors.OpExecError("Error during master delay test")
10279
    if self.op.on_nodes:
10280
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
10281
      for node, node_result in result.items():
10282
        node_result.Raise("Failure during rpc call to node %s" % node)
10283

    
10284
  def Exec(self, feedback_fn):
10285
    """Execute the test delay opcode, with the wanted repetitions.
10286

10287
    """
10288
    if self.op.repeat == 0:
10289
      self._TestDelay()
10290
    else:
10291
      top_value = self.op.repeat - 1
10292
      for i in range(self.op.repeat):
10293
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
10294
        self._TestDelay()
10295

    
10296

    
10297
class LUTestJobqueue(NoHooksLU):
10298
  """Utility LU to test some aspects of the job queue.
10299

10300
  """
10301
  _OP_PARAMS = [
10302
    ("notify_waitlock", False, ht.TBool),
10303
    ("notify_exec", False, ht.TBool),
10304
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString)),
10305
    ("fail", False, ht.TBool),
10306
    ]
10307
  REQ_BGL = False
10308

    
10309
  # Must be lower than default timeout for WaitForJobChange to see whether it
10310
  # notices changed jobs
10311
  _CLIENT_CONNECT_TIMEOUT = 20.0
10312
  _CLIENT_CONFIRM_TIMEOUT = 60.0
10313

    
10314
  @classmethod
10315
  def _NotifyUsingSocket(cls, cb, errcls):
10316
    """Opens a Unix socket and waits for another program to connect.
10317

10318
    @type cb: callable
10319
    @param cb: Callback to send socket name to client
10320
    @type errcls: class
10321
    @param errcls: Exception class to use for errors
10322

10323
    """
10324
    # Using a temporary directory as there's no easy way to create temporary
10325
    # sockets without writing a custom loop around tempfile.mktemp and
10326
    # socket.bind
10327
    tmpdir = tempfile.mkdtemp()
10328
    try:
10329
      tmpsock = utils.PathJoin(tmpdir, "sock")
10330

    
10331
      logging.debug("Creating temporary socket at %s", tmpsock)
10332
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
10333
      try:
10334
        sock.bind(tmpsock)
10335
        sock.listen(1)
10336

    
10337
        # Send details to client
10338
        cb(tmpsock)
10339

    
10340
        # Wait for client to connect before continuing
10341
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
10342
        try:
10343
          (conn, _) = sock.accept()
10344
        except socket.error, err:
10345
          raise errcls("Client didn't connect in time (%s)" % err)
10346
      finally:
10347
        sock.close()
10348
    finally:
10349
      # Remove as soon as client is connected
10350
      shutil.rmtree(tmpdir)
10351

    
10352
    # Wait for client to close
10353
    try:
10354
      try:
10355
        # pylint: disable-msg=E1101
10356
        # Instance of '_socketobject' has no ... member
10357
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
10358
        conn.recv(1)
10359
      except socket.error, err:
10360
        raise errcls("Client failed to confirm notification (%s)" % err)
10361
    finally:
10362
      conn.close()
10363

    
10364
  def _SendNotification(self, test, arg, sockname):
10365
    """Sends a notification to the client.
10366

10367
    @type test: string
10368
    @param test: Test name
10369
    @param arg: Test argument (depends on test)
10370
    @type sockname: string
10371
    @param sockname: Socket path
10372

10373
    """
10374
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
10375

    
10376
  def _Notify(self, prereq, test, arg):
10377
    """Notifies the client of a test.
10378

10379
    @type prereq: bool
10380
    @param prereq: Whether this is a prereq-phase test
10381
    @type test: string
10382
    @param test: Test name
10383
    @param arg: Test argument (depends on test)
10384

10385
    """
10386
    if prereq:
10387
      errcls = errors.OpPrereqError
10388
    else:
10389
      errcls = errors.OpExecError
10390

    
10391
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
10392
                                                  test, arg),
10393
                                   errcls)
10394

    
10395
  def CheckArguments(self):
10396
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
10397
    self.expandnames_calls = 0
10398

    
10399
  def ExpandNames(self):
10400
    checkargs_calls = getattr(self, "checkargs_calls", 0)
10401
    if checkargs_calls < 1:
10402
      raise errors.ProgrammerError("CheckArguments was not called")
10403

    
10404
    self.expandnames_calls += 1
10405

    
10406
    if self.op.notify_waitlock:
10407
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
10408

    
10409
    self.LogInfo("Expanding names")
10410

    
10411
    # Get lock on master node (just to get a lock, not for a particular reason)
10412
    self.needed_locks = {
10413
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
10414
      }
10415

    
10416
  def Exec(self, feedback_fn):
10417
    if self.expandnames_calls < 1:
10418
      raise errors.ProgrammerError("ExpandNames was not called")
10419

    
10420
    if self.op.notify_exec:
10421
      self._Notify(False, constants.JQT_EXEC, None)
10422

    
10423
    self.LogInfo("Executing")
10424

    
10425
    if self.op.log_messages:
10426
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
10427
      for idx, msg in enumerate(self.op.log_messages):
10428
        self.LogInfo("Sending log message %s", idx + 1)
10429
        feedback_fn(constants.JQT_MSGPREFIX + msg)
10430
        # Report how many test messages have been sent
10431
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
10432

    
10433
    if self.op.fail:
10434
      raise errors.OpExecError("Opcode failure was requested")
10435

    
10436
    return True
10437

    
10438

    
10439
class IAllocator(object):
10440
  """IAllocator framework.
10441

10442
  An IAllocator instance has three sets of attributes:
10443
    - cfg that is needed to query the cluster
10444
    - input data (all members of the _KEYS class attribute are required)
10445
    - four buffer attributes (in|out_data|text), that represent the
10446
      input (to the external script) in text and data structure format,
10447
      and the output from it, again in two formats
10448
    - the result variables from the script (success, info, nodes) for
10449
      easy usage
10450

10451
  """
10452
  # pylint: disable-msg=R0902
10453
  # lots of instance attributes
10454
  _ALLO_KEYS = [
10455
    "name", "mem_size", "disks", "disk_template",
10456
    "os", "tags", "nics", "vcpus", "hypervisor",
10457
    ]
10458
  _RELO_KEYS = [
10459
    "name", "relocate_from",
10460
    ]
10461
  _EVAC_KEYS = [
10462
    "evac_nodes",
10463
    ]
10464

    
10465
  def __init__(self, cfg, rpc, mode, **kwargs):
10466
    self.cfg = cfg
10467
    self.rpc = rpc
10468
    # init buffer variables
10469
    self.in_text = self.out_text = self.in_data = self.out_data = None
10470
    # init all input fields so that pylint is happy
10471
    self.mode = mode
10472
    self.mem_size = self.disks = self.disk_template = None
10473
    self.os = self.tags = self.nics = self.vcpus = None
10474
    self.hypervisor = None
10475
    self.relocate_from = None
10476
    self.name = None
10477
    self.evac_nodes = None
10478
    # computed fields
10479
    self.required_nodes = None
10480
    # init result fields
10481
    self.success = self.info = self.result = None
10482
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10483
      keyset = self._ALLO_KEYS
10484
      fn = self._AddNewInstance
10485
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10486
      keyset = self._RELO_KEYS
10487
      fn = self._AddRelocateInstance
10488
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10489
      keyset = self._EVAC_KEYS
10490
      fn = self._AddEvacuateNodes
10491
    else:
10492
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
10493
                                   " IAllocator" % self.mode)
10494
    for key in kwargs:
10495
      if key not in keyset:
10496
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
10497
                                     " IAllocator" % key)
10498
      setattr(self, key, kwargs[key])
10499

    
10500
    for key in keyset:
10501
      if key not in kwargs:
10502
        raise errors.ProgrammerError("Missing input parameter '%s' to"
10503
                                     " IAllocator" % key)
10504
    self._BuildInputData(fn)
10505

    
10506
  def _ComputeClusterData(self):
10507
    """Compute the generic allocator input data.
10508

10509
    This is the data that is independent of the actual operation.
10510

10511
    """
10512
    cfg = self.cfg
10513
    cluster_info = cfg.GetClusterInfo()
10514
    # cluster data
10515
    data = {
10516
      "version": constants.IALLOCATOR_VERSION,
10517
      "cluster_name": cfg.GetClusterName(),
10518
      "cluster_tags": list(cluster_info.GetTags()),
10519
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
10520
      # we don't have job IDs
10521
      }
10522
    iinfo = cfg.GetAllInstancesInfo().values()
10523
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
10524

    
10525
    # node data
10526
    node_list = cfg.GetNodeList()
10527

    
10528
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10529
      hypervisor_name = self.hypervisor
10530
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10531
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
10532
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10533
      hypervisor_name = cluster_info.enabled_hypervisors[0]
10534

    
10535
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
10536
                                        hypervisor_name)
10537
    node_iinfo = \
10538
      self.rpc.call_all_instances_info(node_list,
10539
                                       cluster_info.enabled_hypervisors)
10540

    
10541
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
10542

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

    
10545
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
10546

    
10547
    self.in_data = data
10548

    
10549
  @staticmethod
10550
  def _ComputeNodeGroupData(cfg):
10551
    """Compute node groups data.
10552

10553
    """
10554
    ng = {}
10555
    for guuid, gdata in cfg.GetAllNodeGroupsInfo().items():
10556
      ng[guuid] = { "name": gdata.name }
10557
    return ng
10558

    
10559
  @staticmethod
10560
  def _ComputeNodeData(cfg, node_data, node_iinfo, i_list):
10561
    """Compute global node data.
10562

10563
    """
10564
    node_results = {}
10565
    for nname, nresult in node_data.items():
10566
      # first fill in static (config-based) values
10567
      ninfo = cfg.GetNodeInfo(nname)
10568
      pnr = {
10569
        "tags": list(ninfo.GetTags()),
10570
        "primary_ip": ninfo.primary_ip,
10571
        "secondary_ip": ninfo.secondary_ip,
10572
        "offline": ninfo.offline,
10573
        "drained": ninfo.drained,
10574
        "master_candidate": ninfo.master_candidate,
10575
        "group": ninfo.group,
10576
        "master_capable": ninfo.master_capable,
10577
        "vm_capable": ninfo.vm_capable,
10578
        }
10579

    
10580
      if not (ninfo.offline or ninfo.drained):
10581
        nresult.Raise("Can't get data for node %s" % nname)
10582
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
10583
                                nname)
10584
        remote_info = nresult.payload
10585

    
10586
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
10587
                     'vg_size', 'vg_free', 'cpu_total']:
10588
          if attr not in remote_info:
10589
            raise errors.OpExecError("Node '%s' didn't return attribute"
10590
                                     " '%s'" % (nname, attr))
10591
          if not isinstance(remote_info[attr], int):
10592
            raise errors.OpExecError("Node '%s' returned invalid value"
10593
                                     " for '%s': %s" %
10594
                                     (nname, attr, remote_info[attr]))
10595
        # compute memory used by primary instances
10596
        i_p_mem = i_p_up_mem = 0
10597
        for iinfo, beinfo in i_list:
10598
          if iinfo.primary_node == nname:
10599
            i_p_mem += beinfo[constants.BE_MEMORY]
10600
            if iinfo.name not in node_iinfo[nname].payload:
10601
              i_used_mem = 0
10602
            else:
10603
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
10604
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
10605
            remote_info['memory_free'] -= max(0, i_mem_diff)
10606

    
10607
            if iinfo.admin_up:
10608
              i_p_up_mem += beinfo[constants.BE_MEMORY]
10609

    
10610
        # compute memory used by instances
10611
        pnr_dyn = {
10612
          "total_memory": remote_info['memory_total'],
10613
          "reserved_memory": remote_info['memory_dom0'],
10614
          "free_memory": remote_info['memory_free'],
10615
          "total_disk": remote_info['vg_size'],
10616
          "free_disk": remote_info['vg_free'],
10617
          "total_cpus": remote_info['cpu_total'],
10618
          "i_pri_memory": i_p_mem,
10619
          "i_pri_up_memory": i_p_up_mem,
10620
          }
10621
        pnr.update(pnr_dyn)
10622

    
10623
      node_results[nname] = pnr
10624

    
10625
    return node_results
10626

    
10627
  @staticmethod
10628
  def _ComputeInstanceData(cluster_info, i_list):
10629
    """Compute global instance data.
10630

10631
    """
10632
    instance_data = {}
10633
    for iinfo, beinfo in i_list:
10634
      nic_data = []
10635
      for nic in iinfo.nics:
10636
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
10637
        nic_dict = {"mac": nic.mac,
10638
                    "ip": nic.ip,
10639
                    "mode": filled_params[constants.NIC_MODE],
10640
                    "link": filled_params[constants.NIC_LINK],
10641
                   }
10642
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
10643
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
10644
        nic_data.append(nic_dict)
10645
      pir = {
10646
        "tags": list(iinfo.GetTags()),
10647
        "admin_up": iinfo.admin_up,
10648
        "vcpus": beinfo[constants.BE_VCPUS],
10649
        "memory": beinfo[constants.BE_MEMORY],
10650
        "os": iinfo.os,
10651
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
10652
        "nics": nic_data,
10653
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
10654
        "disk_template": iinfo.disk_template,
10655
        "hypervisor": iinfo.hypervisor,
10656
        }
10657
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
10658
                                                 pir["disks"])
10659
      instance_data[iinfo.name] = pir
10660

    
10661
    return instance_data
10662

    
10663
  def _AddNewInstance(self):
10664
    """Add new instance data to allocator structure.
10665

10666
    This in combination with _AllocatorGetClusterData will create the
10667
    correct structure needed as input for the allocator.
10668

10669
    The checks for the completeness of the opcode must have already been
10670
    done.
10671

10672
    """
10673
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
10674

    
10675
    if self.disk_template in constants.DTS_NET_MIRROR:
10676
      self.required_nodes = 2
10677
    else:
10678
      self.required_nodes = 1
10679
    request = {
10680
      "name": self.name,
10681
      "disk_template": self.disk_template,
10682
      "tags": self.tags,
10683
      "os": self.os,
10684
      "vcpus": self.vcpus,
10685
      "memory": self.mem_size,
10686
      "disks": self.disks,
10687
      "disk_space_total": disk_space,
10688
      "nics": self.nics,
10689
      "required_nodes": self.required_nodes,
10690
      }
10691
    return request
10692

    
10693
  def _AddRelocateInstance(self):
10694
    """Add relocate instance data to allocator structure.
10695

10696
    This in combination with _IAllocatorGetClusterData will create the
10697
    correct structure needed as input for the allocator.
10698

10699
    The checks for the completeness of the opcode must have already been
10700
    done.
10701

10702
    """
10703
    instance = self.cfg.GetInstanceInfo(self.name)
10704
    if instance is None:
10705
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
10706
                                   " IAllocator" % self.name)
10707

    
10708
    if instance.disk_template not in constants.DTS_NET_MIRROR:
10709
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
10710
                                 errors.ECODE_INVAL)
10711

    
10712
    if len(instance.secondary_nodes) != 1:
10713
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
10714
                                 errors.ECODE_STATE)
10715

    
10716
    self.required_nodes = 1
10717
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
10718
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
10719

    
10720
    request = {
10721
      "name": self.name,
10722
      "disk_space_total": disk_space,
10723
      "required_nodes": self.required_nodes,
10724
      "relocate_from": self.relocate_from,
10725
      }
10726
    return request
10727

    
10728
  def _AddEvacuateNodes(self):
10729
    """Add evacuate nodes data to allocator structure.
10730

10731
    """
10732
    request = {
10733
      "evac_nodes": self.evac_nodes
10734
      }
10735
    return request
10736

    
10737
  def _BuildInputData(self, fn):
10738
    """Build input data structures.
10739

10740
    """
10741
    self._ComputeClusterData()
10742

    
10743
    request = fn()
10744
    request["type"] = self.mode
10745
    self.in_data["request"] = request
10746

    
10747
    self.in_text = serializer.Dump(self.in_data)
10748

    
10749
  def Run(self, name, validate=True, call_fn=None):
10750
    """Run an instance allocator and return the results.
10751

10752
    """
10753
    if call_fn is None:
10754
      call_fn = self.rpc.call_iallocator_runner
10755

    
10756
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
10757
    result.Raise("Failure while running the iallocator script")
10758

    
10759
    self.out_text = result.payload
10760
    if validate:
10761
      self._ValidateResult()
10762

    
10763
  def _ValidateResult(self):
10764
    """Process the allocator results.
10765

10766
    This will process and if successful save the result in
10767
    self.out_data and the other parameters.
10768

10769
    """
10770
    try:
10771
      rdict = serializer.Load(self.out_text)
10772
    except Exception, err:
10773
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
10774

    
10775
    if not isinstance(rdict, dict):
10776
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
10777

    
10778
    # TODO: remove backwards compatiblity in later versions
10779
    if "nodes" in rdict and "result" not in rdict:
10780
      rdict["result"] = rdict["nodes"]
10781
      del rdict["nodes"]
10782

    
10783
    for key in "success", "info", "result":
10784
      if key not in rdict:
10785
        raise errors.OpExecError("Can't parse iallocator results:"
10786
                                 " missing key '%s'" % key)
10787
      setattr(self, key, rdict[key])
10788

    
10789
    if not isinstance(rdict["result"], list):
10790
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
10791
                               " is not a list")
10792
    self.out_data = rdict
10793

    
10794

    
10795
class LUTestAllocator(NoHooksLU):
10796
  """Run allocator tests.
10797

10798
  This LU runs the allocator tests
10799

10800
  """
10801
  _OP_PARAMS = [
10802
    ("direction", ht.NoDefault,
10803
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS)),
10804
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES)),
10805
    ("name", ht.NoDefault, ht.TNonEmptyString),
10806
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
10807
      ht.TDictOf(ht.TElemOf(["mac", "ip", "bridge"]),
10808
               ht.TOr(ht.TNone, ht.TNonEmptyString))))),
10809
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList)),
10810
    ("hypervisor", None, ht.TMaybeString),
10811
    ("allocator", None, ht.TMaybeString),
10812
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
10813
    ("mem_size", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
10814
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
10815
    ("os", None, ht.TMaybeString),
10816
    ("disk_template", None, ht.TMaybeString),
10817
    ("evac_nodes", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString))),
10818
    ]
10819

    
10820
  def CheckPrereq(self):
10821
    """Check prerequisites.
10822

10823
    This checks the opcode parameters depending on the director and mode test.
10824

10825
    """
10826
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10827
      for attr in ["mem_size", "disks", "disk_template",
10828
                   "os", "tags", "nics", "vcpus"]:
10829
        if not hasattr(self.op, attr):
10830
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
10831
                                     attr, errors.ECODE_INVAL)
10832
      iname = self.cfg.ExpandInstanceName(self.op.name)
10833
      if iname is not None:
10834
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
10835
                                   iname, errors.ECODE_EXISTS)
10836
      if not isinstance(self.op.nics, list):
10837
        raise errors.OpPrereqError("Invalid parameter 'nics'",
10838
                                   errors.ECODE_INVAL)
10839
      if not isinstance(self.op.disks, list):
10840
        raise errors.OpPrereqError("Invalid parameter 'disks'",
10841
                                   errors.ECODE_INVAL)
10842
      for row in self.op.disks:
10843
        if (not isinstance(row, dict) or
10844
            "size" not in row or
10845
            not isinstance(row["size"], int) or
10846
            "mode" not in row or
10847
            row["mode"] not in ['r', 'w']):
10848
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
10849
                                     " parameter", errors.ECODE_INVAL)
10850
      if self.op.hypervisor is None:
10851
        self.op.hypervisor = self.cfg.GetHypervisorType()
10852
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10853
      fname = _ExpandInstanceName(self.cfg, self.op.name)
10854
      self.op.name = fname
10855
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
10856
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10857
      if not hasattr(self.op, "evac_nodes"):
10858
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
10859
                                   " opcode input", errors.ECODE_INVAL)
10860
    else:
10861
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
10862
                                 self.op.mode, errors.ECODE_INVAL)
10863

    
10864
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
10865
      if self.op.allocator is None:
10866
        raise errors.OpPrereqError("Missing allocator name",
10867
                                   errors.ECODE_INVAL)
10868
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
10869
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
10870
                                 self.op.direction, errors.ECODE_INVAL)
10871

    
10872
  def Exec(self, feedback_fn):
10873
    """Run the allocator test.
10874

10875
    """
10876
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10877
      ial = IAllocator(self.cfg, self.rpc,
10878
                       mode=self.op.mode,
10879
                       name=self.op.name,
10880
                       mem_size=self.op.mem_size,
10881
                       disks=self.op.disks,
10882
                       disk_template=self.op.disk_template,
10883
                       os=self.op.os,
10884
                       tags=self.op.tags,
10885
                       nics=self.op.nics,
10886
                       vcpus=self.op.vcpus,
10887
                       hypervisor=self.op.hypervisor,
10888
                       )
10889
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10890
      ial = IAllocator(self.cfg, self.rpc,
10891
                       mode=self.op.mode,
10892
                       name=self.op.name,
10893
                       relocate_from=list(self.relocate_from),
10894
                       )
10895
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10896
      ial = IAllocator(self.cfg, self.rpc,
10897
                       mode=self.op.mode,
10898
                       evac_nodes=self.op.evac_nodes)
10899
    else:
10900
      raise errors.ProgrammerError("Uncatched mode %s in"
10901
                                   " LUTestAllocator.Exec", self.op.mode)
10902

    
10903
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
10904
      result = ial.in_text
10905
    else:
10906
      ial.Run(self.op.allocator, validate=False)
10907
      result = ial.out_text
10908
    return result