Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 0959c824

History | View | Annotate | Download (232.9 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008 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=W0613,W0201
25

    
26
import os
27
import os.path
28
import sha
29
import time
30
import tempfile
31
import re
32
import platform
33
import logging
34
import copy
35
import random
36

    
37
from ganeti import ssh
38
from ganeti import utils
39
from ganeti import errors
40
from ganeti import hypervisor
41
from ganeti import locking
42
from ganeti import constants
43
from ganeti import objects
44
from ganeti import opcodes
45
from ganeti import serializer
46
from ganeti import ssconf
47

    
48

    
49
class LogicalUnit(object):
50
  """Logical Unit base class.
51

52
  Subclasses must follow these rules:
53
    - implement ExpandNames
54
    - implement CheckPrereq
55
    - implement Exec
56
    - implement BuildHooksEnv
57
    - redefine HPATH and HTYPE
58
    - optionally redefine their run requirements:
59
        REQ_BGL: the LU needs to hold the Big Ganeti Lock exclusively
60

61
  Note that all commands require root permissions.
62

63
  """
64
  HPATH = None
65
  HTYPE = None
66
  _OP_REQP = []
67
  REQ_BGL = True
68

    
69
  def __init__(self, processor, op, context, rpc):
70
    """Constructor for LogicalUnit.
71

72
    This needs to be overriden in derived classes in order to check op
73
    validity.
74

75
    """
76
    self.proc = processor
77
    self.op = op
78
    self.cfg = context.cfg
79
    self.context = context
80
    self.rpc = rpc
81
    # Dicts used to declare locking needs to mcpu
82
    self.needed_locks = None
83
    self.acquired_locks = {}
84
    self.share_locks = dict(((i, 0) for i in locking.LEVELS))
85
    self.add_locks = {}
86
    self.remove_locks = {}
87
    # Used to force good behavior when calling helper functions
88
    self.recalculate_locks = {}
89
    self.__ssh = None
90
    # logging
91
    self.LogWarning = processor.LogWarning
92
    self.LogInfo = processor.LogInfo
93

    
94
    for attr_name in self._OP_REQP:
95
      attr_val = getattr(op, attr_name, None)
96
      if attr_val is None:
97
        raise errors.OpPrereqError("Required parameter '%s' missing" %
98
                                   attr_name)
99
    self.CheckArguments()
100

    
101
  def __GetSSH(self):
102
    """Returns the SshRunner object
103

104
    """
105
    if not self.__ssh:
106
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
107
    return self.__ssh
108

    
109
  ssh = property(fget=__GetSSH)
110

    
111
  def CheckArguments(self):
112
    """Check syntactic validity for the opcode arguments.
113

114
    This method is for doing a simple syntactic check and ensure
115
    validity of opcode parameters, without any cluster-related
116
    checks. While the same can be accomplished in ExpandNames and/or
117
    CheckPrereq, doing these separate is better because:
118

119
      - ExpandNames is left as as purely a lock-related function
120
      - CheckPrereq is run after we have aquired locks (and possible
121
        waited for them)
122

123
    The function is allowed to change the self.op attribute so that
124
    later methods can no longer worry about missing parameters.
125

126
    """
127
    pass
128

    
129
  def ExpandNames(self):
130
    """Expand names for this LU.
131

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

137
    LUs which implement this method must also populate the self.needed_locks
138
    member, as a dict with lock levels as keys, and a list of needed lock names
139
    as values. Rules:
140

141
      - use an empty dict if you don't need any lock
142
      - if you don't need any lock at a particular level omit that level
143
      - don't put anything for the BGL level
144
      - if you want all locks at a level use locking.ALL_SET as a value
145

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

150
    Examples::
151

152
      # Acquire all nodes and one instance
153
      self.needed_locks = {
154
        locking.LEVEL_NODE: locking.ALL_SET,
155
        locking.LEVEL_INSTANCE: ['instance1.example.tld'],
156
      }
157
      # Acquire just two nodes
158
      self.needed_locks = {
159
        locking.LEVEL_NODE: ['node1.example.tld', 'node2.example.tld'],
160
      }
161
      # Acquire no locks
162
      self.needed_locks = {} # No, you can't leave it to the default value None
163

164
    """
165
    # The implementation of this method is mandatory only if the new LU is
166
    # concurrent, so that old LUs don't need to be changed all at the same
167
    # time.
168
    if self.REQ_BGL:
169
      self.needed_locks = {} # Exclusive LUs don't need locks.
170
    else:
171
      raise NotImplementedError
172

    
173
  def DeclareLocks(self, level):
174
    """Declare LU locking needs for a level
175

176
    While most LUs can just declare their locking needs at ExpandNames time,
177
    sometimes there's the need to calculate some locks after having acquired
178
    the ones before. This function is called just before acquiring locks at a
179
    particular level, but after acquiring the ones at lower levels, and permits
180
    such calculations. It can be used to modify self.needed_locks, and by
181
    default it does nothing.
182

183
    This function is only called if you have something already set in
184
    self.needed_locks for the level.
185

186
    @param level: Locking level which is going to be locked
187
    @type level: member of ganeti.locking.LEVELS
188

189
    """
190

    
191
  def CheckPrereq(self):
192
    """Check prerequisites for this LU.
193

194
    This method should check that the prerequisites for the execution
195
    of this LU are fulfilled. It can do internode communication, but
196
    it should be idempotent - no cluster or system changes are
197
    allowed.
198

199
    The method should raise errors.OpPrereqError in case something is
200
    not fulfilled. Its return value is ignored.
201

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

205
    """
206
    raise NotImplementedError
207

    
208
  def Exec(self, feedback_fn):
209
    """Execute the LU.
210

211
    This method should implement the actual work. It should raise
212
    errors.OpExecError for failures that are somewhat dealt with in
213
    code, or expected.
214

215
    """
216
    raise NotImplementedError
217

    
218
  def BuildHooksEnv(self):
219
    """Build hooks environment for this LU.
220

221
    This method should return a three-node tuple consisting of: a dict
222
    containing the environment that will be used for running the
223
    specific hook for this LU, a list of node names on which the hook
224
    should run before the execution, and a list of node names on which
225
    the hook should run after the execution.
226

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

232
    No nodes should be returned as an empty list (and not None).
233

234
    Note that if the HPATH for a LU class is None, this function will
235
    not be called.
236

237
    """
238
    raise NotImplementedError
239

    
240
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
241
    """Notify the LU about the results of its hooks.
242

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

249
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
250
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
251
    @param hook_results: the results of the multi-node hooks rpc call
252
    @param feedback_fn: function used send feedback back to the caller
253
    @param lu_result: the previous Exec result this LU had, or None
254
        in the PRE phase
255
    @return: the new Exec result, based on the previous result
256
        and hook results
257

258
    """
259
    return lu_result
260

    
261
  def _ExpandAndLockInstance(self):
262
    """Helper function to expand and lock an instance.
263

264
    Many LUs that work on an instance take its name in self.op.instance_name
265
    and need to expand it and then declare the expanded name for locking. This
266
    function does it, and then updates self.op.instance_name to the expanded
267
    name. It also initializes needed_locks as a dict, if this hasn't been done
268
    before.
269

270
    """
271
    if self.needed_locks is None:
272
      self.needed_locks = {}
273
    else:
274
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
275
        "_ExpandAndLockInstance called with instance-level locks set"
276
    expanded_name = self.cfg.ExpandInstanceName(self.op.instance_name)
277
    if expanded_name is None:
278
      raise errors.OpPrereqError("Instance '%s' not known" %
279
                                  self.op.instance_name)
280
    self.needed_locks[locking.LEVEL_INSTANCE] = expanded_name
281
    self.op.instance_name = expanded_name
282

    
283
  def _LockInstancesNodes(self, primary_only=False):
284
    """Helper function to declare instances' nodes for locking.
285

286
    This function should be called after locking one or more instances to lock
287
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
288
    with all primary or secondary nodes for instances already locked and
289
    present in self.needed_locks[locking.LEVEL_INSTANCE].
290

291
    It should be called from DeclareLocks, and for safety only works if
292
    self.recalculate_locks[locking.LEVEL_NODE] is set.
293

294
    In the future it may grow parameters to just lock some instance's nodes, or
295
    to just lock primaries or secondary nodes, if needed.
296

297
    If should be called in DeclareLocks in a way similar to::
298

299
      if level == locking.LEVEL_NODE:
300
        self._LockInstancesNodes()
301

302
    @type primary_only: boolean
303
    @param primary_only: only lock primary nodes of locked instances
304

305
    """
306
    assert locking.LEVEL_NODE in self.recalculate_locks, \
307
      "_LockInstancesNodes helper function called with no nodes to recalculate"
308

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

    
311
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
312
    # future we might want to have different behaviors depending on the value
313
    # of self.recalculate_locks[locking.LEVEL_NODE]
314
    wanted_nodes = []
315
    for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
316
      instance = self.context.cfg.GetInstanceInfo(instance_name)
317
      wanted_nodes.append(instance.primary_node)
318
      if not primary_only:
319
        wanted_nodes.extend(instance.secondary_nodes)
320

    
321
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
322
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
323
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
324
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
325

    
326
    del self.recalculate_locks[locking.LEVEL_NODE]
327

    
328

    
329
class NoHooksLU(LogicalUnit):
330
  """Simple LU which runs no hooks.
331

332
  This LU is intended as a parent for other LogicalUnits which will
333
  run no hooks, in order to reduce duplicate code.
334

335
  """
336
  HPATH = None
337
  HTYPE = None
338

    
339

    
340
def _GetWantedNodes(lu, nodes):
341
  """Returns list of checked and expanded node names.
342

343
  @type lu: L{LogicalUnit}
344
  @param lu: the logical unit on whose behalf we execute
345
  @type nodes: list
346
  @param nodes: list of node names or None for all nodes
347
  @rtype: list
348
  @return: the list of nodes, sorted
349
  @raise errors.OpProgrammerError: if the nodes parameter is wrong type
350

351
  """
352
  if not isinstance(nodes, list):
353
    raise errors.OpPrereqError("Invalid argument type 'nodes'")
354

    
355
  if not nodes:
356
    raise errors.ProgrammerError("_GetWantedNodes should only be called with a"
357
      " non-empty list of nodes whose name is to be expanded.")
358

    
359
  wanted = []
360
  for name in nodes:
361
    node = lu.cfg.ExpandNodeName(name)
362
    if node is None:
363
      raise errors.OpPrereqError("No such node name '%s'" % name)
364
    wanted.append(node)
365

    
366
  return utils.NiceSort(wanted)
367

    
368

    
369
def _GetWantedInstances(lu, instances):
370
  """Returns list of checked and expanded instance names.
371

372
  @type lu: L{LogicalUnit}
373
  @param lu: the logical unit on whose behalf we execute
374
  @type instances: list
375
  @param instances: list of instance names or None for all instances
376
  @rtype: list
377
  @return: the list of instances, sorted
378
  @raise errors.OpPrereqError: if the instances parameter is wrong type
379
  @raise errors.OpPrereqError: if any of the passed instances is not found
380

381
  """
382
  if not isinstance(instances, list):
383
    raise errors.OpPrereqError("Invalid argument type 'instances'")
384

    
385
  if instances:
386
    wanted = []
387

    
388
    for name in instances:
389
      instance = lu.cfg.ExpandInstanceName(name)
390
      if instance is None:
391
        raise errors.OpPrereqError("No such instance name '%s'" % name)
392
      wanted.append(instance)
393

    
394
  else:
395
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
396
  return wanted
397

    
398

    
399
def _CheckOutputFields(static, dynamic, selected):
400
  """Checks whether all selected fields are valid.
401

402
  @type static: L{utils.FieldSet}
403
  @param static: static fields set
404
  @type dynamic: L{utils.FieldSet}
405
  @param dynamic: dynamic fields set
406

407
  """
408
  f = utils.FieldSet()
409
  f.Extend(static)
410
  f.Extend(dynamic)
411

    
412
  delta = f.NonMatching(selected)
413
  if delta:
414
    raise errors.OpPrereqError("Unknown output fields selected: %s"
415
                               % ",".join(delta))
416

    
417

    
418
def _CheckBooleanOpField(op, name):
419
  """Validates boolean opcode parameters.
420

421
  This will ensure that an opcode parameter is either a boolean value,
422
  or None (but that it always exists).
423

424
  """
425
  val = getattr(op, name, None)
426
  if not (val is None or isinstance(val, bool)):
427
    raise errors.OpPrereqError("Invalid boolean parameter '%s' (%s)" %
428
                               (name, str(val)))
429
  setattr(op, name, val)
430

    
431

    
432
def _CheckNodeOnline(lu, node):
433
  """Ensure that a given node is online.
434

435
  @param lu: the LU on behalf of which we make the check
436
  @param node: the node to check
437
  @raise errors.OpPrereqError: if the nodes is offline
438

439
  """
440
  if lu.cfg.GetNodeInfo(node).offline:
441
    raise errors.OpPrereqError("Can't use offline node %s" % node)
442

    
443

    
444
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
445
                          memory, vcpus, nics):
446
  """Builds instance related env variables for hooks
447

448
  This builds the hook environment from individual variables.
449

450
  @type name: string
451
  @param name: the name of the instance
452
  @type primary_node: string
453
  @param primary_node: the name of the instance's primary node
454
  @type secondary_nodes: list
455
  @param secondary_nodes: list of secondary nodes as strings
456
  @type os_type: string
457
  @param os_type: the name of the instance's OS
458
  @type status: boolean
459
  @param status: the should_run status of the instance
460
  @type memory: string
461
  @param memory: the memory size of the instance
462
  @type vcpus: string
463
  @param vcpus: the count of VCPUs the instance has
464
  @type nics: list
465
  @param nics: list of tuples (ip, bridge, mac) representing
466
      the NICs the instance  has
467
  @rtype: dict
468
  @return: the hook environment for this instance
469

470
  """
471
  if status:
472
    str_status = "up"
473
  else:
474
    str_status = "down"
475
  env = {
476
    "OP_TARGET": name,
477
    "INSTANCE_NAME": name,
478
    "INSTANCE_PRIMARY": primary_node,
479
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
480
    "INSTANCE_OS_TYPE": os_type,
481
    "INSTANCE_STATUS": str_status,
482
    "INSTANCE_MEMORY": memory,
483
    "INSTANCE_VCPUS": vcpus,
484
  }
485

    
486
  if nics:
487
    nic_count = len(nics)
488
    for idx, (ip, bridge, mac) in enumerate(nics):
489
      if ip is None:
490
        ip = ""
491
      env["INSTANCE_NIC%d_IP" % idx] = ip
492
      env["INSTANCE_NIC%d_BRIDGE" % idx] = bridge
493
      env["INSTANCE_NIC%d_HWADDR" % idx] = mac
494
  else:
495
    nic_count = 0
496

    
497
  env["INSTANCE_NIC_COUNT"] = nic_count
498

    
499
  return env
500

    
501

    
502
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
503
  """Builds instance related env variables for hooks from an object.
504

505
  @type lu: L{LogicalUnit}
506
  @param lu: the logical unit on whose behalf we execute
507
  @type instance: L{objects.Instance}
508
  @param instance: the instance for which we should build the
509
      environment
510
  @type override: dict
511
  @param override: dictionary with key/values that will override
512
      our values
513
  @rtype: dict
514
  @return: the hook environment dictionary
515

516
  """
517
  bep = lu.cfg.GetClusterInfo().FillBE(instance)
518
  args = {
519
    'name': instance.name,
520
    'primary_node': instance.primary_node,
521
    'secondary_nodes': instance.secondary_nodes,
522
    'os_type': instance.os,
523
    'status': instance.admin_up,
524
    'memory': bep[constants.BE_MEMORY],
525
    'vcpus': bep[constants.BE_VCPUS],
526
    'nics': [(nic.ip, nic.bridge, nic.mac) for nic in instance.nics],
527
  }
528
  if override:
529
    args.update(override)
530
  return _BuildInstanceHookEnv(**args)
531

    
532

    
533
def _AdjustCandidatePool(lu):
534
  """Adjust the candidate pool after node operations.
535

536
  """
537
  mod_list = lu.cfg.MaintainCandidatePool()
538
  if mod_list:
539
    lu.LogInfo("Promoted nodes to master candidate role: %s",
540
               ", ".join(node.name for node in mod_list))
541
    for name in mod_list:
542
      lu.context.ReaddNode(name)
543
  mc_now, mc_max = lu.cfg.GetMasterCandidateStats()
544
  if mc_now > mc_max:
545
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
546
               (mc_now, mc_max))
547

    
548

    
549
def _CheckInstanceBridgesExist(lu, instance):
550
  """Check that the brigdes needed by an instance exist.
551

552
  """
553
  # check bridges existance
554
  brlist = [nic.bridge for nic in instance.nics]
555
  result = lu.rpc.call_bridges_exist(instance.primary_node, brlist)
556
  result.Raise()
557
  if not result.data:
558
    raise errors.OpPrereqError("One or more target bridges %s does not"
559
                               " exist on destination node '%s'" %
560
                               (brlist, instance.primary_node))
561

    
562

    
563
class LUDestroyCluster(NoHooksLU):
564
  """Logical unit for destroying the cluster.
565

566
  """
567
  _OP_REQP = []
568

    
569
  def CheckPrereq(self):
570
    """Check prerequisites.
571

572
    This checks whether the cluster is empty.
573

574
    Any errors are signalled by raising errors.OpPrereqError.
575

576
    """
577
    master = self.cfg.GetMasterNode()
578

    
579
    nodelist = self.cfg.GetNodeList()
580
    if len(nodelist) != 1 or nodelist[0] != master:
581
      raise errors.OpPrereqError("There are still %d node(s) in"
582
                                 " this cluster." % (len(nodelist) - 1))
583
    instancelist = self.cfg.GetInstanceList()
584
    if instancelist:
585
      raise errors.OpPrereqError("There are still %d instance(s) in"
586
                                 " this cluster." % len(instancelist))
587

    
588
  def Exec(self, feedback_fn):
589
    """Destroys the cluster.
590

591
    """
592
    master = self.cfg.GetMasterNode()
593
    result = self.rpc.call_node_stop_master(master, False)
594
    result.Raise()
595
    if not result.data:
596
      raise errors.OpExecError("Could not disable the master role")
597
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
598
    utils.CreateBackup(priv_key)
599
    utils.CreateBackup(pub_key)
600
    return master
601

    
602

    
603
class LUVerifyCluster(LogicalUnit):
604
  """Verifies the cluster status.
605

606
  """
607
  HPATH = "cluster-verify"
608
  HTYPE = constants.HTYPE_CLUSTER
609
  _OP_REQP = ["skip_checks"]
610
  REQ_BGL = False
611

    
612
  def ExpandNames(self):
613
    self.needed_locks = {
614
      locking.LEVEL_NODE: locking.ALL_SET,
615
      locking.LEVEL_INSTANCE: locking.ALL_SET,
616
    }
617
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
618

    
619
  def _VerifyNode(self, nodeinfo, file_list, local_cksum,
620
                  node_result, feedback_fn, master_files,
621
                  drbd_map):
622
    """Run multiple tests against a node.
623

624
    Test list:
625

626
      - compares ganeti version
627
      - checks vg existance and size > 20G
628
      - checks config file checksum
629
      - checks ssh to other nodes
630

631
    @type nodeinfo: L{objects.Node}
632
    @param nodeinfo: the node to check
633
    @param file_list: required list of files
634
    @param local_cksum: dictionary of local files and their checksums
635
    @param node_result: the results from the node
636
    @param feedback_fn: function used to accumulate results
637
    @param master_files: list of files that only masters should have
638
    @param drbd_map: the useddrbd minors for this node, in
639
        form of minor: (instance, must_exist) which correspond to instances
640
        and their running status
641

642
    """
643
    node = nodeinfo.name
644

    
645
    # main result, node_result should be a non-empty dict
646
    if not node_result or not isinstance(node_result, dict):
647
      feedback_fn("  - ERROR: unable to verify node %s." % (node,))
648
      return True
649

    
650
    # compares ganeti version
651
    local_version = constants.PROTOCOL_VERSION
652
    remote_version = node_result.get('version', None)
653
    if not (remote_version and isinstance(remote_version, (list, tuple)) and
654
            len(remote_version) == 2):
655
      feedback_fn("  - ERROR: connection to %s failed" % (node))
656
      return True
657

    
658
    if local_version != remote_version[0]:
659
      feedback_fn("  - ERROR: incompatible protocol versions: master %s,"
660
                  " node %s %s" % (local_version, node, remote_version[0]))
661
      return True
662

    
663
    # node seems compatible, we can actually try to look into its results
664

    
665
    bad = False
666

    
667
    # full package version
668
    if constants.RELEASE_VERSION != remote_version[1]:
669
      feedback_fn("  - WARNING: software version mismatch: master %s,"
670
                  " node %s %s" %
671
                  (constants.RELEASE_VERSION, node, remote_version[1]))
672

    
673
    # checks vg existence and size > 20G
674

    
675
    vglist = node_result.get(constants.NV_VGLIST, None)
676
    if not vglist:
677
      feedback_fn("  - ERROR: unable to check volume groups on node %s." %
678
                      (node,))
679
      bad = True
680
    else:
681
      vgstatus = utils.CheckVolumeGroupSize(vglist, self.cfg.GetVGName(),
682
                                            constants.MIN_VG_SIZE)
683
      if vgstatus:
684
        feedback_fn("  - ERROR: %s on node %s" % (vgstatus, node))
685
        bad = True
686

    
687
    # checks config file checksum
688

    
689
    remote_cksum = node_result.get(constants.NV_FILELIST, None)
690
    if not isinstance(remote_cksum, dict):
691
      bad = True
692
      feedback_fn("  - ERROR: node hasn't returned file checksum data")
693
    else:
694
      for file_name in file_list:
695
        node_is_mc = nodeinfo.master_candidate
696
        must_have_file = file_name not in master_files
697
        if file_name not in remote_cksum:
698
          if node_is_mc or must_have_file:
699
            bad = True
700
            feedback_fn("  - ERROR: file '%s' missing" % file_name)
701
        elif remote_cksum[file_name] != local_cksum[file_name]:
702
          if node_is_mc or must_have_file:
703
            bad = True
704
            feedback_fn("  - ERROR: file '%s' has wrong checksum" % file_name)
705
          else:
706
            # not candidate and this is not a must-have file
707
            bad = True
708
            feedback_fn("  - ERROR: non master-candidate has old/wrong file"
709
                        " '%s'" % file_name)
710
        else:
711
          # all good, except non-master/non-must have combination
712
          if not node_is_mc and not must_have_file:
713
            feedback_fn("  - ERROR: file '%s' should not exist on non master"
714
                        " candidates" % file_name)
715

    
716
    # checks ssh to any
717

    
718
    if constants.NV_NODELIST not in node_result:
719
      bad = True
720
      feedback_fn("  - ERROR: node hasn't returned node ssh connectivity data")
721
    else:
722
      if node_result[constants.NV_NODELIST]:
723
        bad = True
724
        for node in node_result[constants.NV_NODELIST]:
725
          feedback_fn("  - ERROR: ssh communication with node '%s': %s" %
726
                          (node, node_result[constants.NV_NODELIST][node]))
727

    
728
    if constants.NV_NODENETTEST not in node_result:
729
      bad = True
730
      feedback_fn("  - ERROR: node hasn't returned node tcp connectivity data")
731
    else:
732
      if node_result[constants.NV_NODENETTEST]:
733
        bad = True
734
        nlist = utils.NiceSort(node_result[constants.NV_NODENETTEST].keys())
735
        for node in nlist:
736
          feedback_fn("  - ERROR: tcp communication with node '%s': %s" %
737
                          (node, node_result[constants.NV_NODENETTEST][node]))
738

    
739
    hyp_result = node_result.get(constants.NV_HYPERVISOR, None)
740
    if isinstance(hyp_result, dict):
741
      for hv_name, hv_result in hyp_result.iteritems():
742
        if hv_result is not None:
743
          feedback_fn("  - ERROR: hypervisor %s verify failure: '%s'" %
744
                      (hv_name, hv_result))
745

    
746
    # check used drbd list
747
    used_minors = node_result.get(constants.NV_DRBDLIST, [])
748
    for minor, (iname, must_exist) in drbd_map.items():
749
      if minor not in used_minors and must_exist:
750
        feedback_fn("  - ERROR: drbd minor %d of instance %s is not active" %
751
                    (minor, iname))
752
        bad = True
753
    for minor in used_minors:
754
      if minor not in drbd_map:
755
        feedback_fn("  - ERROR: unallocated drbd minor %d is in use" % minor)
756
        bad = True
757

    
758
    return bad
759

    
760
  def _VerifyInstance(self, instance, instanceconfig, node_vol_is,
761
                      node_instance, feedback_fn, n_offline):
762
    """Verify an instance.
763

764
    This function checks to see if the required block devices are
765
    available on the instance's node.
766

767
    """
768
    bad = False
769

    
770
    node_current = instanceconfig.primary_node
771

    
772
    node_vol_should = {}
773
    instanceconfig.MapLVsByNode(node_vol_should)
774

    
775
    for node in node_vol_should:
776
      if node in n_offline:
777
        # ignore missing volumes on offline nodes
778
        continue
779
      for volume in node_vol_should[node]:
780
        if node not in node_vol_is or volume not in node_vol_is[node]:
781
          feedback_fn("  - ERROR: volume %s missing on node %s" %
782
                          (volume, node))
783
          bad = True
784

    
785
    if instanceconfig.admin_up:
786
      if ((node_current not in node_instance or
787
          not instance in node_instance[node_current]) and
788
          node_current not in n_offline):
789
        feedback_fn("  - ERROR: instance %s not running on node %s" %
790
                        (instance, node_current))
791
        bad = True
792

    
793
    for node in node_instance:
794
      if (not node == node_current):
795
        if instance in node_instance[node]:
796
          feedback_fn("  - ERROR: instance %s should not run on node %s" %
797
                          (instance, node))
798
          bad = True
799

    
800
    return bad
801

    
802
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is, feedback_fn):
803
    """Verify if there are any unknown volumes in the cluster.
804

805
    The .os, .swap and backup volumes are ignored. All other volumes are
806
    reported as unknown.
807

808
    """
809
    bad = False
810

    
811
    for node in node_vol_is:
812
      for volume in node_vol_is[node]:
813
        if node not in node_vol_should or volume not in node_vol_should[node]:
814
          feedback_fn("  - ERROR: volume %s on node %s should not exist" %
815
                      (volume, node))
816
          bad = True
817
    return bad
818

    
819
  def _VerifyOrphanInstances(self, instancelist, node_instance, feedback_fn):
820
    """Verify the list of running instances.
821

822
    This checks what instances are running but unknown to the cluster.
823

824
    """
825
    bad = False
826
    for node in node_instance:
827
      for runninginstance in node_instance[node]:
828
        if runninginstance not in instancelist:
829
          feedback_fn("  - ERROR: instance %s on node %s should not exist" %
830
                          (runninginstance, node))
831
          bad = True
832
    return bad
833

    
834
  def _VerifyNPlusOneMemory(self, node_info, instance_cfg, feedback_fn):
835
    """Verify N+1 Memory Resilience.
836

837
    Check that if one single node dies we can still start all the instances it
838
    was primary for.
839

840
    """
841
    bad = False
842

    
843
    for node, nodeinfo in node_info.iteritems():
844
      # This code checks that every node which is now listed as secondary has
845
      # enough memory to host all instances it is supposed to should a single
846
      # other node in the cluster fail.
847
      # FIXME: not ready for failover to an arbitrary node
848
      # FIXME: does not support file-backed instances
849
      # WARNING: we currently take into account down instances as well as up
850
      # ones, considering that even if they're down someone might want to start
851
      # them even in the event of a node failure.
852
      for prinode, instances in nodeinfo['sinst-by-pnode'].iteritems():
853
        needed_mem = 0
854
        for instance in instances:
855
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
856
          if bep[constants.BE_AUTO_BALANCE]:
857
            needed_mem += bep[constants.BE_MEMORY]
858
        if nodeinfo['mfree'] < needed_mem:
859
          feedback_fn("  - ERROR: not enough memory on node %s to accomodate"
860
                      " failovers should node %s fail" % (node, prinode))
861
          bad = True
862
    return bad
863

    
864
  def CheckPrereq(self):
865
    """Check prerequisites.
866

867
    Transform the list of checks we're going to skip into a set and check that
868
    all its members are valid.
869

870
    """
871
    self.skip_set = frozenset(self.op.skip_checks)
872
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
873
      raise errors.OpPrereqError("Invalid checks to be skipped specified")
874

    
875
  def BuildHooksEnv(self):
876
    """Build hooks env.
877

878
    Cluster-Verify hooks just rone in the post phase and their failure makes
879
    the output be logged in the verify output and the verification to fail.
880

881
    """
882
    all_nodes = self.cfg.GetNodeList()
883
    # TODO: populate the environment with useful information for verify hooks
884
    env = {}
885
    return env, [], all_nodes
886

    
887
  def Exec(self, feedback_fn):
888
    """Verify integrity of cluster, performing various test on nodes.
889

890
    """
891
    bad = False
892
    feedback_fn("* Verifying global settings")
893
    for msg in self.cfg.VerifyConfig():
894
      feedback_fn("  - ERROR: %s" % msg)
895

    
896
    vg_name = self.cfg.GetVGName()
897
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
898
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
899
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
900
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
901
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
902
                        for iname in instancelist)
903
    i_non_redundant = [] # Non redundant instances
904
    i_non_a_balanced = [] # Non auto-balanced instances
905
    n_offline = [] # List of offline nodes
906
    node_volume = {}
907
    node_instance = {}
908
    node_info = {}
909
    instance_cfg = {}
910

    
911
    # FIXME: verify OS list
912
    # do local checksums
913
    master_files = [constants.CLUSTER_CONF_FILE]
914

    
915
    file_names = ssconf.SimpleStore().GetFileList()
916
    file_names.append(constants.SSL_CERT_FILE)
917
    file_names.append(constants.RAPI_CERT_FILE)
918
    file_names.extend(master_files)
919

    
920
    local_checksums = utils.FingerprintFiles(file_names)
921

    
922
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
923
    node_verify_param = {
924
      constants.NV_FILELIST: file_names,
925
      constants.NV_NODELIST: [node.name for node in nodeinfo
926
                              if not node.offline],
927
      constants.NV_HYPERVISOR: hypervisors,
928
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
929
                                  node.secondary_ip) for node in nodeinfo
930
                                 if not node.offline],
931
      constants.NV_LVLIST: vg_name,
932
      constants.NV_INSTANCELIST: hypervisors,
933
      constants.NV_VGLIST: None,
934
      constants.NV_VERSION: None,
935
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
936
      constants.NV_DRBDLIST: None,
937
      }
938
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
939
                                           self.cfg.GetClusterName())
940

    
941
    cluster = self.cfg.GetClusterInfo()
942
    master_node = self.cfg.GetMasterNode()
943
    all_drbd_map = self.cfg.ComputeDRBDMap()
944

    
945
    for node_i in nodeinfo:
946
      node = node_i.name
947
      nresult = all_nvinfo[node].data
948

    
949
      if node_i.offline:
950
        feedback_fn("* Skipping offline node %s" % (node,))
951
        n_offline.append(node)
952
        continue
953

    
954
      if node == master_node:
955
        ntype = "master"
956
      elif node_i.master_candidate:
957
        ntype = "master candidate"
958
      else:
959
        ntype = "regular"
960
      feedback_fn("* Verifying node %s (%s)" % (node, ntype))
961

    
962
      if all_nvinfo[node].failed or not isinstance(nresult, dict):
963
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
964
        bad = True
965
        continue
966

    
967
      node_drbd = {}
968
      for minor, instance in all_drbd_map[node].items():
969
        instance = instanceinfo[instance]
970
        node_drbd[minor] = (instance.name, instance.admin_up)
971
      result = self._VerifyNode(node_i, file_names, local_checksums,
972
                                nresult, feedback_fn, master_files,
973
                                node_drbd)
974
      bad = bad or result
975

    
976
      lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
977
      if isinstance(lvdata, basestring):
978
        feedback_fn("  - ERROR: LVM problem on node %s: %s" %
979
                    (node, utils.SafeEncode(lvdata)))
980
        bad = True
981
        node_volume[node] = {}
982
      elif not isinstance(lvdata, dict):
983
        feedback_fn("  - ERROR: connection to %s failed (lvlist)" % (node,))
984
        bad = True
985
        continue
986
      else:
987
        node_volume[node] = lvdata
988

    
989
      # node_instance
990
      idata = nresult.get(constants.NV_INSTANCELIST, None)
991
      if not isinstance(idata, list):
992
        feedback_fn("  - ERROR: connection to %s failed (instancelist)" %
993
                    (node,))
994
        bad = True
995
        continue
996

    
997
      node_instance[node] = idata
998

    
999
      # node_info
1000
      nodeinfo = nresult.get(constants.NV_HVINFO, None)
1001
      if not isinstance(nodeinfo, dict):
1002
        feedback_fn("  - ERROR: connection to %s failed (hvinfo)" % (node,))
1003
        bad = True
1004
        continue
1005

    
1006
      try:
1007
        node_info[node] = {
1008
          "mfree": int(nodeinfo['memory_free']),
1009
          "dfree": int(nresult[constants.NV_VGLIST][vg_name]),
1010
          "pinst": [],
1011
          "sinst": [],
1012
          # dictionary holding all instances this node is secondary for,
1013
          # grouped by their primary node. Each key is a cluster node, and each
1014
          # value is a list of instances which have the key as primary and the
1015
          # current node as secondary.  this is handy to calculate N+1 memory
1016
          # availability if you can only failover from a primary to its
1017
          # secondary.
1018
          "sinst-by-pnode": {},
1019
        }
1020
      except ValueError:
1021
        feedback_fn("  - ERROR: invalid value returned from node %s" % (node,))
1022
        bad = True
1023
        continue
1024

    
1025
    node_vol_should = {}
1026

    
1027
    for instance in instancelist:
1028
      feedback_fn("* Verifying instance %s" % instance)
1029
      inst_config = instanceinfo[instance]
1030
      result =  self._VerifyInstance(instance, inst_config, node_volume,
1031
                                     node_instance, feedback_fn, n_offline)
1032
      bad = bad or result
1033
      inst_nodes_offline = []
1034

    
1035
      inst_config.MapLVsByNode(node_vol_should)
1036

    
1037
      instance_cfg[instance] = inst_config
1038

    
1039
      pnode = inst_config.primary_node
1040
      if pnode in node_info:
1041
        node_info[pnode]['pinst'].append(instance)
1042
      elif pnode not in n_offline:
1043
        feedback_fn("  - ERROR: instance %s, connection to primary node"
1044
                    " %s failed" % (instance, pnode))
1045
        bad = True
1046

    
1047
      if pnode in n_offline:
1048
        inst_nodes_offline.append(pnode)
1049

    
1050
      # If the instance is non-redundant we cannot survive losing its primary
1051
      # node, so we are not N+1 compliant. On the other hand we have no disk
1052
      # templates with more than one secondary so that situation is not well
1053
      # supported either.
1054
      # FIXME: does not support file-backed instances
1055
      if len(inst_config.secondary_nodes) == 0:
1056
        i_non_redundant.append(instance)
1057
      elif len(inst_config.secondary_nodes) > 1:
1058
        feedback_fn("  - WARNING: multiple secondaries for instance %s"
1059
                    % instance)
1060

    
1061
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1062
        i_non_a_balanced.append(instance)
1063

    
1064
      for snode in inst_config.secondary_nodes:
1065
        if snode in node_info:
1066
          node_info[snode]['sinst'].append(instance)
1067
          if pnode not in node_info[snode]['sinst-by-pnode']:
1068
            node_info[snode]['sinst-by-pnode'][pnode] = []
1069
          node_info[snode]['sinst-by-pnode'][pnode].append(instance)
1070
        elif snode not in n_offline:
1071
          feedback_fn("  - ERROR: instance %s, connection to secondary node"
1072
                      " %s failed" % (instance, snode))
1073
          bad = True
1074
        if snode in n_offline:
1075
          inst_nodes_offline.append(snode)
1076

    
1077
      if inst_nodes_offline:
1078
        # warn that the instance lives on offline nodes, and set bad=True
1079
        feedback_fn("  - ERROR: instance lives on offline node(s) %s" %
1080
                    ", ".join(inst_nodes_offline))
1081
        bad = True
1082

    
1083
    feedback_fn("* Verifying orphan volumes")
1084
    result = self._VerifyOrphanVolumes(node_vol_should, node_volume,
1085
                                       feedback_fn)
1086
    bad = bad or result
1087

    
1088
    feedback_fn("* Verifying remaining instances")
1089
    result = self._VerifyOrphanInstances(instancelist, node_instance,
1090
                                         feedback_fn)
1091
    bad = bad or result
1092

    
1093
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1094
      feedback_fn("* Verifying N+1 Memory redundancy")
1095
      result = self._VerifyNPlusOneMemory(node_info, instance_cfg, feedback_fn)
1096
      bad = bad or result
1097

    
1098
    feedback_fn("* Other Notes")
1099
    if i_non_redundant:
1100
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1101
                  % len(i_non_redundant))
1102

    
1103
    if i_non_a_balanced:
1104
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1105
                  % len(i_non_a_balanced))
1106

    
1107
    if n_offline:
1108
      feedback_fn("  - NOTICE: %d offline node(s) found." % len(n_offline))
1109

    
1110
    return not bad
1111

    
1112
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1113
    """Analize the post-hooks' result
1114

1115
    This method analyses the hook result, handles it, and sends some
1116
    nicely-formatted feedback back to the user.
1117

1118
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1119
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1120
    @param hooks_results: the results of the multi-node hooks rpc call
1121
    @param feedback_fn: function used send feedback back to the caller
1122
    @param lu_result: previous Exec result
1123
    @return: the new Exec result, based on the previous result
1124
        and hook results
1125

1126
    """
1127
    # We only really run POST phase hooks, and are only interested in
1128
    # their results
1129
    if phase == constants.HOOKS_PHASE_POST:
1130
      # Used to change hooks' output to proper indentation
1131
      indent_re = re.compile('^', re.M)
1132
      feedback_fn("* Hooks Results")
1133
      if not hooks_results:
1134
        feedback_fn("  - ERROR: general communication failure")
1135
        lu_result = 1
1136
      else:
1137
        for node_name in hooks_results:
1138
          show_node_header = True
1139
          res = hooks_results[node_name]
1140
          if res.failed or res.data is False or not isinstance(res.data, list):
1141
            if res.offline:
1142
              # no need to warn or set fail return value
1143
              continue
1144
            feedback_fn("    Communication failure in hooks execution")
1145
            lu_result = 1
1146
            continue
1147
          for script, hkr, output in res.data:
1148
            if hkr == constants.HKR_FAIL:
1149
              # The node header is only shown once, if there are
1150
              # failing hooks on that node
1151
              if show_node_header:
1152
                feedback_fn("  Node %s:" % node_name)
1153
                show_node_header = False
1154
              feedback_fn("    ERROR: Script %s failed, output:" % script)
1155
              output = indent_re.sub('      ', output)
1156
              feedback_fn("%s" % output)
1157
              lu_result = 1
1158

    
1159
      return lu_result
1160

    
1161

    
1162
class LUVerifyDisks(NoHooksLU):
1163
  """Verifies the cluster disks status.
1164

1165
  """
1166
  _OP_REQP = []
1167
  REQ_BGL = False
1168

    
1169
  def ExpandNames(self):
1170
    self.needed_locks = {
1171
      locking.LEVEL_NODE: locking.ALL_SET,
1172
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1173
    }
1174
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
1175

    
1176
  def CheckPrereq(self):
1177
    """Check prerequisites.
1178

1179
    This has no prerequisites.
1180

1181
    """
1182
    pass
1183

    
1184
  def Exec(self, feedback_fn):
1185
    """Verify integrity of cluster disks.
1186

1187
    """
1188
    result = res_nodes, res_nlvm, res_instances, res_missing = [], {}, [], {}
1189

    
1190
    vg_name = self.cfg.GetVGName()
1191
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1192
    instances = [self.cfg.GetInstanceInfo(name)
1193
                 for name in self.cfg.GetInstanceList()]
1194

    
1195
    nv_dict = {}
1196
    for inst in instances:
1197
      inst_lvs = {}
1198
      if (not inst.admin_up or
1199
          inst.disk_template not in constants.DTS_NET_MIRROR):
1200
        continue
1201
      inst.MapLVsByNode(inst_lvs)
1202
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1203
      for node, vol_list in inst_lvs.iteritems():
1204
        for vol in vol_list:
1205
          nv_dict[(node, vol)] = inst
1206

    
1207
    if not nv_dict:
1208
      return result
1209

    
1210
    node_lvs = self.rpc.call_volume_list(nodes, vg_name)
1211

    
1212
    to_act = set()
1213
    for node in nodes:
1214
      # node_volume
1215
      lvs = node_lvs[node]
1216
      if lvs.failed:
1217
        if not lvs.offline:
1218
          self.LogWarning("Connection to node %s failed: %s" %
1219
                          (node, lvs.data))
1220
        continue
1221
      lvs = lvs.data
1222
      if isinstance(lvs, basestring):
1223
        logging.warning("Error enumerating LVs on node %s: %s", node, lvs)
1224
        res_nlvm[node] = lvs
1225
      elif not isinstance(lvs, dict):
1226
        logging.warning("Connection to node %s failed or invalid data"
1227
                        " returned", node)
1228
        res_nodes.append(node)
1229
        continue
1230

    
1231
      for lv_name, (_, lv_inactive, lv_online) in lvs.iteritems():
1232
        inst = nv_dict.pop((node, lv_name), None)
1233
        if (not lv_online and inst is not None
1234
            and inst.name not in res_instances):
1235
          res_instances.append(inst.name)
1236

    
1237
    # any leftover items in nv_dict are missing LVs, let's arrange the
1238
    # data better
1239
    for key, inst in nv_dict.iteritems():
1240
      if inst.name not in res_missing:
1241
        res_missing[inst.name] = []
1242
      res_missing[inst.name].append(key)
1243

    
1244
    return result
1245

    
1246

    
1247
class LURenameCluster(LogicalUnit):
1248
  """Rename the cluster.
1249

1250
  """
1251
  HPATH = "cluster-rename"
1252
  HTYPE = constants.HTYPE_CLUSTER
1253
  _OP_REQP = ["name"]
1254

    
1255
  def BuildHooksEnv(self):
1256
    """Build hooks env.
1257

1258
    """
1259
    env = {
1260
      "OP_TARGET": self.cfg.GetClusterName(),
1261
      "NEW_NAME": self.op.name,
1262
      }
1263
    mn = self.cfg.GetMasterNode()
1264
    return env, [mn], [mn]
1265

    
1266
  def CheckPrereq(self):
1267
    """Verify that the passed name is a valid one.
1268

1269
    """
1270
    hostname = utils.HostInfo(self.op.name)
1271

    
1272
    new_name = hostname.name
1273
    self.ip = new_ip = hostname.ip
1274
    old_name = self.cfg.GetClusterName()
1275
    old_ip = self.cfg.GetMasterIP()
1276
    if new_name == old_name and new_ip == old_ip:
1277
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1278
                                 " cluster has changed")
1279
    if new_ip != old_ip:
1280
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1281
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1282
                                   " reachable on the network. Aborting." %
1283
                                   new_ip)
1284

    
1285
    self.op.name = new_name
1286

    
1287
  def Exec(self, feedback_fn):
1288
    """Rename the cluster.
1289

1290
    """
1291
    clustername = self.op.name
1292
    ip = self.ip
1293

    
1294
    # shutdown the master IP
1295
    master = self.cfg.GetMasterNode()
1296
    result = self.rpc.call_node_stop_master(master, False)
1297
    if result.failed or not result.data:
1298
      raise errors.OpExecError("Could not disable the master role")
1299

    
1300
    try:
1301
      cluster = self.cfg.GetClusterInfo()
1302
      cluster.cluster_name = clustername
1303
      cluster.master_ip = ip
1304
      self.cfg.Update(cluster)
1305

    
1306
      # update the known hosts file
1307
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
1308
      node_list = self.cfg.GetNodeList()
1309
      try:
1310
        node_list.remove(master)
1311
      except ValueError:
1312
        pass
1313
      result = self.rpc.call_upload_file(node_list,
1314
                                         constants.SSH_KNOWN_HOSTS_FILE)
1315
      for to_node, to_result in result.iteritems():
1316
        if to_result.failed or not to_result.data:
1317
          logging.error("Copy of file %s to node %s failed",
1318
                        constants.SSH_KNOWN_HOSTS_FILE, to_node)
1319

    
1320
    finally:
1321
      result = self.rpc.call_node_start_master(master, False)
1322
      if result.failed or not result.data:
1323
        self.LogWarning("Could not re-enable the master role on"
1324
                        " the master, please restart manually.")
1325

    
1326

    
1327
def _RecursiveCheckIfLVMBased(disk):
1328
  """Check if the given disk or its children are lvm-based.
1329

1330
  @type disk: L{objects.Disk}
1331
  @param disk: the disk to check
1332
  @rtype: booleean
1333
  @return: boolean indicating whether a LD_LV dev_type was found or not
1334

1335
  """
1336
  if disk.children:
1337
    for chdisk in disk.children:
1338
      if _RecursiveCheckIfLVMBased(chdisk):
1339
        return True
1340
  return disk.dev_type == constants.LD_LV
1341

    
1342

    
1343
class LUSetClusterParams(LogicalUnit):
1344
  """Change the parameters of the cluster.
1345

1346
  """
1347
  HPATH = "cluster-modify"
1348
  HTYPE = constants.HTYPE_CLUSTER
1349
  _OP_REQP = []
1350
  REQ_BGL = False
1351

    
1352
  def CheckParameters(self):
1353
    """Check parameters
1354

1355
    """
1356
    if not hasattr(self.op, "candidate_pool_size"):
1357
      self.op.candidate_pool_size = None
1358
    if self.op.candidate_pool_size is not None:
1359
      try:
1360
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
1361
      except ValueError, err:
1362
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
1363
                                   str(err))
1364
      if self.op.candidate_pool_size < 1:
1365
        raise errors.OpPrereqError("At least one master candidate needed")
1366

    
1367
  def ExpandNames(self):
1368
    # FIXME: in the future maybe other cluster params won't require checking on
1369
    # all nodes to be modified.
1370
    self.needed_locks = {
1371
      locking.LEVEL_NODE: locking.ALL_SET,
1372
    }
1373
    self.share_locks[locking.LEVEL_NODE] = 1
1374

    
1375
  def BuildHooksEnv(self):
1376
    """Build hooks env.
1377

1378
    """
1379
    env = {
1380
      "OP_TARGET": self.cfg.GetClusterName(),
1381
      "NEW_VG_NAME": self.op.vg_name,
1382
      }
1383
    mn = self.cfg.GetMasterNode()
1384
    return env, [mn], [mn]
1385

    
1386
  def CheckPrereq(self):
1387
    """Check prerequisites.
1388

1389
    This checks whether the given params don't conflict and
1390
    if the given volume group is valid.
1391

1392
    """
1393
    # FIXME: This only works because there is only one parameter that can be
1394
    # changed or removed.
1395
    if self.op.vg_name is not None and not self.op.vg_name:
1396
      instances = self.cfg.GetAllInstancesInfo().values()
1397
      for inst in instances:
1398
        for disk in inst.disks:
1399
          if _RecursiveCheckIfLVMBased(disk):
1400
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1401
                                       " lvm-based instances exist")
1402

    
1403
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1404

    
1405
    # if vg_name not None, checks given volume group on all nodes
1406
    if self.op.vg_name:
1407
      vglist = self.rpc.call_vg_list(node_list)
1408
      for node in node_list:
1409
        if vglist[node].failed:
1410
          # ignoring down node
1411
          self.LogWarning("Node %s unreachable/error, ignoring" % node)
1412
          continue
1413
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].data,
1414
                                              self.op.vg_name,
1415
                                              constants.MIN_VG_SIZE)
1416
        if vgstatus:
1417
          raise errors.OpPrereqError("Error on node '%s': %s" %
1418
                                     (node, vgstatus))
1419

    
1420
    self.cluster = cluster = self.cfg.GetClusterInfo()
1421
    # validate beparams changes
1422
    if self.op.beparams:
1423
      utils.CheckBEParams(self.op.beparams)
1424
      self.new_beparams = cluster.FillDict(
1425
        cluster.beparams[constants.BEGR_DEFAULT], self.op.beparams)
1426

    
1427
    # hypervisor list/parameters
1428
    self.new_hvparams = cluster.FillDict(cluster.hvparams, {})
1429
    if self.op.hvparams:
1430
      if not isinstance(self.op.hvparams, dict):
1431
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input")
1432
      for hv_name, hv_dict in self.op.hvparams.items():
1433
        if hv_name not in self.new_hvparams:
1434
          self.new_hvparams[hv_name] = hv_dict
1435
        else:
1436
          self.new_hvparams[hv_name].update(hv_dict)
1437

    
1438
    if self.op.enabled_hypervisors is not None:
1439
      self.hv_list = self.op.enabled_hypervisors
1440
    else:
1441
      self.hv_list = cluster.enabled_hypervisors
1442

    
1443
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
1444
      # either the enabled list has changed, or the parameters have, validate
1445
      for hv_name, hv_params in self.new_hvparams.items():
1446
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
1447
            (self.op.enabled_hypervisors and
1448
             hv_name in self.op.enabled_hypervisors)):
1449
          # either this is a new hypervisor, or its parameters have changed
1450
          hv_class = hypervisor.GetHypervisor(hv_name)
1451
          hv_class.CheckParameterSyntax(hv_params)
1452
          _CheckHVParams(self, node_list, hv_name, hv_params)
1453

    
1454
  def Exec(self, feedback_fn):
1455
    """Change the parameters of the cluster.
1456

1457
    """
1458
    if self.op.vg_name is not None:
1459
      if self.op.vg_name != self.cfg.GetVGName():
1460
        self.cfg.SetVGName(self.op.vg_name)
1461
      else:
1462
        feedback_fn("Cluster LVM configuration already in desired"
1463
                    " state, not changing")
1464
    if self.op.hvparams:
1465
      self.cluster.hvparams = self.new_hvparams
1466
    if self.op.enabled_hypervisors is not None:
1467
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
1468
    if self.op.beparams:
1469
      self.cluster.beparams[constants.BEGR_DEFAULT] = self.new_beparams
1470
    if self.op.candidate_pool_size is not None:
1471
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
1472

    
1473
    self.cfg.Update(self.cluster)
1474

    
1475
    # we want to update nodes after the cluster so that if any errors
1476
    # happen, we have recorded and saved the cluster info
1477
    if self.op.candidate_pool_size is not None:
1478
      _AdjustCandidatePool(self)
1479

    
1480

    
1481
class LURedistributeConfig(NoHooksLU):
1482
  """Force the redistribution of cluster configuration.
1483

1484
  This is a very simple LU.
1485

1486
  """
1487
  _OP_REQP = []
1488
  REQ_BGL = False
1489

    
1490
  def ExpandNames(self):
1491
    self.needed_locks = {
1492
      locking.LEVEL_NODE: locking.ALL_SET,
1493
    }
1494
    self.share_locks[locking.LEVEL_NODE] = 1
1495

    
1496
  def CheckPrereq(self):
1497
    """Check prerequisites.
1498

1499
    """
1500

    
1501
  def Exec(self, feedback_fn):
1502
    """Redistribute the configuration.
1503

1504
    """
1505
    self.cfg.Update(self.cfg.GetClusterInfo())
1506

    
1507

    
1508
def _WaitForSync(lu, instance, oneshot=False, unlock=False):
1509
  """Sleep and poll for an instance's disk to sync.
1510

1511
  """
1512
  if not instance.disks:
1513
    return True
1514

    
1515
  if not oneshot:
1516
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
1517

    
1518
  node = instance.primary_node
1519

    
1520
  for dev in instance.disks:
1521
    lu.cfg.SetDiskID(dev, node)
1522

    
1523
  retries = 0
1524
  while True:
1525
    max_time = 0
1526
    done = True
1527
    cumul_degraded = False
1528
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
1529
    if rstats.failed or not rstats.data:
1530
      lu.LogWarning("Can't get any data from node %s", node)
1531
      retries += 1
1532
      if retries >= 10:
1533
        raise errors.RemoteError("Can't contact node %s for mirror data,"
1534
                                 " aborting." % node)
1535
      time.sleep(6)
1536
      continue
1537
    rstats = rstats.data
1538
    retries = 0
1539
    for i, mstat in enumerate(rstats):
1540
      if mstat is None:
1541
        lu.LogWarning("Can't compute data for node %s/%s",
1542
                           node, instance.disks[i].iv_name)
1543
        continue
1544
      # we ignore the ldisk parameter
1545
      perc_done, est_time, is_degraded, _ = mstat
1546
      cumul_degraded = cumul_degraded or (is_degraded and perc_done is None)
1547
      if perc_done is not None:
1548
        done = False
1549
        if est_time is not None:
1550
          rem_time = "%d estimated seconds remaining" % est_time
1551
          max_time = est_time
1552
        else:
1553
          rem_time = "no time estimate"
1554
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
1555
                        (instance.disks[i].iv_name, perc_done, rem_time))
1556
    if done or oneshot:
1557
      break
1558

    
1559
    time.sleep(min(60, max_time))
1560

    
1561
  if done:
1562
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
1563
  return not cumul_degraded
1564

    
1565

    
1566
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
1567
  """Check that mirrors are not degraded.
1568

1569
  The ldisk parameter, if True, will change the test from the
1570
  is_degraded attribute (which represents overall non-ok status for
1571
  the device(s)) to the ldisk (representing the local storage status).
1572

1573
  """
1574
  lu.cfg.SetDiskID(dev, node)
1575
  if ldisk:
1576
    idx = 6
1577
  else:
1578
    idx = 5
1579

    
1580
  result = True
1581
  if on_primary or dev.AssembleOnSecondary():
1582
    rstats = lu.rpc.call_blockdev_find(node, dev)
1583
    if rstats.failed or not rstats.data:
1584
      logging.warning("Node %s: disk degraded, not found or node down", node)
1585
      result = False
1586
    else:
1587
      result = result and (not rstats.data[idx])
1588
  if dev.children:
1589
    for child in dev.children:
1590
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
1591

    
1592
  return result
1593

    
1594

    
1595
class LUDiagnoseOS(NoHooksLU):
1596
  """Logical unit for OS diagnose/query.
1597

1598
  """
1599
  _OP_REQP = ["output_fields", "names"]
1600
  REQ_BGL = False
1601
  _FIELDS_STATIC = utils.FieldSet()
1602
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status")
1603

    
1604
  def ExpandNames(self):
1605
    if self.op.names:
1606
      raise errors.OpPrereqError("Selective OS query not supported")
1607

    
1608
    _CheckOutputFields(static=self._FIELDS_STATIC,
1609
                       dynamic=self._FIELDS_DYNAMIC,
1610
                       selected=self.op.output_fields)
1611

    
1612
    # Lock all nodes, in shared mode
1613
    self.needed_locks = {}
1614
    self.share_locks[locking.LEVEL_NODE] = 1
1615
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1616

    
1617
  def CheckPrereq(self):
1618
    """Check prerequisites.
1619

1620
    """
1621

    
1622
  @staticmethod
1623
  def _DiagnoseByOS(node_list, rlist):
1624
    """Remaps a per-node return list into an a per-os per-node dictionary
1625

1626
    @param node_list: a list with the names of all nodes
1627
    @param rlist: a map with node names as keys and OS objects as values
1628

1629
    @rtype: dict
1630
    @returns: a dictionary with osnames as keys and as value another map, with
1631
        nodes as keys and list of OS objects as values, eg::
1632

1633
          {"debian-etch": {"node1": [<object>,...],
1634
                           "node2": [<object>,]}
1635
          }
1636

1637
    """
1638
    all_os = {}
1639
    for node_name, nr in rlist.iteritems():
1640
      if nr.failed or not nr.data:
1641
        continue
1642
      for os_obj in nr.data:
1643
        if os_obj.name not in all_os:
1644
          # build a list of nodes for this os containing empty lists
1645
          # for each node in node_list
1646
          all_os[os_obj.name] = {}
1647
          for nname in node_list:
1648
            all_os[os_obj.name][nname] = []
1649
        all_os[os_obj.name][node_name].append(os_obj)
1650
    return all_os
1651

    
1652
  def Exec(self, feedback_fn):
1653
    """Compute the list of OSes.
1654

1655
    """
1656
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1657
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()
1658
                   if node in node_list]
1659
    node_data = self.rpc.call_os_diagnose(valid_nodes)
1660
    if node_data == False:
1661
      raise errors.OpExecError("Can't gather the list of OSes")
1662
    pol = self._DiagnoseByOS(valid_nodes, node_data)
1663
    output = []
1664
    for os_name, os_data in pol.iteritems():
1665
      row = []
1666
      for field in self.op.output_fields:
1667
        if field == "name":
1668
          val = os_name
1669
        elif field == "valid":
1670
          val = utils.all([osl and osl[0] for osl in os_data.values()])
1671
        elif field == "node_status":
1672
          val = {}
1673
          for node_name, nos_list in os_data.iteritems():
1674
            val[node_name] = [(v.status, v.path) for v in nos_list]
1675
        else:
1676
          raise errors.ParameterError(field)
1677
        row.append(val)
1678
      output.append(row)
1679

    
1680
    return output
1681

    
1682

    
1683
class LURemoveNode(LogicalUnit):
1684
  """Logical unit for removing a node.
1685

1686
  """
1687
  HPATH = "node-remove"
1688
  HTYPE = constants.HTYPE_NODE
1689
  _OP_REQP = ["node_name"]
1690

    
1691
  def BuildHooksEnv(self):
1692
    """Build hooks env.
1693

1694
    This doesn't run on the target node in the pre phase as a failed
1695
    node would then be impossible to remove.
1696

1697
    """
1698
    env = {
1699
      "OP_TARGET": self.op.node_name,
1700
      "NODE_NAME": self.op.node_name,
1701
      }
1702
    all_nodes = self.cfg.GetNodeList()
1703
    all_nodes.remove(self.op.node_name)
1704
    return env, all_nodes, all_nodes
1705

    
1706
  def CheckPrereq(self):
1707
    """Check prerequisites.
1708

1709
    This checks:
1710
     - the node exists in the configuration
1711
     - it does not have primary or secondary instances
1712
     - it's not the master
1713

1714
    Any errors are signalled by raising errors.OpPrereqError.
1715

1716
    """
1717
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
1718
    if node is None:
1719
      raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name)
1720

    
1721
    instance_list = self.cfg.GetInstanceList()
1722

    
1723
    masternode = self.cfg.GetMasterNode()
1724
    if node.name == masternode:
1725
      raise errors.OpPrereqError("Node is the master node,"
1726
                                 " you need to failover first.")
1727

    
1728
    for instance_name in instance_list:
1729
      instance = self.cfg.GetInstanceInfo(instance_name)
1730
      if node.name in instance.all_nodes:
1731
        raise errors.OpPrereqError("Instance %s is still running on the node,"
1732
                                   " please remove first." % instance_name)
1733
    self.op.node_name = node.name
1734
    self.node = node
1735

    
1736
  def Exec(self, feedback_fn):
1737
    """Removes the node from the cluster.
1738

1739
    """
1740
    node = self.node
1741
    logging.info("Stopping the node daemon and removing configs from node %s",
1742
                 node.name)
1743

    
1744
    self.context.RemoveNode(node.name)
1745

    
1746
    self.rpc.call_node_leave_cluster(node.name)
1747

    
1748
    # Promote nodes to master candidate as needed
1749
    _AdjustCandidatePool(self)
1750

    
1751

    
1752
class LUQueryNodes(NoHooksLU):
1753
  """Logical unit for querying nodes.
1754

1755
  """
1756
  _OP_REQP = ["output_fields", "names", "use_locking"]
1757
  REQ_BGL = False
1758
  _FIELDS_DYNAMIC = utils.FieldSet(
1759
    "dtotal", "dfree",
1760
    "mtotal", "mnode", "mfree",
1761
    "bootid",
1762
    "ctotal",
1763
    )
1764

    
1765
  _FIELDS_STATIC = utils.FieldSet(
1766
    "name", "pinst_cnt", "sinst_cnt",
1767
    "pinst_list", "sinst_list",
1768
    "pip", "sip", "tags",
1769
    "serial_no",
1770
    "master_candidate",
1771
    "master",
1772
    "offline",
1773
    )
1774

    
1775
  def ExpandNames(self):
1776
    _CheckOutputFields(static=self._FIELDS_STATIC,
1777
                       dynamic=self._FIELDS_DYNAMIC,
1778
                       selected=self.op.output_fields)
1779

    
1780
    self.needed_locks = {}
1781
    self.share_locks[locking.LEVEL_NODE] = 1
1782

    
1783
    if self.op.names:
1784
      self.wanted = _GetWantedNodes(self, self.op.names)
1785
    else:
1786
      self.wanted = locking.ALL_SET
1787

    
1788
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
1789
    self.do_locking = self.do_node_query and self.op.use_locking
1790
    if self.do_locking:
1791
      # if we don't request only static fields, we need to lock the nodes
1792
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
1793

    
1794

    
1795
  def CheckPrereq(self):
1796
    """Check prerequisites.
1797

1798
    """
1799
    # The validation of the node list is done in the _GetWantedNodes,
1800
    # if non empty, and if empty, there's no validation to do
1801
    pass
1802

    
1803
  def Exec(self, feedback_fn):
1804
    """Computes the list of nodes and their attributes.
1805

1806
    """
1807
    all_info = self.cfg.GetAllNodesInfo()
1808
    if self.do_locking:
1809
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
1810
    elif self.wanted != locking.ALL_SET:
1811
      nodenames = self.wanted
1812
      missing = set(nodenames).difference(all_info.keys())
1813
      if missing:
1814
        raise errors.OpExecError(
1815
          "Some nodes were removed before retrieving their data: %s" % missing)
1816
    else:
1817
      nodenames = all_info.keys()
1818

    
1819
    nodenames = utils.NiceSort(nodenames)
1820
    nodelist = [all_info[name] for name in nodenames]
1821

    
1822
    # begin data gathering
1823

    
1824
    if self.do_node_query:
1825
      live_data = {}
1826
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
1827
                                          self.cfg.GetHypervisorType())
1828
      for name in nodenames:
1829
        nodeinfo = node_data[name]
1830
        if not nodeinfo.failed and nodeinfo.data:
1831
          nodeinfo = nodeinfo.data
1832
          fn = utils.TryConvert
1833
          live_data[name] = {
1834
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
1835
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
1836
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
1837
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
1838
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
1839
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
1840
            "bootid": nodeinfo.get('bootid', None),
1841
            }
1842
        else:
1843
          live_data[name] = {}
1844
    else:
1845
      live_data = dict.fromkeys(nodenames, {})
1846

    
1847
    node_to_primary = dict([(name, set()) for name in nodenames])
1848
    node_to_secondary = dict([(name, set()) for name in nodenames])
1849

    
1850
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
1851
                             "sinst_cnt", "sinst_list"))
1852
    if inst_fields & frozenset(self.op.output_fields):
1853
      instancelist = self.cfg.GetInstanceList()
1854

    
1855
      for instance_name in instancelist:
1856
        inst = self.cfg.GetInstanceInfo(instance_name)
1857
        if inst.primary_node in node_to_primary:
1858
          node_to_primary[inst.primary_node].add(inst.name)
1859
        for secnode in inst.secondary_nodes:
1860
          if secnode in node_to_secondary:
1861
            node_to_secondary[secnode].add(inst.name)
1862

    
1863
    master_node = self.cfg.GetMasterNode()
1864

    
1865
    # end data gathering
1866

    
1867
    output = []
1868
    for node in nodelist:
1869
      node_output = []
1870
      for field in self.op.output_fields:
1871
        if field == "name":
1872
          val = node.name
1873
        elif field == "pinst_list":
1874
          val = list(node_to_primary[node.name])
1875
        elif field == "sinst_list":
1876
          val = list(node_to_secondary[node.name])
1877
        elif field == "pinst_cnt":
1878
          val = len(node_to_primary[node.name])
1879
        elif field == "sinst_cnt":
1880
          val = len(node_to_secondary[node.name])
1881
        elif field == "pip":
1882
          val = node.primary_ip
1883
        elif field == "sip":
1884
          val = node.secondary_ip
1885
        elif field == "tags":
1886
          val = list(node.GetTags())
1887
        elif field == "serial_no":
1888
          val = node.serial_no
1889
        elif field == "master_candidate":
1890
          val = node.master_candidate
1891
        elif field == "master":
1892
          val = node.name == master_node
1893
        elif field == "offline":
1894
          val = node.offline
1895
        elif self._FIELDS_DYNAMIC.Matches(field):
1896
          val = live_data[node.name].get(field, None)
1897
        else:
1898
          raise errors.ParameterError(field)
1899
        node_output.append(val)
1900
      output.append(node_output)
1901

    
1902
    return output
1903

    
1904

    
1905
class LUQueryNodeVolumes(NoHooksLU):
1906
  """Logical unit for getting volumes on node(s).
1907

1908
  """
1909
  _OP_REQP = ["nodes", "output_fields"]
1910
  REQ_BGL = False
1911
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
1912
  _FIELDS_STATIC = utils.FieldSet("node")
1913

    
1914
  def ExpandNames(self):
1915
    _CheckOutputFields(static=self._FIELDS_STATIC,
1916
                       dynamic=self._FIELDS_DYNAMIC,
1917
                       selected=self.op.output_fields)
1918

    
1919
    self.needed_locks = {}
1920
    self.share_locks[locking.LEVEL_NODE] = 1
1921
    if not self.op.nodes:
1922
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1923
    else:
1924
      self.needed_locks[locking.LEVEL_NODE] = \
1925
        _GetWantedNodes(self, self.op.nodes)
1926

    
1927
  def CheckPrereq(self):
1928
    """Check prerequisites.
1929

1930
    This checks that the fields required are valid output fields.
1931

1932
    """
1933
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
1934

    
1935
  def Exec(self, feedback_fn):
1936
    """Computes the list of nodes and their attributes.
1937

1938
    """
1939
    nodenames = self.nodes
1940
    volumes = self.rpc.call_node_volumes(nodenames)
1941

    
1942
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
1943
             in self.cfg.GetInstanceList()]
1944

    
1945
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
1946

    
1947
    output = []
1948
    for node in nodenames:
1949
      if node not in volumes or volumes[node].failed or not volumes[node].data:
1950
        continue
1951

    
1952
      node_vols = volumes[node].data[:]
1953
      node_vols.sort(key=lambda vol: vol['dev'])
1954

    
1955
      for vol in node_vols:
1956
        node_output = []
1957
        for field in self.op.output_fields:
1958
          if field == "node":
1959
            val = node
1960
          elif field == "phys":
1961
            val = vol['dev']
1962
          elif field == "vg":
1963
            val = vol['vg']
1964
          elif field == "name":
1965
            val = vol['name']
1966
          elif field == "size":
1967
            val = int(float(vol['size']))
1968
          elif field == "instance":
1969
            for inst in ilist:
1970
              if node not in lv_by_node[inst]:
1971
                continue
1972
              if vol['name'] in lv_by_node[inst][node]:
1973
                val = inst.name
1974
                break
1975
            else:
1976
              val = '-'
1977
          else:
1978
            raise errors.ParameterError(field)
1979
          node_output.append(str(val))
1980

    
1981
        output.append(node_output)
1982

    
1983
    return output
1984

    
1985

    
1986
class LUAddNode(LogicalUnit):
1987
  """Logical unit for adding node to the cluster.
1988

1989
  """
1990
  HPATH = "node-add"
1991
  HTYPE = constants.HTYPE_NODE
1992
  _OP_REQP = ["node_name"]
1993

    
1994
  def BuildHooksEnv(self):
1995
    """Build hooks env.
1996

1997
    This will run on all nodes before, and on all nodes + the new node after.
1998

1999
    """
2000
    env = {
2001
      "OP_TARGET": self.op.node_name,
2002
      "NODE_NAME": self.op.node_name,
2003
      "NODE_PIP": self.op.primary_ip,
2004
      "NODE_SIP": self.op.secondary_ip,
2005
      }
2006
    nodes_0 = self.cfg.GetNodeList()
2007
    nodes_1 = nodes_0 + [self.op.node_name, ]
2008
    return env, nodes_0, nodes_1
2009

    
2010
  def CheckPrereq(self):
2011
    """Check prerequisites.
2012

2013
    This checks:
2014
     - the new node is not already in the config
2015
     - it is resolvable
2016
     - its parameters (single/dual homed) matches the cluster
2017

2018
    Any errors are signalled by raising errors.OpPrereqError.
2019

2020
    """
2021
    node_name = self.op.node_name
2022
    cfg = self.cfg
2023

    
2024
    dns_data = utils.HostInfo(node_name)
2025

    
2026
    node = dns_data.name
2027
    primary_ip = self.op.primary_ip = dns_data.ip
2028
    secondary_ip = getattr(self.op, "secondary_ip", None)
2029
    if secondary_ip is None:
2030
      secondary_ip = primary_ip
2031
    if not utils.IsValidIP(secondary_ip):
2032
      raise errors.OpPrereqError("Invalid secondary IP given")
2033
    self.op.secondary_ip = secondary_ip
2034

    
2035
    node_list = cfg.GetNodeList()
2036
    if not self.op.readd and node in node_list:
2037
      raise errors.OpPrereqError("Node %s is already in the configuration" %
2038
                                 node)
2039
    elif self.op.readd and node not in node_list:
2040
      raise errors.OpPrereqError("Node %s is not in the configuration" % node)
2041

    
2042
    for existing_node_name in node_list:
2043
      existing_node = cfg.GetNodeInfo(existing_node_name)
2044

    
2045
      if self.op.readd and node == existing_node_name:
2046
        if (existing_node.primary_ip != primary_ip or
2047
            existing_node.secondary_ip != secondary_ip):
2048
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
2049
                                     " address configuration as before")
2050
        continue
2051

    
2052
      if (existing_node.primary_ip == primary_ip or
2053
          existing_node.secondary_ip == primary_ip or
2054
          existing_node.primary_ip == secondary_ip or
2055
          existing_node.secondary_ip == secondary_ip):
2056
        raise errors.OpPrereqError("New node ip address(es) conflict with"
2057
                                   " existing node %s" % existing_node.name)
2058

    
2059
    # check that the type of the node (single versus dual homed) is the
2060
    # same as for the master
2061
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
2062
    master_singlehomed = myself.secondary_ip == myself.primary_ip
2063
    newbie_singlehomed = secondary_ip == primary_ip
2064
    if master_singlehomed != newbie_singlehomed:
2065
      if master_singlehomed:
2066
        raise errors.OpPrereqError("The master has no private ip but the"
2067
                                   " new node has one")
2068
      else:
2069
        raise errors.OpPrereqError("The master has a private ip but the"
2070
                                   " new node doesn't have one")
2071

    
2072
    # checks reachablity
2073
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
2074
      raise errors.OpPrereqError("Node not reachable by ping")
2075

    
2076
    if not newbie_singlehomed:
2077
      # check reachability from my secondary ip to newbie's secondary ip
2078
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
2079
                           source=myself.secondary_ip):
2080
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
2081
                                   " based ping to noded port")
2082

    
2083
    cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2084
    mc_now, _ = self.cfg.GetMasterCandidateStats()
2085
    master_candidate = mc_now < cp_size
2086

    
2087
    self.new_node = objects.Node(name=node,
2088
                                 primary_ip=primary_ip,
2089
                                 secondary_ip=secondary_ip,
2090
                                 master_candidate=master_candidate,
2091
                                 offline=False)
2092

    
2093
  def Exec(self, feedback_fn):
2094
    """Adds the new node to the cluster.
2095

2096
    """
2097
    new_node = self.new_node
2098
    node = new_node.name
2099

    
2100
    # check connectivity
2101
    result = self.rpc.call_version([node])[node]
2102
    result.Raise()
2103
    if result.data:
2104
      if constants.PROTOCOL_VERSION == result.data:
2105
        logging.info("Communication to node %s fine, sw version %s match",
2106
                     node, result.data)
2107
      else:
2108
        raise errors.OpExecError("Version mismatch master version %s,"
2109
                                 " node version %s" %
2110
                                 (constants.PROTOCOL_VERSION, result.data))
2111
    else:
2112
      raise errors.OpExecError("Cannot get version from the new node")
2113

    
2114
    # setup ssh on node
2115
    logging.info("Copy ssh key to node %s", node)
2116
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
2117
    keyarray = []
2118
    keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
2119
                constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
2120
                priv_key, pub_key]
2121

    
2122
    for i in keyfiles:
2123
      f = open(i, 'r')
2124
      try:
2125
        keyarray.append(f.read())
2126
      finally:
2127
        f.close()
2128

    
2129
    result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
2130
                                    keyarray[2],
2131
                                    keyarray[3], keyarray[4], keyarray[5])
2132

    
2133
    msg = result.RemoteFailMsg()
2134
    if msg:
2135
      raise errors.OpExecError("Cannot transfer ssh keys to the"
2136
                               " new node: %s" % msg)
2137

    
2138
    # Add node to our /etc/hosts, and add key to known_hosts
2139
    utils.AddHostToEtcHosts(new_node.name)
2140

    
2141
    if new_node.secondary_ip != new_node.primary_ip:
2142
      result = self.rpc.call_node_has_ip_address(new_node.name,
2143
                                                 new_node.secondary_ip)
2144
      if result.failed or not result.data:
2145
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
2146
                                 " you gave (%s). Please fix and re-run this"
2147
                                 " command." % new_node.secondary_ip)
2148

    
2149
    node_verify_list = [self.cfg.GetMasterNode()]
2150
    node_verify_param = {
2151
      'nodelist': [node],
2152
      # TODO: do a node-net-test as well?
2153
    }
2154

    
2155
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
2156
                                       self.cfg.GetClusterName())
2157
    for verifier in node_verify_list:
2158
      if result[verifier].failed or not result[verifier].data:
2159
        raise errors.OpExecError("Cannot communicate with %s's node daemon"
2160
                                 " for remote verification" % verifier)
2161
      if result[verifier].data['nodelist']:
2162
        for failed in result[verifier].data['nodelist']:
2163
          feedback_fn("ssh/hostname verification failed %s -> %s" %
2164
                      (verifier, result[verifier].data['nodelist'][failed]))
2165
        raise errors.OpExecError("ssh/hostname verification failed.")
2166

    
2167
    # Distribute updated /etc/hosts and known_hosts to all nodes,
2168
    # including the node just added
2169
    myself = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
2170
    dist_nodes = self.cfg.GetNodeList()
2171
    if not self.op.readd:
2172
      dist_nodes.append(node)
2173
    if myself.name in dist_nodes:
2174
      dist_nodes.remove(myself.name)
2175

    
2176
    logging.debug("Copying hosts and known_hosts to all nodes")
2177
    for fname in (constants.ETC_HOSTS, constants.SSH_KNOWN_HOSTS_FILE):
2178
      result = self.rpc.call_upload_file(dist_nodes, fname)
2179
      for to_node, to_result in result.iteritems():
2180
        if to_result.failed or not to_result.data:
2181
          logging.error("Copy of file %s to node %s failed", fname, to_node)
2182

    
2183
    to_copy = []
2184
    enabled_hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
2185
    if constants.HTS_USE_VNC.intersection(enabled_hypervisors):
2186
      to_copy.append(constants.VNC_PASSWORD_FILE)
2187

    
2188
    for fname in to_copy:
2189
      result = self.rpc.call_upload_file([node], fname)
2190
      if result[node].failed or not result[node]:
2191
        logging.error("Could not copy file %s to node %s", fname, node)
2192

    
2193
    if self.op.readd:
2194
      self.context.ReaddNode(new_node)
2195
    else:
2196
      self.context.AddNode(new_node)
2197

    
2198

    
2199
class LUSetNodeParams(LogicalUnit):
2200
  """Modifies the parameters of a node.
2201

2202
  """
2203
  HPATH = "node-modify"
2204
  HTYPE = constants.HTYPE_NODE
2205
  _OP_REQP = ["node_name"]
2206
  REQ_BGL = False
2207

    
2208
  def CheckArguments(self):
2209
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2210
    if node_name is None:
2211
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
2212
    self.op.node_name = node_name
2213
    _CheckBooleanOpField(self.op, 'master_candidate')
2214
    _CheckBooleanOpField(self.op, 'offline')
2215
    if self.op.master_candidate is None and self.op.offline is None:
2216
      raise errors.OpPrereqError("Please pass at least one modification")
2217
    if self.op.offline == True and self.op.master_candidate == True:
2218
      raise errors.OpPrereqError("Can't set the node into offline and"
2219
                                 " master_candidate at the same time")
2220

    
2221
  def ExpandNames(self):
2222
    self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
2223

    
2224
  def BuildHooksEnv(self):
2225
    """Build hooks env.
2226

2227
    This runs on the master node.
2228

2229
    """
2230
    env = {
2231
      "OP_TARGET": self.op.node_name,
2232
      "MASTER_CANDIDATE": str(self.op.master_candidate),
2233
      "OFFLINE": str(self.op.offline),
2234
      }
2235
    nl = [self.cfg.GetMasterNode(),
2236
          self.op.node_name]
2237
    return env, nl, nl
2238

    
2239
  def CheckPrereq(self):
2240
    """Check prerequisites.
2241

2242
    This only checks the instance list against the existing names.
2243

2244
    """
2245
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
2246

    
2247
    if ((self.op.master_candidate == False or self.op.offline == True)
2248
        and node.master_candidate):
2249
      # we will demote the node from master_candidate
2250
      if self.op.node_name == self.cfg.GetMasterNode():
2251
        raise errors.OpPrereqError("The master node has to be a"
2252
                                   " master candidate and online")
2253
      cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2254
      num_candidates, _ = self.cfg.GetMasterCandidateStats()
2255
      if num_candidates <= cp_size:
2256
        msg = ("Not enough master candidates (desired"
2257
               " %d, new value will be %d)" % (cp_size, num_candidates-1))
2258
        if self.op.force:
2259
          self.LogWarning(msg)
2260
        else:
2261
          raise errors.OpPrereqError(msg)
2262

    
2263
    if (self.op.master_candidate == True and node.offline and
2264
        not self.op.offline == False):
2265
      raise errors.OpPrereqError("Can't set an offline node to"
2266
                                 " master_candidate")
2267

    
2268
    return
2269

    
2270
  def Exec(self, feedback_fn):
2271
    """Modifies a node.
2272

2273
    """
2274
    node = self.node
2275

    
2276
    result = []
2277

    
2278
    if self.op.offline is not None:
2279
      node.offline = self.op.offline
2280
      result.append(("offline", str(self.op.offline)))
2281
      if self.op.offline == True and node.master_candidate:
2282
        node.master_candidate = False
2283
        result.append(("master_candidate", "auto-demotion due to offline"))
2284

    
2285
    if self.op.master_candidate is not None:
2286
      node.master_candidate = self.op.master_candidate
2287
      result.append(("master_candidate", str(self.op.master_candidate)))
2288
      if self.op.master_candidate == False:
2289
        rrc = self.rpc.call_node_demote_from_mc(node.name)
2290
        msg = rrc.RemoteFailMsg()
2291
        if msg:
2292
          self.LogWarning("Node failed to demote itself: %s" % msg)
2293

    
2294
    # this will trigger configuration file update, if needed
2295
    self.cfg.Update(node)
2296
    # this will trigger job queue propagation or cleanup
2297
    if self.op.node_name != self.cfg.GetMasterNode():
2298
      self.context.ReaddNode(node)
2299

    
2300
    return result
2301

    
2302

    
2303
class LUQueryClusterInfo(NoHooksLU):
2304
  """Query cluster configuration.
2305

2306
  """
2307
  _OP_REQP = []
2308
  REQ_BGL = False
2309

    
2310
  def ExpandNames(self):
2311
    self.needed_locks = {}
2312

    
2313
  def CheckPrereq(self):
2314
    """No prerequsites needed for this LU.
2315

2316
    """
2317
    pass
2318

    
2319
  def Exec(self, feedback_fn):
2320
    """Return cluster config.
2321

2322
    """
2323
    cluster = self.cfg.GetClusterInfo()
2324
    result = {
2325
      "software_version": constants.RELEASE_VERSION,
2326
      "protocol_version": constants.PROTOCOL_VERSION,
2327
      "config_version": constants.CONFIG_VERSION,
2328
      "os_api_version": constants.OS_API_VERSION,
2329
      "export_version": constants.EXPORT_VERSION,
2330
      "architecture": (platform.architecture()[0], platform.machine()),
2331
      "name": cluster.cluster_name,
2332
      "master": cluster.master_node,
2333
      "default_hypervisor": cluster.default_hypervisor,
2334
      "enabled_hypervisors": cluster.enabled_hypervisors,
2335
      "hvparams": dict([(hypervisor, cluster.hvparams[hypervisor])
2336
                        for hypervisor in cluster.enabled_hypervisors]),
2337
      "beparams": cluster.beparams,
2338
      "candidate_pool_size": cluster.candidate_pool_size,
2339
      }
2340

    
2341
    return result
2342

    
2343

    
2344
class LUQueryConfigValues(NoHooksLU):
2345
  """Return configuration values.
2346

2347
  """
2348
  _OP_REQP = []
2349
  REQ_BGL = False
2350
  _FIELDS_DYNAMIC = utils.FieldSet()
2351
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag")
2352

    
2353
  def ExpandNames(self):
2354
    self.needed_locks = {}
2355

    
2356
    _CheckOutputFields(static=self._FIELDS_STATIC,
2357
                       dynamic=self._FIELDS_DYNAMIC,
2358
                       selected=self.op.output_fields)
2359

    
2360
  def CheckPrereq(self):
2361
    """No prerequisites.
2362

2363
    """
2364
    pass
2365

    
2366
  def Exec(self, feedback_fn):
2367
    """Dump a representation of the cluster config to the standard output.
2368

2369
    """
2370
    values = []
2371
    for field in self.op.output_fields:
2372
      if field == "cluster_name":
2373
        entry = self.cfg.GetClusterName()
2374
      elif field == "master_node":
2375
        entry = self.cfg.GetMasterNode()
2376
      elif field == "drain_flag":
2377
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
2378
      else:
2379
        raise errors.ParameterError(field)
2380
      values.append(entry)
2381
    return values
2382

    
2383

    
2384
class LUActivateInstanceDisks(NoHooksLU):
2385
  """Bring up an instance's disks.
2386

2387
  """
2388
  _OP_REQP = ["instance_name"]
2389
  REQ_BGL = False
2390

    
2391
  def ExpandNames(self):
2392
    self._ExpandAndLockInstance()
2393
    self.needed_locks[locking.LEVEL_NODE] = []
2394
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2395

    
2396
  def DeclareLocks(self, level):
2397
    if level == locking.LEVEL_NODE:
2398
      self._LockInstancesNodes()
2399

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

2403
    This checks that the instance is in the cluster.
2404

2405
    """
2406
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2407
    assert self.instance is not None, \
2408
      "Cannot retrieve locked instance %s" % self.op.instance_name
2409
    _CheckNodeOnline(self, self.instance.primary_node)
2410

    
2411
  def Exec(self, feedback_fn):
2412
    """Activate the disks.
2413

2414
    """
2415
    disks_ok, disks_info = _AssembleInstanceDisks(self, self.instance)
2416
    if not disks_ok:
2417
      raise errors.OpExecError("Cannot activate block devices")
2418

    
2419
    return disks_info
2420

    
2421

    
2422
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False):
2423
  """Prepare the block devices for an instance.
2424

2425
  This sets up the block devices on all nodes.
2426

2427
  @type lu: L{LogicalUnit}
2428
  @param lu: the logical unit on whose behalf we execute
2429
  @type instance: L{objects.Instance}
2430
  @param instance: the instance for whose disks we assemble
2431
  @type ignore_secondaries: boolean
2432
  @param ignore_secondaries: if true, errors on secondary nodes
2433
      won't result in an error return from the function
2434
  @return: False if the operation failed, otherwise a list of
2435
      (host, instance_visible_name, node_visible_name)
2436
      with the mapping from node devices to instance devices
2437

2438
  """
2439
  device_info = []
2440
  disks_ok = True
2441
  iname = instance.name
2442
  # With the two passes mechanism we try to reduce the window of
2443
  # opportunity for the race condition of switching DRBD to primary
2444
  # before handshaking occured, but we do not eliminate it
2445

    
2446
  # The proper fix would be to wait (with some limits) until the
2447
  # connection has been made and drbd transitions from WFConnection
2448
  # into any other network-connected state (Connected, SyncTarget,
2449
  # SyncSource, etc.)
2450

    
2451
  # 1st pass, assemble on all nodes in secondary mode
2452
  for inst_disk in instance.disks:
2453
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2454
      lu.cfg.SetDiskID(node_disk, node)
2455
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
2456
      if result.failed or not result:
2457
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2458
                           " (is_primary=False, pass=1)",
2459
                           inst_disk.iv_name, node)
2460
        if not ignore_secondaries:
2461
          disks_ok = False
2462

    
2463
  # FIXME: race condition on drbd migration to primary
2464

    
2465
  # 2nd pass, do only the primary node
2466
  for inst_disk in instance.disks:
2467
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2468
      if node != instance.primary_node:
2469
        continue
2470
      lu.cfg.SetDiskID(node_disk, node)
2471
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
2472
      if result.failed or not result:
2473
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2474
                           " (is_primary=True, pass=2)",
2475
                           inst_disk.iv_name, node)
2476
        disks_ok = False
2477
    device_info.append((instance.primary_node, inst_disk.iv_name, result.data))
2478

    
2479
  # leave the disks configured for the primary node
2480
  # this is a workaround that would be fixed better by
2481
  # improving the logical/physical id handling
2482
  for disk in instance.disks:
2483
    lu.cfg.SetDiskID(disk, instance.primary_node)
2484

    
2485
  return disks_ok, device_info
2486

    
2487

    
2488
def _StartInstanceDisks(lu, instance, force):
2489
  """Start the disks of an instance.
2490

2491
  """
2492
  disks_ok, dummy = _AssembleInstanceDisks(lu, instance,
2493
                                           ignore_secondaries=force)
2494
  if not disks_ok:
2495
    _ShutdownInstanceDisks(lu, instance)
2496
    if force is not None and not force:
2497
      lu.proc.LogWarning("", hint="If the message above refers to a"
2498
                         " secondary node,"
2499
                         " you can retry the operation using '--force'.")
2500
    raise errors.OpExecError("Disk consistency error")
2501

    
2502

    
2503
class LUDeactivateInstanceDisks(NoHooksLU):
2504
  """Shutdown an instance's disks.
2505

2506
  """
2507
  _OP_REQP = ["instance_name"]
2508
  REQ_BGL = False
2509

    
2510
  def ExpandNames(self):
2511
    self._ExpandAndLockInstance()
2512
    self.needed_locks[locking.LEVEL_NODE] = []
2513
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2514

    
2515
  def DeclareLocks(self, level):
2516
    if level == locking.LEVEL_NODE:
2517
      self._LockInstancesNodes()
2518

    
2519
  def CheckPrereq(self):
2520
    """Check prerequisites.
2521

2522
    This checks that the instance is in the cluster.
2523

2524
    """
2525
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2526
    assert self.instance is not None, \
2527
      "Cannot retrieve locked instance %s" % self.op.instance_name
2528

    
2529
  def Exec(self, feedback_fn):
2530
    """Deactivate the disks
2531

2532
    """
2533
    instance = self.instance
2534
    _SafeShutdownInstanceDisks(self, instance)
2535

    
2536

    
2537
def _SafeShutdownInstanceDisks(lu, instance):
2538
  """Shutdown block devices of an instance.
2539

2540
  This function checks if an instance is running, before calling
2541
  _ShutdownInstanceDisks.
2542

2543
  """
2544
  ins_l = lu.rpc.call_instance_list([instance.primary_node],
2545
                                      [instance.hypervisor])
2546
  ins_l = ins_l[instance.primary_node]
2547
  if ins_l.failed or not isinstance(ins_l.data, list):
2548
    raise errors.OpExecError("Can't contact node '%s'" %
2549
                             instance.primary_node)
2550

    
2551
  if instance.name in ins_l.data:
2552
    raise errors.OpExecError("Instance is running, can't shutdown"
2553
                             " block devices.")
2554

    
2555
  _ShutdownInstanceDisks(lu, instance)
2556

    
2557

    
2558
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
2559
  """Shutdown block devices of an instance.
2560

2561
  This does the shutdown on all nodes of the instance.
2562

2563
  If the ignore_primary is false, errors on the primary node are
2564
  ignored.
2565

2566
  """
2567
  result = True
2568
  for disk in instance.disks:
2569
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
2570
      lu.cfg.SetDiskID(top_disk, node)
2571
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
2572
      if result.failed or not result.data:
2573
        logging.error("Could not shutdown block device %s on node %s",
2574
                      disk.iv_name, node)
2575
        if not ignore_primary or node != instance.primary_node:
2576
          result = False
2577
  return result
2578

    
2579

    
2580
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
2581
  """Checks if a node has enough free memory.
2582

2583
  This function check if a given node has the needed amount of free
2584
  memory. In case the node has less memory or we cannot get the
2585
  information from the node, this function raise an OpPrereqError
2586
  exception.
2587

2588
  @type lu: C{LogicalUnit}
2589
  @param lu: a logical unit from which we get configuration data
2590
  @type node: C{str}
2591
  @param node: the node to check
2592
  @type reason: C{str}
2593
  @param reason: string to use in the error message
2594
  @type requested: C{int}
2595
  @param requested: the amount of memory in MiB to check for
2596
  @type hypervisor_name: C{str}
2597
  @param hypervisor_name: the hypervisor to ask for memory stats
2598
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
2599
      we cannot check the node
2600

2601
  """
2602
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
2603
  nodeinfo[node].Raise()
2604
  free_mem = nodeinfo[node].data.get('memory_free')
2605
  if not isinstance(free_mem, int):
2606
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
2607
                             " was '%s'" % (node, free_mem))
2608
  if requested > free_mem:
2609
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
2610
                             " needed %s MiB, available %s MiB" %
2611
                             (node, reason, requested, free_mem))
2612

    
2613

    
2614
class LUStartupInstance(LogicalUnit):
2615
  """Starts an instance.
2616

2617
  """
2618
  HPATH = "instance-start"
2619
  HTYPE = constants.HTYPE_INSTANCE
2620
  _OP_REQP = ["instance_name", "force"]
2621
  REQ_BGL = False
2622

    
2623
  def ExpandNames(self):
2624
    self._ExpandAndLockInstance()
2625

    
2626
  def BuildHooksEnv(self):
2627
    """Build hooks env.
2628

2629
    This runs on master, primary and secondary nodes of the instance.
2630

2631
    """
2632
    env = {
2633
      "FORCE": self.op.force,
2634
      }
2635
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2636
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2637
    return env, nl, nl
2638

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

2642
    This checks that the instance is in the cluster.
2643

2644
    """
2645
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2646
    assert self.instance is not None, \
2647
      "Cannot retrieve locked instance %s" % self.op.instance_name
2648

    
2649
    _CheckNodeOnline(self, instance.primary_node)
2650

    
2651
    bep = self.cfg.GetClusterInfo().FillBE(instance)
2652
    # check bridges existance
2653
    _CheckInstanceBridgesExist(self, instance)
2654

    
2655
    _CheckNodeFreeMemory(self, instance.primary_node,
2656
                         "starting instance %s" % instance.name,
2657
                         bep[constants.BE_MEMORY], instance.hypervisor)
2658

    
2659
  def Exec(self, feedback_fn):
2660
    """Start the instance.
2661

2662
    """
2663
    instance = self.instance
2664
    force = self.op.force
2665
    extra_args = getattr(self.op, "extra_args", "")
2666

    
2667
    self.cfg.MarkInstanceUp(instance.name)
2668

    
2669
    node_current = instance.primary_node
2670

    
2671
    _StartInstanceDisks(self, instance, force)
2672

    
2673
    result = self.rpc.call_instance_start(node_current, instance, extra_args)
2674
    msg = result.RemoteFailMsg()
2675
    if msg:
2676
      _ShutdownInstanceDisks(self, instance)
2677
      raise errors.OpExecError("Could not start instance: %s" % msg)
2678

    
2679

    
2680
class LURebootInstance(LogicalUnit):
2681
  """Reboot an instance.
2682

2683
  """
2684
  HPATH = "instance-reboot"
2685
  HTYPE = constants.HTYPE_INSTANCE
2686
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
2687
  REQ_BGL = False
2688

    
2689
  def ExpandNames(self):
2690
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
2691
                                   constants.INSTANCE_REBOOT_HARD,
2692
                                   constants.INSTANCE_REBOOT_FULL]:
2693
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
2694
                                  (constants.INSTANCE_REBOOT_SOFT,
2695
                                   constants.INSTANCE_REBOOT_HARD,
2696
                                   constants.INSTANCE_REBOOT_FULL))
2697
    self._ExpandAndLockInstance()
2698

    
2699
  def BuildHooksEnv(self):
2700
    """Build hooks env.
2701

2702
    This runs on master, primary and secondary nodes of the instance.
2703

2704
    """
2705
    env = {
2706
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
2707
      }
2708
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2709
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2710
    return env, nl, nl
2711

    
2712
  def CheckPrereq(self):
2713
    """Check prerequisites.
2714

2715
    This checks that the instance is in the cluster.
2716

2717
    """
2718
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2719
    assert self.instance is not None, \
2720
      "Cannot retrieve locked instance %s" % self.op.instance_name
2721

    
2722
    _CheckNodeOnline(self, instance.primary_node)
2723

    
2724
    # check bridges existance
2725
    _CheckInstanceBridgesExist(self, instance)
2726

    
2727
  def Exec(self, feedback_fn):
2728
    """Reboot the instance.
2729

2730
    """
2731
    instance = self.instance
2732
    ignore_secondaries = self.op.ignore_secondaries
2733
    reboot_type = self.op.reboot_type
2734
    extra_args = getattr(self.op, "extra_args", "")
2735

    
2736
    node_current = instance.primary_node
2737

    
2738
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
2739
                       constants.INSTANCE_REBOOT_HARD]:
2740
      result = self.rpc.call_instance_reboot(node_current, instance,
2741
                                             reboot_type, extra_args)
2742
      if result.failed or not result.data:
2743
        raise errors.OpExecError("Could not reboot instance")
2744
    else:
2745
      if not self.rpc.call_instance_shutdown(node_current, instance):
2746
        raise errors.OpExecError("could not shutdown instance for full reboot")
2747
      _ShutdownInstanceDisks(self, instance)
2748
      _StartInstanceDisks(self, instance, ignore_secondaries)
2749
      result = self.rpc.call_instance_start(node_current, instance, extra_args)
2750
      msg = result.RemoteFailMsg()
2751
      if msg:
2752
        _ShutdownInstanceDisks(self, instance)
2753
        raise errors.OpExecError("Could not start instance for"
2754
                                 " full reboot: %s" % msg)
2755

    
2756
    self.cfg.MarkInstanceUp(instance.name)
2757

    
2758

    
2759
class LUShutdownInstance(LogicalUnit):
2760
  """Shutdown an instance.
2761

2762
  """
2763
  HPATH = "instance-stop"
2764
  HTYPE = constants.HTYPE_INSTANCE
2765
  _OP_REQP = ["instance_name"]
2766
  REQ_BGL = False
2767

    
2768
  def ExpandNames(self):
2769
    self._ExpandAndLockInstance()
2770

    
2771
  def BuildHooksEnv(self):
2772
    """Build hooks env.
2773

2774
    This runs on master, primary and secondary nodes of the instance.
2775

2776
    """
2777
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2778
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2779
    return env, nl, nl
2780

    
2781
  def CheckPrereq(self):
2782
    """Check prerequisites.
2783

2784
    This checks that the instance is in the cluster.
2785

2786
    """
2787
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2788
    assert self.instance is not None, \
2789
      "Cannot retrieve locked instance %s" % self.op.instance_name
2790
    _CheckNodeOnline(self, self.instance.primary_node)
2791

    
2792
  def Exec(self, feedback_fn):
2793
    """Shutdown the instance.
2794

2795
    """
2796
    instance = self.instance
2797
    node_current = instance.primary_node
2798
    self.cfg.MarkInstanceDown(instance.name)
2799
    result = self.rpc.call_instance_shutdown(node_current, instance)
2800
    if result.failed or not result.data:
2801
      self.proc.LogWarning("Could not shutdown instance")
2802

    
2803
    _ShutdownInstanceDisks(self, instance)
2804

    
2805

    
2806
class LUReinstallInstance(LogicalUnit):
2807
  """Reinstall an instance.
2808

2809
  """
2810
  HPATH = "instance-reinstall"
2811
  HTYPE = constants.HTYPE_INSTANCE
2812
  _OP_REQP = ["instance_name"]
2813
  REQ_BGL = False
2814

    
2815
  def ExpandNames(self):
2816
    self._ExpandAndLockInstance()
2817

    
2818
  def BuildHooksEnv(self):
2819
    """Build hooks env.
2820

2821
    This runs on master, primary and secondary nodes of the instance.
2822

2823
    """
2824
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2825
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2826
    return env, nl, nl
2827

    
2828
  def CheckPrereq(self):
2829
    """Check prerequisites.
2830

2831
    This checks that the instance is in the cluster and is not running.
2832

2833
    """
2834
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2835
    assert instance is not None, \
2836
      "Cannot retrieve locked instance %s" % self.op.instance_name
2837
    _CheckNodeOnline(self, instance.primary_node)
2838

    
2839
    if instance.disk_template == constants.DT_DISKLESS:
2840
      raise errors.OpPrereqError("Instance '%s' has no disks" %
2841
                                 self.op.instance_name)
2842
    if instance.admin_up:
2843
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2844
                                 self.op.instance_name)
2845
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2846
                                              instance.name,
2847
                                              instance.hypervisor)
2848
    if remote_info.failed or remote_info.data:
2849
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2850
                                 (self.op.instance_name,
2851
                                  instance.primary_node))
2852

    
2853
    self.op.os_type = getattr(self.op, "os_type", None)
2854
    if self.op.os_type is not None:
2855
      # OS verification
2856
      pnode = self.cfg.GetNodeInfo(
2857
        self.cfg.ExpandNodeName(instance.primary_node))
2858
      if pnode is None:
2859
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
2860
                                   self.op.pnode)
2861
      result = self.rpc.call_os_get(pnode.name, self.op.os_type)
2862
      result.Raise()
2863
      if not isinstance(result.data, objects.OS):
2864
        raise errors.OpPrereqError("OS '%s' not in supported OS list for"
2865
                                   " primary node"  % self.op.os_type)
2866

    
2867
    self.instance = instance
2868

    
2869
  def Exec(self, feedback_fn):
2870
    """Reinstall the instance.
2871

2872
    """
2873
    inst = self.instance
2874

    
2875
    if self.op.os_type is not None:
2876
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
2877
      inst.os = self.op.os_type
2878
      self.cfg.Update(inst)
2879

    
2880
    _StartInstanceDisks(self, inst, None)
2881
    try:
2882
      feedback_fn("Running the instance OS create scripts...")
2883
      result = self.rpc.call_instance_os_add(inst.primary_node, inst)
2884
      msg = result.RemoteFailMsg()
2885
      if msg:
2886
        raise errors.OpExecError("Could not install OS for instance %s"
2887
                                 " on node %s: %s" %
2888
                                 (inst.name, inst.primary_node, msg))
2889
    finally:
2890
      _ShutdownInstanceDisks(self, inst)
2891

    
2892

    
2893
class LURenameInstance(LogicalUnit):
2894
  """Rename an instance.
2895

2896
  """
2897
  HPATH = "instance-rename"
2898
  HTYPE = constants.HTYPE_INSTANCE
2899
  _OP_REQP = ["instance_name", "new_name"]
2900

    
2901
  def BuildHooksEnv(self):
2902
    """Build hooks env.
2903

2904
    This runs on master, primary and secondary nodes of the instance.
2905

2906
    """
2907
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2908
    env["INSTANCE_NEW_NAME"] = self.op.new_name
2909
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2910
    return env, nl, nl
2911

    
2912
  def CheckPrereq(self):
2913
    """Check prerequisites.
2914

2915
    This checks that the instance is in the cluster and is not running.
2916

2917
    """
2918
    instance = self.cfg.GetInstanceInfo(
2919
      self.cfg.ExpandInstanceName(self.op.instance_name))
2920
    if instance is None:
2921
      raise errors.OpPrereqError("Instance '%s' not known" %
2922
                                 self.op.instance_name)
2923
    _CheckNodeOnline(self, instance.primary_node)
2924

    
2925
    if instance.admin_up:
2926
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2927
                                 self.op.instance_name)
2928
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2929
                                              instance.name,
2930
                                              instance.hypervisor)
2931
    remote_info.Raise()
2932
    if remote_info.data:
2933
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2934
                                 (self.op.instance_name,
2935
                                  instance.primary_node))
2936
    self.instance = instance
2937

    
2938
    # new name verification
2939
    name_info = utils.HostInfo(self.op.new_name)
2940

    
2941
    self.op.new_name = new_name = name_info.name
2942
    instance_list = self.cfg.GetInstanceList()
2943
    if new_name in instance_list:
2944
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
2945
                                 new_name)
2946

    
2947
    if not getattr(self.op, "ignore_ip", False):
2948
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
2949
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
2950
                                   (name_info.ip, new_name))
2951

    
2952

    
2953
  def Exec(self, feedback_fn):
2954
    """Reinstall the instance.
2955

2956
    """
2957
    inst = self.instance
2958
    old_name = inst.name
2959

    
2960
    if inst.disk_template == constants.DT_FILE:
2961
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2962

    
2963
    self.cfg.RenameInstance(inst.name, self.op.new_name)
2964
    # Change the instance lock. This is definitely safe while we hold the BGL
2965
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
2966
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
2967

    
2968
    # re-read the instance from the configuration after rename
2969
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
2970

    
2971
    if inst.disk_template == constants.DT_FILE:
2972
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2973
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
2974
                                                     old_file_storage_dir,
2975
                                                     new_file_storage_dir)
2976
      result.Raise()
2977
      if not result.data:
2978
        raise errors.OpExecError("Could not connect to node '%s' to rename"
2979
                                 " directory '%s' to '%s' (but the instance"
2980
                                 " has been renamed in Ganeti)" % (
2981
                                 inst.primary_node, old_file_storage_dir,
2982
                                 new_file_storage_dir))
2983

    
2984
      if not result.data[0]:
2985
        raise errors.OpExecError("Could not rename directory '%s' to '%s'"
2986
                                 " (but the instance has been renamed in"
2987
                                 " Ganeti)" % (old_file_storage_dir,
2988
                                               new_file_storage_dir))
2989

    
2990
    _StartInstanceDisks(self, inst, None)
2991
    try:
2992
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
2993
                                                 old_name)
2994
      msg = result.RemoteFailMsg()
2995
      if msg:
2996
        msg = ("Could not run OS rename script for instance %s on node %s"
2997
               " (but the instance has been renamed in Ganeti): %s" %
2998
               (inst.name, inst.primary_node, msg))
2999
        self.proc.LogWarning(msg)
3000
    finally:
3001
      _ShutdownInstanceDisks(self, inst)
3002

    
3003

    
3004
class LURemoveInstance(LogicalUnit):
3005
  """Remove an instance.
3006

3007
  """
3008
  HPATH = "instance-remove"
3009
  HTYPE = constants.HTYPE_INSTANCE
3010
  _OP_REQP = ["instance_name", "ignore_failures"]
3011
  REQ_BGL = False
3012

    
3013
  def ExpandNames(self):
3014
    self._ExpandAndLockInstance()
3015
    self.needed_locks[locking.LEVEL_NODE] = []
3016
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3017

    
3018
  def DeclareLocks(self, level):
3019
    if level == locking.LEVEL_NODE:
3020
      self._LockInstancesNodes()
3021

    
3022
  def BuildHooksEnv(self):
3023
    """Build hooks env.
3024

3025
    This runs on master, primary and secondary nodes of the instance.
3026

3027
    """
3028
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3029
    nl = [self.cfg.GetMasterNode()]
3030
    return env, nl, nl
3031

    
3032
  def CheckPrereq(self):
3033
    """Check prerequisites.
3034

3035
    This checks that the instance is in the cluster.
3036

3037
    """
3038
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3039
    assert self.instance is not None, \
3040
      "Cannot retrieve locked instance %s" % self.op.instance_name
3041

    
3042
  def Exec(self, feedback_fn):
3043
    """Remove the instance.
3044

3045
    """
3046
    instance = self.instance
3047
    logging.info("Shutting down instance %s on node %s",
3048
                 instance.name, instance.primary_node)
3049

    
3050
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance)
3051
    if result.failed or not result.data:
3052
      if self.op.ignore_failures:
3053
        feedback_fn("Warning: can't shutdown instance")
3054
      else:
3055
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
3056
                                 (instance.name, instance.primary_node))
3057

    
3058
    logging.info("Removing block devices for instance %s", instance.name)
3059

    
3060
    if not _RemoveDisks(self, instance):
3061
      if self.op.ignore_failures:
3062
        feedback_fn("Warning: can't remove instance's disks")
3063
      else:
3064
        raise errors.OpExecError("Can't remove instance's disks")
3065

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

    
3068
    self.cfg.RemoveInstance(instance.name)
3069
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
3070

    
3071

    
3072
class LUQueryInstances(NoHooksLU):
3073
  """Logical unit for querying instances.
3074

3075
  """
3076
  _OP_REQP = ["output_fields", "names", "use_locking"]
3077
  REQ_BGL = False
3078
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
3079
                                    "admin_state", "admin_ram",
3080
                                    "disk_template", "ip", "mac", "bridge",
3081
                                    "sda_size", "sdb_size", "vcpus", "tags",
3082
                                    "network_port", "beparams",
3083
                                    "(disk).(size)/([0-9]+)",
3084
                                    "(disk).(sizes)",
3085
                                    "(nic).(mac|ip|bridge)/([0-9]+)",
3086
                                    "(nic).(macs|ips|bridges)",
3087
                                    "(disk|nic).(count)",
3088
                                    "serial_no", "hypervisor", "hvparams",] +
3089
                                  ["hv/%s" % name
3090
                                   for name in constants.HVS_PARAMETERS] +
3091
                                  ["be/%s" % name
3092
                                   for name in constants.BES_PARAMETERS])
3093
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
3094

    
3095

    
3096
  def ExpandNames(self):
3097
    _CheckOutputFields(static=self._FIELDS_STATIC,
3098
                       dynamic=self._FIELDS_DYNAMIC,
3099
                       selected=self.op.output_fields)
3100

    
3101
    self.needed_locks = {}
3102
    self.share_locks[locking.LEVEL_INSTANCE] = 1
3103
    self.share_locks[locking.LEVEL_NODE] = 1
3104

    
3105
    if self.op.names:
3106
      self.wanted = _GetWantedInstances(self, self.op.names)
3107
    else:
3108
      self.wanted = locking.ALL_SET
3109

    
3110
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3111
    self.do_locking = self.do_node_query and self.op.use_locking
3112
    if self.do_locking:
3113
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
3114
      self.needed_locks[locking.LEVEL_NODE] = []
3115
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3116

    
3117
  def DeclareLocks(self, level):
3118
    if level == locking.LEVEL_NODE and self.do_locking:
3119
      self._LockInstancesNodes()
3120

    
3121
  def CheckPrereq(self):
3122
    """Check prerequisites.
3123

3124
    """
3125
    pass
3126

    
3127
  def Exec(self, feedback_fn):
3128
    """Computes the list of nodes and their attributes.
3129

3130
    """
3131
    all_info = self.cfg.GetAllInstancesInfo()
3132
    if self.wanted == locking.ALL_SET:
3133
      # caller didn't specify instance names, so ordering is not important
3134
      if self.do_locking:
3135
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
3136
      else:
3137
        instance_names = all_info.keys()
3138
      instance_names = utils.NiceSort(instance_names)
3139
    else:
3140
      # caller did specify names, so we must keep the ordering
3141
      if self.do_locking:
3142
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
3143
      else:
3144
        tgt_set = all_info.keys()
3145
      missing = set(self.wanted).difference(tgt_set)
3146
      if missing:
3147
        raise errors.OpExecError("Some instances were removed before"
3148
                                 " retrieving their data: %s" % missing)
3149
      instance_names = self.wanted
3150

    
3151
    instance_list = [all_info[iname] for iname in instance_names]
3152

    
3153
    # begin data gathering
3154

    
3155
    nodes = frozenset([inst.primary_node for inst in instance_list])
3156
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
3157

    
3158
    bad_nodes = []
3159
    off_nodes = []
3160
    if self.do_node_query:
3161
      live_data = {}
3162
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
3163
      for name in nodes:
3164
        result = node_data[name]
3165
        if result.offline:
3166
          # offline nodes will be in both lists
3167
          off_nodes.append(name)
3168
        if result.failed:
3169
          bad_nodes.append(name)
3170
        else:
3171
          if result.data:
3172
            live_data.update(result.data)
3173
            # else no instance is alive
3174
    else:
3175
      live_data = dict([(name, {}) for name in instance_names])
3176

    
3177
    # end data gathering
3178

    
3179
    HVPREFIX = "hv/"
3180
    BEPREFIX = "be/"
3181
    output = []
3182
    for instance in instance_list:
3183
      iout = []
3184
      i_hv = self.cfg.GetClusterInfo().FillHV(instance)
3185
      i_be = self.cfg.GetClusterInfo().FillBE(instance)
3186
      for field in self.op.output_fields:
3187
        st_match = self._FIELDS_STATIC.Matches(field)
3188
        if field == "name":
3189
          val = instance.name
3190
        elif field == "os":
3191
          val = instance.os
3192
        elif field == "pnode":
3193
          val = instance.primary_node
3194
        elif field == "snodes":
3195
          val = list(instance.secondary_nodes)
3196
        elif field == "admin_state":
3197
          val = instance.admin_up
3198
        elif field == "oper_state":
3199
          if instance.primary_node in bad_nodes:
3200
            val = None
3201
          else:
3202
            val = bool(live_data.get(instance.name))
3203
        elif field == "status":
3204
          if instance.primary_node in off_nodes:
3205
            val = "ERROR_nodeoffline"
3206
          elif instance.primary_node in bad_nodes:
3207
            val = "ERROR_nodedown"
3208
          else:
3209
            running = bool(live_data.get(instance.name))
3210
            if running:
3211
              if instance.admin_up:
3212
                val = "running"
3213
              else:
3214
                val = "ERROR_up"
3215
            else:
3216
              if instance.admin_up:
3217
                val = "ERROR_down"
3218
              else:
3219
                val = "ADMIN_down"
3220
        elif field == "oper_ram":
3221
          if instance.primary_node in bad_nodes:
3222
            val = None
3223
          elif instance.name in live_data:
3224
            val = live_data[instance.name].get("memory", "?")
3225
          else:
3226
            val = "-"
3227
        elif field == "disk_template":
3228
          val = instance.disk_template
3229
        elif field == "ip":
3230
          val = instance.nics[0].ip
3231
        elif field == "bridge":
3232
          val = instance.nics[0].bridge
3233
        elif field == "mac":
3234
          val = instance.nics[0].mac
3235
        elif field == "sda_size" or field == "sdb_size":
3236
          idx = ord(field[2]) - ord('a')
3237
          try:
3238
            val = instance.FindDisk(idx).size
3239
          except errors.OpPrereqError:
3240
            val = None
3241
        elif field == "tags":
3242
          val = list(instance.GetTags())
3243
        elif field == "serial_no":
3244
          val = instance.serial_no
3245
        elif field == "network_port":
3246
          val = instance.network_port
3247
        elif field == "hypervisor":
3248
          val = instance.hypervisor
3249
        elif field == "hvparams":
3250
          val = i_hv
3251
        elif (field.startswith(HVPREFIX) and
3252
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS):
3253
          val = i_hv.get(field[len(HVPREFIX):], None)
3254
        elif field == "beparams":
3255
          val = i_be
3256
        elif (field.startswith(BEPREFIX) and
3257
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
3258
          val = i_be.get(field[len(BEPREFIX):], None)
3259
        elif st_match and st_match.groups():
3260
          # matches a variable list
3261
          st_groups = st_match.groups()
3262
          if st_groups and st_groups[0] == "disk":
3263
            if st_groups[1] == "count":
3264
              val = len(instance.disks)
3265
            elif st_groups[1] == "sizes":
3266
              val = [disk.size for disk in instance.disks]
3267
            elif st_groups[1] == "size":
3268
              try:
3269
                val = instance.FindDisk(st_groups[2]).size
3270
              except errors.OpPrereqError:
3271
                val = None
3272
            else:
3273
              assert False, "Unhandled disk parameter"
3274
          elif st_groups[0] == "nic":
3275
            if st_groups[1] == "count":
3276
              val = len(instance.nics)
3277
            elif st_groups[1] == "macs":
3278
              val = [nic.mac for nic in instance.nics]
3279
            elif st_groups[1] == "ips":
3280
              val = [nic.ip for nic in instance.nics]
3281
            elif st_groups[1] == "bridges":
3282
              val = [nic.bridge for nic in instance.nics]
3283
            else:
3284
              # index-based item
3285
              nic_idx = int(st_groups[2])
3286
              if nic_idx >= len(instance.nics):
3287
                val = None
3288
              else:
3289
                if st_groups[1] == "mac":
3290
                  val = instance.nics[nic_idx].mac
3291
                elif st_groups[1] == "ip":
3292
                  val = instance.nics[nic_idx].ip
3293
                elif st_groups[1] == "bridge":
3294
                  val = instance.nics[nic_idx].bridge
3295
                else:
3296
                  assert False, "Unhandled NIC parameter"
3297
          else:
3298
            assert False, "Unhandled variable parameter"
3299
        else:
3300
          raise errors.ParameterError(field)
3301
        iout.append(val)
3302
      output.append(iout)
3303

    
3304
    return output
3305

    
3306

    
3307
class LUFailoverInstance(LogicalUnit):
3308
  """Failover an instance.
3309

3310
  """
3311
  HPATH = "instance-failover"
3312
  HTYPE = constants.HTYPE_INSTANCE
3313
  _OP_REQP = ["instance_name", "ignore_consistency"]
3314
  REQ_BGL = False
3315

    
3316
  def ExpandNames(self):
3317
    self._ExpandAndLockInstance()
3318
    self.needed_locks[locking.LEVEL_NODE] = []
3319
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3320

    
3321
  def DeclareLocks(self, level):
3322
    if level == locking.LEVEL_NODE:
3323
      self._LockInstancesNodes()
3324

    
3325
  def BuildHooksEnv(self):
3326
    """Build hooks env.
3327

3328
    This runs on master, primary and secondary nodes of the instance.
3329

3330
    """
3331
    env = {
3332
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
3333
      }
3334
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3335
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
3336
    return env, nl, nl
3337

    
3338
  def CheckPrereq(self):
3339
    """Check prerequisites.
3340

3341
    This checks that the instance is in the cluster.
3342

3343
    """
3344
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3345
    assert self.instance is not None, \
3346
      "Cannot retrieve locked instance %s" % self.op.instance_name
3347

    
3348
    bep = self.cfg.GetClusterInfo().FillBE(instance)
3349
    if instance.disk_template not in constants.DTS_NET_MIRROR:
3350
      raise errors.OpPrereqError("Instance's disk layout is not"
3351
                                 " network mirrored, cannot failover.")
3352

    
3353
    secondary_nodes = instance.secondary_nodes
3354
    if not secondary_nodes:
3355
      raise errors.ProgrammerError("no secondary node but using "
3356
                                   "a mirrored disk template")
3357

    
3358
    target_node = secondary_nodes[0]
3359
    _CheckNodeOnline(self, target_node)
3360
    # check memory requirements on the secondary node
3361
    _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
3362
                         instance.name, bep[constants.BE_MEMORY],
3363
                         instance.hypervisor)
3364

    
3365
    # check bridge existance
3366
    brlist = [nic.bridge for nic in instance.nics]
3367
    result = self.rpc.call_bridges_exist(target_node, brlist)
3368
    result.Raise()
3369
    if not result.data:
3370
      raise errors.OpPrereqError("One or more target bridges %s does not"
3371
                                 " exist on destination node '%s'" %
3372
                                 (brlist, target_node))
3373

    
3374
  def Exec(self, feedback_fn):
3375
    """Failover an instance.
3376

3377
    The failover is done by shutting it down on its present node and
3378
    starting it on the secondary.
3379

3380
    """
3381
    instance = self.instance
3382

    
3383
    source_node = instance.primary_node
3384
    target_node = instance.secondary_nodes[0]
3385

    
3386
    feedback_fn("* checking disk consistency between source and target")
3387
    for dev in instance.disks:
3388
      # for drbd, these are drbd over lvm
3389
      if not _CheckDiskConsistency(self, dev, target_node, False):
3390
        if instance.admin_up and not self.op.ignore_consistency:
3391
          raise errors.OpExecError("Disk %s is degraded on target node,"
3392
                                   " aborting failover." % dev.iv_name)
3393

    
3394
    feedback_fn("* shutting down instance on source node")
3395
    logging.info("Shutting down instance %s on node %s",
3396
                 instance.name, source_node)
3397

    
3398
    result = self.rpc.call_instance_shutdown(source_node, instance)
3399
    if result.failed or not result.data:
3400
      if self.op.ignore_consistency:
3401
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
3402
                             " Proceeding"
3403
                             " anyway. Please make sure node %s is down",
3404
                             instance.name, source_node, source_node)
3405
      else:
3406
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
3407
                                 (instance.name, source_node))
3408

    
3409
    feedback_fn("* deactivating the instance's disks on source node")
3410
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
3411
      raise errors.OpExecError("Can't shut down the instance's disks.")
3412

    
3413
    instance.primary_node = target_node
3414
    # distribute new instance config to the other nodes
3415
    self.cfg.Update(instance)
3416

    
3417
    # Only start the instance if it's marked as up
3418
    if instance.admin_up:
3419
      feedback_fn("* activating the instance's disks on target node")
3420
      logging.info("Starting instance %s on node %s",
3421
                   instance.name, target_node)
3422

    
3423
      disks_ok, dummy = _AssembleInstanceDisks(self, instance,
3424
                                               ignore_secondaries=True)
3425
      if not disks_ok:
3426
        _ShutdownInstanceDisks(self, instance)
3427
        raise errors.OpExecError("Can't activate the instance's disks")
3428

    
3429
      feedback_fn("* starting the instance on the target node")
3430
      result = self.rpc.call_instance_start(target_node, instance, None)
3431
      msg = result.RemoteFailMsg()
3432
      if msg:
3433
        _ShutdownInstanceDisks(self, instance)
3434
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
3435
                                 (instance.name, target_node, msg))
3436

    
3437

    
3438
class LUMigrateInstance(LogicalUnit):
3439
  """Migrate an instance.
3440

3441
  This is migration without shutting down, compared to the failover,
3442
  which is done with shutdown.
3443

3444
  """
3445
  HPATH = "instance-migrate"
3446
  HTYPE = constants.HTYPE_INSTANCE
3447
  _OP_REQP = ["instance_name", "live", "cleanup"]
3448

    
3449
  REQ_BGL = False
3450

    
3451
  def ExpandNames(self):
3452
    self._ExpandAndLockInstance()
3453
    self.needed_locks[locking.LEVEL_NODE] = []
3454
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3455

    
3456
  def DeclareLocks(self, level):
3457
    if level == locking.LEVEL_NODE:
3458
      self._LockInstancesNodes()
3459

    
3460
  def BuildHooksEnv(self):
3461
    """Build hooks env.
3462

3463
    This runs on master, primary and secondary nodes of the instance.
3464

3465
    """
3466
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3467
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
3468
    return env, nl, nl
3469

    
3470
  def CheckPrereq(self):
3471
    """Check prerequisites.
3472

3473
    This checks that the instance is in the cluster.
3474

3475
    """
3476
    instance = self.cfg.GetInstanceInfo(
3477
      self.cfg.ExpandInstanceName(self.op.instance_name))
3478
    if instance is None:
3479
      raise errors.OpPrereqError("Instance '%s' not known" %
3480
                                 self.op.instance_name)
3481

    
3482
    if instance.disk_template != constants.DT_DRBD8:
3483
      raise errors.OpPrereqError("Instance's disk layout is not"
3484
                                 " drbd8, cannot migrate.")
3485

    
3486
    secondary_nodes = instance.secondary_nodes
3487
    if not secondary_nodes:
3488
      raise errors.ProgrammerError("no secondary node but using "
3489
                                   "drbd8 disk template")
3490

    
3491
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
3492

    
3493
    target_node = secondary_nodes[0]
3494
    # check memory requirements on the secondary node
3495
    _CheckNodeFreeMemory(self, target_node, "migrating instance %s" %
3496
                         instance.name, i_be[constants.BE_MEMORY],
3497
                         instance.hypervisor)
3498

    
3499
    # check bridge existance
3500
    brlist = [nic.bridge for nic in instance.nics]
3501
    result = self.rpc.call_bridges_exist(target_node, brlist)
3502
    if result.failed or not result.data:
3503
      raise errors.OpPrereqError("One or more target bridges %s does not"
3504
                                 " exist on destination node '%s'" %
3505
                                 (brlist, target_node))
3506

    
3507
    if not self.op.cleanup:
3508
      result = self.rpc.call_instance_migratable(instance.primary_node,
3509
                                                 instance)
3510
      msg = result.RemoteFailMsg()
3511
      if msg:
3512
        raise errors.OpPrereqError("Can't migrate: %s - please use failover" %
3513
                                   msg)
3514

    
3515
    self.instance = instance
3516

    
3517
  def _WaitUntilSync(self):
3518
    """Poll with custom rpc for disk sync.
3519

3520
    This uses our own step-based rpc call.
3521

3522
    """
3523
    self.feedback_fn("* wait until resync is done")
3524
    all_done = False
3525
    while not all_done:
3526
      all_done = True
3527
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
3528
                                            self.nodes_ip,
3529
                                            self.instance.disks)
3530
      min_percent = 100
3531
      for node, nres in result.items():
3532
        msg = nres.RemoteFailMsg()
3533
        if msg:
3534
          raise errors.OpExecError("Cannot resync disks on node %s: %s" %
3535
                                   (node, msg))
3536
        node_done, node_percent = nres.payload
3537
        all_done = all_done and node_done
3538
        if node_percent is not None:
3539
          min_percent = min(min_percent, node_percent)
3540
      if not all_done:
3541
        if min_percent < 100:
3542
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
3543
        time.sleep(2)
3544

    
3545
  def _EnsureSecondary(self, node):
3546
    """Demote a node to secondary.
3547

3548
    """
3549
    self.feedback_fn("* switching node %s to secondary mode" % node)
3550

    
3551
    for dev in self.instance.disks:
3552
      self.cfg.SetDiskID(dev, node)
3553

    
3554
    result = self.rpc.call_blockdev_close(node, self.instance.name,
3555
                                          self.instance.disks)
3556
    msg = result.RemoteFailMsg()
3557
    if msg:
3558
      raise errors.OpExecError("Cannot change disk to secondary on node %s,"
3559
                               " error %s" % (node, msg))
3560

    
3561
  def _GoStandalone(self):
3562
    """Disconnect from the network.
3563

3564
    """
3565
    self.feedback_fn("* changing into standalone mode")
3566
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
3567
                                               self.instance.disks)
3568
    for node, nres in result.items():
3569
      msg = nres.RemoteFailMsg()
3570
      if msg:
3571
        raise errors.OpExecError("Cannot disconnect disks node %s,"
3572
                                 " error %s" % (node, msg))
3573

    
3574
  def _GoReconnect(self, multimaster):
3575
    """Reconnect to the network.
3576

3577
    """
3578
    if multimaster:
3579
      msg = "dual-master"
3580
    else:
3581
      msg = "single-master"
3582
    self.feedback_fn("* changing disks into %s mode" % msg)
3583
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
3584
                                           self.instance.disks,
3585
                                           self.instance.name, multimaster)
3586
    for node, nres in result.items():
3587
      msg = nres.RemoteFailMsg()
3588
      if msg:
3589
        raise errors.OpExecError("Cannot change disks config on node %s,"
3590
                                 " error: %s" % (node, msg))
3591

    
3592
  def _ExecCleanup(self):
3593
    """Try to cleanup after a failed migration.
3594

3595
    The cleanup is done by:
3596
      - check that the instance is running only on one node
3597
        (and update the config if needed)
3598
      - change disks on its secondary node to secondary
3599
      - wait until disks are fully synchronized
3600
      - disconnect from the network
3601
      - change disks into single-master mode
3602
      - wait again until disks are fully synchronized
3603

3604
    """
3605
    instance = self.instance
3606
    target_node = self.target_node
3607
    source_node = self.source_node
3608

    
3609
    # check running on only one node
3610
    self.feedback_fn("* checking where the instance actually runs"
3611
                     " (if this hangs, the hypervisor might be in"
3612
                     " a bad state)")
3613
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
3614
    for node, result in ins_l.items():
3615
      result.Raise()
3616
      if not isinstance(result.data, list):
3617
        raise errors.OpExecError("Can't contact node '%s'" % node)
3618

    
3619
    runningon_source = instance.name in ins_l[source_node].data
3620
    runningon_target = instance.name in ins_l[target_node].data
3621

    
3622
    if runningon_source and runningon_target:
3623
      raise errors.OpExecError("Instance seems to be running on two nodes,"
3624
                               " or the hypervisor is confused. You will have"
3625
                               " to ensure manually that it runs only on one"
3626
                               " and restart this operation.")
3627

    
3628
    if not (runningon_source or runningon_target):
3629
      raise errors.OpExecError("Instance does not seem to be running at all."
3630
                               " In this case, it's safer to repair by"
3631
                               " running 'gnt-instance stop' to ensure disk"
3632
                               " shutdown, and then restarting it.")
3633

    
3634
    if runningon_target:
3635
      # the migration has actually succeeded, we need to update the config
3636
      self.feedback_fn("* instance running on secondary node (%s),"
3637
                       " updating config" % target_node)
3638
      instance.primary_node = target_node
3639
      self.cfg.Update(instance)
3640
      demoted_node = source_node
3641
    else:
3642
      self.feedback_fn("* instance confirmed to be running on its"
3643
                       " primary node (%s)" % source_node)
3644
      demoted_node = target_node
3645

    
3646
    self._EnsureSecondary(demoted_node)
3647
    try:
3648
      self._WaitUntilSync()
3649
    except errors.OpExecError:
3650
      # we ignore here errors, since if the device is standalone, it
3651
      # won't be able to sync
3652
      pass
3653
    self._GoStandalone()
3654
    self._GoReconnect(False)
3655
    self._WaitUntilSync()
3656

    
3657
    self.feedback_fn("* done")
3658

    
3659
  def _RevertDiskStatus(self):
3660
    """Try to revert the disk status after a failed migration.
3661

3662
    """
3663
    target_node = self.target_node
3664
    try:
3665
      self._EnsureSecondary(target_node)
3666
      self._GoStandalone()
3667
      self._GoReconnect(False)
3668
      self._WaitUntilSync()
3669
    except errors.OpExecError, err:
3670
      self.LogWarning("Migration failed and I can't reconnect the"
3671
                      " drives: error '%s'\n"
3672
                      "Please look and recover the instance status" %
3673
                      str(err))
3674

    
3675
  def _AbortMigration(self):
3676
    """Call the hypervisor code to abort a started migration.
3677

3678
    """
3679
    instance = self.instance
3680
    target_node = self.target_node
3681
    migration_info = self.migration_info
3682

    
3683
    abort_result = self.rpc.call_finalize_migration(target_node,
3684
                                                    instance,
3685
                                                    migration_info,
3686
                                                    False)
3687
    abort_msg = abort_result.RemoteFailMsg()
3688
    if abort_msg:
3689
      logging.error("Aborting migration failed on target node %s: %s" %
3690
                    (target_node, abort_msg))
3691
      # Don't raise an exception here, as we stil have to try to revert the
3692
      # disk status, even if this step failed.
3693

    
3694
  def _ExecMigration(self):
3695
    """Migrate an instance.
3696

3697
    The migrate is done by:
3698
      - change the disks into dual-master mode
3699
      - wait until disks are fully synchronized again
3700
      - migrate the instance
3701
      - change disks on the new secondary node (the old primary) to secondary
3702
      - wait until disks are fully synchronized
3703
      - change disks into single-master mode
3704

3705
    """
3706
    instance = self.instance
3707
    target_node = self.target_node
3708
    source_node = self.source_node
3709

    
3710
    self.feedback_fn("* checking disk consistency between source and target")
3711
    for dev in instance.disks:
3712
      if not _CheckDiskConsistency(self, dev, target_node, False):
3713
        raise errors.OpExecError("Disk %s is degraded or not fully"
3714
                                 " synchronized on target node,"
3715
                                 " aborting migrate." % dev.iv_name)
3716

    
3717
    # First get the migration information from the remote node
3718
    result = self.rpc.call_migration_info(source_node, instance)
3719
    msg = result.RemoteFailMsg()
3720
    if msg:
3721
      log_err = ("Failed fetching source migration information from %s: %s" %
3722
                 (source_node, msg))
3723
      logging.error(log_err)
3724
      raise errors.OpExecError(log_err)
3725

    
3726
    self.migration_info = migration_info = result.payload
3727

    
3728
    # Then switch the disks to master/master mode
3729
    self._EnsureSecondary(target_node)
3730
    self._GoStandalone()
3731
    self._GoReconnect(True)
3732
    self._WaitUntilSync()
3733

    
3734
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
3735
    result = self.rpc.call_accept_instance(target_node,
3736
                                           instance,
3737
                                           migration_info,
3738
                                           self.nodes_ip[target_node])
3739

    
3740
    msg = result.RemoteFailMsg()
3741
    if msg:
3742
      logging.error("Instance pre-migration failed, trying to revert"
3743
                    " disk status: %s", msg)
3744
      self._AbortMigration()
3745
      self._RevertDiskStatus()
3746
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
3747
                               (instance.name, msg))
3748

    
3749
    self.feedback_fn("* migrating instance to %s" % target_node)
3750
    time.sleep(10)
3751
    result = self.rpc.call_instance_migrate(source_node, instance,
3752
                                            self.nodes_ip[target_node],
3753
                                            self.op.live)
3754
    msg = result.RemoteFailMsg()
3755
    if msg:
3756
      logging.error("Instance migration failed, trying to revert"
3757
                    " disk status: %s", msg)
3758
      self._AbortMigration()
3759
      self._RevertDiskStatus()
3760
      raise errors.OpExecError("Could not migrate instance %s: %s" %
3761
                               (instance.name, msg))
3762
    time.sleep(10)
3763

    
3764
    instance.primary_node = target_node
3765
    # distribute new instance config to the other nodes
3766
    self.cfg.Update(instance)
3767

    
3768
    result = self.rpc.call_finalize_migration(target_node,
3769
                                              instance,
3770
                                              migration_info,
3771
                                              True)
3772
    msg = result.RemoteFailMsg()
3773
    if msg:
3774
      logging.error("Instance migration succeeded, but finalization failed:"
3775
                    " %s" % msg)
3776
      raise errors.OpExecError("Could not finalize instance migration: %s" %
3777
                               msg)
3778

    
3779
    self._EnsureSecondary(source_node)
3780
    self._WaitUntilSync()
3781
    self._GoStandalone()
3782
    self._GoReconnect(False)
3783
    self._WaitUntilSync()
3784

    
3785
    self.feedback_fn("* done")
3786

    
3787
  def Exec(self, feedback_fn):
3788
    """Perform the migration.
3789

3790
    """
3791
    self.feedback_fn = feedback_fn
3792

    
3793
    self.source_node = self.instance.primary_node
3794
    self.target_node = self.instance.secondary_nodes[0]
3795
    self.all_nodes = [self.source_node, self.target_node]
3796
    self.nodes_ip = {
3797
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
3798
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
3799
      }
3800
    if self.op.cleanup:
3801
      return self._ExecCleanup()
3802
    else:
3803
      return self._ExecMigration()
3804

    
3805

    
3806
def _CreateBlockDev(lu, node, instance, device, force_create,
3807
                    info, force_open):
3808
  """Create a tree of block devices on a given node.
3809

3810
  If this device type has to be created on secondaries, create it and
3811
  all its children.
3812

3813
  If not, just recurse to children keeping the same 'force' value.
3814

3815
  @param lu: the lu on whose behalf we execute
3816
  @param node: the node on which to create the device
3817
  @type instance: L{objects.Instance}
3818
  @param instance: the instance which owns the device
3819
  @type device: L{objects.Disk}
3820
  @param device: the device to create
3821
  @type force_create: boolean
3822
  @param force_create: whether to force creation of this device; this
3823
      will be change to True whenever we find a device which has
3824
      CreateOnSecondary() attribute
3825
  @param info: the extra 'metadata' we should attach to the device
3826
      (this will be represented as a LVM tag)
3827
  @type force_open: boolean
3828
  @param force_open: this parameter will be passes to the
3829
      L{backend.CreateBlockDevice} function where it specifies
3830
      whether we run on primary or not, and it affects both
3831
      the child assembly and the device own Open() execution
3832

3833
  """
3834
  if device.CreateOnSecondary():
3835
    force_create = True
3836

    
3837
  if device.children:
3838
    for child in device.children:
3839
      _CreateBlockDev(lu, node, instance, child, force_create,
3840
                      info, force_open)
3841

    
3842
  if not force_create:
3843
    return
3844

    
3845
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
3846

    
3847

    
3848
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
3849
  """Create a single block device on a given node.
3850

3851
  This will not recurse over children of the device, so they must be
3852
  created in advance.
3853

3854
  @param lu: the lu on whose behalf we execute
3855
  @param node: the node on which to create the device
3856
  @type instance: L{objects.Instance}
3857
  @param instance: the instance which owns the device
3858
  @type device: L{objects.Disk}
3859
  @param device: the device to create
3860
  @param info: the extra 'metadata' we should attach to the device
3861
      (this will be represented as a LVM tag)
3862
  @type force_open: boolean
3863
  @param force_open: this parameter will be passes to the
3864
      L{backend.CreateBlockDevice} function where it specifies
3865
      whether we run on primary or not, and it affects both
3866
      the child assembly and the device own Open() execution
3867

3868
  """
3869
  lu.cfg.SetDiskID(device, node)
3870
  result = lu.rpc.call_blockdev_create(node, device, device.size,
3871
                                       instance.name, force_open, info)
3872
  msg = result.RemoteFailMsg()
3873
  if msg:
3874
    raise errors.OpExecError("Can't create block device %s on"
3875
                             " node %s for instance %s: %s" %
3876
                             (device, node, instance.name, msg))
3877
  if device.physical_id is None:
3878
    device.physical_id = result.payload
3879

    
3880

    
3881
def _GenerateUniqueNames(lu, exts):
3882
  """Generate a suitable LV name.
3883

3884
  This will generate a logical volume name for the given instance.
3885

3886
  """
3887
  results = []
3888
  for val in exts:
3889
    new_id = lu.cfg.GenerateUniqueID()
3890
    results.append("%s%s" % (new_id, val))
3891
  return results
3892

    
3893

    
3894
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
3895
                         p_minor, s_minor):
3896
  """Generate a drbd8 device complete with its children.
3897

3898
  """
3899
  port = lu.cfg.AllocatePort()
3900
  vgname = lu.cfg.GetVGName()
3901
  shared_secret = lu.cfg.GenerateDRBDSecret()
3902
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
3903
                          logical_id=(vgname, names[0]))
3904
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
3905
                          logical_id=(vgname, names[1]))
3906
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
3907
                          logical_id=(primary, secondary, port,
3908
                                      p_minor, s_minor,
3909
                                      shared_secret),
3910
                          children=[dev_data, dev_meta],
3911
                          iv_name=iv_name)
3912
  return drbd_dev
3913

    
3914

    
3915
def _GenerateDiskTemplate(lu, template_name,
3916
                          instance_name, primary_node,
3917
                          secondary_nodes, disk_info,
3918
                          file_storage_dir, file_driver,
3919
                          base_index):
3920
  """Generate the entire disk layout for a given template type.
3921

3922
  """
3923
  #TODO: compute space requirements
3924

    
3925
  vgname = lu.cfg.GetVGName()
3926
  disk_count = len(disk_info)
3927
  disks = []
3928
  if template_name == constants.DT_DISKLESS:
3929
    pass
3930
  elif template_name == constants.DT_PLAIN:
3931
    if len(secondary_nodes) != 0:
3932
      raise errors.ProgrammerError("Wrong template configuration")
3933

    
3934
    names = _GenerateUniqueNames(lu, [".disk%d" % i
3935
                                      for i in range(disk_count)])
3936
    for idx, disk in enumerate(disk_info):
3937
      disk_index = idx + base_index
3938
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
3939
                              logical_id=(vgname, names[idx]),
3940
                              iv_name="disk/%d" % disk_index,
3941
                              mode=disk["mode"])
3942
      disks.append(disk_dev)
3943
  elif template_name == constants.DT_DRBD8:
3944
    if len(secondary_nodes) != 1:
3945
      raise errors.ProgrammerError("Wrong template configuration")
3946
    remote_node = secondary_nodes[0]
3947
    minors = lu.cfg.AllocateDRBDMinor(
3948
      [primary_node, remote_node] * len(disk_info), instance_name)
3949

    
3950
    names = []
3951
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % i
3952
                                               for i in range(disk_count)]):
3953
      names.append(lv_prefix + "_data")
3954
      names.append(lv_prefix + "_meta")
3955
    for idx, disk in enumerate(disk_info):
3956
      disk_index = idx + base_index
3957
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
3958
                                      disk["size"], names[idx*2:idx*2+2],
3959
                                      "disk/%d" % disk_index,
3960
                                      minors[idx*2], minors[idx*2+1])
3961
      disk_dev.mode = disk["mode"]
3962
      disks.append(disk_dev)
3963
  elif template_name == constants.DT_FILE:
3964
    if len(secondary_nodes) != 0:
3965
      raise errors.ProgrammerError("Wrong template configuration")
3966

    
3967
    for idx, disk in enumerate(disk_info):
3968
      disk_index = idx + base_index
3969
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
3970
                              iv_name="disk/%d" % disk_index,
3971
                              logical_id=(file_driver,
3972
                                          "%s/disk%d" % (file_storage_dir,
3973
                                                         idx)),
3974
                              mode=disk["mode"])
3975
      disks.append(disk_dev)
3976
  else:
3977
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
3978
  return disks
3979

    
3980

    
3981
def _GetInstanceInfoText(instance):
3982
  """Compute that text that should be added to the disk's metadata.
3983

3984
  """
3985
  return "originstname+%s" % instance.name
3986

    
3987

    
3988
def _CreateDisks(lu, instance):
3989
  """Create all disks for an instance.
3990

3991
  This abstracts away some work from AddInstance.
3992

3993
  @type lu: L{LogicalUnit}
3994
  @param lu: the logical unit on whose behalf we execute
3995
  @type instance: L{objects.Instance}
3996
  @param instance: the instance whose disks we should create
3997
  @rtype: boolean
3998
  @return: the success of the creation
3999

4000
  """
4001
  info = _GetInstanceInfoText(instance)
4002
  pnode = instance.primary_node
4003

    
4004
  if instance.disk_template == constants.DT_FILE:
4005
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
4006
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
4007

    
4008
    if result.failed or not result.data:
4009
      raise errors.OpExecError("Could not connect to node '%s'" % pnode)
4010

    
4011
    if not result.data[0]:
4012
      raise errors.OpExecError("Failed to create directory '%s'" %
4013
                               file_storage_dir)
4014

    
4015
  # Note: this needs to be kept in sync with adding of disks in
4016
  # LUSetInstanceParams
4017
  for device in instance.disks:
4018
    logging.info("Creating volume %s for instance %s",
4019
                 device.iv_name, instance.name)
4020
    #HARDCODE
4021
    for node in instance.all_nodes:
4022
      f_create = node == pnode
4023
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
4024

    
4025

    
4026
def _RemoveDisks(lu, instance):
4027
  """Remove all disks for an instance.
4028

4029
  This abstracts away some work from `AddInstance()` and
4030
  `RemoveInstance()`. Note that in case some of the devices couldn't
4031
  be removed, the removal will continue with the other ones (compare
4032
  with `_CreateDisks()`).
4033

4034
  @type lu: L{LogicalUnit}
4035
  @param lu: the logical unit on whose behalf we execute
4036
  @type instance: L{objects.Instance}
4037
  @param instance: the instance whose disks we should remove
4038
  @rtype: boolean
4039
  @return: the success of the removal
4040

4041
  """
4042
  logging.info("Removing block devices for instance %s", instance.name)
4043

    
4044
  result = True
4045
  for device in instance.disks:
4046
    for node, disk in device.ComputeNodeTree(instance.primary_node):
4047
      lu.cfg.SetDiskID(disk, node)
4048
      result = lu.rpc.call_blockdev_remove(node, disk)
4049
      if result.failed or not result.data:
4050
        lu.proc.LogWarning("Could not remove block device %s on node %s,"
4051
                           " continuing anyway", device.iv_name, node)
4052
        result = False
4053

    
4054
  if instance.disk_template == constants.DT_FILE:
4055
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
4056
    result = lu.rpc.call_file_storage_dir_remove(instance.primary_node,
4057
                                                 file_storage_dir)
4058
    if result.failed or not result.data:
4059
      logging.error("Could not remove directory '%s'", file_storage_dir)
4060
      result = False
4061

    
4062
  return result
4063

    
4064

    
4065
def _ComputeDiskSize(disk_template, disks):
4066
  """Compute disk size requirements in the volume group
4067

4068
  """
4069
  # Required free disk space as a function of disk and swap space
4070
  req_size_dict = {
4071
    constants.DT_DISKLESS: None,
4072
    constants.DT_PLAIN: sum(d["size"] for d in disks),
4073
    # 128 MB are added for drbd metadata for each disk
4074
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
4075
    constants.DT_FILE: None,
4076
  }
4077

    
4078
  if disk_template not in req_size_dict:
4079
    raise errors.ProgrammerError("Disk template '%s' size requirement"
4080
                                 " is unknown" %  disk_template)
4081

    
4082
  return req_size_dict[disk_template]
4083

    
4084

    
4085
def _CheckHVParams(lu, nodenames, hvname, hvparams):
4086
  """Hypervisor parameter validation.
4087

4088
  This function abstract the hypervisor parameter validation to be
4089
  used in both instance create and instance modify.
4090

4091
  @type lu: L{LogicalUnit}
4092
  @param lu: the logical unit for which we check
4093
  @type nodenames: list
4094
  @param nodenames: the list of nodes on which we should check
4095
  @type hvname: string
4096
  @param hvname: the name of the hypervisor we should use
4097
  @type hvparams: dict
4098
  @param hvparams: the parameters which we need to check
4099
  @raise errors.OpPrereqError: if the parameters are not valid
4100

4101
  """
4102
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
4103
                                                  hvname,
4104
                                                  hvparams)
4105
  for node in nodenames:
4106
    info = hvinfo[node]
4107
    if info.offline:
4108
      continue
4109
    msg = info.RemoteFailMsg()
4110
    if msg:
4111
      raise errors.OpPrereqError("Hypervisor parameter validation failed:"
4112
                                 " %s" % msg)
4113

    
4114

    
4115
class LUCreateInstance(LogicalUnit):
4116
  """Create an instance.
4117

4118
  """
4119
  HPATH = "instance-add"
4120
  HTYPE = constants.HTYPE_INSTANCE
4121
  _OP_REQP = ["instance_name", "disks", "disk_template",
4122
              "mode", "start",
4123
              "wait_for_sync", "ip_check", "nics",
4124
              "hvparams", "beparams"]
4125
  REQ_BGL = False
4126

    
4127
  def _ExpandNode(self, node):
4128
    """Expands and checks one node name.
4129

4130
    """
4131
    node_full = self.cfg.ExpandNodeName(node)
4132
    if node_full is None:
4133
      raise errors.OpPrereqError("Unknown node %s" % node)
4134
    return node_full
4135

    
4136
  def ExpandNames(self):
4137
    """ExpandNames for CreateInstance.
4138

4139
    Figure out the right locks for instance creation.
4140

4141
    """
4142
    self.needed_locks = {}
4143

    
4144
    # set optional parameters to none if they don't exist
4145
    for attr in ["pnode", "snode", "iallocator", "hypervisor"]:
4146
      if not hasattr(self.op, attr):
4147
        setattr(self.op, attr, None)
4148

    
4149
    # cheap checks, mostly valid constants given
4150

    
4151
    # verify creation mode
4152
    if self.op.mode not in (constants.INSTANCE_CREATE,
4153
                            constants.INSTANCE_IMPORT):
4154
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
4155
                                 self.op.mode)
4156

    
4157
    # disk template and mirror node verification
4158
    if self.op.disk_template not in constants.DISK_TEMPLATES:
4159
      raise errors.OpPrereqError("Invalid disk template name")
4160

    
4161
    if self.op.hypervisor is None:
4162
      self.op.hypervisor = self.cfg.GetHypervisorType()
4163

    
4164
    cluster = self.cfg.GetClusterInfo()
4165
    enabled_hvs = cluster.enabled_hypervisors
4166
    if self.op.hypervisor not in enabled_hvs:
4167
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
4168
                                 " cluster (%s)" % (self.op.hypervisor,
4169
                                  ",".join(enabled_hvs)))
4170

    
4171
    # check hypervisor parameter syntax (locally)
4172

    
4173
    filled_hvp = cluster.FillDict(cluster.hvparams[self.op.hypervisor],
4174
                                  self.op.hvparams)
4175
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
4176
    hv_type.CheckParameterSyntax(filled_hvp)
4177

    
4178
    # fill and remember the beparams dict
4179
    utils.CheckBEParams(self.op.beparams)
4180
    self.be_full = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
4181
                                    self.op.beparams)
4182

    
4183
    #### instance parameters check
4184

    
4185
    # instance name verification
4186
    hostname1 = utils.HostInfo(self.op.instance_name)
4187
    self.op.instance_name = instance_name = hostname1.name
4188

    
4189
    # this is just a preventive check, but someone might still add this
4190
    # instance in the meantime, and creation will fail at lock-add time
4191
    if instance_name in self.cfg.GetInstanceList():
4192
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4193
                                 instance_name)
4194

    
4195
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
4196

    
4197
    # NIC buildup
4198
    self.nics = []
4199
    for nic in self.op.nics:
4200
      # ip validity checks
4201
      ip = nic.get("ip", None)
4202
      if ip is None or ip.lower() == "none":
4203
        nic_ip = None
4204
      elif ip.lower() == constants.VALUE_AUTO:
4205
        nic_ip = hostname1.ip
4206
      else:
4207
        if not utils.IsValidIP(ip):
4208
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
4209
                                     " like a valid IP" % ip)
4210
        nic_ip = ip
4211

    
4212
      # MAC address verification
4213
      mac = nic.get("mac", constants.VALUE_AUTO)
4214
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
4215
        if not utils.IsValidMac(mac.lower()):
4216
          raise errors.OpPrereqError("Invalid MAC address specified: %s" %
4217
                                     mac)
4218
      # bridge verification
4219
      bridge = nic.get("bridge", None)
4220
      if bridge is None:
4221
        bridge = self.cfg.GetDefBridge()
4222
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, bridge=bridge))
4223

    
4224
    # disk checks/pre-build
4225
    self.disks = []
4226
    for disk in self.op.disks:
4227
      mode = disk.get("mode", constants.DISK_RDWR)
4228
      if mode not in constants.DISK_ACCESS_SET:
4229
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
4230
                                   mode)
4231
      size = disk.get("size", None)
4232
      if size is None:
4233
        raise errors.OpPrereqError("Missing disk size")
4234
      try:
4235
        size = int(size)
4236
      except ValueError:
4237
        raise errors.OpPrereqError("Invalid disk size '%s'" % size)
4238
      self.disks.append({"size": size, "mode": mode})
4239

    
4240
    # used in CheckPrereq for ip ping check
4241
    self.check_ip = hostname1.ip
4242

    
4243
    # file storage checks
4244
    if (self.op.file_driver and
4245
        not self.op.file_driver in constants.FILE_DRIVER):
4246
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
4247
                                 self.op.file_driver)
4248

    
4249
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
4250
      raise errors.OpPrereqError("File storage directory path not absolute")
4251

    
4252
    ### Node/iallocator related checks
4253
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
4254
      raise errors.OpPrereqError("One and only one of iallocator and primary"
4255
                                 " node must be given")
4256

    
4257
    if self.op.iallocator:
4258
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4259
    else:
4260
      self.op.pnode = self._ExpandNode(self.op.pnode)
4261
      nodelist = [self.op.pnode]
4262
      if self.op.snode is not None:
4263
        self.op.snode = self._ExpandNode(self.op.snode)
4264
        nodelist.append(self.op.snode)
4265
      self.needed_locks[locking.LEVEL_NODE] = nodelist
4266

    
4267
    # in case of import lock the source node too
4268
    if self.op.mode == constants.INSTANCE_IMPORT:
4269
      src_node = getattr(self.op, "src_node", None)
4270
      src_path = getattr(self.op, "src_path", None)
4271

    
4272
      if src_path is None:
4273
        self.op.src_path = src_path = self.op.instance_name
4274

    
4275
      if src_node is None:
4276
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4277
        self.op.src_node = None
4278
        if os.path.isabs(src_path):
4279
          raise errors.OpPrereqError("Importing an instance from an absolute"
4280
                                     " path requires a source node option.")
4281
      else:
4282
        self.op.src_node = src_node = self._ExpandNode(src_node)
4283
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4284
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
4285
        if not os.path.isabs(src_path):
4286
          self.op.src_path = src_path = \
4287
            os.path.join(constants.EXPORT_DIR, src_path)
4288

    
4289
    else: # INSTANCE_CREATE
4290
      if getattr(self.op, "os_type", None) is None:
4291
        raise errors.OpPrereqError("No guest OS specified")
4292

    
4293
  def _RunAllocator(self):
4294
    """Run the allocator based on input opcode.
4295

4296
    """
4297
    nics = [n.ToDict() for n in self.nics]
4298
    ial = IAllocator(self,
4299
                     mode=constants.IALLOCATOR_MODE_ALLOC,
4300
                     name=self.op.instance_name,
4301
                     disk_template=self.op.disk_template,
4302
                     tags=[],
4303
                     os=self.op.os_type,
4304
                     vcpus=self.be_full[constants.BE_VCPUS],
4305
                     mem_size=self.be_full[constants.BE_MEMORY],
4306
                     disks=self.disks,
4307
                     nics=nics,
4308
                     hypervisor=self.op.hypervisor,
4309
                     )
4310

    
4311
    ial.Run(self.op.iallocator)
4312

    
4313
    if not ial.success:
4314
      raise errors.OpPrereqError("Can't compute nodes using"
4315
                                 " iallocator '%s': %s" % (self.op.iallocator,
4316
                                                           ial.info))
4317
    if len(ial.nodes) != ial.required_nodes:
4318
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
4319
                                 " of nodes (%s), required %s" %
4320
                                 (self.op.iallocator, len(ial.nodes),
4321
                                  ial.required_nodes))
4322
    self.op.pnode = ial.nodes[0]
4323
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
4324
                 self.op.instance_name, self.op.iallocator,
4325
                 ", ".join(ial.nodes))
4326
    if ial.required_nodes == 2:
4327
      self.op.snode = ial.nodes[1]
4328

    
4329
  def BuildHooksEnv(self):
4330
    """Build hooks env.
4331

4332
    This runs on master, primary and secondary nodes of the instance.
4333

4334
    """
4335
    env = {
4336
      "INSTANCE_DISK_TEMPLATE": self.op.disk_template,
4337
      "INSTANCE_DISK_SIZE": ",".join(str(d["size"]) for d in self.disks),
4338
      "INSTANCE_ADD_MODE": self.op.mode,
4339
      }
4340
    if self.op.mode == constants.INSTANCE_IMPORT:
4341
      env["INSTANCE_SRC_NODE"] = self.op.src_node
4342
      env["INSTANCE_SRC_PATH"] = self.op.src_path
4343
      env["INSTANCE_SRC_IMAGES"] = self.src_images
4344

    
4345
    env.update(_BuildInstanceHookEnv(name=self.op.instance_name,
4346
      primary_node=self.op.pnode,
4347
      secondary_nodes=self.secondaries,
4348
      status=self.op.start,
4349
      os_type=self.op.os_type,
4350
      memory=self.be_full[constants.BE_MEMORY],
4351
      vcpus=self.be_full[constants.BE_VCPUS],
4352
      nics=[(n.ip, n.bridge, n.mac) for n in self.nics],
4353
    ))
4354

    
4355
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
4356
          self.secondaries)
4357
    return env, nl, nl
4358

    
4359

    
4360
  def CheckPrereq(self):
4361
    """Check prerequisites.
4362

4363
    """
4364
    if (not self.cfg.GetVGName() and
4365
        self.op.disk_template not in constants.DTS_NOT_LVM):
4366
      raise errors.OpPrereqError("Cluster does not support lvm-based"
4367
                                 " instances")
4368

    
4369

    
4370
    if self.op.mode == constants.INSTANCE_IMPORT:
4371
      src_node = self.op.src_node
4372
      src_path = self.op.src_path
4373

    
4374
      if src_node is None:
4375
        exp_list = self.rpc.call_export_list(
4376
          self.acquired_locks[locking.LEVEL_NODE])
4377
        found = False
4378
        for node in exp_list:
4379
          if not exp_list[node].failed and src_path in exp_list[node].data:
4380
            found = True
4381
            self.op.src_node = src_node = node
4382
            self.op.src_path = src_path = os.path.join(constants.EXPORT_DIR,
4383
                                                       src_path)
4384
            break
4385
        if not found:
4386
          raise errors.OpPrereqError("No export found for relative path %s" %
4387
                                      src_path)
4388

    
4389
      _CheckNodeOnline(self, src_node)
4390
      result = self.rpc.call_export_info(src_node, src_path)
4391
      result.Raise()
4392
      if not result.data:
4393
        raise errors.OpPrereqError("No export found in dir %s" % src_path)
4394

    
4395
      export_info = result.data
4396
      if not export_info.has_section(constants.INISECT_EXP):
4397
        raise errors.ProgrammerError("Corrupted export config")
4398

    
4399
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
4400
      if (int(ei_version) != constants.EXPORT_VERSION):
4401
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
4402
                                   (ei_version, constants.EXPORT_VERSION))
4403

    
4404
      # Check that the new instance doesn't have less disks than the export
4405
      instance_disks = len(self.disks)
4406
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
4407
      if instance_disks < export_disks:
4408
        raise errors.OpPrereqError("Not enough disks to import."
4409
                                   " (instance: %d, export: %d)" %
4410
                                   (instance_disks, export_disks))
4411

    
4412
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
4413
      disk_images = []
4414
      for idx in range(export_disks):
4415
        option = 'disk%d_dump' % idx
4416
        if export_info.has_option(constants.INISECT_INS, option):
4417
          # FIXME: are the old os-es, disk sizes, etc. useful?
4418
          export_name = export_info.get(constants.INISECT_INS, option)
4419
          image = os.path.join(src_path, export_name)
4420
          disk_images.append(image)
4421
        else:
4422
          disk_images.append(False)
4423

    
4424
      self.src_images = disk_images
4425

    
4426
      old_name = export_info.get(constants.INISECT_INS, 'name')
4427
      # FIXME: int() here could throw a ValueError on broken exports
4428
      exp_nic_count = int(export_info.get(constants.INISECT_INS, 'nic_count'))
4429
      if self.op.instance_name == old_name:
4430
        for idx, nic in enumerate(self.nics):
4431
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
4432
            nic_mac_ini = 'nic%d_mac' % idx
4433
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
4434

    
4435
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
4436
    if self.op.start and not self.op.ip_check:
4437
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
4438
                                 " adding an instance in start mode")
4439

    
4440
    if self.op.ip_check:
4441
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
4442
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4443
                                   (self.check_ip, self.op.instance_name))
4444

    
4445
    #### allocator run
4446

    
4447
    if self.op.iallocator is not None:
4448
      self._RunAllocator()
4449

    
4450
    #### node related checks
4451

    
4452
    # check primary node
4453
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
4454
    assert self.pnode is not None, \
4455
      "Cannot retrieve locked node %s" % self.op.pnode
4456
    if pnode.offline:
4457
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
4458
                                 pnode.name)
4459

    
4460
    self.secondaries = []
4461

    
4462
    # mirror node verification
4463
    if self.op.disk_template in constants.DTS_NET_MIRROR:
4464
      if self.op.snode is None:
4465
        raise errors.OpPrereqError("The networked disk templates need"
4466
                                   " a mirror node")
4467
      if self.op.snode == pnode.name:
4468
        raise errors.OpPrereqError("The secondary node cannot be"
4469
                                   " the primary node.")
4470
      self.secondaries.append(self.op.snode)
4471
      _CheckNodeOnline(self, self.op.snode)
4472

    
4473
    nodenames = [pnode.name] + self.secondaries
4474

    
4475
    req_size = _ComputeDiskSize(self.op.disk_template,
4476
                                self.disks)
4477

    
4478
    # Check lv size requirements
4479
    if req_size is not None:
4480
      nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
4481
                                         self.op.hypervisor)
4482
      for node in nodenames:
4483
        info = nodeinfo[node]
4484
        info.Raise()
4485
        info = info.data
4486
        if not info:
4487
          raise errors.OpPrereqError("Cannot get current information"
4488
                                     " from node '%s'" % node)
4489
        vg_free = info.get('vg_free', None)
4490
        if not isinstance(vg_free, int):
4491
          raise errors.OpPrereqError("Can't compute free disk space on"
4492
                                     " node %s" % node)
4493
        if req_size > info['vg_free']:
4494
          raise errors.OpPrereqError("Not enough disk space on target node %s."
4495
                                     " %d MB available, %d MB required" %
4496
                                     (node, info['vg_free'], req_size))
4497

    
4498
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
4499

    
4500
    # os verification
4501
    result = self.rpc.call_os_get(pnode.name, self.op.os_type)
4502
    result.Raise()
4503
    if not isinstance(result.data, objects.OS):
4504
      raise errors.OpPrereqError("OS '%s' not in supported os list for"
4505
                                 " primary node"  % self.op.os_type)
4506

    
4507
    # bridge check on primary node
4508
    bridges = [n.bridge for n in self.nics]
4509
    result = self.rpc.call_bridges_exist(self.pnode.name, bridges)
4510
    result.Raise()
4511
    if not result.data:
4512
      raise errors.OpPrereqError("One of the target bridges '%s' does not"
4513
                                 " exist on destination node '%s'" %
4514
                                 (",".join(bridges), pnode.name))
4515

    
4516
    # memory check on primary node
4517
    if self.op.start:
4518
      _CheckNodeFreeMemory(self, self.pnode.name,
4519
                           "creating instance %s" % self.op.instance_name,
4520
                           self.be_full[constants.BE_MEMORY],
4521
                           self.op.hypervisor)
4522

    
4523
  def Exec(self, feedback_fn):
4524
    """Create and add the instance to the cluster.
4525

4526
    """
4527
    instance = self.op.instance_name
4528
    pnode_name = self.pnode.name
4529

    
4530
    for nic in self.nics:
4531
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
4532
        nic.mac = self.cfg.GenerateMAC()
4533

    
4534
    ht_kind = self.op.hypervisor
4535
    if ht_kind in constants.HTS_REQ_PORT:
4536
      network_port = self.cfg.AllocatePort()
4537
    else:
4538
      network_port = None
4539

    
4540
    ##if self.op.vnc_bind_address is None:
4541
    ##  self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
4542

    
4543
    # this is needed because os.path.join does not accept None arguments
4544
    if self.op.file_storage_dir is None:
4545
      string_file_storage_dir = ""
4546
    else:
4547
      string_file_storage_dir = self.op.file_storage_dir
4548

    
4549
    # build the full file storage dir path
4550
    file_storage_dir = os.path.normpath(os.path.join(
4551
                                        self.cfg.GetFileStorageDir(),
4552
                                        string_file_storage_dir, instance))
4553

    
4554

    
4555
    disks = _GenerateDiskTemplate(self,
4556
                                  self.op.disk_template,
4557
                                  instance, pnode_name,
4558
                                  self.secondaries,
4559
                                  self.disks,
4560
                                  file_storage_dir,
4561
                                  self.op.file_driver,
4562
                                  0)
4563

    
4564
    iobj = objects.Instance(name=instance, os=self.op.os_type,
4565
                            primary_node=pnode_name,
4566
                            nics=self.nics, disks=disks,
4567
                            disk_template=self.op.disk_template,
4568
                            admin_up=False,
4569
                            network_port=network_port,
4570
                            beparams=self.op.beparams,
4571
                            hvparams=self.op.hvparams,
4572
                            hypervisor=self.op.hypervisor,
4573
                            )
4574

    
4575
    feedback_fn("* creating instance disks...")
4576
    try:
4577
      _CreateDisks(self, iobj)
4578
    except errors.OpExecError:
4579
      self.LogWarning("Device creation failed, reverting...")
4580
      try:
4581
        _RemoveDisks(self, iobj)
4582
      finally:
4583
        self.cfg.ReleaseDRBDMinors(instance)
4584
        raise
4585

    
4586
    feedback_fn("adding instance %s to cluster config" % instance)
4587

    
4588
    self.cfg.AddInstance(iobj)
4589
    # Declare that we don't want to remove the instance lock anymore, as we've
4590
    # added the instance to the config
4591
    del self.remove_locks[locking.LEVEL_INSTANCE]
4592
    # Unlock all the nodes
4593
    if self.op.mode == constants.INSTANCE_IMPORT:
4594
      nodes_keep = [self.op.src_node]
4595
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
4596
                       if node != self.op.src_node]
4597
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
4598
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
4599
    else:
4600
      self.context.glm.release(locking.LEVEL_NODE)
4601
      del self.acquired_locks[locking.LEVEL_NODE]
4602

    
4603
    if self.op.wait_for_sync:
4604
      disk_abort = not _WaitForSync(self, iobj)
4605
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
4606
      # make sure the disks are not degraded (still sync-ing is ok)
4607
      time.sleep(15)
4608
      feedback_fn("* checking mirrors status")
4609
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
4610
    else:
4611
      disk_abort = False
4612

    
4613
    if disk_abort:
4614
      _RemoveDisks(self, iobj)
4615
      self.cfg.RemoveInstance(iobj.name)
4616
      # Make sure the instance lock gets removed
4617
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
4618
      raise errors.OpExecError("There are some degraded disks for"
4619
                               " this instance")
4620

    
4621
    feedback_fn("creating os for instance %s on node %s" %
4622
                (instance, pnode_name))
4623

    
4624
    if iobj.disk_template != constants.DT_DISKLESS:
4625
      if self.op.mode == constants.INSTANCE_CREATE:
4626
        feedback_fn("* running the instance OS create scripts...")
4627
        result = self.rpc.call_instance_os_add(pnode_name, iobj)
4628
        msg = result.RemoteFailMsg()
4629
        if msg:
4630
          raise errors.OpExecError("Could not add os for instance %s"
4631
                                   " on node %s: %s" %
4632
                                   (instance, pnode_name, msg))
4633

    
4634
      elif self.op.mode == constants.INSTANCE_IMPORT:
4635
        feedback_fn("* running the instance OS import scripts...")
4636
        src_node = self.op.src_node
4637
        src_images = self.src_images
4638
        cluster_name = self.cfg.GetClusterName()
4639
        import_result = self.rpc.call_instance_os_import(pnode_name, iobj,
4640
                                                         src_node, src_images,
4641
                                                         cluster_name)
4642
        import_result.Raise()
4643
        for idx, result in enumerate(import_result.data):
4644
          if not result:
4645
            self.LogWarning("Could not import the image %s for instance"
4646
                            " %s, disk %d, on node %s" %
4647
                            (src_images[idx], instance, idx, pnode_name))
4648
      else:
4649
        # also checked in the prereq part
4650
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
4651
                                     % self.op.mode)
4652

    
4653
    if self.op.start:
4654
      iobj.admin_up = True
4655
      self.cfg.Update(iobj)
4656
      logging.info("Starting instance %s on node %s", instance, pnode_name)
4657
      feedback_fn("* starting instance...")
4658
      result = self.rpc.call_instance_start(pnode_name, iobj, None)
4659
      msg = result.RemoteFailMsg()
4660
      if msg:
4661
        raise errors.OpExecError("Could not start instance: %s" % msg)
4662

    
4663

    
4664
class LUConnectConsole(NoHooksLU):
4665
  """Connect to an instance's console.
4666

4667
  This is somewhat special in that it returns the command line that
4668
  you need to run on the master node in order to connect to the
4669
  console.
4670

4671
  """
4672
  _OP_REQP = ["instance_name"]
4673
  REQ_BGL = False
4674

    
4675
  def ExpandNames(self):
4676
    self._ExpandAndLockInstance()
4677

    
4678
  def CheckPrereq(self):
4679
    """Check prerequisites.
4680

4681
    This checks that the instance is in the cluster.
4682

4683
    """
4684
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4685
    assert self.instance is not None, \
4686
      "Cannot retrieve locked instance %s" % self.op.instance_name
4687
    _CheckNodeOnline(self, self.instance.primary_node)
4688

    
4689
  def Exec(self, feedback_fn):
4690
    """Connect to the console of an instance
4691

4692
    """
4693
    instance = self.instance
4694
    node = instance.primary_node
4695

    
4696
    node_insts = self.rpc.call_instance_list([node],
4697
                                             [instance.hypervisor])[node]
4698
    node_insts.Raise()
4699

    
4700
    if instance.name not in node_insts.data:
4701
      raise errors.OpExecError("Instance %s is not running." % instance.name)
4702

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

    
4705
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
4706
    cluster = self.cfg.GetClusterInfo()
4707
    # beparams and hvparams are passed separately, to avoid editing the
4708
    # instance and then saving the defaults in the instance itself.
4709
    hvparams = cluster.FillHV(instance)
4710
    beparams = cluster.FillBE(instance)
4711
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
4712

    
4713
    # build ssh cmdline
4714
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
4715

    
4716

    
4717
class LUReplaceDisks(LogicalUnit):
4718
  """Replace the disks of an instance.
4719

4720
  """
4721
  HPATH = "mirrors-replace"
4722
  HTYPE = constants.HTYPE_INSTANCE
4723
  _OP_REQP = ["instance_name", "mode", "disks"]
4724
  REQ_BGL = False
4725

    
4726
  def CheckArguments(self):
4727
    if not hasattr(self.op, "remote_node"):
4728
      self.op.remote_node = None
4729
    if not hasattr(self.op, "iallocator"):
4730
      self.op.iallocator = None
4731

    
4732
    # check for valid parameter combination
4733
    cnt = [self.op.remote_node, self.op.iallocator].count(None)
4734
    if self.op.mode == constants.REPLACE_DISK_CHG:
4735
      if cnt == 2:
4736
        raise errors.OpPrereqError("When changing the secondary either an"
4737
                                   " iallocator script must be used or the"
4738
                                   " new node given")
4739
      elif cnt == 0:
4740
        raise errors.OpPrereqError("Give either the iallocator or the new"
4741
                                   " secondary, not both")
4742
    else: # not replacing the secondary
4743
      if cnt != 2:
4744
        raise errors.OpPrereqError("The iallocator and new node options can"
4745
                                   " be used only when changing the"
4746
                                   " secondary node")
4747

    
4748
  def ExpandNames(self):
4749
    self._ExpandAndLockInstance()
4750

    
4751
    if self.op.iallocator is not None:
4752
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4753
    elif self.op.remote_node is not None:
4754
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
4755
      if remote_node is None:
4756
        raise errors.OpPrereqError("Node '%s' not known" %
4757
                                   self.op.remote_node)
4758
      self.op.remote_node = remote_node
4759
      # Warning: do not remove the locking of the new secondary here
4760
      # unless DRBD8.AddChildren is changed to work in parallel;
4761
      # currently it doesn't since parallel invocations of
4762
      # FindUnusedMinor will conflict
4763
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
4764
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4765
    else:
4766
      self.needed_locks[locking.LEVEL_NODE] = []
4767
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4768

    
4769
  def DeclareLocks(self, level):
4770
    # If we're not already locking all nodes in the set we have to declare the
4771
    # instance's primary/secondary nodes.
4772
    if (level == locking.LEVEL_NODE and
4773
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
4774
      self._LockInstancesNodes()
4775

    
4776
  def _RunAllocator(self):
4777
    """Compute a new secondary node using an IAllocator.
4778

4779
    """
4780
    ial = IAllocator(self,
4781
                     mode=constants.IALLOCATOR_MODE_RELOC,
4782
                     name=self.op.instance_name,
4783
                     relocate_from=[self.sec_node])
4784

    
4785
    ial.Run(self.op.iallocator)
4786

    
4787
    if not ial.success:
4788
      raise errors.OpPrereqError("Can't compute nodes using"
4789
                                 " iallocator '%s': %s" % (self.op.iallocator,
4790
                                                           ial.info))
4791
    if len(ial.nodes) != ial.required_nodes:
4792
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
4793
                                 " of nodes (%s), required %s" %
4794
                                 (len(ial.nodes), ial.required_nodes))
4795
    self.op.remote_node = ial.nodes[0]
4796
    self.LogInfo("Selected new secondary for the instance: %s",
4797
                 self.op.remote_node)
4798

    
4799
  def BuildHooksEnv(self):
4800
    """Build hooks env.
4801

4802
    This runs on the master, the primary and all the secondaries.
4803

4804
    """
4805
    env = {
4806
      "MODE": self.op.mode,
4807
      "NEW_SECONDARY": self.op.remote_node,
4808
      "OLD_SECONDARY": self.instance.secondary_nodes[0],
4809
      }
4810
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4811
    nl = [
4812
      self.cfg.GetMasterNode(),
4813
      self.instance.primary_node,
4814
      ]
4815
    if self.op.remote_node is not None:
4816
      nl.append(self.op.remote_node)
4817
    return env, nl, nl
4818

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

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

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

    
4830
    if instance.disk_template != constants.DT_DRBD8:
4831
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
4832
                                 " instances")
4833

    
4834
    if len(instance.secondary_nodes) != 1:
4835
      raise errors.OpPrereqError("The instance has a strange layout,"
4836
                                 " expected one secondary but found %d" %
4837
                                 len(instance.secondary_nodes))
4838

    
4839
    self.sec_node = instance.secondary_nodes[0]
4840

    
4841
    if self.op.iallocator is not None:
4842
      self._RunAllocator()
4843

    
4844
    remote_node = self.op.remote_node
4845
    if remote_node is not None:
4846
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
4847
      assert self.remote_node_info is not None, \
4848
        "Cannot retrieve locked node %s" % remote_node
4849
    else:
4850
      self.remote_node_info = None
4851
    if remote_node == instance.primary_node:
4852
      raise errors.OpPrereqError("The specified node is the primary node of"
4853
                                 " the instance.")
4854
    elif remote_node == self.sec_node:
4855
      raise errors.OpPrereqError("The specified node is already the"
4856
                                 " secondary node of the instance.")
4857

    
4858
    if self.op.mode == constants.REPLACE_DISK_PRI:
4859
      n1 = self.tgt_node = instance.primary_node
4860
      n2 = self.oth_node = self.sec_node
4861
    elif self.op.mode == constants.REPLACE_DISK_SEC:
4862
      n1 = self.tgt_node = self.sec_node
4863
      n2 = self.oth_node = instance.primary_node
4864
    elif self.op.mode == constants.REPLACE_DISK_CHG:
4865
      n1 = self.new_node = remote_node
4866
      n2 = self.oth_node = instance.primary_node
4867
      self.tgt_node = self.sec_node
4868
    else:
4869
      raise errors.ProgrammerError("Unhandled disk replace mode")
4870

    
4871
    _CheckNodeOnline(self, n1)
4872
    _CheckNodeOnline(self, n2)
4873

    
4874
    if not self.op.disks:
4875
      self.op.disks = range(len(instance.disks))
4876

    
4877
    for disk_idx in self.op.disks:
4878
      instance.FindDisk(disk_idx)
4879

    
4880
  def _ExecD8DiskOnly(self, feedback_fn):
4881
    """Replace a disk on the primary or secondary for dbrd8.
4882

4883
    The algorithm for replace is quite complicated:
4884

4885
      1. for each disk to be replaced:
4886

4887
        1. create new LVs on the target node with unique names
4888
        1. detach old LVs from the drbd device
4889
        1. rename old LVs to name_replaced.<time_t>
4890
        1. rename new LVs to old LVs
4891
        1. attach the new LVs (with the old names now) to the drbd device
4892

4893
      1. wait for sync across all devices
4894

4895
      1. for each modified disk:
4896

4897
        1. remove old LVs (which have the name name_replaces.<time_t>)
4898

4899
    Failures are not very well handled.
4900

4901
    """
4902
    steps_total = 6
4903
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
4904
    instance = self.instance
4905
    iv_names = {}
4906
    vgname = self.cfg.GetVGName()
4907
    # start of work
4908
    cfg = self.cfg
4909
    tgt_node = self.tgt_node
4910
    oth_node = self.oth_node
4911

    
4912
    # Step: check device activation
4913
    self.proc.LogStep(1, steps_total, "check device existence")
4914
    info("checking volume groups")
4915
    my_vg = cfg.GetVGName()
4916
    results = self.rpc.call_vg_list([oth_node, tgt_node])
4917
    if not results:
4918
      raise errors.OpExecError("Can't list volume groups on the nodes")
4919
    for node in oth_node, tgt_node:
4920
      res = results[node]
4921
      if res.failed or not res.data or my_vg not in res.data:
4922
        raise errors.OpExecError("Volume group '%s' not found on %s" %
4923
                                 (my_vg, node))
4924
    for idx, dev in enumerate(instance.disks):
4925
      if idx not in self.op.disks:
4926
        continue
4927
      for node in tgt_node, oth_node:
4928
        info("checking disk/%d on %s" % (idx, node))
4929
        cfg.SetDiskID(dev, node)
4930
        if not self.rpc.call_blockdev_find(node, dev):
4931
          raise errors.OpExecError("Can't find disk/%d on node %s" %
4932
                                   (idx, node))
4933

    
4934
    # Step: check other node consistency
4935
    self.proc.LogStep(2, steps_total, "check peer consistency")
4936
    for idx, dev in enumerate(instance.disks):
4937
      if idx not in self.op.disks:
4938
        continue
4939
      info("checking disk/%d consistency on %s" % (idx, oth_node))
4940
      if not _CheckDiskConsistency(self, dev, oth_node,
4941
                                   oth_node==instance.primary_node):
4942
        raise errors.OpExecError("Peer node (%s) has degraded storage, unsafe"
4943
                                 " to replace disks on this node (%s)" %
4944
                                 (oth_node, tgt_node))
4945

    
4946
    # Step: create new storage
4947
    self.proc.LogStep(3, steps_total, "allocate new storage")
4948
    for idx, dev in enumerate(instance.disks):
4949
      if idx not in self.op.disks:
4950
        continue
4951
      size = dev.size
4952
      cfg.SetDiskID(dev, tgt_node)
4953
      lv_names = [".disk%d_%s" % (idx, suf)
4954
                  for suf in ["data", "meta"]]
4955
      names = _GenerateUniqueNames(self, lv_names)
4956
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=size,
4957
                             logical_id=(vgname, names[0]))
4958
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
4959
                             logical_id=(vgname, names[1]))
4960
      new_lvs = [lv_data, lv_meta]
4961
      old_lvs = dev.children
4962
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
4963
      info("creating new local storage on %s for %s" %
4964
           (tgt_node, dev.iv_name))
4965
      # we pass force_create=True to force the LVM creation
4966
      for new_lv in new_lvs:
4967
        _CreateBlockDev(self, tgt_node, instance, new_lv, True,
4968
                        _GetInstanceInfoText(instance), False)
4969

    
4970
    # Step: for each lv, detach+rename*2+attach
4971
    self.proc.LogStep(4, steps_total, "change drbd configuration")
4972
    for dev, old_lvs, new_lvs in iv_names.itervalues():
4973
      info("detaching %s drbd from local storage" % dev.iv_name)
4974
      result = self.rpc.call_blockdev_removechildren(tgt_node, dev, old_lvs)
4975
      result.Raise()
4976
      if not result.data:
4977
        raise errors.OpExecError("Can't detach drbd from local storage on node"
4978
                                 " %s for device %s" % (tgt_node, dev.iv_name))
4979
      #dev.children = []
4980
      #cfg.Update(instance)
4981

    
4982
      # ok, we created the new LVs, so now we know we have the needed
4983
      # storage; as such, we proceed on the target node to rename
4984
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
4985
      # using the assumption that logical_id == physical_id (which in
4986
      # turn is the unique_id on that node)
4987

    
4988
      # FIXME(iustin): use a better name for the replaced LVs
4989
      temp_suffix = int(time.time())
4990
      ren_fn = lambda d, suff: (d.physical_id[0],
4991
                                d.physical_id[1] + "_replaced-%s" % suff)
4992
      # build the rename list based on what LVs exist on the node
4993
      rlist = []
4994
      for to_ren in old_lvs:
4995
        find_res = self.rpc.call_blockdev_find(tgt_node, to_ren)
4996
        if not find_res.failed and find_res.data is not None: # device exists
4997
          rlist.append((to_ren, ren_fn(to_ren, temp_suffix)))
4998

    
4999
      info("renaming the old LVs on the target node")
5000
      result = self.rpc.call_blockdev_rename(tgt_node, rlist)
5001
      result.Raise()
5002
      if not result.data:
5003
        raise errors.OpExecError("Can't rename old LVs on node %s" % tgt_node)
5004
      # now we rename the new LVs to the old LVs
5005
      info("renaming the new LVs on the target node")
5006
      rlist = [(new, old.physical_id) for old, new in zip(old_lvs, new_lvs)]
5007
      result = self.rpc.call_blockdev_rename(tgt_node, rlist)
5008
      result.Raise()
5009
      if not result.data:
5010
        raise errors.OpExecError("Can't rename new LVs on node %s" % tgt_node)
5011

    
5012
      for old, new in zip(old_lvs, new_lvs):
5013
        new.logical_id = old.logical_id
5014
        cfg.SetDiskID(new, tgt_node)
5015

    
5016
      for disk in old_lvs:
5017
        disk.logical_id = ren_fn(disk, temp_suffix)
5018
        cfg.SetDiskID(disk, tgt_node)
5019

    
5020
      # now that the new lvs have the old name, we can add them to the device
5021
      info("adding new mirror component on %s" % tgt_node)
5022
      result = self.rpc.call_blockdev_addchildren(tgt_node, dev, new_lvs)
5023
      if result.failed or not result.data:
5024
        for new_lv in new_lvs:
5025
          result = self.rpc.call_blockdev_remove(tgt_node, new_lv)
5026
          if result.failed or not result.data:
5027
            warning("Can't rollback device %s", hint="manually cleanup unused"
5028
                    " logical volumes")
5029
        raise errors.OpExecError("Can't add local storage to drbd")
5030

    
5031
      dev.children = new_lvs
5032
      cfg.Update(instance)
5033

    
5034
    # Step: wait for sync
5035

    
5036
    # this can fail as the old devices are degraded and _WaitForSync
5037
    # does a combined result over all disks, so we don't check its
5038
    # return value
5039
    self.proc.LogStep(5, steps_total, "sync devices")
5040
    _WaitForSync(self, instance, unlock=True)
5041

    
5042
    # so check manually all the devices
5043
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
5044
      cfg.SetDiskID(dev, instance.primary_node)
5045
      result = self.rpc.call_blockdev_find(instance.primary_node, dev)
5046
      if result.failed or result.data[5]:
5047
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
5048

    
5049
    # Step: remove old storage
5050
    self.proc.LogStep(6, steps_total, "removing old storage")
5051
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
5052
      info("remove logical volumes for %s" % name)
5053
      for lv in old_lvs:
5054
        cfg.SetDiskID(lv, tgt_node)
5055
        result = self.rpc.call_blockdev_remove(tgt_node, lv)
5056
        if result.failed or not result.data:
5057
          warning("Can't remove old LV", hint="manually remove unused LVs")
5058
          continue
5059

    
5060
  def _ExecD8Secondary(self, feedback_fn):
5061
    """Replace the secondary node for drbd8.
5062

5063
    The algorithm for replace is quite complicated:
5064
      - for all disks of the instance:
5065
        - create new LVs on the new node with same names
5066
        - shutdown the drbd device on the old secondary
5067
        - disconnect the drbd network on the primary
5068
        - create the drbd device on the new secondary
5069
        - network attach the drbd on the primary, using an artifice:
5070
          the drbd code for Attach() will connect to the network if it
5071
          finds a device which is connected to the good local disks but
5072
          not network enabled
5073
      - wait for sync across all devices
5074
      - remove all disks from the old secondary
5075

5076
    Failures are not very well handled.
5077

5078
    """
5079
    steps_total = 6
5080
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
5081
    instance = self.instance
5082
    iv_names = {}
5083
    # start of work
5084
    cfg = self.cfg
5085
    old_node = self.tgt_node
5086
    new_node = self.new_node
5087
    pri_node = instance.primary_node
5088
    nodes_ip = {
5089
      old_node: self.cfg.GetNodeInfo(old_node).secondary_ip,
5090
      new_node: self.cfg.GetNodeInfo(new_node).secondary_ip,
5091
      pri_node: self.cfg.GetNodeInfo(pri_node).secondary_ip,
5092
      }
5093

    
5094
    # Step: check device activation
5095
    self.proc.LogStep(1, steps_total, "check device existence")
5096
    info("checking volume groups")
5097
    my_vg = cfg.GetVGName()
5098
    results = self.rpc.call_vg_list([pri_node, new_node])
5099
    for node in pri_node, new_node:
5100
      res = results[node]
5101
      if res.failed or not res.data or my_vg not in res.data:
5102
        raise errors.OpExecError("Volume group '%s' not found on %s" %
5103
                                 (my_vg, node))
5104
    for idx, dev in enumerate(instance.disks):
5105
      if idx not in self.op.disks:
5106
        continue
5107
      info("checking disk/%d on %s" % (idx, pri_node))
5108
      cfg.SetDiskID(dev, pri_node)
5109
      result = self.rpc.call_blockdev_find(pri_node, dev)
5110
      result.Raise()
5111
      if not result.data:
5112
        raise errors.OpExecError("Can't find disk/%d on node %s" %
5113
                                 (idx, pri_node))
5114

    
5115
    # Step: check other node consistency
5116
    self.proc.LogStep(2, steps_total, "check peer consistency")
5117
    for idx, dev in enumerate(instance.disks):
5118
      if idx not in self.op.disks:
5119
        continue
5120
      info("checking disk/%d consistency on %s" % (idx, pri_node))
5121
      if not _CheckDiskConsistency(self, dev, pri_node, True, ldisk=True):
5122
        raise errors.OpExecError("Primary node (%s) has degraded storage,"
5123
                                 " unsafe to replace the secondary" %
5124
                                 pri_node)
5125

    
5126
    # Step: create new storage
5127
    self.proc.LogStep(3, steps_total, "allocate new storage")
5128
    for idx, dev in enumerate(instance.disks):
5129
      info("adding new local storage on %s for disk/%d" %
5130
           (new_node, idx))
5131
      # we pass force_create=True to force LVM creation
5132
      for new_lv in dev.children:
5133
        _CreateBlockDev(self, new_node, instance, new_lv, True,
5134
                        _GetInstanceInfoText(instance), False)
5135

    
5136
    # Step 4: dbrd minors and drbd setups changes
5137
    # after this, we must manually remove the drbd minors on both the
5138
    # error and the success paths
5139
    minors = cfg.AllocateDRBDMinor([new_node for dev in instance.disks],
5140
                                   instance.name)
5141
    logging.debug("Allocated minors %s" % (minors,))
5142
    self.proc.LogStep(4, steps_total, "changing drbd configuration")
5143
    for idx, (dev, new_minor) in enumerate(zip(instance.disks, minors)):
5144
      size = dev.size
5145
      info("activating a new drbd on %s for disk/%d" % (new_node, idx))
5146
      # create new devices on new_node; note that we create two IDs:
5147
      # one without port, so the drbd will be activated without
5148
      # networking information on the new node at this stage, and one
5149
      # with network, for the latter activation in step 4
5150
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
5151
      if pri_node == o_node1:
5152
        p_minor = o_minor1
5153
      else:
5154
        p_minor = o_minor2
5155

    
5156
      new_alone_id = (pri_node, new_node, None, p_minor, new_minor, o_secret)
5157
      new_net_id = (pri_node, new_node, o_port, p_minor, new_minor, o_secret)
5158

    
5159
      iv_names[idx] = (dev, dev.children, new_net_id)
5160
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
5161
                    new_net_id)
5162
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
5163
                              logical_id=new_alone_id,
5164
                              children=dev.children)
5165
      try:
5166
        _CreateSingleBlockDev(self, new_node, instance, new_drbd,
5167
                              _GetInstanceInfoText(instance), False)
5168
      except errors.BlockDeviceError:
5169
        self.cfg.ReleaseDRBDMinors(instance.name)
5170
        raise
5171

    
5172
    for idx, dev in enumerate(instance.disks):
5173
      # we have new devices, shutdown the drbd on the old secondary
5174
      info("shutting down drbd for disk/%d on old node" % idx)
5175
      cfg.SetDiskID(dev, old_node)
5176
      result = self.rpc.call_blockdev_shutdown(old_node, dev)
5177
      if result.failed or not result.data:
5178
        warning("Failed to shutdown drbd for disk/%d on old node" % idx,
5179
                hint="Please cleanup this device manually as soon as possible")
5180

    
5181
    info("detaching primary drbds from the network (=> standalone)")
5182
    result = self.rpc.call_drbd_disconnect_net([pri_node], nodes_ip,
5183
                                               instance.disks)[pri_node]
5184

    
5185
    msg = result.RemoteFailMsg()
5186
    if msg:
5187
      # detaches didn't succeed (unlikely)
5188
      self.cfg.ReleaseDRBDMinors(instance.name)
5189
      raise errors.OpExecError("Can't detach the disks from the network on"
5190
                               " old node: %s" % (msg,))
5191

    
5192
    # if we managed to detach at least one, we update all the disks of
5193
    # the instance to point to the new secondary
5194
    info("updating instance configuration")
5195
    for dev, _, new_logical_id in iv_names.itervalues():
5196
      dev.logical_id = new_logical_id
5197
      cfg.SetDiskID(dev, pri_node)
5198
    cfg.Update(instance)
5199

    
5200
    # and now perform the drbd attach
5201
    info("attaching primary drbds to new secondary (standalone => connected)")
5202
    result = self.rpc.call_drbd_attach_net([pri_node, new_node], nodes_ip,
5203
                                           instance.disks, instance.name,
5204
                                           False)
5205
    for to_node, to_result in result.items():
5206
      msg = to_result.RemoteFailMsg()
5207
      if msg:
5208
        warning("can't attach drbd disks on node %s: %s", to_node, msg,
5209
                hint="please do a gnt-instance info to see the"
5210
                " status of disks")
5211

    
5212
    # this can fail as the old devices are degraded and _WaitForSync
5213
    # does a combined result over all disks, so we don't check its
5214
    # return value
5215
    self.proc.LogStep(5, steps_total, "sync devices")
5216
    _WaitForSync(self, instance, unlock=True)
5217

    
5218
    # so check manually all the devices
5219
    for idx, (dev, old_lvs, _) in iv_names.iteritems():
5220
      cfg.SetDiskID(dev, pri_node)
5221
      result = self.rpc.call_blockdev_find(pri_node, dev)
5222
      result.Raise()
5223
      if result.data[5]:
5224
        raise errors.OpExecError("DRBD device disk/%d is degraded!" % idx)
5225

    
5226
    self.proc.LogStep(6, steps_total, "removing old storage")
5227
    for idx, (dev, old_lvs, _) in iv_names.iteritems():
5228
      info("remove logical volumes for disk/%d" % idx)
5229
      for lv in old_lvs:
5230
        cfg.SetDiskID(lv, old_node)
5231
        result = self.rpc.call_blockdev_remove(old_node, lv)
5232
        if result.failed or not result.data:
5233
          warning("Can't remove LV on old secondary",
5234
                  hint="Cleanup stale volumes by hand")
5235

    
5236
  def Exec(self, feedback_fn):
5237
    """Execute disk replacement.
5238

5239
    This dispatches the disk replacement to the appropriate handler.
5240

5241
    """
5242
    instance = self.instance
5243

    
5244
    # Activate the instance disks if we're replacing them on a down instance
5245
    if not instance.admin_up:
5246
      _StartInstanceDisks(self, instance, True)
5247

    
5248
    if self.op.mode == constants.REPLACE_DISK_CHG:
5249
      fn = self._ExecD8Secondary
5250
    else:
5251
      fn = self._ExecD8DiskOnly
5252

    
5253
    ret = fn(feedback_fn)
5254

    
5255
    # Deactivate the instance disks if we're replacing them on a down instance
5256
    if not instance.admin_up:
5257
      _SafeShutdownInstanceDisks(self, instance)
5258

    
5259
    return ret
5260

    
5261

    
5262
class LUGrowDisk(LogicalUnit):
5263
  """Grow a disk of an instance.
5264

5265
  """
5266
  HPATH = "disk-grow"
5267
  HTYPE = constants.HTYPE_INSTANCE
5268
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
5269
  REQ_BGL = False
5270

    
5271
  def ExpandNames(self):
5272
    self._ExpandAndLockInstance()
5273
    self.needed_locks[locking.LEVEL_NODE] = []
5274
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5275

    
5276
  def DeclareLocks(self, level):
5277
    if level == locking.LEVEL_NODE:
5278
      self._LockInstancesNodes()
5279

    
5280
  def BuildHooksEnv(self):
5281
    """Build hooks env.
5282

5283
    This runs on the master, the primary and all the secondaries.
5284

5285
    """
5286
    env = {
5287
      "DISK": self.op.disk,
5288
      "AMOUNT": self.op.amount,
5289
      }
5290
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5291
    nl = [
5292
      self.cfg.GetMasterNode(),
5293
      self.instance.primary_node,
5294
      ]
5295
    return env, nl, nl
5296

    
5297
  def CheckPrereq(self):
5298
    """Check prerequisites.
5299

5300
    This checks that the instance is in the cluster.
5301

5302
    """
5303
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5304
    assert instance is not None, \
5305
      "Cannot retrieve locked instance %s" % self.op.instance_name
5306
    nodenames = list(instance.all_nodes)
5307
    for node in nodenames:
5308
      _CheckNodeOnline(self, node)
5309

    
5310

    
5311
    self.instance = instance
5312

    
5313
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
5314
      raise errors.OpPrereqError("Instance's disk layout does not support"
5315
                                 " growing.")
5316

    
5317
    self.disk = instance.FindDisk(self.op.disk)
5318

    
5319
    nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
5320
                                       instance.hypervisor)
5321
    for node in nodenames:
5322
      info = nodeinfo[node]
5323
      if info.failed or not info.data:
5324
        raise errors.OpPrereqError("Cannot get current information"
5325
                                   " from node '%s'" % node)
5326
      vg_free = info.data.get('vg_free', None)
5327
      if not isinstance(vg_free, int):
5328
        raise errors.OpPrereqError("Can't compute free disk space on"
5329
                                   " node %s" % node)
5330
      if self.op.amount > vg_free:
5331
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
5332
                                   " %d MiB available, %d MiB required" %
5333
                                   (node, vg_free, self.op.amount))
5334

    
5335
  def Exec(self, feedback_fn):
5336
    """Execute disk grow.
5337

5338
    """
5339
    instance = self.instance
5340
    disk = self.disk
5341
    for node in instance.all_nodes:
5342
      self.cfg.SetDiskID(disk, node)
5343
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
5344
      msg = result.RemoteFailMsg()
5345
      if msg:
5346
        raise errors.OpExecError("Grow request failed to node %s: %s" %
5347
                                 (node, msg))
5348
    disk.RecordGrow(self.op.amount)
5349
    self.cfg.Update(instance)
5350
    if self.op.wait_for_sync:
5351
      disk_abort = not _WaitForSync(self, instance)
5352
      if disk_abort:
5353
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
5354
                             " status.\nPlease check the instance.")
5355

    
5356

    
5357
class LUQueryInstanceData(NoHooksLU):
5358
  """Query runtime instance data.
5359

5360
  """
5361
  _OP_REQP = ["instances", "static"]
5362
  REQ_BGL = False
5363

    
5364
  def ExpandNames(self):
5365
    self.needed_locks = {}
5366
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
5367

    
5368
    if not isinstance(self.op.instances, list):
5369
      raise errors.OpPrereqError("Invalid argument type 'instances'")
5370

    
5371
    if self.op.instances:
5372
      self.wanted_names = []
5373
      for name in self.op.instances:
5374
        full_name = self.cfg.ExpandInstanceName(name)
5375
        if full_name is None:
5376
          raise errors.OpPrereqError("Instance '%s' not known" % name)
5377
        self.wanted_names.append(full_name)
5378
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
5379
    else:
5380
      self.wanted_names = None
5381
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
5382

    
5383
    self.needed_locks[locking.LEVEL_NODE] = []
5384
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5385

    
5386
  def DeclareLocks(self, level):
5387
    if level == locking.LEVEL_NODE:
5388
      self._LockInstancesNodes()
5389

    
5390
  def CheckPrereq(self):
5391
    """Check prerequisites.
5392

5393
    This only checks the optional instance list against the existing names.
5394

5395
    """
5396
    if self.wanted_names is None:
5397
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5398

    
5399
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
5400
                             in self.wanted_names]
5401
    return
5402

    
5403
  def _ComputeDiskStatus(self, instance, snode, dev):
5404
    """Compute block device status.
5405

5406
    """
5407
    static = self.op.static
5408
    if not static:
5409
      self.cfg.SetDiskID(dev, instance.primary_node)
5410
      dev_pstatus = self.rpc.call_blockdev_find(instance.primary_node, dev)
5411
      dev_pstatus.Raise()
5412
      dev_pstatus = dev_pstatus.data
5413
    else:
5414
      dev_pstatus = None
5415

    
5416
    if dev.dev_type in constants.LDS_DRBD:
5417
      # we change the snode then (otherwise we use the one passed in)
5418
      if dev.logical_id[0] == instance.primary_node:
5419
        snode = dev.logical_id[1]
5420
      else:
5421
        snode = dev.logical_id[0]
5422

    
5423
    if snode and not static:
5424
      self.cfg.SetDiskID(dev, snode)
5425
      dev_sstatus = self.rpc.call_blockdev_find(snode, dev)
5426
      dev_sstatus.Raise()
5427
      dev_sstatus = dev_sstatus.data
5428
    else:
5429
      dev_sstatus = None
5430

    
5431
    if dev.children:
5432
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
5433
                      for child in dev.children]
5434
    else:
5435
      dev_children = []
5436

    
5437
    data = {
5438
      "iv_name": dev.iv_name,
5439
      "dev_type": dev.dev_type,
5440
      "logical_id": dev.logical_id,
5441
      "physical_id": dev.physical_id,
5442
      "pstatus": dev_pstatus,
5443
      "sstatus": dev_sstatus,
5444
      "children": dev_children,
5445
      "mode": dev.mode,
5446
      }
5447

    
5448
    return data
5449

    
5450
  def Exec(self, feedback_fn):
5451
    """Gather and return data"""
5452
    result = {}
5453

    
5454
    cluster = self.cfg.GetClusterInfo()
5455

    
5456
    for instance in self.wanted_instances:
5457
      if not self.op.static:
5458
        remote_info = self.rpc.call_instance_info(instance.primary_node,
5459
                                                  instance.name,
5460
                                                  instance.hypervisor)
5461
        remote_info.Raise()
5462
        remote_info = remote_info.data
5463
        if remote_info and "state" in remote_info:
5464
          remote_state = "up"
5465
        else:
5466
          remote_state = "down"
5467
      else:
5468
        remote_state = None
5469
      if instance.admin_up:
5470
        config_state = "up"
5471
      else:
5472
        config_state = "down"
5473

    
5474
      disks = [self._ComputeDiskStatus(instance, None, device)
5475
               for device in instance.disks]
5476

    
5477
      idict = {
5478
        "name": instance.name,
5479
        "config_state": config_state,
5480
        "run_state": remote_state,
5481
        "pnode": instance.primary_node,
5482
        "snodes": instance.secondary_nodes,
5483
        "os": instance.os,
5484
        "nics": [(nic.mac, nic.ip, nic.bridge) for nic in instance.nics],
5485
        "disks": disks,
5486
        "hypervisor": instance.hypervisor,
5487
        "network_port": instance.network_port,
5488
        "hv_instance": instance.hvparams,
5489
        "hv_actual": cluster.FillHV(instance),
5490
        "be_instance": instance.beparams,
5491
        "be_actual": cluster.FillBE(instance),
5492
        }
5493

    
5494
      result[instance.name] = idict
5495

    
5496
    return result
5497

    
5498

    
5499
class LUSetInstanceParams(LogicalUnit):
5500
  """Modifies an instances's parameters.
5501

5502
  """
5503
  HPATH = "instance-modify"
5504
  HTYPE = constants.HTYPE_INSTANCE
5505
  _OP_REQP = ["instance_name"]
5506
  REQ_BGL = False
5507

    
5508
  def CheckArguments(self):
5509
    if not hasattr(self.op, 'nics'):
5510
      self.op.nics = []
5511
    if not hasattr(self.op, 'disks'):
5512
      self.op.disks = []
5513
    if not hasattr(self.op, 'beparams'):
5514
      self.op.beparams = {}
5515
    if not hasattr(self.op, 'hvparams'):
5516
      self.op.hvparams = {}
5517
    self.op.force = getattr(self.op, "force", False)
5518
    if not (self.op.nics or self.op.disks or
5519
            self.op.hvparams or self.op.beparams):
5520
      raise errors.OpPrereqError("No changes submitted")
5521

    
5522
    utils.CheckBEParams(self.op.beparams)
5523

    
5524
    # Disk validation
5525
    disk_addremove = 0
5526
    for disk_op, disk_dict in self.op.disks:
5527
      if disk_op == constants.DDM_REMOVE:
5528
        disk_addremove += 1
5529
        continue
5530
      elif disk_op == constants.DDM_ADD:
5531
        disk_addremove += 1
5532
      else:
5533
        if not isinstance(disk_op, int):
5534
          raise errors.OpPrereqError("Invalid disk index")
5535
      if disk_op == constants.DDM_ADD:
5536
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
5537
        if mode not in constants.DISK_ACCESS_SET:
5538
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode)
5539
        size = disk_dict.get('size', None)
5540
        if size is None:
5541
          raise errors.OpPrereqError("Required disk parameter size missing")
5542
        try:
5543
          size = int(size)
5544
        except ValueError, err:
5545
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
5546
                                     str(err))
5547
        disk_dict['size'] = size
5548
      else:
5549
        # modification of disk
5550
        if 'size' in disk_dict:
5551
          raise errors.OpPrereqError("Disk size change not possible, use"
5552
                                     " grow-disk")
5553

    
5554
    if disk_addremove > 1:
5555
      raise errors.OpPrereqError("Only one disk add or remove operation"
5556
                                 " supported at a time")
5557

    
5558
    # NIC validation
5559
    nic_addremove = 0
5560
    for nic_op, nic_dict in self.op.nics:
5561
      if nic_op == constants.DDM_REMOVE:
5562
        nic_addremove += 1
5563
        continue
5564
      elif nic_op == constants.DDM_ADD:
5565
        nic_addremove += 1
5566
      else:
5567
        if not isinstance(nic_op, int):
5568
          raise errors.OpPrereqError("Invalid nic index")
5569

    
5570
      # nic_dict should be a dict
5571
      nic_ip = nic_dict.get('ip', None)
5572
      if nic_ip is not None:
5573
        if nic_ip.lower() == "none":
5574
          nic_dict['ip'] = None
5575
        else:
5576
          if not utils.IsValidIP(nic_ip):
5577
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip)
5578
      # we can only check None bridges and assign the default one
5579
      nic_bridge = nic_dict.get('bridge', None)
5580
      if nic_bridge is None:
5581
        nic_dict['bridge'] = self.cfg.GetDefBridge()
5582
      # but we can validate MACs
5583
      nic_mac = nic_dict.get('mac', None)
5584
      if nic_mac is not None:
5585
        if self.cfg.IsMacInUse(nic_mac):
5586
          raise errors.OpPrereqError("MAC address %s already in use"
5587
                                     " in cluster" % nic_mac)
5588
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5589
          if not utils.IsValidMac(nic_mac):
5590
            raise errors.OpPrereqError("Invalid MAC address %s" % nic_mac)
5591
    if nic_addremove > 1:
5592
      raise errors.OpPrereqError("Only one NIC add or remove operation"
5593
                                 " supported at a time")
5594

    
5595
  def ExpandNames(self):
5596
    self._ExpandAndLockInstance()
5597
    self.needed_locks[locking.LEVEL_NODE] = []
5598
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5599

    
5600
  def DeclareLocks(self, level):
5601
    if level == locking.LEVEL_NODE:
5602
      self._LockInstancesNodes()
5603

    
5604
  def BuildHooksEnv(self):
5605
    """Build hooks env.
5606

5607
    This runs on the master, primary and secondaries.
5608

5609
    """
5610
    args = dict()
5611
    if constants.BE_MEMORY in self.be_new:
5612
      args['memory'] = self.be_new[constants.BE_MEMORY]
5613
    if constants.BE_VCPUS in self.be_new:
5614
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
5615
    # FIXME: readd disk/nic changes
5616
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
5617
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5618
    return env, nl, nl
5619

    
5620
  def CheckPrereq(self):
5621
    """Check prerequisites.
5622

5623
    This only checks the instance list against the existing names.
5624

5625
    """
5626
    force = self.force = self.op.force
5627

    
5628
    # checking the new params on the primary/secondary nodes
5629

    
5630
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5631
    assert self.instance is not None, \
5632
      "Cannot retrieve locked instance %s" % self.op.instance_name
5633
    pnode = instance.primary_node
5634
    nodelist = list(instance.all_nodes)
5635

    
5636
    # hvparams processing
5637
    if self.op.hvparams:
5638
      i_hvdict = copy.deepcopy(instance.hvparams)
5639
      for key, val in self.op.hvparams.iteritems():
5640
        if val == constants.VALUE_DEFAULT:
5641
          try:
5642
            del i_hvdict[key]
5643
          except KeyError:
5644
            pass
5645
        elif val == constants.VALUE_NONE:
5646
          i_hvdict[key] = None
5647
        else:
5648
          i_hvdict[key] = val
5649
      cluster = self.cfg.GetClusterInfo()
5650
      hv_new = cluster.FillDict(cluster.hvparams[instance.hypervisor],
5651
                                i_hvdict)
5652
      # local check
5653
      hypervisor.GetHypervisor(
5654
        instance.hypervisor).CheckParameterSyntax(hv_new)
5655
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
5656
      self.hv_new = hv_new # the new actual values
5657
      self.hv_inst = i_hvdict # the new dict (without defaults)
5658
    else:
5659
      self.hv_new = self.hv_inst = {}
5660

    
5661
    # beparams processing
5662
    if self.op.beparams:
5663
      i_bedict = copy.deepcopy(instance.beparams)
5664
      for key, val in self.op.beparams.iteritems():
5665
        if val == constants.VALUE_DEFAULT:
5666
          try:
5667
            del i_bedict[key]
5668
          except KeyError:
5669
            pass
5670
        else:
5671
          i_bedict[key] = val
5672
      cluster = self.cfg.GetClusterInfo()
5673
      be_new = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
5674
                                i_bedict)
5675
      self.be_new = be_new # the new actual values
5676
      self.be_inst = i_bedict # the new dict (without defaults)
5677
    else:
5678
      self.be_new = self.be_inst = {}
5679

    
5680
    self.warn = []
5681

    
5682
    if constants.BE_MEMORY in self.op.beparams and not self.force:
5683
      mem_check_list = [pnode]
5684
      if be_new[constants.BE_AUTO_BALANCE]:
5685
        # either we changed auto_balance to yes or it was from before
5686
        mem_check_list.extend(instance.secondary_nodes)
5687
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
5688
                                                  instance.hypervisor)
5689
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
5690
                                         instance.hypervisor)
5691
      if nodeinfo[pnode].failed or not isinstance(nodeinfo[pnode].data, dict):
5692
        # Assume the primary node is unreachable and go ahead
5693
        self.warn.append("Can't get info from primary node %s" % pnode)
5694
      else:
5695
        if not instance_info.failed and instance_info.data:
5696
          current_mem = instance_info.data['memory']
5697
        else:
5698
          # Assume instance not running
5699
          # (there is a slight race condition here, but it's not very probable,
5700
          # and we have no other way to check)
5701
          current_mem = 0
5702
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
5703
                    nodeinfo[pnode].data['memory_free'])
5704
        if miss_mem > 0:
5705
          raise errors.OpPrereqError("This change will prevent the instance"
5706
                                     " from starting, due to %d MB of memory"
5707
                                     " missing on its primary node" % miss_mem)
5708

    
5709
      if be_new[constants.BE_AUTO_BALANCE]:
5710
        for node, nres in nodeinfo.iteritems():
5711
          if node not in instance.secondary_nodes:
5712
            continue
5713
          if nres.failed or not isinstance(nres.data, dict):
5714
            self.warn.append("Can't get info from secondary node %s" % node)
5715
          elif be_new[constants.BE_MEMORY] > nres.data['memory_free']:
5716
            self.warn.append("Not enough memory to failover instance to"
5717
                             " secondary node %s" % node)
5718

    
5719
    # NIC processing
5720
    for nic_op, nic_dict in self.op.nics:
5721
      if nic_op == constants.DDM_REMOVE:
5722
        if not instance.nics:
5723
          raise errors.OpPrereqError("Instance has no NICs, cannot remove")
5724
        continue
5725
      if nic_op != constants.DDM_ADD:
5726
        # an existing nic
5727
        if nic_op < 0 or nic_op >= len(instance.nics):
5728
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
5729
                                     " are 0 to %d" %
5730
                                     (nic_op, len(instance.nics)))
5731
      nic_bridge = nic_dict.get('bridge', None)
5732
      if nic_bridge is not None:
5733
        if not self.rpc.call_bridges_exist(pnode, [nic_bridge]):
5734
          msg = ("Bridge '%s' doesn't exist on one of"
5735
                 " the instance nodes" % nic_bridge)
5736
          if self.force:
5737
            self.warn.append(msg)
5738
          else:
5739
            raise errors.OpPrereqError(msg)
5740

    
5741
    # DISK processing
5742
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
5743
      raise errors.OpPrereqError("Disk operations not supported for"
5744
                                 " diskless instances")
5745
    for disk_op, disk_dict in self.op.disks:
5746
      if disk_op == constants.DDM_REMOVE:
5747
        if len(instance.disks) == 1:
5748
          raise errors.OpPrereqError("Cannot remove the last disk of"
5749
                                     " an instance")
5750
        ins_l = self.rpc.call_instance_list([pnode], [instance.hypervisor])
5751
        ins_l = ins_l[pnode]
5752
        if ins_l.failed or not isinstance(ins_l.data, list):
5753
          raise errors.OpPrereqError("Can't contact node '%s'" % pnode)
5754
        if instance.name in ins_l.data:
5755
          raise errors.OpPrereqError("Instance is running, can't remove"
5756
                                     " disks.")
5757

    
5758
      if (disk_op == constants.DDM_ADD and
5759
          len(instance.nics) >= constants.MAX_DISKS):
5760
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
5761
                                   " add more" % constants.MAX_DISKS)
5762
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
5763
        # an existing disk
5764
        if disk_op < 0 or disk_op >= len(instance.disks):
5765
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
5766
                                     " are 0 to %d" %
5767
                                     (disk_op, len(instance.disks)))
5768

    
5769
    return
5770

    
5771
  def Exec(self, feedback_fn):
5772
    """Modifies an instance.
5773

5774
    All parameters take effect only at the next restart of the instance.
5775

5776
    """
5777
    # Process here the warnings from CheckPrereq, as we don't have a
5778
    # feedback_fn there.
5779
    for warn in self.warn:
5780
      feedback_fn("WARNING: %s" % warn)
5781

    
5782
    result = []
5783
    instance = self.instance
5784
    # disk changes
5785
    for disk_op, disk_dict in self.op.disks:
5786
      if disk_op == constants.DDM_REMOVE:
5787
        # remove the last disk
5788
        device = instance.disks.pop()
5789
        device_idx = len(instance.disks)
5790
        for node, disk in device.ComputeNodeTree(instance.primary_node):
5791
          self.cfg.SetDiskID(disk, node)
5792
          rpc_result = self.rpc.call_blockdev_remove(node, disk)
5793
          if rpc_result.failed or not rpc_result.data:
5794
            self.proc.LogWarning("Could not remove disk/%d on node %s,"
5795
                                 " continuing anyway", device_idx, node)
5796
        result.append(("disk/%d" % device_idx, "remove"))
5797
      elif disk_op == constants.DDM_ADD:
5798
        # add a new disk
5799
        if instance.disk_template == constants.DT_FILE:
5800
          file_driver, file_path = instance.disks[0].logical_id
5801
          file_path = os.path.dirname(file_path)
5802
        else:
5803
          file_driver = file_path = None
5804
        disk_idx_base = len(instance.disks)
5805
        new_disk = _GenerateDiskTemplate(self,
5806
                                         instance.disk_template,
5807
                                         instance.name, instance.primary_node,
5808
                                         instance.secondary_nodes,
5809
                                         [disk_dict],
5810
                                         file_path,
5811
                                         file_driver,
5812
                                         disk_idx_base)[0]
5813
        instance.disks.append(new_disk)
5814
        info = _GetInstanceInfoText(instance)
5815

    
5816
        logging.info("Creating volume %s for instance %s",
5817
                     new_disk.iv_name, instance.name)
5818
        # Note: this needs to be kept in sync with _CreateDisks
5819
        #HARDCODE
5820
        for node in instance.all_nodes:
5821
          f_create = node == instance.primary_node
5822
          try:
5823
            _CreateBlockDev(self, node, instance, new_disk,
5824
                            f_create, info, f_create)
5825
          except errors.OpExecError, err:
5826
            self.LogWarning("Failed to create volume %s (%s) on"
5827
                            " node %s: %s",
5828
                            new_disk.iv_name, new_disk, node, err)
5829
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
5830
                       (new_disk.size, new_disk.mode)))
5831
      else:
5832
        # change a given disk
5833
        instance.disks[disk_op].mode = disk_dict['mode']
5834
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
5835
    # NIC changes
5836
    for nic_op, nic_dict in self.op.nics:
5837
      if nic_op == constants.DDM_REMOVE:
5838
        # remove the last nic
5839
        del instance.nics[-1]
5840
        result.append(("nic.%d" % len(instance.nics), "remove"))
5841
      elif nic_op == constants.DDM_ADD:
5842
        # add a new nic
5843
        if 'mac' not in nic_dict:
5844
          mac = constants.VALUE_GENERATE
5845
        else:
5846
          mac = nic_dict['mac']
5847
        if mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5848
          mac = self.cfg.GenerateMAC()
5849
        new_nic = objects.NIC(mac=mac, ip=nic_dict.get('ip', None),
5850
                              bridge=nic_dict.get('bridge', None))
5851
        instance.nics.append(new_nic)
5852
        result.append(("nic.%d" % (len(instance.nics) - 1),
5853
                       "add:mac=%s,ip=%s,bridge=%s" %
5854
                       (new_nic.mac, new_nic.ip, new_nic.bridge)))
5855
      else:
5856
        # change a given nic
5857
        for key in 'mac', 'ip', 'bridge':
5858
          if key in nic_dict:
5859
            setattr(instance.nics[nic_op], key, nic_dict[key])
5860
            result.append(("nic.%s/%d" % (key, nic_op), nic_dict[key]))
5861

    
5862
    # hvparams changes
5863
    if self.op.hvparams:
5864
      instance.hvparams = self.hv_new
5865
      for key, val in self.op.hvparams.iteritems():
5866
        result.append(("hv/%s" % key, val))
5867

    
5868
    # beparams changes
5869
    if self.op.beparams:
5870
      instance.beparams = self.be_inst
5871
      for key, val in self.op.beparams.iteritems():
5872
        result.append(("be/%s" % key, val))
5873

    
5874
    self.cfg.Update(instance)
5875

    
5876
    return result
5877

    
5878

    
5879
class LUQueryExports(NoHooksLU):
5880
  """Query the exports list
5881

5882
  """
5883
  _OP_REQP = ['nodes']
5884
  REQ_BGL = False
5885

    
5886
  def ExpandNames(self):
5887
    self.needed_locks = {}
5888
    self.share_locks[locking.LEVEL_NODE] = 1
5889
    if not self.op.nodes:
5890
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5891
    else:
5892
      self.needed_locks[locking.LEVEL_NODE] = \
5893
        _GetWantedNodes(self, self.op.nodes)
5894

    
5895
  def CheckPrereq(self):
5896
    """Check prerequisites.
5897

5898
    """
5899
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
5900

    
5901
  def Exec(self, feedback_fn):
5902
    """Compute the list of all the exported system images.
5903

5904
    @rtype: dict
5905
    @return: a dictionary with the structure node->(export-list)
5906
        where export-list is a list of the instances exported on
5907
        that node.
5908

5909
    """
5910
    rpcresult = self.rpc.call_export_list(self.nodes)
5911
    result = {}
5912
    for node in rpcresult:
5913
      if rpcresult[node].failed:
5914
        result[node] = False
5915
      else:
5916
        result[node] = rpcresult[node].data
5917

    
5918
    return result
5919

    
5920

    
5921
class LUExportInstance(LogicalUnit):
5922
  """Export an instance to an image in the cluster.
5923

5924
  """
5925
  HPATH = "instance-export"
5926
  HTYPE = constants.HTYPE_INSTANCE
5927
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
5928
  REQ_BGL = False
5929

    
5930
  def ExpandNames(self):
5931
    self._ExpandAndLockInstance()
5932
    # FIXME: lock only instance primary and destination node
5933
    #
5934
    # Sad but true, for now we have do lock all nodes, as we don't know where
5935
    # the previous export might be, and and in this LU we search for it and
5936
    # remove it from its current node. In the future we could fix this by:
5937
    #  - making a tasklet to search (share-lock all), then create the new one,
5938
    #    then one to remove, after
5939
    #  - removing the removal operation altoghether
5940
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5941

    
5942
  def DeclareLocks(self, level):
5943
    """Last minute lock declaration."""
5944
    # All nodes are locked anyway, so nothing to do here.
5945

    
5946
  def BuildHooksEnv(self):
5947
    """Build hooks env.
5948

5949
    This will run on the master, primary node and target node.
5950

5951
    """
5952
    env = {
5953
      "EXPORT_NODE": self.op.target_node,
5954
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
5955
      }
5956
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5957
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node,
5958
          self.op.target_node]
5959
    return env, nl, nl
5960

    
5961
  def CheckPrereq(self):
5962
    """Check prerequisites.
5963

5964
    This checks that the instance and node names are valid.
5965

5966
    """
5967
    instance_name = self.op.instance_name
5968
    self.instance = self.cfg.GetInstanceInfo(instance_name)
5969
    assert self.instance is not None, \
5970
          "Cannot retrieve locked instance %s" % self.op.instance_name
5971
    _CheckNodeOnline(self, self.instance.primary_node)
5972

    
5973
    self.dst_node = self.cfg.GetNodeInfo(
5974
      self.cfg.ExpandNodeName(self.op.target_node))
5975

    
5976
    if self.dst_node is None:
5977
      # This is wrong node name, not a non-locked node
5978
      raise errors.OpPrereqError("Wrong node name %s" % self.op.target_node)
5979
    _CheckNodeOnline(self, self.dst_node.name)
5980

    
5981
    # instance disk type verification
5982
    for disk in self.instance.disks:
5983
      if disk.dev_type == constants.LD_FILE:
5984
        raise errors.OpPrereqError("Export not supported for instances with"
5985
                                   " file-based disks")
5986

    
5987
  def Exec(self, feedback_fn):
5988
    """Export an instance to an image in the cluster.
5989

5990
    """
5991
    instance = self.instance
5992
    dst_node = self.dst_node
5993
    src_node = instance.primary_node
5994
    if self.op.shutdown:
5995
      # shutdown the instance, but not the disks
5996
      result = self.rpc.call_instance_shutdown(src_node, instance)
5997
      result.Raise()
5998
      if not result.data:
5999
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
6000
                                 (instance.name, src_node))
6001

    
6002
    vgname = self.cfg.GetVGName()
6003

    
6004
    snap_disks = []
6005

    
6006
    # set the disks ID correctly since call_instance_start needs the
6007
    # correct drbd minor to create the symlinks
6008
    for disk in instance.disks:
6009
      self.cfg.SetDiskID(disk, src_node)
6010

    
6011
    try:
6012
      for disk in instance.disks:
6013
        # new_dev_name will be a snapshot of an lvm leaf of the one we passed
6014
        new_dev_name = self.rpc.call_blockdev_snapshot(src_node, disk)
6015
        if new_dev_name.failed or not new_dev_name.data:
6016
          self.LogWarning("Could not snapshot block device %s on node %s",
6017
                          disk.logical_id[1], src_node)
6018
          snap_disks.append(False)
6019
        else:
6020
          new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
6021
                                 logical_id=(vgname, new_dev_name.data),
6022
                                 physical_id=(vgname, new_dev_name.data),
6023
                                 iv_name=disk.iv_name)
6024
          snap_disks.append(new_dev)
6025

    
6026
    finally:
6027
      if self.op.shutdown and instance.admin_up:
6028
        result = self.rpc.call_instance_start(src_node, instance, None)
6029
        msg = result.RemoteFailMsg()
6030
        if msg:
6031
          _ShutdownInstanceDisks(self, instance)
6032
          raise errors.OpExecError("Could not start instance: %s" % msg)
6033

    
6034
    # TODO: check for size
6035

    
6036
    cluster_name = self.cfg.GetClusterName()
6037
    for idx, dev in enumerate(snap_disks):
6038
      if dev:
6039
        result = self.rpc.call_snapshot_export(src_node, dev, dst_node.name,
6040
                                               instance, cluster_name, idx)
6041
        if result.failed or not result.data:
6042
          self.LogWarning("Could not export block device %s from node %s to"
6043
                          " node %s", dev.logical_id[1], src_node,
6044
                          dst_node.name)
6045
        result = self.rpc.call_blockdev_remove(src_node, dev)
6046
        if result.failed or not result.data:
6047
          self.LogWarning("Could not remove snapshot block device %s from node"
6048
                          " %s", dev.logical_id[1], src_node)
6049

    
6050
    result = self.rpc.call_finalize_export(dst_node.name, instance, snap_disks)
6051
    if result.failed or not result.data:
6052
      self.LogWarning("Could not finalize export for instance %s on node %s",
6053
                      instance.name, dst_node.name)
6054

    
6055
    nodelist = self.cfg.GetNodeList()
6056
    nodelist.remove(dst_node.name)
6057

    
6058
    # on one-node clusters nodelist will be empty after the removal
6059
    # if we proceed the backup would be removed because OpQueryExports
6060
    # substitutes an empty list with the full cluster node list.
6061
    if nodelist:
6062
      exportlist = self.rpc.call_export_list(nodelist)
6063
      for node in exportlist:
6064
        if exportlist[node].failed:
6065
          continue
6066
        if instance.name in exportlist[node].data:
6067
          if not self.rpc.call_export_remove(node, instance.name):
6068
            self.LogWarning("Could not remove older export for instance %s"
6069
                            " on node %s", instance.name, node)
6070

    
6071

    
6072
class LURemoveExport(NoHooksLU):
6073
  """Remove exports related to the named instance.
6074

6075
  """
6076
  _OP_REQP = ["instance_name"]
6077
  REQ_BGL = False
6078

    
6079
  def ExpandNames(self):
6080
    self.needed_locks = {}
6081
    # We need all nodes to be locked in order for RemoveExport to work, but we
6082
    # don't need to lock the instance itself, as nothing will happen to it (and
6083
    # we can remove exports also for a removed instance)
6084
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6085

    
6086
  def CheckPrereq(self):
6087
    """Check prerequisites.
6088
    """
6089
    pass
6090

    
6091
  def Exec(self, feedback_fn):
6092
    """Remove any export.
6093

6094
    """
6095
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
6096
    # If the instance was not found we'll try with the name that was passed in.
6097
    # This will only work if it was an FQDN, though.
6098
    fqdn_warn = False
6099
    if not instance_name:
6100
      fqdn_warn = True
6101
      instance_name = self.op.instance_name
6102

    
6103
    exportlist = self.rpc.call_export_list(self.acquired_locks[
6104
      locking.LEVEL_NODE])
6105
    found = False
6106
    for node in exportlist:
6107
      if exportlist[node].failed:
6108
        self.LogWarning("Failed to query node %s, continuing" % node)
6109
        continue
6110
      if instance_name in exportlist[node].data:
6111
        found = True
6112
        result = self.rpc.call_export_remove(node, instance_name)
6113
        if result.failed or not result.data:
6114
          logging.error("Could not remove export for instance %s"
6115
                        " on node %s", instance_name, node)
6116

    
6117
    if fqdn_warn and not found:
6118
      feedback_fn("Export not found. If trying to remove an export belonging"
6119
                  " to a deleted instance please use its Fully Qualified"
6120
                  " Domain Name.")
6121

    
6122

    
6123
class TagsLU(NoHooksLU):
6124
  """Generic tags LU.
6125

6126
  This is an abstract class which is the parent of all the other tags LUs.
6127

6128
  """
6129

    
6130
  def ExpandNames(self):
6131
    self.needed_locks = {}
6132
    if self.op.kind == constants.TAG_NODE:
6133
      name = self.cfg.ExpandNodeName(self.op.name)
6134
      if name is None:
6135
        raise errors.OpPrereqError("Invalid node name (%s)" %
6136
                                   (self.op.name,))
6137
      self.op.name = name
6138
      self.needed_locks[locking.LEVEL_NODE] = name
6139
    elif self.op.kind == constants.TAG_INSTANCE:
6140
      name = self.cfg.ExpandInstanceName(self.op.name)
6141
      if name is None:
6142
        raise errors.OpPrereqError("Invalid instance name (%s)" %
6143
                                   (self.op.name,))
6144
      self.op.name = name
6145
      self.needed_locks[locking.LEVEL_INSTANCE] = name
6146

    
6147
  def CheckPrereq(self):
6148
    """Check prerequisites.
6149

6150
    """
6151
    if self.op.kind == constants.TAG_CLUSTER:
6152
      self.target = self.cfg.GetClusterInfo()
6153
    elif self.op.kind == constants.TAG_NODE:
6154
      self.target = self.cfg.GetNodeInfo(self.op.name)
6155
    elif self.op.kind == constants.TAG_INSTANCE:
6156
      self.target = self.cfg.GetInstanceInfo(self.op.name)
6157
    else:
6158
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
6159
                                 str(self.op.kind))
6160

    
6161

    
6162
class LUGetTags(TagsLU):
6163
  """Returns the tags of a given object.
6164

6165
  """
6166
  _OP_REQP = ["kind", "name"]
6167
  REQ_BGL = False
6168

    
6169
  def Exec(self, feedback_fn):
6170
    """Returns the tag list.
6171

6172
    """
6173
    return list(self.target.GetTags())
6174

    
6175

    
6176
class LUSearchTags(NoHooksLU):
6177
  """Searches the tags for a given pattern.
6178

6179
  """
6180
  _OP_REQP = ["pattern"]
6181
  REQ_BGL = False
6182

    
6183
  def ExpandNames(self):
6184
    self.needed_locks = {}
6185

    
6186
  def CheckPrereq(self):
6187
    """Check prerequisites.
6188

6189
    This checks the pattern passed for validity by compiling it.
6190

6191
    """
6192
    try:
6193
      self.re = re.compile(self.op.pattern)
6194
    except re.error, err:
6195
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
6196
                                 (self.op.pattern, err))
6197

    
6198
  def Exec(self, feedback_fn):
6199
    """Returns the tag list.
6200

6201
    """
6202
    cfg = self.cfg
6203
    tgts = [("/cluster", cfg.GetClusterInfo())]
6204
    ilist = cfg.GetAllInstancesInfo().values()
6205
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
6206
    nlist = cfg.GetAllNodesInfo().values()
6207
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
6208
    results = []
6209
    for path, target in tgts:
6210
      for tag in target.GetTags():
6211
        if self.re.search(tag):
6212
          results.append((path, tag))
6213
    return results
6214

    
6215

    
6216
class LUAddTags(TagsLU):
6217
  """Sets a tag on a given object.
6218

6219
  """
6220
  _OP_REQP = ["kind", "name", "tags"]
6221
  REQ_BGL = False
6222

    
6223
  def CheckPrereq(self):
6224
    """Check prerequisites.
6225

6226
    This checks the type and length of the tag name and value.
6227

6228
    """
6229
    TagsLU.CheckPrereq(self)
6230
    for tag in self.op.tags:
6231
      objects.TaggableObject.ValidateTag(tag)
6232

    
6233
  def Exec(self, feedback_fn):
6234
    """Sets the tag.
6235

6236
    """
6237
    try:
6238
      for tag in self.op.tags:
6239
        self.target.AddTag(tag)
6240
    except errors.TagError, err:
6241
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
6242
    try:
6243
      self.cfg.Update(self.target)
6244
    except errors.ConfigurationError:
6245
      raise errors.OpRetryError("There has been a modification to the"
6246
                                " config file and the operation has been"
6247
                                " aborted. Please retry.")
6248

    
6249

    
6250
class LUDelTags(TagsLU):
6251
  """Delete a list of tags from a given object.
6252

6253
  """
6254
  _OP_REQP = ["kind", "name", "tags"]
6255
  REQ_BGL = False
6256

    
6257
  def CheckPrereq(self):
6258
    """Check prerequisites.
6259

6260
    This checks that we have the given tag.
6261

6262
    """
6263
    TagsLU.CheckPrereq(self)
6264
    for tag in self.op.tags:
6265
      objects.TaggableObject.ValidateTag(tag)
6266
    del_tags = frozenset(self.op.tags)
6267
    cur_tags = self.target.GetTags()
6268
    if not del_tags <= cur_tags:
6269
      diff_tags = del_tags - cur_tags
6270
      diff_names = ["'%s'" % tag for tag in diff_tags]
6271
      diff_names.sort()
6272
      raise errors.OpPrereqError("Tag(s) %s not found" %
6273
                                 (",".join(diff_names)))
6274

    
6275
  def Exec(self, feedback_fn):
6276
    """Remove the tag from the object.
6277

6278
    """
6279
    for tag in self.op.tags:
6280
      self.target.RemoveTag(tag)
6281
    try:
6282
      self.cfg.Update(self.target)
6283
    except errors.ConfigurationError:
6284
      raise errors.OpRetryError("There has been a modification to the"
6285
                                " config file and the operation has been"
6286
                                " aborted. Please retry.")
6287

    
6288

    
6289
class LUTestDelay(NoHooksLU):
6290
  """Sleep for a specified amount of time.
6291

6292
  This LU sleeps on the master and/or nodes for a specified amount of
6293
  time.
6294

6295
  """
6296
  _OP_REQP = ["duration", "on_master", "on_nodes"]
6297
  REQ_BGL = False
6298

    
6299
  def ExpandNames(self):
6300
    """Expand names and set required locks.
6301

6302
    This expands the node list, if any.
6303

6304
    """
6305
    self.needed_locks = {}
6306
    if self.op.on_nodes:
6307
      # _GetWantedNodes can be used here, but is not always appropriate to use
6308
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
6309
      # more information.
6310
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
6311
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
6312

    
6313
  def CheckPrereq(self):
6314
    """Check prerequisites.
6315

6316
    """
6317

    
6318
  def Exec(self, feedback_fn):
6319
    """Do the actual sleep.
6320

6321
    """
6322
    if self.op.on_master:
6323
      if not utils.TestDelay(self.op.duration):
6324
        raise errors.OpExecError("Error during master delay test")
6325
    if self.op.on_nodes:
6326
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
6327
      if not result:
6328
        raise errors.OpExecError("Complete failure from rpc call")
6329
      for node, node_result in result.items():
6330
        node_result.Raise()
6331
        if not node_result.data:
6332
          raise errors.OpExecError("Failure during rpc call to node %s,"
6333
                                   " result: %s" % (node, node_result.data))
6334

    
6335

    
6336
class IAllocator(object):
6337
  """IAllocator framework.
6338

6339
  An IAllocator instance has three sets of attributes:
6340
    - cfg that is needed to query the cluster
6341
    - input data (all members of the _KEYS class attribute are required)
6342
    - four buffer attributes (in|out_data|text), that represent the
6343
      input (to the external script) in text and data structure format,
6344
      and the output from it, again in two formats
6345
    - the result variables from the script (success, info, nodes) for
6346
      easy usage
6347

6348
  """
6349
  _ALLO_KEYS = [
6350
    "mem_size", "disks", "disk_template",
6351
    "os", "tags", "nics", "vcpus", "hypervisor",
6352
    ]
6353
  _RELO_KEYS = [
6354
    "relocate_from",
6355
    ]
6356

    
6357
  def __init__(self, lu, mode, name, **kwargs):
6358
    self.lu = lu
6359
    # init buffer variables
6360
    self.in_text = self.out_text = self.in_data = self.out_data = None
6361
    # init all input fields so that pylint is happy
6362
    self.mode = mode
6363
    self.name = name
6364
    self.mem_size = self.disks = self.disk_template = None
6365
    self.os = self.tags = self.nics = self.vcpus = None
6366
    self.hypervisor = None
6367
    self.relocate_from = None
6368
    # computed fields
6369
    self.required_nodes = None
6370
    # init result fields
6371
    self.success = self.info = self.nodes = None
6372
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6373
      keyset = self._ALLO_KEYS
6374
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
6375
      keyset = self._RELO_KEYS
6376
    else:
6377
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
6378
                                   " IAllocator" % self.mode)
6379
    for key in kwargs:
6380
      if key not in keyset:
6381
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
6382
                                     " IAllocator" % key)
6383
      setattr(self, key, kwargs[key])
6384
    for key in keyset:
6385
      if key not in kwargs:
6386
        raise errors.ProgrammerError("Missing input parameter '%s' to"
6387
                                     " IAllocator" % key)
6388
    self._BuildInputData()
6389

    
6390
  def _ComputeClusterData(self):
6391
    """Compute the generic allocator input data.
6392

6393
    This is the data that is independent of the actual operation.
6394

6395
    """
6396
    cfg = self.lu.cfg
6397
    cluster_info = cfg.GetClusterInfo()
6398
    # cluster data
6399
    data = {
6400
      "version": 1,
6401
      "cluster_name": cfg.GetClusterName(),
6402
      "cluster_tags": list(cluster_info.GetTags()),
6403
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
6404
      # we don't have job IDs
6405
      }
6406
    iinfo = cfg.GetAllInstancesInfo().values()
6407
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
6408

    
6409
    # node data
6410
    node_results = {}
6411
    node_list = cfg.GetNodeList()
6412

    
6413
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6414
      hypervisor_name = self.hypervisor
6415
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
6416
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
6417

    
6418
    node_data = self.lu.rpc.call_node_info(node_list, cfg.GetVGName(),
6419
                                           hypervisor_name)
6420
    node_iinfo = self.lu.rpc.call_all_instances_info(node_list,
6421
                       cluster_info.enabled_hypervisors)
6422
    for nname, nresult in node_data.items():
6423
      # first fill in static (config-based) values
6424
      ninfo = cfg.GetNodeInfo(nname)
6425
      pnr = {
6426
        "tags": list(ninfo.GetTags()),
6427
        "primary_ip": ninfo.primary_ip,
6428
        "secondary_ip": ninfo.secondary_ip,
6429
        "offline": ninfo.offline,
6430
        "master_candidate": ninfo.master_candidate,
6431
        }
6432

    
6433
      if not ninfo.offline:
6434
        nresult.Raise()
6435
        if not isinstance(nresult.data, dict):
6436
          raise errors.OpExecError("Can't get data for node %s" % nname)
6437
        remote_info = nresult.data
6438
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
6439
                     'vg_size', 'vg_free', 'cpu_total']:
6440
          if attr not in remote_info:
6441
            raise errors.OpExecError("Node '%s' didn't return attribute"
6442
                                     " '%s'" % (nname, attr))
6443
          try:
6444
            remote_info[attr] = int(remote_info[attr])
6445
          except ValueError, err:
6446
            raise errors.OpExecError("Node '%s' returned invalid value"
6447
                                     " for '%s': %s" % (nname, attr, err))
6448
        # compute memory used by primary instances
6449
        i_p_mem = i_p_up_mem = 0
6450
        for iinfo, beinfo in i_list:
6451
          if iinfo.primary_node == nname:
6452
            i_p_mem += beinfo[constants.BE_MEMORY]
6453
            if iinfo.name not in node_iinfo[nname].data:
6454
              i_used_mem = 0
6455
            else:
6456
              i_used_mem = int(node_iinfo[nname].data[iinfo.name]['memory'])
6457
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
6458
            remote_info['memory_free'] -= max(0, i_mem_diff)
6459

    
6460
            if iinfo.admin_up:
6461
              i_p_up_mem += beinfo[constants.BE_MEMORY]
6462

    
6463
        # compute memory used by instances
6464
        pnr_dyn = {
6465
          "total_memory": remote_info['memory_total'],
6466
          "reserved_memory": remote_info['memory_dom0'],
6467
          "free_memory": remote_info['memory_free'],
6468
          "total_disk": remote_info['vg_size'],
6469
          "free_disk": remote_info['vg_free'],
6470
          "total_cpus": remote_info['cpu_total'],
6471
          "i_pri_memory": i_p_mem,
6472
          "i_pri_up_memory": i_p_up_mem,
6473
          }
6474
        pnr.update(pnr_dyn)
6475

    
6476
      node_results[nname] = pnr
6477
    data["nodes"] = node_results
6478

    
6479
    # instance data
6480
    instance_data = {}
6481
    for iinfo, beinfo in i_list:
6482
      nic_data = [{"mac": n.mac, "ip": n.ip, "bridge": n.bridge}
6483
                  for n in iinfo.nics]
6484
      pir = {
6485
        "tags": list(iinfo.GetTags()),
6486
        "admin_up": iinfo.admin_up,
6487
        "vcpus": beinfo[constants.BE_VCPUS],
6488
        "memory": beinfo[constants.BE_MEMORY],
6489
        "os": iinfo.os,
6490
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
6491
        "nics": nic_data,
6492
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
6493
        "disk_template": iinfo.disk_template,
6494
        "hypervisor": iinfo.hypervisor,
6495
        }
6496
      instance_data[iinfo.name] = pir
6497

    
6498
    data["instances"] = instance_data
6499

    
6500
    self.in_data = data
6501

    
6502
  def _AddNewInstance(self):
6503
    """Add new instance data to allocator structure.
6504

6505
    This in combination with _AllocatorGetClusterData will create the
6506
    correct structure needed as input for the allocator.
6507

6508
    The checks for the completeness of the opcode must have already been
6509
    done.
6510

6511
    """
6512
    data = self.in_data
6513

    
6514
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
6515

    
6516
    if self.disk_template in constants.DTS_NET_MIRROR:
6517
      self.required_nodes = 2
6518
    else:
6519
      self.required_nodes = 1
6520
    request = {
6521
      "type": "allocate",
6522
      "name": self.name,
6523
      "disk_template": self.disk_template,
6524
      "tags": self.tags,
6525
      "os": self.os,
6526
      "vcpus": self.vcpus,
6527
      "memory": self.mem_size,
6528
      "disks": self.disks,
6529
      "disk_space_total": disk_space,
6530
      "nics": self.nics,
6531
      "required_nodes": self.required_nodes,
6532
      }
6533
    data["request"] = request
6534

    
6535
  def _AddRelocateInstance(self):
6536
    """Add relocate instance data to allocator structure.
6537

6538
    This in combination with _IAllocatorGetClusterData will create the
6539
    correct structure needed as input for the allocator.
6540

6541
    The checks for the completeness of the opcode must have already been
6542
    done.
6543

6544
    """
6545
    instance = self.lu.cfg.GetInstanceInfo(self.name)
6546
    if instance is None:
6547
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
6548
                                   " IAllocator" % self.name)
6549

    
6550
    if instance.disk_template not in constants.DTS_NET_MIRROR:
6551
      raise errors.OpPrereqError("Can't relocate non-mirrored instances")
6552

    
6553
    if len(instance.secondary_nodes) != 1:
6554
      raise errors.OpPrereqError("Instance has not exactly one secondary node")
6555

    
6556
    self.required_nodes = 1
6557
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
6558
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
6559

    
6560
    request = {
6561
      "type": "relocate",
6562
      "name": self.name,
6563
      "disk_space_total": disk_space,
6564
      "required_nodes": self.required_nodes,
6565
      "relocate_from": self.relocate_from,
6566
      }
6567
    self.in_data["request"] = request
6568

    
6569
  def _BuildInputData(self):
6570
    """Build input data structures.
6571

6572
    """
6573
    self._ComputeClusterData()
6574

    
6575
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6576
      self._AddNewInstance()
6577
    else:
6578
      self._AddRelocateInstance()
6579

    
6580
    self.in_text = serializer.Dump(self.in_data)
6581

    
6582
  def Run(self, name, validate=True, call_fn=None):
6583
    """Run an instance allocator and return the results.
6584

6585
    """
6586
    if call_fn is None:
6587
      call_fn = self.lu.rpc.call_iallocator_runner
6588
    data = self.in_text
6589

    
6590
    result = call_fn(self.lu.cfg.GetMasterNode(), name, self.in_text)
6591
    result.Raise()
6592

    
6593
    if not isinstance(result.data, (list, tuple)) or len(result.data) != 4:
6594
      raise errors.OpExecError("Invalid result from master iallocator runner")
6595

    
6596
    rcode, stdout, stderr, fail = result.data
6597

    
6598
    if rcode == constants.IARUN_NOTFOUND:
6599
      raise errors.OpExecError("Can't find allocator '%s'" % name)
6600
    elif rcode == constants.IARUN_FAILURE:
6601
      raise errors.OpExecError("Instance allocator call failed: %s,"
6602
                               " output: %s" % (fail, stdout+stderr))
6603
    self.out_text = stdout
6604
    if validate:
6605
      self._ValidateResult()
6606

    
6607
  def _ValidateResult(self):
6608
    """Process the allocator results.
6609

6610
    This will process and if successful save the result in
6611
    self.out_data and the other parameters.
6612

6613
    """
6614
    try:
6615
      rdict = serializer.Load(self.out_text)
6616
    except Exception, err:
6617
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
6618

    
6619
    if not isinstance(rdict, dict):
6620
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
6621

    
6622
    for key in "success", "info", "nodes":
6623
      if key not in rdict:
6624
        raise errors.OpExecError("Can't parse iallocator results:"
6625
                                 " missing key '%s'" % key)
6626
      setattr(self, key, rdict[key])
6627

    
6628
    if not isinstance(rdict["nodes"], list):
6629
      raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
6630
                               " is not a list")
6631
    self.out_data = rdict
6632

    
6633

    
6634
class LUTestAllocator(NoHooksLU):
6635
  """Run allocator tests.
6636

6637
  This LU runs the allocator tests
6638

6639
  """
6640
  _OP_REQP = ["direction", "mode", "name"]
6641

    
6642
  def CheckPrereq(self):
6643
    """Check prerequisites.
6644

6645
    This checks the opcode parameters depending on the director and mode test.
6646

6647
    """
6648
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
6649
      for attr in ["name", "mem_size", "disks", "disk_template",
6650
                   "os", "tags", "nics", "vcpus"]:
6651
        if not hasattr(self.op, attr):
6652
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
6653
                                     attr)
6654
      iname = self.cfg.ExpandInstanceName(self.op.name)
6655
      if iname is not None:
6656
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
6657
                                   iname)
6658
      if not isinstance(self.op.nics, list):
6659
        raise errors.OpPrereqError("Invalid parameter 'nics'")
6660
      for row in self.op.nics:
6661
        if (not isinstance(row, dict) or
6662
            "mac" not in row or
6663
            "ip" not in row or
6664
            "bridge" not in row):
6665
          raise errors.OpPrereqError("Invalid contents of the"
6666
                                     " 'nics' parameter")
6667
      if not isinstance(self.op.disks, list):
6668
        raise errors.OpPrereqError("Invalid parameter 'disks'")
6669
      for row in self.op.disks:
6670
        if (not isinstance(row, dict) or
6671
            "size" not in row or
6672
            not isinstance(row["size"], int) or
6673
            "mode" not in row or
6674
            row["mode"] not in ['r', 'w']):
6675
          raise errors.OpPrereqError("Invalid contents of the"
6676
                                     " 'disks' parameter")
6677
      if not hasattr(self.op, "hypervisor") or self.op.hypervisor is None:
6678
        self.op.hypervisor = self.cfg.GetHypervisorType()
6679
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
6680
      if not hasattr(self.op, "name"):
6681
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input")
6682
      fname = self.cfg.ExpandInstanceName(self.op.name)
6683
      if fname is None:
6684
        raise errors.OpPrereqError("Instance '%s' not found for relocation" %
6685
                                   self.op.name)
6686
      self.op.name = fname
6687
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
6688
    else:
6689
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
6690
                                 self.op.mode)
6691

    
6692
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
6693
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
6694
        raise errors.OpPrereqError("Missing allocator name")
6695
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
6696
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
6697
                                 self.op.direction)
6698

    
6699
  def Exec(self, feedback_fn):
6700
    """Run the allocator test.
6701

6702
    """
6703
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
6704
      ial = IAllocator(self,
6705
                       mode=self.op.mode,
6706
                       name=self.op.name,
6707
                       mem_size=self.op.mem_size,
6708
                       disks=self.op.disks,
6709
                       disk_template=self.op.disk_template,
6710
                       os=self.op.os,
6711
                       tags=self.op.tags,
6712
                       nics=self.op.nics,
6713
                       vcpus=self.op.vcpus,
6714
                       hypervisor=self.op.hypervisor,
6715
                       )
6716
    else:
6717
      ial = IAllocator(self,
6718
                       mode=self.op.mode,
6719
                       name=self.op.name,
6720
                       relocate_from=list(self.relocate_from),
6721
                       )
6722

    
6723
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
6724
      result = ial.in_text
6725
    else:
6726
      ial.Run(self.op.allocator, validate=False)
6727
      result = ial.out_text
6728
    return result