Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ d1dc3548

History | View | Annotate | Download (218.2 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 = lu.cfg.GetInstanceList()
396
  return utils.NiceSort(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: string
459
  @param status: the desired status of the instances
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
  env = {
472
    "OP_TARGET": name,
473
    "INSTANCE_NAME": name,
474
    "INSTANCE_PRIMARY": primary_node,
475
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
476
    "INSTANCE_OS_TYPE": os_type,
477
    "INSTANCE_STATUS": status,
478
    "INSTANCE_MEMORY": memory,
479
    "INSTANCE_VCPUS": vcpus,
480
  }
481

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

    
493
  env["INSTANCE_NIC_COUNT"] = nic_count
494

    
495
  return env
496

    
497

    
498
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
499
  """Builds instance related env variables for hooks from an object.
500

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

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

    
528

    
529
def _AdjustCandidatePool(lu):
530
  """Adjust the candidate pool after node operations.
531

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

    
544

    
545
def _CheckInstanceBridgesExist(lu, instance):
546
  """Check that the brigdes needed by an instance exist.
547

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

    
558

    
559
class LUDestroyCluster(NoHooksLU):
560
  """Logical unit for destroying the cluster.
561

562
  """
563
  _OP_REQP = []
564

    
565
  def CheckPrereq(self):
566
    """Check prerequisites.
567

568
    This checks whether the cluster is empty.
569

570
    Any errors are signalled by raising errors.OpPrereqError.
571

572
    """
573
    master = self.cfg.GetMasterNode()
574

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

    
584
  def Exec(self, feedback_fn):
585
    """Destroys the cluster.
586

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

    
598

    
599
class LUVerifyCluster(LogicalUnit):
600
  """Verifies the cluster status.
601

602
  """
603
  HPATH = "cluster-verify"
604
  HTYPE = constants.HTYPE_CLUSTER
605
  _OP_REQP = ["skip_checks"]
606
  REQ_BGL = False
607

    
608
  def ExpandNames(self):
609
    self.needed_locks = {
610
      locking.LEVEL_NODE: locking.ALL_SET,
611
      locking.LEVEL_INSTANCE: locking.ALL_SET,
612
    }
613
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
614

    
615
  def _VerifyNode(self, nodeinfo, file_list, local_cksum,
616
                  node_result, feedback_fn, master_files):
617
    """Run multiple tests against a node.
618

619
    Test list:
620

621
      - compares ganeti version
622
      - checks vg existance and size > 20G
623
      - checks config file checksum
624
      - checks ssh to other nodes
625

626
    @type nodeinfo: L{objects.Node}
627
    @param nodeinfo: the node to check
628
    @param file_list: required list of files
629
    @param local_cksum: dictionary of local files and their checksums
630
    @param node_result: the results from the node
631
    @param feedback_fn: function used to accumulate results
632
    @param master_files: list of files that only masters should have
633

634
    """
635
    node = nodeinfo.name
636

    
637
    # main result, node_result should be a non-empty dict
638
    if not node_result or not isinstance(node_result, dict):
639
      feedback_fn("  - ERROR: unable to verify node %s." % (node,))
640
      return True
641

    
642
    # compares ganeti version
643
    local_version = constants.PROTOCOL_VERSION
644
    remote_version = node_result.get('version', None)
645
    if not remote_version:
646
      feedback_fn("  - ERROR: connection to %s failed" % (node))
647
      return True
648

    
649
    if local_version != remote_version:
650
      feedback_fn("  - ERROR: sw version mismatch: master %s, node(%s) %s" %
651
                      (local_version, node, remote_version))
652
      return True
653

    
654
    # checks vg existance and size > 20G
655

    
656
    bad = False
657
    vglist = node_result.get(constants.NV_VGLIST, None)
658
    if not vglist:
659
      feedback_fn("  - ERROR: unable to check volume groups on node %s." %
660
                      (node,))
661
      bad = True
662
    else:
663
      vgstatus = utils.CheckVolumeGroupSize(vglist, self.cfg.GetVGName(),
664
                                            constants.MIN_VG_SIZE)
665
      if vgstatus:
666
        feedback_fn("  - ERROR: %s on node %s" % (vgstatus, node))
667
        bad = True
668

    
669
    # checks config file checksum
670

    
671
    remote_cksum = node_result.get(constants.NV_FILELIST, None)
672
    if not isinstance(remote_cksum, dict):
673
      bad = True
674
      feedback_fn("  - ERROR: node hasn't returned file checksum data")
675
    else:
676
      for file_name in file_list:
677
        node_is_mc = nodeinfo.master_candidate
678
        must_have_file = file_name not in master_files
679
        if file_name not in remote_cksum:
680
          if node_is_mc or must_have_file:
681
            bad = True
682
            feedback_fn("  - ERROR: file '%s' missing" % file_name)
683
        elif remote_cksum[file_name] != local_cksum[file_name]:
684
          if node_is_mc or must_have_file:
685
            bad = True
686
            feedback_fn("  - ERROR: file '%s' has wrong checksum" % file_name)
687
          else:
688
            # not candidate and this is not a must-have file
689
            bad = True
690
            feedback_fn("  - ERROR: non master-candidate has old/wrong file"
691
                        " '%s'" % file_name)
692
        else:
693
          # all good, except non-master/non-must have combination
694
          if not node_is_mc and not must_have_file:
695
            feedback_fn("  - ERROR: file '%s' should not exist on non master"
696
                        " candidates" % file_name)
697

    
698
    # checks ssh to any
699

    
700
    if constants.NV_NODELIST not in node_result:
701
      bad = True
702
      feedback_fn("  - ERROR: node hasn't returned node ssh connectivity data")
703
    else:
704
      if node_result[constants.NV_NODELIST]:
705
        bad = True
706
        for node in node_result[constants.NV_NODELIST]:
707
          feedback_fn("  - ERROR: ssh communication with node '%s': %s" %
708
                          (node, node_result[constants.NV_NODELIST][node]))
709

    
710
    if constants.NV_NODENETTEST not in node_result:
711
      bad = True
712
      feedback_fn("  - ERROR: node hasn't returned node tcp connectivity data")
713
    else:
714
      if node_result[constants.NV_NODENETTEST]:
715
        bad = True
716
        nlist = utils.NiceSort(node_result[constants.NV_NODENETTEST].keys())
717
        for node in nlist:
718
          feedback_fn("  - ERROR: tcp communication with node '%s': %s" %
719
                          (node, node_result[constants.NV_NODENETTEST][node]))
720

    
721
    hyp_result = node_result.get(constants.NV_HYPERVISOR, None)
722
    if isinstance(hyp_result, dict):
723
      for hv_name, hv_result in hyp_result.iteritems():
724
        if hv_result is not None:
725
          feedback_fn("  - ERROR: hypervisor %s verify failure: '%s'" %
726
                      (hv_name, hv_result))
727
    return bad
728

    
729
  def _VerifyInstance(self, instance, instanceconfig, node_vol_is,
730
                      node_instance, feedback_fn, n_offline):
731
    """Verify an instance.
732

733
    This function checks to see if the required block devices are
734
    available on the instance's node.
735

736
    """
737
    bad = False
738

    
739
    node_current = instanceconfig.primary_node
740

    
741
    node_vol_should = {}
742
    instanceconfig.MapLVsByNode(node_vol_should)
743

    
744
    for node in node_vol_should:
745
      if node in n_offline:
746
        # ignore missing volumes on offline nodes
747
        continue
748
      for volume in node_vol_should[node]:
749
        if node not in node_vol_is or volume not in node_vol_is[node]:
750
          feedback_fn("  - ERROR: volume %s missing on node %s" %
751
                          (volume, node))
752
          bad = True
753

    
754
    if not instanceconfig.status == 'down':
755
      if ((node_current not in node_instance or
756
          not instance in node_instance[node_current]) and
757
          node_current not in n_offline):
758
        feedback_fn("  - ERROR: instance %s not running on node %s" %
759
                        (instance, node_current))
760
        bad = True
761

    
762
    for node in node_instance:
763
      if (not node == node_current):
764
        if instance in node_instance[node]:
765
          feedback_fn("  - ERROR: instance %s should not run on node %s" %
766
                          (instance, node))
767
          bad = True
768

    
769
    return bad
770

    
771
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is, feedback_fn):
772
    """Verify if there are any unknown volumes in the cluster.
773

774
    The .os, .swap and backup volumes are ignored. All other volumes are
775
    reported as unknown.
776

777
    """
778
    bad = False
779

    
780
    for node in node_vol_is:
781
      for volume in node_vol_is[node]:
782
        if node not in node_vol_should or volume not in node_vol_should[node]:
783
          feedback_fn("  - ERROR: volume %s on node %s should not exist" %
784
                      (volume, node))
785
          bad = True
786
    return bad
787

    
788
  def _VerifyOrphanInstances(self, instancelist, node_instance, feedback_fn):
789
    """Verify the list of running instances.
790

791
    This checks what instances are running but unknown to the cluster.
792

793
    """
794
    bad = False
795
    for node in node_instance:
796
      for runninginstance in node_instance[node]:
797
        if runninginstance not in instancelist:
798
          feedback_fn("  - ERROR: instance %s on node %s should not exist" %
799
                          (runninginstance, node))
800
          bad = True
801
    return bad
802

    
803
  def _VerifyNPlusOneMemory(self, node_info, instance_cfg, feedback_fn):
804
    """Verify N+1 Memory Resilience.
805

806
    Check that if one single node dies we can still start all the instances it
807
    was primary for.
808

809
    """
810
    bad = False
811

    
812
    for node, nodeinfo in node_info.iteritems():
813
      # This code checks that every node which is now listed as secondary has
814
      # enough memory to host all instances it is supposed to should a single
815
      # other node in the cluster fail.
816
      # FIXME: not ready for failover to an arbitrary node
817
      # FIXME: does not support file-backed instances
818
      # WARNING: we currently take into account down instances as well as up
819
      # ones, considering that even if they're down someone might want to start
820
      # them even in the event of a node failure.
821
      for prinode, instances in nodeinfo['sinst-by-pnode'].iteritems():
822
        needed_mem = 0
823
        for instance in instances:
824
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
825
          if bep[constants.BE_AUTO_BALANCE]:
826
            needed_mem += bep[constants.BE_MEMORY]
827
        if nodeinfo['mfree'] < needed_mem:
828
          feedback_fn("  - ERROR: not enough memory on node %s to accomodate"
829
                      " failovers should node %s fail" % (node, prinode))
830
          bad = True
831
    return bad
832

    
833
  def CheckPrereq(self):
834
    """Check prerequisites.
835

836
    Transform the list of checks we're going to skip into a set and check that
837
    all its members are valid.
838

839
    """
840
    self.skip_set = frozenset(self.op.skip_checks)
841
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
842
      raise errors.OpPrereqError("Invalid checks to be skipped specified")
843

    
844
  def BuildHooksEnv(self):
845
    """Build hooks env.
846

847
    Cluster-Verify hooks just rone in the post phase and their failure makes
848
    the output be logged in the verify output and the verification to fail.
849

850
    """
851
    all_nodes = self.cfg.GetNodeList()
852
    # TODO: populate the environment with useful information for verify hooks
853
    env = {}
854
    return env, [], all_nodes
855

    
856
  def Exec(self, feedback_fn):
857
    """Verify integrity of cluster, performing various test on nodes.
858

859
    """
860
    bad = False
861
    feedback_fn("* Verifying global settings")
862
    for msg in self.cfg.VerifyConfig():
863
      feedback_fn("  - ERROR: %s" % msg)
864

    
865
    vg_name = self.cfg.GetVGName()
866
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
867
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
868
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
869
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
870
    i_non_redundant = [] # Non redundant instances
871
    i_non_a_balanced = [] # Non auto-balanced instances
872
    n_offline = [] # List of offline nodes
873
    node_volume = {}
874
    node_instance = {}
875
    node_info = {}
876
    instance_cfg = {}
877

    
878
    # FIXME: verify OS list
879
    # do local checksums
880
    master_files = [constants.CLUSTER_CONF_FILE]
881

    
882
    file_names = ssconf.SimpleStore().GetFileList()
883
    file_names.append(constants.SSL_CERT_FILE)
884
    file_names.extend(master_files)
885

    
886
    local_checksums = utils.FingerprintFiles(file_names)
887

    
888
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
889
    node_verify_param = {
890
      constants.NV_FILELIST: file_names,
891
      constants.NV_NODELIST: nodelist,
892
      constants.NV_HYPERVISOR: hypervisors,
893
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
894
                                  node.secondary_ip) for node in nodeinfo],
895
      constants.NV_LVLIST: vg_name,
896
      constants.NV_INSTANCELIST: hypervisors,
897
      constants.NV_VGLIST: None,
898
      constants.NV_VERSION: None,
899
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
900
      }
901
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
902
                                           self.cfg.GetClusterName())
903

    
904
    cluster = self.cfg.GetClusterInfo()
905
    master_node = self.cfg.GetMasterNode()
906
    for node_i in nodeinfo:
907
      node = node_i.name
908
      nresult = all_nvinfo[node].data
909

    
910
      if node_i.offline:
911
        feedback_fn("* Skipping offline node %s" % (node,))
912
        n_offline.append(node)
913
        continue
914

    
915
      if node == master_node:
916
        ntype = "master"
917
      elif node_i.master_candidate:
918
        ntype = "master candidate"
919
      else:
920
        ntype = "regular"
921
      feedback_fn("* Verifying node %s (%s)" % (node, ntype))
922

    
923
      if all_nvinfo[node].failed or not isinstance(nresult, dict):
924
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
925
        bad = True
926
        continue
927

    
928
      result = self._VerifyNode(node_i, file_names, local_checksums,
929
                                nresult, feedback_fn, master_files)
930
      bad = bad or result
931

    
932
      lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
933
      if isinstance(lvdata, basestring):
934
        feedback_fn("  - ERROR: LVM problem on node %s: %s" %
935
                    (node, lvdata.encode('string_escape')))
936
        bad = True
937
        node_volume[node] = {}
938
      elif not isinstance(lvdata, dict):
939
        feedback_fn("  - ERROR: connection to %s failed (lvlist)" % (node,))
940
        bad = True
941
        continue
942
      else:
943
        node_volume[node] = lvdata
944

    
945
      # node_instance
946
      idata = nresult.get(constants.NV_INSTANCELIST, None)
947
      if not isinstance(idata, list):
948
        feedback_fn("  - ERROR: connection to %s failed (instancelist)" %
949
                    (node,))
950
        bad = True
951
        continue
952

    
953
      node_instance[node] = idata
954

    
955
      # node_info
956
      nodeinfo = nresult.get(constants.NV_HVINFO, None)
957
      if not isinstance(nodeinfo, dict):
958
        feedback_fn("  - ERROR: connection to %s failed (hvinfo)" % (node,))
959
        bad = True
960
        continue
961

    
962
      try:
963
        node_info[node] = {
964
          "mfree": int(nodeinfo['memory_free']),
965
          "dfree": int(nresult[constants.NV_VGLIST][vg_name]),
966
          "pinst": [],
967
          "sinst": [],
968
          # dictionary holding all instances this node is secondary for,
969
          # grouped by their primary node. Each key is a cluster node, and each
970
          # value is a list of instances which have the key as primary and the
971
          # current node as secondary.  this is handy to calculate N+1 memory
972
          # availability if you can only failover from a primary to its
973
          # secondary.
974
          "sinst-by-pnode": {},
975
        }
976
      except ValueError:
977
        feedback_fn("  - ERROR: invalid value returned from node %s" % (node,))
978
        bad = True
979
        continue
980

    
981
    node_vol_should = {}
982

    
983
    for instance in instancelist:
984
      feedback_fn("* Verifying instance %s" % instance)
985
      inst_config = self.cfg.GetInstanceInfo(instance)
986
      result =  self._VerifyInstance(instance, inst_config, node_volume,
987
                                     node_instance, feedback_fn, n_offline)
988
      bad = bad or result
989
      inst_nodes_offline = []
990

    
991
      inst_config.MapLVsByNode(node_vol_should)
992

    
993
      instance_cfg[instance] = inst_config
994

    
995
      pnode = inst_config.primary_node
996
      if pnode in node_info:
997
        node_info[pnode]['pinst'].append(instance)
998
      elif pnode not in n_offline:
999
        feedback_fn("  - ERROR: instance %s, connection to primary node"
1000
                    " %s failed" % (instance, pnode))
1001
        bad = True
1002

    
1003
      if pnode in n_offline:
1004
        inst_nodes_offline.append(pnode)
1005

    
1006
      # If the instance is non-redundant we cannot survive losing its primary
1007
      # node, so we are not N+1 compliant. On the other hand we have no disk
1008
      # templates with more than one secondary so that situation is not well
1009
      # supported either.
1010
      # FIXME: does not support file-backed instances
1011
      if len(inst_config.secondary_nodes) == 0:
1012
        i_non_redundant.append(instance)
1013
      elif len(inst_config.secondary_nodes) > 1:
1014
        feedback_fn("  - WARNING: multiple secondaries for instance %s"
1015
                    % instance)
1016

    
1017
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1018
        i_non_a_balanced.append(instance)
1019

    
1020
      for snode in inst_config.secondary_nodes:
1021
        if snode in node_info:
1022
          node_info[snode]['sinst'].append(instance)
1023
          if pnode not in node_info[snode]['sinst-by-pnode']:
1024
            node_info[snode]['sinst-by-pnode'][pnode] = []
1025
          node_info[snode]['sinst-by-pnode'][pnode].append(instance)
1026
        elif snode not in n_offline:
1027
          feedback_fn("  - ERROR: instance %s, connection to secondary node"
1028
                      " %s failed" % (instance, snode))
1029
          bad = True
1030
        if snode in n_offline:
1031
          inst_nodes_offline.append(snode)
1032

    
1033
      if inst_nodes_offline:
1034
        # warn that the instance lives on offline nodes, and set bad=True
1035
        feedback_fn("  - ERROR: instance lives on offline node(s) %s" %
1036
                    ", ".join(inst_nodes_offline))
1037
        bad = True
1038

    
1039
    feedback_fn("* Verifying orphan volumes")
1040
    result = self._VerifyOrphanVolumes(node_vol_should, node_volume,
1041
                                       feedback_fn)
1042
    bad = bad or result
1043

    
1044
    feedback_fn("* Verifying remaining instances")
1045
    result = self._VerifyOrphanInstances(instancelist, node_instance,
1046
                                         feedback_fn)
1047
    bad = bad or result
1048

    
1049
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1050
      feedback_fn("* Verifying N+1 Memory redundancy")
1051
      result = self._VerifyNPlusOneMemory(node_info, instance_cfg, feedback_fn)
1052
      bad = bad or result
1053

    
1054
    feedback_fn("* Other Notes")
1055
    if i_non_redundant:
1056
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1057
                  % len(i_non_redundant))
1058

    
1059
    if i_non_a_balanced:
1060
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1061
                  % len(i_non_a_balanced))
1062

    
1063
    if n_offline:
1064
      feedback_fn("  - NOTICE: %d offline node(s) found." % len(n_offline))
1065

    
1066
    return not bad
1067

    
1068
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1069
    """Analize the post-hooks' result
1070

1071
    This method analyses the hook result, handles it, and sends some
1072
    nicely-formatted feedback back to the user.
1073

1074
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1075
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1076
    @param hooks_results: the results of the multi-node hooks rpc call
1077
    @param feedback_fn: function used send feedback back to the caller
1078
    @param lu_result: previous Exec result
1079
    @return: the new Exec result, based on the previous result
1080
        and hook results
1081

1082
    """
1083
    # We only really run POST phase hooks, and are only interested in
1084
    # their results
1085
    if phase == constants.HOOKS_PHASE_POST:
1086
      # Used to change hooks' output to proper indentation
1087
      indent_re = re.compile('^', re.M)
1088
      feedback_fn("* Hooks Results")
1089
      if not hooks_results:
1090
        feedback_fn("  - ERROR: general communication failure")
1091
        lu_result = 1
1092
      else:
1093
        for node_name in hooks_results:
1094
          show_node_header = True
1095
          res = hooks_results[node_name]
1096
          if res.failed or res.data is False or not isinstance(res.data, list):
1097
            if res.offline:
1098
              # no need to warn or set fail return value
1099
              continue
1100
            feedback_fn("    Communication failure in hooks execution")
1101
            lu_result = 1
1102
            continue
1103
          for script, hkr, output in res.data:
1104
            if hkr == constants.HKR_FAIL:
1105
              # The node header is only shown once, if there are
1106
              # failing hooks on that node
1107
              if show_node_header:
1108
                feedback_fn("  Node %s:" % node_name)
1109
                show_node_header = False
1110
              feedback_fn("    ERROR: Script %s failed, output:" % script)
1111
              output = indent_re.sub('      ', output)
1112
              feedback_fn("%s" % output)
1113
              lu_result = 1
1114

    
1115
      return lu_result
1116

    
1117

    
1118
class LUVerifyDisks(NoHooksLU):
1119
  """Verifies the cluster disks status.
1120

1121
  """
1122
  _OP_REQP = []
1123
  REQ_BGL = False
1124

    
1125
  def ExpandNames(self):
1126
    self.needed_locks = {
1127
      locking.LEVEL_NODE: locking.ALL_SET,
1128
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1129
    }
1130
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
1131

    
1132
  def CheckPrereq(self):
1133
    """Check prerequisites.
1134

1135
    This has no prerequisites.
1136

1137
    """
1138
    pass
1139

    
1140
  def Exec(self, feedback_fn):
1141
    """Verify integrity of cluster disks.
1142

1143
    """
1144
    result = res_nodes, res_nlvm, res_instances, res_missing = [], {}, [], {}
1145

    
1146
    vg_name = self.cfg.GetVGName()
1147
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1148
    instances = [self.cfg.GetInstanceInfo(name)
1149
                 for name in self.cfg.GetInstanceList()]
1150

    
1151
    nv_dict = {}
1152
    for inst in instances:
1153
      inst_lvs = {}
1154
      if (inst.status != "up" or
1155
          inst.disk_template not in constants.DTS_NET_MIRROR):
1156
        continue
1157
      inst.MapLVsByNode(inst_lvs)
1158
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1159
      for node, vol_list in inst_lvs.iteritems():
1160
        for vol in vol_list:
1161
          nv_dict[(node, vol)] = inst
1162

    
1163
    if not nv_dict:
1164
      return result
1165

    
1166
    node_lvs = self.rpc.call_volume_list(nodes, vg_name)
1167

    
1168
    to_act = set()
1169
    for node in nodes:
1170
      # node_volume
1171
      lvs = node_lvs[node]
1172
      if lvs.failed:
1173
        if not lvs.offline:
1174
          self.LogWarning("Connection to node %s failed: %s" %
1175
                          (node, lvs.data))
1176
        continue
1177
      lvs = lvs.data
1178
      if isinstance(lvs, basestring):
1179
        logging.warning("Error enumerating LVs on node %s: %s", node, lvs)
1180
        res_nlvm[node] = lvs
1181
      elif not isinstance(lvs, dict):
1182
        logging.warning("Connection to node %s failed or invalid data"
1183
                        " returned", node)
1184
        res_nodes.append(node)
1185
        continue
1186

    
1187
      for lv_name, (_, lv_inactive, lv_online) in lvs.iteritems():
1188
        inst = nv_dict.pop((node, lv_name), None)
1189
        if (not lv_online and inst is not None
1190
            and inst.name not in res_instances):
1191
          res_instances.append(inst.name)
1192

    
1193
    # any leftover items in nv_dict are missing LVs, let's arrange the
1194
    # data better
1195
    for key, inst in nv_dict.iteritems():
1196
      if inst.name not in res_missing:
1197
        res_missing[inst.name] = []
1198
      res_missing[inst.name].append(key)
1199

    
1200
    return result
1201

    
1202

    
1203
class LURenameCluster(LogicalUnit):
1204
  """Rename the cluster.
1205

1206
  """
1207
  HPATH = "cluster-rename"
1208
  HTYPE = constants.HTYPE_CLUSTER
1209
  _OP_REQP = ["name"]
1210

    
1211
  def BuildHooksEnv(self):
1212
    """Build hooks env.
1213

1214
    """
1215
    env = {
1216
      "OP_TARGET": self.cfg.GetClusterName(),
1217
      "NEW_NAME": self.op.name,
1218
      }
1219
    mn = self.cfg.GetMasterNode()
1220
    return env, [mn], [mn]
1221

    
1222
  def CheckPrereq(self):
1223
    """Verify that the passed name is a valid one.
1224

1225
    """
1226
    hostname = utils.HostInfo(self.op.name)
1227

    
1228
    new_name = hostname.name
1229
    self.ip = new_ip = hostname.ip
1230
    old_name = self.cfg.GetClusterName()
1231
    old_ip = self.cfg.GetMasterIP()
1232
    if new_name == old_name and new_ip == old_ip:
1233
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1234
                                 " cluster has changed")
1235
    if new_ip != old_ip:
1236
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1237
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1238
                                   " reachable on the network. Aborting." %
1239
                                   new_ip)
1240

    
1241
    self.op.name = new_name
1242

    
1243
  def Exec(self, feedback_fn):
1244
    """Rename the cluster.
1245

1246
    """
1247
    clustername = self.op.name
1248
    ip = self.ip
1249

    
1250
    # shutdown the master IP
1251
    master = self.cfg.GetMasterNode()
1252
    result = self.rpc.call_node_stop_master(master, False)
1253
    if result.failed or not result.data:
1254
      raise errors.OpExecError("Could not disable the master role")
1255

    
1256
    try:
1257
      cluster = self.cfg.GetClusterInfo()
1258
      cluster.cluster_name = clustername
1259
      cluster.master_ip = ip
1260
      self.cfg.Update(cluster)
1261

    
1262
      # update the known hosts file
1263
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
1264
      node_list = self.cfg.GetNodeList()
1265
      try:
1266
        node_list.remove(master)
1267
      except ValueError:
1268
        pass
1269
      result = self.rpc.call_upload_file(node_list,
1270
                                         constants.SSH_KNOWN_HOSTS_FILE)
1271
      for to_node, to_result in result.iteritems():
1272
        if to_result.failed or not to_result.data:
1273
          logging.error("Copy of file %s to node %s failed",
1274
                        constants.SSH_KNOWN_HOSTS_FILE, to_node)
1275

    
1276
    finally:
1277
      result = self.rpc.call_node_start_master(master, False)
1278
      if result.failed or not result.data:
1279
        self.LogWarning("Could not re-enable the master role on"
1280
                        " the master, please restart manually.")
1281

    
1282

    
1283
def _RecursiveCheckIfLVMBased(disk):
1284
  """Check if the given disk or its children are lvm-based.
1285

1286
  @type disk: L{objects.Disk}
1287
  @param disk: the disk to check
1288
  @rtype: booleean
1289
  @return: boolean indicating whether a LD_LV dev_type was found or not
1290

1291
  """
1292
  if disk.children:
1293
    for chdisk in disk.children:
1294
      if _RecursiveCheckIfLVMBased(chdisk):
1295
        return True
1296
  return disk.dev_type == constants.LD_LV
1297

    
1298

    
1299
class LUSetClusterParams(LogicalUnit):
1300
  """Change the parameters of the cluster.
1301

1302
  """
1303
  HPATH = "cluster-modify"
1304
  HTYPE = constants.HTYPE_CLUSTER
1305
  _OP_REQP = []
1306
  REQ_BGL = False
1307

    
1308
  def CheckParameters(self):
1309
    """Check parameters
1310

1311
    """
1312
    if not hasattr(self.op, "candidate_pool_size"):
1313
      self.op.candidate_pool_size = None
1314
    if self.op.candidate_pool_size is not None:
1315
      try:
1316
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
1317
      except ValueError, err:
1318
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
1319
                                   str(err))
1320
      if self.op.candidate_pool_size < 1:
1321
        raise errors.OpPrereqError("At least one master candidate needed")
1322

    
1323
  def ExpandNames(self):
1324
    # FIXME: in the future maybe other cluster params won't require checking on
1325
    # all nodes to be modified.
1326
    self.needed_locks = {
1327
      locking.LEVEL_NODE: locking.ALL_SET,
1328
    }
1329
    self.share_locks[locking.LEVEL_NODE] = 1
1330

    
1331
  def BuildHooksEnv(self):
1332
    """Build hooks env.
1333

1334
    """
1335
    env = {
1336
      "OP_TARGET": self.cfg.GetClusterName(),
1337
      "NEW_VG_NAME": self.op.vg_name,
1338
      }
1339
    mn = self.cfg.GetMasterNode()
1340
    return env, [mn], [mn]
1341

    
1342
  def CheckPrereq(self):
1343
    """Check prerequisites.
1344

1345
    This checks whether the given params don't conflict and
1346
    if the given volume group is valid.
1347

1348
    """
1349
    # FIXME: This only works because there is only one parameter that can be
1350
    # changed or removed.
1351
    if self.op.vg_name is not None and not self.op.vg_name:
1352
      instances = self.cfg.GetAllInstancesInfo().values()
1353
      for inst in instances:
1354
        for disk in inst.disks:
1355
          if _RecursiveCheckIfLVMBased(disk):
1356
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1357
                                       " lvm-based instances exist")
1358

    
1359
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1360

    
1361
    # if vg_name not None, checks given volume group on all nodes
1362
    if self.op.vg_name:
1363
      vglist = self.rpc.call_vg_list(node_list)
1364
      for node in node_list:
1365
        if vglist[node].failed:
1366
          # ignoring down node
1367
          self.LogWarning("Node %s unreachable/error, ignoring" % node)
1368
          continue
1369
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].data,
1370
                                              self.op.vg_name,
1371
                                              constants.MIN_VG_SIZE)
1372
        if vgstatus:
1373
          raise errors.OpPrereqError("Error on node '%s': %s" %
1374
                                     (node, vgstatus))
1375

    
1376
    self.cluster = cluster = self.cfg.GetClusterInfo()
1377
    # validate beparams changes
1378
    if self.op.beparams:
1379
      utils.CheckBEParams(self.op.beparams)
1380
      self.new_beparams = cluster.FillDict(
1381
        cluster.beparams[constants.BEGR_DEFAULT], self.op.beparams)
1382

    
1383
    # hypervisor list/parameters
1384
    self.new_hvparams = cluster.FillDict(cluster.hvparams, {})
1385
    if self.op.hvparams:
1386
      if not isinstance(self.op.hvparams, dict):
1387
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input")
1388
      for hv_name, hv_dict in self.op.hvparams.items():
1389
        if hv_name not in self.new_hvparams:
1390
          self.new_hvparams[hv_name] = hv_dict
1391
        else:
1392
          self.new_hvparams[hv_name].update(hv_dict)
1393

    
1394
    if self.op.enabled_hypervisors is not None:
1395
      self.hv_list = self.op.enabled_hypervisors
1396
    else:
1397
      self.hv_list = cluster.enabled_hypervisors
1398

    
1399
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
1400
      # either the enabled list has changed, or the parameters have, validate
1401
      for hv_name, hv_params in self.new_hvparams.items():
1402
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
1403
            (self.op.enabled_hypervisors and
1404
             hv_name in self.op.enabled_hypervisors)):
1405
          # either this is a new hypervisor, or its parameters have changed
1406
          hv_class = hypervisor.GetHypervisor(hv_name)
1407
          hv_class.CheckParameterSyntax(hv_params)
1408
          _CheckHVParams(self, node_list, hv_name, hv_params)
1409

    
1410
  def Exec(self, feedback_fn):
1411
    """Change the parameters of the cluster.
1412

1413
    """
1414
    if self.op.vg_name is not None:
1415
      if self.op.vg_name != self.cfg.GetVGName():
1416
        self.cfg.SetVGName(self.op.vg_name)
1417
      else:
1418
        feedback_fn("Cluster LVM configuration already in desired"
1419
                    " state, not changing")
1420
    if self.op.hvparams:
1421
      self.cluster.hvparams = self.new_hvparams
1422
    if self.op.enabled_hypervisors is not None:
1423
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
1424
    if self.op.beparams:
1425
      self.cluster.beparams[constants.BEGR_DEFAULT] = self.new_beparams
1426
    if self.op.candidate_pool_size is not None:
1427
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
1428

    
1429
    self.cfg.Update(self.cluster)
1430

    
1431
    # we want to update nodes after the cluster so that if any errors
1432
    # happen, we have recorded and saved the cluster info
1433
    if self.op.candidate_pool_size is not None:
1434
      _AdjustCandidatePool(self)
1435

    
1436

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

1440
  """
1441
  if not instance.disks:
1442
    return True
1443

    
1444
  if not oneshot:
1445
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
1446

    
1447
  node = instance.primary_node
1448

    
1449
  for dev in instance.disks:
1450
    lu.cfg.SetDiskID(dev, node)
1451

    
1452
  retries = 0
1453
  while True:
1454
    max_time = 0
1455
    done = True
1456
    cumul_degraded = False
1457
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
1458
    if rstats.failed or not rstats.data:
1459
      lu.LogWarning("Can't get any data from node %s", node)
1460
      retries += 1
1461
      if retries >= 10:
1462
        raise errors.RemoteError("Can't contact node %s for mirror data,"
1463
                                 " aborting." % node)
1464
      time.sleep(6)
1465
      continue
1466
    rstats = rstats.data
1467
    retries = 0
1468
    for i in range(len(rstats)):
1469
      mstat = rstats[i]
1470
      if mstat is None:
1471
        lu.LogWarning("Can't compute data for node %s/%s",
1472
                           node, instance.disks[i].iv_name)
1473
        continue
1474
      # we ignore the ldisk parameter
1475
      perc_done, est_time, is_degraded, _ = mstat
1476
      cumul_degraded = cumul_degraded or (is_degraded and perc_done is None)
1477
      if perc_done is not None:
1478
        done = False
1479
        if est_time is not None:
1480
          rem_time = "%d estimated seconds remaining" % est_time
1481
          max_time = est_time
1482
        else:
1483
          rem_time = "no time estimate"
1484
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
1485
                        (instance.disks[i].iv_name, perc_done, rem_time))
1486
    if done or oneshot:
1487
      break
1488

    
1489
    time.sleep(min(60, max_time))
1490

    
1491
  if done:
1492
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
1493
  return not cumul_degraded
1494

    
1495

    
1496
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
1497
  """Check that mirrors are not degraded.
1498

1499
  The ldisk parameter, if True, will change the test from the
1500
  is_degraded attribute (which represents overall non-ok status for
1501
  the device(s)) to the ldisk (representing the local storage status).
1502

1503
  """
1504
  lu.cfg.SetDiskID(dev, node)
1505
  if ldisk:
1506
    idx = 6
1507
  else:
1508
    idx = 5
1509

    
1510
  result = True
1511
  if on_primary or dev.AssembleOnSecondary():
1512
    rstats = lu.rpc.call_blockdev_find(node, dev)
1513
    if rstats.failed or not rstats.data:
1514
      logging.warning("Node %s: disk degraded, not found or node down", node)
1515
      result = False
1516
    else:
1517
      result = result and (not rstats.data[idx])
1518
  if dev.children:
1519
    for child in dev.children:
1520
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
1521

    
1522
  return result
1523

    
1524

    
1525
class LUDiagnoseOS(NoHooksLU):
1526
  """Logical unit for OS diagnose/query.
1527

1528
  """
1529
  _OP_REQP = ["output_fields", "names"]
1530
  REQ_BGL = False
1531
  _FIELDS_STATIC = utils.FieldSet()
1532
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status")
1533

    
1534
  def ExpandNames(self):
1535
    if self.op.names:
1536
      raise errors.OpPrereqError("Selective OS query not supported")
1537

    
1538
    _CheckOutputFields(static=self._FIELDS_STATIC,
1539
                       dynamic=self._FIELDS_DYNAMIC,
1540
                       selected=self.op.output_fields)
1541

    
1542
    # Lock all nodes, in shared mode
1543
    self.needed_locks = {}
1544
    self.share_locks[locking.LEVEL_NODE] = 1
1545
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1546

    
1547
  def CheckPrereq(self):
1548
    """Check prerequisites.
1549

1550
    """
1551

    
1552
  @staticmethod
1553
  def _DiagnoseByOS(node_list, rlist):
1554
    """Remaps a per-node return list into an a per-os per-node dictionary
1555

1556
    @param node_list: a list with the names of all nodes
1557
    @param rlist: a map with node names as keys and OS objects as values
1558

1559
    @rtype: dict
1560
    @returns: a dictionary with osnames as keys and as value another map, with
1561
        nodes as keys and list of OS objects as values, eg::
1562

1563
          {"debian-etch": {"node1": [<object>,...],
1564
                           "node2": [<object>,]}
1565
          }
1566

1567
    """
1568
    all_os = {}
1569
    for node_name, nr in rlist.iteritems():
1570
      if nr.failed or not nr.data:
1571
        continue
1572
      for os_obj in nr.data:
1573
        if os_obj.name not in all_os:
1574
          # build a list of nodes for this os containing empty lists
1575
          # for each node in node_list
1576
          all_os[os_obj.name] = {}
1577
          for nname in node_list:
1578
            all_os[os_obj.name][nname] = []
1579
        all_os[os_obj.name][node_name].append(os_obj)
1580
    return all_os
1581

    
1582
  def Exec(self, feedback_fn):
1583
    """Compute the list of OSes.
1584

1585
    """
1586
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1587
    node_data = self.rpc.call_os_diagnose(node_list)
1588
    if node_data == False:
1589
      raise errors.OpExecError("Can't gather the list of OSes")
1590
    pol = self._DiagnoseByOS(node_list, node_data)
1591
    output = []
1592
    for os_name, os_data in pol.iteritems():
1593
      row = []
1594
      for field in self.op.output_fields:
1595
        if field == "name":
1596
          val = os_name
1597
        elif field == "valid":
1598
          val = utils.all([osl and osl[0] for osl in os_data.values()])
1599
        elif field == "node_status":
1600
          val = {}
1601
          for node_name, nos_list in os_data.iteritems():
1602
            val[node_name] = [(v.status, v.path) for v in nos_list]
1603
        else:
1604
          raise errors.ParameterError(field)
1605
        row.append(val)
1606
      output.append(row)
1607

    
1608
    return output
1609

    
1610

    
1611
class LURemoveNode(LogicalUnit):
1612
  """Logical unit for removing a node.
1613

1614
  """
1615
  HPATH = "node-remove"
1616
  HTYPE = constants.HTYPE_NODE
1617
  _OP_REQP = ["node_name"]
1618

    
1619
  def BuildHooksEnv(self):
1620
    """Build hooks env.
1621

1622
    This doesn't run on the target node in the pre phase as a failed
1623
    node would then be impossible to remove.
1624

1625
    """
1626
    env = {
1627
      "OP_TARGET": self.op.node_name,
1628
      "NODE_NAME": self.op.node_name,
1629
      }
1630
    all_nodes = self.cfg.GetNodeList()
1631
    all_nodes.remove(self.op.node_name)
1632
    return env, all_nodes, all_nodes
1633

    
1634
  def CheckPrereq(self):
1635
    """Check prerequisites.
1636

1637
    This checks:
1638
     - the node exists in the configuration
1639
     - it does not have primary or secondary instances
1640
     - it's not the master
1641

1642
    Any errors are signalled by raising errors.OpPrereqError.
1643

1644
    """
1645
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
1646
    if node is None:
1647
      raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name)
1648

    
1649
    instance_list = self.cfg.GetInstanceList()
1650

    
1651
    masternode = self.cfg.GetMasterNode()
1652
    if node.name == masternode:
1653
      raise errors.OpPrereqError("Node is the master node,"
1654
                                 " you need to failover first.")
1655

    
1656
    for instance_name in instance_list:
1657
      instance = self.cfg.GetInstanceInfo(instance_name)
1658
      if node.name == instance.primary_node:
1659
        raise errors.OpPrereqError("Instance %s still running on the node,"
1660
                                   " please remove first." % instance_name)
1661
      if node.name in instance.secondary_nodes:
1662
        raise errors.OpPrereqError("Instance %s has node as a secondary,"
1663
                                   " please remove first." % instance_name)
1664
    self.op.node_name = node.name
1665
    self.node = node
1666

    
1667
  def Exec(self, feedback_fn):
1668
    """Removes the node from the cluster.
1669

1670
    """
1671
    node = self.node
1672
    logging.info("Stopping the node daemon and removing configs from node %s",
1673
                 node.name)
1674

    
1675
    self.context.RemoveNode(node.name)
1676

    
1677
    self.rpc.call_node_leave_cluster(node.name)
1678

    
1679
    # Promote nodes to master candidate as needed
1680
    _AdjustCandidatePool(self)
1681

    
1682

    
1683
class LUQueryNodes(NoHooksLU):
1684
  """Logical unit for querying nodes.
1685

1686
  """
1687
  _OP_REQP = ["output_fields", "names"]
1688
  REQ_BGL = False
1689
  _FIELDS_DYNAMIC = utils.FieldSet(
1690
    "dtotal", "dfree",
1691
    "mtotal", "mnode", "mfree",
1692
    "bootid",
1693
    "ctotal",
1694
    )
1695

    
1696
  _FIELDS_STATIC = utils.FieldSet(
1697
    "name", "pinst_cnt", "sinst_cnt",
1698
    "pinst_list", "sinst_list",
1699
    "pip", "sip", "tags",
1700
    "serial_no",
1701
    "master_candidate",
1702
    "master",
1703
    "offline",
1704
    )
1705

    
1706
  def ExpandNames(self):
1707
    _CheckOutputFields(static=self._FIELDS_STATIC,
1708
                       dynamic=self._FIELDS_DYNAMIC,
1709
                       selected=self.op.output_fields)
1710

    
1711
    self.needed_locks = {}
1712
    self.share_locks[locking.LEVEL_NODE] = 1
1713

    
1714
    if self.op.names:
1715
      self.wanted = _GetWantedNodes(self, self.op.names)
1716
    else:
1717
      self.wanted = locking.ALL_SET
1718

    
1719
    self.do_locking = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
1720
    if self.do_locking:
1721
      # if we don't request only static fields, we need to lock the nodes
1722
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
1723

    
1724

    
1725
  def CheckPrereq(self):
1726
    """Check prerequisites.
1727

1728
    """
1729
    # The validation of the node list is done in the _GetWantedNodes,
1730
    # if non empty, and if empty, there's no validation to do
1731
    pass
1732

    
1733
  def Exec(self, feedback_fn):
1734
    """Computes the list of nodes and their attributes.
1735

1736
    """
1737
    all_info = self.cfg.GetAllNodesInfo()
1738
    if self.do_locking:
1739
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
1740
    elif self.wanted != locking.ALL_SET:
1741
      nodenames = self.wanted
1742
      missing = set(nodenames).difference(all_info.keys())
1743
      if missing:
1744
        raise errors.OpExecError(
1745
          "Some nodes were removed before retrieving their data: %s" % missing)
1746
    else:
1747
      nodenames = all_info.keys()
1748

    
1749
    nodenames = utils.NiceSort(nodenames)
1750
    nodelist = [all_info[name] for name in nodenames]
1751

    
1752
    # begin data gathering
1753

    
1754
    if self.do_locking:
1755
      live_data = {}
1756
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
1757
                                          self.cfg.GetHypervisorType())
1758
      for name in nodenames:
1759
        nodeinfo = node_data[name]
1760
        if not nodeinfo.failed and nodeinfo.data:
1761
          nodeinfo = nodeinfo.data
1762
          fn = utils.TryConvert
1763
          live_data[name] = {
1764
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
1765
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
1766
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
1767
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
1768
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
1769
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
1770
            "bootid": nodeinfo.get('bootid', None),
1771
            }
1772
        else:
1773
          live_data[name] = {}
1774
    else:
1775
      live_data = dict.fromkeys(nodenames, {})
1776

    
1777
    node_to_primary = dict([(name, set()) for name in nodenames])
1778
    node_to_secondary = dict([(name, set()) for name in nodenames])
1779

    
1780
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
1781
                             "sinst_cnt", "sinst_list"))
1782
    if inst_fields & frozenset(self.op.output_fields):
1783
      instancelist = self.cfg.GetInstanceList()
1784

    
1785
      for instance_name in instancelist:
1786
        inst = self.cfg.GetInstanceInfo(instance_name)
1787
        if inst.primary_node in node_to_primary:
1788
          node_to_primary[inst.primary_node].add(inst.name)
1789
        for secnode in inst.secondary_nodes:
1790
          if secnode in node_to_secondary:
1791
            node_to_secondary[secnode].add(inst.name)
1792

    
1793
    master_node = self.cfg.GetMasterNode()
1794

    
1795
    # end data gathering
1796

    
1797
    output = []
1798
    for node in nodelist:
1799
      node_output = []
1800
      for field in self.op.output_fields:
1801
        if field == "name":
1802
          val = node.name
1803
        elif field == "pinst_list":
1804
          val = list(node_to_primary[node.name])
1805
        elif field == "sinst_list":
1806
          val = list(node_to_secondary[node.name])
1807
        elif field == "pinst_cnt":
1808
          val = len(node_to_primary[node.name])
1809
        elif field == "sinst_cnt":
1810
          val = len(node_to_secondary[node.name])
1811
        elif field == "pip":
1812
          val = node.primary_ip
1813
        elif field == "sip":
1814
          val = node.secondary_ip
1815
        elif field == "tags":
1816
          val = list(node.GetTags())
1817
        elif field == "serial_no":
1818
          val = node.serial_no
1819
        elif field == "master_candidate":
1820
          val = node.master_candidate
1821
        elif field == "master":
1822
          val = node.name == master_node
1823
        elif field == "offline":
1824
          val = node.offline
1825
        elif self._FIELDS_DYNAMIC.Matches(field):
1826
          val = live_data[node.name].get(field, None)
1827
        else:
1828
          raise errors.ParameterError(field)
1829
        node_output.append(val)
1830
      output.append(node_output)
1831

    
1832
    return output
1833

    
1834

    
1835
class LUQueryNodeVolumes(NoHooksLU):
1836
  """Logical unit for getting volumes on node(s).
1837

1838
  """
1839
  _OP_REQP = ["nodes", "output_fields"]
1840
  REQ_BGL = False
1841
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
1842
  _FIELDS_STATIC = utils.FieldSet("node")
1843

    
1844
  def ExpandNames(self):
1845
    _CheckOutputFields(static=self._FIELDS_STATIC,
1846
                       dynamic=self._FIELDS_DYNAMIC,
1847
                       selected=self.op.output_fields)
1848

    
1849
    self.needed_locks = {}
1850
    self.share_locks[locking.LEVEL_NODE] = 1
1851
    if not self.op.nodes:
1852
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1853
    else:
1854
      self.needed_locks[locking.LEVEL_NODE] = \
1855
        _GetWantedNodes(self, self.op.nodes)
1856

    
1857
  def CheckPrereq(self):
1858
    """Check prerequisites.
1859

1860
    This checks that the fields required are valid output fields.
1861

1862
    """
1863
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
1864

    
1865
  def Exec(self, feedback_fn):
1866
    """Computes the list of nodes and their attributes.
1867

1868
    """
1869
    nodenames = self.nodes
1870
    volumes = self.rpc.call_node_volumes(nodenames)
1871

    
1872
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
1873
             in self.cfg.GetInstanceList()]
1874

    
1875
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
1876

    
1877
    output = []
1878
    for node in nodenames:
1879
      if node not in volumes or volumes[node].failed or not volumes[node].data:
1880
        continue
1881

    
1882
      node_vols = volumes[node].data[:]
1883
      node_vols.sort(key=lambda vol: vol['dev'])
1884

    
1885
      for vol in node_vols:
1886
        node_output = []
1887
        for field in self.op.output_fields:
1888
          if field == "node":
1889
            val = node
1890
          elif field == "phys":
1891
            val = vol['dev']
1892
          elif field == "vg":
1893
            val = vol['vg']
1894
          elif field == "name":
1895
            val = vol['name']
1896
          elif field == "size":
1897
            val = int(float(vol['size']))
1898
          elif field == "instance":
1899
            for inst in ilist:
1900
              if node not in lv_by_node[inst]:
1901
                continue
1902
              if vol['name'] in lv_by_node[inst][node]:
1903
                val = inst.name
1904
                break
1905
            else:
1906
              val = '-'
1907
          else:
1908
            raise errors.ParameterError(field)
1909
          node_output.append(str(val))
1910

    
1911
        output.append(node_output)
1912

    
1913
    return output
1914

    
1915

    
1916
class LUAddNode(LogicalUnit):
1917
  """Logical unit for adding node to the cluster.
1918

1919
  """
1920
  HPATH = "node-add"
1921
  HTYPE = constants.HTYPE_NODE
1922
  _OP_REQP = ["node_name"]
1923

    
1924
  def BuildHooksEnv(self):
1925
    """Build hooks env.
1926

1927
    This will run on all nodes before, and on all nodes + the new node after.
1928

1929
    """
1930
    env = {
1931
      "OP_TARGET": self.op.node_name,
1932
      "NODE_NAME": self.op.node_name,
1933
      "NODE_PIP": self.op.primary_ip,
1934
      "NODE_SIP": self.op.secondary_ip,
1935
      }
1936
    nodes_0 = self.cfg.GetNodeList()
1937
    nodes_1 = nodes_0 + [self.op.node_name, ]
1938
    return env, nodes_0, nodes_1
1939

    
1940
  def CheckPrereq(self):
1941
    """Check prerequisites.
1942

1943
    This checks:
1944
     - the new node is not already in the config
1945
     - it is resolvable
1946
     - its parameters (single/dual homed) matches the cluster
1947

1948
    Any errors are signalled by raising errors.OpPrereqError.
1949

1950
    """
1951
    node_name = self.op.node_name
1952
    cfg = self.cfg
1953

    
1954
    dns_data = utils.HostInfo(node_name)
1955

    
1956
    node = dns_data.name
1957
    primary_ip = self.op.primary_ip = dns_data.ip
1958
    secondary_ip = getattr(self.op, "secondary_ip", None)
1959
    if secondary_ip is None:
1960
      secondary_ip = primary_ip
1961
    if not utils.IsValidIP(secondary_ip):
1962
      raise errors.OpPrereqError("Invalid secondary IP given")
1963
    self.op.secondary_ip = secondary_ip
1964

    
1965
    node_list = cfg.GetNodeList()
1966
    if not self.op.readd and node in node_list:
1967
      raise errors.OpPrereqError("Node %s is already in the configuration" %
1968
                                 node)
1969
    elif self.op.readd and node not in node_list:
1970
      raise errors.OpPrereqError("Node %s is not in the configuration" % node)
1971

    
1972
    for existing_node_name in node_list:
1973
      existing_node = cfg.GetNodeInfo(existing_node_name)
1974

    
1975
      if self.op.readd and node == existing_node_name:
1976
        if (existing_node.primary_ip != primary_ip or
1977
            existing_node.secondary_ip != secondary_ip):
1978
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
1979
                                     " address configuration as before")
1980
        continue
1981

    
1982
      if (existing_node.primary_ip == primary_ip or
1983
          existing_node.secondary_ip == primary_ip or
1984
          existing_node.primary_ip == secondary_ip or
1985
          existing_node.secondary_ip == secondary_ip):
1986
        raise errors.OpPrereqError("New node ip address(es) conflict with"
1987
                                   " existing node %s" % existing_node.name)
1988

    
1989
    # check that the type of the node (single versus dual homed) is the
1990
    # same as for the master
1991
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
1992
    master_singlehomed = myself.secondary_ip == myself.primary_ip
1993
    newbie_singlehomed = secondary_ip == primary_ip
1994
    if master_singlehomed != newbie_singlehomed:
1995
      if master_singlehomed:
1996
        raise errors.OpPrereqError("The master has no private ip but the"
1997
                                   " new node has one")
1998
      else:
1999
        raise errors.OpPrereqError("The master has a private ip but the"
2000
                                   " new node doesn't have one")
2001

    
2002
    # checks reachablity
2003
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
2004
      raise errors.OpPrereqError("Node not reachable by ping")
2005

    
2006
    if not newbie_singlehomed:
2007
      # check reachability from my secondary ip to newbie's secondary ip
2008
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
2009
                           source=myself.secondary_ip):
2010
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
2011
                                   " based ping to noded port")
2012

    
2013
    cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2014
    node_info = self.cfg.GetAllNodesInfo().values()
2015
    mc_now, _ = self.cfg.GetMasterCandidateStats()
2016
    master_candidate = mc_now < cp_size
2017

    
2018
    self.new_node = objects.Node(name=node,
2019
                                 primary_ip=primary_ip,
2020
                                 secondary_ip=secondary_ip,
2021
                                 master_candidate=master_candidate,
2022
                                 offline=False)
2023

    
2024
  def Exec(self, feedback_fn):
2025
    """Adds the new node to the cluster.
2026

2027
    """
2028
    new_node = self.new_node
2029
    node = new_node.name
2030

    
2031
    # check connectivity
2032
    result = self.rpc.call_version([node])[node]
2033
    result.Raise()
2034
    if result.data:
2035
      if constants.PROTOCOL_VERSION == result.data:
2036
        logging.info("Communication to node %s fine, sw version %s match",
2037
                     node, result.data)
2038
      else:
2039
        raise errors.OpExecError("Version mismatch master version %s,"
2040
                                 " node version %s" %
2041
                                 (constants.PROTOCOL_VERSION, result.data))
2042
    else:
2043
      raise errors.OpExecError("Cannot get version from the new node")
2044

    
2045
    # setup ssh on node
2046
    logging.info("Copy ssh key to node %s", node)
2047
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
2048
    keyarray = []
2049
    keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
2050
                constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
2051
                priv_key, pub_key]
2052

    
2053
    for i in keyfiles:
2054
      f = open(i, 'r')
2055
      try:
2056
        keyarray.append(f.read())
2057
      finally:
2058
        f.close()
2059

    
2060
    result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
2061
                                    keyarray[2],
2062
                                    keyarray[3], keyarray[4], keyarray[5])
2063

    
2064
    if result.failed or not result.data:
2065
      raise errors.OpExecError("Cannot transfer ssh keys to the new node")
2066

    
2067
    # Add node to our /etc/hosts, and add key to known_hosts
2068
    utils.AddHostToEtcHosts(new_node.name)
2069

    
2070
    if new_node.secondary_ip != new_node.primary_ip:
2071
      result = self.rpc.call_node_has_ip_address(new_node.name,
2072
                                                 new_node.secondary_ip)
2073
      if result.failed or not result.data:
2074
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
2075
                                 " you gave (%s). Please fix and re-run this"
2076
                                 " command." % new_node.secondary_ip)
2077

    
2078
    node_verify_list = [self.cfg.GetMasterNode()]
2079
    node_verify_param = {
2080
      'nodelist': [node],
2081
      # TODO: do a node-net-test as well?
2082
    }
2083

    
2084
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
2085
                                       self.cfg.GetClusterName())
2086
    for verifier in node_verify_list:
2087
      if result[verifier].failed or not result[verifier].data:
2088
        raise errors.OpExecError("Cannot communicate with %s's node daemon"
2089
                                 " for remote verification" % verifier)
2090
      if result[verifier].data['nodelist']:
2091
        for failed in result[verifier].data['nodelist']:
2092
          feedback_fn("ssh/hostname verification failed %s -> %s" %
2093
                      (verifier, result[verifier]['nodelist'][failed]))
2094
        raise errors.OpExecError("ssh/hostname verification failed.")
2095

    
2096
    # Distribute updated /etc/hosts and known_hosts to all nodes,
2097
    # including the node just added
2098
    myself = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
2099
    dist_nodes = self.cfg.GetNodeList()
2100
    if not self.op.readd:
2101
      dist_nodes.append(node)
2102
    if myself.name in dist_nodes:
2103
      dist_nodes.remove(myself.name)
2104

    
2105
    logging.debug("Copying hosts and known_hosts to all nodes")
2106
    for fname in (constants.ETC_HOSTS, constants.SSH_KNOWN_HOSTS_FILE):
2107
      result = self.rpc.call_upload_file(dist_nodes, fname)
2108
      for to_node, to_result in result.iteritems():
2109
        if to_result.failed or not to_result.data:
2110
          logging.error("Copy of file %s to node %s failed", fname, to_node)
2111

    
2112
    to_copy = []
2113
    if constants.HT_XEN_HVM in self.cfg.GetClusterInfo().enabled_hypervisors:
2114
      to_copy.append(constants.VNC_PASSWORD_FILE)
2115
    for fname in to_copy:
2116
      result = self.rpc.call_upload_file([node], fname)
2117
      if result[node].failed or not result[node]:
2118
        logging.error("Could not copy file %s to node %s", fname, node)
2119

    
2120
    if self.op.readd:
2121
      self.context.ReaddNode(new_node)
2122
    else:
2123
      self.context.AddNode(new_node)
2124

    
2125

    
2126
class LUSetNodeParams(LogicalUnit):
2127
  """Modifies the parameters of a node.
2128

2129
  """
2130
  HPATH = "node-modify"
2131
  HTYPE = constants.HTYPE_NODE
2132
  _OP_REQP = ["node_name"]
2133
  REQ_BGL = False
2134

    
2135
  def CheckArguments(self):
2136
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2137
    if node_name is None:
2138
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
2139
    self.op.node_name = node_name
2140
    _CheckBooleanOpField(self.op, 'master_candidate')
2141
    _CheckBooleanOpField(self.op, 'offline')
2142
    if self.op.master_candidate is None and self.op.offline is None:
2143
      raise errors.OpPrereqError("Please pass at least one modification")
2144
    if self.op.offline == True and self.op.master_candidate == True:
2145
      raise errors.OpPrereqError("Can't set the node into offline and"
2146
                                 " master_candidate at the same time")
2147

    
2148
  def ExpandNames(self):
2149
    self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
2150

    
2151
  def BuildHooksEnv(self):
2152
    """Build hooks env.
2153

2154
    This runs on the master node.
2155

2156
    """
2157
    env = {
2158
      "OP_TARGET": self.op.node_name,
2159
      "MASTER_CANDIDATE": str(self.op.master_candidate),
2160
      "OFFLINE": str(self.op.offline),
2161
      }
2162
    nl = [self.cfg.GetMasterNode(),
2163
          self.op.node_name]
2164
    return env, nl, nl
2165

    
2166
  def CheckPrereq(self):
2167
    """Check prerequisites.
2168

2169
    This only checks the instance list against the existing names.
2170

2171
    """
2172
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
2173

    
2174
    if ((self.op.master_candidate == False or self.op.offline == True)
2175
        and node.master_candidate):
2176
      # we will demote the node from master_candidate
2177
      if self.op.node_name == self.cfg.GetMasterNode():
2178
        raise errors.OpPrereqError("The master node has to be a"
2179
                                   " master candidate and online")
2180
      cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2181
      node_info = self.cfg.GetAllNodesInfo().values()
2182
      num_candidates, _ = self.cfg.GetMasterCandidateStats()
2183
      if num_candidates <= cp_size:
2184
        msg = ("Not enough master candidates (desired"
2185
               " %d, new value will be %d)" % (cp_size, num_candidates-1))
2186
        if self.op.force:
2187
          self.LogWarning(msg)
2188
        else:
2189
          raise errors.OpPrereqError(msg)
2190

    
2191
    if (self.op.master_candidate == True and node.offline and
2192
        not self.op.offline == False):
2193
      raise errors.OpPrereqError("Can't set an offline node to"
2194
                                 " master_candidate")
2195

    
2196
    return
2197

    
2198
  def Exec(self, feedback_fn):
2199
    """Modifies a node.
2200

2201
    """
2202
    node = self.node
2203

    
2204
    result = []
2205

    
2206
    if self.op.offline is not None:
2207
      node.offline = self.op.offline
2208
      result.append(("offline", str(self.op.offline)))
2209
      if self.op.offline == True and node.master_candidate:
2210
        node.master_candidate = False
2211
        result.append(("master_candidate", "auto-demotion due to offline"))
2212

    
2213
    if self.op.master_candidate is not None:
2214
      node.master_candidate = self.op.master_candidate
2215
      result.append(("master_candidate", str(self.op.master_candidate)))
2216
      if self.op.master_candidate == False:
2217
        rrc = self.rpc.call_node_demote_from_mc(node.name)
2218
        if (rrc.failed or not isinstance(rrc.data, (tuple, list))
2219
            or len(rrc.data) != 2):
2220
          self.LogWarning("Node rpc error: %s" % rrc.error)
2221
        elif not rrc.data[0]:
2222
          self.LogWarning("Node failed to demote itself: %s" % rrc.data[1])
2223

    
2224
    # this will trigger configuration file update, if needed
2225
    self.cfg.Update(node)
2226
    # this will trigger job queue propagation or cleanup
2227
    if self.op.node_name != self.cfg.GetMasterNode():
2228
      self.context.ReaddNode(node)
2229

    
2230
    return result
2231

    
2232

    
2233
class LUQueryClusterInfo(NoHooksLU):
2234
  """Query cluster configuration.
2235

2236
  """
2237
  _OP_REQP = []
2238
  REQ_BGL = False
2239

    
2240
  def ExpandNames(self):
2241
    self.needed_locks = {}
2242

    
2243
  def CheckPrereq(self):
2244
    """No prerequsites needed for this LU.
2245

2246
    """
2247
    pass
2248

    
2249
  def Exec(self, feedback_fn):
2250
    """Return cluster config.
2251

2252
    """
2253
    cluster = self.cfg.GetClusterInfo()
2254
    result = {
2255
      "software_version": constants.RELEASE_VERSION,
2256
      "protocol_version": constants.PROTOCOL_VERSION,
2257
      "config_version": constants.CONFIG_VERSION,
2258
      "os_api_version": constants.OS_API_VERSION,
2259
      "export_version": constants.EXPORT_VERSION,
2260
      "architecture": (platform.architecture()[0], platform.machine()),
2261
      "name": cluster.cluster_name,
2262
      "master": cluster.master_node,
2263
      "default_hypervisor": cluster.default_hypervisor,
2264
      "enabled_hypervisors": cluster.enabled_hypervisors,
2265
      "hvparams": cluster.hvparams,
2266
      "beparams": cluster.beparams,
2267
      "candidate_pool_size": cluster.candidate_pool_size,
2268
      }
2269

    
2270
    return result
2271

    
2272

    
2273
class LUQueryConfigValues(NoHooksLU):
2274
  """Return configuration values.
2275

2276
  """
2277
  _OP_REQP = []
2278
  REQ_BGL = False
2279
  _FIELDS_DYNAMIC = utils.FieldSet()
2280
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag")
2281

    
2282
  def ExpandNames(self):
2283
    self.needed_locks = {}
2284

    
2285
    _CheckOutputFields(static=self._FIELDS_STATIC,
2286
                       dynamic=self._FIELDS_DYNAMIC,
2287
                       selected=self.op.output_fields)
2288

    
2289
  def CheckPrereq(self):
2290
    """No prerequisites.
2291

2292
    """
2293
    pass
2294

    
2295
  def Exec(self, feedback_fn):
2296
    """Dump a representation of the cluster config to the standard output.
2297

2298
    """
2299
    values = []
2300
    for field in self.op.output_fields:
2301
      if field == "cluster_name":
2302
        entry = self.cfg.GetClusterName()
2303
      elif field == "master_node":
2304
        entry = self.cfg.GetMasterNode()
2305
      elif field == "drain_flag":
2306
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
2307
      else:
2308
        raise errors.ParameterError(field)
2309
      values.append(entry)
2310
    return values
2311

    
2312

    
2313
class LUActivateInstanceDisks(NoHooksLU):
2314
  """Bring up an instance's disks.
2315

2316
  """
2317
  _OP_REQP = ["instance_name"]
2318
  REQ_BGL = False
2319

    
2320
  def ExpandNames(self):
2321
    self._ExpandAndLockInstance()
2322
    self.needed_locks[locking.LEVEL_NODE] = []
2323
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2324

    
2325
  def DeclareLocks(self, level):
2326
    if level == locking.LEVEL_NODE:
2327
      self._LockInstancesNodes()
2328

    
2329
  def CheckPrereq(self):
2330
    """Check prerequisites.
2331

2332
    This checks that the instance is in the cluster.
2333

2334
    """
2335
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2336
    assert self.instance is not None, \
2337
      "Cannot retrieve locked instance %s" % self.op.instance_name
2338
    _CheckNodeOnline(self, instance.primary_node)
2339

    
2340
  def Exec(self, feedback_fn):
2341
    """Activate the disks.
2342

2343
    """
2344
    disks_ok, disks_info = _AssembleInstanceDisks(self, self.instance)
2345
    if not disks_ok:
2346
      raise errors.OpExecError("Cannot activate block devices")
2347

    
2348
    return disks_info
2349

    
2350

    
2351
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False):
2352
  """Prepare the block devices for an instance.
2353

2354
  This sets up the block devices on all nodes.
2355

2356
  @type lu: L{LogicalUnit}
2357
  @param lu: the logical unit on whose behalf we execute
2358
  @type instance: L{objects.Instance}
2359
  @param instance: the instance for whose disks we assemble
2360
  @type ignore_secondaries: boolean
2361
  @param ignore_secondaries: if true, errors on secondary nodes
2362
      won't result in an error return from the function
2363
  @return: False if the operation failed, otherwise a list of
2364
      (host, instance_visible_name, node_visible_name)
2365
      with the mapping from node devices to instance devices
2366

2367
  """
2368
  device_info = []
2369
  disks_ok = True
2370
  iname = instance.name
2371
  # With the two passes mechanism we try to reduce the window of
2372
  # opportunity for the race condition of switching DRBD to primary
2373
  # before handshaking occured, but we do not eliminate it
2374

    
2375
  # The proper fix would be to wait (with some limits) until the
2376
  # connection has been made and drbd transitions from WFConnection
2377
  # into any other network-connected state (Connected, SyncTarget,
2378
  # SyncSource, etc.)
2379

    
2380
  # 1st pass, assemble on all nodes in secondary mode
2381
  for inst_disk in instance.disks:
2382
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2383
      lu.cfg.SetDiskID(node_disk, node)
2384
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
2385
      if result.failed or not result:
2386
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2387
                           " (is_primary=False, pass=1)",
2388
                           inst_disk.iv_name, node)
2389
        if not ignore_secondaries:
2390
          disks_ok = False
2391

    
2392
  # FIXME: race condition on drbd migration to primary
2393

    
2394
  # 2nd pass, do only the primary node
2395
  for inst_disk in instance.disks:
2396
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2397
      if node != instance.primary_node:
2398
        continue
2399
      lu.cfg.SetDiskID(node_disk, node)
2400
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
2401
      if result.failed or not result:
2402
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2403
                           " (is_primary=True, pass=2)",
2404
                           inst_disk.iv_name, node)
2405
        disks_ok = False
2406
    device_info.append((instance.primary_node, inst_disk.iv_name, result))
2407

    
2408
  # leave the disks configured for the primary node
2409
  # this is a workaround that would be fixed better by
2410
  # improving the logical/physical id handling
2411
  for disk in instance.disks:
2412
    lu.cfg.SetDiskID(disk, instance.primary_node)
2413

    
2414
  return disks_ok, device_info
2415

    
2416

    
2417
def _StartInstanceDisks(lu, instance, force):
2418
  """Start the disks of an instance.
2419

2420
  """
2421
  disks_ok, dummy = _AssembleInstanceDisks(lu, instance,
2422
                                           ignore_secondaries=force)
2423
  if not disks_ok:
2424
    _ShutdownInstanceDisks(lu, instance)
2425
    if force is not None and not force:
2426
      lu.proc.LogWarning("", hint="If the message above refers to a"
2427
                         " secondary node,"
2428
                         " you can retry the operation using '--force'.")
2429
    raise errors.OpExecError("Disk consistency error")
2430

    
2431

    
2432
class LUDeactivateInstanceDisks(NoHooksLU):
2433
  """Shutdown an instance's disks.
2434

2435
  """
2436
  _OP_REQP = ["instance_name"]
2437
  REQ_BGL = False
2438

    
2439
  def ExpandNames(self):
2440
    self._ExpandAndLockInstance()
2441
    self.needed_locks[locking.LEVEL_NODE] = []
2442
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2443

    
2444
  def DeclareLocks(self, level):
2445
    if level == locking.LEVEL_NODE:
2446
      self._LockInstancesNodes()
2447

    
2448
  def CheckPrereq(self):
2449
    """Check prerequisites.
2450

2451
    This checks that the instance is in the cluster.
2452

2453
    """
2454
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2455
    assert self.instance is not None, \
2456
      "Cannot retrieve locked instance %s" % self.op.instance_name
2457

    
2458
  def Exec(self, feedback_fn):
2459
    """Deactivate the disks
2460

2461
    """
2462
    instance = self.instance
2463
    _SafeShutdownInstanceDisks(self, instance)
2464

    
2465

    
2466
def _SafeShutdownInstanceDisks(lu, instance):
2467
  """Shutdown block devices of an instance.
2468

2469
  This function checks if an instance is running, before calling
2470
  _ShutdownInstanceDisks.
2471

2472
  """
2473
  ins_l = lu.rpc.call_instance_list([instance.primary_node],
2474
                                      [instance.hypervisor])
2475
  ins_l = ins_l[instance.primary_node]
2476
  if ins_l.failed or not isinstance(ins_l.data, list):
2477
    raise errors.OpExecError("Can't contact node '%s'" %
2478
                             instance.primary_node)
2479

    
2480
  if instance.name in ins_l.data:
2481
    raise errors.OpExecError("Instance is running, can't shutdown"
2482
                             " block devices.")
2483

    
2484
  _ShutdownInstanceDisks(lu, instance)
2485

    
2486

    
2487
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
2488
  """Shutdown block devices of an instance.
2489

2490
  This does the shutdown on all nodes of the instance.
2491

2492
  If the ignore_primary is false, errors on the primary node are
2493
  ignored.
2494

2495
  """
2496
  result = True
2497
  for disk in instance.disks:
2498
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
2499
      lu.cfg.SetDiskID(top_disk, node)
2500
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
2501
      if result.failed or not result.data:
2502
        logging.error("Could not shutdown block device %s on node %s",
2503
                      disk.iv_name, node)
2504
        if not ignore_primary or node != instance.primary_node:
2505
          result = False
2506
  return result
2507

    
2508

    
2509
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor):
2510
  """Checks if a node has enough free memory.
2511

2512
  This function check if a given node has the needed amount of free
2513
  memory. In case the node has less memory or we cannot get the
2514
  information from the node, this function raise an OpPrereqError
2515
  exception.
2516

2517
  @type lu: C{LogicalUnit}
2518
  @param lu: a logical unit from which we get configuration data
2519
  @type node: C{str}
2520
  @param node: the node to check
2521
  @type reason: C{str}
2522
  @param reason: string to use in the error message
2523
  @type requested: C{int}
2524
  @param requested: the amount of memory in MiB to check for
2525
  @type hypervisor: C{str}
2526
  @param hypervisor: the hypervisor to ask for memory stats
2527
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
2528
      we cannot check the node
2529

2530
  """
2531
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor)
2532
  nodeinfo[node].Raise()
2533
  free_mem = nodeinfo[node].data.get('memory_free')
2534
  if not isinstance(free_mem, int):
2535
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
2536
                             " was '%s'" % (node, free_mem))
2537
  if requested > free_mem:
2538
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
2539
                             " needed %s MiB, available %s MiB" %
2540
                             (node, reason, requested, free_mem))
2541

    
2542

    
2543
class LUStartupInstance(LogicalUnit):
2544
  """Starts an instance.
2545

2546
  """
2547
  HPATH = "instance-start"
2548
  HTYPE = constants.HTYPE_INSTANCE
2549
  _OP_REQP = ["instance_name", "force"]
2550
  REQ_BGL = False
2551

    
2552
  def ExpandNames(self):
2553
    self._ExpandAndLockInstance()
2554

    
2555
  def BuildHooksEnv(self):
2556
    """Build hooks env.
2557

2558
    This runs on master, primary and secondary nodes of the instance.
2559

2560
    """
2561
    env = {
2562
      "FORCE": self.op.force,
2563
      }
2564
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2565
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2566
          list(self.instance.secondary_nodes))
2567
    return env, nl, nl
2568

    
2569
  def CheckPrereq(self):
2570
    """Check prerequisites.
2571

2572
    This checks that the instance is in the cluster.
2573

2574
    """
2575
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2576
    assert self.instance is not None, \
2577
      "Cannot retrieve locked instance %s" % self.op.instance_name
2578

    
2579
    _CheckNodeOnline(self, instance.primary_node)
2580

    
2581
    bep = self.cfg.GetClusterInfo().FillBE(instance)
2582
    # check bridges existance
2583
    _CheckInstanceBridgesExist(self, instance)
2584

    
2585
    _CheckNodeFreeMemory(self, instance.primary_node,
2586
                         "starting instance %s" % instance.name,
2587
                         bep[constants.BE_MEMORY], instance.hypervisor)
2588

    
2589
  def Exec(self, feedback_fn):
2590
    """Start the instance.
2591

2592
    """
2593
    instance = self.instance
2594
    force = self.op.force
2595
    extra_args = getattr(self.op, "extra_args", "")
2596

    
2597
    self.cfg.MarkInstanceUp(instance.name)
2598

    
2599
    node_current = instance.primary_node
2600

    
2601
    _StartInstanceDisks(self, instance, force)
2602

    
2603
    result = self.rpc.call_instance_start(node_current, instance, extra_args)
2604
    if result.failed or not result.data:
2605
      _ShutdownInstanceDisks(self, instance)
2606
      raise errors.OpExecError("Could not start instance")
2607

    
2608

    
2609
class LURebootInstance(LogicalUnit):
2610
  """Reboot an instance.
2611

2612
  """
2613
  HPATH = "instance-reboot"
2614
  HTYPE = constants.HTYPE_INSTANCE
2615
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
2616
  REQ_BGL = False
2617

    
2618
  def ExpandNames(self):
2619
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
2620
                                   constants.INSTANCE_REBOOT_HARD,
2621
                                   constants.INSTANCE_REBOOT_FULL]:
2622
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
2623
                                  (constants.INSTANCE_REBOOT_SOFT,
2624
                                   constants.INSTANCE_REBOOT_HARD,
2625
                                   constants.INSTANCE_REBOOT_FULL))
2626
    self._ExpandAndLockInstance()
2627

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

2631
    This runs on master, primary and secondary nodes of the instance.
2632

2633
    """
2634
    env = {
2635
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
2636
      }
2637
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2638
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2639
          list(self.instance.secondary_nodes))
2640
    return env, nl, nl
2641

    
2642
  def CheckPrereq(self):
2643
    """Check prerequisites.
2644

2645
    This checks that the instance is in the cluster.
2646

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

    
2652
    _CheckNodeOnline(self, instance.primary_node)
2653

    
2654
    # check bridges existance
2655
    _CheckInstanceBridgesExist(self, instance)
2656

    
2657
  def Exec(self, feedback_fn):
2658
    """Reboot the instance.
2659

2660
    """
2661
    instance = self.instance
2662
    ignore_secondaries = self.op.ignore_secondaries
2663
    reboot_type = self.op.reboot_type
2664
    extra_args = getattr(self.op, "extra_args", "")
2665

    
2666
    node_current = instance.primary_node
2667

    
2668
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
2669
                       constants.INSTANCE_REBOOT_HARD]:
2670
      result = self.rpc.call_instance_reboot(node_current, instance,
2671
                                             reboot_type, extra_args)
2672
      if result.failed or not result.data:
2673
        raise errors.OpExecError("Could not reboot instance")
2674
    else:
2675
      if not self.rpc.call_instance_shutdown(node_current, instance):
2676
        raise errors.OpExecError("could not shutdown instance for full reboot")
2677
      _ShutdownInstanceDisks(self, instance)
2678
      _StartInstanceDisks(self, instance, ignore_secondaries)
2679
      result = self.rpc.call_instance_start(node_current, instance, extra_args)
2680
      if result.failed or not result.data:
2681
        _ShutdownInstanceDisks(self, instance)
2682
        raise errors.OpExecError("Could not start instance for full reboot")
2683

    
2684
    self.cfg.MarkInstanceUp(instance.name)
2685

    
2686

    
2687
class LUShutdownInstance(LogicalUnit):
2688
  """Shutdown an instance.
2689

2690
  """
2691
  HPATH = "instance-stop"
2692
  HTYPE = constants.HTYPE_INSTANCE
2693
  _OP_REQP = ["instance_name"]
2694
  REQ_BGL = False
2695

    
2696
  def ExpandNames(self):
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 = _BuildInstanceHookEnvByObject(self, self.instance)
2706
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2707
          list(self.instance.secondary_nodes))
2708
    return env, nl, nl
2709

    
2710
  def CheckPrereq(self):
2711
    """Check prerequisites.
2712

2713
    This checks that the instance is in the cluster.
2714

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

    
2721
  def Exec(self, feedback_fn):
2722
    """Shutdown the instance.
2723

2724
    """
2725
    instance = self.instance
2726
    node_current = instance.primary_node
2727
    self.cfg.MarkInstanceDown(instance.name)
2728
    result = self.rpc.call_instance_shutdown(node_current, instance)
2729
    if result.failed or not result.data:
2730
      self.proc.LogWarning("Could not shutdown instance")
2731

    
2732
    _ShutdownInstanceDisks(self, instance)
2733

    
2734

    
2735
class LUReinstallInstance(LogicalUnit):
2736
  """Reinstall an instance.
2737

2738
  """
2739
  HPATH = "instance-reinstall"
2740
  HTYPE = constants.HTYPE_INSTANCE
2741
  _OP_REQP = ["instance_name"]
2742
  REQ_BGL = False
2743

    
2744
  def ExpandNames(self):
2745
    self._ExpandAndLockInstance()
2746

    
2747
  def BuildHooksEnv(self):
2748
    """Build hooks env.
2749

2750
    This runs on master, primary and secondary nodes of the instance.
2751

2752
    """
2753
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2754
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2755
          list(self.instance.secondary_nodes))
2756
    return env, nl, nl
2757

    
2758
  def CheckPrereq(self):
2759
    """Check prerequisites.
2760

2761
    This checks that the instance is in the cluster and is not running.
2762

2763
    """
2764
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2765
    assert instance is not None, \
2766
      "Cannot retrieve locked instance %s" % self.op.instance_name
2767
    _CheckNodeOnline(self, instance.primary_node)
2768

    
2769
    if instance.disk_template == constants.DT_DISKLESS:
2770
      raise errors.OpPrereqError("Instance '%s' has no disks" %
2771
                                 self.op.instance_name)
2772
    if instance.status != "down":
2773
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2774
                                 self.op.instance_name)
2775
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2776
                                              instance.name,
2777
                                              instance.hypervisor)
2778
    if remote_info.failed or remote_info.data:
2779
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2780
                                 (self.op.instance_name,
2781
                                  instance.primary_node))
2782

    
2783
    self.op.os_type = getattr(self.op, "os_type", None)
2784
    if self.op.os_type is not None:
2785
      # OS verification
2786
      pnode = self.cfg.GetNodeInfo(
2787
        self.cfg.ExpandNodeName(instance.primary_node))
2788
      if pnode is None:
2789
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
2790
                                   self.op.pnode)
2791
      result = self.rpc.call_os_get(pnode.name, self.op.os_type)
2792
      result.Raise()
2793
      if not isinstance(result.data, objects.OS):
2794
        raise errors.OpPrereqError("OS '%s' not in supported OS list for"
2795
                                   " primary node"  % self.op.os_type)
2796

    
2797
    self.instance = instance
2798

    
2799
  def Exec(self, feedback_fn):
2800
    """Reinstall the instance.
2801

2802
    """
2803
    inst = self.instance
2804

    
2805
    if self.op.os_type is not None:
2806
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
2807
      inst.os = self.op.os_type
2808
      self.cfg.Update(inst)
2809

    
2810
    _StartInstanceDisks(self, inst, None)
2811
    try:
2812
      feedback_fn("Running the instance OS create scripts...")
2813
      result = self.rpc.call_instance_os_add(inst.primary_node, inst)
2814
      result.Raise()
2815
      if not result.data:
2816
        raise errors.OpExecError("Could not install OS for instance %s"
2817
                                 " on node %s" %
2818
                                 (inst.name, inst.primary_node))
2819
    finally:
2820
      _ShutdownInstanceDisks(self, inst)
2821

    
2822

    
2823
class LURenameInstance(LogicalUnit):
2824
  """Rename an instance.
2825

2826
  """
2827
  HPATH = "instance-rename"
2828
  HTYPE = constants.HTYPE_INSTANCE
2829
  _OP_REQP = ["instance_name", "new_name"]
2830

    
2831
  def BuildHooksEnv(self):
2832
    """Build hooks env.
2833

2834
    This runs on master, primary and secondary nodes of the instance.
2835

2836
    """
2837
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2838
    env["INSTANCE_NEW_NAME"] = self.op.new_name
2839
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2840
          list(self.instance.secondary_nodes))
2841
    return env, nl, nl
2842

    
2843
  def CheckPrereq(self):
2844
    """Check prerequisites.
2845

2846
    This checks that the instance is in the cluster and is not running.
2847

2848
    """
2849
    instance = self.cfg.GetInstanceInfo(
2850
      self.cfg.ExpandInstanceName(self.op.instance_name))
2851
    if instance is None:
2852
      raise errors.OpPrereqError("Instance '%s' not known" %
2853
                                 self.op.instance_name)
2854
    _CheckNodeOnline(self, instance.primary_node)
2855

    
2856
    if instance.status != "down":
2857
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2858
                                 self.op.instance_name)
2859
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2860
                                              instance.name,
2861
                                              instance.hypervisor)
2862
    remote_info.Raise()
2863
    if remote_info.data:
2864
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2865
                                 (self.op.instance_name,
2866
                                  instance.primary_node))
2867
    self.instance = instance
2868

    
2869
    # new name verification
2870
    name_info = utils.HostInfo(self.op.new_name)
2871

    
2872
    self.op.new_name = new_name = name_info.name
2873
    instance_list = self.cfg.GetInstanceList()
2874
    if new_name in instance_list:
2875
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
2876
                                 new_name)
2877

    
2878
    if not getattr(self.op, "ignore_ip", False):
2879
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
2880
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
2881
                                   (name_info.ip, new_name))
2882

    
2883

    
2884
  def Exec(self, feedback_fn):
2885
    """Reinstall the instance.
2886

2887
    """
2888
    inst = self.instance
2889
    old_name = inst.name
2890

    
2891
    if inst.disk_template == constants.DT_FILE:
2892
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2893

    
2894
    self.cfg.RenameInstance(inst.name, self.op.new_name)
2895
    # Change the instance lock. This is definitely safe while we hold the BGL
2896
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
2897
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
2898

    
2899
    # re-read the instance from the configuration after rename
2900
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
2901

    
2902
    if inst.disk_template == constants.DT_FILE:
2903
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2904
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
2905
                                                     old_file_storage_dir,
2906
                                                     new_file_storage_dir)
2907
      result.Raise()
2908
      if not result.data:
2909
        raise errors.OpExecError("Could not connect to node '%s' to rename"
2910
                                 " directory '%s' to '%s' (but the instance"
2911
                                 " has been renamed in Ganeti)" % (
2912
                                 inst.primary_node, old_file_storage_dir,
2913
                                 new_file_storage_dir))
2914

    
2915
      if not result.data[0]:
2916
        raise errors.OpExecError("Could not rename directory '%s' to '%s'"
2917
                                 " (but the instance has been renamed in"
2918
                                 " Ganeti)" % (old_file_storage_dir,
2919
                                               new_file_storage_dir))
2920

    
2921
    _StartInstanceDisks(self, inst, None)
2922
    try:
2923
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
2924
                                                 old_name)
2925
      if result.failed or not result.data:
2926
        msg = ("Could not run OS rename script for instance %s on node %s"
2927
               " (but the instance has been renamed in Ganeti)" %
2928
               (inst.name, inst.primary_node))
2929
        self.proc.LogWarning(msg)
2930
    finally:
2931
      _ShutdownInstanceDisks(self, inst)
2932

    
2933

    
2934
class LURemoveInstance(LogicalUnit):
2935
  """Remove an instance.
2936

2937
  """
2938
  HPATH = "instance-remove"
2939
  HTYPE = constants.HTYPE_INSTANCE
2940
  _OP_REQP = ["instance_name", "ignore_failures"]
2941
  REQ_BGL = False
2942

    
2943
  def ExpandNames(self):
2944
    self._ExpandAndLockInstance()
2945
    self.needed_locks[locking.LEVEL_NODE] = []
2946
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2947

    
2948
  def DeclareLocks(self, level):
2949
    if level == locking.LEVEL_NODE:
2950
      self._LockInstancesNodes()
2951

    
2952
  def BuildHooksEnv(self):
2953
    """Build hooks env.
2954

2955
    This runs on master, primary and secondary nodes of the instance.
2956

2957
    """
2958
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2959
    nl = [self.cfg.GetMasterNode()]
2960
    return env, nl, nl
2961

    
2962
  def CheckPrereq(self):
2963
    """Check prerequisites.
2964

2965
    This checks that the instance is in the cluster.
2966

2967
    """
2968
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2969
    assert self.instance is not None, \
2970
      "Cannot retrieve locked instance %s" % self.op.instance_name
2971

    
2972
  def Exec(self, feedback_fn):
2973
    """Remove the instance.
2974

2975
    """
2976
    instance = self.instance
2977
    logging.info("Shutting down instance %s on node %s",
2978
                 instance.name, instance.primary_node)
2979

    
2980
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance)
2981
    if result.failed or not result.data:
2982
      if self.op.ignore_failures:
2983
        feedback_fn("Warning: can't shutdown instance")
2984
      else:
2985
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
2986
                                 (instance.name, instance.primary_node))
2987

    
2988
    logging.info("Removing block devices for instance %s", instance.name)
2989

    
2990
    if not _RemoveDisks(self, instance):
2991
      if self.op.ignore_failures:
2992
        feedback_fn("Warning: can't remove instance's disks")
2993
      else:
2994
        raise errors.OpExecError("Can't remove instance's disks")
2995

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

    
2998
    self.cfg.RemoveInstance(instance.name)
2999
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
3000

    
3001

    
3002
class LUQueryInstances(NoHooksLU):
3003
  """Logical unit for querying instances.
3004

3005
  """
3006
  _OP_REQP = ["output_fields", "names"]
3007
  REQ_BGL = False
3008
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
3009
                                    "admin_state", "admin_ram",
3010
                                    "disk_template", "ip", "mac", "bridge",
3011
                                    "sda_size", "sdb_size", "vcpus", "tags",
3012
                                    "network_port", "beparams",
3013
                                    "(disk).(size)/([0-9]+)",
3014
                                    "(disk).(sizes)",
3015
                                    "(nic).(mac|ip|bridge)/([0-9]+)",
3016
                                    "(nic).(macs|ips|bridges)",
3017
                                    "(disk|nic).(count)",
3018
                                    "serial_no", "hypervisor", "hvparams",] +
3019
                                  ["hv/%s" % name
3020
                                   for name in constants.HVS_PARAMETERS] +
3021
                                  ["be/%s" % name
3022
                                   for name in constants.BES_PARAMETERS])
3023
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
3024

    
3025

    
3026
  def ExpandNames(self):
3027
    _CheckOutputFields(static=self._FIELDS_STATIC,
3028
                       dynamic=self._FIELDS_DYNAMIC,
3029
                       selected=self.op.output_fields)
3030

    
3031
    self.needed_locks = {}
3032
    self.share_locks[locking.LEVEL_INSTANCE] = 1
3033
    self.share_locks[locking.LEVEL_NODE] = 1
3034

    
3035
    if self.op.names:
3036
      self.wanted = _GetWantedInstances(self, self.op.names)
3037
    else:
3038
      self.wanted = locking.ALL_SET
3039

    
3040
    self.do_locking = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3041
    if self.do_locking:
3042
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
3043
      self.needed_locks[locking.LEVEL_NODE] = []
3044
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3045

    
3046
  def DeclareLocks(self, level):
3047
    if level == locking.LEVEL_NODE and self.do_locking:
3048
      self._LockInstancesNodes()
3049

    
3050
  def CheckPrereq(self):
3051
    """Check prerequisites.
3052

3053
    """
3054
    pass
3055

    
3056
  def Exec(self, feedback_fn):
3057
    """Computes the list of nodes and their attributes.
3058

3059
    """
3060
    all_info = self.cfg.GetAllInstancesInfo()
3061
    if self.do_locking:
3062
      instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
3063
    elif self.wanted != locking.ALL_SET:
3064
      instance_names = self.wanted
3065
      missing = set(instance_names).difference(all_info.keys())
3066
      if missing:
3067
        raise errors.OpExecError(
3068
          "Some instances were removed before retrieving their data: %s"
3069
          % missing)
3070
    else:
3071
      instance_names = all_info.keys()
3072

    
3073
    instance_names = utils.NiceSort(instance_names)
3074
    instance_list = [all_info[iname] for iname in instance_names]
3075

    
3076
    # begin data gathering
3077

    
3078
    nodes = frozenset([inst.primary_node for inst in instance_list])
3079
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
3080

    
3081
    bad_nodes = []
3082
    off_nodes = []
3083
    if self.do_locking:
3084
      live_data = {}
3085
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
3086
      for name in nodes:
3087
        result = node_data[name]
3088
        if result.offline:
3089
          # offline nodes will be in both lists
3090
          off_nodes.append(name)
3091
        if result.failed:
3092
          bad_nodes.append(name)
3093
        else:
3094
          if result.data:
3095
            live_data.update(result.data)
3096
            # else no instance is alive
3097
    else:
3098
      live_data = dict([(name, {}) for name in instance_names])
3099

    
3100
    # end data gathering
3101

    
3102
    HVPREFIX = "hv/"
3103
    BEPREFIX = "be/"
3104
    output = []
3105
    for instance in instance_list:
3106
      iout = []
3107
      i_hv = self.cfg.GetClusterInfo().FillHV(instance)
3108
      i_be = self.cfg.GetClusterInfo().FillBE(instance)
3109
      for field in self.op.output_fields:
3110
        st_match = self._FIELDS_STATIC.Matches(field)
3111
        if field == "name":
3112
          val = instance.name
3113
        elif field == "os":
3114
          val = instance.os
3115
        elif field == "pnode":
3116
          val = instance.primary_node
3117
        elif field == "snodes":
3118
          val = list(instance.secondary_nodes)
3119
        elif field == "admin_state":
3120
          val = (instance.status != "down")
3121
        elif field == "oper_state":
3122
          if instance.primary_node in bad_nodes:
3123
            val = None
3124
          else:
3125
            val = bool(live_data.get(instance.name))
3126
        elif field == "status":
3127
          if instance.primary_node in off_nodes:
3128
            val = "ERROR_nodeoffline"
3129
          elif instance.primary_node in bad_nodes:
3130
            val = "ERROR_nodedown"
3131
          else:
3132
            running = bool(live_data.get(instance.name))
3133
            if running:
3134
              if instance.status != "down":
3135
                val = "running"
3136
              else:
3137
                val = "ERROR_up"
3138
            else:
3139
              if instance.status != "down":
3140
                val = "ERROR_down"
3141
              else:
3142
                val = "ADMIN_down"
3143
        elif field == "oper_ram":
3144
          if instance.primary_node in bad_nodes:
3145
            val = None
3146
          elif instance.name in live_data:
3147
            val = live_data[instance.name].get("memory", "?")
3148
          else:
3149
            val = "-"
3150
        elif field == "disk_template":
3151
          val = instance.disk_template
3152
        elif field == "ip":
3153
          val = instance.nics[0].ip
3154
        elif field == "bridge":
3155
          val = instance.nics[0].bridge
3156
        elif field == "mac":
3157
          val = instance.nics[0].mac
3158
        elif field == "sda_size" or field == "sdb_size":
3159
          idx = ord(field[2]) - ord('a')
3160
          try:
3161
            val = instance.FindDisk(idx).size
3162
          except errors.OpPrereqError:
3163
            val = None
3164
        elif field == "tags":
3165
          val = list(instance.GetTags())
3166
        elif field == "serial_no":
3167
          val = instance.serial_no
3168
        elif field == "network_port":
3169
          val = instance.network_port
3170
        elif field == "hypervisor":
3171
          val = instance.hypervisor
3172
        elif field == "hvparams":
3173
          val = i_hv
3174
        elif (field.startswith(HVPREFIX) and
3175
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS):
3176
          val = i_hv.get(field[len(HVPREFIX):], None)
3177
        elif field == "beparams":
3178
          val = i_be
3179
        elif (field.startswith(BEPREFIX) and
3180
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
3181
          val = i_be.get(field[len(BEPREFIX):], None)
3182
        elif st_match and st_match.groups():
3183
          # matches a variable list
3184
          st_groups = st_match.groups()
3185
          if st_groups and st_groups[0] == "disk":
3186
            if st_groups[1] == "count":
3187
              val = len(instance.disks)
3188
            elif st_groups[1] == "sizes":
3189
              val = [disk.size for disk in instance.disks]
3190
            elif st_groups[1] == "size":
3191
              try:
3192
                val = instance.FindDisk(st_groups[2]).size
3193
              except errors.OpPrereqError:
3194
                val = None
3195
            else:
3196
              assert False, "Unhandled disk parameter"
3197
          elif st_groups[0] == "nic":
3198
            if st_groups[1] == "count":
3199
              val = len(instance.nics)
3200
            elif st_groups[1] == "macs":
3201
              val = [nic.mac for nic in instance.nics]
3202
            elif st_groups[1] == "ips":
3203
              val = [nic.ip for nic in instance.nics]
3204
            elif st_groups[1] == "bridges":
3205
              val = [nic.bridge for nic in instance.nics]
3206
            else:
3207
              # index-based item
3208
              nic_idx = int(st_groups[2])
3209
              if nic_idx >= len(instance.nics):
3210
                val = None
3211
              else:
3212
                if st_groups[1] == "mac":
3213
                  val = instance.nics[nic_idx].mac
3214
                elif st_groups[1] == "ip":
3215
                  val = instance.nics[nic_idx].ip
3216
                elif st_groups[1] == "bridge":
3217
                  val = instance.nics[nic_idx].bridge
3218
                else:
3219
                  assert False, "Unhandled NIC parameter"
3220
          else:
3221
            assert False, "Unhandled variable parameter"
3222
        else:
3223
          raise errors.ParameterError(field)
3224
        iout.append(val)
3225
      output.append(iout)
3226

    
3227
    return output
3228

    
3229

    
3230
class LUFailoverInstance(LogicalUnit):
3231
  """Failover an instance.
3232

3233
  """
3234
  HPATH = "instance-failover"
3235
  HTYPE = constants.HTYPE_INSTANCE
3236
  _OP_REQP = ["instance_name", "ignore_consistency"]
3237
  REQ_BGL = False
3238

    
3239
  def ExpandNames(self):
3240
    self._ExpandAndLockInstance()
3241
    self.needed_locks[locking.LEVEL_NODE] = []
3242
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3243

    
3244
  def DeclareLocks(self, level):
3245
    if level == locking.LEVEL_NODE:
3246
      self._LockInstancesNodes()
3247

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

3251
    This runs on master, primary and secondary nodes of the instance.
3252

3253
    """
3254
    env = {
3255
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
3256
      }
3257
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3258
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
3259
    return env, nl, nl
3260

    
3261
  def CheckPrereq(self):
3262
    """Check prerequisites.
3263

3264
    This checks that the instance is in the cluster.
3265

3266
    """
3267
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3268
    assert self.instance is not None, \
3269
      "Cannot retrieve locked instance %s" % self.op.instance_name
3270

    
3271
    bep = self.cfg.GetClusterInfo().FillBE(instance)
3272
    if instance.disk_template not in constants.DTS_NET_MIRROR:
3273
      raise errors.OpPrereqError("Instance's disk layout is not"
3274
                                 " network mirrored, cannot failover.")
3275

    
3276
    secondary_nodes = instance.secondary_nodes
3277
    if not secondary_nodes:
3278
      raise errors.ProgrammerError("no secondary node but using "
3279
                                   "a mirrored disk template")
3280

    
3281
    target_node = secondary_nodes[0]
3282
    _CheckNodeOnline(self, target_node)
3283
    # check memory requirements on the secondary node
3284
    _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
3285
                         instance.name, bep[constants.BE_MEMORY],
3286
                         instance.hypervisor)
3287

    
3288
    # check bridge existance
3289
    brlist = [nic.bridge for nic in instance.nics]
3290
    result = self.rpc.call_bridges_exist(target_node, brlist)
3291
    result.Raise()
3292
    if not result.data:
3293
      raise errors.OpPrereqError("One or more target bridges %s does not"
3294
                                 " exist on destination node '%s'" %
3295
                                 (brlist, target_node))
3296

    
3297
  def Exec(self, feedback_fn):
3298
    """Failover an instance.
3299

3300
    The failover is done by shutting it down on its present node and
3301
    starting it on the secondary.
3302

3303
    """
3304
    instance = self.instance
3305

    
3306
    source_node = instance.primary_node
3307
    target_node = instance.secondary_nodes[0]
3308

    
3309
    feedback_fn("* checking disk consistency between source and target")
3310
    for dev in instance.disks:
3311
      # for drbd, these are drbd over lvm
3312
      if not _CheckDiskConsistency(self, dev, target_node, False):
3313
        if instance.status == "up" and not self.op.ignore_consistency:
3314
          raise errors.OpExecError("Disk %s is degraded on target node,"
3315
                                   " aborting failover." % dev.iv_name)
3316

    
3317
    feedback_fn("* shutting down instance on source node")
3318
    logging.info("Shutting down instance %s on node %s",
3319
                 instance.name, source_node)
3320

    
3321
    result = self.rpc.call_instance_shutdown(source_node, instance)
3322
    if result.failed or not result.data:
3323
      if self.op.ignore_consistency:
3324
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
3325
                             " Proceeding"
3326
                             " anyway. Please make sure node %s is down",
3327
                             instance.name, source_node, source_node)
3328
      else:
3329
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
3330
                                 (instance.name, source_node))
3331

    
3332
    feedback_fn("* deactivating the instance's disks on source node")
3333
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
3334
      raise errors.OpExecError("Can't shut down the instance's disks.")
3335

    
3336
    instance.primary_node = target_node
3337
    # distribute new instance config to the other nodes
3338
    self.cfg.Update(instance)
3339

    
3340
    # Only start the instance if it's marked as up
3341
    if instance.status == "up":
3342
      feedback_fn("* activating the instance's disks on target node")
3343
      logging.info("Starting instance %s on node %s",
3344
                   instance.name, target_node)
3345

    
3346
      disks_ok, dummy = _AssembleInstanceDisks(self, instance,
3347
                                               ignore_secondaries=True)
3348
      if not disks_ok:
3349
        _ShutdownInstanceDisks(self, instance)
3350
        raise errors.OpExecError("Can't activate the instance's disks")
3351

    
3352
      feedback_fn("* starting the instance on the target node")
3353
      result = self.rpc.call_instance_start(target_node, instance, None)
3354
      if result.failed or not result.data:
3355
        _ShutdownInstanceDisks(self, instance)
3356
        raise errors.OpExecError("Could not start instance %s on node %s." %
3357
                                 (instance.name, target_node))
3358

    
3359

    
3360
def _CreateBlockDevOnPrimary(lu, node, instance, device, info):
3361
  """Create a tree of block devices on the primary node.
3362

3363
  This always creates all devices.
3364

3365
  """
3366
  if device.children:
3367
    for child in device.children:
3368
      if not _CreateBlockDevOnPrimary(lu, node, instance, child, info):
3369
        return False
3370

    
3371
  lu.cfg.SetDiskID(device, node)
3372
  new_id = lu.rpc.call_blockdev_create(node, device, device.size,
3373
                                       instance.name, True, info)
3374
  if new_id.failed or not new_id.data:
3375
    return False
3376
  if device.physical_id is None:
3377
    device.physical_id = new_id
3378
  return True
3379

    
3380

    
3381
def _CreateBlockDevOnSecondary(lu, node, instance, device, force, info):
3382
  """Create a tree of block devices on a secondary node.
3383

3384
  If this device type has to be created on secondaries, create it and
3385
  all its children.
3386

3387
  If not, just recurse to children keeping the same 'force' value.
3388

3389
  """
3390
  if device.CreateOnSecondary():
3391
    force = True
3392
  if device.children:
3393
    for child in device.children:
3394
      if not _CreateBlockDevOnSecondary(lu, node, instance,
3395
                                        child, force, info):
3396
        return False
3397

    
3398
  if not force:
3399
    return True
3400
  lu.cfg.SetDiskID(device, node)
3401
  new_id = lu.rpc.call_blockdev_create(node, device, device.size,
3402
                                       instance.name, False, info)
3403
  if new_id.failed or not new_id.data:
3404
    return False
3405
  if device.physical_id is None:
3406
    device.physical_id = new_id
3407
  return True
3408

    
3409

    
3410
def _GenerateUniqueNames(lu, exts):
3411
  """Generate a suitable LV name.
3412

3413
  This will generate a logical volume name for the given instance.
3414

3415
  """
3416
  results = []
3417
  for val in exts:
3418
    new_id = lu.cfg.GenerateUniqueID()
3419
    results.append("%s%s" % (new_id, val))
3420
  return results
3421

    
3422

    
3423
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
3424
                         p_minor, s_minor):
3425
  """Generate a drbd8 device complete with its children.
3426

3427
  """
3428
  port = lu.cfg.AllocatePort()
3429
  vgname = lu.cfg.GetVGName()
3430
  shared_secret = lu.cfg.GenerateDRBDSecret()
3431
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
3432
                          logical_id=(vgname, names[0]))
3433
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
3434
                          logical_id=(vgname, names[1]))
3435
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
3436
                          logical_id=(primary, secondary, port,
3437
                                      p_minor, s_minor,
3438
                                      shared_secret),
3439
                          children=[dev_data, dev_meta],
3440
                          iv_name=iv_name)
3441
  return drbd_dev
3442

    
3443

    
3444
def _GenerateDiskTemplate(lu, template_name,
3445
                          instance_name, primary_node,
3446
                          secondary_nodes, disk_info,
3447
                          file_storage_dir, file_driver,
3448
                          base_index):
3449
  """Generate the entire disk layout for a given template type.
3450

3451
  """
3452
  #TODO: compute space requirements
3453

    
3454
  vgname = lu.cfg.GetVGName()
3455
  disk_count = len(disk_info)
3456
  disks = []
3457
  if template_name == constants.DT_DISKLESS:
3458
    pass
3459
  elif template_name == constants.DT_PLAIN:
3460
    if len(secondary_nodes) != 0:
3461
      raise errors.ProgrammerError("Wrong template configuration")
3462

    
3463
    names = _GenerateUniqueNames(lu, [".disk%d" % i
3464
                                      for i in range(disk_count)])
3465
    for idx, disk in enumerate(disk_info):
3466
      disk_index = idx + base_index
3467
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
3468
                              logical_id=(vgname, names[idx]),
3469
                              iv_name="disk/%d" % disk_index)
3470
      disks.append(disk_dev)
3471
  elif template_name == constants.DT_DRBD8:
3472
    if len(secondary_nodes) != 1:
3473
      raise errors.ProgrammerError("Wrong template configuration")
3474
    remote_node = secondary_nodes[0]
3475
    minors = lu.cfg.AllocateDRBDMinor(
3476
      [primary_node, remote_node] * len(disk_info), instance_name)
3477

    
3478
    names = _GenerateUniqueNames(lu,
3479
                                 [".disk%d_%s" % (i, s)
3480
                                  for i in range(disk_count)
3481
                                  for s in ("data", "meta")
3482
                                  ])
3483
    for idx, disk in enumerate(disk_info):
3484
      disk_index = idx + base_index
3485
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
3486
                                      disk["size"], names[idx*2:idx*2+2],
3487
                                      "disk/%d" % disk_index,
3488
                                      minors[idx*2], minors[idx*2+1])
3489
      disks.append(disk_dev)
3490
  elif template_name == constants.DT_FILE:
3491
    if len(secondary_nodes) != 0:
3492
      raise errors.ProgrammerError("Wrong template configuration")
3493

    
3494
    for idx, disk in enumerate(disk_info):
3495
      disk_index = idx + base_index
3496
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
3497
                              iv_name="disk/%d" % disk_index,
3498
                              logical_id=(file_driver,
3499
                                          "%s/disk%d" % (file_storage_dir,
3500
                                                         idx)))
3501
      disks.append(disk_dev)
3502
  else:
3503
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
3504
  return disks
3505

    
3506

    
3507
def _GetInstanceInfoText(instance):
3508
  """Compute that text that should be added to the disk's metadata.
3509

3510
  """
3511
  return "originstname+%s" % instance.name
3512

    
3513

    
3514
def _CreateDisks(lu, instance):
3515
  """Create all disks for an instance.
3516

3517
  This abstracts away some work from AddInstance.
3518

3519
  @type lu: L{LogicalUnit}
3520
  @param lu: the logical unit on whose behalf we execute
3521
  @type instance: L{objects.Instance}
3522
  @param instance: the instance whose disks we should create
3523
  @rtype: boolean
3524
  @return: the success of the creation
3525

3526
  """
3527
  info = _GetInstanceInfoText(instance)
3528

    
3529
  if instance.disk_template == constants.DT_FILE:
3530
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
3531
    result = lu.rpc.call_file_storage_dir_create(instance.primary_node,
3532
                                                 file_storage_dir)
3533

    
3534
    if result.failed or not result.data:
3535
      logging.error("Could not connect to node '%s'", instance.primary_node)
3536
      return False
3537

    
3538
    if not result.data[0]:
3539
      logging.error("Failed to create directory '%s'", file_storage_dir)
3540
      return False
3541

    
3542
  # Note: this needs to be kept in sync with adding of disks in
3543
  # LUSetInstanceParams
3544
  for device in instance.disks:
3545
    logging.info("Creating volume %s for instance %s",
3546
                 device.iv_name, instance.name)
3547
    #HARDCODE
3548
    for secondary_node in instance.secondary_nodes:
3549
      if not _CreateBlockDevOnSecondary(lu, secondary_node, instance,
3550
                                        device, False, info):
3551
        logging.error("Failed to create volume %s (%s) on secondary node %s!",
3552
                      device.iv_name, device, secondary_node)
3553
        return False
3554
    #HARDCODE
3555
    if not _CreateBlockDevOnPrimary(lu, instance.primary_node,
3556
                                    instance, device, info):
3557
      logging.error("Failed to create volume %s on primary!", device.iv_name)
3558
      return False
3559

    
3560
  return True
3561

    
3562

    
3563
def _RemoveDisks(lu, instance):
3564
  """Remove all disks for an instance.
3565

3566
  This abstracts away some work from `AddInstance()` and
3567
  `RemoveInstance()`. Note that in case some of the devices couldn't
3568
  be removed, the removal will continue with the other ones (compare
3569
  with `_CreateDisks()`).
3570

3571
  @type lu: L{LogicalUnit}
3572
  @param lu: the logical unit on whose behalf we execute
3573
  @type instance: L{objects.Instance}
3574
  @param instance: the instance whose disks we should remove
3575
  @rtype: boolean
3576
  @return: the success of the removal
3577

3578
  """
3579
  logging.info("Removing block devices for instance %s", instance.name)
3580

    
3581
  result = True
3582
  for device in instance.disks:
3583
    for node, disk in device.ComputeNodeTree(instance.primary_node):
3584
      lu.cfg.SetDiskID(disk, node)
3585
      result = lu.rpc.call_blockdev_remove(node, disk)
3586
      if result.failed or not result.data:
3587
        lu.proc.LogWarning("Could not remove block device %s on node %s,"
3588
                           " continuing anyway", device.iv_name, node)
3589
        result = False
3590

    
3591
  if instance.disk_template == constants.DT_FILE:
3592
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
3593
    result = lu.rpc.call_file_storage_dir_remove(instance.primary_node,
3594
                                                 file_storage_dir)
3595
    if result.failed or not result.data:
3596
      logging.error("Could not remove directory '%s'", file_storage_dir)
3597
      result = False
3598

    
3599
  return result
3600

    
3601

    
3602
def _ComputeDiskSize(disk_template, disks):
3603
  """Compute disk size requirements in the volume group
3604

3605
  """
3606
  # Required free disk space as a function of disk and swap space
3607
  req_size_dict = {
3608
    constants.DT_DISKLESS: None,
3609
    constants.DT_PLAIN: sum(d["size"] for d in disks),
3610
    # 128 MB are added for drbd metadata for each disk
3611
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
3612
    constants.DT_FILE: None,
3613
  }
3614

    
3615
  if disk_template not in req_size_dict:
3616
    raise errors.ProgrammerError("Disk template '%s' size requirement"
3617
                                 " is unknown" %  disk_template)
3618

    
3619
  return req_size_dict[disk_template]
3620

    
3621

    
3622
def _CheckHVParams(lu, nodenames, hvname, hvparams):
3623
  """Hypervisor parameter validation.
3624

3625
  This function abstract the hypervisor parameter validation to be
3626
  used in both instance create and instance modify.
3627

3628
  @type lu: L{LogicalUnit}
3629
  @param lu: the logical unit for which we check
3630
  @type nodenames: list
3631
  @param nodenames: the list of nodes on which we should check
3632
  @type hvname: string
3633
  @param hvname: the name of the hypervisor we should use
3634
  @type hvparams: dict
3635
  @param hvparams: the parameters which we need to check
3636
  @raise errors.OpPrereqError: if the parameters are not valid
3637

3638
  """
3639
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
3640
                                                  hvname,
3641
                                                  hvparams)
3642
  for node in nodenames:
3643
    info = hvinfo[node]
3644
    info.Raise()
3645
    if not info.data or not isinstance(info.data, (tuple, list)):
3646
      raise errors.OpPrereqError("Cannot get current information"
3647
                                 " from node '%s' (%s)" % (node, info.data))
3648
    if not info.data[0]:
3649
      raise errors.OpPrereqError("Hypervisor parameter validation failed:"
3650
                                 " %s" % info.data[1])
3651

    
3652

    
3653
class LUCreateInstance(LogicalUnit):
3654
  """Create an instance.
3655

3656
  """
3657
  HPATH = "instance-add"
3658
  HTYPE = constants.HTYPE_INSTANCE
3659
  _OP_REQP = ["instance_name", "disks", "disk_template",
3660
              "mode", "start",
3661
              "wait_for_sync", "ip_check", "nics",
3662
              "hvparams", "beparams"]
3663
  REQ_BGL = False
3664

    
3665
  def _ExpandNode(self, node):
3666
    """Expands and checks one node name.
3667

3668
    """
3669
    node_full = self.cfg.ExpandNodeName(node)
3670
    if node_full is None:
3671
      raise errors.OpPrereqError("Unknown node %s" % node)
3672
    return node_full
3673

    
3674
  def ExpandNames(self):
3675
    """ExpandNames for CreateInstance.
3676

3677
    Figure out the right locks for instance creation.
3678

3679
    """
3680
    self.needed_locks = {}
3681

    
3682
    # set optional parameters to none if they don't exist
3683
    for attr in ["pnode", "snode", "iallocator", "hypervisor"]:
3684
      if not hasattr(self.op, attr):
3685
        setattr(self.op, attr, None)
3686

    
3687
    # cheap checks, mostly valid constants given
3688

    
3689
    # verify creation mode
3690
    if self.op.mode not in (constants.INSTANCE_CREATE,
3691
                            constants.INSTANCE_IMPORT):
3692
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
3693
                                 self.op.mode)
3694

    
3695
    # disk template and mirror node verification
3696
    if self.op.disk_template not in constants.DISK_TEMPLATES:
3697
      raise errors.OpPrereqError("Invalid disk template name")
3698

    
3699
    if self.op.hypervisor is None:
3700
      self.op.hypervisor = self.cfg.GetHypervisorType()
3701

    
3702
    cluster = self.cfg.GetClusterInfo()
3703
    enabled_hvs = cluster.enabled_hypervisors
3704
    if self.op.hypervisor not in enabled_hvs:
3705
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
3706
                                 " cluster (%s)" % (self.op.hypervisor,
3707
                                  ",".join(enabled_hvs)))
3708

    
3709
    # check hypervisor parameter syntax (locally)
3710

    
3711
    filled_hvp = cluster.FillDict(cluster.hvparams[self.op.hypervisor],
3712
                                  self.op.hvparams)
3713
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
3714
    hv_type.CheckParameterSyntax(filled_hvp)
3715

    
3716
    # fill and remember the beparams dict
3717
    utils.CheckBEParams(self.op.beparams)
3718
    self.be_full = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
3719
                                    self.op.beparams)
3720

    
3721
    #### instance parameters check
3722

    
3723
    # instance name verification
3724
    hostname1 = utils.HostInfo(self.op.instance_name)
3725
    self.op.instance_name = instance_name = hostname1.name
3726

    
3727
    # this is just a preventive check, but someone might still add this
3728
    # instance in the meantime, and creation will fail at lock-add time
3729
    if instance_name in self.cfg.GetInstanceList():
3730
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
3731
                                 instance_name)
3732

    
3733
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
3734

    
3735
    # NIC buildup
3736
    self.nics = []
3737
    for nic in self.op.nics:
3738
      # ip validity checks
3739
      ip = nic.get("ip", None)
3740
      if ip is None or ip.lower() == "none":
3741
        nic_ip = None
3742
      elif ip.lower() == constants.VALUE_AUTO:
3743
        nic_ip = hostname1.ip
3744
      else:
3745
        if not utils.IsValidIP(ip):
3746
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
3747
                                     " like a valid IP" % ip)
3748
        nic_ip = ip
3749

    
3750
      # MAC address verification
3751
      mac = nic.get("mac", constants.VALUE_AUTO)
3752
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
3753
        if not utils.IsValidMac(mac.lower()):
3754
          raise errors.OpPrereqError("Invalid MAC address specified: %s" %
3755
                                     mac)
3756
      # bridge verification
3757
      bridge = nic.get("bridge", self.cfg.GetDefBridge())
3758
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, bridge=bridge))
3759

    
3760
    # disk checks/pre-build
3761
    self.disks = []
3762
    for disk in self.op.disks:
3763
      mode = disk.get("mode", constants.DISK_RDWR)
3764
      if mode not in constants.DISK_ACCESS_SET:
3765
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
3766
                                   mode)
3767
      size = disk.get("size", None)
3768
      if size is None:
3769
        raise errors.OpPrereqError("Missing disk size")
3770
      try:
3771
        size = int(size)
3772
      except ValueError:
3773
        raise errors.OpPrereqError("Invalid disk size '%s'" % size)
3774
      self.disks.append({"size": size, "mode": mode})
3775

    
3776
    # used in CheckPrereq for ip ping check
3777
    self.check_ip = hostname1.ip
3778

    
3779
    # file storage checks
3780
    if (self.op.file_driver and
3781
        not self.op.file_driver in constants.FILE_DRIVER):
3782
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
3783
                                 self.op.file_driver)
3784

    
3785
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
3786
      raise errors.OpPrereqError("File storage directory path not absolute")
3787

    
3788
    ### Node/iallocator related checks
3789
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
3790
      raise errors.OpPrereqError("One and only one of iallocator and primary"
3791
                                 " node must be given")
3792

    
3793
    if self.op.iallocator:
3794
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3795
    else:
3796
      self.op.pnode = self._ExpandNode(self.op.pnode)
3797
      nodelist = [self.op.pnode]
3798
      if self.op.snode is not None:
3799
        self.op.snode = self._ExpandNode(self.op.snode)
3800
        nodelist.append(self.op.snode)
3801
      self.needed_locks[locking.LEVEL_NODE] = nodelist
3802

    
3803
    # in case of import lock the source node too
3804
    if self.op.mode == constants.INSTANCE_IMPORT:
3805
      src_node = getattr(self.op, "src_node", None)
3806
      src_path = getattr(self.op, "src_path", None)
3807

    
3808
      if src_path is None:
3809
        self.op.src_path = src_path = self.op.instance_name
3810

    
3811
      if src_node is None:
3812
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3813
        self.op.src_node = None
3814
        if os.path.isabs(src_path):
3815
          raise errors.OpPrereqError("Importing an instance from an absolute"
3816
                                     " path requires a source node option.")
3817
      else:
3818
        self.op.src_node = src_node = self._ExpandNode(src_node)
3819
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
3820
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
3821
        if not os.path.isabs(src_path):
3822
          self.op.src_path = src_path = \
3823
            os.path.join(constants.EXPORT_DIR, src_path)
3824

    
3825
    else: # INSTANCE_CREATE
3826
      if getattr(self.op, "os_type", None) is None:
3827
        raise errors.OpPrereqError("No guest OS specified")
3828

    
3829
  def _RunAllocator(self):
3830
    """Run the allocator based on input opcode.
3831

3832
    """
3833
    nics = [n.ToDict() for n in self.nics]
3834
    ial = IAllocator(self,
3835
                     mode=constants.IALLOCATOR_MODE_ALLOC,
3836
                     name=self.op.instance_name,
3837
                     disk_template=self.op.disk_template,
3838
                     tags=[],
3839
                     os=self.op.os_type,
3840
                     vcpus=self.be_full[constants.BE_VCPUS],
3841
                     mem_size=self.be_full[constants.BE_MEMORY],
3842
                     disks=self.disks,
3843
                     nics=nics,
3844
                     hypervisor=self.op.hypervisor,
3845
                     )
3846

    
3847
    ial.Run(self.op.iallocator)
3848

    
3849
    if not ial.success:
3850
      raise errors.OpPrereqError("Can't compute nodes using"
3851
                                 " iallocator '%s': %s" % (self.op.iallocator,
3852
                                                           ial.info))
3853
    if len(ial.nodes) != ial.required_nodes:
3854
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
3855
                                 " of nodes (%s), required %s" %
3856
                                 (self.op.iallocator, len(ial.nodes),
3857
                                  ial.required_nodes))
3858
    self.op.pnode = ial.nodes[0]
3859
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
3860
                 self.op.instance_name, self.op.iallocator,
3861
                 ", ".join(ial.nodes))
3862
    if ial.required_nodes == 2:
3863
      self.op.snode = ial.nodes[1]
3864

    
3865
  def BuildHooksEnv(self):
3866
    """Build hooks env.
3867

3868
    This runs on master, primary and secondary nodes of the instance.
3869

3870
    """
3871
    env = {
3872
      "INSTANCE_DISK_TEMPLATE": self.op.disk_template,
3873
      "INSTANCE_DISK_SIZE": ",".join(str(d["size"]) for d in self.disks),
3874
      "INSTANCE_ADD_MODE": self.op.mode,
3875
      }
3876
    if self.op.mode == constants.INSTANCE_IMPORT:
3877
      env["INSTANCE_SRC_NODE"] = self.op.src_node
3878
      env["INSTANCE_SRC_PATH"] = self.op.src_path
3879
      env["INSTANCE_SRC_IMAGES"] = self.src_images
3880

    
3881
    env.update(_BuildInstanceHookEnv(name=self.op.instance_name,
3882
      primary_node=self.op.pnode,
3883
      secondary_nodes=self.secondaries,
3884
      status=self.instance_status,
3885
      os_type=self.op.os_type,
3886
      memory=self.be_full[constants.BE_MEMORY],
3887
      vcpus=self.be_full[constants.BE_VCPUS],
3888
      nics=[(n.ip, n.bridge, n.mac) for n in self.nics],
3889
    ))
3890

    
3891
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
3892
          self.secondaries)
3893
    return env, nl, nl
3894

    
3895

    
3896
  def CheckPrereq(self):
3897
    """Check prerequisites.
3898

3899
    """
3900
    if (not self.cfg.GetVGName() and
3901
        self.op.disk_template not in constants.DTS_NOT_LVM):
3902
      raise errors.OpPrereqError("Cluster does not support lvm-based"
3903
                                 " instances")
3904

    
3905

    
3906
    if self.op.mode == constants.INSTANCE_IMPORT:
3907
      src_node = self.op.src_node
3908
      src_path = self.op.src_path
3909

    
3910
      if src_node is None:
3911
        exp_list = self.rpc.call_export_list(
3912
          self.acquired_locks[locking.LEVEL_NODE])
3913
        found = False
3914
        for node in exp_list:
3915
          if not exp_list[node].failed and src_path in exp_list[node].data:
3916
            found = True
3917
            self.op.src_node = src_node = node
3918
            self.op.src_path = src_path = os.path.join(constants.EXPORT_DIR,
3919
                                                       src_path)
3920
            break
3921
        if not found:
3922
          raise errors.OpPrereqError("No export found for relative path %s" %
3923
                                      src_path)
3924

    
3925
      _CheckNodeOnline(self, src_node)
3926
      result = self.rpc.call_export_info(src_node, src_path)
3927
      result.Raise()
3928
      if not result.data:
3929
        raise errors.OpPrereqError("No export found in dir %s" % src_path)
3930

    
3931
      export_info = result.data
3932
      if not export_info.has_section(constants.INISECT_EXP):
3933
        raise errors.ProgrammerError("Corrupted export config")
3934

    
3935
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
3936
      if (int(ei_version) != constants.EXPORT_VERSION):
3937
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
3938
                                   (ei_version, constants.EXPORT_VERSION))
3939

    
3940
      # Check that the new instance doesn't have less disks than the export
3941
      instance_disks = len(self.disks)
3942
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
3943
      if instance_disks < export_disks:
3944
        raise errors.OpPrereqError("Not enough disks to import."
3945
                                   " (instance: %d, export: %d)" %
3946
                                   (instance_disks, export_disks))
3947

    
3948
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
3949
      disk_images = []
3950
      for idx in range(export_disks):
3951
        option = 'disk%d_dump' % idx
3952
        if export_info.has_option(constants.INISECT_INS, option):
3953
          # FIXME: are the old os-es, disk sizes, etc. useful?
3954
          export_name = export_info.get(constants.INISECT_INS, option)
3955
          image = os.path.join(src_path, export_name)
3956
          disk_images.append(image)
3957
        else:
3958
          disk_images.append(False)
3959

    
3960
      self.src_images = disk_images
3961

    
3962
      old_name = export_info.get(constants.INISECT_INS, 'name')
3963
      # FIXME: int() here could throw a ValueError on broken exports
3964
      exp_nic_count = int(export_info.get(constants.INISECT_INS, 'nic_count'))
3965
      if self.op.instance_name == old_name:
3966
        for idx, nic in enumerate(self.nics):
3967
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
3968
            nic_mac_ini = 'nic%d_mac' % idx
3969
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
3970

    
3971
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
3972
    if self.op.start and not self.op.ip_check:
3973
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
3974
                                 " adding an instance in start mode")
3975

    
3976
    if self.op.ip_check:
3977
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
3978
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
3979
                                   (self.check_ip, self.op.instance_name))
3980

    
3981
    #### allocator run
3982

    
3983
    if self.op.iallocator is not None:
3984
      self._RunAllocator()
3985

    
3986
    #### node related checks
3987

    
3988
    # check primary node
3989
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
3990
    assert self.pnode is not None, \
3991
      "Cannot retrieve locked node %s" % self.op.pnode
3992
    if pnode.offline:
3993
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
3994
                                 pnode.name)
3995

    
3996
    self.secondaries = []
3997

    
3998
    # mirror node verification
3999
    if self.op.disk_template in constants.DTS_NET_MIRROR:
4000
      if self.op.snode is None:
4001
        raise errors.OpPrereqError("The networked disk templates need"
4002
                                   " a mirror node")
4003
      if self.op.snode == pnode.name:
4004
        raise errors.OpPrereqError("The secondary node cannot be"
4005
                                   " the primary node.")
4006
      self.secondaries.append(self.op.snode)
4007
      _CheckNodeOnline(self, self.op.snode)
4008

    
4009
    nodenames = [pnode.name] + self.secondaries
4010

    
4011
    req_size = _ComputeDiskSize(self.op.disk_template,
4012
                                self.disks)
4013

    
4014
    # Check lv size requirements
4015
    if req_size is not None:
4016
      nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
4017
                                         self.op.hypervisor)
4018
      for node in nodenames:
4019
        info = nodeinfo[node]
4020
        info.Raise()
4021
        info = info.data
4022
        if not info:
4023
          raise errors.OpPrereqError("Cannot get current information"
4024
                                     " from node '%s'" % node)
4025
        vg_free = info.get('vg_free', None)
4026
        if not isinstance(vg_free, int):
4027
          raise errors.OpPrereqError("Can't compute free disk space on"
4028
                                     " node %s" % node)
4029
        if req_size > info['vg_free']:
4030
          raise errors.OpPrereqError("Not enough disk space on target node %s."
4031
                                     " %d MB available, %d MB required" %
4032
                                     (node, info['vg_free'], req_size))
4033

    
4034
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
4035

    
4036
    # os verification
4037
    result = self.rpc.call_os_get(pnode.name, self.op.os_type)
4038
    result.Raise()
4039
    if not isinstance(result.data, objects.OS):
4040
      raise errors.OpPrereqError("OS '%s' not in supported os list for"
4041
                                 " primary node"  % self.op.os_type)
4042

    
4043
    # bridge check on primary node
4044
    bridges = [n.bridge for n in self.nics]
4045
    result = self.rpc.call_bridges_exist(self.pnode.name, bridges)
4046
    result.Raise()
4047
    if not result.data:
4048
      raise errors.OpPrereqError("One of the target bridges '%s' does not"
4049
                                 " exist on destination node '%s'" %
4050
                                 (",".join(bridges), pnode.name))
4051

    
4052
    # memory check on primary node
4053
    if self.op.start:
4054
      _CheckNodeFreeMemory(self, self.pnode.name,
4055
                           "creating instance %s" % self.op.instance_name,
4056
                           self.be_full[constants.BE_MEMORY],
4057
                           self.op.hypervisor)
4058

    
4059
    if self.op.start:
4060
      self.instance_status = 'up'
4061
    else:
4062
      self.instance_status = 'down'
4063

    
4064
  def Exec(self, feedback_fn):
4065
    """Create and add the instance to the cluster.
4066

4067
    """
4068
    instance = self.op.instance_name
4069
    pnode_name = self.pnode.name
4070

    
4071
    for nic in self.nics:
4072
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
4073
        nic.mac = self.cfg.GenerateMAC()
4074

    
4075
    ht_kind = self.op.hypervisor
4076
    if ht_kind in constants.HTS_REQ_PORT:
4077
      network_port = self.cfg.AllocatePort()
4078
    else:
4079
      network_port = None
4080

    
4081
    ##if self.op.vnc_bind_address is None:
4082
    ##  self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
4083

    
4084
    # this is needed because os.path.join does not accept None arguments
4085
    if self.op.file_storage_dir is None:
4086
      string_file_storage_dir = ""
4087
    else:
4088
      string_file_storage_dir = self.op.file_storage_dir
4089

    
4090
    # build the full file storage dir path
4091
    file_storage_dir = os.path.normpath(os.path.join(
4092
                                        self.cfg.GetFileStorageDir(),
4093
                                        string_file_storage_dir, instance))
4094

    
4095

    
4096
    disks = _GenerateDiskTemplate(self,
4097
                                  self.op.disk_template,
4098
                                  instance, pnode_name,
4099
                                  self.secondaries,
4100
                                  self.disks,
4101
                                  file_storage_dir,
4102
                                  self.op.file_driver,
4103
                                  0)
4104

    
4105
    iobj = objects.Instance(name=instance, os=self.op.os_type,
4106
                            primary_node=pnode_name,
4107
                            nics=self.nics, disks=disks,
4108
                            disk_template=self.op.disk_template,
4109
                            status=self.instance_status,
4110
                            network_port=network_port,
4111
                            beparams=self.op.beparams,
4112
                            hvparams=self.op.hvparams,
4113
                            hypervisor=self.op.hypervisor,
4114
                            )
4115

    
4116
    feedback_fn("* creating instance disks...")
4117
    if not _CreateDisks(self, iobj):
4118
      _RemoveDisks(self, iobj)
4119
      self.cfg.ReleaseDRBDMinors(instance)
4120
      raise errors.OpExecError("Device creation failed, reverting...")
4121

    
4122
    feedback_fn("adding instance %s to cluster config" % instance)
4123

    
4124
    self.cfg.AddInstance(iobj)
4125
    # Declare that we don't want to remove the instance lock anymore, as we've
4126
    # added the instance to the config
4127
    del self.remove_locks[locking.LEVEL_INSTANCE]
4128
    # Remove the temp. assignements for the instance's drbds
4129
    self.cfg.ReleaseDRBDMinors(instance)
4130
    # Unlock all the nodes
4131
    if self.op.mode == constants.INSTANCE_IMPORT:
4132
      nodes_keep = [self.op.src_node]
4133
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
4134
                       if node != self.op.src_node]
4135
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
4136
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
4137
    else:
4138
      self.context.glm.release(locking.LEVEL_NODE)
4139
      del self.acquired_locks[locking.LEVEL_NODE]
4140

    
4141
    if self.op.wait_for_sync:
4142
      disk_abort = not _WaitForSync(self, iobj)
4143
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
4144
      # make sure the disks are not degraded (still sync-ing is ok)
4145
      time.sleep(15)
4146
      feedback_fn("* checking mirrors status")
4147
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
4148
    else:
4149
      disk_abort = False
4150

    
4151
    if disk_abort:
4152
      _RemoveDisks(self, iobj)
4153
      self.cfg.RemoveInstance(iobj.name)
4154
      # Make sure the instance lock gets removed
4155
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
4156
      raise errors.OpExecError("There are some degraded disks for"
4157
                               " this instance")
4158

    
4159
    feedback_fn("creating os for instance %s on node %s" %
4160
                (instance, pnode_name))
4161

    
4162
    if iobj.disk_template != constants.DT_DISKLESS:
4163
      if self.op.mode == constants.INSTANCE_CREATE:
4164
        feedback_fn("* running the instance OS create scripts...")
4165
        result = self.rpc.call_instance_os_add(pnode_name, iobj)
4166
        result.Raise()
4167
        if not result.data:
4168
          raise errors.OpExecError("Could not add os for instance %s"
4169
                                   " on node %s" %
4170
                                   (instance, pnode_name))
4171

    
4172
      elif self.op.mode == constants.INSTANCE_IMPORT:
4173
        feedback_fn("* running the instance OS import scripts...")
4174
        src_node = self.op.src_node
4175
        src_images = self.src_images
4176
        cluster_name = self.cfg.GetClusterName()
4177
        import_result = self.rpc.call_instance_os_import(pnode_name, iobj,
4178
                                                         src_node, src_images,
4179
                                                         cluster_name)
4180
        import_result.Raise()
4181
        for idx, result in enumerate(import_result.data):
4182
          if not result:
4183
            self.LogWarning("Could not import the image %s for instance"
4184
                            " %s, disk %d, on node %s" %
4185
                            (src_images[idx], instance, idx, pnode_name))
4186
      else:
4187
        # also checked in the prereq part
4188
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
4189
                                     % self.op.mode)
4190

    
4191
    if self.op.start:
4192
      logging.info("Starting instance %s on node %s", instance, pnode_name)
4193
      feedback_fn("* starting instance...")
4194
      result = self.rpc.call_instance_start(pnode_name, iobj, None)
4195
      result.Raise()
4196
      if not result.data:
4197
        raise errors.OpExecError("Could not start instance")
4198

    
4199

    
4200
class LUConnectConsole(NoHooksLU):
4201
  """Connect to an instance's console.
4202

4203
  This is somewhat special in that it returns the command line that
4204
  you need to run on the master node in order to connect to the
4205
  console.
4206

4207
  """
4208
  _OP_REQP = ["instance_name"]
4209
  REQ_BGL = False
4210

    
4211
  def ExpandNames(self):
4212
    self._ExpandAndLockInstance()
4213

    
4214
  def CheckPrereq(self):
4215
    """Check prerequisites.
4216

4217
    This checks that the instance is in the cluster.
4218

4219
    """
4220
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4221
    assert self.instance is not None, \
4222
      "Cannot retrieve locked instance %s" % self.op.instance_name
4223
    _CheckNodeOnline(self, self.op.primary_node)
4224

    
4225
  def Exec(self, feedback_fn):
4226
    """Connect to the console of an instance
4227

4228
    """
4229
    instance = self.instance
4230
    node = instance.primary_node
4231

    
4232
    node_insts = self.rpc.call_instance_list([node],
4233
                                             [instance.hypervisor])[node]
4234
    node_insts.Raise()
4235

    
4236
    if instance.name not in node_insts.data:
4237
      raise errors.OpExecError("Instance %s is not running." % instance.name)
4238

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

    
4241
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
4242
    console_cmd = hyper.GetShellCommandForConsole(instance)
4243

    
4244
    # build ssh cmdline
4245
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
4246

    
4247

    
4248
class LUReplaceDisks(LogicalUnit):
4249
  """Replace the disks of an instance.
4250

4251
  """
4252
  HPATH = "mirrors-replace"
4253
  HTYPE = constants.HTYPE_INSTANCE
4254
  _OP_REQP = ["instance_name", "mode", "disks"]
4255
  REQ_BGL = False
4256

    
4257
  def ExpandNames(self):
4258
    self._ExpandAndLockInstance()
4259

    
4260
    if not hasattr(self.op, "remote_node"):
4261
      self.op.remote_node = None
4262

    
4263
    ia_name = getattr(self.op, "iallocator", None)
4264
    if ia_name is not None:
4265
      if self.op.remote_node is not None:
4266
        raise errors.OpPrereqError("Give either the iallocator or the new"
4267
                                   " secondary, not both")
4268
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4269
    elif self.op.remote_node is not None:
4270
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
4271
      if remote_node is None:
4272
        raise errors.OpPrereqError("Node '%s' not known" %
4273
                                   self.op.remote_node)
4274
      self.op.remote_node = remote_node
4275
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
4276
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4277
    else:
4278
      self.needed_locks[locking.LEVEL_NODE] = []
4279
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4280

    
4281
  def DeclareLocks(self, level):
4282
    # If we're not already locking all nodes in the set we have to declare the
4283
    # instance's primary/secondary nodes.
4284
    if (level == locking.LEVEL_NODE and
4285
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
4286
      self._LockInstancesNodes()
4287

    
4288
  def _RunAllocator(self):
4289
    """Compute a new secondary node using an IAllocator.
4290

4291
    """
4292
    ial = IAllocator(self,
4293
                     mode=constants.IALLOCATOR_MODE_RELOC,
4294
                     name=self.op.instance_name,
4295
                     relocate_from=[self.sec_node])
4296

    
4297
    ial.Run(self.op.iallocator)
4298

    
4299
    if not ial.success:
4300
      raise errors.OpPrereqError("Can't compute nodes using"
4301
                                 " iallocator '%s': %s" % (self.op.iallocator,
4302
                                                           ial.info))
4303
    if len(ial.nodes) != ial.required_nodes:
4304
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
4305
                                 " of nodes (%s), required %s" %
4306
                                 (len(ial.nodes), ial.required_nodes))
4307
    self.op.remote_node = ial.nodes[0]
4308
    self.LogInfo("Selected new secondary for the instance: %s",
4309
                 self.op.remote_node)
4310

    
4311
  def BuildHooksEnv(self):
4312
    """Build hooks env.
4313

4314
    This runs on the master, the primary and all the secondaries.
4315

4316
    """
4317
    env = {
4318
      "MODE": self.op.mode,
4319
      "NEW_SECONDARY": self.op.remote_node,
4320
      "OLD_SECONDARY": self.instance.secondary_nodes[0],
4321
      }
4322
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4323
    nl = [
4324
      self.cfg.GetMasterNode(),
4325
      self.instance.primary_node,
4326
      ]
4327
    if self.op.remote_node is not None:
4328
      nl.append(self.op.remote_node)
4329
    return env, nl, nl
4330

    
4331
  def CheckPrereq(self):
4332
    """Check prerequisites.
4333

4334
    This checks that the instance is in the cluster.
4335

4336
    """
4337
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4338
    assert instance is not None, \
4339
      "Cannot retrieve locked instance %s" % self.op.instance_name
4340
    self.instance = instance
4341

    
4342
    if instance.disk_template not in constants.DTS_NET_MIRROR:
4343
      raise errors.OpPrereqError("Instance's disk layout is not"
4344
                                 " network mirrored.")
4345

    
4346
    if len(instance.secondary_nodes) != 1:
4347
      raise errors.OpPrereqError("The instance has a strange layout,"
4348
                                 " expected one secondary but found %d" %
4349
                                 len(instance.secondary_nodes))
4350

    
4351
    self.sec_node = instance.secondary_nodes[0]
4352

    
4353
    ia_name = getattr(self.op, "iallocator", None)
4354
    if ia_name is not None:
4355
      self._RunAllocator()
4356

    
4357
    remote_node = self.op.remote_node
4358
    if remote_node is not None:
4359
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
4360
      assert self.remote_node_info is not None, \
4361
        "Cannot retrieve locked node %s" % remote_node
4362
    else:
4363
      self.remote_node_info = None
4364
    if remote_node == instance.primary_node:
4365
      raise errors.OpPrereqError("The specified node is the primary node of"
4366
                                 " the instance.")
4367
    elif remote_node == self.sec_node:
4368
      if self.op.mode == constants.REPLACE_DISK_SEC:
4369
        # this is for DRBD8, where we can't execute the same mode of
4370
        # replacement as for drbd7 (no different port allocated)
4371
        raise errors.OpPrereqError("Same secondary given, cannot execute"
4372
                                   " replacement")
4373
    if instance.disk_template == constants.DT_DRBD8:
4374
      if (self.op.mode == constants.REPLACE_DISK_ALL and
4375
          remote_node is not None):
4376
        # switch to replace secondary mode
4377
        self.op.mode = constants.REPLACE_DISK_SEC
4378

    
4379
      if self.op.mode == constants.REPLACE_DISK_ALL:
4380
        raise errors.OpPrereqError("Template 'drbd' only allows primary or"
4381
                                   " secondary disk replacement, not"
4382
                                   " both at once")
4383
      elif self.op.mode == constants.REPLACE_DISK_PRI:
4384
        if remote_node is not None:
4385
          raise errors.OpPrereqError("Template 'drbd' does not allow changing"
4386
                                     " the secondary while doing a primary"
4387
                                     " node disk replacement")
4388
        self.tgt_node = instance.primary_node
4389
        self.oth_node = instance.secondary_nodes[0]
4390
        _CheckNodeOnline(self, self.tgt_node)
4391
        _CheckNodeOnline(self, self.oth_node)
4392
      elif self.op.mode == constants.REPLACE_DISK_SEC:
4393
        self.new_node = remote_node # this can be None, in which case
4394
                                    # we don't change the secondary
4395
        self.tgt_node = instance.secondary_nodes[0]
4396
        self.oth_node = instance.primary_node
4397
        _CheckNodeOnline(self, self.oth_node)
4398
        if self.new_node is not None:
4399
          _CheckNodeOnline(self, self.new_node)
4400
        else:
4401
          _CheckNodeOnline(self, self.tgt_node)
4402
      else:
4403
        raise errors.ProgrammerError("Unhandled disk replace mode")
4404

    
4405
    if not self.op.disks:
4406
      self.op.disks = range(len(instance.disks))
4407

    
4408
    for disk_idx in self.op.disks:
4409
      instance.FindDisk(disk_idx)
4410

    
4411
  def _ExecD8DiskOnly(self, feedback_fn):
4412
    """Replace a disk on the primary or secondary for dbrd8.
4413

4414
    The algorithm for replace is quite complicated:
4415

4416
      1. for each disk to be replaced:
4417

4418
        1. create new LVs on the target node with unique names
4419
        1. detach old LVs from the drbd device
4420
        1. rename old LVs to name_replaced.<time_t>
4421
        1. rename new LVs to old LVs
4422
        1. attach the new LVs (with the old names now) to the drbd device
4423

4424
      1. wait for sync across all devices
4425

4426
      1. for each modified disk:
4427

4428
        1. remove old LVs (which have the name name_replaces.<time_t>)
4429

4430
    Failures are not very well handled.
4431

4432
    """
4433
    steps_total = 6
4434
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
4435
    instance = self.instance
4436
    iv_names = {}
4437
    vgname = self.cfg.GetVGName()
4438
    # start of work
4439
    cfg = self.cfg
4440
    tgt_node = self.tgt_node
4441
    oth_node = self.oth_node
4442

    
4443
    # Step: check device activation
4444
    self.proc.LogStep(1, steps_total, "check device existence")
4445
    info("checking volume groups")
4446
    my_vg = cfg.GetVGName()
4447
    results = self.rpc.call_vg_list([oth_node, tgt_node])
4448
    if not results:
4449
      raise errors.OpExecError("Can't list volume groups on the nodes")
4450
    for node in oth_node, tgt_node:
4451
      res = results[node]
4452
      if res.failed or not res.data or my_vg not in res.data:
4453
        raise errors.OpExecError("Volume group '%s' not found on %s" %
4454
                                 (my_vg, node))
4455
    for idx, dev in enumerate(instance.disks):
4456
      if idx not in self.op.disks:
4457
        continue
4458
      for node in tgt_node, oth_node:
4459
        info("checking disk/%d on %s" % (idx, node))
4460
        cfg.SetDiskID(dev, node)
4461
        if not self.rpc.call_blockdev_find(node, dev):
4462
          raise errors.OpExecError("Can't find disk/%d on node %s" %
4463
                                   (idx, node))
4464

    
4465
    # Step: check other node consistency
4466
    self.proc.LogStep(2, steps_total, "check peer consistency")
4467
    for idx, dev in enumerate(instance.disks):
4468
      if idx not in self.op.disks:
4469
        continue
4470
      info("checking disk/%d consistency on %s" % (idx, oth_node))
4471
      if not _CheckDiskConsistency(self, dev, oth_node,
4472
                                   oth_node==instance.primary_node):
4473
        raise errors.OpExecError("Peer node (%s) has degraded storage, unsafe"
4474
                                 " to replace disks on this node (%s)" %
4475
                                 (oth_node, tgt_node))
4476

    
4477
    # Step: create new storage
4478
    self.proc.LogStep(3, steps_total, "allocate new storage")
4479
    for idx, dev in enumerate(instance.disks):
4480
      if idx not in self.op.disks:
4481
        continue
4482
      size = dev.size
4483
      cfg.SetDiskID(dev, tgt_node)
4484
      lv_names = [".disk%d_%s" % (idx, suf)
4485
                  for suf in ["data", "meta"]]
4486
      names = _GenerateUniqueNames(self, lv_names)
4487
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=size,
4488
                             logical_id=(vgname, names[0]))
4489
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
4490
                             logical_id=(vgname, names[1]))
4491
      new_lvs = [lv_data, lv_meta]
4492
      old_lvs = dev.children
4493
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
4494
      info("creating new local storage on %s for %s" %
4495
           (tgt_node, dev.iv_name))
4496
      # since we *always* want to create this LV, we use the
4497
      # _Create...OnPrimary (which forces the creation), even if we
4498
      # are talking about the secondary node
4499
      for new_lv in new_lvs:
4500
        if not _CreateBlockDevOnPrimary(self, tgt_node, instance, new_lv,
4501
                                        _GetInstanceInfoText(instance)):
4502
          raise errors.OpExecError("Failed to create new LV named '%s' on"
4503
                                   " node '%s'" %
4504
                                   (new_lv.logical_id[1], tgt_node))
4505

    
4506
    # Step: for each lv, detach+rename*2+attach
4507
    self.proc.LogStep(4, steps_total, "change drbd configuration")
4508
    for dev, old_lvs, new_lvs in iv_names.itervalues():
4509
      info("detaching %s drbd from local storage" % dev.iv_name)
4510
      result = self.rpc.call_blockdev_removechildren(tgt_node, dev, old_lvs)
4511
      result.Raise()
4512
      if not result.data:
4513
        raise errors.OpExecError("Can't detach drbd from local storage on node"
4514
                                 " %s for device %s" % (tgt_node, dev.iv_name))
4515
      #dev.children = []
4516
      #cfg.Update(instance)
4517

    
4518
      # ok, we created the new LVs, so now we know we have the needed
4519
      # storage; as such, we proceed on the target node to rename
4520
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
4521
      # using the assumption that logical_id == physical_id (which in
4522
      # turn is the unique_id on that node)
4523

    
4524
      # FIXME(iustin): use a better name for the replaced LVs
4525
      temp_suffix = int(time.time())
4526
      ren_fn = lambda d, suff: (d.physical_id[0],
4527
                                d.physical_id[1] + "_replaced-%s" % suff)
4528
      # build the rename list based on what LVs exist on the node
4529
      rlist = []
4530
      for to_ren in old_lvs:
4531
        find_res = self.rpc.call_blockdev_find(tgt_node, to_ren)
4532
        if not find_res.failed and find_res.data is not None: # device exists
4533
          rlist.append((to_ren, ren_fn(to_ren, temp_suffix)))
4534

    
4535
      info("renaming the old LVs on the target node")
4536
      result = self.rpc.call_blockdev_rename(tgt_node, rlist)
4537
      result.Raise()
4538
      if not result.data:
4539
        raise errors.OpExecError("Can't rename old LVs on node %s" % tgt_node)
4540
      # now we rename the new LVs to the old LVs
4541
      info("renaming the new LVs on the target node")
4542
      rlist = [(new, old.physical_id) for old, new in zip(old_lvs, new_lvs)]
4543
      result = self.rpc.call_blockdev_rename(tgt_node, rlist)
4544
      result.Raise()
4545
      if not result.data:
4546
        raise errors.OpExecError("Can't rename new LVs on node %s" % tgt_node)
4547

    
4548
      for old, new in zip(old_lvs, new_lvs):
4549
        new.logical_id = old.logical_id
4550
        cfg.SetDiskID(new, tgt_node)
4551

    
4552
      for disk in old_lvs:
4553
        disk.logical_id = ren_fn(disk, temp_suffix)
4554
        cfg.SetDiskID(disk, tgt_node)
4555

    
4556
      # now that the new lvs have the old name, we can add them to the device
4557
      info("adding new mirror component on %s" % tgt_node)
4558
      result =self.rpc.call_blockdev_addchildren(tgt_node, dev, new_lvs)
4559
      if result.failed or not result.data:
4560
        for new_lv in new_lvs:
4561
          result = self.rpc.call_blockdev_remove(tgt_node, new_lv)
4562
          if result.failed or not result.data:
4563
            warning("Can't rollback device %s", hint="manually cleanup unused"
4564
                    " logical volumes")
4565
        raise errors.OpExecError("Can't add local storage to drbd")
4566

    
4567
      dev.children = new_lvs
4568
      cfg.Update(instance)
4569

    
4570
    # Step: wait for sync
4571

    
4572
    # this can fail as the old devices are degraded and _WaitForSync
4573
    # does a combined result over all disks, so we don't check its
4574
    # return value
4575
    self.proc.LogStep(5, steps_total, "sync devices")
4576
    _WaitForSync(self, instance, unlock=True)
4577

    
4578
    # so check manually all the devices
4579
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
4580
      cfg.SetDiskID(dev, instance.primary_node)
4581
      result = self.rpc.call_blockdev_find(instance.primary_node, dev)
4582
      if result.failed or result.data[5]:
4583
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
4584

    
4585
    # Step: remove old storage
4586
    self.proc.LogStep(6, steps_total, "removing old storage")
4587
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
4588
      info("remove logical volumes for %s" % name)
4589
      for lv in old_lvs:
4590
        cfg.SetDiskID(lv, tgt_node)
4591
        result = self.rpc.call_blockdev_remove(tgt_node, lv)
4592
        if result.failed or not result.data:
4593
          warning("Can't remove old LV", hint="manually remove unused LVs")
4594
          continue
4595

    
4596
  def _ExecD8Secondary(self, feedback_fn):
4597
    """Replace the secondary node for drbd8.
4598

4599
    The algorithm for replace is quite complicated:
4600
      - for all disks of the instance:
4601
        - create new LVs on the new node with same names
4602
        - shutdown the drbd device on the old secondary
4603
        - disconnect the drbd network on the primary
4604
        - create the drbd device on the new secondary
4605
        - network attach the drbd on the primary, using an artifice:
4606
          the drbd code for Attach() will connect to the network if it
4607
          finds a device which is connected to the good local disks but
4608
          not network enabled
4609
      - wait for sync across all devices
4610
      - remove all disks from the old secondary
4611

4612
    Failures are not very well handled.
4613

4614
    """
4615
    steps_total = 6
4616
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
4617
    instance = self.instance
4618
    iv_names = {}
4619
    vgname = self.cfg.GetVGName()
4620
    # start of work
4621
    cfg = self.cfg
4622
    old_node = self.tgt_node
4623
    new_node = self.new_node
4624
    pri_node = instance.primary_node
4625

    
4626
    # Step: check device activation
4627
    self.proc.LogStep(1, steps_total, "check device existence")
4628
    info("checking volume groups")
4629
    my_vg = cfg.GetVGName()
4630
    results = self.rpc.call_vg_list([pri_node, new_node])
4631
    for node in pri_node, new_node:
4632
      res = results[node]
4633
      if res.failed or not res.data or my_vg not in res.data:
4634
        raise errors.OpExecError("Volume group '%s' not found on %s" %
4635
                                 (my_vg, node))
4636
    for idx, dev in enumerate(instance.disks):
4637
      if idx not in self.op.disks:
4638
        continue
4639
      info("checking disk/%d on %s" % (idx, pri_node))
4640
      cfg.SetDiskID(dev, pri_node)
4641
      result = self.rpc.call_blockdev_find(pri_node, dev)
4642
      result.Raise()
4643
      if not result.data:
4644
        raise errors.OpExecError("Can't find disk/%d on node %s" %
4645
                                 (idx, pri_node))
4646

    
4647
    # Step: check other node consistency
4648
    self.proc.LogStep(2, steps_total, "check peer consistency")
4649
    for idx, dev in enumerate(instance.disks):
4650
      if idx not in self.op.disks:
4651
        continue
4652
      info("checking disk/%d consistency on %s" % (idx, pri_node))
4653
      if not _CheckDiskConsistency(self, dev, pri_node, True, ldisk=True):
4654
        raise errors.OpExecError("Primary node (%s) has degraded storage,"
4655
                                 " unsafe to replace the secondary" %
4656
                                 pri_node)
4657

    
4658
    # Step: create new storage
4659
    self.proc.LogStep(3, steps_total, "allocate new storage")
4660
    for idx, dev in enumerate(instance.disks):
4661
      size = dev.size
4662
      info("adding new local storage on %s for disk/%d" %
4663
           (new_node, idx))
4664
      # since we *always* want to create this LV, we use the
4665
      # _Create...OnPrimary (which forces the creation), even if we
4666
      # are talking about the secondary node
4667
      for new_lv in dev.children:
4668
        if not _CreateBlockDevOnPrimary(self, new_node, instance, new_lv,
4669
                                        _GetInstanceInfoText(instance)):
4670
          raise errors.OpExecError("Failed to create new LV named '%s' on"
4671
                                   " node '%s'" %
4672
                                   (new_lv.logical_id[1], new_node))
4673

    
4674
    # Step 4: dbrd minors and drbd setups changes
4675
    # after this, we must manually remove the drbd minors on both the
4676
    # error and the success paths
4677
    minors = cfg.AllocateDRBDMinor([new_node for dev in instance.disks],
4678
                                   instance.name)
4679
    logging.debug("Allocated minors %s" % (minors,))
4680
    self.proc.LogStep(4, steps_total, "changing drbd configuration")
4681
    for idx, (dev, new_minor) in enumerate(zip(instance.disks, minors)):
4682
      size = dev.size
4683
      info("activating a new drbd on %s for disk/%d" % (new_node, idx))
4684
      # create new devices on new_node
4685
      if pri_node == dev.logical_id[0]:
4686
        new_logical_id = (pri_node, new_node,
4687
                          dev.logical_id[2], dev.logical_id[3], new_minor,
4688
                          dev.logical_id[5])
4689
      else:
4690
        new_logical_id = (new_node, pri_node,
4691
                          dev.logical_id[2], new_minor, dev.logical_id[4],
4692
                          dev.logical_id[5])
4693
      iv_names[idx] = (dev, dev.children, new_logical_id)
4694
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
4695
                    new_logical_id)
4696
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
4697
                              logical_id=new_logical_id,
4698
                              children=dev.children)
4699
      if not _CreateBlockDevOnSecondary(self, new_node, instance,
4700
                                        new_drbd, False,
4701
                                        _GetInstanceInfoText(instance)):
4702
        self.cfg.ReleaseDRBDMinors(instance.name)
4703
        raise errors.OpExecError("Failed to create new DRBD on"
4704
                                 " node '%s'" % new_node)
4705

    
4706
    for idx, dev in enumerate(instance.disks):
4707
      # we have new devices, shutdown the drbd on the old secondary
4708
      info("shutting down drbd for disk/%d on old node" % idx)
4709
      cfg.SetDiskID(dev, old_node)
4710
      result = self.rpc.call_blockdev_shutdown(old_node, dev)
4711
      if result.failed or not result.data:
4712
        warning("Failed to shutdown drbd for disk/%d on old node" % idx,
4713
                hint="Please cleanup this device manually as soon as possible")
4714

    
4715
    info("detaching primary drbds from the network (=> standalone)")
4716
    done = 0
4717
    for idx, dev in enumerate(instance.disks):
4718
      cfg.SetDiskID(dev, pri_node)
4719
      # set the network part of the physical (unique in bdev terms) id
4720
      # to None, meaning detach from network
4721
      dev.physical_id = (None, None, None, None) + dev.physical_id[4:]
4722
      # and 'find' the device, which will 'fix' it to match the
4723
      # standalone state
4724
      result = self.rpc.call_blockdev_find(pri_node, dev)
4725
      if not result.failed and result.data:
4726
        done += 1
4727
      else:
4728
        warning("Failed to detach drbd disk/%d from network, unusual case" %
4729
                idx)
4730

    
4731
    if not done:
4732
      # no detaches succeeded (very unlikely)
4733
      self.cfg.ReleaseDRBDMinors(instance.name)
4734
      raise errors.OpExecError("Can't detach at least one DRBD from old node")
4735

    
4736
    # if we managed to detach at least one, we update all the disks of
4737
    # the instance to point to the new secondary
4738
    info("updating instance configuration")
4739
    for dev, _, new_logical_id in iv_names.itervalues():
4740
      dev.logical_id = new_logical_id
4741
      cfg.SetDiskID(dev, pri_node)
4742
    cfg.Update(instance)
4743
    # we can remove now the temp minors as now the new values are
4744
    # written to the config file (and therefore stable)
4745
    self.cfg.ReleaseDRBDMinors(instance.name)
4746

    
4747
    # and now perform the drbd attach
4748
    info("attaching primary drbds to new secondary (standalone => connected)")
4749
    failures = []
4750
    for idx, dev in enumerate(instance.disks):
4751
      info("attaching primary drbd for disk/%d to new secondary node" % idx)
4752
      # since the attach is smart, it's enough to 'find' the device,
4753
      # it will automatically activate the network, if the physical_id
4754
      # is correct
4755
      cfg.SetDiskID(dev, pri_node)
4756
      logging.debug("Disk to attach: %s", dev)
4757
      result = self.rpc.call_blockdev_find(pri_node, dev)
4758
      if result.failed or not result.data:
4759
        warning("can't attach drbd disk/%d to new secondary!" % idx,
4760
                "please do a gnt-instance info to see the status of disks")
4761

    
4762
    # this can fail as the old devices are degraded and _WaitForSync
4763
    # does a combined result over all disks, so we don't check its
4764
    # return value
4765
    self.proc.LogStep(5, steps_total, "sync devices")
4766
    _WaitForSync(self, instance, unlock=True)
4767

    
4768
    # so check manually all the devices
4769
    for idx, (dev, old_lvs, _) in iv_names.iteritems():
4770
      cfg.SetDiskID(dev, pri_node)
4771
      result = self.rpc.call_blockdev_find(pri_node, dev)
4772
      result.Raise()
4773
      if result.data[5]:
4774
        raise errors.OpExecError("DRBD device disk/%d is degraded!" % idx)
4775

    
4776
    self.proc.LogStep(6, steps_total, "removing old storage")
4777
    for idx, (dev, old_lvs, _) in iv_names.iteritems():
4778
      info("remove logical volumes for disk/%d" % idx)
4779
      for lv in old_lvs:
4780
        cfg.SetDiskID(lv, old_node)
4781
        result = self.rpc.call_blockdev_remove(old_node, lv)
4782
        if result.failed or not result.data:
4783
          warning("Can't remove LV on old secondary",
4784
                  hint="Cleanup stale volumes by hand")
4785

    
4786
  def Exec(self, feedback_fn):
4787
    """Execute disk replacement.
4788

4789
    This dispatches the disk replacement to the appropriate handler.
4790

4791
    """
4792
    instance = self.instance
4793

    
4794
    # Activate the instance disks if we're replacing them on a down instance
4795
    if instance.status == "down":
4796
      _StartInstanceDisks(self, instance, True)
4797

    
4798
    if instance.disk_template == constants.DT_DRBD8:
4799
      if self.op.remote_node is None:
4800
        fn = self._ExecD8DiskOnly
4801
      else:
4802
        fn = self._ExecD8Secondary
4803
    else:
4804
      raise errors.ProgrammerError("Unhandled disk replacement case")
4805

    
4806
    ret = fn(feedback_fn)
4807

    
4808
    # Deactivate the instance disks if we're replacing them on a down instance
4809
    if instance.status == "down":
4810
      _SafeShutdownInstanceDisks(self, instance)
4811

    
4812
    return ret
4813

    
4814

    
4815
class LUGrowDisk(LogicalUnit):
4816
  """Grow a disk of an instance.
4817

4818
  """
4819
  HPATH = "disk-grow"
4820
  HTYPE = constants.HTYPE_INSTANCE
4821
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
4822
  REQ_BGL = False
4823

    
4824
  def ExpandNames(self):
4825
    self._ExpandAndLockInstance()
4826
    self.needed_locks[locking.LEVEL_NODE] = []
4827
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4828

    
4829
  def DeclareLocks(self, level):
4830
    if level == locking.LEVEL_NODE:
4831
      self._LockInstancesNodes()
4832

    
4833
  def BuildHooksEnv(self):
4834
    """Build hooks env.
4835

4836
    This runs on the master, the primary and all the secondaries.
4837

4838
    """
4839
    env = {
4840
      "DISK": self.op.disk,
4841
      "AMOUNT": self.op.amount,
4842
      }
4843
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4844
    nl = [
4845
      self.cfg.GetMasterNode(),
4846
      self.instance.primary_node,
4847
      ]
4848
    return env, nl, nl
4849

    
4850
  def CheckPrereq(self):
4851
    """Check prerequisites.
4852

4853
    This checks that the instance is in the cluster.
4854

4855
    """
4856
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4857
    assert instance is not None, \
4858
      "Cannot retrieve locked instance %s" % self.op.instance_name
4859
    _CheckNodeOnline(self, instance.primary_node)
4860
    for node in instance.secondary_nodes:
4861
      _CheckNodeOnline(self, node)
4862

    
4863

    
4864
    self.instance = instance
4865

    
4866
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
4867
      raise errors.OpPrereqError("Instance's disk layout does not support"
4868
                                 " growing.")
4869

    
4870
    self.disk = instance.FindDisk(self.op.disk)
4871

    
4872
    nodenames = [instance.primary_node] + list(instance.secondary_nodes)
4873
    nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
4874
                                       instance.hypervisor)
4875
    for node in nodenames:
4876
      info = nodeinfo[node]
4877
      if info.failed or not info.data:
4878
        raise errors.OpPrereqError("Cannot get current information"
4879
                                   " from node '%s'" % node)
4880
      vg_free = info.data.get('vg_free', None)
4881
      if not isinstance(vg_free, int):
4882
        raise errors.OpPrereqError("Can't compute free disk space on"
4883
                                   " node %s" % node)
4884
      if self.op.amount > vg_free:
4885
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
4886
                                   " %d MiB available, %d MiB required" %
4887
                                   (node, vg_free, self.op.amount))
4888

    
4889
  def Exec(self, feedback_fn):
4890
    """Execute disk grow.
4891

4892
    """
4893
    instance = self.instance
4894
    disk = self.disk
4895
    for node in (instance.secondary_nodes + (instance.primary_node,)):
4896
      self.cfg.SetDiskID(disk, node)
4897
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
4898
      result.Raise()
4899
      if (not result.data or not isinstance(result.data, (list, tuple)) or
4900
          len(result.data) != 2):
4901
        raise errors.OpExecError("Grow request failed to node %s" % node)
4902
      elif not result.data[0]:
4903
        raise errors.OpExecError("Grow request failed to node %s: %s" %
4904
                                 (node, result.data[1]))
4905
    disk.RecordGrow(self.op.amount)
4906
    self.cfg.Update(instance)
4907
    if self.op.wait_for_sync:
4908
      disk_abort = not _WaitForSync(self, instance)
4909
      if disk_abort:
4910
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
4911
                             " status.\nPlease check the instance.")
4912

    
4913

    
4914
class LUQueryInstanceData(NoHooksLU):
4915
  """Query runtime instance data.
4916

4917
  """
4918
  _OP_REQP = ["instances", "static"]
4919
  REQ_BGL = False
4920

    
4921
  def ExpandNames(self):
4922
    self.needed_locks = {}
4923
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
4924

    
4925
    if not isinstance(self.op.instances, list):
4926
      raise errors.OpPrereqError("Invalid argument type 'instances'")
4927

    
4928
    if self.op.instances:
4929
      self.wanted_names = []
4930
      for name in self.op.instances:
4931
        full_name = self.cfg.ExpandInstanceName(name)
4932
        if full_name is None:
4933
          raise errors.OpPrereqError("Instance '%s' not known" %
4934
                                     self.op.instance_name)
4935
        self.wanted_names.append(full_name)
4936
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
4937
    else:
4938
      self.wanted_names = None
4939
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4940

    
4941
    self.needed_locks[locking.LEVEL_NODE] = []
4942
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4943

    
4944
  def DeclareLocks(self, level):
4945
    if level == locking.LEVEL_NODE:
4946
      self._LockInstancesNodes()
4947

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

4951
    This only checks the optional instance list against the existing names.
4952

4953
    """
4954
    if self.wanted_names is None:
4955
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
4956

    
4957
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
4958
                             in self.wanted_names]
4959
    return
4960

    
4961
  def _ComputeDiskStatus(self, instance, snode, dev):
4962
    """Compute block device status.
4963

4964
    """
4965
    static = self.op.static
4966
    if not static:
4967
      self.cfg.SetDiskID(dev, instance.primary_node)
4968
      dev_pstatus = self.rpc.call_blockdev_find(instance.primary_node, dev)
4969
      dev_pstatus.Raise()
4970
      dev_pstatus = dev_pstatus.data
4971
    else:
4972
      dev_pstatus = None
4973

    
4974
    if dev.dev_type in constants.LDS_DRBD:
4975
      # we change the snode then (otherwise we use the one passed in)
4976
      if dev.logical_id[0] == instance.primary_node:
4977
        snode = dev.logical_id[1]
4978
      else:
4979
        snode = dev.logical_id[0]
4980

    
4981
    if snode and not static:
4982
      self.cfg.SetDiskID(dev, snode)
4983
      dev_sstatus = self.rpc.call_blockdev_find(snode, dev)
4984
      dev_sstatus.Raise()
4985
      dev_sstatus = dev_sstatus.data
4986
    else:
4987
      dev_sstatus = None
4988

    
4989
    if dev.children:
4990
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
4991
                      for child in dev.children]
4992
    else:
4993
      dev_children = []
4994

    
4995
    data = {
4996
      "iv_name": dev.iv_name,
4997
      "dev_type": dev.dev_type,
4998
      "logical_id": dev.logical_id,
4999
      "physical_id": dev.physical_id,
5000
      "pstatus": dev_pstatus,
5001
      "sstatus": dev_sstatus,
5002
      "children": dev_children,
5003
      "mode": dev.mode,
5004
      }
5005

    
5006
    return data
5007

    
5008
  def Exec(self, feedback_fn):
5009
    """Gather and return data"""
5010
    result = {}
5011

    
5012
    cluster = self.cfg.GetClusterInfo()
5013

    
5014
    for instance in self.wanted_instances:
5015
      if not self.op.static:
5016
        remote_info = self.rpc.call_instance_info(instance.primary_node,
5017
                                                  instance.name,
5018
                                                  instance.hypervisor)
5019
        remote_info.Raise()
5020
        remote_info = remote_info.data
5021
        if remote_info and "state" in remote_info:
5022
          remote_state = "up"
5023
        else:
5024
          remote_state = "down"
5025
      else:
5026
        remote_state = None
5027
      if instance.status == "down":
5028
        config_state = "down"
5029
      else:
5030
        config_state = "up"
5031

    
5032
      disks = [self._ComputeDiskStatus(instance, None, device)
5033
               for device in instance.disks]
5034

    
5035
      idict = {
5036
        "name": instance.name,
5037
        "config_state": config_state,
5038
        "run_state": remote_state,
5039
        "pnode": instance.primary_node,
5040
        "snodes": instance.secondary_nodes,
5041
        "os": instance.os,
5042
        "nics": [(nic.mac, nic.ip, nic.bridge) for nic in instance.nics],
5043
        "disks": disks,
5044
        "hypervisor": instance.hypervisor,
5045
        "network_port": instance.network_port,
5046
        "hv_instance": instance.hvparams,
5047
        "hv_actual": cluster.FillHV(instance),
5048
        "be_instance": instance.beparams,
5049
        "be_actual": cluster.FillBE(instance),
5050
        }
5051

    
5052
      result[instance.name] = idict
5053

    
5054
    return result
5055

    
5056

    
5057
class LUSetInstanceParams(LogicalUnit):
5058
  """Modifies an instances's parameters.
5059

5060
  """
5061
  HPATH = "instance-modify"
5062
  HTYPE = constants.HTYPE_INSTANCE
5063
  _OP_REQP = ["instance_name"]
5064
  REQ_BGL = False
5065

    
5066
  def CheckArguments(self):
5067
    if not hasattr(self.op, 'nics'):
5068
      self.op.nics = []
5069
    if not hasattr(self.op, 'disks'):
5070
      self.op.disks = []
5071
    if not hasattr(self.op, 'beparams'):
5072
      self.op.beparams = {}
5073
    if not hasattr(self.op, 'hvparams'):
5074
      self.op.hvparams = {}
5075
    self.op.force = getattr(self.op, "force", False)
5076
    if not (self.op.nics or self.op.disks or
5077
            self.op.hvparams or self.op.beparams):
5078
      raise errors.OpPrereqError("No changes submitted")
5079

    
5080
    utils.CheckBEParams(self.op.beparams)
5081

    
5082
    # Disk validation
5083
    disk_addremove = 0
5084
    for disk_op, disk_dict in self.op.disks:
5085
      if disk_op == constants.DDM_REMOVE:
5086
        disk_addremove += 1
5087
        continue
5088
      elif disk_op == constants.DDM_ADD:
5089
        disk_addremove += 1
5090
      else:
5091
        if not isinstance(disk_op, int):
5092
          raise errors.OpPrereqError("Invalid disk index")
5093
      if disk_op == constants.DDM_ADD:
5094
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
5095
        if mode not in (constants.DISK_RDONLY, constants.DISK_RDWR):
5096
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode)
5097
        size = disk_dict.get('size', None)
5098
        if size is None:
5099
          raise errors.OpPrereqError("Required disk parameter size missing")
5100
        try:
5101
          size = int(size)
5102
        except ValueError, err:
5103
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
5104
                                     str(err))
5105
        disk_dict['size'] = size
5106
      else:
5107
        # modification of disk
5108
        if 'size' in disk_dict:
5109
          raise errors.OpPrereqError("Disk size change not possible, use"
5110
                                     " grow-disk")
5111

    
5112
    if disk_addremove > 1:
5113
      raise errors.OpPrereqError("Only one disk add or remove operation"
5114
                                 " supported at a time")
5115

    
5116
    # NIC validation
5117
    nic_addremove = 0
5118
    for nic_op, nic_dict in self.op.nics:
5119
      if nic_op == constants.DDM_REMOVE:
5120
        nic_addremove += 1
5121
        continue
5122
      elif nic_op == constants.DDM_ADD:
5123
        nic_addremove += 1
5124
      else:
5125
        if not isinstance(nic_op, int):
5126
          raise errors.OpPrereqError("Invalid nic index")
5127

    
5128
      # nic_dict should be a dict
5129
      nic_ip = nic_dict.get('ip', None)
5130
      if nic_ip is not None:
5131
        if nic_ip.lower() == "none":
5132
          nic_dict['ip'] = None
5133
        else:
5134
          if not utils.IsValidIP(nic_ip):
5135
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip)
5136
      # we can only check None bridges and assign the default one
5137
      nic_bridge = nic_dict.get('bridge', None)
5138
      if nic_bridge is None:
5139
        nic_dict['bridge'] = self.cfg.GetDefBridge()
5140
      # but we can validate MACs
5141
      nic_mac = nic_dict.get('mac', None)
5142
      if nic_mac is not None:
5143
        if self.cfg.IsMacInUse(nic_mac):
5144
          raise errors.OpPrereqError("MAC address %s already in use"
5145
                                     " in cluster" % nic_mac)
5146
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5147
          if not utils.IsValidMac(nic_mac):
5148
            raise errors.OpPrereqError("Invalid MAC address %s" % nic_mac)
5149
    if nic_addremove > 1:
5150
      raise errors.OpPrereqError("Only one NIC add or remove operation"
5151
                                 " supported at a time")
5152

    
5153
  def ExpandNames(self):
5154
    self._ExpandAndLockInstance()
5155
    self.needed_locks[locking.LEVEL_NODE] = []
5156
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5157

    
5158
  def DeclareLocks(self, level):
5159
    if level == locking.LEVEL_NODE:
5160
      self._LockInstancesNodes()
5161

    
5162
  def BuildHooksEnv(self):
5163
    """Build hooks env.
5164

5165
    This runs on the master, primary and secondaries.
5166

5167
    """
5168
    args = dict()
5169
    if constants.BE_MEMORY in self.be_new:
5170
      args['memory'] = self.be_new[constants.BE_MEMORY]
5171
    if constants.BE_VCPUS in self.be_new:
5172
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
5173
    # FIXME: readd disk/nic changes
5174
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
5175
    nl = [self.cfg.GetMasterNode(),
5176
          self.instance.primary_node] + list(self.instance.secondary_nodes)
5177
    return env, nl, nl
5178

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

5182
    This only checks the instance list against the existing names.
5183

5184
    """
5185
    force = self.force = self.op.force
5186

    
5187
    # checking the new params on the primary/secondary nodes
5188

    
5189
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5190
    assert self.instance is not None, \
5191
      "Cannot retrieve locked instance %s" % self.op.instance_name
5192
    pnode = self.instance.primary_node
5193
    nodelist = [pnode]
5194
    nodelist.extend(instance.secondary_nodes)
5195

    
5196
    # hvparams processing
5197
    if self.op.hvparams:
5198
      i_hvdict = copy.deepcopy(instance.hvparams)
5199
      for key, val in self.op.hvparams.iteritems():
5200
        if val == constants.VALUE_DEFAULT:
5201
          try:
5202
            del i_hvdict[key]
5203
          except KeyError:
5204
            pass
5205
        elif val == constants.VALUE_NONE:
5206
          i_hvdict[key] = None
5207
        else:
5208
          i_hvdict[key] = val
5209
      cluster = self.cfg.GetClusterInfo()
5210
      hv_new = cluster.FillDict(cluster.hvparams[instance.hypervisor],
5211
                                i_hvdict)
5212
      # local check
5213
      hypervisor.GetHypervisor(
5214
        instance.hypervisor).CheckParameterSyntax(hv_new)
5215
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
5216
      self.hv_new = hv_new # the new actual values
5217
      self.hv_inst = i_hvdict # the new dict (without defaults)
5218
    else:
5219
      self.hv_new = self.hv_inst = {}
5220

    
5221
    # beparams processing
5222
    if self.op.beparams:
5223
      i_bedict = copy.deepcopy(instance.beparams)
5224
      for key, val in self.op.beparams.iteritems():
5225
        if val == constants.VALUE_DEFAULT:
5226
          try:
5227
            del i_bedict[key]
5228
          except KeyError:
5229
            pass
5230
        else:
5231
          i_bedict[key] = val
5232
      cluster = self.cfg.GetClusterInfo()
5233
      be_new = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
5234
                                i_bedict)
5235
      self.be_new = be_new # the new actual values
5236
      self.be_inst = i_bedict # the new dict (without defaults)
5237
    else:
5238
      self.be_new = self.be_inst = {}
5239

    
5240
    self.warn = []
5241

    
5242
    if constants.BE_MEMORY in self.op.beparams and not self.force:
5243
      mem_check_list = [pnode]
5244
      if be_new[constants.BE_AUTO_BALANCE]:
5245
        # either we changed auto_balance to yes or it was from before
5246
        mem_check_list.extend(instance.secondary_nodes)
5247
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
5248
                                                  instance.hypervisor)
5249
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
5250
                                         instance.hypervisor)
5251
      if nodeinfo[pnode].failed or not isinstance(nodeinfo[pnode].data, dict):
5252
        # Assume the primary node is unreachable and go ahead
5253
        self.warn.append("Can't get info from primary node %s" % pnode)
5254
      else:
5255
        if not instance_info.failed and instance_info.data:
5256
          current_mem = instance_info.data['memory']
5257
        else:
5258
          # Assume instance not running
5259
          # (there is a slight race condition here, but it's not very probable,
5260
          # and we have no other way to check)
5261
          current_mem = 0
5262
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
5263
                    nodeinfo[pnode].data['memory_free'])
5264
        if miss_mem > 0:
5265
          raise errors.OpPrereqError("This change will prevent the instance"
5266
                                     " from starting, due to %d MB of memory"
5267
                                     " missing on its primary node" % miss_mem)
5268

    
5269
      if be_new[constants.BE_AUTO_BALANCE]:
5270
        for node, nres in instance.secondary_nodes.iteritems():
5271
          if nres.failed or not isinstance(nres.data, dict):
5272
            self.warn.append("Can't get info from secondary node %s" % node)
5273
          elif be_new[constants.BE_MEMORY] > nres.data['memory_free']:
5274
            self.warn.append("Not enough memory to failover instance to"
5275
                             " secondary node %s" % node)
5276

    
5277
    # NIC processing
5278
    for nic_op, nic_dict in self.op.nics:
5279
      if nic_op == constants.DDM_REMOVE:
5280
        if not instance.nics:
5281
          raise errors.OpPrereqError("Instance has no NICs, cannot remove")
5282
        continue
5283
      if nic_op != constants.DDM_ADD:
5284
        # an existing nic
5285
        if nic_op < 0 or nic_op >= len(instance.nics):
5286
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
5287
                                     " are 0 to %d" %
5288
                                     (nic_op, len(instance.nics)))
5289
      nic_bridge = nic_dict.get('bridge', None)
5290
      if nic_bridge is not None:
5291
        if not self.rpc.call_bridges_exist(pnode, [nic_bridge]):
5292
          msg = ("Bridge '%s' doesn't exist on one of"
5293
                 " the instance nodes" % nic_bridge)
5294
          if self.force:
5295
            self.warn.append(msg)
5296
          else:
5297
            raise errors.OpPrereqError(msg)
5298

    
5299
    # DISK processing
5300
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
5301
      raise errors.OpPrereqError("Disk operations not supported for"
5302
                                 " diskless instances")
5303
    for disk_op, disk_dict in self.op.disks:
5304
      if disk_op == constants.DDM_REMOVE:
5305
        if len(instance.disks) == 1:
5306
          raise errors.OpPrereqError("Cannot remove the last disk of"
5307
                                     " an instance")
5308
        ins_l = self.rpc.call_instance_list([pnode], [instance.hypervisor])
5309
        ins_l = ins_l[pnode]
5310
        if not type(ins_l) is list:
5311
          raise errors.OpPrereqError("Can't contact node '%s'" % pnode)
5312
        if instance.name in ins_l:
5313
          raise errors.OpPrereqError("Instance is running, can't remove"
5314
                                     " disks.")
5315

    
5316
      if (disk_op == constants.DDM_ADD and
5317
          len(instance.nics) >= constants.MAX_DISKS):
5318
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
5319
                                   " add more" % constants.MAX_DISKS)
5320
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
5321
        # an existing disk
5322
        if disk_op < 0 or disk_op >= len(instance.disks):
5323
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
5324
                                     " are 0 to %d" %
5325
                                     (disk_op, len(instance.disks)))
5326

    
5327
    return
5328

    
5329
  def Exec(self, feedback_fn):
5330
    """Modifies an instance.
5331

5332
    All parameters take effect only at the next restart of the instance.
5333

5334
    """
5335
    # Process here the warnings from CheckPrereq, as we don't have a
5336
    # feedback_fn there.
5337
    for warn in self.warn:
5338
      feedback_fn("WARNING: %s" % warn)
5339

    
5340
    result = []
5341
    instance = self.instance
5342
    # disk changes
5343
    for disk_op, disk_dict in self.op.disks:
5344
      if disk_op == constants.DDM_REMOVE:
5345
        # remove the last disk
5346
        device = instance.disks.pop()
5347
        device_idx = len(instance.disks)
5348
        for node, disk in device.ComputeNodeTree(instance.primary_node):
5349
          self.cfg.SetDiskID(disk, node)
5350
          result = self.rpc.call_blockdev_remove(node, disk)
5351
          if result.failed or not result.data:
5352
            self.proc.LogWarning("Could not remove disk/%d on node %s,"
5353
                                 " continuing anyway", device_idx, node)
5354
        result.append(("disk/%d" % device_idx, "remove"))
5355
      elif disk_op == constants.DDM_ADD:
5356
        # add a new disk
5357
        if instance.disk_template == constants.DT_FILE:
5358
          file_driver, file_path = instance.disks[0].logical_id
5359
          file_path = os.path.dirname(file_path)
5360
        else:
5361
          file_driver = file_path = None
5362
        disk_idx_base = len(instance.disks)
5363
        new_disk = _GenerateDiskTemplate(self,
5364
                                         instance.disk_template,
5365
                                         instance, instance.primary_node,
5366
                                         instance.secondary_nodes,
5367
                                         [disk_dict],
5368
                                         file_path,
5369
                                         file_driver,
5370
                                         disk_idx_base)[0]
5371
        new_disk.mode = disk_dict['mode']
5372
        instance.disks.append(new_disk)
5373
        info = _GetInstanceInfoText(instance)
5374

    
5375
        logging.info("Creating volume %s for instance %s",
5376
                     new_disk.iv_name, instance.name)
5377
        # Note: this needs to be kept in sync with _CreateDisks
5378
        #HARDCODE
5379
        for secondary_node in instance.secondary_nodes:
5380
          if not _CreateBlockDevOnSecondary(self, secondary_node, instance,
5381
                                            new_disk, False, info):
5382
            self.LogWarning("Failed to create volume %s (%s) on"
5383
                            " secondary node %s!",
5384
                            new_disk.iv_name, new_disk, secondary_node)
5385
        #HARDCODE
5386
        if not _CreateBlockDevOnPrimary(self, instance.primary_node,
5387
                                        instance, new_disk, info):
5388
          self.LogWarning("Failed to create volume %s on primary!",
5389
                          new_disk.iv_name)
5390
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
5391
                       (new_disk.size, new_disk.mode)))
5392
      else:
5393
        # change a given disk
5394
        instance.disks[disk_op].mode = disk_dict['mode']
5395
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
5396
    # NIC changes
5397
    for nic_op, nic_dict in self.op.nics:
5398
      if nic_op == constants.DDM_REMOVE:
5399
        # remove the last nic
5400
        del instance.nics[-1]
5401
        result.append(("nic.%d" % len(instance.nics), "remove"))
5402
      elif nic_op == constants.DDM_ADD:
5403
        # add a new nic
5404
        if 'mac' not in nic_dict:
5405
          mac = constants.VALUE_GENERATE
5406
        else:
5407
          mac = nic_dict['mac']
5408
        if mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5409
          mac = self.cfg.GenerateMAC()
5410
        new_nic = objects.NIC(mac=mac, ip=nic_dict.get('ip', None),
5411
                              bridge=nic_dict.get('bridge', None))
5412
        instance.nics.append(new_nic)
5413
        result.append(("nic.%d" % (len(instance.nics) - 1),
5414
                       "add:mac=%s,ip=%s,bridge=%s" %
5415
                       (new_nic.mac, new_nic.ip, new_nic.bridge)))
5416
      else:
5417
        # change a given nic
5418
        for key in 'mac', 'ip', 'bridge':
5419
          if key in nic_dict:
5420
            setattr(instance.nics[nic_op], key, nic_dict[key])
5421
            result.append(("nic.%s/%d" % (key, nic_op), nic_dict[key]))
5422

    
5423
    # hvparams changes
5424
    if self.op.hvparams:
5425
      instance.hvparams = self.hv_new
5426
      for key, val in self.op.hvparams.iteritems():
5427
        result.append(("hv/%s" % key, val))
5428

    
5429
    # beparams changes
5430
    if self.op.beparams:
5431
      instance.beparams = self.be_inst
5432
      for key, val in self.op.beparams.iteritems():
5433
        result.append(("be/%s" % key, val))
5434

    
5435
    self.cfg.Update(instance)
5436

    
5437
    return result
5438

    
5439

    
5440
class LUQueryExports(NoHooksLU):
5441
  """Query the exports list
5442

5443
  """
5444
  _OP_REQP = ['nodes']
5445
  REQ_BGL = False
5446

    
5447
  def ExpandNames(self):
5448
    self.needed_locks = {}
5449
    self.share_locks[locking.LEVEL_NODE] = 1
5450
    if not self.op.nodes:
5451
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5452
    else:
5453
      self.needed_locks[locking.LEVEL_NODE] = \
5454
        _GetWantedNodes(self, self.op.nodes)
5455

    
5456
  def CheckPrereq(self):
5457
    """Check prerequisites.
5458

5459
    """
5460
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
5461

    
5462
  def Exec(self, feedback_fn):
5463
    """Compute the list of all the exported system images.
5464

5465
    @rtype: dict
5466
    @return: a dictionary with the structure node->(export-list)
5467
        where export-list is a list of the instances exported on
5468
        that node.
5469

5470
    """
5471
    rpcresult = self.rpc.call_export_list(self.nodes)
5472
    result = {}
5473
    for node in rpcresult:
5474
      if rpcresult[node].failed:
5475
        result[node] = False
5476
      else:
5477
        result[node] = rpcresult[node].data
5478

    
5479
    return result
5480

    
5481

    
5482
class LUExportInstance(LogicalUnit):
5483
  """Export an instance to an image in the cluster.
5484

5485
  """
5486
  HPATH = "instance-export"
5487
  HTYPE = constants.HTYPE_INSTANCE
5488
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
5489
  REQ_BGL = False
5490

    
5491
  def ExpandNames(self):
5492
    self._ExpandAndLockInstance()
5493
    # FIXME: lock only instance primary and destination node
5494
    #
5495
    # Sad but true, for now we have do lock all nodes, as we don't know where
5496
    # the previous export might be, and and in this LU we search for it and
5497
    # remove it from its current node. In the future we could fix this by:
5498
    #  - making a tasklet to search (share-lock all), then create the new one,
5499
    #    then one to remove, after
5500
    #  - removing the removal operation altoghether
5501
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5502

    
5503
  def DeclareLocks(self, level):
5504
    """Last minute lock declaration."""
5505
    # All nodes are locked anyway, so nothing to do here.
5506

    
5507
  def BuildHooksEnv(self):
5508
    """Build hooks env.
5509

5510
    This will run on the master, primary node and target node.
5511

5512
    """
5513
    env = {
5514
      "EXPORT_NODE": self.op.target_node,
5515
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
5516
      }
5517
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5518
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node,
5519
          self.op.target_node]
5520
    return env, nl, nl
5521

    
5522
  def CheckPrereq(self):
5523
    """Check prerequisites.
5524

5525
    This checks that the instance and node names are valid.
5526

5527
    """
5528
    instance_name = self.op.instance_name
5529
    self.instance = self.cfg.GetInstanceInfo(instance_name)
5530
    assert self.instance is not None, \
5531
          "Cannot retrieve locked instance %s" % self.op.instance_name
5532
    _CheckNodeOnline(self, instance.primary_node)
5533

    
5534
    self.dst_node = self.cfg.GetNodeInfo(
5535
      self.cfg.ExpandNodeName(self.op.target_node))
5536

    
5537
    if self.dst_node is None:
5538
      # This is wrong node name, not a non-locked node
5539
      raise errors.OpPrereqError("Wrong node name %s" % self.op.target_node)
5540
    _CheckNodeOnline(self, self.op.target_node)
5541

    
5542
    # instance disk type verification
5543
    for disk in self.instance.disks:
5544
      if disk.dev_type == constants.LD_FILE:
5545
        raise errors.OpPrereqError("Export not supported for instances with"
5546
                                   " file-based disks")
5547

    
5548
  def Exec(self, feedback_fn):
5549
    """Export an instance to an image in the cluster.
5550

5551
    """
5552
    instance = self.instance
5553
    dst_node = self.dst_node
5554
    src_node = instance.primary_node
5555
    if self.op.shutdown:
5556
      # shutdown the instance, but not the disks
5557
      result = self.rpc.call_instance_shutdown(src_node, instance)
5558
      result.Raise()
5559
      if not result.data:
5560
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
5561
                                 (instance.name, src_node))
5562

    
5563
    vgname = self.cfg.GetVGName()
5564

    
5565
    snap_disks = []
5566

    
5567
    try:
5568
      for disk in instance.disks:
5569
        # new_dev_name will be a snapshot of an lvm leaf of the one we passed
5570
        new_dev_name = self.rpc.call_blockdev_snapshot(src_node, disk)
5571
        if new_dev_name.failed or not new_dev_name.data:
5572
          self.LogWarning("Could not snapshot block device %s on node %s",
5573
                          disk.logical_id[1], src_node)
5574
          snap_disks.append(False)
5575
        else:
5576
          new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
5577
                                 logical_id=(vgname, new_dev_name.data),
5578
                                 physical_id=(vgname, new_dev_name.data),
5579
                                 iv_name=disk.iv_name)
5580
          snap_disks.append(new_dev)
5581

    
5582
    finally:
5583
      if self.op.shutdown and instance.status == "up":
5584
        result = self.rpc.call_instance_start(src_node, instance, None)
5585
        if result.failed or not result.data:
5586
          _ShutdownInstanceDisks(self, instance)
5587
          raise errors.OpExecError("Could not start instance")
5588

    
5589
    # TODO: check for size
5590

    
5591
    cluster_name = self.cfg.GetClusterName()
5592
    for idx, dev in enumerate(snap_disks):
5593
      if dev:
5594
        result = self.rpc.call_snapshot_export(src_node, dev, dst_node.name,
5595
                                               instance, cluster_name, idx)
5596
        if result.failed or not result.data:
5597
          self.LogWarning("Could not export block device %s from node %s to"
5598
                          " node %s", dev.logical_id[1], src_node,
5599
                          dst_node.name)
5600
        result = self.rpc.call_blockdev_remove(src_node, dev)
5601
        if result.failed or not result.data:
5602
          self.LogWarning("Could not remove snapshot block device %s from node"
5603
                          " %s", dev.logical_id[1], src_node)
5604

    
5605
    result = self.rpc.call_finalize_export(dst_node.name, instance, snap_disks)
5606
    if result.failed or not result.data:
5607
      self.LogWarning("Could not finalize export for instance %s on node %s",
5608
                      instance.name, dst_node.name)
5609

    
5610
    nodelist = self.cfg.GetNodeList()
5611
    nodelist.remove(dst_node.name)
5612

    
5613
    # on one-node clusters nodelist will be empty after the removal
5614
    # if we proceed the backup would be removed because OpQueryExports
5615
    # substitutes an empty list with the full cluster node list.
5616
    if nodelist:
5617
      exportlist = self.rpc.call_export_list(nodelist)
5618
      for node in exportlist:
5619
        if exportlist[node].failed:
5620
          continue
5621
        if instance.name in exportlist[node].data:
5622
          if not self.rpc.call_export_remove(node, instance.name):
5623
            self.LogWarning("Could not remove older export for instance %s"
5624
                            " on node %s", instance.name, node)
5625

    
5626

    
5627
class LURemoveExport(NoHooksLU):
5628
  """Remove exports related to the named instance.
5629

5630
  """
5631
  _OP_REQP = ["instance_name"]
5632
  REQ_BGL = False
5633

    
5634
  def ExpandNames(self):
5635
    self.needed_locks = {}
5636
    # We need all nodes to be locked in order for RemoveExport to work, but we
5637
    # don't need to lock the instance itself, as nothing will happen to it (and
5638
    # we can remove exports also for a removed instance)
5639
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5640

    
5641
  def CheckPrereq(self):
5642
    """Check prerequisites.
5643
    """
5644
    pass
5645

    
5646
  def Exec(self, feedback_fn):
5647
    """Remove any export.
5648

5649
    """
5650
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
5651
    # If the instance was not found we'll try with the name that was passed in.
5652
    # This will only work if it was an FQDN, though.
5653
    fqdn_warn = False
5654
    if not instance_name:
5655
      fqdn_warn = True
5656
      instance_name = self.op.instance_name
5657

    
5658
    exportlist = self.rpc.call_export_list(self.acquired_locks[
5659
      locking.LEVEL_NODE])
5660
    found = False
5661
    for node in exportlist:
5662
      if exportlist[node].failed:
5663
        self.LogWarning("Failed to query node %s, continuing" % node)
5664
        continue
5665
      if instance_name in exportlist[node].data:
5666
        found = True
5667
        result = self.rpc.call_export_remove(node, instance_name)
5668
        if result.failed or not result.data:
5669
          logging.error("Could not remove export for instance %s"
5670
                        " on node %s", instance_name, node)
5671

    
5672
    if fqdn_warn and not found:
5673
      feedback_fn("Export not found. If trying to remove an export belonging"
5674
                  " to a deleted instance please use its Fully Qualified"
5675
                  " Domain Name.")
5676

    
5677

    
5678
class TagsLU(NoHooksLU):
5679
  """Generic tags LU.
5680

5681
  This is an abstract class which is the parent of all the other tags LUs.
5682

5683
  """
5684

    
5685
  def ExpandNames(self):
5686
    self.needed_locks = {}
5687
    if self.op.kind == constants.TAG_NODE:
5688
      name = self.cfg.ExpandNodeName(self.op.name)
5689
      if name is None:
5690
        raise errors.OpPrereqError("Invalid node name (%s)" %
5691
                                   (self.op.name,))
5692
      self.op.name = name
5693
      self.needed_locks[locking.LEVEL_NODE] = name
5694
    elif self.op.kind == constants.TAG_INSTANCE:
5695
      name = self.cfg.ExpandInstanceName(self.op.name)
5696
      if name is None:
5697
        raise errors.OpPrereqError("Invalid instance name (%s)" %
5698
                                   (self.op.name,))
5699
      self.op.name = name
5700
      self.needed_locks[locking.LEVEL_INSTANCE] = name
5701

    
5702
  def CheckPrereq(self):
5703
    """Check prerequisites.
5704

5705
    """
5706
    if self.op.kind == constants.TAG_CLUSTER:
5707
      self.target = self.cfg.GetClusterInfo()
5708
    elif self.op.kind == constants.TAG_NODE:
5709
      self.target = self.cfg.GetNodeInfo(self.op.name)
5710
    elif self.op.kind == constants.TAG_INSTANCE:
5711
      self.target = self.cfg.GetInstanceInfo(self.op.name)
5712
    else:
5713
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
5714
                                 str(self.op.kind))
5715

    
5716

    
5717
class LUGetTags(TagsLU):
5718
  """Returns the tags of a given object.
5719

5720
  """
5721
  _OP_REQP = ["kind", "name"]
5722
  REQ_BGL = False
5723

    
5724
  def Exec(self, feedback_fn):
5725
    """Returns the tag list.
5726

5727
    """
5728
    return list(self.target.GetTags())
5729

    
5730

    
5731
class LUSearchTags(NoHooksLU):
5732
  """Searches the tags for a given pattern.
5733

5734
  """
5735
  _OP_REQP = ["pattern"]
5736
  REQ_BGL = False
5737

    
5738
  def ExpandNames(self):
5739
    self.needed_locks = {}
5740

    
5741
  def CheckPrereq(self):
5742
    """Check prerequisites.
5743

5744
    This checks the pattern passed for validity by compiling it.
5745

5746
    """
5747
    try:
5748
      self.re = re.compile(self.op.pattern)
5749
    except re.error, err:
5750
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
5751
                                 (self.op.pattern, err))
5752

    
5753
  def Exec(self, feedback_fn):
5754
    """Returns the tag list.
5755

5756
    """
5757
    cfg = self.cfg
5758
    tgts = [("/cluster", cfg.GetClusterInfo())]
5759
    ilist = cfg.GetAllInstancesInfo().values()
5760
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
5761
    nlist = cfg.GetAllNodesInfo().values()
5762
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
5763
    results = []
5764
    for path, target in tgts:
5765
      for tag in target.GetTags():
5766
        if self.re.search(tag):
5767
          results.append((path, tag))
5768
    return results
5769

    
5770

    
5771
class LUAddTags(TagsLU):
5772
  """Sets a tag on a given object.
5773

5774
  """
5775
  _OP_REQP = ["kind", "name", "tags"]
5776
  REQ_BGL = False
5777

    
5778
  def CheckPrereq(self):
5779
    """Check prerequisites.
5780

5781
    This checks the type and length of the tag name and value.
5782

5783
    """
5784
    TagsLU.CheckPrereq(self)
5785
    for tag in self.op.tags:
5786
      objects.TaggableObject.ValidateTag(tag)
5787

    
5788
  def Exec(self, feedback_fn):
5789
    """Sets the tag.
5790

5791
    """
5792
    try:
5793
      for tag in self.op.tags:
5794
        self.target.AddTag(tag)
5795
    except errors.TagError, err:
5796
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
5797
    try:
5798
      self.cfg.Update(self.target)
5799
    except errors.ConfigurationError:
5800
      raise errors.OpRetryError("There has been a modification to the"
5801
                                " config file and the operation has been"
5802
                                " aborted. Please retry.")
5803

    
5804

    
5805
class LUDelTags(TagsLU):
5806
  """Delete a list of tags from a given object.
5807

5808
  """
5809
  _OP_REQP = ["kind", "name", "tags"]
5810
  REQ_BGL = False
5811

    
5812
  def CheckPrereq(self):
5813
    """Check prerequisites.
5814

5815
    This checks that we have the given tag.
5816

5817
    """
5818
    TagsLU.CheckPrereq(self)
5819
    for tag in self.op.tags:
5820
      objects.TaggableObject.ValidateTag(tag)
5821
    del_tags = frozenset(self.op.tags)
5822
    cur_tags = self.target.GetTags()
5823
    if not del_tags <= cur_tags:
5824
      diff_tags = del_tags - cur_tags
5825
      diff_names = ["'%s'" % tag for tag in diff_tags]
5826
      diff_names.sort()
5827
      raise errors.OpPrereqError("Tag(s) %s not found" %
5828
                                 (",".join(diff_names)))
5829

    
5830
  def Exec(self, feedback_fn):
5831
    """Remove the tag from the object.
5832

5833
    """
5834
    for tag in self.op.tags:
5835
      self.target.RemoveTag(tag)
5836
    try:
5837
      self.cfg.Update(self.target)
5838
    except errors.ConfigurationError:
5839
      raise errors.OpRetryError("There has been a modification to the"
5840
                                " config file and the operation has been"
5841
                                " aborted. Please retry.")
5842

    
5843

    
5844
class LUTestDelay(NoHooksLU):
5845
  """Sleep for a specified amount of time.
5846

5847
  This LU sleeps on the master and/or nodes for a specified amount of
5848
  time.
5849

5850
  """
5851
  _OP_REQP = ["duration", "on_master", "on_nodes"]
5852
  REQ_BGL = False
5853

    
5854
  def ExpandNames(self):
5855
    """Expand names and set required locks.
5856

5857
    This expands the node list, if any.
5858

5859
    """
5860
    self.needed_locks = {}
5861
    if self.op.on_nodes:
5862
      # _GetWantedNodes can be used here, but is not always appropriate to use
5863
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
5864
      # more information.
5865
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
5866
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
5867

    
5868
  def CheckPrereq(self):
5869
    """Check prerequisites.
5870

5871
    """
5872

    
5873
  def Exec(self, feedback_fn):
5874
    """Do the actual sleep.
5875

5876
    """
5877
    if self.op.on_master:
5878
      if not utils.TestDelay(self.op.duration):
5879
        raise errors.OpExecError("Error during master delay test")
5880
    if self.op.on_nodes:
5881
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
5882
      if not result:
5883
        raise errors.OpExecError("Complete failure from rpc call")
5884
      for node, node_result in result.items():
5885
        node_result.Raise()
5886
        if not node_result.data:
5887
          raise errors.OpExecError("Failure during rpc call to node %s,"
5888
                                   " result: %s" % (node, node_result.data))
5889

    
5890

    
5891
class IAllocator(object):
5892
  """IAllocator framework.
5893

5894
  An IAllocator instance has three sets of attributes:
5895
    - cfg that is needed to query the cluster
5896
    - input data (all members of the _KEYS class attribute are required)
5897
    - four buffer attributes (in|out_data|text), that represent the
5898
      input (to the external script) in text and data structure format,
5899
      and the output from it, again in two formats
5900
    - the result variables from the script (success, info, nodes) for
5901
      easy usage
5902

5903
  """
5904
  _ALLO_KEYS = [
5905
    "mem_size", "disks", "disk_template",
5906
    "os", "tags", "nics", "vcpus", "hypervisor",
5907
    ]
5908
  _RELO_KEYS = [
5909
    "relocate_from",
5910
    ]
5911

    
5912
  def __init__(self, lu, mode, name, **kwargs):
5913
    self.lu = lu
5914
    # init buffer variables
5915
    self.in_text = self.out_text = self.in_data = self.out_data = None
5916
    # init all input fields so that pylint is happy
5917
    self.mode = mode
5918
    self.name = name
5919
    self.mem_size = self.disks = self.disk_template = None
5920
    self.os = self.tags = self.nics = self.vcpus = None
5921
    self.relocate_from = None
5922
    # computed fields
5923
    self.required_nodes = None
5924
    # init result fields
5925
    self.success = self.info = self.nodes = None
5926
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
5927
      keyset = self._ALLO_KEYS
5928
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
5929
      keyset = self._RELO_KEYS
5930
    else:
5931
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
5932
                                   " IAllocator" % self.mode)
5933
    for key in kwargs:
5934
      if key not in keyset:
5935
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
5936
                                     " IAllocator" % key)
5937
      setattr(self, key, kwargs[key])
5938
    for key in keyset:
5939
      if key not in kwargs:
5940
        raise errors.ProgrammerError("Missing input parameter '%s' to"
5941
                                     " IAllocator" % key)
5942
    self._BuildInputData()
5943

    
5944
  def _ComputeClusterData(self):
5945
    """Compute the generic allocator input data.
5946

5947
    This is the data that is independent of the actual operation.
5948

5949
    """
5950
    cfg = self.lu.cfg
5951
    cluster_info = cfg.GetClusterInfo()
5952
    # cluster data
5953
    data = {
5954
      "version": 1,
5955
      "cluster_name": cfg.GetClusterName(),
5956
      "cluster_tags": list(cluster_info.GetTags()),
5957
      "enable_hypervisors": list(cluster_info.enabled_hypervisors),
5958
      # we don't have job IDs
5959
      }
5960
    iinfo = cfg.GetAllInstancesInfo().values()
5961
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
5962

    
5963
    # node data
5964
    node_results = {}
5965
    node_list = cfg.GetNodeList()
5966

    
5967
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
5968
      hypervisor = self.hypervisor
5969
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
5970
      hypervisor = cfg.GetInstanceInfo(self.name).hypervisor
5971

    
5972
    node_data = self.lu.rpc.call_node_info(node_list, cfg.GetVGName(),
5973
                                           hypervisor)
5974
    node_iinfo = self.lu.rpc.call_all_instances_info(node_list,
5975
                       cluster_info.enabled_hypervisors)
5976
    for nname in node_list:
5977
      ninfo = cfg.GetNodeInfo(nname)
5978
      node_data[nname].Raise()
5979
      if not isinstance(node_data[nname].data, dict):
5980
        raise errors.OpExecError("Can't get data for node %s" % nname)
5981
      remote_info = node_data[nname].data
5982
      for attr in ['memory_total', 'memory_free', 'memory_dom0',
5983
                   'vg_size', 'vg_free', 'cpu_total']:
5984
        if attr not in remote_info:
5985
          raise errors.OpExecError("Node '%s' didn't return attribute '%s'" %
5986
                                   (nname, attr))
5987
        try:
5988
          remote_info[attr] = int(remote_info[attr])
5989
        except ValueError, err:
5990
          raise errors.OpExecError("Node '%s' returned invalid value for '%s':"
5991
                                   " %s" % (nname, attr, str(err)))
5992
      # compute memory used by primary instances
5993
      i_p_mem = i_p_up_mem = 0
5994
      for iinfo, beinfo in i_list:
5995
        if iinfo.primary_node == nname:
5996
          i_p_mem += beinfo[constants.BE_MEMORY]
5997
          if iinfo.name not in node_iinfo[nname]:
5998
            i_used_mem = 0
5999
          else:
6000
            i_used_mem = int(node_iinfo[nname][iinfo.name]['memory'])
6001
          i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
6002
          remote_info['memory_free'] -= max(0, i_mem_diff)
6003

    
6004
          if iinfo.status == "up":
6005
            i_p_up_mem += beinfo[constants.BE_MEMORY]
6006

    
6007
      # compute memory used by instances
6008
      pnr = {
6009
        "tags": list(ninfo.GetTags()),
6010
        "total_memory": remote_info['memory_total'],
6011
        "reserved_memory": remote_info['memory_dom0'],
6012
        "free_memory": remote_info['memory_free'],
6013
        "i_pri_memory": i_p_mem,
6014
        "i_pri_up_memory": i_p_up_mem,
6015
        "total_disk": remote_info['vg_size'],
6016
        "free_disk": remote_info['vg_free'],
6017
        "primary_ip": ninfo.primary_ip,
6018
        "secondary_ip": ninfo.secondary_ip,
6019
        "total_cpus": remote_info['cpu_total'],
6020
        "offline": ninfo.offline,
6021
        }
6022
      node_results[nname] = pnr
6023
    data["nodes"] = node_results
6024

    
6025
    # instance data
6026
    instance_data = {}
6027
    for iinfo, beinfo in i_list:
6028
      nic_data = [{"mac": n.mac, "ip": n.ip, "bridge": n.bridge}
6029
                  for n in iinfo.nics]
6030
      pir = {
6031
        "tags": list(iinfo.GetTags()),
6032
        "should_run": iinfo.status == "up",
6033
        "vcpus": beinfo[constants.BE_VCPUS],
6034
        "memory": beinfo[constants.BE_MEMORY],
6035
        "os": iinfo.os,
6036
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
6037
        "nics": nic_data,
6038
        "disks": [{"size": dsk.size, "mode": "w"} for dsk in iinfo.disks],
6039
        "disk_template": iinfo.disk_template,
6040
        "hypervisor": iinfo.hypervisor,
6041
        }
6042
      instance_data[iinfo.name] = pir
6043

    
6044
    data["instances"] = instance_data
6045

    
6046
    self.in_data = data
6047

    
6048
  def _AddNewInstance(self):
6049
    """Add new instance data to allocator structure.
6050

6051
    This in combination with _AllocatorGetClusterData will create the
6052
    correct structure needed as input for the allocator.
6053

6054
    The checks for the completeness of the opcode must have already been
6055
    done.
6056

6057
    """
6058
    data = self.in_data
6059
    if len(self.disks) != 2:
6060
      raise errors.OpExecError("Only two-disk configurations supported")
6061

    
6062
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
6063

    
6064
    if self.disk_template in constants.DTS_NET_MIRROR:
6065
      self.required_nodes = 2
6066
    else:
6067
      self.required_nodes = 1
6068
    request = {
6069
      "type": "allocate",
6070
      "name": self.name,
6071
      "disk_template": self.disk_template,
6072
      "tags": self.tags,
6073
      "os": self.os,
6074
      "vcpus": self.vcpus,
6075
      "memory": self.mem_size,
6076
      "disks": self.disks,
6077
      "disk_space_total": disk_space,
6078
      "nics": self.nics,
6079
      "required_nodes": self.required_nodes,
6080
      }
6081
    data["request"] = request
6082

    
6083
  def _AddRelocateInstance(self):
6084
    """Add relocate instance data to allocator structure.
6085

6086
    This in combination with _IAllocatorGetClusterData will create the
6087
    correct structure needed as input for the allocator.
6088

6089
    The checks for the completeness of the opcode must have already been
6090
    done.
6091

6092
    """
6093
    instance = self.lu.cfg.GetInstanceInfo(self.name)
6094
    if instance is None:
6095
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
6096
                                   " IAllocator" % self.name)
6097

    
6098
    if instance.disk_template not in constants.DTS_NET_MIRROR:
6099
      raise errors.OpPrereqError("Can't relocate non-mirrored instances")
6100

    
6101
    if len(instance.secondary_nodes) != 1:
6102
      raise errors.OpPrereqError("Instance has not exactly one secondary node")
6103

    
6104
    self.required_nodes = 1
6105
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
6106
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
6107

    
6108
    request = {
6109
      "type": "relocate",
6110
      "name": self.name,
6111
      "disk_space_total": disk_space,
6112
      "required_nodes": self.required_nodes,
6113
      "relocate_from": self.relocate_from,
6114
      }
6115
    self.in_data["request"] = request
6116

    
6117
  def _BuildInputData(self):
6118
    """Build input data structures.
6119

6120
    """
6121
    self._ComputeClusterData()
6122

    
6123
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6124
      self._AddNewInstance()
6125
    else:
6126
      self._AddRelocateInstance()
6127

    
6128
    self.in_text = serializer.Dump(self.in_data)
6129

    
6130
  def Run(self, name, validate=True, call_fn=None):
6131
    """Run an instance allocator and return the results.
6132

6133
    """
6134
    if call_fn is None:
6135
      call_fn = self.lu.rpc.call_iallocator_runner
6136
    data = self.in_text
6137

    
6138
    result = call_fn(self.lu.cfg.GetMasterNode(), name, self.in_text)
6139
    result.Raise()
6140

    
6141
    if not isinstance(result.data, (list, tuple)) or len(result.data) != 4:
6142
      raise errors.OpExecError("Invalid result from master iallocator runner")
6143

    
6144
    rcode, stdout, stderr, fail = result.data
6145

    
6146
    if rcode == constants.IARUN_NOTFOUND:
6147
      raise errors.OpExecError("Can't find allocator '%s'" % name)
6148
    elif rcode == constants.IARUN_FAILURE:
6149
      raise errors.OpExecError("Instance allocator call failed: %s,"
6150
                               " output: %s" % (fail, stdout+stderr))
6151
    self.out_text = stdout
6152
    if validate:
6153
      self._ValidateResult()
6154

    
6155
  def _ValidateResult(self):
6156
    """Process the allocator results.
6157

6158
    This will process and if successful save the result in
6159
    self.out_data and the other parameters.
6160

6161
    """
6162
    try:
6163
      rdict = serializer.Load(self.out_text)
6164
    except Exception, err:
6165
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
6166

    
6167
    if not isinstance(rdict, dict):
6168
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
6169

    
6170
    for key in "success", "info", "nodes":
6171
      if key not in rdict:
6172
        raise errors.OpExecError("Can't parse iallocator results:"
6173
                                 " missing key '%s'" % key)
6174
      setattr(self, key, rdict[key])
6175

    
6176
    if not isinstance(rdict["nodes"], list):
6177
      raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
6178
                               " is not a list")
6179
    self.out_data = rdict
6180

    
6181

    
6182
class LUTestAllocator(NoHooksLU):
6183
  """Run allocator tests.
6184

6185
  This LU runs the allocator tests
6186

6187
  """
6188
  _OP_REQP = ["direction", "mode", "name"]
6189

    
6190
  def CheckPrereq(self):
6191
    """Check prerequisites.
6192

6193
    This checks the opcode parameters depending on the director and mode test.
6194

6195
    """
6196
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
6197
      for attr in ["name", "mem_size", "disks", "disk_template",
6198
                   "os", "tags", "nics", "vcpus"]:
6199
        if not hasattr(self.op, attr):
6200
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
6201
                                     attr)
6202
      iname = self.cfg.ExpandInstanceName(self.op.name)
6203
      if iname is not None:
6204
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
6205
                                   iname)
6206
      if not isinstance(self.op.nics, list):
6207
        raise errors.OpPrereqError("Invalid parameter 'nics'")
6208
      for row in self.op.nics:
6209
        if (not isinstance(row, dict) or
6210
            "mac" not in row or
6211
            "ip" not in row or
6212
            "bridge" not in row):
6213
          raise errors.OpPrereqError("Invalid contents of the"
6214
                                     " 'nics' parameter")
6215
      if not isinstance(self.op.disks, list):
6216
        raise errors.OpPrereqError("Invalid parameter 'disks'")
6217
      if len(self.op.disks) != 2:
6218
        raise errors.OpPrereqError("Only two-disk configurations supported")
6219
      for row in self.op.disks:
6220
        if (not isinstance(row, dict) or
6221
            "size" not in row or
6222
            not isinstance(row["size"], int) or
6223
            "mode" not in row or
6224
            row["mode"] not in ['r', 'w']):
6225
          raise errors.OpPrereqError("Invalid contents of the"
6226
                                     " 'disks' parameter")
6227
      if self.op.hypervisor is None:
6228
        self.op.hypervisor = self.cfg.GetHypervisorType()
6229
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
6230
      if not hasattr(self.op, "name"):
6231
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input")
6232
      fname = self.cfg.ExpandInstanceName(self.op.name)
6233
      if fname is None:
6234
        raise errors.OpPrereqError("Instance '%s' not found for relocation" %
6235
                                   self.op.name)
6236
      self.op.name = fname
6237
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
6238
    else:
6239
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
6240
                                 self.op.mode)
6241

    
6242
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
6243
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
6244
        raise errors.OpPrereqError("Missing allocator name")
6245
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
6246
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
6247
                                 self.op.direction)
6248

    
6249
  def Exec(self, feedback_fn):
6250
    """Run the allocator test.
6251

6252
    """
6253
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
6254
      ial = IAllocator(self,
6255
                       mode=self.op.mode,
6256
                       name=self.op.name,
6257
                       mem_size=self.op.mem_size,
6258
                       disks=self.op.disks,
6259
                       disk_template=self.op.disk_template,
6260
                       os=self.op.os,
6261
                       tags=self.op.tags,
6262
                       nics=self.op.nics,
6263
                       vcpus=self.op.vcpus,
6264
                       hypervisor=self.op.hypervisor,
6265
                       )
6266
    else:
6267
      ial = IAllocator(self,
6268
                       mode=self.op.mode,
6269
                       name=self.op.name,
6270
                       relocate_from=list(self.relocate_from),
6271
                       )
6272

    
6273
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
6274
      result = ial.in_text
6275
    else:
6276
      ial.Run(self.op.allocator, validate=False)
6277
      result = ial.out_text
6278
    return result