Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ c6a9dffa

History | View | Annotate | Download (383.7 kB)

1
#
2
#
3

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

    
21

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

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

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

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

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

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

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

    
60
# Common opcode attributes
61

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

    
65

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

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

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

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

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

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

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

    
89

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

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

103
  Note that all commands require root permissions.
104

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

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

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

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

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

    
149
    # Tasklets
150
    self.tasklets = None
151

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

    
179
    self.CheckArguments()
180

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

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

    
189
  ssh = property(fget=__GetSSH)
190

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

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

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

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

206
    """
207
    pass
208

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

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

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

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

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

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

234
    Examples::
235

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

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

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

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

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

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

273
    """
274

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

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

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

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

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

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

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

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

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

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

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

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

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

332
    """
333
    raise NotImplementedError
334

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
421
    del self.recalculate_locks[locking.LEVEL_NODE]
422

    
423

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

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

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

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

437
    This just raises an error.
438

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

    
442

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

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

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

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

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

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

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

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

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

475
    """
476
    pass
477

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

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

485
    """
486
    raise NotImplementedError
487

    
488

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

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

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

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

    
508

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

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

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

    
528

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

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

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

    
561

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

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

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

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

    
580

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

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

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

    
595

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

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

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

    
608

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

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

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

    
621

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

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

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

    
634

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

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

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

    
652

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

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

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

    
679

    
680
def _RequireFileStorage():
681
  """Checks that file storage is enabled.
682

683
  @raise errors.OpPrereqError: when file storage is disabled
684

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

    
690

    
691
def _CheckDiskTemplate(template):
692
  """Ensure a given disk template is valid.
693

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

    
703

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

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

    
715

    
716
def _GetClusterDomainSecret():
717
  """Reads the cluster domain secret.
718

719
  """
720
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
721
                               strict=True)
722

    
723

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

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

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

    
739

    
740
def _ExpandItemName(fn, name, kind):
741
  """Expand an item name.
742

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

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

    
756

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

    
761

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

    
766

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

772
  This builds the hook environment from individual variables.
773

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

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

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

    
836
  env["INSTANCE_NIC_COUNT"] = nic_count
837

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

    
846
  env["INSTANCE_DISK_COUNT"] = disk_count
847

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

    
852
  return env
853

    
854

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

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

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

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

    
878

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

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

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

    
916

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

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

    
932

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

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

    
943

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

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

    
957

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

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

    
966

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

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

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

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

    
986

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

    
990

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

994
  """
995

    
996
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
997

    
998

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

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

    
1006

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

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

    
1014

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

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

    
1024
  return []
1025

    
1026

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

    
1030
  for dev in instance.disks:
1031
    cfg.SetDiskID(dev, node_name)
1032

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

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

    
1041
  return faulty
1042

    
1043

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

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

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

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

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

    
1075

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

1079
  """
1080
  HPATH = "cluster-init"
1081
  HTYPE = constants.HTYPE_CLUSTER
1082

    
1083
  def BuildHooksEnv(self):
1084
    """Build hooks env.
1085

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

    
1091
  def Exec(self, feedback_fn):
1092
    """Nothing to do.
1093

1094
    """
1095
    return True
1096

    
1097

    
1098
class LUDestroyCluster(LogicalUnit):
1099
  """Logical unit for destroying the cluster.
1100

1101
  """
1102
  HPATH = "cluster-destroy"
1103
  HTYPE = constants.HTYPE_CLUSTER
1104

    
1105
  def BuildHooksEnv(self):
1106
    """Build hooks env.
1107

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

    
1112
  def CheckPrereq(self):
1113
    """Check prerequisites.
1114

1115
    This checks whether the cluster is empty.
1116

1117
    Any errors are signaled by raising errors.OpPrereqError.
1118

1119
    """
1120
    master = self.cfg.GetMasterNode()
1121

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

    
1133
  def Exec(self, feedback_fn):
1134
    """Destroys the cluster.
1135

1136
    """
1137
    master = self.cfg.GetMasterNode()
1138

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

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

    
1150
    return master
1151

    
1152

    
1153
def _VerifyCertificate(filename):
1154
  """Verifies a certificate for LUVerifyCluster.
1155

1156
  @type filename: string
1157
  @param filename: Path to PEM file
1158

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

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

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

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

    
1183
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1184

    
1185

    
1186
class LUVerifyCluster(LogicalUnit):
1187
  """Verifies the cluster status.
1188

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

    
1201
  TCLUSTER = "cluster"
1202
  TNODE = "node"
1203
  TINSTANCE = "instance"
1204

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

    
1230
  ETYPE_FIELD = "code"
1231
  ETYPE_ERROR = "ERROR"
1232
  ETYPE_WARNING = "WARNING"
1233

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

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

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

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

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

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

1297
    This must be called only from Exec and functions called from Exec.
1298

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

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

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

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

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

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

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

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

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

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

    
1371
    # node seems compatible, we can actually try to look into its results
1372

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

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

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

    
1392
    return True
1393

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

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

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

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

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

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

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

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

1434
    """
1435
    if vg_name is None:
1436
      return
1437

    
1438
    node = ninfo.name
1439
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1440

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

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

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

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

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

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

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

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

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

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

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

    
1516
    node_vol_should = {}
1517
    instanceconfig.MapLVsByNode(node_vol_should)
1518

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

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

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

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

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

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

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

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

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

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

1580
    This checks what instances are running but unknown to the cluster.
1581

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1743
    nimg.os_fail = test
1744

    
1745
    if test:
1746
      return
1747

    
1748
    os_dict = {}
1749

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

    
1753
      if name not in os_dict:
1754
        os_dict[name] = []
1755

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

    
1762
    nimg.oslist = os_dict
1763

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

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

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

    
1776
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1777

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1916
    """
1917
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1918

    
1919
    node_disks = {}
1920
    node_disks_devonly = {}
1921

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

    
1929
      if not disks:
1930
        # No need to collect data
1931
        continue
1932

    
1933
      node_disks[nname] = disks
1934

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

    
1939
      for dev in devonly:
1940
        self.cfg.SetDiskID(dev, nname)
1941

    
1942
      node_disks_devonly[nname] = devonly
1943

    
1944
    assert len(node_disks) == len(node_disks_devonly)
1945

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

    
1950
    assert len(result) == len(node_disks)
1951

    
1952
    instdisk = {}
1953

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

    
1959
      disks = node_disks[nname]
1960

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

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

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

    
1978
    return instdisk
1979

    
1980
  def BuildHooksEnv(self):
1981
    """Build hooks env.
1982

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

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

    
1994
    return env, [], all_nodes
1995

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

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

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

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

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

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

    
2040
    local_checksums = utils.FingerprintFiles(file_names)
2041

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

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

    
2067
    if drbd_helper:
2068
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2069

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

    
2076
    for instance in instancelist:
2077
      inst_config = instanceinfo[instance]
2078

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

    
2086
      inst_config.MapLVsByNode(node_vol_should)
2087

    
2088
      pnode = inst_config.primary_node
2089
      node_image[pnode].pinst.append(instance)
2090

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

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

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

    
2110
    all_drbd_map = self.cfg.ComputeDRBDMap()
2111

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

    
2115
    feedback_fn("* Verifying node status")
2116

    
2117
    refos_img = None
2118

    
2119
    for node_i in nodeinfo:
2120
      node = node_i.name
2121
      nimg = node_image[node]
2122

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

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

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

    
2147
      nresult = all_nvinfo[node].payload
2148

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

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

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

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

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

    
2184
      if pnode_img.offline:
2185
        inst_nodes_offline.append(pnode)
2186

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

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

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

    
2207
        if s_img.offline:
2208
          inst_nodes_offline.append(snode)
2209

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

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

    
2225
    feedback_fn("* Verifying orphan instances")
2226
    self._VerifyOrphanInstances(instancelist, node_image)
2227

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

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

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

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

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

    
2247
    return not self.bad
2248

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

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

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

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

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

    
2293
      return lu_result
2294

    
2295

    
2296
class LUVerifyDisks(NoHooksLU):
2297
  """Verifies the cluster disks status.
2298

2299
  """
2300
  REQ_BGL = False
2301

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

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

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

2317
    """
2318
    result = res_nodes, res_instances, res_missing = {}, [], {}
2319

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

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

    
2337
    if not nv_dict:
2338
      return result
2339

    
2340
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
2341

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

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

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

    
2367
    return result
2368

    
2369

    
2370
class LURepairDiskSizes(NoHooksLU):
2371
  """Verifies the cluster disks sizes.
2372

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

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

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

    
2400
  def CheckPrereq(self):
2401
    """Check prerequisites.
2402

2403
    This only checks the optional instance list against the existing names.
2404

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

    
2409
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2410
                             in self.wanted_names]
2411

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

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

2418
    @param disk: an L{ganeti.objects.Disk} object
2419

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

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

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

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

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

    
2485

    
2486
class LURenameCluster(LogicalUnit):
2487
  """Rename the cluster.
2488

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

    
2494
  def BuildHooksEnv(self):
2495
    """Build hooks env.
2496

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

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

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

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

    
2527
    self.op.name = new_name
2528

    
2529
  def Exec(self, feedback_fn):
2530
    """Rename the cluster.
2531

2532
    """
2533
    clustername = self.op.name
2534
    ip = self.ip
2535

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

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

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

    
2562
    return clustername
2563

    
2564

    
2565
class LUSetClusterParams(LogicalUnit):
2566
  """Change the parameters of the cluster.
2567

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2905

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

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

    
2919

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

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

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

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

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

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

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

    
2968

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

2972
  This is a very simple LU.
2973

2974
  """
2975
  REQ_BGL = False
2976

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

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

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

    
2990

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

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

    
2998
  disks = _ExpandCheckDisks(instance, disks)
2999

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

    
3003
  node = instance.primary_node
3004

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

    
3008
  # TODO: Convert to utils.Retry
3009

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

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

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

    
3056
    if done or oneshot:
3057
      break
3058

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

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

    
3065

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

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

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

    
3076
  result = True
3077

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

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

    
3097
  return result
3098

    
3099

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3235
    return output
3236

    
3237

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

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

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

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

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

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

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

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

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

    
3282
    instance_list = self.cfg.GetInstanceList()
3283

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

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

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

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

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

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

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

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

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

    
3336

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

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

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

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

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

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

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

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

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

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

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

    
3404
    nodenames = utils.NiceSort(nodenames)
3405
    nodelist = [all_info[name] for name in nodenames]
3406

    
3407
    # begin data gathering
3408

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

    
3434
    node_to_primary = dict([(name, set()) for name in nodenames])
3435
    node_to_secondary = dict([(name, set()) for name in nodenames])
3436

    
3437
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
3438
                             "sinst_cnt", "sinst_list"))
3439
    if inst_fields & frozenset(self.op.output_fields):
3440
      inst_data = self.cfg.GetAllInstancesInfo()
3441

    
3442
      for inst in inst_data.values():
3443
        if inst.primary_node in node_to_primary:
3444
          node_to_primary[inst.primary_node].add(inst.name)
3445
        for secnode in inst.secondary_nodes:
3446
          if secnode in node_to_secondary:
3447
            node_to_secondary[secnode].add(inst.name)
3448

    
3449
    master_node = self.cfg.GetMasterNode()
3450

    
3451
    # end data gathering
3452

    
3453
    output = []
3454
    for node in nodelist:
3455
      node_output = []
3456
      for field in self.op.output_fields:
3457
        if field in self._SIMPLE_FIELDS:
3458
          val = getattr(node, field)
3459
        elif field == "pinst_list":
3460
          val = list(node_to_primary[node.name])
3461
        elif field == "sinst_list":
3462
          val = list(node_to_secondary[node.name])
3463
        elif field == "pinst_cnt":
3464
          val = len(node_to_primary[node.name])
3465
        elif field == "sinst_cnt":
3466
          val = len(node_to_secondary[node.name])
3467
        elif field == "pip":
3468
          val = node.primary_ip
3469
        elif field == "sip":
3470
          val = node.secondary_ip
3471
        elif field == "tags":
3472
          val = list(node.GetTags())
3473
        elif field == "master":
3474
          val = node.name == master_node
3475
        elif self._FIELDS_DYNAMIC.Matches(field):
3476
          val = live_data[node.name].get(field, None)
3477
        elif field == "role":
3478
          if node.name == master_node:
3479
            val = "M"
3480
          elif node.master_candidate:
3481
            val = "C"
3482
          elif node.drained:
3483
            val = "D"
3484
          elif node.offline:
3485
            val = "O"
3486
          else:
3487
            val = "R"
3488
        else:
3489
          raise errors.ParameterError(field)
3490
        node_output.append(val)
3491
      output.append(node_output)
3492

    
3493
    return output
3494

    
3495

    
3496
class LUQueryNodeVolumes(NoHooksLU):
3497
  """Logical unit for getting volumes on node(s).
3498

3499
  """
3500
  _OP_PARAMS = [
3501
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3502
    ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
3503
    ]
3504
  REQ_BGL = False
3505
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3506
  _FIELDS_STATIC = utils.FieldSet("node")
3507

    
3508
  def CheckArguments(self):
3509
    _CheckOutputFields(static=self._FIELDS_STATIC,
3510
                       dynamic=self._FIELDS_DYNAMIC,
3511
                       selected=self.op.output_fields)
3512

    
3513
  def ExpandNames(self):
3514
    self.needed_locks = {}
3515
    self.share_locks[locking.LEVEL_NODE] = 1
3516
    if not self.op.nodes:
3517
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3518
    else:
3519
      self.needed_locks[locking.LEVEL_NODE] = \
3520
        _GetWantedNodes(self, self.op.nodes)
3521

    
3522
  def Exec(self, feedback_fn):
3523
    """Computes the list of nodes and their attributes.
3524

3525
    """
3526
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3527
    volumes = self.rpc.call_node_volumes(nodenames)
3528

    
3529
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3530
             in self.cfg.GetInstanceList()]
3531

    
3532
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3533

    
3534
    output = []
3535
    for node in nodenames:
3536
      nresult = volumes[node]
3537
      if nresult.offline:
3538
        continue
3539
      msg = nresult.fail_msg
3540
      if msg:
3541
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3542
        continue
3543

    
3544
      node_vols = nresult.payload[:]
3545
      node_vols.sort(key=lambda vol: vol['dev'])
3546

    
3547
      for vol in node_vols:
3548
        node_output = []
3549
        for field in self.op.output_fields:
3550
          if field == "node":
3551
            val = node
3552
          elif field == "phys":
3553
            val = vol['dev']
3554
          elif field == "vg":
3555
            val = vol['vg']
3556
          elif field == "name":
3557
            val = vol['name']
3558
          elif field == "size":
3559
            val = int(float(vol['size']))
3560
          elif field == "instance":
3561
            for inst in ilist:
3562
              if node not in lv_by_node[inst]:
3563
                continue
3564
              if vol['name'] in lv_by_node[inst][node]:
3565
                val = inst.name
3566
                break
3567
            else:
3568
              val = '-'
3569
          else:
3570
            raise errors.ParameterError(field)
3571
          node_output.append(str(val))
3572

    
3573
        output.append(node_output)
3574

    
3575
    return output
3576

    
3577

    
3578
class LUQueryNodeStorage(NoHooksLU):
3579
  """Logical unit for getting information on storage units on node(s).
3580

3581
  """
3582
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3583
  _OP_PARAMS = [
3584
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3585
    ("storage_type", ht.NoDefault, _CheckStorageType),
3586
    ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
3587
    ("name", None, ht.TMaybeString),
3588
    ]
3589
  REQ_BGL = False
3590

    
3591
  def CheckArguments(self):
3592
    _CheckOutputFields(static=self._FIELDS_STATIC,
3593
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3594
                       selected=self.op.output_fields)
3595

    
3596
  def ExpandNames(self):
3597
    self.needed_locks = {}
3598
    self.share_locks[locking.LEVEL_NODE] = 1
3599

    
3600
    if self.op.nodes:
3601
      self.needed_locks[locking.LEVEL_NODE] = \
3602
        _GetWantedNodes(self, self.op.nodes)
3603
    else:
3604
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3605

    
3606
  def Exec(self, feedback_fn):
3607
    """Computes the list of nodes and their attributes.
3608

3609
    """
3610
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3611

    
3612
    # Always get name to sort by
3613
    if constants.SF_NAME in self.op.output_fields:
3614
      fields = self.op.output_fields[:]
3615
    else:
3616
      fields = [constants.SF_NAME] + self.op.output_fields
3617

    
3618
    # Never ask for node or type as it's only known to the LU
3619
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3620
      while extra in fields:
3621
        fields.remove(extra)
3622

    
3623
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3624
    name_idx = field_idx[constants.SF_NAME]
3625

    
3626
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3627
    data = self.rpc.call_storage_list(self.nodes,
3628
                                      self.op.storage_type, st_args,
3629
                                      self.op.name, fields)
3630

    
3631
    result = []
3632

    
3633
    for node in utils.NiceSort(self.nodes):
3634
      nresult = data[node]
3635
      if nresult.offline:
3636
        continue
3637

    
3638
      msg = nresult.fail_msg
3639
      if msg:
3640
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3641
        continue
3642

    
3643
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3644

    
3645
      for name in utils.NiceSort(rows.keys()):
3646
        row = rows[name]
3647

    
3648
        out = []
3649

    
3650
        for field in self.op.output_fields:
3651
          if field == constants.SF_NODE:
3652
            val = node
3653
          elif field == constants.SF_TYPE:
3654
            val = self.op.storage_type
3655
          elif field in field_idx:
3656
            val = row[field_idx[field]]
3657
          else:
3658
            raise errors.ParameterError(field)
3659

    
3660
          out.append(val)
3661

    
3662
        result.append(out)
3663

    
3664
    return result
3665

    
3666

    
3667
class LUModifyNodeStorage(NoHooksLU):
3668
  """Logical unit for modifying a storage volume on a node.
3669

3670
  """
3671
  _OP_PARAMS = [
3672
    _PNodeName,
3673
    ("storage_type", ht.NoDefault, _CheckStorageType),
3674
    ("name", ht.NoDefault, ht.TNonEmptyString),
3675
    ("changes", ht.NoDefault, ht.TDict),
3676
    ]
3677
  REQ_BGL = False
3678

    
3679
  def CheckArguments(self):
3680
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3681

    
3682
    storage_type = self.op.storage_type
3683

    
3684
    try:
3685
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3686
    except KeyError:
3687
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3688
                                 " modified" % storage_type,
3689
                                 errors.ECODE_INVAL)
3690

    
3691
    diff = set(self.op.changes.keys()) - modifiable
3692
    if diff:
3693
      raise errors.OpPrereqError("The following fields can not be modified for"
3694
                                 " storage units of type '%s': %r" %
3695
                                 (storage_type, list(diff)),
3696
                                 errors.ECODE_INVAL)
3697

    
3698
  def ExpandNames(self):
3699
    self.needed_locks = {
3700
      locking.LEVEL_NODE: self.op.node_name,
3701
      }
3702

    
3703
  def Exec(self, feedback_fn):
3704
    """Computes the list of nodes and their attributes.
3705

3706
    """
3707
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3708
    result = self.rpc.call_storage_modify(self.op.node_name,
3709
                                          self.op.storage_type, st_args,
3710
                                          self.op.name, self.op.changes)
3711
    result.Raise("Failed to modify storage unit '%s' on %s" %
3712
                 (self.op.name, self.op.node_name))
3713

    
3714

    
3715
class LUAddNode(LogicalUnit):
3716
  """Logical unit for adding node to the cluster.
3717

3718
  """
3719
  HPATH = "node-add"
3720
  HTYPE = constants.HTYPE_NODE
3721
  _OP_PARAMS = [
3722
    _PNodeName,
3723
    ("primary_ip", None, ht.NoType),
3724
    ("secondary_ip", None, ht.TMaybeString),
3725
    ("readd", False, ht.TBool),
3726
    ("group", None, ht.TMaybeString),
3727
    ("master_capable", None, ht.TMaybeBool),
3728
    ("vm_capable", None, ht.TMaybeBool),
3729
    ]
3730
  _NFLAGS = ["master_capable", "vm_capable"]
3731

    
3732
  def CheckArguments(self):
3733
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
3734
    # validate/normalize the node name
3735
    self.hostname = netutils.GetHostname(name=self.op.node_name,
3736
                                         family=self.primary_ip_family)
3737
    self.op.node_name = self.hostname.name
3738
    if self.op.readd and self.op.group:
3739
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
3740
                                 " being readded", errors.ECODE_INVAL)
3741

    
3742
  def BuildHooksEnv(self):
3743
    """Build hooks env.
3744

3745
    This will run on all nodes before, and on all nodes + the new node after.
3746

3747
    """
3748
    env = {
3749
      "OP_TARGET": self.op.node_name,
3750
      "NODE_NAME": self.op.node_name,
3751
      "NODE_PIP": self.op.primary_ip,
3752
      "NODE_SIP": self.op.secondary_ip,
3753
      "MASTER_CAPABLE": str(self.op.master_capable),
3754
      "VM_CAPABLE": str(self.op.vm_capable),
3755
      }
3756
    nodes_0 = self.cfg.GetNodeList()
3757
    nodes_1 = nodes_0 + [self.op.node_name, ]
3758
    return env, nodes_0, nodes_1
3759

    
3760
  def CheckPrereq(self):
3761
    """Check prerequisites.
3762

3763
    This checks:
3764
     - the new node is not already in the config
3765
     - it is resolvable
3766
     - its parameters (single/dual homed) matches the cluster
3767

3768
    Any errors are signaled by raising errors.OpPrereqError.
3769

3770
    """
3771
    cfg = self.cfg
3772
    hostname = self.hostname
3773
    node = hostname.name
3774
    primary_ip = self.op.primary_ip = hostname.ip
3775
    if self.op.secondary_ip is None:
3776
      if self.primary_ip_family == netutils.IP6Address.family:
3777
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
3778
                                   " IPv4 address must be given as secondary",
3779
                                   errors.ECODE_INVAL)
3780
      self.op.secondary_ip = primary_ip
3781

    
3782
    secondary_ip = self.op.secondary_ip
3783
    if not netutils.IP4Address.IsValid(secondary_ip):
3784
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
3785
                                 " address" % secondary_ip, errors.ECODE_INVAL)
3786

    
3787
    node_list = cfg.GetNodeList()
3788
    if not self.op.readd and node in node_list:
3789
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3790
                                 node, errors.ECODE_EXISTS)
3791
    elif self.op.readd and node not in node_list:
3792
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3793
                                 errors.ECODE_NOENT)
3794

    
3795
    self.changed_primary_ip = False
3796

    
3797
    for existing_node_name in node_list:
3798
      existing_node = cfg.GetNodeInfo(existing_node_name)
3799

    
3800
      if self.op.readd and node == existing_node_name:
3801
        if existing_node.secondary_ip != secondary_ip:
3802
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3803
                                     " address configuration as before",
3804
                                     errors.ECODE_INVAL)
3805
        if existing_node.primary_ip != primary_ip:
3806
          self.changed_primary_ip = True
3807

    
3808
        continue
3809

    
3810
      if (existing_node.primary_ip == primary_ip or
3811
          existing_node.secondary_ip == primary_ip or
3812
          existing_node.primary_ip == secondary_ip or
3813
          existing_node.secondary_ip == secondary_ip):
3814
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3815
                                   " existing node %s" % existing_node.name,
3816
                                   errors.ECODE_NOTUNIQUE)
3817

    
3818
    # After this 'if' block, None is no longer a valid value for the
3819
    # _capable op attributes
3820
    if self.op.readd:
3821
      old_node = self.cfg.GetNodeInfo(node)
3822
      assert old_node is not None, "Can't retrieve locked node %s" % node
3823
      for attr in self._NFLAGS:
3824
        if getattr(self.op, attr) is None:
3825
          setattr(self.op, attr, getattr(old_node, attr))
3826
    else:
3827
      for attr in self._NFLAGS:
3828
        if getattr(self.op, attr) is None:
3829
          setattr(self.op, attr, True)
3830

    
3831
    if self.op.readd and not self.op.vm_capable:
3832
      pri, sec = cfg.GetNodeInstances(node)
3833
      if pri or sec:
3834
        raise errors.OpPrereqError("Node %s being re-added with vm_capable"
3835
                                   " flag set to false, but it already holds"
3836
                                   " instances" % node,
3837
                                   errors.ECODE_STATE)
3838

    
3839
    # check that the type of the node (single versus dual homed) is the
3840
    # same as for the master
3841
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
3842
    master_singlehomed = myself.secondary_ip == myself.primary_ip
3843
    newbie_singlehomed = secondary_ip == primary_ip
3844
    if master_singlehomed != newbie_singlehomed:
3845
      if master_singlehomed:
3846
        raise errors.OpPrereqError("The master has no secondary ip but the"
3847
                                   " new node has one",
3848
                                   errors.ECODE_INVAL)
3849
      else:
3850
        raise errors.OpPrereqError("The master has a secondary ip but the"
3851
                                   " new node doesn't have one",
3852
                                   errors.ECODE_INVAL)
3853

    
3854
    # checks reachability
3855
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3856
      raise errors.OpPrereqError("Node not reachable by ping",
3857
                                 errors.ECODE_ENVIRON)
3858

    
3859
    if not newbie_singlehomed:
3860
      # check reachability from my secondary ip to newbie's secondary ip
3861
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3862
                           source=myself.secondary_ip):
3863
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3864
                                   " based ping to node daemon port",
3865
                                   errors.ECODE_ENVIRON)
3866

    
3867
    if self.op.readd:
3868
      exceptions = [node]
3869
    else:
3870
      exceptions = []
3871

    
3872
    if self.op.master_capable:
3873
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3874
    else:
3875
      self.master_candidate = False
3876

    
3877
    if self.op.readd:
3878
      self.new_node = old_node
3879
    else:
3880
      node_group = cfg.LookupNodeGroup(self.op.group)
3881
      self.new_node = objects.Node(name=node,
3882
                                   primary_ip=primary_ip,
3883
                                   secondary_ip=secondary_ip,
3884
                                   master_candidate=self.master_candidate,
3885
                                   offline=False, drained=False,
3886
                                   group=node_group)
3887

    
3888
  def Exec(self, feedback_fn):
3889
    """Adds the new node to the cluster.
3890

3891
    """
3892
    new_node = self.new_node
3893
    node = new_node.name
3894

    
3895
    # for re-adds, reset the offline/drained/master-candidate flags;
3896
    # we need to reset here, otherwise offline would prevent RPC calls
3897
    # later in the procedure; this also means that if the re-add
3898
    # fails, we are left with a non-offlined, broken node
3899
    if self.op.readd:
3900
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3901
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3902
      # if we demote the node, we do cleanup later in the procedure
3903
      new_node.master_candidate = self.master_candidate
3904
      if self.changed_primary_ip:
3905
        new_node.primary_ip = self.op.primary_ip
3906

    
3907
    # copy the master/vm_capable flags
3908
    for attr in self._NFLAGS:
3909
      setattr(new_node, attr, getattr(self.op, attr))
3910

    
3911
    # notify the user about any possible mc promotion
3912
    if new_node.master_candidate:
3913
      self.LogInfo("Node will be a master candidate")
3914

    
3915
    # check connectivity
3916
    result = self.rpc.call_version([node])[node]
3917
    result.Raise("Can't get version information from node %s" % node)
3918
    if constants.PROTOCOL_VERSION == result.payload:
3919
      logging.info("Communication to node %s fine, sw version %s match",
3920
                   node, result.payload)
3921
    else:
3922
      raise errors.OpExecError("Version mismatch master version %s,"
3923
                               " node version %s" %
3924
                               (constants.PROTOCOL_VERSION, result.payload))
3925

    
3926
    # Add node to our /etc/hosts, and add key to known_hosts
3927
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3928
      master_node = self.cfg.GetMasterNode()
3929
      result = self.rpc.call_etc_hosts_modify(master_node,
3930
                                              constants.ETC_HOSTS_ADD,
3931
                                              self.hostname.name,
3932
                                              self.hostname.ip)
3933
      result.Raise("Can't update hosts file with new host data")
3934

    
3935
    if new_node.secondary_ip != new_node.primary_ip:
3936
      _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
3937
                               False)
3938

    
3939
    node_verify_list = [self.cfg.GetMasterNode()]
3940
    node_verify_param = {
3941
      constants.NV_NODELIST: [node],
3942
      # TODO: do a node-net-test as well?
3943
    }
3944

    
3945
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3946
                                       self.cfg.GetClusterName())
3947
    for verifier in node_verify_list:
3948
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3949
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3950
      if nl_payload:
3951
        for failed in nl_payload:
3952
          feedback_fn("ssh/hostname verification failed"
3953
                      " (checking from %s): %s" %
3954
                      (verifier, nl_payload[failed]))
3955
        raise errors.OpExecError("ssh/hostname verification failed.")
3956

    
3957
    if self.op.readd:
3958
      _RedistributeAncillaryFiles(self)
3959
      self.context.ReaddNode(new_node)
3960
      # make sure we redistribute the config
3961
      self.cfg.Update(new_node, feedback_fn)
3962
      # and make sure the new node will not have old files around
3963
      if not new_node.master_candidate:
3964
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3965
        msg = result.fail_msg
3966
        if msg:
3967
          self.LogWarning("Node failed to demote itself from master"
3968
                          " candidate status: %s" % msg)
3969
    else:
3970
      _RedistributeAncillaryFiles(self, additional_nodes=[node],
3971
                                  additional_vm=self.op.vm_capable)
3972
      self.context.AddNode(new_node, self.proc.GetECId())
3973

    
3974

    
3975
class LUSetNodeParams(LogicalUnit):
3976
  """Modifies the parameters of a node.
3977

3978
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
3979
      to the node role (as _ROLE_*)
3980
  @cvar _R2F: a dictionary from node role to tuples of flags
3981
  @cvar _FLAGS: a list of attribute names corresponding to the flags
3982

3983
  """
3984
  HPATH = "node-modify"
3985
  HTYPE = constants.HTYPE_NODE
3986
  _OP_PARAMS = [
3987
    _PNodeName,
3988
    ("master_candidate", None, ht.TMaybeBool),
3989
    ("offline", None, ht.TMaybeBool),
3990
    ("drained", None, ht.TMaybeBool),
3991
    ("auto_promote", False, ht.TBool),
3992
    ("master_capable", None, ht.TMaybeBool),
3993
    ("vm_capable", None, ht.TMaybeBool),
3994
    ("secondary_ip", None, ht.TMaybeString),
3995
    _PForce,
3996
    ]
3997
  REQ_BGL = False
3998
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
3999
  _F2R = {
4000
    (True, False, False): _ROLE_CANDIDATE,
4001
    (False, True, False): _ROLE_DRAINED,
4002
    (False, False, True): _ROLE_OFFLINE,
4003
    (False, False, False): _ROLE_REGULAR,
4004
    }
4005
  _R2F = dict((v, k) for k, v in _F2R.items())
4006
  _FLAGS = ["master_candidate", "drained", "offline"]
4007

    
4008
  def CheckArguments(self):
4009
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4010
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
4011
                self.op.master_capable, self.op.vm_capable,
4012
                self.op.secondary_ip]
4013
    if all_mods.count(None) == len(all_mods):
4014
      raise errors.OpPrereqError("Please pass at least one modification",
4015
                                 errors.ECODE_INVAL)
4016
    if all_mods.count(True) > 1:
4017
      raise errors.OpPrereqError("Can't set the node into more than one"
4018
                                 " state at the same time",
4019
                                 errors.ECODE_INVAL)
4020

    
4021
    # Boolean value that tells us whether we might be demoting from MC
4022
    self.might_demote = (self.op.master_candidate == False or
4023
                         self.op.offline == True or
4024
                         self.op.drained == True or
4025
                         self.op.master_capable == False)
4026

    
4027
    if self.op.secondary_ip:
4028
      if not netutils.IP4Address.IsValid(self.op.secondary_ip):
4029
        raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4030
                                   " address" % self.op.secondary_ip,
4031
                                   errors.ECODE_INVAL)
4032

    
4033
    self.lock_all = self.op.auto_promote and self.might_demote
4034
    self.lock_instances = self.op.secondary_ip is not None
4035

    
4036
  def ExpandNames(self):
4037
    if self.lock_all:
4038
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
4039
    else:
4040
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
4041

    
4042
    if self.lock_instances:
4043
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4044

    
4045
  def DeclareLocks(self, level):
4046
    # If we have locked all instances, before waiting to lock nodes, release
4047
    # all the ones living on nodes unrelated to the current operation.
4048
    if level == locking.LEVEL_NODE and self.lock_instances:
4049
      instances_release = []
4050
      instances_keep = []
4051
      self.affected_instances = []
4052
      if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4053
        for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
4054
          instance = self.context.cfg.GetInstanceInfo(instance_name)
4055
          i_mirrored = instance.disk_template in constants.DTS_NET_MIRROR
4056
          if i_mirrored and self.op.node_name in instance.all_nodes:
4057
            instances_keep.append(instance_name)
4058
            self.affected_instances.append(instance)
4059
          else:
4060
            instances_release.append(instance_name)
4061
        if instances_release:
4062
          self.context.glm.release(locking.LEVEL_INSTANCE, instances_release)
4063
          self.acquired_locks[locking.LEVEL_INSTANCE] = instances_keep
4064

    
4065
  def BuildHooksEnv(self):
4066
    """Build hooks env.
4067

4068
    This runs on the master node.
4069

4070
    """
4071
    env = {
4072
      "OP_TARGET": self.op.node_name,
4073
      "MASTER_CANDIDATE": str(self.op.master_candidate),
4074
      "OFFLINE": str(self.op.offline),
4075
      "DRAINED": str(self.op.drained),
4076
      "MASTER_CAPABLE": str(self.op.master_capable),
4077
      "VM_CAPABLE": str(self.op.vm_capable),
4078
      }
4079
    nl = [self.cfg.GetMasterNode(),
4080
          self.op.node_name]
4081
    return env, nl, nl
4082

    
4083
  def CheckPrereq(self):
4084
    """Check prerequisites.
4085

4086
    This only checks the instance list against the existing names.
4087

4088
    """
4089
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
4090

    
4091
    if (self.op.master_candidate is not None or
4092
        self.op.drained is not None or
4093
        self.op.offline is not None):
4094
      # we can't change the master's node flags
4095
      if self.op.node_name == self.cfg.GetMasterNode():
4096
        raise errors.OpPrereqError("The master role can be changed"
4097
                                   " only via master-failover",
4098
                                   errors.ECODE_INVAL)
4099

    
4100
    if self.op.master_candidate and not node.master_capable:
4101
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4102
                                 " it a master candidate" % node.name,
4103
                                 errors.ECODE_STATE)
4104

    
4105
    if self.op.vm_capable == False:
4106
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
4107
      if ipri or isec:
4108
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
4109
                                   " the vm_capable flag" % node.name,
4110
                                   errors.ECODE_STATE)
4111

    
4112
    if node.master_candidate and self.might_demote and not self.lock_all:
4113
      assert not self.op.auto_promote, "auto-promote set but lock_all not"
4114
      # check if after removing the current node, we're missing master
4115
      # candidates
4116
      (mc_remaining, mc_should, _) = \
4117
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
4118
      if mc_remaining < mc_should:
4119
        raise errors.OpPrereqError("Not enough master candidates, please"
4120
                                   " pass auto_promote to allow promotion",
4121
                                   errors.ECODE_STATE)
4122

    
4123
    self.old_flags = old_flags = (node.master_candidate,
4124
                                  node.drained, node.offline)
4125
    assert old_flags in self._F2R, "Un-handled old flags  %s" % str(old_flags)
4126
    self.old_role = old_role = self._F2R[old_flags]
4127

    
4128
    # Check for ineffective changes
4129
    for attr in self._FLAGS:
4130
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
4131
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
4132
        setattr(self.op, attr, None)
4133

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

    
4137
    # If we're being deofflined/drained, we'll MC ourself if needed
4138
    if (self.op.drained == False or self.op.offline == False or
4139
        (self.op.master_capable and not node.master_capable)):
4140
      if _DecideSelfPromotion(self):
4141
        self.op.master_candidate = True
4142
        self.LogInfo("Auto-promoting node to master candidate")
4143

    
4144
    # If we're no longer master capable, we'll demote ourselves from MC
4145
    if self.op.master_capable == False and node.master_candidate:
4146
      self.LogInfo("Demoting from master candidate")
4147
      self.op.master_candidate = False
4148

    
4149
    # Compute new role
4150
    assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
4151
    if self.op.master_candidate:
4152
      new_role = self._ROLE_CANDIDATE
4153
    elif self.op.drained:
4154
      new_role = self._ROLE_DRAINED
4155
    elif self.op.offline:
4156
      new_role = self._ROLE_OFFLINE
4157
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
4158
      # False is still in new flags, which means we're un-setting (the
4159
      # only) True flag
4160
      new_role = self._ROLE_REGULAR
4161
    else: # no new flags, nothing, keep old role
4162
      new_role = old_role
4163

    
4164
    self.new_role = new_role
4165

    
4166
    if old_role == self._ROLE_OFFLINE and new_role != old_role:
4167
      # Trying to transition out of offline status
4168
      result = self.rpc.call_version([node.name])[node.name]
4169
      if result.fail_msg:
4170
        raise errors.OpPrereqError("Node %s is being de-offlined but fails"
4171
                                   " to report its version: %s" %
4172
                                   (node.name, result.fail_msg),
4173
                                   errors.ECODE_STATE)
4174
      else:
4175
        self.LogWarning("Transitioning node from offline to online state"
4176
                        " without using re-add. Please make sure the node"
4177
                        " is healthy!")
4178

    
4179
    if self.op.secondary_ip:
4180
      # Ok even without locking, because this can't be changed by any LU
4181
      master = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
4182
      master_singlehomed = master.secondary_ip == master.primary_ip
4183
      if master_singlehomed and self.op.secondary_ip:
4184
        raise errors.OpPrereqError("Cannot change the secondary ip on a single"
4185
                                   " homed cluster", errors.ECODE_INVAL)
4186

    
4187
      if node.offline:
4188
        if self.affected_instances:
4189
          raise errors.OpPrereqError("Cannot change secondary ip: offline"
4190
                                     " node has instances (%s) configured"
4191
                                     " to use it" % self.affected_instances)
4192
      else:
4193
        # On online nodes, check that no instances are running, and that
4194
        # the node has the new ip and we can reach it.
4195
        for instance in self.affected_instances:
4196
          _CheckInstanceDown(self, instance, "cannot change secondary ip")
4197

    
4198
        _CheckNodeHasSecondaryIP(self, node.name, self.op.secondary_ip, True)
4199
        if master.name != node.name:
4200
          # check reachability from master secondary ip to new secondary ip
4201
          if not netutils.TcpPing(self.op.secondary_ip,
4202
                                  constants.DEFAULT_NODED_PORT,
4203
                                  source=master.secondary_ip):
4204
            raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4205
                                       " based ping to node daemon port",
4206
                                       errors.ECODE_ENVIRON)
4207

    
4208
  def Exec(self, feedback_fn):
4209
    """Modifies a node.
4210

4211
    """
4212
    node = self.node
4213
    old_role = self.old_role
4214
    new_role = self.new_role
4215

    
4216
    result = []
4217

    
4218
    for attr in ["master_capable", "vm_capable"]:
4219
      val = getattr(self.op, attr)
4220
      if val is not None:
4221
        setattr(node, attr, val)
4222
        result.append((attr, str(val)))
4223

    
4224
    if new_role != old_role:
4225
      # Tell the node to demote itself, if no longer MC and not offline
4226
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
4227
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
4228
        if msg:
4229
          self.LogWarning("Node failed to demote itself: %s", msg)
4230

    
4231
      new_flags = self._R2F[new_role]
4232
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
4233
        if of != nf:
4234
          result.append((desc, str(nf)))
4235
      (node.master_candidate, node.drained, node.offline) = new_flags
4236

    
4237
      # we locked all nodes, we adjust the CP before updating this node
4238
      if self.lock_all:
4239
        _AdjustCandidatePool(self, [node.name])
4240

    
4241
    if self.op.secondary_ip:
4242
      node.secondary_ip = self.op.secondary_ip
4243
      result.append(("secondary_ip", self.op.secondary_ip))
4244

    
4245
    # this will trigger configuration file update, if needed
4246
    self.cfg.Update(node, feedback_fn)
4247

    
4248
    # this will trigger job queue propagation or cleanup if the mc
4249
    # flag changed
4250
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
4251
      self.context.ReaddNode(node)
4252

    
4253
    return result
4254

    
4255

    
4256
class LUPowercycleNode(NoHooksLU):
4257
  """Powercycles a node.
4258

4259
  """
4260
  _OP_PARAMS = [
4261
    _PNodeName,
4262
    _PForce,
4263
    ]
4264
  REQ_BGL = False
4265

    
4266
  def CheckArguments(self):
4267
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4268
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4269
      raise errors.OpPrereqError("The node is the master and the force"
4270
                                 " parameter was not set",
4271
                                 errors.ECODE_INVAL)
4272

    
4273
  def ExpandNames(self):
4274
    """Locking for PowercycleNode.
4275

4276
    This is a last-resort option and shouldn't block on other
4277
    jobs. Therefore, we grab no locks.
4278

4279
    """
4280
    self.needed_locks = {}
4281

    
4282
  def Exec(self, feedback_fn):
4283
    """Reboots a node.
4284

4285
    """
4286
    result = self.rpc.call_node_powercycle(self.op.node_name,
4287
                                           self.cfg.GetHypervisorType())
4288
    result.Raise("Failed to schedule the reboot")
4289
    return result.payload
4290

    
4291

    
4292
class LUQueryClusterInfo(NoHooksLU):
4293
  """Query cluster configuration.
4294

4295
  """
4296
  REQ_BGL = False
4297

    
4298
  def ExpandNames(self):
4299
    self.needed_locks = {}
4300

    
4301
  def Exec(self, feedback_fn):
4302
    """Return cluster config.
4303

4304
    """
4305
    cluster = self.cfg.GetClusterInfo()
4306
    os_hvp = {}
4307

    
4308
    # Filter just for enabled hypervisors
4309
    for os_name, hv_dict in cluster.os_hvp.items():
4310
      os_hvp[os_name] = {}
4311
      for hv_name, hv_params in hv_dict.items():
4312
        if hv_name in cluster.enabled_hypervisors:
4313
          os_hvp[os_name][hv_name] = hv_params
4314

    
4315
    # Convert ip_family to ip_version
4316
    primary_ip_version = constants.IP4_VERSION
4317
    if cluster.primary_ip_family == netutils.IP6Address.family:
4318
      primary_ip_version = constants.IP6_VERSION
4319

    
4320
    result = {
4321
      "software_version": constants.RELEASE_VERSION,
4322
      "protocol_version": constants.PROTOCOL_VERSION,
4323
      "config_version": constants.CONFIG_VERSION,
4324
      "os_api_version": max(constants.OS_API_VERSIONS),
4325
      "export_version": constants.EXPORT_VERSION,
4326
      "architecture": (platform.architecture()[0], platform.machine()),
4327
      "name": cluster.cluster_name,
4328
      "master": cluster.master_node,
4329
      "default_hypervisor": cluster.enabled_hypervisors[0],
4330
      "enabled_hypervisors": cluster.enabled_hypervisors,
4331
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4332
                        for hypervisor_name in cluster.enabled_hypervisors]),
4333
      "os_hvp": os_hvp,
4334
      "beparams": cluster.beparams,
4335
      "osparams": cluster.osparams,
4336
      "nicparams": cluster.nicparams,
4337
      "candidate_pool_size": cluster.candidate_pool_size,
4338
      "master_netdev": cluster.master_netdev,
4339
      "volume_group_name": cluster.volume_group_name,
4340
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
4341
      "file_storage_dir": cluster.file_storage_dir,
4342
      "maintain_node_health": cluster.maintain_node_health,
4343
      "ctime": cluster.ctime,
4344
      "mtime": cluster.mtime,
4345
      "uuid": cluster.uuid,
4346
      "tags": list(cluster.GetTags()),
4347
      "uid_pool": cluster.uid_pool,
4348
      "default_iallocator": cluster.default_iallocator,
4349
      "reserved_lvs": cluster.reserved_lvs,
4350
      "primary_ip_version": primary_ip_version,
4351
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
4352
      }
4353

    
4354
    return result
4355

    
4356

    
4357
class LUQueryConfigValues(NoHooksLU):
4358
  """Return configuration values.
4359

4360
  """
4361
  _OP_PARAMS = [_POutputFields]
4362
  REQ_BGL = False
4363
  _FIELDS_DYNAMIC = utils.FieldSet()
4364
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4365
                                  "watcher_pause", "volume_group_name")
4366

    
4367
  def CheckArguments(self):
4368
    _CheckOutputFields(static=self._FIELDS_STATIC,
4369
                       dynamic=self._FIELDS_DYNAMIC,
4370
                       selected=self.op.output_fields)
4371

    
4372
  def ExpandNames(self):
4373
    self.needed_locks = {}
4374

    
4375
  def Exec(self, feedback_fn):
4376
    """Dump a representation of the cluster config to the standard output.
4377

4378
    """
4379
    values = []
4380
    for field in self.op.output_fields:
4381
      if field == "cluster_name":
4382
        entry = self.cfg.GetClusterName()
4383
      elif field == "master_node":
4384
        entry = self.cfg.GetMasterNode()
4385
      elif field == "drain_flag":
4386
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4387
      elif field == "watcher_pause":
4388
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4389
      elif field == "volume_group_name":
4390
        entry = self.cfg.GetVGName()
4391
      else:
4392
        raise errors.ParameterError(field)
4393
      values.append(entry)
4394
    return values
4395

    
4396

    
4397
class LUActivateInstanceDisks(NoHooksLU):
4398
  """Bring up an instance's disks.
4399

4400
  """
4401
  _OP_PARAMS = [
4402
    _PInstanceName,
4403
    ("ignore_size", False, ht.TBool),
4404
    ]
4405
  REQ_BGL = False
4406

    
4407
  def ExpandNames(self):
4408
    self._ExpandAndLockInstance()
4409
    self.needed_locks[locking.LEVEL_NODE] = []
4410
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4411

    
4412
  def DeclareLocks(self, level):
4413
    if level == locking.LEVEL_NODE:
4414
      self._LockInstancesNodes()
4415

    
4416
  def CheckPrereq(self):
4417
    """Check prerequisites.
4418

4419
    This checks that the instance is in the cluster.
4420

4421
    """
4422
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4423
    assert self.instance is not None, \
4424
      "Cannot retrieve locked instance %s" % self.op.instance_name
4425
    _CheckNodeOnline(self, self.instance.primary_node)
4426

    
4427
  def Exec(self, feedback_fn):
4428
    """Activate the disks.
4429

4430
    """
4431
    disks_ok, disks_info = \
4432
              _AssembleInstanceDisks(self, self.instance,
4433
                                     ignore_size=self.op.ignore_size)
4434
    if not disks_ok:
4435
      raise errors.OpExecError("Cannot activate block devices")
4436

    
4437
    return disks_info
4438

    
4439

    
4440
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4441
                           ignore_size=False):
4442
  """Prepare the block devices for an instance.
4443

4444
  This sets up the block devices on all nodes.
4445

4446
  @type lu: L{LogicalUnit}
4447
  @param lu: the logical unit on whose behalf we execute
4448
  @type instance: L{objects.Instance}
4449
  @param instance: the instance for whose disks we assemble
4450
  @type disks: list of L{objects.Disk} or None
4451
  @param disks: which disks to assemble (or all, if None)
4452
  @type ignore_secondaries: boolean
4453
  @param ignore_secondaries: if true, errors on secondary nodes
4454
      won't result in an error return from the function
4455
  @type ignore_size: boolean
4456
  @param ignore_size: if true, the current known size of the disk
4457
      will not be used during the disk activation, useful for cases
4458
      when the size is wrong
4459
  @return: False if the operation failed, otherwise a list of
4460
      (host, instance_visible_name, node_visible_name)
4461
      with the mapping from node devices to instance devices
4462

4463
  """
4464
  device_info = []
4465
  disks_ok = True
4466
  iname = instance.name
4467
  disks = _ExpandCheckDisks(instance, disks)
4468

    
4469
  # With the two passes mechanism we try to reduce the window of
4470
  # opportunity for the race condition of switching DRBD to primary
4471
  # before handshaking occured, but we do not eliminate it
4472

    
4473
  # The proper fix would be to wait (with some limits) until the
4474
  # connection has been made and drbd transitions from WFConnection
4475
  # into any other network-connected state (Connected, SyncTarget,
4476
  # SyncSource, etc.)
4477

    
4478
  # 1st pass, assemble on all nodes in secondary mode
4479
  for inst_disk in disks:
4480
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4481
      if ignore_size:
4482
        node_disk = node_disk.Copy()
4483
        node_disk.UnsetSize()
4484
      lu.cfg.SetDiskID(node_disk, node)
4485
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
4486
      msg = result.fail_msg
4487
      if msg:
4488
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4489
                           " (is_primary=False, pass=1): %s",
4490
                           inst_disk.iv_name, node, msg)
4491
        if not ignore_secondaries:
4492
          disks_ok = False
4493

    
4494
  # FIXME: race condition on drbd migration to primary
4495

    
4496
  # 2nd pass, do only the primary node
4497
  for inst_disk in disks:
4498
    dev_path = None
4499

    
4500
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4501
      if node != instance.primary_node:
4502
        continue
4503
      if ignore_size:
4504
        node_disk = node_disk.Copy()
4505
        node_disk.UnsetSize()
4506
      lu.cfg.SetDiskID(node_disk, node)
4507
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
4508
      msg = result.fail_msg
4509
      if msg:
4510
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4511
                           " (is_primary=True, pass=2): %s",
4512
                           inst_disk.iv_name, node, msg)
4513
        disks_ok = False
4514
      else:
4515
        dev_path = result.payload
4516

    
4517
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4518

    
4519
  # leave the disks configured for the primary node
4520
  # this is a workaround that would be fixed better by
4521
  # improving the logical/physical id handling
4522
  for disk in disks:
4523
    lu.cfg.SetDiskID(disk, instance.primary_node)
4524

    
4525
  return disks_ok, device_info
4526

    
4527

    
4528
def _StartInstanceDisks(lu, instance, force):
4529
  """Start the disks of an instance.
4530

4531
  """
4532
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4533
                                           ignore_secondaries=force)
4534
  if not disks_ok:
4535
    _ShutdownInstanceDisks(lu, instance)
4536
    if force is not None and not force:
4537
      lu.proc.LogWarning("", hint="If the message above refers to a"
4538
                         " secondary node,"
4539
                         " you can retry the operation using '--force'.")
4540
    raise errors.OpExecError("Disk consistency error")
4541

    
4542

    
4543
class LUDeactivateInstanceDisks(NoHooksLU):
4544
  """Shutdown an instance's disks.
4545

4546
  """
4547
  _OP_PARAMS = [
4548
    _PInstanceName,
4549
    ]
4550
  REQ_BGL = False
4551

    
4552
  def ExpandNames(self):
4553
    self._ExpandAndLockInstance()
4554
    self.needed_locks[locking.LEVEL_NODE] = []
4555
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4556

    
4557
  def DeclareLocks(self, level):
4558
    if level == locking.LEVEL_NODE:
4559
      self._LockInstancesNodes()
4560

    
4561
  def CheckPrereq(self):
4562
    """Check prerequisites.
4563

4564
    This checks that the instance is in the cluster.
4565

4566
    """
4567
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4568
    assert self.instance is not None, \
4569
      "Cannot retrieve locked instance %s" % self.op.instance_name
4570

    
4571
  def Exec(self, feedback_fn):
4572
    """Deactivate the disks
4573

4574
    """
4575
    instance = self.instance
4576
    _SafeShutdownInstanceDisks(self, instance)
4577

    
4578

    
4579
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4580
  """Shutdown block devices of an instance.
4581

4582
  This function checks if an instance is running, before calling
4583
  _ShutdownInstanceDisks.
4584

4585
  """
4586
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4587
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4588

    
4589

    
4590
def _ExpandCheckDisks(instance, disks):
4591
  """Return the instance disks selected by the disks list
4592

4593
  @type disks: list of L{objects.Disk} or None
4594
  @param disks: selected disks
4595
  @rtype: list of L{objects.Disk}
4596
  @return: selected instance disks to act on
4597

4598
  """
4599
  if disks is None:
4600
    return instance.disks
4601
  else:
4602
    if not set(disks).issubset(instance.disks):
4603
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4604
                                   " target instance")
4605
    return disks
4606

    
4607

    
4608
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4609
  """Shutdown block devices of an instance.
4610

4611
  This does the shutdown on all nodes of the instance.
4612

4613
  If the ignore_primary is false, errors on the primary node are
4614
  ignored.
4615

4616
  """
4617
  all_result = True
4618
  disks = _ExpandCheckDisks(instance, disks)
4619

    
4620
  for disk in disks:
4621
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4622
      lu.cfg.SetDiskID(top_disk, node)
4623
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4624
      msg = result.fail_msg
4625
      if msg:
4626
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4627
                      disk.iv_name, node, msg)
4628
        if not ignore_primary or node != instance.primary_node:
4629
          all_result = False
4630
  return all_result
4631

    
4632

    
4633
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4634
  """Checks if a node has enough free memory.
4635

4636
  This function check if a given node has the needed amount of free
4637
  memory. In case the node has less memory or we cannot get the
4638
  information from the node, this function raise an OpPrereqError
4639
  exception.
4640

4641
  @type lu: C{LogicalUnit}
4642
  @param lu: a logical unit from which we get configuration data
4643
  @type node: C{str}
4644
  @param node: the node to check
4645
  @type reason: C{str}
4646
  @param reason: string to use in the error message
4647
  @type requested: C{int}
4648
  @param requested: the amount of memory in MiB to check for
4649
  @type hypervisor_name: C{str}
4650
  @param hypervisor_name: the hypervisor to ask for memory stats
4651
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4652
      we cannot check the node
4653

4654
  """
4655
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
4656
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4657
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4658
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4659
  if not isinstance(free_mem, int):
4660
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4661
                               " was '%s'" % (node, free_mem),
4662
                               errors.ECODE_ENVIRON)
4663
  if requested > free_mem:
4664
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
4665
                               " needed %s MiB, available %s MiB" %
4666
                               (node, reason, requested, free_mem),
4667
                               errors.ECODE_NORES)
4668

    
4669

    
4670
def _CheckNodesFreeDisk(lu, nodenames, requested):
4671
  """Checks if nodes have enough free disk space in the default VG.
4672

4673
  This function check if all given nodes have the needed amount of
4674
  free disk. In case any node has less disk or we cannot get the
4675
  information from the node, this function raise an OpPrereqError
4676
  exception.
4677

4678
  @type lu: C{LogicalUnit}
4679
  @param lu: a logical unit from which we get configuration data
4680
  @type nodenames: C{list}
4681
  @param nodenames: the list of node names to check
4682
  @type requested: C{int}
4683
  @param requested: the amount of disk in MiB to check for
4684
  @raise errors.OpPrereqError: if the node doesn't have enough disk, or
4685
      we cannot check the node
4686

4687
  """
4688
  nodeinfo = lu.rpc.call_node_info(nodenames, lu.cfg.GetVGName(),
4689
                                   lu.cfg.GetHypervisorType())
4690
  for node in nodenames:
4691
    info = nodeinfo[node]
4692
    info.Raise("Cannot get current information from node %s" % node,
4693
               prereq=True, ecode=errors.ECODE_ENVIRON)
4694
    vg_free = info.payload.get("vg_free", None)
4695
    if not isinstance(vg_free, int):
4696
      raise errors.OpPrereqError("Can't compute free disk space on node %s,"
4697
                                 " result was '%s'" % (node, vg_free),
4698
                                 errors.ECODE_ENVIRON)
4699
    if requested > vg_free:
4700
      raise errors.OpPrereqError("Not enough disk space on target node %s:"
4701
                                 " required %d MiB, available %d MiB" %
4702
                                 (node, requested, vg_free),
4703
                                 errors.ECODE_NORES)
4704

    
4705

    
4706
class LUStartupInstance(LogicalUnit):
4707
  """Starts an instance.
4708

4709
  """
4710
  HPATH = "instance-start"
4711
  HTYPE = constants.HTYPE_INSTANCE
4712
  _OP_PARAMS = [
4713
    _PInstanceName,
4714
    _PForce,
4715
    _PIgnoreOfflineNodes,
4716
    ("hvparams", ht.EmptyDict, ht.TDict),
4717
    ("beparams", ht.EmptyDict, ht.TDict),
4718
    ]
4719
  REQ_BGL = False
4720

    
4721
  def CheckArguments(self):
4722
    # extra beparams
4723
    if self.op.beparams:
4724
      # fill the beparams dict
4725
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
4726

    
4727
  def ExpandNames(self):
4728
    self._ExpandAndLockInstance()
4729

    
4730
  def BuildHooksEnv(self):
4731
    """Build hooks env.
4732

4733
    This runs on master, primary and secondary nodes of the instance.
4734

4735
    """
4736
    env = {
4737
      "FORCE": self.op.force,
4738
      }
4739
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4740
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4741
    return env, nl, nl
4742

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

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

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

    
4753
    # extra hvparams
4754
    if self.op.hvparams:
4755
      # check hypervisor parameter syntax (locally)
4756
      cluster = self.cfg.GetClusterInfo()
4757
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
4758
      filled_hvp = cluster.FillHV(instance)
4759
      filled_hvp.update(self.op.hvparams)
4760
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
4761
      hv_type.CheckParameterSyntax(filled_hvp)
4762
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
4763

    
4764
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
4765

    
4766
    if self.primary_offline and self.op.ignore_offline_nodes:
4767
      self.proc.LogWarning("Ignoring offline primary node")
4768

    
4769
      if self.op.hvparams or self.op.beparams:
4770
        self.proc.LogWarning("Overridden parameters are ignored")
4771
    else:
4772
      _CheckNodeOnline(self, instance.primary_node)
4773

    
4774
      bep = self.cfg.GetClusterInfo().FillBE(instance)
4775

    
4776
      # check bridges existence
4777
      _CheckInstanceBridgesExist(self, instance)
4778

    
4779
      remote_info = self.rpc.call_instance_info(instance.primary_node,
4780
                                                instance.name,
4781
                                                instance.hypervisor)
4782
      remote_info.Raise("Error checking node %s" % instance.primary_node,
4783
                        prereq=True, ecode=errors.ECODE_ENVIRON)
4784
      if not remote_info.payload: # not running already
4785
        _CheckNodeFreeMemory(self, instance.primary_node,
4786
                             "starting instance %s" % instance.name,
4787
                             bep[constants.BE_MEMORY], instance.hypervisor)
4788

    
4789
  def Exec(self, feedback_fn):
4790
    """Start the instance.
4791

4792
    """
4793
    instance = self.instance
4794
    force = self.op.force
4795

    
4796
    self.cfg.MarkInstanceUp(instance.name)
4797

    
4798
    if self.primary_offline:
4799
      assert self.op.ignore_offline_nodes
4800
      self.proc.LogInfo("Primary node offline, marked instance as started")
4801
    else:
4802
      node_current = instance.primary_node
4803

    
4804
      _StartInstanceDisks(self, instance, force)
4805

    
4806
      result = self.rpc.call_instance_start(node_current, instance,
4807
                                            self.op.hvparams, self.op.beparams)
4808
      msg = result.fail_msg
4809
      if msg:
4810
        _ShutdownInstanceDisks(self, instance)
4811
        raise errors.OpExecError("Could not start instance: %s" % msg)
4812

    
4813

    
4814
class LURebootInstance(LogicalUnit):
4815
  """Reboot an instance.
4816

4817
  """
4818
  HPATH = "instance-reboot"
4819
  HTYPE = constants.HTYPE_INSTANCE
4820
  _OP_PARAMS = [
4821
    _PInstanceName,
4822
    ("ignore_secondaries", False, ht.TBool),
4823
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES)),
4824
    _PShutdownTimeout,
4825
    ]
4826
  REQ_BGL = False
4827

    
4828
  def ExpandNames(self):
4829
    self._ExpandAndLockInstance()
4830

    
4831
  def BuildHooksEnv(self):
4832
    """Build hooks env.
4833

4834
    This runs on master, primary and secondary nodes of the instance.
4835

4836
    """
4837
    env = {
4838
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
4839
      "REBOOT_TYPE": self.op.reboot_type,
4840
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
4841
      }
4842
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4843
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4844
    return env, nl, nl
4845

    
4846
  def CheckPrereq(self):
4847
    """Check prerequisites.
4848

4849
    This checks that the instance is in the cluster.
4850

4851
    """
4852
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4853
    assert self.instance is not None, \
4854
      "Cannot retrieve locked instance %s" % self.op.instance_name
4855

    
4856
    _CheckNodeOnline(self, instance.primary_node)
4857

    
4858
    # check bridges existence
4859
    _CheckInstanceBridgesExist(self, instance)
4860

    
4861
  def Exec(self, feedback_fn):
4862
    """Reboot the instance.
4863

4864
    """
4865
    instance = self.instance
4866
    ignore_secondaries = self.op.ignore_secondaries
4867
    reboot_type = self.op.reboot_type
4868

    
4869
    node_current = instance.primary_node
4870

    
4871
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
4872
                       constants.INSTANCE_REBOOT_HARD]:
4873
      for disk in instance.disks:
4874
        self.cfg.SetDiskID(disk, node_current)
4875
      result = self.rpc.call_instance_reboot(node_current, instance,
4876
                                             reboot_type,
4877
                                             self.op.shutdown_timeout)
4878
      result.Raise("Could not reboot instance")
4879
    else:
4880
      result = self.rpc.call_instance_shutdown(node_current, instance,
4881
                                               self.op.shutdown_timeout)
4882
      result.Raise("Could not shutdown instance for full reboot")
4883
      _ShutdownInstanceDisks(self, instance)
4884
      _StartInstanceDisks(self, instance, ignore_secondaries)
4885
      result = self.rpc.call_instance_start(node_current, instance, None, None)
4886
      msg = result.fail_msg
4887
      if msg:
4888
        _ShutdownInstanceDisks(self, instance)
4889
        raise errors.OpExecError("Could not start instance for"
4890
                                 " full reboot: %s" % msg)
4891

    
4892
    self.cfg.MarkInstanceUp(instance.name)
4893

    
4894

    
4895
class LUShutdownInstance(LogicalUnit):
4896
  """Shutdown an instance.
4897

4898
  """
4899
  HPATH = "instance-stop"
4900
  HTYPE = constants.HTYPE_INSTANCE
4901
  _OP_PARAMS = [
4902
    _PInstanceName,
4903
    _PIgnoreOfflineNodes,
4904
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt),
4905
    ]
4906
  REQ_BGL = False
4907

    
4908
  def ExpandNames(self):
4909
    self._ExpandAndLockInstance()
4910

    
4911
  def BuildHooksEnv(self):
4912
    """Build hooks env.
4913

4914
    This runs on master, primary and secondary nodes of the instance.
4915

4916
    """
4917
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4918
    env["TIMEOUT"] = self.op.timeout
4919
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4920
    return env, nl, nl
4921

    
4922
  def CheckPrereq(self):
4923
    """Check prerequisites.
4924

4925
    This checks that the instance is in the cluster.
4926

4927
    """
4928
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4929
    assert self.instance is not None, \
4930
      "Cannot retrieve locked instance %s" % self.op.instance_name
4931

    
4932
    self.primary_offline = \
4933
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
4934

    
4935
    if self.primary_offline and self.op.ignore_offline_nodes:
4936
      self.proc.LogWarning("Ignoring offline primary node")
4937
    else:
4938
      _CheckNodeOnline(self, self.instance.primary_node)
4939

    
4940
  def Exec(self, feedback_fn):
4941
    """Shutdown the instance.
4942

4943
    """
4944
    instance = self.instance
4945
    node_current = instance.primary_node
4946
    timeout = self.op.timeout
4947

    
4948
    self.cfg.MarkInstanceDown(instance.name)
4949

    
4950
    if self.primary_offline:
4951
      assert self.op.ignore_offline_nodes
4952
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
4953
    else:
4954
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
4955
      msg = result.fail_msg
4956
      if msg:
4957
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
4958

    
4959
      _ShutdownInstanceDisks(self, instance)
4960

    
4961

    
4962
class LUReinstallInstance(LogicalUnit):
4963
  """Reinstall an instance.
4964

4965
  """
4966
  HPATH = "instance-reinstall"
4967
  HTYPE = constants.HTYPE_INSTANCE
4968
  _OP_PARAMS = [
4969
    _PInstanceName,
4970
    ("os_type", None, ht.TMaybeString),
4971
    ("force_variant", False, ht.TBool),
4972
    ("osparams", None, ht.TOr(ht.TDict, ht.TNone)),
4973
    ]
4974
  REQ_BGL = False
4975

    
4976
  def ExpandNames(self):
4977
    self._ExpandAndLockInstance()
4978

    
4979
  def BuildHooksEnv(self):
4980
    """Build hooks env.
4981

4982
    This runs on master, primary and secondary nodes of the instance.
4983

4984
    """
4985
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4986
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4987
    return env, nl, nl
4988

    
4989
  def CheckPrereq(self):
4990
    """Check prerequisites.
4991

4992
    This checks that the instance is in the cluster and is not running.
4993

4994
    """
4995
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4996
    assert instance is not None, \
4997
      "Cannot retrieve locked instance %s" % self.op.instance_name
4998
    _CheckNodeOnline(self, instance.primary_node)
4999

    
5000
    if instance.disk_template == constants.DT_DISKLESS:
5001
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5002
                                 self.op.instance_name,
5003
                                 errors.ECODE_INVAL)
5004
    _CheckInstanceDown(self, instance, "cannot reinstall")
5005

    
5006
    if self.op.os_type is not None:
5007
      # OS verification
5008
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
5009
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
5010
      instance_os = self.op.os_type
5011
    else:
5012
      instance_os = instance.os
5013

    
5014
    nodelist = list(instance.all_nodes)
5015

    
5016
    if self.op.osparams:
5017
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
5018
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
5019
      self.os_inst = i_osdict # the new dict (without defaults)
5020
    else:
5021
      self.os_inst = None
5022

    
5023
    self.instance = instance
5024

    
5025
  def Exec(self, feedback_fn):
5026
    """Reinstall the instance.
5027

5028
    """
5029
    inst = self.instance
5030

    
5031
    if self.op.os_type is not None:
5032
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
5033
      inst.os = self.op.os_type
5034
      # Write to configuration
5035
      self.cfg.Update(inst, feedback_fn)
5036

    
5037
    _StartInstanceDisks(self, inst, None)
5038
    try:
5039
      feedback_fn("Running the instance OS create scripts...")
5040
      # FIXME: pass debug option from opcode to backend
5041
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
5042
                                             self.op.debug_level,
5043
                                             osparams=self.os_inst)
5044
      result.Raise("Could not install OS for instance %s on node %s" %
5045
                   (inst.name, inst.primary_node))
5046
    finally:
5047
      _ShutdownInstanceDisks(self, inst)
5048

    
5049

    
5050
class LURecreateInstanceDisks(LogicalUnit):
5051
  """Recreate an instance's missing disks.
5052

5053
  """
5054
  HPATH = "instance-recreate-disks"
5055
  HTYPE = constants.HTYPE_INSTANCE
5056
  _OP_PARAMS = [
5057
    _PInstanceName,
5058
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt)),
5059
    ]
5060
  REQ_BGL = False
5061

    
5062
  def ExpandNames(self):
5063
    self._ExpandAndLockInstance()
5064

    
5065
  def BuildHooksEnv(self):
5066
    """Build hooks env.
5067

5068
    This runs on master, primary and secondary nodes of the instance.
5069

5070
    """
5071
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5072
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5073
    return env, nl, nl
5074

    
5075
  def CheckPrereq(self):
5076
    """Check prerequisites.
5077

5078
    This checks that the instance is in the cluster and is not running.
5079

5080
    """
5081
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5082
    assert instance is not None, \
5083
      "Cannot retrieve locked instance %s" % self.op.instance_name
5084
    _CheckNodeOnline(self, instance.primary_node)
5085

    
5086
    if instance.disk_template == constants.DT_DISKLESS:
5087
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5088
                                 self.op.instance_name, errors.ECODE_INVAL)
5089
    _CheckInstanceDown(self, instance, "cannot recreate disks")
5090

    
5091
    if not self.op.disks:
5092
      self.op.disks = range(len(instance.disks))
5093
    else:
5094
      for idx in self.op.disks:
5095
        if idx >= len(instance.disks):
5096
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
5097
                                     errors.ECODE_INVAL)
5098

    
5099
    self.instance = instance
5100

    
5101
  def Exec(self, feedback_fn):
5102
    """Recreate the disks.
5103

5104
    """
5105
    to_skip = []
5106
    for idx, _ in enumerate(self.instance.disks):
5107
      if idx not in self.op.disks: # disk idx has not been passed in
5108
        to_skip.append(idx)
5109
        continue
5110

    
5111
    _CreateDisks(self, self.instance, to_skip=to_skip)
5112

    
5113

    
5114
class LURenameInstance(LogicalUnit):
5115
  """Rename an instance.
5116

5117
  """
5118
  HPATH = "instance-rename"
5119
  HTYPE = constants.HTYPE_INSTANCE
5120
  _OP_PARAMS = [
5121
    _PInstanceName,
5122
    ("new_name", ht.NoDefault, ht.TNonEmptyString),
5123
    ("ip_check", False, ht.TBool),
5124
    ("name_check", True, ht.TBool),
5125
    ]
5126

    
5127
  def CheckArguments(self):
5128
    """Check arguments.
5129

5130
    """
5131
    if self.op.ip_check and not self.op.name_check:
5132
      # TODO: make the ip check more flexible and not depend on the name check
5133
      raise errors.OpPrereqError("Cannot do ip check without a name check",
5134
                                 errors.ECODE_INVAL)
5135

    
5136
  def BuildHooksEnv(self):
5137
    """Build hooks env.
5138

5139
    This runs on master, primary and secondary nodes of the instance.
5140

5141
    """
5142
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5143
    env["INSTANCE_NEW_NAME"] = self.op.new_name
5144
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5145
    return env, nl, nl
5146

    
5147
  def CheckPrereq(self):
5148
    """Check prerequisites.
5149

5150
    This checks that the instance is in the cluster and is not running.
5151

5152
    """
5153
    self.op.instance_name = _ExpandInstanceName(self.cfg,
5154
                                                self.op.instance_name)
5155
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5156
    assert instance is not None
5157
    _CheckNodeOnline(self, instance.primary_node)
5158
    _CheckInstanceDown(self, instance, "cannot rename")
5159
    self.instance = instance
5160

    
5161
    new_name = self.op.new_name
5162
    if self.op.name_check:
5163
      hostname = netutils.GetHostname(name=new_name)
5164
      new_name = self.op.new_name = hostname.name
5165
      if (self.op.ip_check and
5166
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
5167
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
5168
                                   (hostname.ip, new_name),
5169
                                   errors.ECODE_NOTUNIQUE)
5170

    
5171
    instance_list = self.cfg.GetInstanceList()
5172
    if new_name in instance_list:
5173
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5174
                                 new_name, errors.ECODE_EXISTS)
5175

    
5176
  def Exec(self, feedback_fn):
5177
    """Reinstall the instance.
5178

5179
    """
5180
    inst = self.instance
5181
    old_name = inst.name
5182

    
5183
    if inst.disk_template == constants.DT_FILE:
5184
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5185

    
5186
    self.cfg.RenameInstance(inst.name, self.op.new_name)
5187
    # Change the instance lock. This is definitely safe while we hold the BGL
5188
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
5189
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
5190

    
5191
    # re-read the instance from the configuration after rename
5192
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
5193

    
5194
    if inst.disk_template == constants.DT_FILE:
5195
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5196
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
5197
                                                     old_file_storage_dir,
5198
                                                     new_file_storage_dir)
5199
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
5200
                   " (but the instance has been renamed in Ganeti)" %
5201
                   (inst.primary_node, old_file_storage_dir,
5202
                    new_file_storage_dir))
5203

    
5204
    _StartInstanceDisks(self, inst, None)
5205
    try:
5206
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
5207
                                                 old_name, self.op.debug_level)
5208
      msg = result.fail_msg
5209
      if msg:
5210
        msg = ("Could not run OS rename script for instance %s on node %s"
5211
               " (but the instance has been renamed in Ganeti): %s" %
5212
               (inst.name, inst.primary_node, msg))
5213
        self.proc.LogWarning(msg)
5214
    finally:
5215
      _ShutdownInstanceDisks(self, inst)
5216

    
5217
    return inst.name
5218

    
5219

    
5220
class LURemoveInstance(LogicalUnit):
5221
  """Remove an instance.
5222

5223
  """
5224
  HPATH = "instance-remove"
5225
  HTYPE = constants.HTYPE_INSTANCE
5226
  _OP_PARAMS = [
5227
    _PInstanceName,
5228
    ("ignore_failures", False, ht.TBool),
5229
    _PShutdownTimeout,
5230
    ]
5231
  REQ_BGL = False
5232

    
5233
  def ExpandNames(self):
5234
    self._ExpandAndLockInstance()
5235
    self.needed_locks[locking.LEVEL_NODE] = []
5236
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5237

    
5238
  def DeclareLocks(self, level):
5239
    if level == locking.LEVEL_NODE:
5240
      self._LockInstancesNodes()
5241

    
5242
  def BuildHooksEnv(self):
5243
    """Build hooks env.
5244

5245
    This runs on master, primary and secondary nodes of the instance.
5246

5247
    """
5248
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5249
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
5250
    nl = [self.cfg.GetMasterNode()]
5251
    nl_post = list(self.instance.all_nodes) + nl
5252
    return env, nl, nl_post
5253

    
5254
  def CheckPrereq(self):
5255
    """Check prerequisites.
5256

5257
    This checks that the instance is in the cluster.
5258

5259
    """
5260
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5261
    assert self.instance is not None, \
5262
      "Cannot retrieve locked instance %s" % self.op.instance_name
5263

    
5264
  def Exec(self, feedback_fn):
5265
    """Remove the instance.
5266

5267
    """
5268
    instance = self.instance
5269
    logging.info("Shutting down instance %s on node %s",
5270
                 instance.name, instance.primary_node)
5271

    
5272
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5273
                                             self.op.shutdown_timeout)
5274
    msg = result.fail_msg
5275
    if msg:
5276
      if self.op.ignore_failures:
5277
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5278
      else:
5279
        raise errors.OpExecError("Could not shutdown instance %s on"
5280
                                 " node %s: %s" %
5281
                                 (instance.name, instance.primary_node, msg))
5282

    
5283
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5284

    
5285

    
5286
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5287
  """Utility function to remove an instance.
5288

5289
  """
5290
  logging.info("Removing block devices for instance %s", instance.name)
5291

    
5292
  if not _RemoveDisks(lu, instance):
5293
    if not ignore_failures:
5294
      raise errors.OpExecError("Can't remove instance's disks")
5295
    feedback_fn("Warning: can't remove instance's disks")
5296

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

    
5299
  lu.cfg.RemoveInstance(instance.name)
5300

    
5301
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5302
    "Instance lock removal conflict"
5303

    
5304
  # Remove lock for the instance
5305
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5306

    
5307

    
5308
class LUQueryInstances(NoHooksLU):
5309
  """Logical unit for querying instances.
5310

5311
  """
5312
  # pylint: disable-msg=W0142
5313
  _OP_PARAMS = [
5314
    ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
5315
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
5316
    ("use_locking", False, ht.TBool),
5317
    ]
5318
  REQ_BGL = False
5319
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
5320
                    "serial_no", "ctime", "mtime", "uuid"]
5321
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
5322
                                    "admin_state",
5323
                                    "disk_template", "ip", "mac", "bridge",
5324
                                    "nic_mode", "nic_link",
5325
                                    "sda_size", "sdb_size", "vcpus", "tags",
5326
                                    "network_port", "beparams",
5327
                                    r"(disk)\.(size)/([0-9]+)",
5328
                                    r"(disk)\.(sizes)", "disk_usage",
5329
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
5330
                                    r"(nic)\.(bridge)/([0-9]+)",
5331
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
5332
                                    r"(disk|nic)\.(count)",
5333
                                    "hvparams", "custom_hvparams",
5334
                                    "custom_beparams", "custom_nicparams",
5335
                                    ] + _SIMPLE_FIELDS +
5336
                                  ["hv/%s" % name
5337
                                   for name in constants.HVS_PARAMETERS
5338
                                   if name not in constants.HVC_GLOBALS] +
5339
                                  ["be/%s" % name
5340
                                   for name in constants.BES_PARAMETERS])
5341
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state",
5342
                                   "oper_ram",
5343
                                   "oper_vcpus",
5344
                                   "status")
5345

    
5346

    
5347
  def CheckArguments(self):
5348
    _CheckOutputFields(static=self._FIELDS_STATIC,
5349
                       dynamic=self._FIELDS_DYNAMIC,
5350
                       selected=self.op.output_fields)
5351

    
5352
  def ExpandNames(self):
5353
    self.needed_locks = {}
5354
    self.share_locks[locking.LEVEL_INSTANCE] = 1
5355
    self.share_locks[locking.LEVEL_NODE] = 1
5356

    
5357
    if self.op.names:
5358
      self.wanted = _GetWantedInstances(self, self.op.names)
5359
    else:
5360
      self.wanted = locking.ALL_SET
5361

    
5362
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
5363
    self.do_locking = self.do_node_query and self.op.use_locking
5364
    if self.do_locking:
5365
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
5366
      self.needed_locks[locking.LEVEL_NODE] = []
5367
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5368

    
5369
  def DeclareLocks(self, level):
5370
    if level == locking.LEVEL_NODE and self.do_locking:
5371
      self._LockInstancesNodes()
5372

    
5373
  def Exec(self, feedback_fn):
5374
    """Computes the list of nodes and their attributes.
5375

5376
    """
5377
    # pylint: disable-msg=R0912
5378
    # way too many branches here
5379
    all_info = self.cfg.GetAllInstancesInfo()
5380
    if self.wanted == locking.ALL_SET:
5381
      # caller didn't specify instance names, so ordering is not important
5382
      if self.do_locking:
5383
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5384
      else:
5385
        instance_names = all_info.keys()
5386
      instance_names = utils.NiceSort(instance_names)
5387
    else:
5388
      # caller did specify names, so we must keep the ordering
5389
      if self.do_locking:
5390
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
5391
      else:
5392
        tgt_set = all_info.keys()
5393
      missing = set(self.wanted).difference(tgt_set)
5394
      if missing:
5395
        raise errors.OpExecError("Some instances were removed before"
5396
                                 " retrieving their data: %s" % missing)
5397
      instance_names = self.wanted
5398

    
5399
    instance_list = [all_info[iname] for iname in instance_names]
5400

    
5401
    # begin data gathering
5402

    
5403
    nodes = frozenset([inst.primary_node for inst in instance_list])
5404
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
5405

    
5406
    bad_nodes = []
5407
    off_nodes = []
5408
    if self.do_node_query:
5409
      live_data = {}
5410
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
5411
      for name in nodes:
5412
        result = node_data[name]
5413
        if result.offline:
5414
          # offline nodes will be in both lists
5415
          off_nodes.append(name)
5416
        if result.fail_msg:
5417
          bad_nodes.append(name)
5418
        else:
5419
          if result.payload:
5420
            live_data.update(result.payload)
5421
          # else no instance is alive
5422
    else:
5423
      live_data = dict([(name, {}) for name in instance_names])
5424

    
5425
    # end data gathering
5426

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

    
5603
    return output
5604

    
5605

    
5606
class LUFailoverInstance(LogicalUnit):
5607
  """Failover an instance.
5608

5609
  """
5610
  HPATH = "instance-failover"
5611
  HTYPE = constants.HTYPE_INSTANCE
5612
  _OP_PARAMS = [
5613
    _PInstanceName,
5614
    ("ignore_consistency", False, ht.TBool),
5615
    _PShutdownTimeout,
5616
    ]
5617
  REQ_BGL = False
5618

    
5619
  def ExpandNames(self):
5620
    self._ExpandAndLockInstance()
5621
    self.needed_locks[locking.LEVEL_NODE] = []
5622
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5623

    
5624
  def DeclareLocks(self, level):
5625
    if level == locking.LEVEL_NODE:
5626
      self._LockInstancesNodes()
5627

    
5628
  def BuildHooksEnv(self):
5629
    """Build hooks env.
5630

5631
    This runs on master, primary and secondary nodes of the instance.
5632

5633
    """
5634
    instance = self.instance
5635
    source_node = instance.primary_node
5636
    target_node = instance.secondary_nodes[0]
5637
    env = {
5638
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5639
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5640
      "OLD_PRIMARY": source_node,
5641
      "OLD_SECONDARY": target_node,
5642
      "NEW_PRIMARY": target_node,
5643
      "NEW_SECONDARY": source_node,
5644
      }
5645
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5646
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5647
    nl_post = list(nl)
5648
    nl_post.append(source_node)
5649
    return env, nl, nl_post
5650

    
5651
  def CheckPrereq(self):
5652
    """Check prerequisites.
5653

5654
    This checks that the instance is in the cluster.
5655

5656
    """
5657
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5658
    assert self.instance is not None, \
5659
      "Cannot retrieve locked instance %s" % self.op.instance_name
5660

    
5661
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5662
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5663
      raise errors.OpPrereqError("Instance's disk layout is not"
5664
                                 " network mirrored, cannot failover.",
5665
                                 errors.ECODE_STATE)
5666

    
5667
    secondary_nodes = instance.secondary_nodes
5668
    if not secondary_nodes:
5669
      raise errors.ProgrammerError("no secondary node but using "
5670
                                   "a mirrored disk template")
5671

    
5672
    target_node = secondary_nodes[0]
5673
    _CheckNodeOnline(self, target_node)
5674
    _CheckNodeNotDrained(self, target_node)
5675
    if instance.admin_up:
5676
      # check memory requirements on the secondary node
5677
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5678
                           instance.name, bep[constants.BE_MEMORY],
5679
                           instance.hypervisor)
5680
    else:
5681
      self.LogInfo("Not checking memory on the secondary node as"
5682
                   " instance will not be started")
5683

    
5684
    # check bridge existance
5685
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5686

    
5687
  def Exec(self, feedback_fn):
5688
    """Failover an instance.
5689

5690
    The failover is done by shutting it down on its present node and
5691
    starting it on the secondary.
5692

5693
    """
5694
    instance = self.instance
5695
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
5696

    
5697
    source_node = instance.primary_node
5698
    target_node = instance.secondary_nodes[0]
5699

    
5700
    if instance.admin_up:
5701
      feedback_fn("* checking disk consistency between source and target")
5702
      for dev in instance.disks:
5703
        # for drbd, these are drbd over lvm
5704
        if not _CheckDiskConsistency(self, dev, target_node, False):
5705
          if not self.op.ignore_consistency:
5706
            raise errors.OpExecError("Disk %s is degraded on target node,"
5707
                                     " aborting failover." % dev.iv_name)
5708
    else:
5709
      feedback_fn("* not checking disk consistency as instance is not running")
5710

    
5711
    feedback_fn("* shutting down instance on source node")
5712
    logging.info("Shutting down instance %s on node %s",
5713
                 instance.name, source_node)
5714

    
5715
    result = self.rpc.call_instance_shutdown(source_node, instance,
5716
                                             self.op.shutdown_timeout)
5717
    msg = result.fail_msg
5718
    if msg:
5719
      if self.op.ignore_consistency or primary_node.offline:
5720
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5721
                             " Proceeding anyway. Please make sure node"
5722
                             " %s is down. Error details: %s",
5723
                             instance.name, source_node, source_node, msg)
5724
      else:
5725
        raise errors.OpExecError("Could not shutdown instance %s on"
5726
                                 " node %s: %s" %
5727
                                 (instance.name, source_node, msg))
5728

    
5729
    feedback_fn("* deactivating the instance's disks on source node")
5730
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5731
      raise errors.OpExecError("Can't shut down the instance's disks.")
5732

    
5733
    instance.primary_node = target_node
5734
    # distribute new instance config to the other nodes
5735
    self.cfg.Update(instance, feedback_fn)
5736

    
5737
    # Only start the instance if it's marked as up
5738
    if instance.admin_up:
5739
      feedback_fn("* activating the instance's disks on target node")
5740
      logging.info("Starting instance %s on node %s",
5741
                   instance.name, target_node)
5742

    
5743
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5744
                                           ignore_secondaries=True)
5745
      if not disks_ok:
5746
        _ShutdownInstanceDisks(self, instance)
5747
        raise errors.OpExecError("Can't activate the instance's disks")
5748

    
5749
      feedback_fn("* starting the instance on the target node")
5750
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5751
      msg = result.fail_msg
5752
      if msg:
5753
        _ShutdownInstanceDisks(self, instance)
5754
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5755
                                 (instance.name, target_node, msg))
5756

    
5757

    
5758
class LUMigrateInstance(LogicalUnit):
5759
  """Migrate an instance.
5760

5761
  This is migration without shutting down, compared to the failover,
5762
  which is done with shutdown.
5763

5764
  """
5765
  HPATH = "instance-migrate"
5766
  HTYPE = constants.HTYPE_INSTANCE
5767
  _OP_PARAMS = [
5768
    _PInstanceName,
5769
    _PMigrationMode,
5770
    _PMigrationLive,
5771
    ("cleanup", False, ht.TBool),
5772
    ]
5773

    
5774
  REQ_BGL = False
5775

    
5776
  def ExpandNames(self):
5777
    self._ExpandAndLockInstance()
5778

    
5779
    self.needed_locks[locking.LEVEL_NODE] = []
5780
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5781

    
5782
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5783
                                       self.op.cleanup)
5784
    self.tasklets = [self._migrater]
5785

    
5786
  def DeclareLocks(self, level):
5787
    if level == locking.LEVEL_NODE:
5788
      self._LockInstancesNodes()
5789

    
5790
  def BuildHooksEnv(self):
5791
    """Build hooks env.
5792

5793
    This runs on master, primary and secondary nodes of the instance.
5794

5795
    """
5796
    instance = self._migrater.instance
5797
    source_node = instance.primary_node
5798
    target_node = instance.secondary_nodes[0]
5799
    env = _BuildInstanceHookEnvByObject(self, instance)
5800
    env["MIGRATE_LIVE"] = self._migrater.live
5801
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5802
    env.update({
5803
        "OLD_PRIMARY": source_node,
5804
        "OLD_SECONDARY": target_node,
5805
        "NEW_PRIMARY": target_node,
5806
        "NEW_SECONDARY": source_node,
5807
        })
5808
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5809
    nl_post = list(nl)
5810
    nl_post.append(source_node)
5811
    return env, nl, nl_post
5812

    
5813

    
5814
class LUMoveInstance(LogicalUnit):
5815
  """Move an instance by data-copying.
5816

5817
  """
5818
  HPATH = "instance-move"
5819
  HTYPE = constants.HTYPE_INSTANCE
5820
  _OP_PARAMS = [
5821
    _PInstanceName,
5822
    ("target_node", ht.NoDefault, ht.TNonEmptyString),
5823
    _PShutdownTimeout,
5824
    ]
5825
  REQ_BGL = False
5826

    
5827
  def ExpandNames(self):
5828
    self._ExpandAndLockInstance()
5829
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5830
    self.op.target_node = target_node
5831
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5832
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5833

    
5834
  def DeclareLocks(self, level):
5835
    if level == locking.LEVEL_NODE:
5836
      self._LockInstancesNodes(primary_only=True)
5837

    
5838
  def BuildHooksEnv(self):
5839
    """Build hooks env.
5840

5841
    This runs on master, primary and secondary nodes of the instance.
5842

5843
    """
5844
    env = {
5845
      "TARGET_NODE": self.op.target_node,
5846
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5847
      }
5848
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5849
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5850
                                       self.op.target_node]
5851
    return env, nl, nl
5852

    
5853
  def CheckPrereq(self):
5854
    """Check prerequisites.
5855

5856
    This checks that the instance is in the cluster.
5857

5858
    """
5859
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5860
    assert self.instance is not None, \
5861
      "Cannot retrieve locked instance %s" % self.op.instance_name
5862

    
5863
    node = self.cfg.GetNodeInfo(self.op.target_node)
5864
    assert node is not None, \
5865
      "Cannot retrieve locked node %s" % self.op.target_node
5866

    
5867
    self.target_node = target_node = node.name
5868

    
5869
    if target_node == instance.primary_node:
5870
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5871
                                 (instance.name, target_node),
5872
                                 errors.ECODE_STATE)
5873

    
5874
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5875

    
5876
    for idx, dsk in enumerate(instance.disks):
5877
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5878
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5879
                                   " cannot copy" % idx, errors.ECODE_STATE)
5880

    
5881
    _CheckNodeOnline(self, target_node)
5882
    _CheckNodeNotDrained(self, target_node)
5883
    _CheckNodeVmCapable(self, target_node)
5884

    
5885
    if instance.admin_up:
5886
      # check memory requirements on the secondary node
5887
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5888
                           instance.name, bep[constants.BE_MEMORY],
5889
                           instance.hypervisor)
5890
    else:
5891
      self.LogInfo("Not checking memory on the secondary node as"
5892
                   " instance will not be started")
5893

    
5894
    # check bridge existance
5895
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5896

    
5897
  def Exec(self, feedback_fn):
5898
    """Move an instance.
5899

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

5903
    """
5904
    instance = self.instance
5905

    
5906
    source_node = instance.primary_node
5907
    target_node = self.target_node
5908

    
5909
    self.LogInfo("Shutting down instance %s on source node %s",
5910
                 instance.name, source_node)
5911

    
5912
    result = self.rpc.call_instance_shutdown(source_node, instance,
5913
                                             self.op.shutdown_timeout)
5914
    msg = result.fail_msg
5915
    if msg:
5916
      if self.op.ignore_consistency:
5917
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5918
                             " Proceeding anyway. Please make sure node"
5919
                             " %s is down. Error details: %s",
5920
                             instance.name, source_node, source_node, msg)
5921
      else:
5922
        raise errors.OpExecError("Could not shutdown instance %s on"
5923
                                 " node %s: %s" %
5924
                                 (instance.name, source_node, msg))
5925

    
5926
    # create the target disks
5927
    try:
5928
      _CreateDisks(self, instance, target_node=target_node)
5929
    except errors.OpExecError:
5930
      self.LogWarning("Device creation failed, reverting...")
5931
      try:
5932
        _RemoveDisks(self, instance, target_node=target_node)
5933
      finally:
5934
        self.cfg.ReleaseDRBDMinors(instance.name)
5935
        raise
5936

    
5937
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5938

    
5939
    errs = []
5940
    # activate, get path, copy the data over
5941
    for idx, disk in enumerate(instance.disks):
5942
      self.LogInfo("Copying data for disk %d", idx)
5943
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5944
                                               instance.name, True)
5945
      if result.fail_msg:
5946
        self.LogWarning("Can't assemble newly created disk %d: %s",
5947
                        idx, result.fail_msg)
5948
        errs.append(result.fail_msg)
5949
        break
5950
      dev_path = result.payload
5951
      result = self.rpc.call_blockdev_export(source_node, disk,
5952
                                             target_node, dev_path,
5953
                                             cluster_name)
5954
      if result.fail_msg:
5955
        self.LogWarning("Can't copy data over for disk %d: %s",
5956
                        idx, result.fail_msg)
5957
        errs.append(result.fail_msg)
5958
        break
5959

    
5960
    if errs:
5961
      self.LogWarning("Some disks failed to copy, aborting")
5962
      try:
5963
        _RemoveDisks(self, instance, target_node=target_node)
5964
      finally:
5965
        self.cfg.ReleaseDRBDMinors(instance.name)
5966
        raise errors.OpExecError("Errors during disk copy: %s" %
5967
                                 (",".join(errs),))
5968

    
5969
    instance.primary_node = target_node
5970
    self.cfg.Update(instance, feedback_fn)
5971

    
5972
    self.LogInfo("Removing the disks on the original node")
5973
    _RemoveDisks(self, instance, target_node=source_node)
5974

    
5975
    # Only start the instance if it's marked as up
5976
    if instance.admin_up:
5977
      self.LogInfo("Starting instance %s on node %s",
5978
                   instance.name, target_node)
5979

    
5980
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5981
                                           ignore_secondaries=True)
5982
      if not disks_ok:
5983
        _ShutdownInstanceDisks(self, instance)
5984
        raise errors.OpExecError("Can't activate the instance's disks")
5985

    
5986
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5987
      msg = result.fail_msg
5988
      if msg:
5989
        _ShutdownInstanceDisks(self, instance)
5990
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5991
                                 (instance.name, target_node, msg))
5992

    
5993

    
5994
class LUMigrateNode(LogicalUnit):
5995
  """Migrate all instances from a node.
5996

5997
  """
5998
  HPATH = "node-migrate"
5999
  HTYPE = constants.HTYPE_NODE
6000
  _OP_PARAMS = [
6001
    _PNodeName,
6002
    _PMigrationMode,
6003
    _PMigrationLive,
6004
    ]
6005
  REQ_BGL = False
6006

    
6007
  def ExpandNames(self):
6008
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6009

    
6010
    self.needed_locks = {
6011
      locking.LEVEL_NODE: [self.op.node_name],
6012
      }
6013

    
6014
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6015

    
6016
    # Create tasklets for migrating instances for all instances on this node
6017
    names = []
6018
    tasklets = []
6019

    
6020
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
6021
      logging.debug("Migrating instance %s", inst.name)
6022
      names.append(inst.name)
6023

    
6024
      tasklets.append(TLMigrateInstance(self, inst.name, False))
6025

    
6026
    self.tasklets = tasklets
6027

    
6028
    # Declare instance locks
6029
    self.needed_locks[locking.LEVEL_INSTANCE] = names
6030

    
6031
  def DeclareLocks(self, level):
6032
    if level == locking.LEVEL_NODE:
6033
      self._LockInstancesNodes()
6034

    
6035
  def BuildHooksEnv(self):
6036
    """Build hooks env.
6037

6038
    This runs on the master, the primary and all the secondaries.
6039

6040
    """
6041
    env = {
6042
      "NODE_NAME": self.op.node_name,
6043
      }
6044

    
6045
    nl = [self.cfg.GetMasterNode()]
6046

    
6047
    return (env, nl, nl)
6048

    
6049

    
6050
class TLMigrateInstance(Tasklet):
6051
  """Tasklet class for instance migration.
6052

6053
  @type live: boolean
6054
  @ivar live: whether the migration will be done live or non-live;
6055
      this variable is initalized only after CheckPrereq has run
6056

6057
  """
6058
  def __init__(self, lu, instance_name, cleanup):
6059
    """Initializes this class.
6060

6061
    """
6062
    Tasklet.__init__(self, lu)
6063

    
6064
    # Parameters
6065
    self.instance_name = instance_name
6066
    self.cleanup = cleanup
6067
    self.live = False # will be overridden later
6068

    
6069
  def CheckPrereq(self):
6070
    """Check prerequisites.
6071

6072
    This checks that the instance is in the cluster.
6073

6074
    """
6075
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
6076
    instance = self.cfg.GetInstanceInfo(instance_name)
6077
    assert instance is not None
6078

    
6079
    if instance.disk_template != constants.DT_DRBD8:
6080
      raise errors.OpPrereqError("Instance's disk layout is not"
6081
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
6082

    
6083
    secondary_nodes = instance.secondary_nodes
6084
    if not secondary_nodes:
6085
      raise errors.ConfigurationError("No secondary node but using"
6086
                                      " drbd8 disk template")
6087

    
6088
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
6089

    
6090
    target_node = secondary_nodes[0]
6091
    # check memory requirements on the secondary node
6092
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
6093
                         instance.name, i_be[constants.BE_MEMORY],
6094
                         instance.hypervisor)
6095

    
6096
    # check bridge existance
6097
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
6098

    
6099
    if not self.cleanup:
6100
      _CheckNodeNotDrained(self.lu, target_node)
6101
      result = self.rpc.call_instance_migratable(instance.primary_node,
6102
                                                 instance)
6103
      result.Raise("Can't migrate, please use failover",
6104
                   prereq=True, ecode=errors.ECODE_STATE)
6105

    
6106
    self.instance = instance
6107

    
6108
    if self.lu.op.live is not None and self.lu.op.mode is not None:
6109
      raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
6110
                                 " parameters are accepted",
6111
                                 errors.ECODE_INVAL)
6112
    if self.lu.op.live is not None:
6113
      if self.lu.op.live:
6114
        self.lu.op.mode = constants.HT_MIGRATION_LIVE
6115
      else:
6116
        self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6117
      # reset the 'live' parameter to None so that repeated
6118
      # invocations of CheckPrereq do not raise an exception
6119
      self.lu.op.live = None
6120
    elif self.lu.op.mode is None:
6121
      # read the default value from the hypervisor
6122
      i_hv = self.cfg.GetClusterInfo().FillHV(instance, skip_globals=False)
6123
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6124

    
6125
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6126

    
6127
  def _WaitUntilSync(self):
6128
    """Poll with custom rpc for disk sync.
6129

6130
    This uses our own step-based rpc call.
6131

6132
    """
6133
    self.feedback_fn("* wait until resync is done")
6134
    all_done = False
6135
    while not all_done:
6136
      all_done = True
6137
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6138
                                            self.nodes_ip,
6139
                                            self.instance.disks)
6140
      min_percent = 100
6141
      for node, nres in result.items():
6142
        nres.Raise("Cannot resync disks on node %s" % node)
6143
        node_done, node_percent = nres.payload
6144
        all_done = all_done and node_done
6145
        if node_percent is not None:
6146
          min_percent = min(min_percent, node_percent)
6147
      if not all_done:
6148
        if min_percent < 100:
6149
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6150
        time.sleep(2)
6151

    
6152
  def _EnsureSecondary(self, node):
6153
    """Demote a node to secondary.
6154

6155
    """
6156
    self.feedback_fn("* switching node %s to secondary mode" % node)
6157

    
6158
    for dev in self.instance.disks:
6159
      self.cfg.SetDiskID(dev, node)
6160

    
6161
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6162
                                          self.instance.disks)
6163
    result.Raise("Cannot change disk to secondary on node %s" % node)
6164

    
6165
  def _GoStandalone(self):
6166
    """Disconnect from the network.
6167

6168
    """
6169
    self.feedback_fn("* changing into standalone mode")
6170
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6171
                                               self.instance.disks)
6172
    for node, nres in result.items():
6173
      nres.Raise("Cannot disconnect disks node %s" % node)
6174

    
6175
  def _GoReconnect(self, multimaster):
6176
    """Reconnect to the network.
6177

6178
    """
6179
    if multimaster:
6180
      msg = "dual-master"
6181
    else:
6182
      msg = "single-master"
6183
    self.feedback_fn("* changing disks into %s mode" % msg)
6184
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6185
                                           self.instance.disks,
6186
                                           self.instance.name, multimaster)
6187
    for node, nres in result.items():
6188
      nres.Raise("Cannot change disks config on node %s" % node)
6189

    
6190
  def _ExecCleanup(self):
6191
    """Try to cleanup after a failed migration.
6192

6193
    The cleanup is done by:
6194
      - check that the instance is running only on one node
6195
        (and update the config if needed)
6196
      - change disks on its secondary node to secondary
6197
      - wait until disks are fully synchronized
6198
      - disconnect from the network
6199
      - change disks into single-master mode
6200
      - wait again until disks are fully synchronized
6201

6202
    """
6203
    instance = self.instance
6204
    target_node = self.target_node
6205
    source_node = self.source_node
6206

    
6207
    # check running on only one node
6208
    self.feedback_fn("* checking where the instance actually runs"
6209
                     " (if this hangs, the hypervisor might be in"
6210
                     " a bad state)")
6211
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
6212
    for node, result in ins_l.items():
6213
      result.Raise("Can't contact node %s" % node)
6214

    
6215
    runningon_source = instance.name in ins_l[source_node].payload
6216
    runningon_target = instance.name in ins_l[target_node].payload
6217

    
6218
    if runningon_source and runningon_target:
6219
      raise errors.OpExecError("Instance seems to be running on two nodes,"
6220
                               " or the hypervisor is confused. You will have"
6221
                               " to ensure manually that it runs only on one"
6222
                               " and restart this operation.")
6223

    
6224
    if not (runningon_source or runningon_target):
6225
      raise errors.OpExecError("Instance does not seem to be running at all."
6226
                               " In this case, it's safer to repair by"
6227
                               " running 'gnt-instance stop' to ensure disk"
6228
                               " shutdown, and then restarting it.")
6229

    
6230
    if runningon_target:
6231
      # the migration has actually succeeded, we need to update the config
6232
      self.feedback_fn("* instance running on secondary node (%s),"
6233
                       " updating config" % target_node)
6234
      instance.primary_node = target_node
6235
      self.cfg.Update(instance, self.feedback_fn)
6236
      demoted_node = source_node
6237
    else:
6238
      self.feedback_fn("* instance confirmed to be running on its"
6239
                       " primary node (%s)" % source_node)
6240
      demoted_node = target_node
6241

    
6242
    self._EnsureSecondary(demoted_node)
6243
    try:
6244
      self._WaitUntilSync()
6245
    except errors.OpExecError:
6246
      # we ignore here errors, since if the device is standalone, it
6247
      # won't be able to sync
6248
      pass
6249
    self._GoStandalone()
6250
    self._GoReconnect(False)
6251
    self._WaitUntilSync()
6252

    
6253
    self.feedback_fn("* done")
6254

    
6255
  def _RevertDiskStatus(self):
6256
    """Try to revert the disk status after a failed migration.
6257

6258
    """
6259
    target_node = self.target_node
6260
    try:
6261
      self._EnsureSecondary(target_node)
6262
      self._GoStandalone()
6263
      self._GoReconnect(False)
6264
      self._WaitUntilSync()
6265
    except errors.OpExecError, err:
6266
      self.lu.LogWarning("Migration failed and I can't reconnect the"
6267
                         " drives: error '%s'\n"
6268
                         "Please look and recover the instance status" %
6269
                         str(err))
6270

    
6271
  def _AbortMigration(self):
6272
    """Call the hypervisor code to abort a started migration.
6273

6274
    """
6275
    instance = self.instance
6276
    target_node = self.target_node
6277
    migration_info = self.migration_info
6278

    
6279
    abort_result = self.rpc.call_finalize_migration(target_node,
6280
                                                    instance,
6281
                                                    migration_info,
6282
                                                    False)
6283
    abort_msg = abort_result.fail_msg
6284
    if abort_msg:
6285
      logging.error("Aborting migration failed on target node %s: %s",
6286
                    target_node, abort_msg)
6287
      # Don't raise an exception here, as we stil have to try to revert the
6288
      # disk status, even if this step failed.
6289

    
6290
  def _ExecMigration(self):
6291
    """Migrate an instance.
6292

6293
    The migrate is done by:
6294
      - change the disks into dual-master mode
6295
      - wait until disks are fully synchronized again
6296
      - migrate the instance
6297
      - change disks on the new secondary node (the old primary) to secondary
6298
      - wait until disks are fully synchronized
6299
      - change disks into single-master mode
6300

6301
    """
6302
    instance = self.instance
6303
    target_node = self.target_node
6304
    source_node = self.source_node
6305

    
6306
    self.feedback_fn("* checking disk consistency between source and target")
6307
    for dev in instance.disks:
6308
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6309
        raise errors.OpExecError("Disk %s is degraded or not fully"
6310
                                 " synchronized on target node,"
6311
                                 " aborting migrate." % dev.iv_name)
6312

    
6313
    # First get the migration information from the remote node
6314
    result = self.rpc.call_migration_info(source_node, instance)
6315
    msg = result.fail_msg
6316
    if msg:
6317
      log_err = ("Failed fetching source migration information from %s: %s" %
6318
                 (source_node, msg))
6319
      logging.error(log_err)
6320
      raise errors.OpExecError(log_err)
6321

    
6322
    self.migration_info = migration_info = result.payload
6323

    
6324
    # Then switch the disks to master/master mode
6325
    self._EnsureSecondary(target_node)
6326
    self._GoStandalone()
6327
    self._GoReconnect(True)
6328
    self._WaitUntilSync()
6329

    
6330
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6331
    result = self.rpc.call_accept_instance(target_node,
6332
                                           instance,
6333
                                           migration_info,
6334
                                           self.nodes_ip[target_node])
6335

    
6336
    msg = result.fail_msg
6337
    if msg:
6338
      logging.error("Instance pre-migration failed, trying to revert"
6339
                    " disk status: %s", msg)
6340
      self.feedback_fn("Pre-migration failed, aborting")
6341
      self._AbortMigration()
6342
      self._RevertDiskStatus()
6343
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6344
                               (instance.name, msg))
6345

    
6346
    self.feedback_fn("* migrating instance to %s" % target_node)
6347
    time.sleep(10)
6348
    result = self.rpc.call_instance_migrate(source_node, instance,
6349
                                            self.nodes_ip[target_node],
6350
                                            self.live)
6351
    msg = result.fail_msg
6352
    if msg:
6353
      logging.error("Instance migration failed, trying to revert"
6354
                    " disk status: %s", msg)
6355
      self.feedback_fn("Migration failed, aborting")
6356
      self._AbortMigration()
6357
      self._RevertDiskStatus()
6358
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6359
                               (instance.name, msg))
6360
    time.sleep(10)
6361

    
6362
    instance.primary_node = target_node
6363
    # distribute new instance config to the other nodes
6364
    self.cfg.Update(instance, self.feedback_fn)
6365

    
6366
    result = self.rpc.call_finalize_migration(target_node,
6367
                                              instance,
6368
                                              migration_info,
6369
                                              True)
6370
    msg = result.fail_msg
6371
    if msg:
6372
      logging.error("Instance migration succeeded, but finalization failed:"
6373
                    " %s", msg)
6374
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6375
                               msg)
6376

    
6377
    self._EnsureSecondary(source_node)
6378
    self._WaitUntilSync()
6379
    self._GoStandalone()
6380
    self._GoReconnect(False)
6381
    self._WaitUntilSync()
6382

    
6383
    self.feedback_fn("* done")
6384

    
6385
  def Exec(self, feedback_fn):
6386
    """Perform the migration.
6387

6388
    """
6389
    feedback_fn("Migrating instance %s" % self.instance.name)
6390

    
6391
    self.feedback_fn = feedback_fn
6392

    
6393
    self.source_node = self.instance.primary_node
6394
    self.target_node = self.instance.secondary_nodes[0]
6395
    self.all_nodes = [self.source_node, self.target_node]
6396
    self.nodes_ip = {
6397
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6398
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6399
      }
6400

    
6401
    if self.cleanup:
6402
      return self._ExecCleanup()
6403
    else:
6404
      return self._ExecMigration()
6405

    
6406

    
6407
def _CreateBlockDev(lu, node, instance, device, force_create,
6408
                    info, force_open):
6409
  """Create a tree of block devices on a given node.
6410

6411
  If this device type has to be created on secondaries, create it and
6412
  all its children.
6413

6414
  If not, just recurse to children keeping the same 'force' value.
6415

6416
  @param lu: the lu on whose behalf we execute
6417
  @param node: the node on which to create the device
6418
  @type instance: L{objects.Instance}
6419
  @param instance: the instance which owns the device
6420
  @type device: L{objects.Disk}
6421
  @param device: the device to create
6422
  @type force_create: boolean
6423
  @param force_create: whether to force creation of this device; this
6424
      will be change to True whenever we find a device which has
6425
      CreateOnSecondary() attribute
6426
  @param info: the extra 'metadata' we should attach to the device
6427
      (this will be represented as a LVM tag)
6428
  @type force_open: boolean
6429
  @param force_open: this parameter will be passes to the
6430
      L{backend.BlockdevCreate} function where it specifies
6431
      whether we run on primary or not, and it affects both
6432
      the child assembly and the device own Open() execution
6433

6434
  """
6435
  if device.CreateOnSecondary():
6436
    force_create = True
6437

    
6438
  if device.children:
6439
    for child in device.children:
6440
      _CreateBlockDev(lu, node, instance, child, force_create,
6441
                      info, force_open)
6442

    
6443
  if not force_create:
6444
    return
6445

    
6446
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6447

    
6448

    
6449
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6450
  """Create a single block device on a given node.
6451

6452
  This will not recurse over children of the device, so they must be
6453
  created in advance.
6454

6455
  @param lu: the lu on whose behalf we execute
6456
  @param node: the node on which to create the device
6457
  @type instance: L{objects.Instance}
6458
  @param instance: the instance which owns the device
6459
  @type device: L{objects.Disk}
6460
  @param device: the device to create
6461
  @param info: the extra 'metadata' we should attach to the device
6462
      (this will be represented as a LVM tag)
6463
  @type force_open: boolean
6464
  @param force_open: this parameter will be passes to the
6465
      L{backend.BlockdevCreate} function where it specifies
6466
      whether we run on primary or not, and it affects both
6467
      the child assembly and the device own Open() execution
6468

6469
  """
6470
  lu.cfg.SetDiskID(device, node)
6471
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6472
                                       instance.name, force_open, info)
6473
  result.Raise("Can't create block device %s on"
6474
               " node %s for instance %s" % (device, node, instance.name))
6475
  if device.physical_id is None:
6476
    device.physical_id = result.payload
6477

    
6478

    
6479
def _GenerateUniqueNames(lu, exts):
6480
  """Generate a suitable LV name.
6481

6482
  This will generate a logical volume name for the given instance.
6483

6484
  """
6485
  results = []
6486
  for val in exts:
6487
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6488
    results.append("%s%s" % (new_id, val))
6489
  return results
6490

    
6491

    
6492
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
6493
                         p_minor, s_minor):
6494
  """Generate a drbd8 device complete with its children.
6495

6496
  """
6497
  port = lu.cfg.AllocatePort()
6498
  vgname = lu.cfg.GetVGName()
6499
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6500
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6501
                          logical_id=(vgname, names[0]))
6502
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6503
                          logical_id=(vgname, names[1]))
6504
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6505
                          logical_id=(primary, secondary, port,
6506
                                      p_minor, s_minor,
6507
                                      shared_secret),
6508
                          children=[dev_data, dev_meta],
6509
                          iv_name=iv_name)
6510
  return drbd_dev
6511

    
6512

    
6513
def _GenerateDiskTemplate(lu, template_name,
6514
                          instance_name, primary_node,
6515
                          secondary_nodes, disk_info,
6516
                          file_storage_dir, file_driver,
6517
                          base_index):
6518
  """Generate the entire disk layout for a given template type.
6519

6520
  """
6521
  #TODO: compute space requirements
6522

    
6523
  vgname = lu.cfg.GetVGName()
6524
  disk_count = len(disk_info)
6525
  disks = []
6526
  if template_name == constants.DT_DISKLESS:
6527
    pass
6528
  elif template_name == constants.DT_PLAIN:
6529
    if len(secondary_nodes) != 0:
6530
      raise errors.ProgrammerError("Wrong template configuration")
6531

    
6532
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6533
                                      for i in range(disk_count)])
6534
    for idx, disk in enumerate(disk_info):
6535
      disk_index = idx + base_index
6536
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6537
                              logical_id=(vgname, names[idx]),
6538
                              iv_name="disk/%d" % disk_index,
6539
                              mode=disk["mode"])
6540
      disks.append(disk_dev)
6541
  elif template_name == constants.DT_DRBD8:
6542
    if len(secondary_nodes) != 1:
6543
      raise errors.ProgrammerError("Wrong template configuration")
6544
    remote_node = secondary_nodes[0]
6545
    minors = lu.cfg.AllocateDRBDMinor(
6546
      [primary_node, remote_node] * len(disk_info), instance_name)
6547

    
6548
    names = []
6549
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6550
                                               for i in range(disk_count)]):
6551
      names.append(lv_prefix + "_data")
6552
      names.append(lv_prefix + "_meta")
6553
    for idx, disk in enumerate(disk_info):
6554
      disk_index = idx + base_index
6555
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6556
                                      disk["size"], names[idx*2:idx*2+2],
6557
                                      "disk/%d" % disk_index,
6558
                                      minors[idx*2], minors[idx*2+1])
6559
      disk_dev.mode = disk["mode"]
6560
      disks.append(disk_dev)
6561
  elif template_name == constants.DT_FILE:
6562
    if len(secondary_nodes) != 0:
6563
      raise errors.ProgrammerError("Wrong template configuration")
6564

    
6565
    _RequireFileStorage()
6566

    
6567
    for idx, disk in enumerate(disk_info):
6568
      disk_index = idx + base_index
6569
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6570
                              iv_name="disk/%d" % disk_index,
6571
                              logical_id=(file_driver,
6572
                                          "%s/disk%d" % (file_storage_dir,
6573
                                                         disk_index)),
6574
                              mode=disk["mode"])
6575
      disks.append(disk_dev)
6576
  else:
6577
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6578
  return disks
6579

    
6580

    
6581
def _GetInstanceInfoText(instance):
6582
  """Compute that text that should be added to the disk's metadata.
6583

6584
  """
6585
  return "originstname+%s" % instance.name
6586

    
6587

    
6588
def _CalcEta(time_taken, written, total_size):
6589
  """Calculates the ETA based on size written and total size.
6590

6591
  @param time_taken: The time taken so far
6592
  @param written: amount written so far
6593
  @param total_size: The total size of data to be written
6594
  @return: The remaining time in seconds
6595

6596
  """
6597
  avg_time = time_taken / float(written)
6598
  return (total_size - written) * avg_time
6599

    
6600

    
6601
def _WipeDisks(lu, instance):
6602
  """Wipes instance disks.
6603

6604
  @type lu: L{LogicalUnit}
6605
  @param lu: the logical unit on whose behalf we execute
6606
  @type instance: L{objects.Instance}
6607
  @param instance: the instance whose disks we should create
6608
  @return: the success of the wipe
6609

6610
  """
6611
  node = instance.primary_node
6612
  for idx, device in enumerate(instance.disks):
6613
    lu.LogInfo("* Wiping disk %d", idx)
6614
    logging.info("Wiping disk %d for instance %s", idx, instance.name)
6615

    
6616
    # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
6617
    # MAX_WIPE_CHUNK at max
6618
    wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
6619
                          constants.MIN_WIPE_CHUNK_PERCENT)
6620

    
6621
    offset = 0
6622
    size = device.size
6623
    last_output = 0
6624
    start_time = time.time()
6625

    
6626
    while offset < size:
6627
      wipe_size = min(wipe_chunk_size, size - offset)
6628
      result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
6629
      result.Raise("Could not wipe disk %d at offset %d for size %d" %
6630
                   (idx, offset, wipe_size))
6631
      now = time.time()
6632
      offset += wipe_size
6633
      if now - last_output >= 60:
6634
        eta = _CalcEta(now - start_time, offset, size)
6635
        lu.LogInfo(" - done: %.1f%% ETA: %s" %
6636
                   (offset / float(size) * 100, utils.FormatSeconds(eta)))
6637
        last_output = now
6638

    
6639

    
6640
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6641
  """Create all disks for an instance.
6642

6643
  This abstracts away some work from AddInstance.
6644

6645
  @type lu: L{LogicalUnit}
6646
  @param lu: the logical unit on whose behalf we execute
6647
  @type instance: L{objects.Instance}
6648
  @param instance: the instance whose disks we should create
6649
  @type to_skip: list
6650
  @param to_skip: list of indices to skip
6651
  @type target_node: string
6652
  @param target_node: if passed, overrides the target node for creation
6653
  @rtype: boolean
6654
  @return: the success of the creation
6655

6656
  """
6657
  info = _GetInstanceInfoText(instance)
6658
  if target_node is None:
6659
    pnode = instance.primary_node
6660
    all_nodes = instance.all_nodes
6661
  else:
6662
    pnode = target_node
6663
    all_nodes = [pnode]
6664

    
6665
  if instance.disk_template == constants.DT_FILE:
6666
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6667
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6668

    
6669
    result.Raise("Failed to create directory '%s' on"
6670
                 " node %s" % (file_storage_dir, pnode))
6671

    
6672
  # Note: this needs to be kept in sync with adding of disks in
6673
  # LUSetInstanceParams
6674
  for idx, device in enumerate(instance.disks):
6675
    if to_skip and idx in to_skip:
6676
      continue
6677
    logging.info("Creating volume %s for instance %s",
6678
                 device.iv_name, instance.name)
6679
    #HARDCODE
6680
    for node in all_nodes:
6681
      f_create = node == pnode
6682
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6683

    
6684

    
6685
def _RemoveDisks(lu, instance, target_node=None):
6686
  """Remove all disks for an instance.
6687

6688
  This abstracts away some work from `AddInstance()` and
6689
  `RemoveInstance()`. Note that in case some of the devices couldn't
6690
  be removed, the removal will continue with the other ones (compare
6691
  with `_CreateDisks()`).
6692

6693
  @type lu: L{LogicalUnit}
6694
  @param lu: the logical unit on whose behalf we execute
6695
  @type instance: L{objects.Instance}
6696
  @param instance: the instance whose disks we should remove
6697
  @type target_node: string
6698
  @param target_node: used to override the node on which to remove the disks
6699
  @rtype: boolean
6700
  @return: the success of the removal
6701

6702
  """
6703
  logging.info("Removing block devices for instance %s", instance.name)
6704

    
6705
  all_result = True
6706
  for device in instance.disks:
6707
    if target_node:
6708
      edata = [(target_node, device)]
6709
    else:
6710
      edata = device.ComputeNodeTree(instance.primary_node)
6711
    for node, disk in edata:
6712
      lu.cfg.SetDiskID(disk, node)
6713
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6714
      if msg:
6715
        lu.LogWarning("Could not remove block device %s on node %s,"
6716
                      " continuing anyway: %s", device.iv_name, node, msg)
6717
        all_result = False
6718

    
6719
  if instance.disk_template == constants.DT_FILE:
6720
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6721
    if target_node:
6722
      tgt = target_node
6723
    else:
6724
      tgt = instance.primary_node
6725
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6726
    if result.fail_msg:
6727
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6728
                    file_storage_dir, instance.primary_node, result.fail_msg)
6729
      all_result = False
6730

    
6731
  return all_result
6732

    
6733

    
6734
def _ComputeDiskSize(disk_template, disks):
6735
  """Compute disk size requirements in the volume group
6736

6737
  """
6738
  # Required free disk space as a function of disk and swap space
6739
  req_size_dict = {
6740
    constants.DT_DISKLESS: None,
6741
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6742
    # 128 MB are added for drbd metadata for each disk
6743
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6744
    constants.DT_FILE: None,
6745
  }
6746

    
6747
  if disk_template not in req_size_dict:
6748
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6749
                                 " is unknown" %  disk_template)
6750

    
6751
  return req_size_dict[disk_template]
6752

    
6753

    
6754
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6755
  """Hypervisor parameter validation.
6756

6757
  This function abstract the hypervisor parameter validation to be
6758
  used in both instance create and instance modify.
6759

6760
  @type lu: L{LogicalUnit}
6761
  @param lu: the logical unit for which we check
6762
  @type nodenames: list
6763
  @param nodenames: the list of nodes on which we should check
6764
  @type hvname: string
6765
  @param hvname: the name of the hypervisor we should use
6766
  @type hvparams: dict
6767
  @param hvparams: the parameters which we need to check
6768
  @raise errors.OpPrereqError: if the parameters are not valid
6769

6770
  """
6771
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6772
                                                  hvname,
6773
                                                  hvparams)
6774
  for node in nodenames:
6775
    info = hvinfo[node]
6776
    if info.offline:
6777
      continue
6778
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6779

    
6780

    
6781
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6782
  """OS parameters validation.
6783

6784
  @type lu: L{LogicalUnit}
6785
  @param lu: the logical unit for which we check
6786
  @type required: boolean
6787
  @param required: whether the validation should fail if the OS is not
6788
      found
6789
  @type nodenames: list
6790
  @param nodenames: the list of nodes on which we should check
6791
  @type osname: string
6792
  @param osname: the name of the hypervisor we should use
6793
  @type osparams: dict
6794
  @param osparams: the parameters which we need to check
6795
  @raise errors.OpPrereqError: if the parameters are not valid
6796

6797
  """
6798
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6799
                                   [constants.OS_VALIDATE_PARAMETERS],
6800
                                   osparams)
6801
  for node, nres in result.items():
6802
    # we don't check for offline cases since this should be run only
6803
    # against the master node and/or an instance's nodes
6804
    nres.Raise("OS Parameters validation failed on node %s" % node)
6805
    if not nres.payload:
6806
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6807
                 osname, node)
6808

    
6809

    
6810
class LUCreateInstance(LogicalUnit):
6811
  """Create an instance.
6812

6813
  """
6814
  HPATH = "instance-add"
6815
  HTYPE = constants.HTYPE_INSTANCE
6816
  _OP_PARAMS = [
6817
    _PInstanceName,
6818
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES)),
6819
    ("start", True, ht.TBool),
6820
    ("wait_for_sync", True, ht.TBool),
6821
    ("ip_check", True, ht.TBool),
6822
    ("name_check", True, ht.TBool),
6823
    ("disks", ht.NoDefault, ht.TListOf(ht.TDict)),
6824
    ("nics", ht.NoDefault, ht.TListOf(ht.TDict)),
6825
    ("hvparams", ht.EmptyDict, ht.TDict),
6826
    ("beparams", ht.EmptyDict, ht.TDict),
6827
    ("osparams", ht.EmptyDict, ht.TDict),
6828
    ("no_install", None, ht.TMaybeBool),
6829
    ("os_type", None, ht.TMaybeString),
6830
    ("force_variant", False, ht.TBool),
6831
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone)),
6832
    ("source_x509_ca", None, ht.TMaybeString),
6833
    ("source_instance_name", None, ht.TMaybeString),
6834
    ("src_node", None, ht.TMaybeString),
6835
    ("src_path", None, ht.TMaybeString),
6836
    ("pnode", None, ht.TMaybeString),
6837
    ("snode", None, ht.TMaybeString),
6838
    ("iallocator", None, ht.TMaybeString),
6839
    ("hypervisor", None, ht.TMaybeString),
6840
    ("disk_template", ht.NoDefault, _CheckDiskTemplate),
6841
    ("identify_defaults", False, ht.TBool),
6842
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER))),
6843
    ("file_storage_dir", None, ht.TMaybeString),
6844
    ]
6845
  REQ_BGL = False
6846

    
6847
  def CheckArguments(self):
6848
    """Check arguments.
6849

6850
    """
6851
    # do not require name_check to ease forward/backward compatibility
6852
    # for tools
6853
    if self.op.no_install and self.op.start:
6854
      self.LogInfo("No-installation mode selected, disabling startup")
6855
      self.op.start = False
6856
    # validate/normalize the instance name
6857
    self.op.instance_name = \
6858
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
6859

    
6860
    if self.op.ip_check and not self.op.name_check:
6861
      # TODO: make the ip check more flexible and not depend on the name check
6862
      raise errors.OpPrereqError("Cannot do ip check without a name check",
6863
                                 errors.ECODE_INVAL)
6864

    
6865
    # check nics' parameter names
6866
    for nic in self.op.nics:
6867
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6868

    
6869
    # check disks. parameter names and consistent adopt/no-adopt strategy
6870
    has_adopt = has_no_adopt = False
6871
    for disk in self.op.disks:
6872
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6873
      if "adopt" in disk:
6874
        has_adopt = True
6875
      else:
6876
        has_no_adopt = True
6877
    if has_adopt and has_no_adopt:
6878
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6879
                                 errors.ECODE_INVAL)
6880
    if has_adopt:
6881
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6882
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6883
                                   " '%s' disk template" %
6884
                                   self.op.disk_template,
6885
                                   errors.ECODE_INVAL)
6886
      if self.op.iallocator is not None:
6887
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6888
                                   " iallocator script", errors.ECODE_INVAL)
6889
      if self.op.mode == constants.INSTANCE_IMPORT:
6890
        raise errors.OpPrereqError("Disk adoption not allowed for"
6891
                                   " instance import", errors.ECODE_INVAL)
6892

    
6893
    self.adopt_disks = has_adopt
6894

    
6895
    # instance name verification
6896
    if self.op.name_check:
6897
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
6898
      self.op.instance_name = self.hostname1.name
6899
      # used in CheckPrereq for ip ping check
6900
      self.check_ip = self.hostname1.ip
6901
    else:
6902
      self.check_ip = None
6903

    
6904
    # file storage checks
6905
    if (self.op.file_driver and
6906
        not self.op.file_driver in constants.FILE_DRIVER):
6907
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6908
                                 self.op.file_driver, errors.ECODE_INVAL)
6909

    
6910
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6911
      raise errors.OpPrereqError("File storage directory path not absolute",
6912
                                 errors.ECODE_INVAL)
6913

    
6914
    ### Node/iallocator related checks
6915
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
6916

    
6917
    if self.op.pnode is not None:
6918
      if self.op.disk_template in constants.DTS_NET_MIRROR:
6919
        if self.op.snode is None:
6920
          raise errors.OpPrereqError("The networked disk templates need"
6921
                                     " a mirror node", errors.ECODE_INVAL)
6922
      elif self.op.snode:
6923
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
6924
                        " template")
6925
        self.op.snode = None
6926

    
6927
    self._cds = _GetClusterDomainSecret()
6928

    
6929
    if self.op.mode == constants.INSTANCE_IMPORT:
6930
      # On import force_variant must be True, because if we forced it at
6931
      # initial install, our only chance when importing it back is that it
6932
      # works again!
6933
      self.op.force_variant = True
6934

    
6935
      if self.op.no_install:
6936
        self.LogInfo("No-installation mode has no effect during import")
6937

    
6938
    elif self.op.mode == constants.INSTANCE_CREATE:
6939
      if self.op.os_type is None:
6940
        raise errors.OpPrereqError("No guest OS specified",
6941
                                   errors.ECODE_INVAL)
6942
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
6943
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
6944
                                   " installation" % self.op.os_type,
6945
                                   errors.ECODE_STATE)
6946
      if self.op.disk_template is None:
6947
        raise errors.OpPrereqError("No disk template specified",
6948
                                   errors.ECODE_INVAL)
6949

    
6950
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6951
      # Check handshake to ensure both clusters have the same domain secret
6952
      src_handshake = self.op.source_handshake
6953
      if not src_handshake:
6954
        raise errors.OpPrereqError("Missing source handshake",
6955
                                   errors.ECODE_INVAL)
6956

    
6957
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6958
                                                           src_handshake)
6959
      if errmsg:
6960
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6961
                                   errors.ECODE_INVAL)
6962

    
6963
      # Load and check source CA
6964
      self.source_x509_ca_pem = self.op.source_x509_ca
6965
      if not self.source_x509_ca_pem:
6966
        raise errors.OpPrereqError("Missing source X509 CA",
6967
                                   errors.ECODE_INVAL)
6968

    
6969
      try:
6970
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
6971
                                                    self._cds)
6972
      except OpenSSL.crypto.Error, err:
6973
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
6974
                                   (err, ), errors.ECODE_INVAL)
6975

    
6976
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
6977
      if errcode is not None:
6978
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
6979
                                   errors.ECODE_INVAL)
6980

    
6981
      self.source_x509_ca = cert
6982

    
6983
      src_instance_name = self.op.source_instance_name
6984
      if not src_instance_name:
6985
        raise errors.OpPrereqError("Missing source instance name",
6986
                                   errors.ECODE_INVAL)
6987

    
6988
      self.source_instance_name = \
6989
          netutils.GetHostname(name=src_instance_name).name
6990

    
6991
    else:
6992
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
6993
                                 self.op.mode, errors.ECODE_INVAL)
6994

    
6995
  def ExpandNames(self):
6996
    """ExpandNames for CreateInstance.
6997

6998
    Figure out the right locks for instance creation.
6999

7000
    """
7001
    self.needed_locks = {}
7002

    
7003
    instance_name = self.op.instance_name
7004
    # this is just a preventive check, but someone might still add this
7005
    # instance in the meantime, and creation will fail at lock-add time
7006
    if instance_name in self.cfg.GetInstanceList():
7007
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
7008
                                 instance_name, errors.ECODE_EXISTS)
7009

    
7010
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
7011

    
7012
    if self.op.iallocator:
7013
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7014
    else:
7015
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
7016
      nodelist = [self.op.pnode]
7017
      if self.op.snode is not None:
7018
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
7019
        nodelist.append(self.op.snode)
7020
      self.needed_locks[locking.LEVEL_NODE] = nodelist
7021

    
7022
    # in case of import lock the source node too
7023
    if self.op.mode == constants.INSTANCE_IMPORT:
7024
      src_node = self.op.src_node
7025
      src_path = self.op.src_path
7026

    
7027
      if src_path is None:
7028
        self.op.src_path = src_path = self.op.instance_name
7029

    
7030
      if src_node is None:
7031
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7032
        self.op.src_node = None
7033
        if os.path.isabs(src_path):
7034
          raise errors.OpPrereqError("Importing an instance from an absolute"
7035
                                     " path requires a source node option.",
7036
                                     errors.ECODE_INVAL)
7037
      else:
7038
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
7039
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
7040
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
7041
        if not os.path.isabs(src_path):
7042
          self.op.src_path = src_path = \
7043
            utils.PathJoin(constants.EXPORT_DIR, src_path)
7044

    
7045
  def _RunAllocator(self):
7046
    """Run the allocator based on input opcode.
7047

7048
    """
7049
    nics = [n.ToDict() for n in self.nics]
7050
    ial = IAllocator(self.cfg, self.rpc,
7051
                     mode=constants.IALLOCATOR_MODE_ALLOC,
7052
                     name=self.op.instance_name,
7053
                     disk_template=self.op.disk_template,
7054
                     tags=[],
7055
                     os=self.op.os_type,
7056
                     vcpus=self.be_full[constants.BE_VCPUS],
7057
                     mem_size=self.be_full[constants.BE_MEMORY],
7058
                     disks=self.disks,
7059
                     nics=nics,
7060
                     hypervisor=self.op.hypervisor,
7061
                     )
7062

    
7063
    ial.Run(self.op.iallocator)
7064

    
7065
    if not ial.success:
7066
      raise errors.OpPrereqError("Can't compute nodes using"
7067
                                 " iallocator '%s': %s" %
7068
                                 (self.op.iallocator, ial.info),
7069
                                 errors.ECODE_NORES)
7070
    if len(ial.result) != ial.required_nodes:
7071
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7072
                                 " of nodes (%s), required %s" %
7073
                                 (self.op.iallocator, len(ial.result),
7074
                                  ial.required_nodes), errors.ECODE_FAULT)
7075
    self.op.pnode = ial.result[0]
7076
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
7077
                 self.op.instance_name, self.op.iallocator,
7078
                 utils.CommaJoin(ial.result))
7079
    if ial.required_nodes == 2:
7080
      self.op.snode = ial.result[1]
7081

    
7082
  def BuildHooksEnv(self):
7083
    """Build hooks env.
7084

7085
    This runs on master, primary and secondary nodes of the instance.
7086

7087
    """
7088
    env = {
7089
      "ADD_MODE": self.op.mode,
7090
      }
7091
    if self.op.mode == constants.INSTANCE_IMPORT:
7092
      env["SRC_NODE"] = self.op.src_node
7093
      env["SRC_PATH"] = self.op.src_path
7094
      env["SRC_IMAGES"] = self.src_images
7095

    
7096
    env.update(_BuildInstanceHookEnv(
7097
      name=self.op.instance_name,
7098
      primary_node=self.op.pnode,
7099
      secondary_nodes=self.secondaries,
7100
      status=self.op.start,
7101
      os_type=self.op.os_type,
7102
      memory=self.be_full[constants.BE_MEMORY],
7103
      vcpus=self.be_full[constants.BE_VCPUS],
7104
      nics=_NICListToTuple(self, self.nics),
7105
      disk_template=self.op.disk_template,
7106
      disks=[(d["size"], d["mode"]) for d in self.disks],
7107
      bep=self.be_full,
7108
      hvp=self.hv_full,
7109
      hypervisor_name=self.op.hypervisor,
7110
    ))
7111

    
7112
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
7113
          self.secondaries)
7114
    return env, nl, nl
7115

    
7116
  def _ReadExportInfo(self):
7117
    """Reads the export information from disk.
7118

7119
    It will override the opcode source node and path with the actual
7120
    information, if these two were not specified before.
7121

7122
    @return: the export information
7123

7124
    """
7125
    assert self.op.mode == constants.INSTANCE_IMPORT
7126

    
7127
    src_node = self.op.src_node
7128
    src_path = self.op.src_path
7129

    
7130
    if src_node is None:
7131
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
7132
      exp_list = self.rpc.call_export_list(locked_nodes)
7133
      found = False
7134
      for node in exp_list:
7135
        if exp_list[node].fail_msg:
7136
          continue
7137
        if src_path in exp_list[node].payload:
7138
          found = True
7139
          self.op.src_node = src_node = node
7140
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
7141
                                                       src_path)
7142
          break
7143
      if not found:
7144
        raise errors.OpPrereqError("No export found for relative path %s" %
7145
                                    src_path, errors.ECODE_INVAL)
7146

    
7147
    _CheckNodeOnline(self, src_node)
7148
    result = self.rpc.call_export_info(src_node, src_path)
7149
    result.Raise("No export or invalid export found in dir %s" % src_path)
7150

    
7151
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
7152
    if not export_info.has_section(constants.INISECT_EXP):
7153
      raise errors.ProgrammerError("Corrupted export config",
7154
                                   errors.ECODE_ENVIRON)
7155

    
7156
    ei_version = export_info.get(constants.INISECT_EXP, "version")
7157
    if (int(ei_version) != constants.EXPORT_VERSION):
7158
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
7159
                                 (ei_version, constants.EXPORT_VERSION),
7160
                                 errors.ECODE_ENVIRON)
7161
    return export_info
7162

    
7163
  def _ReadExportParams(self, einfo):
7164
    """Use export parameters as defaults.
7165

7166
    In case the opcode doesn't specify (as in override) some instance
7167
    parameters, then try to use them from the export information, if
7168
    that declares them.
7169

7170
    """
7171
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
7172

    
7173
    if self.op.disk_template is None:
7174
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
7175
        self.op.disk_template = einfo.get(constants.INISECT_INS,
7176
                                          "disk_template")
7177
      else:
7178
        raise errors.OpPrereqError("No disk template specified and the export"
7179
                                   " is missing the disk_template information",
7180
                                   errors.ECODE_INVAL)
7181

    
7182
    if not self.op.disks:
7183
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
7184
        disks = []
7185
        # TODO: import the disk iv_name too
7186
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
7187
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
7188
          disks.append({"size": disk_sz})
7189
        self.op.disks = disks
7190
      else:
7191
        raise errors.OpPrereqError("No disk info specified and the export"
7192
                                   " is missing the disk information",
7193
                                   errors.ECODE_INVAL)
7194

    
7195
    if (not self.op.nics and
7196
        einfo.has_option(constants.INISECT_INS, "nic_count")):
7197
      nics = []
7198
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
7199
        ndict = {}
7200
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
7201
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
7202
          ndict[name] = v
7203
        nics.append(ndict)
7204
      self.op.nics = nics
7205

    
7206
    if (self.op.hypervisor is None and
7207
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
7208
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
7209
    if einfo.has_section(constants.INISECT_HYP):
7210
      # use the export parameters but do not override the ones
7211
      # specified by the user
7212
      for name, value in einfo.items(constants.INISECT_HYP):
7213
        if name not in self.op.hvparams:
7214
          self.op.hvparams[name] = value
7215

    
7216
    if einfo.has_section(constants.INISECT_BEP):
7217
      # use the parameters, without overriding
7218
      for name, value in einfo.items(constants.INISECT_BEP):
7219
        if name not in self.op.beparams:
7220
          self.op.beparams[name] = value
7221
    else:
7222
      # try to read the parameters old style, from the main section
7223
      for name in constants.BES_PARAMETERS:
7224
        if (name not in self.op.beparams and
7225
            einfo.has_option(constants.INISECT_INS, name)):
7226
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
7227

    
7228
    if einfo.has_section(constants.INISECT_OSP):
7229
      # use the parameters, without overriding
7230
      for name, value in einfo.items(constants.INISECT_OSP):
7231
        if name not in self.op.osparams:
7232
          self.op.osparams[name] = value
7233

    
7234
  def _RevertToDefaults(self, cluster):
7235
    """Revert the instance parameters to the default values.
7236

7237
    """
7238
    # hvparams
7239
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
7240
    for name in self.op.hvparams.keys():
7241
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
7242
        del self.op.hvparams[name]
7243
    # beparams
7244
    be_defs = cluster.SimpleFillBE({})
7245
    for name in self.op.beparams.keys():
7246
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
7247
        del self.op.beparams[name]
7248
    # nic params
7249
    nic_defs = cluster.SimpleFillNIC({})
7250
    for nic in self.op.nics:
7251
      for name in constants.NICS_PARAMETERS:
7252
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
7253
          del nic[name]
7254
    # osparams
7255
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
7256
    for name in self.op.osparams.keys():
7257
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
7258
        del self.op.osparams[name]
7259

    
7260
  def CheckPrereq(self):
7261
    """Check prerequisites.
7262

7263
    """
7264
    if self.op.mode == constants.INSTANCE_IMPORT:
7265
      export_info = self._ReadExportInfo()
7266
      self._ReadExportParams(export_info)
7267

    
7268
    _CheckDiskTemplate(self.op.disk_template)
7269

    
7270
    if (not self.cfg.GetVGName() and
7271
        self.op.disk_template not in constants.DTS_NOT_LVM):
7272
      raise errors.OpPrereqError("Cluster does not support lvm-based"
7273
                                 " instances", errors.ECODE_STATE)
7274

    
7275
    if self.op.hypervisor is None:
7276
      self.op.hypervisor = self.cfg.GetHypervisorType()
7277

    
7278
    cluster = self.cfg.GetClusterInfo()
7279
    enabled_hvs = cluster.enabled_hypervisors
7280
    if self.op.hypervisor not in enabled_hvs:
7281
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
7282
                                 " cluster (%s)" % (self.op.hypervisor,
7283
                                  ",".join(enabled_hvs)),
7284
                                 errors.ECODE_STATE)
7285

    
7286
    # check hypervisor parameter syntax (locally)
7287
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
7288
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
7289
                                      self.op.hvparams)
7290
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
7291
    hv_type.CheckParameterSyntax(filled_hvp)
7292
    self.hv_full = filled_hvp
7293
    # check that we don't specify global parameters on an instance
7294
    _CheckGlobalHvParams(self.op.hvparams)
7295

    
7296
    # fill and remember the beparams dict
7297
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
7298
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
7299

    
7300
    # build os parameters
7301
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
7302

    
7303
    # now that hvp/bep are in final format, let's reset to defaults,
7304
    # if told to do so
7305
    if self.op.identify_defaults:
7306
      self._RevertToDefaults(cluster)
7307

    
7308
    # NIC buildup
7309
    self.nics = []
7310
    for idx, nic in enumerate(self.op.nics):
7311
      nic_mode_req = nic.get("mode", None)
7312
      nic_mode = nic_mode_req
7313
      if nic_mode is None:
7314
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
7315

    
7316
      # in routed mode, for the first nic, the default ip is 'auto'
7317
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
7318
        default_ip_mode = constants.VALUE_AUTO
7319
      else:
7320
        default_ip_mode = constants.VALUE_NONE
7321

    
7322
      # ip validity checks
7323
      ip = nic.get("ip", default_ip_mode)
7324
      if ip is None or ip.lower() == constants.VALUE_NONE:
7325
        nic_ip = None
7326
      elif ip.lower() == constants.VALUE_AUTO:
7327
        if not self.op.name_check:
7328
          raise errors.OpPrereqError("IP address set to auto but name checks"
7329
                                     " have been skipped",
7330
                                     errors.ECODE_INVAL)
7331
        nic_ip = self.hostname1.ip
7332
      else:
7333
        if not netutils.IPAddress.IsValid(ip):
7334
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
7335
                                     errors.ECODE_INVAL)
7336
        nic_ip = ip
7337

    
7338
      # TODO: check the ip address for uniqueness
7339
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7340
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7341
                                   errors.ECODE_INVAL)
7342

    
7343
      # MAC address verification
7344
      mac = nic.get("mac", constants.VALUE_AUTO)
7345
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7346
        mac = utils.NormalizeAndValidateMac(mac)
7347

    
7348
        try:
7349
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7350
        except errors.ReservationError:
7351
          raise errors.OpPrereqError("MAC address %s already in use"
7352
                                     " in cluster" % mac,
7353
                                     errors.ECODE_NOTUNIQUE)
7354

    
7355
      # bridge verification
7356
      bridge = nic.get("bridge", None)
7357
      link = nic.get("link", None)
7358
      if bridge and link:
7359
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7360
                                   " at the same time", errors.ECODE_INVAL)
7361
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7362
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7363
                                   errors.ECODE_INVAL)
7364
      elif bridge:
7365
        link = bridge
7366

    
7367
      nicparams = {}
7368
      if nic_mode_req:
7369
        nicparams[constants.NIC_MODE] = nic_mode_req
7370
      if link:
7371
        nicparams[constants.NIC_LINK] = link
7372

    
7373
      check_params = cluster.SimpleFillNIC(nicparams)
7374
      objects.NIC.CheckParameterSyntax(check_params)
7375
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7376

    
7377
    # disk checks/pre-build
7378
    self.disks = []
7379
    for disk in self.op.disks:
7380
      mode = disk.get("mode", constants.DISK_RDWR)
7381
      if mode not in constants.DISK_ACCESS_SET:
7382
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7383
                                   mode, errors.ECODE_INVAL)
7384
      size = disk.get("size", None)
7385
      if size is None:
7386
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7387
      try:
7388
        size = int(size)
7389
      except (TypeError, ValueError):
7390
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7391
                                   errors.ECODE_INVAL)
7392
      new_disk = {"size": size, "mode": mode}
7393
      if "adopt" in disk:
7394
        new_disk["adopt"] = disk["adopt"]
7395
      self.disks.append(new_disk)
7396

    
7397
    if self.op.mode == constants.INSTANCE_IMPORT:
7398

    
7399
      # Check that the new instance doesn't have less disks than the export
7400
      instance_disks = len(self.disks)
7401
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7402
      if instance_disks < export_disks:
7403
        raise errors.OpPrereqError("Not enough disks to import."
7404
                                   " (instance: %d, export: %d)" %
7405
                                   (instance_disks, export_disks),
7406
                                   errors.ECODE_INVAL)
7407

    
7408
      disk_images = []
7409
      for idx in range(export_disks):
7410
        option = 'disk%d_dump' % idx
7411
        if export_info.has_option(constants.INISECT_INS, option):
7412
          # FIXME: are the old os-es, disk sizes, etc. useful?
7413
          export_name = export_info.get(constants.INISECT_INS, option)
7414
          image = utils.PathJoin(self.op.src_path, export_name)
7415
          disk_images.append(image)
7416
        else:
7417
          disk_images.append(False)
7418

    
7419
      self.src_images = disk_images
7420

    
7421
      old_name = export_info.get(constants.INISECT_INS, 'name')
7422
      try:
7423
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7424
      except (TypeError, ValueError), err:
7425
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7426
                                   " an integer: %s" % str(err),
7427
                                   errors.ECODE_STATE)
7428
      if self.op.instance_name == old_name:
7429
        for idx, nic in enumerate(self.nics):
7430
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7431
            nic_mac_ini = 'nic%d_mac' % idx
7432
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7433

    
7434
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7435

    
7436
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7437
    if self.op.ip_check:
7438
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7439
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7440
                                   (self.check_ip, self.op.instance_name),
7441
                                   errors.ECODE_NOTUNIQUE)
7442

    
7443
    #### mac address generation
7444
    # By generating here the mac address both the allocator and the hooks get
7445
    # the real final mac address rather than the 'auto' or 'generate' value.
7446
    # There is a race condition between the generation and the instance object
7447
    # creation, which means that we know the mac is valid now, but we're not
7448
    # sure it will be when we actually add the instance. If things go bad
7449
    # adding the instance will abort because of a duplicate mac, and the
7450
    # creation job will fail.
7451
    for nic in self.nics:
7452
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7453
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7454

    
7455
    #### allocator run
7456

    
7457
    if self.op.iallocator is not None:
7458
      self._RunAllocator()
7459

    
7460
    #### node related checks
7461

    
7462
    # check primary node
7463
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7464
    assert self.pnode is not None, \
7465
      "Cannot retrieve locked node %s" % self.op.pnode
7466
    if pnode.offline:
7467
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7468
                                 pnode.name, errors.ECODE_STATE)
7469
    if pnode.drained:
7470
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7471
                                 pnode.name, errors.ECODE_STATE)
7472
    if not pnode.vm_capable:
7473
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
7474
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
7475

    
7476
    self.secondaries = []
7477

    
7478
    # mirror node verification
7479
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7480
      if self.op.snode == pnode.name:
7481
        raise errors.OpPrereqError("The secondary node cannot be the"
7482
                                   " primary node.", errors.ECODE_INVAL)
7483
      _CheckNodeOnline(self, self.op.snode)
7484
      _CheckNodeNotDrained(self, self.op.snode)
7485
      _CheckNodeVmCapable(self, self.op.snode)
7486
      self.secondaries.append(self.op.snode)
7487

    
7488
    nodenames = [pnode.name] + self.secondaries
7489

    
7490
    req_size = _ComputeDiskSize(self.op.disk_template,
7491
                                self.disks)
7492

    
7493
    # Check lv size requirements, if not adopting
7494
    if req_size is not None and not self.adopt_disks:
7495
      _CheckNodesFreeDisk(self, nodenames, req_size)
7496

    
7497
    if self.adopt_disks: # instead, we must check the adoption data
7498
      all_lvs = set([i["adopt"] for i in self.disks])
7499
      if len(all_lvs) != len(self.disks):
7500
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7501
                                   errors.ECODE_INVAL)
7502
      for lv_name in all_lvs:
7503
        try:
7504
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7505
        except errors.ReservationError:
7506
          raise errors.OpPrereqError("LV named %s used by another instance" %
7507
                                     lv_name, errors.ECODE_NOTUNIQUE)
7508

    
7509
      node_lvs = self.rpc.call_lv_list([pnode.name],
7510
                                       self.cfg.GetVGName())[pnode.name]
7511
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7512
      node_lvs = node_lvs.payload
7513
      delta = all_lvs.difference(node_lvs.keys())
7514
      if delta:
7515
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7516
                                   utils.CommaJoin(delta),
7517
                                   errors.ECODE_INVAL)
7518
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7519
      if online_lvs:
7520
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7521
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7522
                                   errors.ECODE_STATE)
7523
      # update the size of disk based on what is found
7524
      for dsk in self.disks:
7525
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
7526

    
7527
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7528

    
7529
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7530
    # check OS parameters (remotely)
7531
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7532

    
7533
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7534

    
7535
    # memory check on primary node
7536
    if self.op.start:
7537
      _CheckNodeFreeMemory(self, self.pnode.name,
7538
                           "creating instance %s" % self.op.instance_name,
7539
                           self.be_full[constants.BE_MEMORY],
7540
                           self.op.hypervisor)
7541

    
7542
    self.dry_run_result = list(nodenames)
7543

    
7544
  def Exec(self, feedback_fn):
7545
    """Create and add the instance to the cluster.
7546

7547
    """
7548
    instance = self.op.instance_name
7549
    pnode_name = self.pnode.name
7550

    
7551
    ht_kind = self.op.hypervisor
7552
    if ht_kind in constants.HTS_REQ_PORT:
7553
      network_port = self.cfg.AllocatePort()
7554
    else:
7555
      network_port = None
7556

    
7557
    if constants.ENABLE_FILE_STORAGE:
7558
      # this is needed because os.path.join does not accept None arguments
7559
      if self.op.file_storage_dir is None:
7560
        string_file_storage_dir = ""
7561
      else:
7562
        string_file_storage_dir = self.op.file_storage_dir
7563

    
7564
      # build the full file storage dir path
7565
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7566
                                        string_file_storage_dir, instance)
7567
    else:
7568
      file_storage_dir = ""
7569

    
7570
    disks = _GenerateDiskTemplate(self,
7571
                                  self.op.disk_template,
7572
                                  instance, pnode_name,
7573
                                  self.secondaries,
7574
                                  self.disks,
7575
                                  file_storage_dir,
7576
                                  self.op.file_driver,
7577
                                  0)
7578

    
7579
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7580
                            primary_node=pnode_name,
7581
                            nics=self.nics, disks=disks,
7582
                            disk_template=self.op.disk_template,
7583
                            admin_up=False,
7584
                            network_port=network_port,
7585
                            beparams=self.op.beparams,
7586
                            hvparams=self.op.hvparams,
7587
                            hypervisor=self.op.hypervisor,
7588
                            osparams=self.op.osparams,
7589
                            )
7590

    
7591
    if self.adopt_disks:
7592
      # rename LVs to the newly-generated names; we need to construct
7593
      # 'fake' LV disks with the old data, plus the new unique_id
7594
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7595
      rename_to = []
7596
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7597
        rename_to.append(t_dsk.logical_id)
7598
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7599
        self.cfg.SetDiskID(t_dsk, pnode_name)
7600
      result = self.rpc.call_blockdev_rename(pnode_name,
7601
                                             zip(tmp_disks, rename_to))
7602
      result.Raise("Failed to rename adoped LVs")
7603
    else:
7604
      feedback_fn("* creating instance disks...")
7605
      try:
7606
        _CreateDisks(self, iobj)
7607
      except errors.OpExecError:
7608
        self.LogWarning("Device creation failed, reverting...")
7609
        try:
7610
          _RemoveDisks(self, iobj)
7611
        finally:
7612
          self.cfg.ReleaseDRBDMinors(instance)
7613
          raise
7614

    
7615
      if self.cfg.GetClusterInfo().prealloc_wipe_disks:
7616
        feedback_fn("* wiping instance disks...")
7617
        try:
7618
          _WipeDisks(self, iobj)
7619
        except errors.OpExecError:
7620
          self.LogWarning("Device wiping failed, reverting...")
7621
          try:
7622
            _RemoveDisks(self, iobj)
7623
          finally:
7624
            self.cfg.ReleaseDRBDMinors(instance)
7625
            raise
7626

    
7627
    feedback_fn("adding instance %s to cluster config" % instance)
7628

    
7629
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7630

    
7631
    # Declare that we don't want to remove the instance lock anymore, as we've
7632
    # added the instance to the config
7633
    del self.remove_locks[locking.LEVEL_INSTANCE]
7634
    # Unlock all the nodes
7635
    if self.op.mode == constants.INSTANCE_IMPORT:
7636
      nodes_keep = [self.op.src_node]
7637
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7638
                       if node != self.op.src_node]
7639
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7640
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7641
    else:
7642
      self.context.glm.release(locking.LEVEL_NODE)
7643
      del self.acquired_locks[locking.LEVEL_NODE]
7644

    
7645
    if self.op.wait_for_sync:
7646
      disk_abort = not _WaitForSync(self, iobj)
7647
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7648
      # make sure the disks are not degraded (still sync-ing is ok)
7649
      time.sleep(15)
7650
      feedback_fn("* checking mirrors status")
7651
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7652
    else:
7653
      disk_abort = False
7654

    
7655
    if disk_abort:
7656
      _RemoveDisks(self, iobj)
7657
      self.cfg.RemoveInstance(iobj.name)
7658
      # Make sure the instance lock gets removed
7659
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7660
      raise errors.OpExecError("There are some degraded disks for"
7661
                               " this instance")
7662

    
7663
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7664
      if self.op.mode == constants.INSTANCE_CREATE:
7665
        if not self.op.no_install:
7666
          feedback_fn("* running the instance OS create scripts...")
7667
          # FIXME: pass debug option from opcode to backend
7668
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7669
                                                 self.op.debug_level)
7670
          result.Raise("Could not add os for instance %s"
7671
                       " on node %s" % (instance, pnode_name))
7672

    
7673
      elif self.op.mode == constants.INSTANCE_IMPORT:
7674
        feedback_fn("* running the instance OS import scripts...")
7675

    
7676
        transfers = []
7677

    
7678
        for idx, image in enumerate(self.src_images):
7679
          if not image:
7680
            continue
7681

    
7682
          # FIXME: pass debug option from opcode to backend
7683
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7684
                                             constants.IEIO_FILE, (image, ),
7685
                                             constants.IEIO_SCRIPT,
7686
                                             (iobj.disks[idx], idx),
7687
                                             None)
7688
          transfers.append(dt)
7689

    
7690
        import_result = \
7691
          masterd.instance.TransferInstanceData(self, feedback_fn,
7692
                                                self.op.src_node, pnode_name,
7693
                                                self.pnode.secondary_ip,
7694
                                                iobj, transfers)
7695
        if not compat.all(import_result):
7696
          self.LogWarning("Some disks for instance %s on node %s were not"
7697
                          " imported successfully" % (instance, pnode_name))
7698

    
7699
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7700
        feedback_fn("* preparing remote import...")
7701
        connect_timeout = constants.RIE_CONNECT_TIMEOUT
7702
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7703

    
7704
        disk_results = masterd.instance.RemoteImport(self, feedback_fn, iobj,
7705
                                                     self.source_x509_ca,
7706
                                                     self._cds, timeouts)
7707
        if not compat.all(disk_results):
7708
          # TODO: Should the instance still be started, even if some disks
7709
          # failed to import (valid for local imports, too)?
7710
          self.LogWarning("Some disks for instance %s on node %s were not"
7711
                          " imported successfully" % (instance, pnode_name))
7712

    
7713
        # Run rename script on newly imported instance
7714
        assert iobj.name == instance
7715
        feedback_fn("Running rename script for %s" % instance)
7716
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7717
                                                   self.source_instance_name,
7718
                                                   self.op.debug_level)
7719
        if result.fail_msg:
7720
          self.LogWarning("Failed to run rename script for %s on node"
7721
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7722

    
7723
      else:
7724
        # also checked in the prereq part
7725
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7726
                                     % self.op.mode)
7727

    
7728
    if self.op.start:
7729
      iobj.admin_up = True
7730
      self.cfg.Update(iobj, feedback_fn)
7731
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7732
      feedback_fn("* starting instance...")
7733
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7734
      result.Raise("Could not start instance")
7735

    
7736
    return list(iobj.all_nodes)
7737

    
7738

    
7739
class LUConnectConsole(NoHooksLU):
7740
  """Connect to an instance's console.
7741

7742
  This is somewhat special in that it returns the command line that
7743
  you need to run on the master node in order to connect to the
7744
  console.
7745

7746
  """
7747
  _OP_PARAMS = [
7748
    _PInstanceName
7749
    ]
7750
  REQ_BGL = False
7751

    
7752
  def ExpandNames(self):
7753
    self._ExpandAndLockInstance()
7754

    
7755
  def CheckPrereq(self):
7756
    """Check prerequisites.
7757

7758
    This checks that the instance is in the cluster.
7759

7760
    """
7761
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7762
    assert self.instance is not None, \
7763
      "Cannot retrieve locked instance %s" % self.op.instance_name
7764
    _CheckNodeOnline(self, self.instance.primary_node)
7765

    
7766
  def Exec(self, feedback_fn):
7767
    """Connect to the console of an instance
7768

7769
    """
7770
    instance = self.instance
7771
    node = instance.primary_node
7772

    
7773
    node_insts = self.rpc.call_instance_list([node],
7774
                                             [instance.hypervisor])[node]
7775
    node_insts.Raise("Can't get node information from %s" % node)
7776

    
7777
    if instance.name not in node_insts.payload:
7778
      if instance.admin_up:
7779
        state = "ERROR_down"
7780
      else:
7781
        state = "ADMIN_down"
7782
      raise errors.OpExecError("Instance %s is not running (state %s)" %
7783
                               (instance.name, state))
7784

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

    
7787
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
7788
    cluster = self.cfg.GetClusterInfo()
7789
    # beparams and hvparams are passed separately, to avoid editing the
7790
    # instance and then saving the defaults in the instance itself.
7791
    hvparams = cluster.FillHV(instance)
7792
    beparams = cluster.FillBE(instance)
7793
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
7794

    
7795
    # build ssh cmdline
7796
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
7797

    
7798

    
7799
class LUReplaceDisks(LogicalUnit):
7800
  """Replace the disks of an instance.
7801

7802
  """
7803
  HPATH = "mirrors-replace"
7804
  HTYPE = constants.HTYPE_INSTANCE
7805
  _OP_PARAMS = [
7806
    _PInstanceName,
7807
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES)),
7808
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt)),
7809
    ("remote_node", None, ht.TMaybeString),
7810
    ("iallocator", None, ht.TMaybeString),
7811
    ("early_release", False, ht.TBool),
7812
    ]
7813
  REQ_BGL = False
7814

    
7815
  def CheckArguments(self):
7816
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7817
                                  self.op.iallocator)
7818

    
7819
  def ExpandNames(self):
7820
    self._ExpandAndLockInstance()
7821

    
7822
    if self.op.iallocator is not None:
7823
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7824

    
7825
    elif self.op.remote_node is not None:
7826
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7827
      self.op.remote_node = remote_node
7828

    
7829
      # Warning: do not remove the locking of the new secondary here
7830
      # unless DRBD8.AddChildren is changed to work in parallel;
7831
      # currently it doesn't since parallel invocations of
7832
      # FindUnusedMinor will conflict
7833
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7834
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7835

    
7836
    else:
7837
      self.needed_locks[locking.LEVEL_NODE] = []
7838
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7839

    
7840
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7841
                                   self.op.iallocator, self.op.remote_node,
7842
                                   self.op.disks, False, self.op.early_release)
7843

    
7844
    self.tasklets = [self.replacer]
7845

    
7846
  def DeclareLocks(self, level):
7847
    # If we're not already locking all nodes in the set we have to declare the
7848
    # instance's primary/secondary nodes.
7849
    if (level == locking.LEVEL_NODE and
7850
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7851
      self._LockInstancesNodes()
7852

    
7853
  def BuildHooksEnv(self):
7854
    """Build hooks env.
7855

7856
    This runs on the master, the primary and all the secondaries.
7857

7858
    """
7859
    instance = self.replacer.instance
7860
    env = {
7861
      "MODE": self.op.mode,
7862
      "NEW_SECONDARY": self.op.remote_node,
7863
      "OLD_SECONDARY": instance.secondary_nodes[0],
7864
      }
7865
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7866
    nl = [
7867
      self.cfg.GetMasterNode(),
7868
      instance.primary_node,
7869
      ]
7870
    if self.op.remote_node is not None:
7871
      nl.append(self.op.remote_node)
7872
    return env, nl, nl
7873

    
7874

    
7875
class TLReplaceDisks(Tasklet):
7876
  """Replaces disks for an instance.
7877

7878
  Note: Locking is not within the scope of this class.
7879

7880
  """
7881
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7882
               disks, delay_iallocator, early_release):
7883
    """Initializes this class.
7884

7885
    """
7886
    Tasklet.__init__(self, lu)
7887

    
7888
    # Parameters
7889
    self.instance_name = instance_name
7890
    self.mode = mode
7891
    self.iallocator_name = iallocator_name
7892
    self.remote_node = remote_node
7893
    self.disks = disks
7894
    self.delay_iallocator = delay_iallocator
7895
    self.early_release = early_release
7896

    
7897
    # Runtime data
7898
    self.instance = None
7899
    self.new_node = None
7900
    self.target_node = None
7901
    self.other_node = None
7902
    self.remote_node_info = None
7903
    self.node_secondary_ip = None
7904

    
7905
  @staticmethod
7906
  def CheckArguments(mode, remote_node, iallocator):
7907
    """Helper function for users of this class.
7908

7909
    """
7910
    # check for valid parameter combination
7911
    if mode == constants.REPLACE_DISK_CHG:
7912
      if remote_node is None and iallocator is None:
7913
        raise errors.OpPrereqError("When changing the secondary either an"
7914
                                   " iallocator script must be used or the"
7915
                                   " new node given", errors.ECODE_INVAL)
7916

    
7917
      if remote_node is not None and iallocator is not None:
7918
        raise errors.OpPrereqError("Give either the iallocator or the new"
7919
                                   " secondary, not both", errors.ECODE_INVAL)
7920

    
7921
    elif remote_node is not None or iallocator is not None:
7922
      # Not replacing the secondary
7923
      raise errors.OpPrereqError("The iallocator and new node options can"
7924
                                 " only be used when changing the"
7925
                                 " secondary node", errors.ECODE_INVAL)
7926

    
7927
  @staticmethod
7928
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7929
    """Compute a new secondary node using an IAllocator.
7930

7931
    """
7932
    ial = IAllocator(lu.cfg, lu.rpc,
7933
                     mode=constants.IALLOCATOR_MODE_RELOC,
7934
                     name=instance_name,
7935
                     relocate_from=relocate_from)
7936

    
7937
    ial.Run(iallocator_name)
7938

    
7939
    if not ial.success:
7940
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7941
                                 " %s" % (iallocator_name, ial.info),
7942
                                 errors.ECODE_NORES)
7943

    
7944
    if len(ial.result) != ial.required_nodes:
7945
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7946
                                 " of nodes (%s), required %s" %
7947
                                 (iallocator_name,
7948
                                  len(ial.result), ial.required_nodes),
7949
                                 errors.ECODE_FAULT)
7950

    
7951
    remote_node_name = ial.result[0]
7952

    
7953
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7954
               instance_name, remote_node_name)
7955

    
7956
    return remote_node_name
7957

    
7958
  def _FindFaultyDisks(self, node_name):
7959
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7960
                                    node_name, True)
7961

    
7962
  def CheckPrereq(self):
7963
    """Check prerequisites.
7964

7965
    This checks that the instance is in the cluster.
7966

7967
    """
7968
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7969
    assert instance is not None, \
7970
      "Cannot retrieve locked instance %s" % self.instance_name
7971

    
7972
    if instance.disk_template != constants.DT_DRBD8:
7973
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7974
                                 " instances", errors.ECODE_INVAL)
7975

    
7976
    if len(instance.secondary_nodes) != 1:
7977
      raise errors.OpPrereqError("The instance has a strange layout,"
7978
                                 " expected one secondary but found %d" %
7979
                                 len(instance.secondary_nodes),
7980
                                 errors.ECODE_FAULT)
7981

    
7982
    if not self.delay_iallocator:
7983
      self._CheckPrereq2()
7984

    
7985
  def _CheckPrereq2(self):
7986
    """Check prerequisites, second part.
7987

7988
    This function should always be part of CheckPrereq. It was separated and is
7989
    now called from Exec because during node evacuation iallocator was only
7990
    called with an unmodified cluster model, not taking planned changes into
7991
    account.
7992

7993
    """
7994
    instance = self.instance
7995
    secondary_node = instance.secondary_nodes[0]
7996

    
7997
    if self.iallocator_name is None:
7998
      remote_node = self.remote_node
7999
    else:
8000
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
8001
                                       instance.name, instance.secondary_nodes)
8002

    
8003
    if remote_node is not None:
8004
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
8005
      assert self.remote_node_info is not None, \
8006
        "Cannot retrieve locked node %s" % remote_node
8007
    else:
8008
      self.remote_node_info = None
8009

    
8010
    if remote_node == self.instance.primary_node:
8011
      raise errors.OpPrereqError("The specified node is the primary node of"
8012
                                 " the instance.", errors.ECODE_INVAL)
8013

    
8014
    if remote_node == secondary_node:
8015
      raise errors.OpPrereqError("The specified node is already the"
8016
                                 " secondary node of the instance.",
8017
                                 errors.ECODE_INVAL)
8018

    
8019
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
8020
                                    constants.REPLACE_DISK_CHG):
8021
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
8022
                                 errors.ECODE_INVAL)
8023

    
8024
    if self.mode == constants.REPLACE_DISK_AUTO:
8025
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
8026
      faulty_secondary = self._FindFaultyDisks(secondary_node)
8027

    
8028
      if faulty_primary and faulty_secondary:
8029
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
8030
                                   " one node and can not be repaired"
8031
                                   " automatically" % self.instance_name,
8032
                                   errors.ECODE_STATE)
8033

    
8034
      if faulty_primary:
8035
        self.disks = faulty_primary
8036
        self.target_node = instance.primary_node
8037
        self.other_node = secondary_node
8038
        check_nodes = [self.target_node, self.other_node]
8039
      elif faulty_secondary:
8040
        self.disks = faulty_secondary
8041
        self.target_node = secondary_node
8042
        self.other_node = instance.primary_node
8043
        check_nodes = [self.target_node, self.other_node]
8044
      else:
8045
        self.disks = []
8046
        check_nodes = []
8047

    
8048
    else:
8049
      # Non-automatic modes
8050
      if self.mode == constants.REPLACE_DISK_PRI:
8051
        self.target_node = instance.primary_node
8052
        self.other_node = secondary_node
8053
        check_nodes = [self.target_node, self.other_node]
8054

    
8055
      elif self.mode == constants.REPLACE_DISK_SEC:
8056
        self.target_node = secondary_node
8057
        self.other_node = instance.primary_node
8058
        check_nodes = [self.target_node, self.other_node]
8059

    
8060
      elif self.mode == constants.REPLACE_DISK_CHG:
8061
        self.new_node = remote_node
8062
        self.other_node = instance.primary_node
8063
        self.target_node = secondary_node
8064
        check_nodes = [self.new_node, self.other_node]
8065

    
8066
        _CheckNodeNotDrained(self.lu, remote_node)
8067
        _CheckNodeVmCapable(self.lu, remote_node)
8068

    
8069
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
8070
        assert old_node_info is not None
8071
        if old_node_info.offline and not self.early_release:
8072
          # doesn't make sense to delay the release
8073
          self.early_release = True
8074
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
8075
                          " early-release mode", secondary_node)
8076

    
8077
      else:
8078
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
8079
                                     self.mode)
8080

    
8081
      # If not specified all disks should be replaced
8082
      if not self.disks:
8083
        self.disks = range(len(self.instance.disks))
8084

    
8085
    for node in check_nodes:
8086
      _CheckNodeOnline(self.lu, node)
8087

    
8088
    # Check whether disks are valid
8089
    for disk_idx in self.disks:
8090
      instance.FindDisk(disk_idx)
8091

    
8092
    # Get secondary node IP addresses
8093
    node_2nd_ip = {}
8094

    
8095
    for node_name in [self.target_node, self.other_node, self.new_node]:
8096
      if node_name is not None:
8097
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
8098

    
8099
    self.node_secondary_ip = node_2nd_ip
8100

    
8101
  def Exec(self, feedback_fn):
8102
    """Execute disk replacement.
8103

8104
    This dispatches the disk replacement to the appropriate handler.
8105

8106
    """
8107
    if self.delay_iallocator:
8108
      self._CheckPrereq2()
8109

    
8110
    if not self.disks:
8111
      feedback_fn("No disks need replacement")
8112
      return
8113

    
8114
    feedback_fn("Replacing disk(s) %s for %s" %
8115
                (utils.CommaJoin(self.disks), self.instance.name))
8116

    
8117
    activate_disks = (not self.instance.admin_up)
8118

    
8119
    # Activate the instance disks if we're replacing them on a down instance
8120
    if activate_disks:
8121
      _StartInstanceDisks(self.lu, self.instance, True)
8122

    
8123
    try:
8124
      # Should we replace the secondary node?
8125
      if self.new_node is not None:
8126
        fn = self._ExecDrbd8Secondary
8127
      else:
8128
        fn = self._ExecDrbd8DiskOnly
8129

    
8130
      return fn(feedback_fn)
8131

    
8132
    finally:
8133
      # Deactivate the instance disks if we're replacing them on a
8134
      # down instance
8135
      if activate_disks:
8136
        _SafeShutdownInstanceDisks(self.lu, self.instance)
8137

    
8138
  def _CheckVolumeGroup(self, nodes):
8139
    self.lu.LogInfo("Checking volume groups")
8140

    
8141
    vgname = self.cfg.GetVGName()
8142

    
8143
    # Make sure volume group exists on all involved nodes
8144
    results = self.rpc.call_vg_list(nodes)
8145
    if not results:
8146
      raise errors.OpExecError("Can't list volume groups on the nodes")
8147

    
8148
    for node in nodes:
8149
      res = results[node]
8150
      res.Raise("Error checking node %s" % node)
8151
      if vgname not in res.payload:
8152
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
8153
                                 (vgname, node))
8154

    
8155
  def _CheckDisksExistence(self, nodes):
8156
    # Check disk existence
8157
    for idx, dev in enumerate(self.instance.disks):
8158
      if idx not in self.disks:
8159
        continue
8160

    
8161
      for node in nodes:
8162
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
8163
        self.cfg.SetDiskID(dev, node)
8164

    
8165
        result = self.rpc.call_blockdev_find(node, dev)
8166

    
8167
        msg = result.fail_msg
8168
        if msg or not result.payload:
8169
          if not msg:
8170
            msg = "disk not found"
8171
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
8172
                                   (idx, node, msg))
8173

    
8174
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
8175
    for idx, dev in enumerate(self.instance.disks):
8176
      if idx not in self.disks:
8177
        continue
8178

    
8179
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
8180
                      (idx, node_name))
8181

    
8182
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
8183
                                   ldisk=ldisk):
8184
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
8185
                                 " replace disks for instance %s" %
8186
                                 (node_name, self.instance.name))
8187

    
8188
  def _CreateNewStorage(self, node_name):
8189
    vgname = self.cfg.GetVGName()
8190
    iv_names = {}
8191

    
8192
    for idx, dev in enumerate(self.instance.disks):
8193
      if idx not in self.disks:
8194
        continue
8195

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

    
8198
      self.cfg.SetDiskID(dev, node_name)
8199

    
8200
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
8201
      names = _GenerateUniqueNames(self.lu, lv_names)
8202

    
8203
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
8204
                             logical_id=(vgname, names[0]))
8205
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
8206
                             logical_id=(vgname, names[1]))
8207

    
8208
      new_lvs = [lv_data, lv_meta]
8209
      old_lvs = dev.children
8210
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
8211

    
8212
      # we pass force_create=True to force the LVM creation
8213
      for new_lv in new_lvs:
8214
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
8215
                        _GetInstanceInfoText(self.instance), False)
8216

    
8217
    return iv_names
8218

    
8219
  def _CheckDevices(self, node_name, iv_names):
8220
    for name, (dev, _, _) in iv_names.iteritems():
8221
      self.cfg.SetDiskID(dev, node_name)
8222

    
8223
      result = self.rpc.call_blockdev_find(node_name, dev)
8224

    
8225
      msg = result.fail_msg
8226
      if msg or not result.payload:
8227
        if not msg:
8228
          msg = "disk not found"
8229
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
8230
                                 (name, msg))
8231

    
8232
      if result.payload.is_degraded:
8233
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
8234

    
8235
  def _RemoveOldStorage(self, node_name, iv_names):
8236
    for name, (_, old_lvs, _) in iv_names.iteritems():
8237
      self.lu.LogInfo("Remove logical volumes for %s" % name)
8238

    
8239
      for lv in old_lvs:
8240
        self.cfg.SetDiskID(lv, node_name)
8241

    
8242
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
8243
        if msg:
8244
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
8245
                             hint="remove unused LVs manually")
8246

    
8247
  def _ReleaseNodeLock(self, node_name):
8248
    """Releases the lock for a given node."""
8249
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
8250

    
8251
  def _ExecDrbd8DiskOnly(self, feedback_fn):
8252
    """Replace a disk on the primary or secondary for DRBD 8.
8253

8254
    The algorithm for replace is quite complicated:
8255

8256
      1. for each disk to be replaced:
8257

8258
        1. create new LVs on the target node with unique names
8259
        1. detach old LVs from the drbd device
8260
        1. rename old LVs to name_replaced.<time_t>
8261
        1. rename new LVs to old LVs
8262
        1. attach the new LVs (with the old names now) to the drbd device
8263

8264
      1. wait for sync across all devices
8265

8266
      1. for each modified disk:
8267

8268
        1. remove old LVs (which have the name name_replaces.<time_t>)
8269

8270
    Failures are not very well handled.
8271

8272
    """
8273
    steps_total = 6
8274

    
8275
    # Step: check device activation
8276
    self.lu.LogStep(1, steps_total, "Check device existence")
8277
    self._CheckDisksExistence([self.other_node, self.target_node])
8278
    self._CheckVolumeGroup([self.target_node, self.other_node])
8279

    
8280
    # Step: check other node consistency
8281
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8282
    self._CheckDisksConsistency(self.other_node,
8283
                                self.other_node == self.instance.primary_node,
8284
                                False)
8285

    
8286
    # Step: create new storage
8287
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8288
    iv_names = self._CreateNewStorage(self.target_node)
8289

    
8290
    # Step: for each lv, detach+rename*2+attach
8291
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8292
    for dev, old_lvs, new_lvs in iv_names.itervalues():
8293
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
8294

    
8295
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
8296
                                                     old_lvs)
8297
      result.Raise("Can't detach drbd from local storage on node"
8298
                   " %s for device %s" % (self.target_node, dev.iv_name))
8299
      #dev.children = []
8300
      #cfg.Update(instance)
8301

    
8302
      # ok, we created the new LVs, so now we know we have the needed
8303
      # storage; as such, we proceed on the target node to rename
8304
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
8305
      # using the assumption that logical_id == physical_id (which in
8306
      # turn is the unique_id on that node)
8307

    
8308
      # FIXME(iustin): use a better name for the replaced LVs
8309
      temp_suffix = int(time.time())
8310
      ren_fn = lambda d, suff: (d.physical_id[0],
8311
                                d.physical_id[1] + "_replaced-%s" % suff)
8312

    
8313
      # Build the rename list based on what LVs exist on the node
8314
      rename_old_to_new = []
8315
      for to_ren in old_lvs:
8316
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
8317
        if not result.fail_msg and result.payload:
8318
          # device exists
8319
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
8320

    
8321
      self.lu.LogInfo("Renaming the old LVs on the target node")
8322
      result = self.rpc.call_blockdev_rename(self.target_node,
8323
                                             rename_old_to_new)
8324
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
8325

    
8326
      # Now we rename the new LVs to the old LVs
8327
      self.lu.LogInfo("Renaming the new LVs on the target node")
8328
      rename_new_to_old = [(new, old.physical_id)
8329
                           for old, new in zip(old_lvs, new_lvs)]
8330
      result = self.rpc.call_blockdev_rename(self.target_node,
8331
                                             rename_new_to_old)
8332
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
8333

    
8334
      for old, new in zip(old_lvs, new_lvs):
8335
        new.logical_id = old.logical_id
8336
        self.cfg.SetDiskID(new, self.target_node)
8337

    
8338
      for disk in old_lvs:
8339
        disk.logical_id = ren_fn(disk, temp_suffix)
8340
        self.cfg.SetDiskID(disk, self.target_node)
8341

    
8342
      # Now that the new lvs have the old name, we can add them to the device
8343
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
8344
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
8345
                                                  new_lvs)
8346
      msg = result.fail_msg
8347
      if msg:
8348
        for new_lv in new_lvs:
8349
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
8350
                                               new_lv).fail_msg
8351
          if msg2:
8352
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
8353
                               hint=("cleanup manually the unused logical"
8354
                                     "volumes"))
8355
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8356

    
8357
      dev.children = new_lvs
8358

    
8359
      self.cfg.Update(self.instance, feedback_fn)
8360

    
8361
    cstep = 5
8362
    if self.early_release:
8363
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8364
      cstep += 1
8365
      self._RemoveOldStorage(self.target_node, iv_names)
8366
      # WARNING: we release both node locks here, do not do other RPCs
8367
      # than WaitForSync to the primary node
8368
      self._ReleaseNodeLock([self.target_node, self.other_node])
8369

    
8370
    # Wait for sync
8371
    # This can fail as the old devices are degraded and _WaitForSync
8372
    # does a combined result over all disks, so we don't check its return value
8373
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8374
    cstep += 1
8375
    _WaitForSync(self.lu, self.instance)
8376

    
8377
    # Check all devices manually
8378
    self._CheckDevices(self.instance.primary_node, iv_names)
8379

    
8380
    # Step: remove old storage
8381
    if not self.early_release:
8382
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8383
      cstep += 1
8384
      self._RemoveOldStorage(self.target_node, iv_names)
8385

    
8386
  def _ExecDrbd8Secondary(self, feedback_fn):
8387
    """Replace the secondary node for DRBD 8.
8388

8389
    The algorithm for replace is quite complicated:
8390
      - for all disks of the instance:
8391
        - create new LVs on the new node with same names
8392
        - shutdown the drbd device on the old secondary
8393
        - disconnect the drbd network on the primary
8394
        - create the drbd device on the new secondary
8395
        - network attach the drbd on the primary, using an artifice:
8396
          the drbd code for Attach() will connect to the network if it
8397
          finds a device which is connected to the good local disks but
8398
          not network enabled
8399
      - wait for sync across all devices
8400
      - remove all disks from the old secondary
8401

8402
    Failures are not very well handled.
8403

8404
    """
8405
    steps_total = 6
8406

    
8407
    # Step: check device activation
8408
    self.lu.LogStep(1, steps_total, "Check device existence")
8409
    self._CheckDisksExistence([self.instance.primary_node])
8410
    self._CheckVolumeGroup([self.instance.primary_node])
8411

    
8412
    # Step: check other node consistency
8413
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8414
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8415

    
8416
    # Step: create new storage
8417
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8418
    for idx, dev in enumerate(self.instance.disks):
8419
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8420
                      (self.new_node, idx))
8421
      # we pass force_create=True to force LVM creation
8422
      for new_lv in dev.children:
8423
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8424
                        _GetInstanceInfoText(self.instance), False)
8425

    
8426
    # Step 4: dbrd minors and drbd setups changes
8427
    # after this, we must manually remove the drbd minors on both the
8428
    # error and the success paths
8429
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8430
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8431
                                         for dev in self.instance.disks],
8432
                                        self.instance.name)
8433
    logging.debug("Allocated minors %r", minors)
8434

    
8435
    iv_names = {}
8436
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8437
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8438
                      (self.new_node, idx))
8439
      # create new devices on new_node; note that we create two IDs:
8440
      # one without port, so the drbd will be activated without
8441
      # networking information on the new node at this stage, and one
8442
      # with network, for the latter activation in step 4
8443
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8444
      if self.instance.primary_node == o_node1:
8445
        p_minor = o_minor1
8446
      else:
8447
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8448
        p_minor = o_minor2
8449

    
8450
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8451
                      p_minor, new_minor, o_secret)
8452
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8453
                    p_minor, new_minor, o_secret)
8454

    
8455
      iv_names[idx] = (dev, dev.children, new_net_id)
8456
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8457
                    new_net_id)
8458
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8459
                              logical_id=new_alone_id,
8460
                              children=dev.children,
8461
                              size=dev.size)
8462
      try:
8463
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8464
                              _GetInstanceInfoText(self.instance), False)
8465
      except errors.GenericError:
8466
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8467
        raise
8468

    
8469
    # We have new devices, shutdown the drbd on the old secondary
8470
    for idx, dev in enumerate(self.instance.disks):
8471
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8472
      self.cfg.SetDiskID(dev, self.target_node)
8473
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8474
      if msg:
8475
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8476
                           "node: %s" % (idx, msg),
8477
                           hint=("Please cleanup this device manually as"
8478
                                 " soon as possible"))
8479

    
8480
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8481
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8482
                                               self.node_secondary_ip,
8483
                                               self.instance.disks)\
8484
                                              [self.instance.primary_node]
8485

    
8486
    msg = result.fail_msg
8487
    if msg:
8488
      # detaches didn't succeed (unlikely)
8489
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8490
      raise errors.OpExecError("Can't detach the disks from the network on"
8491
                               " old node: %s" % (msg,))
8492

    
8493
    # if we managed to detach at least one, we update all the disks of
8494
    # the instance to point to the new secondary
8495
    self.lu.LogInfo("Updating instance configuration")
8496
    for dev, _, new_logical_id in iv_names.itervalues():
8497
      dev.logical_id = new_logical_id
8498
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8499

    
8500
    self.cfg.Update(self.instance, feedback_fn)
8501

    
8502
    # and now perform the drbd attach
8503
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8504
                    " (standalone => connected)")
8505
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8506
                                            self.new_node],
8507
                                           self.node_secondary_ip,
8508
                                           self.instance.disks,
8509
                                           self.instance.name,
8510
                                           False)
8511
    for to_node, to_result in result.items():
8512
      msg = to_result.fail_msg
8513
      if msg:
8514
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8515
                           to_node, msg,
8516
                           hint=("please do a gnt-instance info to see the"
8517
                                 " status of disks"))
8518
    cstep = 5
8519
    if self.early_release:
8520
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8521
      cstep += 1
8522
      self._RemoveOldStorage(self.target_node, iv_names)
8523
      # WARNING: we release all node locks here, do not do other RPCs
8524
      # than WaitForSync to the primary node
8525
      self._ReleaseNodeLock([self.instance.primary_node,
8526
                             self.target_node,
8527
                             self.new_node])
8528

    
8529
    # Wait for sync
8530
    # This can fail as the old devices are degraded and _WaitForSync
8531
    # does a combined result over all disks, so we don't check its return value
8532
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8533
    cstep += 1
8534
    _WaitForSync(self.lu, self.instance)
8535

    
8536
    # Check all devices manually
8537
    self._CheckDevices(self.instance.primary_node, iv_names)
8538

    
8539
    # Step: remove old storage
8540
    if not self.early_release:
8541
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8542
      self._RemoveOldStorage(self.target_node, iv_names)
8543

    
8544

    
8545
class LURepairNodeStorage(NoHooksLU):
8546
  """Repairs the volume group on a node.
8547

8548
  """
8549
  _OP_PARAMS = [
8550
    _PNodeName,
8551
    ("storage_type", ht.NoDefault, _CheckStorageType),
8552
    ("name", ht.NoDefault, ht.TNonEmptyString),
8553
    ("ignore_consistency", False, ht.TBool),
8554
    ]
8555
  REQ_BGL = False
8556

    
8557
  def CheckArguments(self):
8558
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8559

    
8560
    storage_type = self.op.storage_type
8561

    
8562
    if (constants.SO_FIX_CONSISTENCY not in
8563
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8564
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8565
                                 " repaired" % storage_type,
8566
                                 errors.ECODE_INVAL)
8567

    
8568
  def ExpandNames(self):
8569
    self.needed_locks = {
8570
      locking.LEVEL_NODE: [self.op.node_name],
8571
      }
8572

    
8573
  def _CheckFaultyDisks(self, instance, node_name):
8574
    """Ensure faulty disks abort the opcode or at least warn."""
8575
    try:
8576
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8577
                                  node_name, True):
8578
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8579
                                   " node '%s'" % (instance.name, node_name),
8580
                                   errors.ECODE_STATE)
8581
    except errors.OpPrereqError, err:
8582
      if self.op.ignore_consistency:
8583
        self.proc.LogWarning(str(err.args[0]))
8584
      else:
8585
        raise
8586

    
8587
  def CheckPrereq(self):
8588
    """Check prerequisites.
8589

8590
    """
8591
    # Check whether any instance on this node has faulty disks
8592
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8593
      if not inst.admin_up:
8594
        continue
8595
      check_nodes = set(inst.all_nodes)
8596
      check_nodes.discard(self.op.node_name)
8597
      for inst_node_name in check_nodes:
8598
        self._CheckFaultyDisks(inst, inst_node_name)
8599

    
8600
  def Exec(self, feedback_fn):
8601
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8602
                (self.op.name, self.op.node_name))
8603

    
8604
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8605
    result = self.rpc.call_storage_execute(self.op.node_name,
8606
                                           self.op.storage_type, st_args,
8607
                                           self.op.name,
8608
                                           constants.SO_FIX_CONSISTENCY)
8609
    result.Raise("Failed to repair storage unit '%s' on %s" %
8610
                 (self.op.name, self.op.node_name))
8611

    
8612

    
8613
class LUNodeEvacuationStrategy(NoHooksLU):
8614
  """Computes the node evacuation strategy.
8615

8616
  """
8617
  _OP_PARAMS = [
8618
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
8619
    ("remote_node", None, ht.TMaybeString),
8620
    ("iallocator", None, ht.TMaybeString),
8621
    ]
8622
  REQ_BGL = False
8623

    
8624
  def CheckArguments(self):
8625
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8626

    
8627
  def ExpandNames(self):
8628
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8629
    self.needed_locks = locks = {}
8630
    if self.op.remote_node is None:
8631
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8632
    else:
8633
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8634
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8635

    
8636
  def Exec(self, feedback_fn):
8637
    if self.op.remote_node is not None:
8638
      instances = []
8639
      for node in self.op.nodes:
8640
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8641
      result = []
8642
      for i in instances:
8643
        if i.primary_node == self.op.remote_node:
8644
          raise errors.OpPrereqError("Node %s is the primary node of"
8645
                                     " instance %s, cannot use it as"
8646
                                     " secondary" %
8647
                                     (self.op.remote_node, i.name),
8648
                                     errors.ECODE_INVAL)
8649
        result.append([i.name, self.op.remote_node])
8650
    else:
8651
      ial = IAllocator(self.cfg, self.rpc,
8652
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8653
                       evac_nodes=self.op.nodes)
8654
      ial.Run(self.op.iallocator, validate=True)
8655
      if not ial.success:
8656
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8657
                                 errors.ECODE_NORES)
8658
      result = ial.result
8659
    return result
8660

    
8661

    
8662
class LUGrowDisk(LogicalUnit):
8663
  """Grow a disk of an instance.
8664

8665
  """
8666
  HPATH = "disk-grow"
8667
  HTYPE = constants.HTYPE_INSTANCE
8668
  _OP_PARAMS = [
8669
    _PInstanceName,
8670
    ("disk", ht.NoDefault, ht.TInt),
8671
    ("amount", ht.NoDefault, ht.TInt),
8672
    ("wait_for_sync", True, ht.TBool),
8673
    ]
8674
  REQ_BGL = False
8675

    
8676
  def ExpandNames(self):
8677
    self._ExpandAndLockInstance()
8678
    self.needed_locks[locking.LEVEL_NODE] = []
8679
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8680

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

    
8685
  def BuildHooksEnv(self):
8686
    """Build hooks env.
8687

8688
    This runs on the master, the primary and all the secondaries.
8689

8690
    """
8691
    env = {
8692
      "DISK": self.op.disk,
8693
      "AMOUNT": self.op.amount,
8694
      }
8695
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8696
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8697
    return env, nl, nl
8698

    
8699
  def CheckPrereq(self):
8700
    """Check prerequisites.
8701

8702
    This checks that the instance is in the cluster.
8703

8704
    """
8705
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8706
    assert instance is not None, \
8707
      "Cannot retrieve locked instance %s" % self.op.instance_name
8708
    nodenames = list(instance.all_nodes)
8709
    for node in nodenames:
8710
      _CheckNodeOnline(self, node)
8711

    
8712
    self.instance = instance
8713

    
8714
    if instance.disk_template not in constants.DTS_GROWABLE:
8715
      raise errors.OpPrereqError("Instance's disk layout does not support"
8716
                                 " growing.", errors.ECODE_INVAL)
8717

    
8718
    self.disk = instance.FindDisk(self.op.disk)
8719

    
8720
    if instance.disk_template != constants.DT_FILE:
8721
      # TODO: check the free disk space for file, when that feature will be
8722
      # supported
8723
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
8724

    
8725
  def Exec(self, feedback_fn):
8726
    """Execute disk grow.
8727

8728
    """
8729
    instance = self.instance
8730
    disk = self.disk
8731

    
8732
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8733
    if not disks_ok:
8734
      raise errors.OpExecError("Cannot activate block device to grow")
8735

    
8736
    for node in instance.all_nodes:
8737
      self.cfg.SetDiskID(disk, node)
8738
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8739
      result.Raise("Grow request failed to node %s" % node)
8740

    
8741
      # TODO: Rewrite code to work properly
8742
      # DRBD goes into sync mode for a short amount of time after executing the
8743
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8744
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8745
      # time is a work-around.
8746
      time.sleep(5)
8747

    
8748
    disk.RecordGrow(self.op.amount)
8749
    self.cfg.Update(instance, feedback_fn)
8750
    if self.op.wait_for_sync:
8751
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8752
      if disk_abort:
8753
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8754
                             " status.\nPlease check the instance.")
8755
      if not instance.admin_up:
8756
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8757
    elif not instance.admin_up:
8758
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8759
                           " not supposed to be running because no wait for"
8760
                           " sync mode was requested.")
8761

    
8762

    
8763
class LUQueryInstanceData(NoHooksLU):
8764
  """Query runtime instance data.
8765

8766
  """
8767
  _OP_PARAMS = [
8768
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
8769
    ("static", False, ht.TBool),
8770
    ]
8771
  REQ_BGL = False
8772

    
8773
  def ExpandNames(self):
8774
    self.needed_locks = {}
8775
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8776

    
8777
    if self.op.instances:
8778
      self.wanted_names = []
8779
      for name in self.op.instances:
8780
        full_name = _ExpandInstanceName(self.cfg, name)
8781
        self.wanted_names.append(full_name)
8782
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8783
    else:
8784
      self.wanted_names = None
8785
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8786

    
8787
    self.needed_locks[locking.LEVEL_NODE] = []
8788
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8789

    
8790
  def DeclareLocks(self, level):
8791
    if level == locking.LEVEL_NODE:
8792
      self._LockInstancesNodes()
8793

    
8794
  def CheckPrereq(self):
8795
    """Check prerequisites.
8796

8797
    This only checks the optional instance list against the existing names.
8798

8799
    """
8800
    if self.wanted_names is None:
8801
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8802

    
8803
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8804
                             in self.wanted_names]
8805

    
8806
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8807
    """Returns the status of a block device
8808

8809
    """
8810
    if self.op.static or not node:
8811
      return None
8812

    
8813
    self.cfg.SetDiskID(dev, node)
8814

    
8815
    result = self.rpc.call_blockdev_find(node, dev)
8816
    if result.offline:
8817
      return None
8818

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

    
8821
    status = result.payload
8822
    if status is None:
8823
      return None
8824

    
8825
    return (status.dev_path, status.major, status.minor,
8826
            status.sync_percent, status.estimated_time,
8827
            status.is_degraded, status.ldisk_status)
8828

    
8829
  def _ComputeDiskStatus(self, instance, snode, dev):
8830
    """Compute block device status.
8831

8832
    """
8833
    if dev.dev_type in constants.LDS_DRBD:
8834
      # we change the snode then (otherwise we use the one passed in)
8835
      if dev.logical_id[0] == instance.primary_node:
8836
        snode = dev.logical_id[1]
8837
      else:
8838
        snode = dev.logical_id[0]
8839

    
8840
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8841
                                              instance.name, dev)
8842
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8843

    
8844
    if dev.children:
8845
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8846
                      for child in dev.children]
8847
    else:
8848
      dev_children = []
8849

    
8850
    data = {
8851
      "iv_name": dev.iv_name,
8852
      "dev_type": dev.dev_type,
8853
      "logical_id": dev.logical_id,
8854
      "physical_id": dev.physical_id,
8855
      "pstatus": dev_pstatus,
8856
      "sstatus": dev_sstatus,
8857
      "children": dev_children,
8858
      "mode": dev.mode,
8859
      "size": dev.size,
8860
      }
8861

    
8862
    return data
8863

    
8864
  def Exec(self, feedback_fn):
8865
    """Gather and return data"""
8866
    result = {}
8867

    
8868
    cluster = self.cfg.GetClusterInfo()
8869

    
8870
    for instance in self.wanted_instances:
8871
      if not self.op.static:
8872
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8873
                                                  instance.name,
8874
                                                  instance.hypervisor)
8875
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8876
        remote_info = remote_info.payload
8877
        if remote_info and "state" in remote_info:
8878
          remote_state = "up"
8879
        else:
8880
          remote_state = "down"
8881
      else:
8882
        remote_state = None
8883
      if instance.admin_up:
8884
        config_state = "up"
8885
      else:
8886
        config_state = "down"
8887

    
8888
      disks = [self._ComputeDiskStatus(instance, None, device)
8889
               for device in instance.disks]
8890

    
8891
      idict = {
8892
        "name": instance.name,
8893
        "config_state": config_state,
8894
        "run_state": remote_state,
8895
        "pnode": instance.primary_node,
8896
        "snodes": instance.secondary_nodes,
8897
        "os": instance.os,
8898
        # this happens to be the same format used for hooks
8899
        "nics": _NICListToTuple(self, instance.nics),
8900
        "disk_template": instance.disk_template,
8901
        "disks": disks,
8902
        "hypervisor": instance.hypervisor,
8903
        "network_port": instance.network_port,
8904
        "hv_instance": instance.hvparams,
8905
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8906
        "be_instance": instance.beparams,
8907
        "be_actual": cluster.FillBE(instance),
8908
        "os_instance": instance.osparams,
8909
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8910
        "serial_no": instance.serial_no,
8911
        "mtime": instance.mtime,
8912
        "ctime": instance.ctime,
8913
        "uuid": instance.uuid,
8914
        }
8915

    
8916
      result[instance.name] = idict
8917

    
8918
    return result
8919

    
8920

    
8921
class LUSetInstanceParams(LogicalUnit):
8922
  """Modifies an instances's parameters.
8923

8924
  """
8925
  HPATH = "instance-modify"
8926
  HTYPE = constants.HTYPE_INSTANCE
8927
  _OP_PARAMS = [
8928
    _PInstanceName,
8929
    ("nics", ht.EmptyList, ht.TList),
8930
    ("disks", ht.EmptyList, ht.TList),
8931
    ("beparams", ht.EmptyDict, ht.TDict),
8932
    ("hvparams", ht.EmptyDict, ht.TDict),
8933
    ("disk_template", None, ht.TMaybeString),
8934
    ("remote_node", None, ht.TMaybeString),
8935
    ("os_name", None, ht.TMaybeString),
8936
    ("force_variant", False, ht.TBool),
8937
    ("osparams", None, ht.TOr(ht.TDict, ht.TNone)),
8938
    _PForce,
8939
    ]
8940
  REQ_BGL = False
8941

    
8942
  def CheckArguments(self):
8943
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8944
            self.op.hvparams or self.op.beparams or self.op.os_name):
8945
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8946

    
8947
    if self.op.hvparams:
8948
      _CheckGlobalHvParams(self.op.hvparams)
8949

    
8950
    # Disk validation
8951
    disk_addremove = 0
8952
    for disk_op, disk_dict in self.op.disks:
8953
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8954
      if disk_op == constants.DDM_REMOVE:
8955
        disk_addremove += 1
8956
        continue
8957
      elif disk_op == constants.DDM_ADD:
8958
        disk_addremove += 1
8959
      else:
8960
        if not isinstance(disk_op, int):
8961
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8962
        if not isinstance(disk_dict, dict):
8963
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8964
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8965

    
8966
      if disk_op == constants.DDM_ADD:
8967
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8968
        if mode not in constants.DISK_ACCESS_SET:
8969
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8970
                                     errors.ECODE_INVAL)
8971
        size = disk_dict.get('size', None)
8972
        if size is None:
8973
          raise errors.OpPrereqError("Required disk parameter size missing",
8974
                                     errors.ECODE_INVAL)
8975
        try:
8976
          size = int(size)
8977
        except (TypeError, ValueError), err:
8978
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8979
                                     str(err), errors.ECODE_INVAL)
8980
        disk_dict['size'] = size
8981
      else:
8982
        # modification of disk
8983
        if 'size' in disk_dict:
8984
          raise errors.OpPrereqError("Disk size change not possible, use"
8985
                                     " grow-disk", errors.ECODE_INVAL)
8986

    
8987
    if disk_addremove > 1:
8988
      raise errors.OpPrereqError("Only one disk add or remove operation"
8989
                                 " supported at a time", errors.ECODE_INVAL)
8990

    
8991
    if self.op.disks and self.op.disk_template is not None:
8992
      raise errors.OpPrereqError("Disk template conversion and other disk"
8993
                                 " changes not supported at the same time",
8994
                                 errors.ECODE_INVAL)
8995

    
8996
    if self.op.disk_template:
8997
      _CheckDiskTemplate(self.op.disk_template)
8998
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
8999
          self.op.remote_node is None):
9000
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
9001
                                   " one requires specifying a secondary node",
9002
                                   errors.ECODE_INVAL)
9003

    
9004
    # NIC validation
9005
    nic_addremove = 0
9006
    for nic_op, nic_dict in self.op.nics:
9007
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
9008
      if nic_op == constants.DDM_REMOVE:
9009
        nic_addremove += 1
9010
        continue
9011
      elif nic_op == constants.DDM_ADD:
9012
        nic_addremove += 1
9013
      else:
9014
        if not isinstance(nic_op, int):
9015
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
9016
        if not isinstance(nic_dict, dict):
9017
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
9018
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9019

    
9020
      # nic_dict should be a dict
9021
      nic_ip = nic_dict.get('ip', None)
9022
      if nic_ip is not None:
9023
        if nic_ip.lower() == constants.VALUE_NONE:
9024
          nic_dict['ip'] = None
9025
        else:
9026
          if not netutils.IPAddress.IsValid(nic_ip):
9027
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
9028
                                       errors.ECODE_INVAL)
9029

    
9030
      nic_bridge = nic_dict.get('bridge', None)
9031
      nic_link = nic_dict.get('link', None)
9032
      if nic_bridge and nic_link:
9033
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
9034
                                   " at the same time", errors.ECODE_INVAL)
9035
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
9036
        nic_dict['bridge'] = None
9037
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
9038
        nic_dict['link'] = None
9039

    
9040
      if nic_op == constants.DDM_ADD:
9041
        nic_mac = nic_dict.get('mac', None)
9042
        if nic_mac is None:
9043
          nic_dict['mac'] = constants.VALUE_AUTO
9044

    
9045
      if 'mac' in nic_dict:
9046
        nic_mac = nic_dict['mac']
9047
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9048
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
9049

    
9050
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
9051
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
9052
                                     " modifying an existing nic",
9053
                                     errors.ECODE_INVAL)
9054

    
9055
    if nic_addremove > 1:
9056
      raise errors.OpPrereqError("Only one NIC add or remove operation"
9057
                                 " supported at a time", errors.ECODE_INVAL)
9058

    
9059
  def ExpandNames(self):
9060
    self._ExpandAndLockInstance()
9061
    self.needed_locks[locking.LEVEL_NODE] = []
9062
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9063

    
9064
  def DeclareLocks(self, level):
9065
    if level == locking.LEVEL_NODE:
9066
      self._LockInstancesNodes()
9067
      if self.op.disk_template and self.op.remote_node:
9068
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9069
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
9070

    
9071
  def BuildHooksEnv(self):
9072
    """Build hooks env.
9073

9074
    This runs on the master, primary and secondaries.
9075

9076
    """
9077
    args = dict()
9078
    if constants.BE_MEMORY in self.be_new:
9079
      args['memory'] = self.be_new[constants.BE_MEMORY]
9080
    if constants.BE_VCPUS in self.be_new:
9081
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
9082
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
9083
    # information at all.
9084
    if self.op.nics:
9085
      args['nics'] = []
9086
      nic_override = dict(self.op.nics)
9087
      for idx, nic in enumerate(self.instance.nics):
9088
        if idx in nic_override:
9089
          this_nic_override = nic_override[idx]
9090
        else:
9091
          this_nic_override = {}
9092
        if 'ip' in this_nic_override:
9093
          ip = this_nic_override['ip']
9094
        else:
9095
          ip = nic.ip
9096
        if 'mac' in this_nic_override:
9097
          mac = this_nic_override['mac']
9098
        else:
9099
          mac = nic.mac
9100
        if idx in self.nic_pnew:
9101
          nicparams = self.nic_pnew[idx]
9102
        else:
9103
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
9104
        mode = nicparams[constants.NIC_MODE]
9105
        link = nicparams[constants.NIC_LINK]
9106
        args['nics'].append((ip, mac, mode, link))
9107
      if constants.DDM_ADD in nic_override:
9108
        ip = nic_override[constants.DDM_ADD].get('ip', None)
9109
        mac = nic_override[constants.DDM_ADD]['mac']
9110
        nicparams = self.nic_pnew[constants.DDM_ADD]
9111
        mode = nicparams[constants.NIC_MODE]
9112
        link = nicparams[constants.NIC_LINK]
9113
        args['nics'].append((ip, mac, mode, link))
9114
      elif constants.DDM_REMOVE in nic_override:
9115
        del args['nics'][-1]
9116

    
9117
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
9118
    if self.op.disk_template:
9119
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
9120
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9121
    return env, nl, nl
9122

    
9123
  def CheckPrereq(self):
9124
    """Check prerequisites.
9125

9126
    This only checks the instance list against the existing names.
9127

9128
    """
9129
    # checking the new params on the primary/secondary nodes
9130

    
9131
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9132
    cluster = self.cluster = self.cfg.GetClusterInfo()
9133
    assert self.instance is not None, \
9134
      "Cannot retrieve locked instance %s" % self.op.instance_name
9135
    pnode = instance.primary_node
9136
    nodelist = list(instance.all_nodes)
9137

    
9138
    # OS change
9139
    if self.op.os_name and not self.op.force:
9140
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
9141
                      self.op.force_variant)
9142
      instance_os = self.op.os_name
9143
    else:
9144
      instance_os = instance.os
9145

    
9146
    if self.op.disk_template:
9147
      if instance.disk_template == self.op.disk_template:
9148
        raise errors.OpPrereqError("Instance already has disk template %s" %
9149
                                   instance.disk_template, errors.ECODE_INVAL)
9150

    
9151
      if (instance.disk_template,
9152
          self.op.disk_template) not in self._DISK_CONVERSIONS:
9153
        raise errors.OpPrereqError("Unsupported disk template conversion from"
9154
                                   " %s to %s" % (instance.disk_template,
9155
                                                  self.op.disk_template),
9156
                                   errors.ECODE_INVAL)
9157
      _CheckInstanceDown(self, instance, "cannot change disk template")
9158
      if self.op.disk_template in constants.DTS_NET_MIRROR:
9159
        if self.op.remote_node == pnode:
9160
          raise errors.OpPrereqError("Given new secondary node %s is the same"
9161
                                     " as the primary node of the instance" %
9162
                                     self.op.remote_node, errors.ECODE_STATE)
9163
        _CheckNodeOnline(self, self.op.remote_node)
9164
        _CheckNodeNotDrained(self, self.op.remote_node)
9165
        disks = [{"size": d.size} for d in instance.disks]
9166
        required = _ComputeDiskSize(self.op.disk_template, disks)
9167
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
9168

    
9169
    # hvparams processing
9170
    if self.op.hvparams:
9171
      hv_type = instance.hypervisor
9172
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
9173
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
9174
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
9175

    
9176
      # local check
9177
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
9178
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
9179
      self.hv_new = hv_new # the new actual values
9180
      self.hv_inst = i_hvdict # the new dict (without defaults)
9181
    else:
9182
      self.hv_new = self.hv_inst = {}
9183

    
9184
    # beparams processing
9185
    if self.op.beparams:
9186
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
9187
                                   use_none=True)
9188
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
9189
      be_new = cluster.SimpleFillBE(i_bedict)
9190
      self.be_new = be_new # the new actual values
9191
      self.be_inst = i_bedict # the new dict (without defaults)
9192
    else:
9193
      self.be_new = self.be_inst = {}
9194

    
9195
    # osparams processing
9196
    if self.op.osparams:
9197
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
9198
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
9199
      self.os_inst = i_osdict # the new dict (without defaults)
9200
    else:
9201
      self.os_inst = {}
9202

    
9203
    self.warn = []
9204

    
9205
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
9206
      mem_check_list = [pnode]
9207
      if be_new[constants.BE_AUTO_BALANCE]:
9208
        # either we changed auto_balance to yes or it was from before
9209
        mem_check_list.extend(instance.secondary_nodes)
9210
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
9211
                                                  instance.hypervisor)
9212
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
9213
                                         instance.hypervisor)
9214
      pninfo = nodeinfo[pnode]
9215
      msg = pninfo.fail_msg
9216
      if msg:
9217
        # Assume the primary node is unreachable and go ahead
9218
        self.warn.append("Can't get info from primary node %s: %s" %
9219
                         (pnode,  msg))
9220
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
9221
        self.warn.append("Node data from primary node %s doesn't contain"
9222
                         " free memory information" % pnode)
9223
      elif instance_info.fail_msg:
9224
        self.warn.append("Can't get instance runtime information: %s" %
9225
                        instance_info.fail_msg)
9226
      else:
9227
        if instance_info.payload:
9228
          current_mem = int(instance_info.payload['memory'])
9229
        else:
9230
          # Assume instance not running
9231
          # (there is a slight race condition here, but it's not very probable,
9232
          # and we have no other way to check)
9233
          current_mem = 0
9234
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
9235
                    pninfo.payload['memory_free'])
9236
        if miss_mem > 0:
9237
          raise errors.OpPrereqError("This change will prevent the instance"
9238
                                     " from starting, due to %d MB of memory"
9239
                                     " missing on its primary node" % miss_mem,
9240
                                     errors.ECODE_NORES)
9241

    
9242
      if be_new[constants.BE_AUTO_BALANCE]:
9243
        for node, nres in nodeinfo.items():
9244
          if node not in instance.secondary_nodes:
9245
            continue
9246
          msg = nres.fail_msg
9247
          if msg:
9248
            self.warn.append("Can't get info from secondary node %s: %s" %
9249
                             (node, msg))
9250
          elif not isinstance(nres.payload.get('memory_free', None), int):
9251
            self.warn.append("Secondary node %s didn't return free"
9252
                             " memory information" % node)
9253
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
9254
            self.warn.append("Not enough memory to failover instance to"
9255
                             " secondary node %s" % node)
9256

    
9257
    # NIC processing
9258
    self.nic_pnew = {}
9259
    self.nic_pinst = {}
9260
    for nic_op, nic_dict in self.op.nics:
9261
      if nic_op == constants.DDM_REMOVE:
9262
        if not instance.nics:
9263
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
9264
                                     errors.ECODE_INVAL)
9265
        continue
9266
      if nic_op != constants.DDM_ADD:
9267
        # an existing nic
9268
        if not instance.nics:
9269
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
9270
                                     " no NICs" % nic_op,
9271
                                     errors.ECODE_INVAL)
9272
        if nic_op < 0 or nic_op >= len(instance.nics):
9273
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
9274
                                     " are 0 to %d" %
9275
                                     (nic_op, len(instance.nics) - 1),
9276
                                     errors.ECODE_INVAL)
9277
        old_nic_params = instance.nics[nic_op].nicparams
9278
        old_nic_ip = instance.nics[nic_op].ip
9279
      else:
9280
        old_nic_params = {}
9281
        old_nic_ip = None
9282

    
9283
      update_params_dict = dict([(key, nic_dict[key])
9284
                                 for key in constants.NICS_PARAMETERS
9285
                                 if key in nic_dict])
9286

    
9287
      if 'bridge' in nic_dict:
9288
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
9289

    
9290
      new_nic_params = _GetUpdatedParams(old_nic_params,
9291
                                         update_params_dict)
9292
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
9293
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
9294
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
9295
      self.nic_pinst[nic_op] = new_nic_params
9296
      self.nic_pnew[nic_op] = new_filled_nic_params
9297
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
9298

    
9299
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
9300
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
9301
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
9302
        if msg:
9303
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
9304
          if self.op.force:
9305
            self.warn.append(msg)
9306
          else:
9307
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
9308
      if new_nic_mode == constants.NIC_MODE_ROUTED:
9309
        if 'ip' in nic_dict:
9310
          nic_ip = nic_dict['ip']
9311
        else:
9312
          nic_ip = old_nic_ip
9313
        if nic_ip is None:
9314
          raise errors.OpPrereqError('Cannot set the nic ip to None'
9315
                                     ' on a routed nic', errors.ECODE_INVAL)
9316
      if 'mac' in nic_dict:
9317
        nic_mac = nic_dict['mac']
9318
        if nic_mac is None:
9319
          raise errors.OpPrereqError('Cannot set the nic mac to None',
9320
                                     errors.ECODE_INVAL)
9321
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9322
          # otherwise generate the mac
9323
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
9324
        else:
9325
          # or validate/reserve the current one
9326
          try:
9327
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
9328
          except errors.ReservationError:
9329
            raise errors.OpPrereqError("MAC address %s already in use"
9330
                                       " in cluster" % nic_mac,
9331
                                       errors.ECODE_NOTUNIQUE)
9332

    
9333
    # DISK processing
9334
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
9335
      raise errors.OpPrereqError("Disk operations not supported for"
9336
                                 " diskless instances",
9337
                                 errors.ECODE_INVAL)
9338
    for disk_op, _ in self.op.disks:
9339
      if disk_op == constants.DDM_REMOVE:
9340
        if len(instance.disks) == 1:
9341
          raise errors.OpPrereqError("Cannot remove the last disk of"
9342
                                     " an instance", errors.ECODE_INVAL)
9343
        _CheckInstanceDown(self, instance, "cannot remove disks")
9344

    
9345
      if (disk_op == constants.DDM_ADD and
9346
          len(instance.nics) >= constants.MAX_DISKS):
9347
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
9348
                                   " add more" % constants.MAX_DISKS,
9349
                                   errors.ECODE_STATE)
9350
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
9351
        # an existing disk
9352
        if disk_op < 0 or disk_op >= len(instance.disks):
9353
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9354
                                     " are 0 to %d" %
9355
                                     (disk_op, len(instance.disks)),
9356
                                     errors.ECODE_INVAL)
9357

    
9358
    return
9359

    
9360
  def _ConvertPlainToDrbd(self, feedback_fn):
9361
    """Converts an instance from plain to drbd.
9362

9363
    """
9364
    feedback_fn("Converting template to drbd")
9365
    instance = self.instance
9366
    pnode = instance.primary_node
9367
    snode = self.op.remote_node
9368

    
9369
    # create a fake disk info for _GenerateDiskTemplate
9370
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
9371
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9372
                                      instance.name, pnode, [snode],
9373
                                      disk_info, None, None, 0)
9374
    info = _GetInstanceInfoText(instance)
9375
    feedback_fn("Creating aditional volumes...")
9376
    # first, create the missing data and meta devices
9377
    for disk in new_disks:
9378
      # unfortunately this is... not too nice
9379
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9380
                            info, True)
9381
      for child in disk.children:
9382
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9383
    # at this stage, all new LVs have been created, we can rename the
9384
    # old ones
9385
    feedback_fn("Renaming original volumes...")
9386
    rename_list = [(o, n.children[0].logical_id)
9387
                   for (o, n) in zip(instance.disks, new_disks)]
9388
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9389
    result.Raise("Failed to rename original LVs")
9390

    
9391
    feedback_fn("Initializing DRBD devices...")
9392
    # all child devices are in place, we can now create the DRBD devices
9393
    for disk in new_disks:
9394
      for node in [pnode, snode]:
9395
        f_create = node == pnode
9396
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9397

    
9398
    # at this point, the instance has been modified
9399
    instance.disk_template = constants.DT_DRBD8
9400
    instance.disks = new_disks
9401
    self.cfg.Update(instance, feedback_fn)
9402

    
9403
    # disks are created, waiting for sync
9404
    disk_abort = not _WaitForSync(self, instance)
9405
    if disk_abort:
9406
      raise errors.OpExecError("There are some degraded disks for"
9407
                               " this instance, please cleanup manually")
9408

    
9409
  def _ConvertDrbdToPlain(self, feedback_fn):
9410
    """Converts an instance from drbd to plain.
9411

9412
    """
9413
    instance = self.instance
9414
    assert len(instance.secondary_nodes) == 1
9415
    pnode = instance.primary_node
9416
    snode = instance.secondary_nodes[0]
9417
    feedback_fn("Converting template to plain")
9418

    
9419
    old_disks = instance.disks
9420
    new_disks = [d.children[0] for d in old_disks]
9421

    
9422
    # copy over size and mode
9423
    for parent, child in zip(old_disks, new_disks):
9424
      child.size = parent.size
9425
      child.mode = parent.mode
9426

    
9427
    # update instance structure
9428
    instance.disks = new_disks
9429
    instance.disk_template = constants.DT_PLAIN
9430
    self.cfg.Update(instance, feedback_fn)
9431

    
9432
    feedback_fn("Removing volumes on the secondary node...")
9433
    for disk in old_disks:
9434
      self.cfg.SetDiskID(disk, snode)
9435
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9436
      if msg:
9437
        self.LogWarning("Could not remove block device %s on node %s,"
9438
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9439

    
9440
    feedback_fn("Removing unneeded volumes on the primary node...")
9441
    for idx, disk in enumerate(old_disks):
9442
      meta = disk.children[1]
9443
      self.cfg.SetDiskID(meta, pnode)
9444
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9445
      if msg:
9446
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9447
                        " continuing anyway: %s", idx, pnode, msg)
9448

    
9449

    
9450
  def Exec(self, feedback_fn):
9451
    """Modifies an instance.
9452

9453
    All parameters take effect only at the next restart of the instance.
9454

9455
    """
9456
    # Process here the warnings from CheckPrereq, as we don't have a
9457
    # feedback_fn there.
9458
    for warn in self.warn:
9459
      feedback_fn("WARNING: %s" % warn)
9460

    
9461
    result = []
9462
    instance = self.instance
9463
    # disk changes
9464
    for disk_op, disk_dict in self.op.disks:
9465
      if disk_op == constants.DDM_REMOVE:
9466
        # remove the last disk
9467
        device = instance.disks.pop()
9468
        device_idx = len(instance.disks)
9469
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9470
          self.cfg.SetDiskID(disk, node)
9471
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9472
          if msg:
9473
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9474
                            " continuing anyway", device_idx, node, msg)
9475
        result.append(("disk/%d" % device_idx, "remove"))
9476
      elif disk_op == constants.DDM_ADD:
9477
        # add a new disk
9478
        if instance.disk_template == constants.DT_FILE:
9479
          file_driver, file_path = instance.disks[0].logical_id
9480
          file_path = os.path.dirname(file_path)
9481
        else:
9482
          file_driver = file_path = None
9483
        disk_idx_base = len(instance.disks)
9484
        new_disk = _GenerateDiskTemplate(self,
9485
                                         instance.disk_template,
9486
                                         instance.name, instance.primary_node,
9487
                                         instance.secondary_nodes,
9488
                                         [disk_dict],
9489
                                         file_path,
9490
                                         file_driver,
9491
                                         disk_idx_base)[0]
9492
        instance.disks.append(new_disk)
9493
        info = _GetInstanceInfoText(instance)
9494

    
9495
        logging.info("Creating volume %s for instance %s",
9496
                     new_disk.iv_name, instance.name)
9497
        # Note: this needs to be kept in sync with _CreateDisks
9498
        #HARDCODE
9499
        for node in instance.all_nodes:
9500
          f_create = node == instance.primary_node
9501
          try:
9502
            _CreateBlockDev(self, node, instance, new_disk,
9503
                            f_create, info, f_create)
9504
          except errors.OpExecError, err:
9505
            self.LogWarning("Failed to create volume %s (%s) on"
9506
                            " node %s: %s",
9507
                            new_disk.iv_name, new_disk, node, err)
9508
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9509
                       (new_disk.size, new_disk.mode)))
9510
      else:
9511
        # change a given disk
9512
        instance.disks[disk_op].mode = disk_dict['mode']
9513
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9514

    
9515
    if self.op.disk_template:
9516
      r_shut = _ShutdownInstanceDisks(self, instance)
9517
      if not r_shut:
9518
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
9519
                                 " proceed with disk template conversion")
9520
      mode = (instance.disk_template, self.op.disk_template)
9521
      try:
9522
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9523
      except:
9524
        self.cfg.ReleaseDRBDMinors(instance.name)
9525
        raise
9526
      result.append(("disk_template", self.op.disk_template))
9527

    
9528
    # NIC changes
9529
    for nic_op, nic_dict in self.op.nics:
9530
      if nic_op == constants.DDM_REMOVE:
9531
        # remove the last nic
9532
        del instance.nics[-1]
9533
        result.append(("nic.%d" % len(instance.nics), "remove"))
9534
      elif nic_op == constants.DDM_ADD:
9535
        # mac and bridge should be set, by now
9536
        mac = nic_dict['mac']
9537
        ip = nic_dict.get('ip', None)
9538
        nicparams = self.nic_pinst[constants.DDM_ADD]
9539
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9540
        instance.nics.append(new_nic)
9541
        result.append(("nic.%d" % (len(instance.nics) - 1),
9542
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9543
                       (new_nic.mac, new_nic.ip,
9544
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9545
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9546
                       )))
9547
      else:
9548
        for key in 'mac', 'ip':
9549
          if key in nic_dict:
9550
            setattr(instance.nics[nic_op], key, nic_dict[key])
9551
        if nic_op in self.nic_pinst:
9552
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9553
        for key, val in nic_dict.iteritems():
9554
          result.append(("nic.%s/%d" % (key, nic_op), val))
9555

    
9556
    # hvparams changes
9557
    if self.op.hvparams:
9558
      instance.hvparams = self.hv_inst
9559
      for key, val in self.op.hvparams.iteritems():
9560
        result.append(("hv/%s" % key, val))
9561

    
9562
    # beparams changes
9563
    if self.op.beparams:
9564
      instance.beparams = self.be_inst
9565
      for key, val in self.op.beparams.iteritems():
9566
        result.append(("be/%s" % key, val))
9567

    
9568
    # OS change
9569
    if self.op.os_name:
9570
      instance.os = self.op.os_name
9571

    
9572
    # osparams changes
9573
    if self.op.osparams:
9574
      instance.osparams = self.os_inst
9575
      for key, val in self.op.osparams.iteritems():
9576
        result.append(("os/%s" % key, val))
9577

    
9578
    self.cfg.Update(instance, feedback_fn)
9579

    
9580
    return result
9581

    
9582
  _DISK_CONVERSIONS = {
9583
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9584
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9585
    }
9586

    
9587

    
9588
class LUQueryExports(NoHooksLU):
9589
  """Query the exports list
9590

9591
  """
9592
  _OP_PARAMS = [
9593
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
9594
    ("use_locking", False, ht.TBool),
9595
    ]
9596
  REQ_BGL = False
9597

    
9598
  def ExpandNames(self):
9599
    self.needed_locks = {}
9600
    self.share_locks[locking.LEVEL_NODE] = 1
9601
    if not self.op.nodes:
9602
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9603
    else:
9604
      self.needed_locks[locking.LEVEL_NODE] = \
9605
        _GetWantedNodes(self, self.op.nodes)
9606

    
9607
  def Exec(self, feedback_fn):
9608
    """Compute the list of all the exported system images.
9609

9610
    @rtype: dict
9611
    @return: a dictionary with the structure node->(export-list)
9612
        where export-list is a list of the instances exported on
9613
        that node.
9614

9615
    """
9616
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9617
    rpcresult = self.rpc.call_export_list(self.nodes)
9618
    result = {}
9619
    for node in rpcresult:
9620
      if rpcresult[node].fail_msg:
9621
        result[node] = False
9622
      else:
9623
        result[node] = rpcresult[node].payload
9624

    
9625
    return result
9626

    
9627

    
9628
class LUPrepareExport(NoHooksLU):
9629
  """Prepares an instance for an export and returns useful information.
9630

9631
  """
9632
  _OP_PARAMS = [
9633
    _PInstanceName,
9634
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES)),
9635
    ]
9636
  REQ_BGL = False
9637

    
9638
  def ExpandNames(self):
9639
    self._ExpandAndLockInstance()
9640

    
9641
  def CheckPrereq(self):
9642
    """Check prerequisites.
9643

9644
    """
9645
    instance_name = self.op.instance_name
9646

    
9647
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9648
    assert self.instance is not None, \
9649
          "Cannot retrieve locked instance %s" % self.op.instance_name
9650
    _CheckNodeOnline(self, self.instance.primary_node)
9651

    
9652
    self._cds = _GetClusterDomainSecret()
9653

    
9654
  def Exec(self, feedback_fn):
9655
    """Prepares an instance for an export.
9656

9657
    """
9658
    instance = self.instance
9659

    
9660
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9661
      salt = utils.GenerateSecret(8)
9662

    
9663
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9664
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9665
                                              constants.RIE_CERT_VALIDITY)
9666
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9667

    
9668
      (name, cert_pem) = result.payload
9669

    
9670
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9671
                                             cert_pem)
9672

    
9673
      return {
9674
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9675
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9676
                          salt),
9677
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9678
        }
9679

    
9680
    return None
9681

    
9682

    
9683
class LUExportInstance(LogicalUnit):
9684
  """Export an instance to an image in the cluster.
9685

9686
  """
9687
  HPATH = "instance-export"
9688
  HTYPE = constants.HTYPE_INSTANCE
9689
  _OP_PARAMS = [
9690
    _PInstanceName,
9691
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList)),
9692
    ("shutdown", True, ht.TBool),
9693
    _PShutdownTimeout,
9694
    ("remove_instance", False, ht.TBool),
9695
    ("ignore_remove_failures", False, ht.TBool),
9696
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES)),
9697
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone)),
9698
    ("destination_x509_ca", None, ht.TMaybeString),
9699
    ]
9700
  REQ_BGL = False
9701

    
9702
  def CheckArguments(self):
9703
    """Check the arguments.
9704

9705
    """
9706
    self.x509_key_name = self.op.x509_key_name
9707
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9708

    
9709
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9710
      if not self.x509_key_name:
9711
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9712
                                   errors.ECODE_INVAL)
9713

    
9714
      if not self.dest_x509_ca_pem:
9715
        raise errors.OpPrereqError("Missing destination X509 CA",
9716
                                   errors.ECODE_INVAL)
9717

    
9718
  def ExpandNames(self):
9719
    self._ExpandAndLockInstance()
9720

    
9721
    # Lock all nodes for local exports
9722
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9723
      # FIXME: lock only instance primary and destination node
9724
      #
9725
      # Sad but true, for now we have do lock all nodes, as we don't know where
9726
      # the previous export might be, and in this LU we search for it and
9727
      # remove it from its current node. In the future we could fix this by:
9728
      #  - making a tasklet to search (share-lock all), then create the
9729
      #    new one, then one to remove, after
9730
      #  - removing the removal operation altogether
9731
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9732

    
9733
  def DeclareLocks(self, level):
9734
    """Last minute lock declaration."""
9735
    # All nodes are locked anyway, so nothing to do here.
9736

    
9737
  def BuildHooksEnv(self):
9738
    """Build hooks env.
9739

9740
    This will run on the master, primary node and target node.
9741

9742
    """
9743
    env = {
9744
      "EXPORT_MODE": self.op.mode,
9745
      "EXPORT_NODE": self.op.target_node,
9746
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9747
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9748
      # TODO: Generic function for boolean env variables
9749
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9750
      }
9751

    
9752
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9753

    
9754
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9755

    
9756
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9757
      nl.append(self.op.target_node)
9758

    
9759
    return env, nl, nl
9760

    
9761
  def CheckPrereq(self):
9762
    """Check prerequisites.
9763

9764
    This checks that the instance and node names are valid.
9765

9766
    """
9767
    instance_name = self.op.instance_name
9768

    
9769
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9770
    assert self.instance is not None, \
9771
          "Cannot retrieve locked instance %s" % self.op.instance_name
9772
    _CheckNodeOnline(self, self.instance.primary_node)
9773

    
9774
    if (self.op.remove_instance and self.instance.admin_up and
9775
        not self.op.shutdown):
9776
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9777
                                 " down before")
9778

    
9779
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9780
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9781
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9782
      assert self.dst_node is not None
9783

    
9784
      _CheckNodeOnline(self, self.dst_node.name)
9785
      _CheckNodeNotDrained(self, self.dst_node.name)
9786

    
9787
      self._cds = None
9788
      self.dest_disk_info = None
9789
      self.dest_x509_ca = None
9790

    
9791
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9792
      self.dst_node = None
9793

    
9794
      if len(self.op.target_node) != len(self.instance.disks):
9795
        raise errors.OpPrereqError(("Received destination information for %s"
9796
                                    " disks, but instance %s has %s disks") %
9797
                                   (len(self.op.target_node), instance_name,
9798
                                    len(self.instance.disks)),
9799
                                   errors.ECODE_INVAL)
9800

    
9801
      cds = _GetClusterDomainSecret()
9802

    
9803
      # Check X509 key name
9804
      try:
9805
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9806
      except (TypeError, ValueError), err:
9807
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9808

    
9809
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9810
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9811
                                   errors.ECODE_INVAL)
9812

    
9813
      # Load and verify CA
9814
      try:
9815
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9816
      except OpenSSL.crypto.Error, err:
9817
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9818
                                   (err, ), errors.ECODE_INVAL)
9819

    
9820
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9821
      if errcode is not None:
9822
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9823
                                   (msg, ), errors.ECODE_INVAL)
9824

    
9825
      self.dest_x509_ca = cert
9826

    
9827
      # Verify target information
9828
      disk_info = []
9829
      for idx, disk_data in enumerate(self.op.target_node):
9830
        try:
9831
          (host, port, magic) = \
9832
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9833
        except errors.GenericError, err:
9834
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9835
                                     (idx, err), errors.ECODE_INVAL)
9836

    
9837
        disk_info.append((host, port, magic))
9838

    
9839
      assert len(disk_info) == len(self.op.target_node)
9840
      self.dest_disk_info = disk_info
9841

    
9842
    else:
9843
      raise errors.ProgrammerError("Unhandled export mode %r" %
9844
                                   self.op.mode)
9845

    
9846
    # instance disk type verification
9847
    # TODO: Implement export support for file-based disks
9848
    for disk in self.instance.disks:
9849
      if disk.dev_type == constants.LD_FILE:
9850
        raise errors.OpPrereqError("Export not supported for instances with"
9851
                                   " file-based disks", errors.ECODE_INVAL)
9852

    
9853
  def _CleanupExports(self, feedback_fn):
9854
    """Removes exports of current instance from all other nodes.
9855

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

9859
    """
9860
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9861

    
9862
    nodelist = self.cfg.GetNodeList()
9863
    nodelist.remove(self.dst_node.name)
9864

    
9865
    # on one-node clusters nodelist will be empty after the removal
9866
    # if we proceed the backup would be removed because OpQueryExports
9867
    # substitutes an empty list with the full cluster node list.
9868
    iname = self.instance.name
9869
    if nodelist:
9870
      feedback_fn("Removing old exports for instance %s" % iname)
9871
      exportlist = self.rpc.call_export_list(nodelist)
9872
      for node in exportlist:
9873
        if exportlist[node].fail_msg:
9874
          continue
9875
        if iname in exportlist[node].payload:
9876
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9877
          if msg:
9878
            self.LogWarning("Could not remove older export for instance %s"
9879
                            " on node %s: %s", iname, node, msg)
9880

    
9881
  def Exec(self, feedback_fn):
9882
    """Export an instance to an image in the cluster.
9883

9884
    """
9885
    assert self.op.mode in constants.EXPORT_MODES
9886

    
9887
    instance = self.instance
9888
    src_node = instance.primary_node
9889

    
9890
    if self.op.shutdown:
9891
      # shutdown the instance, but not the disks
9892
      feedback_fn("Shutting down instance %s" % instance.name)
9893
      result = self.rpc.call_instance_shutdown(src_node, instance,
9894
                                               self.op.shutdown_timeout)
9895
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9896
      result.Raise("Could not shutdown instance %s on"
9897
                   " node %s" % (instance.name, src_node))
9898

    
9899
    # set the disks ID correctly since call_instance_start needs the
9900
    # correct drbd minor to create the symlinks
9901
    for disk in instance.disks:
9902
      self.cfg.SetDiskID(disk, src_node)
9903

    
9904
    activate_disks = (not instance.admin_up)
9905

    
9906
    if activate_disks:
9907
      # Activate the instance disks if we'exporting a stopped instance
9908
      feedback_fn("Activating disks for %s" % instance.name)
9909
      _StartInstanceDisks(self, instance, None)
9910

    
9911
    try:
9912
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9913
                                                     instance)
9914

    
9915
      helper.CreateSnapshots()
9916
      try:
9917
        if (self.op.shutdown and instance.admin_up and
9918
            not self.op.remove_instance):
9919
          assert not activate_disks
9920
          feedback_fn("Starting instance %s" % instance.name)
9921
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9922
          msg = result.fail_msg
9923
          if msg:
9924
            feedback_fn("Failed to start instance: %s" % msg)
9925
            _ShutdownInstanceDisks(self, instance)
9926
            raise errors.OpExecError("Could not start instance: %s" % msg)
9927

    
9928
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9929
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9930
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9931
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9932
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9933

    
9934
          (key_name, _, _) = self.x509_key_name
9935

    
9936
          dest_ca_pem = \
9937
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9938
                                            self.dest_x509_ca)
9939

    
9940
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9941
                                                     key_name, dest_ca_pem,
9942
                                                     timeouts)
9943
      finally:
9944
        helper.Cleanup()
9945

    
9946
      # Check for backwards compatibility
9947
      assert len(dresults) == len(instance.disks)
9948
      assert compat.all(isinstance(i, bool) for i in dresults), \
9949
             "Not all results are boolean: %r" % dresults
9950

    
9951
    finally:
9952
      if activate_disks:
9953
        feedback_fn("Deactivating disks for %s" % instance.name)
9954
        _ShutdownInstanceDisks(self, instance)
9955

    
9956
    if not (compat.all(dresults) and fin_resu):
9957
      failures = []
9958
      if not fin_resu:
9959
        failures.append("export finalization")
9960
      if not compat.all(dresults):
9961
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
9962
                               if not dsk)
9963
        failures.append("disk export: disk(s) %s" % fdsk)
9964

    
9965
      raise errors.OpExecError("Export failed, errors in %s" %
9966
                               utils.CommaJoin(failures))
9967

    
9968
    # At this point, the export was successful, we can cleanup/finish
9969

    
9970
    # Remove instance if requested
9971
    if self.op.remove_instance:
9972
      feedback_fn("Removing instance %s" % instance.name)
9973
      _RemoveInstance(self, feedback_fn, instance,
9974
                      self.op.ignore_remove_failures)
9975

    
9976
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9977
      self._CleanupExports(feedback_fn)
9978

    
9979
    return fin_resu, dresults
9980

    
9981

    
9982
class LURemoveExport(NoHooksLU):
9983
  """Remove exports related to the named instance.
9984

9985
  """
9986
  _OP_PARAMS = [
9987
    _PInstanceName,
9988
    ]
9989
  REQ_BGL = False
9990

    
9991
  def ExpandNames(self):
9992
    self.needed_locks = {}
9993
    # We need all nodes to be locked in order for RemoveExport to work, but we
9994
    # don't need to lock the instance itself, as nothing will happen to it (and
9995
    # we can remove exports also for a removed instance)
9996
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9997

    
9998
  def Exec(self, feedback_fn):
9999
    """Remove any export.
10000

10001
    """
10002
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
10003
    # If the instance was not found we'll try with the name that was passed in.
10004
    # This will only work if it was an FQDN, though.
10005
    fqdn_warn = False
10006
    if not instance_name:
10007
      fqdn_warn = True
10008
      instance_name = self.op.instance_name
10009

    
10010
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
10011
    exportlist = self.rpc.call_export_list(locked_nodes)
10012
    found = False
10013
    for node in exportlist:
10014
      msg = exportlist[node].fail_msg
10015
      if msg:
10016
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
10017
        continue
10018
      if instance_name in exportlist[node].payload:
10019
        found = True
10020
        result = self.rpc.call_export_remove(node, instance_name)
10021
        msg = result.fail_msg
10022
        if msg:
10023
          logging.error("Could not remove export for instance %s"
10024
                        " on node %s: %s", instance_name, node, msg)
10025

    
10026
    if fqdn_warn and not found:
10027
      feedback_fn("Export not found. If trying to remove an export belonging"
10028
                  " to a deleted instance please use its Fully Qualified"
10029
                  " Domain Name.")
10030

    
10031

    
10032
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
10033
  """Generic tags LU.
10034

10035
  This is an abstract class which is the parent of all the other tags LUs.
10036

10037
  """
10038

    
10039
  def ExpandNames(self):
10040
    self.needed_locks = {}
10041
    if self.op.kind == constants.TAG_NODE:
10042
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
10043
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
10044
    elif self.op.kind == constants.TAG_INSTANCE:
10045
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
10046
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
10047

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

    
10051
  def CheckPrereq(self):
10052
    """Check prerequisites.
10053

10054
    """
10055
    if self.op.kind == constants.TAG_CLUSTER:
10056
      self.target = self.cfg.GetClusterInfo()
10057
    elif self.op.kind == constants.TAG_NODE:
10058
      self.target = self.cfg.GetNodeInfo(self.op.name)
10059
    elif self.op.kind == constants.TAG_INSTANCE:
10060
      self.target = self.cfg.GetInstanceInfo(self.op.name)
10061
    else:
10062
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
10063
                                 str(self.op.kind), errors.ECODE_INVAL)
10064

    
10065

    
10066
class LUGetTags(TagsLU):
10067
  """Returns the tags of a given object.
10068

10069
  """
10070
  _OP_PARAMS = [
10071
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
10072
    # Name is only meaningful for nodes and instances
10073
    ("name", ht.NoDefault, ht.TMaybeString),
10074
    ]
10075
  REQ_BGL = False
10076

    
10077
  def ExpandNames(self):
10078
    TagsLU.ExpandNames(self)
10079

    
10080
    # Share locks as this is only a read operation
10081
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
10082

    
10083
  def Exec(self, feedback_fn):
10084
    """Returns the tag list.
10085

10086
    """
10087
    return list(self.target.GetTags())
10088

    
10089

    
10090
class LUSearchTags(NoHooksLU):
10091
  """Searches the tags for a given pattern.
10092

10093
  """
10094
  _OP_PARAMS = [
10095
    ("pattern", ht.NoDefault, ht.TNonEmptyString),
10096
    ]
10097
  REQ_BGL = False
10098

    
10099
  def ExpandNames(self):
10100
    self.needed_locks = {}
10101

    
10102
  def CheckPrereq(self):
10103
    """Check prerequisites.
10104

10105
    This checks the pattern passed for validity by compiling it.
10106

10107
    """
10108
    try:
10109
      self.re = re.compile(self.op.pattern)
10110
    except re.error, err:
10111
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
10112
                                 (self.op.pattern, err), errors.ECODE_INVAL)
10113

    
10114
  def Exec(self, feedback_fn):
10115
    """Returns the tag list.
10116

10117
    """
10118
    cfg = self.cfg
10119
    tgts = [("/cluster", cfg.GetClusterInfo())]
10120
    ilist = cfg.GetAllInstancesInfo().values()
10121
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
10122
    nlist = cfg.GetAllNodesInfo().values()
10123
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
10124
    results = []
10125
    for path, target in tgts:
10126
      for tag in target.GetTags():
10127
        if self.re.search(tag):
10128
          results.append((path, tag))
10129
    return results
10130

    
10131

    
10132
class LUAddTags(TagsLU):
10133
  """Sets a tag on a given object.
10134

10135
  """
10136
  _OP_PARAMS = [
10137
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
10138
    # Name is only meaningful for nodes and instances
10139
    ("name", ht.NoDefault, ht.TMaybeString),
10140
    ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
10141
    ]
10142
  REQ_BGL = False
10143

    
10144
  def CheckPrereq(self):
10145
    """Check prerequisites.
10146

10147
    This checks the type and length of the tag name and value.
10148

10149
    """
10150
    TagsLU.CheckPrereq(self)
10151
    for tag in self.op.tags:
10152
      objects.TaggableObject.ValidateTag(tag)
10153

    
10154
  def Exec(self, feedback_fn):
10155
    """Sets the tag.
10156

10157
    """
10158
    try:
10159
      for tag in self.op.tags:
10160
        self.target.AddTag(tag)
10161
    except errors.TagError, err:
10162
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
10163
    self.cfg.Update(self.target, feedback_fn)
10164

    
10165

    
10166
class LUDelTags(TagsLU):
10167
  """Delete a list of tags from a given object.
10168

10169
  """
10170
  _OP_PARAMS = [
10171
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
10172
    # Name is only meaningful for nodes and instances
10173
    ("name", ht.NoDefault, ht.TMaybeString),
10174
    ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
10175
    ]
10176
  REQ_BGL = False
10177

    
10178
  def CheckPrereq(self):
10179
    """Check prerequisites.
10180

10181
    This checks that we have the given tag.
10182

10183
    """
10184
    TagsLU.CheckPrereq(self)
10185
    for tag in self.op.tags:
10186
      objects.TaggableObject.ValidateTag(tag)
10187
    del_tags = frozenset(self.op.tags)
10188
    cur_tags = self.target.GetTags()
10189

    
10190
    diff_tags = del_tags - cur_tags
10191
    if diff_tags:
10192
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
10193
      raise errors.OpPrereqError("Tag(s) %s not found" %
10194
                                 (utils.CommaJoin(diff_names), ),
10195
                                 errors.ECODE_NOENT)
10196

    
10197
  def Exec(self, feedback_fn):
10198
    """Remove the tag from the object.
10199

10200
    """
10201
    for tag in self.op.tags:
10202
      self.target.RemoveTag(tag)
10203
    self.cfg.Update(self.target, feedback_fn)
10204

    
10205

    
10206
class LUTestDelay(NoHooksLU):
10207
  """Sleep for a specified amount of time.
10208

10209
  This LU sleeps on the master and/or nodes for a specified amount of
10210
  time.
10211

10212
  """
10213
  _OP_PARAMS = [
10214
    ("duration", ht.NoDefault, ht.TFloat),
10215
    ("on_master", True, ht.TBool),
10216
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
10217
    ("repeat", 0, ht.TPositiveInt)
10218
    ]
10219
  REQ_BGL = False
10220

    
10221
  def ExpandNames(self):
10222
    """Expand names and set required locks.
10223

10224
    This expands the node list, if any.
10225

10226
    """
10227
    self.needed_locks = {}
10228
    if self.op.on_nodes:
10229
      # _GetWantedNodes can be used here, but is not always appropriate to use
10230
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
10231
      # more information.
10232
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
10233
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
10234

    
10235
  def _TestDelay(self):
10236
    """Do the actual sleep.
10237

10238
    """
10239
    if self.op.on_master:
10240
      if not utils.TestDelay(self.op.duration):
10241
        raise errors.OpExecError("Error during master delay test")
10242
    if self.op.on_nodes:
10243
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
10244
      for node, node_result in result.items():
10245
        node_result.Raise("Failure during rpc call to node %s" % node)
10246

    
10247
  def Exec(self, feedback_fn):
10248
    """Execute the test delay opcode, with the wanted repetitions.
10249

10250
    """
10251
    if self.op.repeat == 0:
10252
      self._TestDelay()
10253
    else:
10254
      top_value = self.op.repeat - 1
10255
      for i in range(self.op.repeat):
10256
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
10257
        self._TestDelay()
10258

    
10259

    
10260
class LUTestJobqueue(NoHooksLU):
10261
  """Utility LU to test some aspects of the job queue.
10262

10263
  """
10264
  _OP_PARAMS = [
10265
    ("notify_waitlock", False, ht.TBool),
10266
    ("notify_exec", False, ht.TBool),
10267
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString)),
10268
    ("fail", False, ht.TBool),
10269
    ]
10270
  REQ_BGL = False
10271

    
10272
  # Must be lower than default timeout for WaitForJobChange to see whether it
10273
  # notices changed jobs
10274
  _CLIENT_CONNECT_TIMEOUT = 20.0
10275
  _CLIENT_CONFIRM_TIMEOUT = 60.0
10276

    
10277
  @classmethod
10278
  def _NotifyUsingSocket(cls, cb, errcls):
10279
    """Opens a Unix socket and waits for another program to connect.
10280

10281
    @type cb: callable
10282
    @param cb: Callback to send socket name to client
10283
    @type errcls: class
10284
    @param errcls: Exception class to use for errors
10285

10286
    """
10287
    # Using a temporary directory as there's no easy way to create temporary
10288
    # sockets without writing a custom loop around tempfile.mktemp and
10289
    # socket.bind
10290
    tmpdir = tempfile.mkdtemp()
10291
    try:
10292
      tmpsock = utils.PathJoin(tmpdir, "sock")
10293

    
10294
      logging.debug("Creating temporary socket at %s", tmpsock)
10295
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
10296
      try:
10297
        sock.bind(tmpsock)
10298
        sock.listen(1)
10299

    
10300
        # Send details to client
10301
        cb(tmpsock)
10302

    
10303
        # Wait for client to connect before continuing
10304
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
10305
        try:
10306
          (conn, _) = sock.accept()
10307
        except socket.error, err:
10308
          raise errcls("Client didn't connect in time (%s)" % err)
10309
      finally:
10310
        sock.close()
10311
    finally:
10312
      # Remove as soon as client is connected
10313
      shutil.rmtree(tmpdir)
10314

    
10315
    # Wait for client to close
10316
    try:
10317
      try:
10318
        # pylint: disable-msg=E1101
10319
        # Instance of '_socketobject' has no ... member
10320
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
10321
        conn.recv(1)
10322
      except socket.error, err:
10323
        raise errcls("Client failed to confirm notification (%s)" % err)
10324
    finally:
10325
      conn.close()
10326

    
10327
  def _SendNotification(self, test, arg, sockname):
10328
    """Sends a notification to the client.
10329

10330
    @type test: string
10331
    @param test: Test name
10332
    @param arg: Test argument (depends on test)
10333
    @type sockname: string
10334
    @param sockname: Socket path
10335

10336
    """
10337
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
10338

    
10339
  def _Notify(self, prereq, test, arg):
10340
    """Notifies the client of a test.
10341

10342
    @type prereq: bool
10343
    @param prereq: Whether this is a prereq-phase test
10344
    @type test: string
10345
    @param test: Test name
10346
    @param arg: Test argument (depends on test)
10347

10348
    """
10349
    if prereq:
10350
      errcls = errors.OpPrereqError
10351
    else:
10352
      errcls = errors.OpExecError
10353

    
10354
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
10355
                                                  test, arg),
10356
                                   errcls)
10357

    
10358
  def CheckArguments(self):
10359
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
10360
    self.expandnames_calls = 0
10361

    
10362
  def ExpandNames(self):
10363
    checkargs_calls = getattr(self, "checkargs_calls", 0)
10364
    if checkargs_calls < 1:
10365
      raise errors.ProgrammerError("CheckArguments was not called")
10366

    
10367
    self.expandnames_calls += 1
10368

    
10369
    if self.op.notify_waitlock:
10370
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
10371

    
10372
    self.LogInfo("Expanding names")
10373

    
10374
    # Get lock on master node (just to get a lock, not for a particular reason)
10375
    self.needed_locks = {
10376
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
10377
      }
10378

    
10379
  def Exec(self, feedback_fn):
10380
    if self.expandnames_calls < 1:
10381
      raise errors.ProgrammerError("ExpandNames was not called")
10382

    
10383
    if self.op.notify_exec:
10384
      self._Notify(False, constants.JQT_EXEC, None)
10385

    
10386
    self.LogInfo("Executing")
10387

    
10388
    if self.op.log_messages:
10389
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
10390
      for idx, msg in enumerate(self.op.log_messages):
10391
        self.LogInfo("Sending log message %s", idx + 1)
10392
        feedback_fn(constants.JQT_MSGPREFIX + msg)
10393
        # Report how many test messages have been sent
10394
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
10395

    
10396
    if self.op.fail:
10397
      raise errors.OpExecError("Opcode failure was requested")
10398

    
10399
    return True
10400

    
10401

    
10402
class IAllocator(object):
10403
  """IAllocator framework.
10404

10405
  An IAllocator instance has three sets of attributes:
10406
    - cfg that is needed to query the cluster
10407
    - input data (all members of the _KEYS class attribute are required)
10408
    - four buffer attributes (in|out_data|text), that represent the
10409
      input (to the external script) in text and data structure format,
10410
      and the output from it, again in two formats
10411
    - the result variables from the script (success, info, nodes) for
10412
      easy usage
10413

10414
  """
10415
  # pylint: disable-msg=R0902
10416
  # lots of instance attributes
10417
  _ALLO_KEYS = [
10418
    "name", "mem_size", "disks", "disk_template",
10419
    "os", "tags", "nics", "vcpus", "hypervisor",
10420
    ]
10421
  _RELO_KEYS = [
10422
    "name", "relocate_from",
10423
    ]
10424
  _EVAC_KEYS = [
10425
    "evac_nodes",
10426
    ]
10427

    
10428
  def __init__(self, cfg, rpc, mode, **kwargs):
10429
    self.cfg = cfg
10430
    self.rpc = rpc
10431
    # init buffer variables
10432
    self.in_text = self.out_text = self.in_data = self.out_data = None
10433
    # init all input fields so that pylint is happy
10434
    self.mode = mode
10435
    self.mem_size = self.disks = self.disk_template = None
10436
    self.os = self.tags = self.nics = self.vcpus = None
10437
    self.hypervisor = None
10438
    self.relocate_from = None
10439
    self.name = None
10440
    self.evac_nodes = None
10441
    # computed fields
10442
    self.required_nodes = None
10443
    # init result fields
10444
    self.success = self.info = self.result = None
10445
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10446
      keyset = self._ALLO_KEYS
10447
      fn = self._AddNewInstance
10448
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10449
      keyset = self._RELO_KEYS
10450
      fn = self._AddRelocateInstance
10451
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10452
      keyset = self._EVAC_KEYS
10453
      fn = self._AddEvacuateNodes
10454
    else:
10455
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
10456
                                   " IAllocator" % self.mode)
10457
    for key in kwargs:
10458
      if key not in keyset:
10459
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
10460
                                     " IAllocator" % key)
10461
      setattr(self, key, kwargs[key])
10462

    
10463
    for key in keyset:
10464
      if key not in kwargs:
10465
        raise errors.ProgrammerError("Missing input parameter '%s' to"
10466
                                     " IAllocator" % key)
10467
    self._BuildInputData(fn)
10468

    
10469
  def _ComputeClusterData(self):
10470
    """Compute the generic allocator input data.
10471

10472
    This is the data that is independent of the actual operation.
10473

10474
    """
10475
    cfg = self.cfg
10476
    cluster_info = cfg.GetClusterInfo()
10477
    # cluster data
10478
    data = {
10479
      "version": constants.IALLOCATOR_VERSION,
10480
      "cluster_name": cfg.GetClusterName(),
10481
      "cluster_tags": list(cluster_info.GetTags()),
10482
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
10483
      # we don't have job IDs
10484
      }
10485
    iinfo = cfg.GetAllInstancesInfo().values()
10486
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
10487

    
10488
    # node data
10489
    node_list = cfg.GetNodeList()
10490

    
10491
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10492
      hypervisor_name = self.hypervisor
10493
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10494
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
10495
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10496
      hypervisor_name = cluster_info.enabled_hypervisors[0]
10497

    
10498
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
10499
                                        hypervisor_name)
10500
    node_iinfo = \
10501
      self.rpc.call_all_instances_info(node_list,
10502
                                       cluster_info.enabled_hypervisors)
10503

    
10504
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
10505

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

    
10508
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
10509

    
10510
    self.in_data = data
10511

    
10512
  @staticmethod
10513
  def _ComputeNodeGroupData(cfg):
10514
    """Compute node groups data.
10515

10516
    """
10517
    ng = {}
10518
    for guuid, gdata in cfg.GetAllNodeGroupsInfo().items():
10519
      ng[guuid] = { "name": gdata.name }
10520
    return ng
10521

    
10522
  @staticmethod
10523
  def _ComputeNodeData(cfg, node_data, node_iinfo, i_list):
10524
    """Compute global node data.
10525

10526
    """
10527
    node_results = {}
10528
    for nname, nresult in node_data.items():
10529
      # first fill in static (config-based) values
10530
      ninfo = cfg.GetNodeInfo(nname)
10531
      pnr = {
10532
        "tags": list(ninfo.GetTags()),
10533
        "primary_ip": ninfo.primary_ip,
10534
        "secondary_ip": ninfo.secondary_ip,
10535
        "offline": ninfo.offline,
10536
        "drained": ninfo.drained,
10537
        "master_candidate": ninfo.master_candidate,
10538
        "group": ninfo.group,
10539
        "master_capable": ninfo.master_capable,
10540
        "vm_capable": ninfo.vm_capable,
10541
        }
10542

    
10543
      if not (ninfo.offline or ninfo.drained):
10544
        nresult.Raise("Can't get data for node %s" % nname)
10545
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
10546
                                nname)
10547
        remote_info = nresult.payload
10548

    
10549
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
10550
                     'vg_size', 'vg_free', 'cpu_total']:
10551
          if attr not in remote_info:
10552
            raise errors.OpExecError("Node '%s' didn't return attribute"
10553
                                     " '%s'" % (nname, attr))
10554
          if not isinstance(remote_info[attr], int):
10555
            raise errors.OpExecError("Node '%s' returned invalid value"
10556
                                     " for '%s': %s" %
10557
                                     (nname, attr, remote_info[attr]))
10558
        # compute memory used by primary instances
10559
        i_p_mem = i_p_up_mem = 0
10560
        for iinfo, beinfo in i_list:
10561
          if iinfo.primary_node == nname:
10562
            i_p_mem += beinfo[constants.BE_MEMORY]
10563
            if iinfo.name not in node_iinfo[nname].payload:
10564
              i_used_mem = 0
10565
            else:
10566
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
10567
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
10568
            remote_info['memory_free'] -= max(0, i_mem_diff)
10569

    
10570
            if iinfo.admin_up:
10571
              i_p_up_mem += beinfo[constants.BE_MEMORY]
10572

    
10573
        # compute memory used by instances
10574
        pnr_dyn = {
10575
          "total_memory": remote_info['memory_total'],
10576
          "reserved_memory": remote_info['memory_dom0'],
10577
          "free_memory": remote_info['memory_free'],
10578
          "total_disk": remote_info['vg_size'],
10579
          "free_disk": remote_info['vg_free'],
10580
          "total_cpus": remote_info['cpu_total'],
10581
          "i_pri_memory": i_p_mem,
10582
          "i_pri_up_memory": i_p_up_mem,
10583
          }
10584
        pnr.update(pnr_dyn)
10585

    
10586
      node_results[nname] = pnr
10587

    
10588
    return node_results
10589

    
10590
  @staticmethod
10591
  def _ComputeInstanceData(cluster_info, i_list):
10592
    """Compute global instance data.
10593

10594
    """
10595
    instance_data = {}
10596
    for iinfo, beinfo in i_list:
10597
      nic_data = []
10598
      for nic in iinfo.nics:
10599
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
10600
        nic_dict = {"mac": nic.mac,
10601
                    "ip": nic.ip,
10602
                    "mode": filled_params[constants.NIC_MODE],
10603
                    "link": filled_params[constants.NIC_LINK],
10604
                   }
10605
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
10606
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
10607
        nic_data.append(nic_dict)
10608
      pir = {
10609
        "tags": list(iinfo.GetTags()),
10610
        "admin_up": iinfo.admin_up,
10611
        "vcpus": beinfo[constants.BE_VCPUS],
10612
        "memory": beinfo[constants.BE_MEMORY],
10613
        "os": iinfo.os,
10614
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
10615
        "nics": nic_data,
10616
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
10617
        "disk_template": iinfo.disk_template,
10618
        "hypervisor": iinfo.hypervisor,
10619
        }
10620
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
10621
                                                 pir["disks"])
10622
      instance_data[iinfo.name] = pir
10623

    
10624
    return instance_data
10625

    
10626
  def _AddNewInstance(self):
10627
    """Add new instance data to allocator structure.
10628

10629
    This in combination with _AllocatorGetClusterData will create the
10630
    correct structure needed as input for the allocator.
10631

10632
    The checks for the completeness of the opcode must have already been
10633
    done.
10634

10635
    """
10636
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
10637

    
10638
    if self.disk_template in constants.DTS_NET_MIRROR:
10639
      self.required_nodes = 2
10640
    else:
10641
      self.required_nodes = 1
10642
    request = {
10643
      "name": self.name,
10644
      "disk_template": self.disk_template,
10645
      "tags": self.tags,
10646
      "os": self.os,
10647
      "vcpus": self.vcpus,
10648
      "memory": self.mem_size,
10649
      "disks": self.disks,
10650
      "disk_space_total": disk_space,
10651
      "nics": self.nics,
10652
      "required_nodes": self.required_nodes,
10653
      }
10654
    return request
10655

    
10656
  def _AddRelocateInstance(self):
10657
    """Add relocate instance data to allocator structure.
10658

10659
    This in combination with _IAllocatorGetClusterData will create the
10660
    correct structure needed as input for the allocator.
10661

10662
    The checks for the completeness of the opcode must have already been
10663
    done.
10664

10665
    """
10666
    instance = self.cfg.GetInstanceInfo(self.name)
10667
    if instance is None:
10668
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
10669
                                   " IAllocator" % self.name)
10670

    
10671
    if instance.disk_template not in constants.DTS_NET_MIRROR:
10672
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
10673
                                 errors.ECODE_INVAL)
10674

    
10675
    if len(instance.secondary_nodes) != 1:
10676
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
10677
                                 errors.ECODE_STATE)
10678

    
10679
    self.required_nodes = 1
10680
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
10681
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
10682

    
10683
    request = {
10684
      "name": self.name,
10685
      "disk_space_total": disk_space,
10686
      "required_nodes": self.required_nodes,
10687
      "relocate_from": self.relocate_from,
10688
      }
10689
    return request
10690

    
10691
  def _AddEvacuateNodes(self):
10692
    """Add evacuate nodes data to allocator structure.
10693

10694
    """
10695
    request = {
10696
      "evac_nodes": self.evac_nodes
10697
      }
10698
    return request
10699

    
10700
  def _BuildInputData(self, fn):
10701
    """Build input data structures.
10702

10703
    """
10704
    self._ComputeClusterData()
10705

    
10706
    request = fn()
10707
    request["type"] = self.mode
10708
    self.in_data["request"] = request
10709

    
10710
    self.in_text = serializer.Dump(self.in_data)
10711

    
10712
  def Run(self, name, validate=True, call_fn=None):
10713
    """Run an instance allocator and return the results.
10714

10715
    """
10716
    if call_fn is None:
10717
      call_fn = self.rpc.call_iallocator_runner
10718

    
10719
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
10720
    result.Raise("Failure while running the iallocator script")
10721

    
10722
    self.out_text = result.payload
10723
    if validate:
10724
      self._ValidateResult()
10725

    
10726
  def _ValidateResult(self):
10727
    """Process the allocator results.
10728

10729
    This will process and if successful save the result in
10730
    self.out_data and the other parameters.
10731

10732
    """
10733
    try:
10734
      rdict = serializer.Load(self.out_text)
10735
    except Exception, err:
10736
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
10737

    
10738
    if not isinstance(rdict, dict):
10739
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
10740

    
10741
    # TODO: remove backwards compatiblity in later versions
10742
    if "nodes" in rdict and "result" not in rdict:
10743
      rdict["result"] = rdict["nodes"]
10744
      del rdict["nodes"]
10745

    
10746
    for key in "success", "info", "result":
10747
      if key not in rdict:
10748
        raise errors.OpExecError("Can't parse iallocator results:"
10749
                                 " missing key '%s'" % key)
10750
      setattr(self, key, rdict[key])
10751

    
10752
    if not isinstance(rdict["result"], list):
10753
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
10754
                               " is not a list")
10755
    self.out_data = rdict
10756

    
10757

    
10758
class LUTestAllocator(NoHooksLU):
10759
  """Run allocator tests.
10760

10761
  This LU runs the allocator tests
10762

10763
  """
10764
  _OP_PARAMS = [
10765
    ("direction", ht.NoDefault,
10766
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS)),
10767
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES)),
10768
    ("name", ht.NoDefault, ht.TNonEmptyString),
10769
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
10770
      ht.TDictOf(ht.TElemOf(["mac", "ip", "bridge"]),
10771
               ht.TOr(ht.TNone, ht.TNonEmptyString))))),
10772
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList)),
10773
    ("hypervisor", None, ht.TMaybeString),
10774
    ("allocator", None, ht.TMaybeString),
10775
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
10776
    ("mem_size", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
10777
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
10778
    ("os", None, ht.TMaybeString),
10779
    ("disk_template", None, ht.TMaybeString),
10780
    ("evac_nodes", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString))),
10781
    ]
10782

    
10783
  def CheckPrereq(self):
10784
    """Check prerequisites.
10785

10786
    This checks the opcode parameters depending on the director and mode test.
10787

10788
    """
10789
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10790
      for attr in ["mem_size", "disks", "disk_template",
10791
                   "os", "tags", "nics", "vcpus"]:
10792
        if not hasattr(self.op, attr):
10793
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
10794
                                     attr, errors.ECODE_INVAL)
10795
      iname = self.cfg.ExpandInstanceName(self.op.name)
10796
      if iname is not None:
10797
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
10798
                                   iname, errors.ECODE_EXISTS)
10799
      if not isinstance(self.op.nics, list):
10800
        raise errors.OpPrereqError("Invalid parameter 'nics'",
10801
                                   errors.ECODE_INVAL)
10802
      if not isinstance(self.op.disks, list):
10803
        raise errors.OpPrereqError("Invalid parameter 'disks'",
10804
                                   errors.ECODE_INVAL)
10805
      for row in self.op.disks:
10806
        if (not isinstance(row, dict) or
10807
            "size" not in row or
10808
            not isinstance(row["size"], int) or
10809
            "mode" not in row or
10810
            row["mode"] not in ['r', 'w']):
10811
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
10812
                                     " parameter", errors.ECODE_INVAL)
10813
      if self.op.hypervisor is None:
10814
        self.op.hypervisor = self.cfg.GetHypervisorType()
10815
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10816
      fname = _ExpandInstanceName(self.cfg, self.op.name)
10817
      self.op.name = fname
10818
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
10819
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10820
      if not hasattr(self.op, "evac_nodes"):
10821
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
10822
                                   " opcode input", errors.ECODE_INVAL)
10823
    else:
10824
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
10825
                                 self.op.mode, errors.ECODE_INVAL)
10826

    
10827
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
10828
      if self.op.allocator is None:
10829
        raise errors.OpPrereqError("Missing allocator name",
10830
                                   errors.ECODE_INVAL)
10831
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
10832
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
10833
                                 self.op.direction, errors.ECODE_INVAL)
10834

    
10835
  def Exec(self, feedback_fn):
10836
    """Run the allocator test.
10837

10838
    """
10839
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10840
      ial = IAllocator(self.cfg, self.rpc,
10841
                       mode=self.op.mode,
10842
                       name=self.op.name,
10843
                       mem_size=self.op.mem_size,
10844
                       disks=self.op.disks,
10845
                       disk_template=self.op.disk_template,
10846
                       os=self.op.os,
10847
                       tags=self.op.tags,
10848
                       nics=self.op.nics,
10849
                       vcpus=self.op.vcpus,
10850
                       hypervisor=self.op.hypervisor,
10851
                       )
10852
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10853
      ial = IAllocator(self.cfg, self.rpc,
10854
                       mode=self.op.mode,
10855
                       name=self.op.name,
10856
                       relocate_from=list(self.relocate_from),
10857
                       )
10858
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10859
      ial = IAllocator(self.cfg, self.rpc,
10860
                       mode=self.op.mode,
10861
                       evac_nodes=self.op.evac_nodes)
10862
    else:
10863
      raise errors.ProgrammerError("Uncatched mode %s in"
10864
                                   " LUTestAllocator.Exec", self.op.mode)
10865

    
10866
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
10867
      result = ial.in_text
10868
    else:
10869
      ial.Run(self.op.allocator, validate=False)
10870
      result = ial.out_text
10871
    return result