Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 7e9366f7

History | View | Annotate | Download (217.7 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.append(constants.RAPI_CERT_FILE)
885
    file_names.extend(master_files)
886

    
887
    local_checksums = utils.FingerprintFiles(file_names)
888

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

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

    
913
      if node_i.offline:
914
        feedback_fn("* Skipping offline node %s" % (node,))
915
        n_offline.append(node)
916
        continue
917

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

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

    
931
      result = self._VerifyNode(node_i, file_names, local_checksums,
932
                                nresult, feedback_fn, master_files)
933
      bad = bad or result
934

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

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

    
956
      node_instance[node] = idata
957

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

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

    
984
    node_vol_should = {}
985

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

    
994
      inst_config.MapLVsByNode(node_vol_should)
995

    
996
      instance_cfg[instance] = inst_config
997

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

    
1006
      if pnode in n_offline:
1007
        inst_nodes_offline.append(pnode)
1008

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

    
1020
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1021
        i_non_a_balanced.append(instance)
1022

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

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

    
1042
    feedback_fn("* Verifying orphan volumes")
1043
    result = self._VerifyOrphanVolumes(node_vol_should, node_volume,
1044
                                       feedback_fn)
1045
    bad = bad or result
1046

    
1047
    feedback_fn("* Verifying remaining instances")
1048
    result = self._VerifyOrphanInstances(instancelist, node_instance,
1049
                                         feedback_fn)
1050
    bad = bad or result
1051

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

    
1057
    feedback_fn("* Other Notes")
1058
    if i_non_redundant:
1059
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1060
                  % len(i_non_redundant))
1061

    
1062
    if i_non_a_balanced:
1063
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1064
                  % len(i_non_a_balanced))
1065

    
1066
    if n_offline:
1067
      feedback_fn("  - NOTICE: %d offline node(s) found." % len(n_offline))
1068

    
1069
    return not bad
1070

    
1071
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1072
    """Analize the post-hooks' result
1073

1074
    This method analyses the hook result, handles it, and sends some
1075
    nicely-formatted feedback back to the user.
1076

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

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

    
1118
      return lu_result
1119

    
1120

    
1121
class LUVerifyDisks(NoHooksLU):
1122
  """Verifies the cluster disks status.
1123

1124
  """
1125
  _OP_REQP = []
1126
  REQ_BGL = False
1127

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

    
1135
  def CheckPrereq(self):
1136
    """Check prerequisites.
1137

1138
    This has no prerequisites.
1139

1140
    """
1141
    pass
1142

    
1143
  def Exec(self, feedback_fn):
1144
    """Verify integrity of cluster disks.
1145

1146
    """
1147
    result = res_nodes, res_nlvm, res_instances, res_missing = [], {}, [], {}
1148

    
1149
    vg_name = self.cfg.GetVGName()
1150
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1151
    instances = [self.cfg.GetInstanceInfo(name)
1152
                 for name in self.cfg.GetInstanceList()]
1153

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

    
1166
    if not nv_dict:
1167
      return result
1168

    
1169
    node_lvs = self.rpc.call_volume_list(nodes, vg_name)
1170

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

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

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

    
1203
    return result
1204

    
1205

    
1206
class LURenameCluster(LogicalUnit):
1207
  """Rename the cluster.
1208

1209
  """
1210
  HPATH = "cluster-rename"
1211
  HTYPE = constants.HTYPE_CLUSTER
1212
  _OP_REQP = ["name"]
1213

    
1214
  def BuildHooksEnv(self):
1215
    """Build hooks env.
1216

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

    
1225
  def CheckPrereq(self):
1226
    """Verify that the passed name is a valid one.
1227

1228
    """
1229
    hostname = utils.HostInfo(self.op.name)
1230

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

    
1244
    self.op.name = new_name
1245

    
1246
  def Exec(self, feedback_fn):
1247
    """Rename the cluster.
1248

1249
    """
1250
    clustername = self.op.name
1251
    ip = self.ip
1252

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

    
1259
    try:
1260
      cluster = self.cfg.GetClusterInfo()
1261
      cluster.cluster_name = clustername
1262
      cluster.master_ip = ip
1263
      self.cfg.Update(cluster)
1264

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

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

    
1285

    
1286
def _RecursiveCheckIfLVMBased(disk):
1287
  """Check if the given disk or its children are lvm-based.
1288

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

1294
  """
1295
  if disk.children:
1296
    for chdisk in disk.children:
1297
      if _RecursiveCheckIfLVMBased(chdisk):
1298
        return True
1299
  return disk.dev_type == constants.LD_LV
1300

    
1301

    
1302
class LUSetClusterParams(LogicalUnit):
1303
  """Change the parameters of the cluster.
1304

1305
  """
1306
  HPATH = "cluster-modify"
1307
  HTYPE = constants.HTYPE_CLUSTER
1308
  _OP_REQP = []
1309
  REQ_BGL = False
1310

    
1311
  def CheckParameters(self):
1312
    """Check parameters
1313

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

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

    
1334
  def BuildHooksEnv(self):
1335
    """Build hooks env.
1336

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

    
1345
  def CheckPrereq(self):
1346
    """Check prerequisites.
1347

1348
    This checks whether the given params don't conflict and
1349
    if the given volume group is valid.
1350

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

    
1362
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1363

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

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

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

    
1397
    if self.op.enabled_hypervisors is not None:
1398
      self.hv_list = self.op.enabled_hypervisors
1399
    else:
1400
      self.hv_list = cluster.enabled_hypervisors
1401

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

    
1413
  def Exec(self, feedback_fn):
1414
    """Change the parameters of the cluster.
1415

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

    
1432
    self.cfg.Update(self.cluster)
1433

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

    
1439

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

1443
  """
1444
  if not instance.disks:
1445
    return True
1446

    
1447
  if not oneshot:
1448
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
1449

    
1450
  node = instance.primary_node
1451

    
1452
  for dev in instance.disks:
1453
    lu.cfg.SetDiskID(dev, node)
1454

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

    
1492
    time.sleep(min(60, max_time))
1493

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

    
1498

    
1499
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
1500
  """Check that mirrors are not degraded.
1501

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

1506
  """
1507
  lu.cfg.SetDiskID(dev, node)
1508
  if ldisk:
1509
    idx = 6
1510
  else:
1511
    idx = 5
1512

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

    
1525
  return result
1526

    
1527

    
1528
class LUDiagnoseOS(NoHooksLU):
1529
  """Logical unit for OS diagnose/query.
1530

1531
  """
1532
  _OP_REQP = ["output_fields", "names"]
1533
  REQ_BGL = False
1534
  _FIELDS_STATIC = utils.FieldSet()
1535
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status")
1536

    
1537
  def ExpandNames(self):
1538
    if self.op.names:
1539
      raise errors.OpPrereqError("Selective OS query not supported")
1540

    
1541
    _CheckOutputFields(static=self._FIELDS_STATIC,
1542
                       dynamic=self._FIELDS_DYNAMIC,
1543
                       selected=self.op.output_fields)
1544

    
1545
    # Lock all nodes, in shared mode
1546
    self.needed_locks = {}
1547
    self.share_locks[locking.LEVEL_NODE] = 1
1548
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1549

    
1550
  def CheckPrereq(self):
1551
    """Check prerequisites.
1552

1553
    """
1554

    
1555
  @staticmethod
1556
  def _DiagnoseByOS(node_list, rlist):
1557
    """Remaps a per-node return list into an a per-os per-node dictionary
1558

1559
    @param node_list: a list with the names of all nodes
1560
    @param rlist: a map with node names as keys and OS objects as values
1561

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

1566
          {"debian-etch": {"node1": [<object>,...],
1567
                           "node2": [<object>,]}
1568
          }
1569

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

    
1585
  def Exec(self, feedback_fn):
1586
    """Compute the list of OSes.
1587

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

    
1611
    return output
1612

    
1613

    
1614
class LURemoveNode(LogicalUnit):
1615
  """Logical unit for removing a node.
1616

1617
  """
1618
  HPATH = "node-remove"
1619
  HTYPE = constants.HTYPE_NODE
1620
  _OP_REQP = ["node_name"]
1621

    
1622
  def BuildHooksEnv(self):
1623
    """Build hooks env.
1624

1625
    This doesn't run on the target node in the pre phase as a failed
1626
    node would then be impossible to remove.
1627

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

    
1637
  def CheckPrereq(self):
1638
    """Check prerequisites.
1639

1640
    This checks:
1641
     - the node exists in the configuration
1642
     - it does not have primary or secondary instances
1643
     - it's not the master
1644

1645
    Any errors are signalled by raising errors.OpPrereqError.
1646

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

    
1652
    instance_list = self.cfg.GetInstanceList()
1653

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

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

    
1670
  def Exec(self, feedback_fn):
1671
    """Removes the node from the cluster.
1672

1673
    """
1674
    node = self.node
1675
    logging.info("Stopping the node daemon and removing configs from node %s",
1676
                 node.name)
1677

    
1678
    self.context.RemoveNode(node.name)
1679

    
1680
    self.rpc.call_node_leave_cluster(node.name)
1681

    
1682
    # Promote nodes to master candidate as needed
1683
    _AdjustCandidatePool(self)
1684

    
1685

    
1686
class LUQueryNodes(NoHooksLU):
1687
  """Logical unit for querying nodes.
1688

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

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

    
1709
  def ExpandNames(self):
1710
    _CheckOutputFields(static=self._FIELDS_STATIC,
1711
                       dynamic=self._FIELDS_DYNAMIC,
1712
                       selected=self.op.output_fields)
1713

    
1714
    self.needed_locks = {}
1715
    self.share_locks[locking.LEVEL_NODE] = 1
1716

    
1717
    if self.op.names:
1718
      self.wanted = _GetWantedNodes(self, self.op.names)
1719
    else:
1720
      self.wanted = locking.ALL_SET
1721

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

    
1727

    
1728
  def CheckPrereq(self):
1729
    """Check prerequisites.
1730

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

    
1736
  def Exec(self, feedback_fn):
1737
    """Computes the list of nodes and their attributes.
1738

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

    
1752
    nodenames = utils.NiceSort(nodenames)
1753
    nodelist = [all_info[name] for name in nodenames]
1754

    
1755
    # begin data gathering
1756

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

    
1780
    node_to_primary = dict([(name, set()) for name in nodenames])
1781
    node_to_secondary = dict([(name, set()) for name in nodenames])
1782

    
1783
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
1784
                             "sinst_cnt", "sinst_list"))
1785
    if inst_fields & frozenset(self.op.output_fields):
1786
      instancelist = self.cfg.GetInstanceList()
1787

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

    
1796
    master_node = self.cfg.GetMasterNode()
1797

    
1798
    # end data gathering
1799

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

    
1835
    return output
1836

    
1837

    
1838
class LUQueryNodeVolumes(NoHooksLU):
1839
  """Logical unit for getting volumes on node(s).
1840

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

    
1847
  def ExpandNames(self):
1848
    _CheckOutputFields(static=self._FIELDS_STATIC,
1849
                       dynamic=self._FIELDS_DYNAMIC,
1850
                       selected=self.op.output_fields)
1851

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

    
1860
  def CheckPrereq(self):
1861
    """Check prerequisites.
1862

1863
    This checks that the fields required are valid output fields.
1864

1865
    """
1866
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
1867

    
1868
  def Exec(self, feedback_fn):
1869
    """Computes the list of nodes and their attributes.
1870

1871
    """
1872
    nodenames = self.nodes
1873
    volumes = self.rpc.call_node_volumes(nodenames)
1874

    
1875
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
1876
             in self.cfg.GetInstanceList()]
1877

    
1878
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
1879

    
1880
    output = []
1881
    for node in nodenames:
1882
      if node not in volumes or volumes[node].failed or not volumes[node].data:
1883
        continue
1884

    
1885
      node_vols = volumes[node].data[:]
1886
      node_vols.sort(key=lambda vol: vol['dev'])
1887

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

    
1914
        output.append(node_output)
1915

    
1916
    return output
1917

    
1918

    
1919
class LUAddNode(LogicalUnit):
1920
  """Logical unit for adding node to the cluster.
1921

1922
  """
1923
  HPATH = "node-add"
1924
  HTYPE = constants.HTYPE_NODE
1925
  _OP_REQP = ["node_name"]
1926

    
1927
  def BuildHooksEnv(self):
1928
    """Build hooks env.
1929

1930
    This will run on all nodes before, and on all nodes + the new node after.
1931

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

    
1943
  def CheckPrereq(self):
1944
    """Check prerequisites.
1945

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

1951
    Any errors are signalled by raising errors.OpPrereqError.
1952

1953
    """
1954
    node_name = self.op.node_name
1955
    cfg = self.cfg
1956

    
1957
    dns_data = utils.HostInfo(node_name)
1958

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

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

    
1975
    for existing_node_name in node_list:
1976
      existing_node = cfg.GetNodeInfo(existing_node_name)
1977

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

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

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

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

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

    
2016
    cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2017
    mc_now, _ = self.cfg.GetMasterCandidateStats()
2018
    master_candidate = mc_now < cp_size
2019

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

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

2029
    """
2030
    new_node = self.new_node
2031
    node = new_node.name
2032

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2127

    
2128
class LUSetNodeParams(LogicalUnit):
2129
  """Modifies the parameters of a node.
2130

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

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

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

    
2153
  def BuildHooksEnv(self):
2154
    """Build hooks env.
2155

2156
    This runs on the master node.
2157

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

    
2168
  def CheckPrereq(self):
2169
    """Check prerequisites.
2170

2171
    This only checks the instance list against the existing names.
2172

2173
    """
2174
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
2175

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

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

    
2197
    return
2198

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

2202
    """
2203
    node = self.node
2204

    
2205
    result = []
2206

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

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

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

    
2231
    return result
2232

    
2233

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

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

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

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

2247
    """
2248
    pass
2249

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

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

    
2271
    return result
2272

    
2273

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

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

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

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

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

2293
    """
2294
    pass
2295

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

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

    
2313

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

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

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

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

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

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

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

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

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

    
2349
    return disks_info
2350

    
2351

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

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

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

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

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

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

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

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

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

    
2415
  return disks_ok, device_info
2416

    
2417

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

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

    
2432

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

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

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

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

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

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

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

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

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

    
2466

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

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

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

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

    
2485
  _ShutdownInstanceDisks(lu, instance)
2486

    
2487

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

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

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

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

    
2509

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

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

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

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

    
2543

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

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

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

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

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

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

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

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

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

    
2580
    _CheckNodeOnline(self, instance.primary_node)
2581

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

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

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

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

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

    
2600
    node_current = instance.primary_node
2601

    
2602
    _StartInstanceDisks(self, instance, force)
2603

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

    
2609

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

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

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

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

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

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

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

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

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

    
2653
    _CheckNodeOnline(self, instance.primary_node)
2654

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

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

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

    
2667
    node_current = instance.primary_node
2668

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

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

    
2687

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

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

    
2697
  def ExpandNames(self):
2698
    self._ExpandAndLockInstance()
2699

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

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

2705
    """
2706
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2707
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2708
          list(self.instance.secondary_nodes))
2709
    return env, nl, nl
2710

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

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

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

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

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

    
2733
    _ShutdownInstanceDisks(self, instance)
2734

    
2735

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

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

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

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

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

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

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

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

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

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

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

    
2798
    self.instance = instance
2799

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

2803
    """
2804
    inst = self.instance
2805

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

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

    
2823

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

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

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

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

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

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

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

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

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

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

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

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

    
2884

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

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

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

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

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

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

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

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

    
2934

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3002

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

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

    
3026

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

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

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

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

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

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

3054
    """
3055
    pass
3056

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

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

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

    
3077
    # begin data gathering
3078

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

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

    
3101
    # end data gathering
3102

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

    
3228
    return output
3229

    
3230

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3304
    """
3305
    instance = self.instance
3306

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

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

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

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

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

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

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

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

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

    
3360

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

3364
  This always creates all devices.
3365

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

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

    
3381

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

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

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

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

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

    
3410

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

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

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

    
3423

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

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

    
3444

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

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

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

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

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

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

    
3507

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

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

    
3514

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

3518
  This abstracts away some work from AddInstance.
3519

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

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

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

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

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

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

    
3561
  return True
3562

    
3563

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

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

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

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

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

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

    
3600
  return result
3601

    
3602

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

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

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

    
3620
  return req_size_dict[disk_template]
3621

    
3622

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

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

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

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

    
3653

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

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

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

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

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

3678
    Figure out the right locks for instance creation.
3679

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

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

    
3688
    # cheap checks, mostly valid constants given
3689

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

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

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

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

    
3710
    # check hypervisor parameter syntax (locally)
3711

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

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

    
3722
    #### instance parameters check
3723

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3896

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

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

    
3906

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

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

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

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

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

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

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

    
3961
      self.src_images = disk_images
3962

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

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

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

    
3982
    #### allocator run
3983

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

    
3987
    #### node related checks
3988

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

    
3997
    self.secondaries = []
3998

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4096

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

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

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

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

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

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

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

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

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

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

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

    
4200

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4248

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

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

    
4258
  def CheckArguments(self):
4259
    if not hasattr(self.op, "remote_node"):
4260
      self.op.remote_node = None
4261
    if not hasattr(self.op, "iallocator"):
4262
      self.op.iallocator = None
4263

    
4264
    # check for valid parameter combination
4265
    cnt = [self.op.remote_node, self.op.iallocator].count(None)
4266
    if self.op.mode == constants.REPLACE_DISK_CHG:
4267
      if cnt == 2:
4268
        raise errors.OpPrereqError("When changing the secondary either an"
4269
                                   " iallocator script must be used or the"
4270
                                   " new node given")
4271
      elif cnt == 0:
4272
        raise errors.OpPrereqError("Give either the iallocator or the new"
4273
                                   " secondary, not both")
4274
    else: # not replacing the secondary
4275
      if cnt != 2:
4276
        raise errors.OpPrereqError("The iallocator and new node options can"
4277
                                   " be used only when changing the"
4278
                                   " secondary node")
4279

    
4280
  def ExpandNames(self):
4281
    self._ExpandAndLockInstance()
4282

    
4283
    if self.op.iallocator is not None:
4284
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4285
    elif self.op.remote_node is not None:
4286
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
4287
      if remote_node is None:
4288
        raise errors.OpPrereqError("Node '%s' not known" %
4289
                                   self.op.remote_node)
4290
      self.op.remote_node = remote_node
4291
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
4292
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4293
    else:
4294
      self.needed_locks[locking.LEVEL_NODE] = []
4295
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4296

    
4297
  def DeclareLocks(self, level):
4298
    # If we're not already locking all nodes in the set we have to declare the
4299
    # instance's primary/secondary nodes.
4300
    if (level == locking.LEVEL_NODE and
4301
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
4302
      self._LockInstancesNodes()
4303

    
4304
  def _RunAllocator(self):
4305
    """Compute a new secondary node using an IAllocator.
4306

4307
    """
4308
    ial = IAllocator(self,
4309
                     mode=constants.IALLOCATOR_MODE_RELOC,
4310
                     name=self.op.instance_name,
4311
                     relocate_from=[self.sec_node])
4312

    
4313
    ial.Run(self.op.iallocator)
4314

    
4315
    if not ial.success:
4316
      raise errors.OpPrereqError("Can't compute nodes using"
4317
                                 " iallocator '%s': %s" % (self.op.iallocator,
4318
                                                           ial.info))
4319
    if len(ial.nodes) != ial.required_nodes:
4320
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
4321
                                 " of nodes (%s), required %s" %
4322
                                 (len(ial.nodes), ial.required_nodes))
4323
    self.op.remote_node = ial.nodes[0]
4324
    self.LogInfo("Selected new secondary for the instance: %s",
4325
                 self.op.remote_node)
4326

    
4327
  def BuildHooksEnv(self):
4328
    """Build hooks env.
4329

4330
    This runs on the master, the primary and all the secondaries.
4331

4332
    """
4333
    env = {
4334
      "MODE": self.op.mode,
4335
      "NEW_SECONDARY": self.op.remote_node,
4336
      "OLD_SECONDARY": self.instance.secondary_nodes[0],
4337
      }
4338
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4339
    nl = [
4340
      self.cfg.GetMasterNode(),
4341
      self.instance.primary_node,
4342
      ]
4343
    if self.op.remote_node is not None:
4344
      nl.append(self.op.remote_node)
4345
    return env, nl, nl
4346

    
4347
  def CheckPrereq(self):
4348
    """Check prerequisites.
4349

4350
    This checks that the instance is in the cluster.
4351

4352
    """
4353
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4354
    assert instance is not None, \
4355
      "Cannot retrieve locked instance %s" % self.op.instance_name
4356
    self.instance = instance
4357

    
4358
    if instance.disk_template != constants.DT_DRBD8:
4359
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
4360
                                 " instances")
4361

    
4362
    if len(instance.secondary_nodes) != 1:
4363
      raise errors.OpPrereqError("The instance has a strange layout,"
4364
                                 " expected one secondary but found %d" %
4365
                                 len(instance.secondary_nodes))
4366

    
4367
    self.sec_node = instance.secondary_nodes[0]
4368

    
4369
    if self.op.iallocator is not None:
4370
      self._RunAllocator()
4371

    
4372
    remote_node = self.op.remote_node
4373
    if remote_node is not None:
4374
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
4375
      assert self.remote_node_info is not None, \
4376
        "Cannot retrieve locked node %s" % remote_node
4377
    else:
4378
      self.remote_node_info = None
4379
    if remote_node == instance.primary_node:
4380
      raise errors.OpPrereqError("The specified node is the primary node of"
4381
                                 " the instance.")
4382
    elif remote_node == self.sec_node:
4383
      raise errors.OpPrereqError("The specified node is already the"
4384
                                 " secondary node of the instance.")
4385

    
4386
    if self.op.mode == constants.REPLACE_DISK_PRI:
4387
      n1 = self.tgt_node = instance.primary_node
4388
      n2 = self.oth_node = self.sec_node
4389
    elif self.op.mode == constants.REPLACE_DISK_SEC:
4390
      n1 = self.tgt_node = self.sec_node
4391
      n2 = self.oth_node = instance.primary_node
4392
    elif self.op.mode == constants.REPLACE_DISK_CHG:
4393
      n1 = self.new_node = remote_node
4394
      n2 = self.oth_node = instance.primary_node
4395
      self.tgt_node = self.sec_node
4396
    else:
4397
      raise errors.ProgrammerError("Unhandled disk replace mode")
4398

    
4399
    _CheckNodeOnline(self, n1)
4400
    _CheckNodeOnline(self, n2)
4401

    
4402
    if not self.op.disks:
4403
      self.op.disks = range(len(instance.disks))
4404

    
4405
    for disk_idx in self.op.disks:
4406
      instance.FindDisk(disk_idx)
4407

    
4408
  def _ExecD8DiskOnly(self, feedback_fn):
4409
    """Replace a disk on the primary or secondary for dbrd8.
4410

4411
    The algorithm for replace is quite complicated:
4412

4413
      1. for each disk to be replaced:
4414

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

4421
      1. wait for sync across all devices
4422

4423
      1. for each modified disk:
4424

4425
        1. remove old LVs (which have the name name_replaces.<time_t>)
4426

4427
    Failures are not very well handled.
4428

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

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

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

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

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

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

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

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

    
4545
      for old, new in zip(old_lvs, new_lvs):
4546
        new.logical_id = old.logical_id
4547
        cfg.SetDiskID(new, tgt_node)
4548

    
4549
      for disk in old_lvs:
4550
        disk.logical_id = ren_fn(disk, temp_suffix)
4551
        cfg.SetDiskID(disk, tgt_node)
4552

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

    
4564
      dev.children = new_lvs
4565
      cfg.Update(instance)
4566

    
4567
    # Step: wait for sync
4568

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

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

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

    
4593
  def _ExecD8Secondary(self, feedback_fn):
4594
    """Replace the secondary node for drbd8.
4595

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

4609
    Failures are not very well handled.
4610

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

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

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

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

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

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

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

    
4726
    if not done:
4727
      # no detaches succeeded (very unlikely)
4728
      self.cfg.ReleaseDRBDMinors(instance.name)
4729
      raise errors.OpExecError("Can't detach at least one DRBD from old node")
4730

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

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

    
4756
    # this can fail as the old devices are degraded and _WaitForSync
4757
    # does a combined result over all disks, so we don't check its
4758
    # return value
4759
    self.proc.LogStep(5, steps_total, "sync devices")
4760
    _WaitForSync(self, instance, unlock=True)
4761

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

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

    
4780
  def Exec(self, feedback_fn):
4781
    """Execute disk replacement.
4782

4783
    This dispatches the disk replacement to the appropriate handler.
4784

4785
    """
4786
    instance = self.instance
4787

    
4788
    # Activate the instance disks if we're replacing them on a down instance
4789
    if instance.status == "down":
4790
      _StartInstanceDisks(self, instance, True)
4791

    
4792
    if self.op.mode == constants.REPLACE_DISK_CHG:
4793
      fn = self._ExecD8Secondary
4794
    else:
4795
      fn = self._ExecD8DiskOnly
4796

    
4797
    ret = fn(feedback_fn)
4798

    
4799
    # Deactivate the instance disks if we're replacing them on a down instance
4800
    if instance.status == "down":
4801
      _SafeShutdownInstanceDisks(self, instance)
4802

    
4803
    return ret
4804

    
4805

    
4806
class LUGrowDisk(LogicalUnit):
4807
  """Grow a disk of an instance.
4808

4809
  """
4810
  HPATH = "disk-grow"
4811
  HTYPE = constants.HTYPE_INSTANCE
4812
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
4813
  REQ_BGL = False
4814

    
4815
  def ExpandNames(self):
4816
    self._ExpandAndLockInstance()
4817
    self.needed_locks[locking.LEVEL_NODE] = []
4818
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4819

    
4820
  def DeclareLocks(self, level):
4821
    if level == locking.LEVEL_NODE:
4822
      self._LockInstancesNodes()
4823

    
4824
  def BuildHooksEnv(self):
4825
    """Build hooks env.
4826

4827
    This runs on the master, the primary and all the secondaries.
4828

4829
    """
4830
    env = {
4831
      "DISK": self.op.disk,
4832
      "AMOUNT": self.op.amount,
4833
      }
4834
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4835
    nl = [
4836
      self.cfg.GetMasterNode(),
4837
      self.instance.primary_node,
4838
      ]
4839
    return env, nl, nl
4840

    
4841
  def CheckPrereq(self):
4842
    """Check prerequisites.
4843

4844
    This checks that the instance is in the cluster.
4845

4846
    """
4847
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4848
    assert instance is not None, \
4849
      "Cannot retrieve locked instance %s" % self.op.instance_name
4850
    _CheckNodeOnline(self, instance.primary_node)
4851
    for node in instance.secondary_nodes:
4852
      _CheckNodeOnline(self, node)
4853

    
4854

    
4855
    self.instance = instance
4856

    
4857
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
4858
      raise errors.OpPrereqError("Instance's disk layout does not support"
4859
                                 " growing.")
4860

    
4861
    self.disk = instance.FindDisk(self.op.disk)
4862

    
4863
    nodenames = [instance.primary_node] + list(instance.secondary_nodes)
4864
    nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
4865
                                       instance.hypervisor)
4866
    for node in nodenames:
4867
      info = nodeinfo[node]
4868
      if info.failed or not info.data:
4869
        raise errors.OpPrereqError("Cannot get current information"
4870
                                   " from node '%s'" % node)
4871
      vg_free = info.data.get('vg_free', None)
4872
      if not isinstance(vg_free, int):
4873
        raise errors.OpPrereqError("Can't compute free disk space on"
4874
                                   " node %s" % node)
4875
      if self.op.amount > vg_free:
4876
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
4877
                                   " %d MiB available, %d MiB required" %
4878
                                   (node, vg_free, self.op.amount))
4879

    
4880
  def Exec(self, feedback_fn):
4881
    """Execute disk grow.
4882

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

    
4904

    
4905
class LUQueryInstanceData(NoHooksLU):
4906
  """Query runtime instance data.
4907

4908
  """
4909
  _OP_REQP = ["instances", "static"]
4910
  REQ_BGL = False
4911

    
4912
  def ExpandNames(self):
4913
    self.needed_locks = {}
4914
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
4915

    
4916
    if not isinstance(self.op.instances, list):
4917
      raise errors.OpPrereqError("Invalid argument type 'instances'")
4918

    
4919
    if self.op.instances:
4920
      self.wanted_names = []
4921
      for name in self.op.instances:
4922
        full_name = self.cfg.ExpandInstanceName(name)
4923
        if full_name is None:
4924
          raise errors.OpPrereqError("Instance '%s' not known" %
4925
                                     self.op.instance_name)
4926
        self.wanted_names.append(full_name)
4927
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
4928
    else:
4929
      self.wanted_names = None
4930
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4931

    
4932
    self.needed_locks[locking.LEVEL_NODE] = []
4933
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4934

    
4935
  def DeclareLocks(self, level):
4936
    if level == locking.LEVEL_NODE:
4937
      self._LockInstancesNodes()
4938

    
4939
  def CheckPrereq(self):
4940
    """Check prerequisites.
4941

4942
    This only checks the optional instance list against the existing names.
4943

4944
    """
4945
    if self.wanted_names is None:
4946
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
4947

    
4948
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
4949
                             in self.wanted_names]
4950
    return
4951

    
4952
  def _ComputeDiskStatus(self, instance, snode, dev):
4953
    """Compute block device status.
4954

4955
    """
4956
    static = self.op.static
4957
    if not static:
4958
      self.cfg.SetDiskID(dev, instance.primary_node)
4959
      dev_pstatus = self.rpc.call_blockdev_find(instance.primary_node, dev)
4960
      dev_pstatus.Raise()
4961
      dev_pstatus = dev_pstatus.data
4962
    else:
4963
      dev_pstatus = None
4964

    
4965
    if dev.dev_type in constants.LDS_DRBD:
4966
      # we change the snode then (otherwise we use the one passed in)
4967
      if dev.logical_id[0] == instance.primary_node:
4968
        snode = dev.logical_id[1]
4969
      else:
4970
        snode = dev.logical_id[0]
4971

    
4972
    if snode and not static:
4973
      self.cfg.SetDiskID(dev, snode)
4974
      dev_sstatus = self.rpc.call_blockdev_find(snode, dev)
4975
      dev_sstatus.Raise()
4976
      dev_sstatus = dev_sstatus.data
4977
    else:
4978
      dev_sstatus = None
4979

    
4980
    if dev.children:
4981
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
4982
                      for child in dev.children]
4983
    else:
4984
      dev_children = []
4985

    
4986
    data = {
4987
      "iv_name": dev.iv_name,
4988
      "dev_type": dev.dev_type,
4989
      "logical_id": dev.logical_id,
4990
      "physical_id": dev.physical_id,
4991
      "pstatus": dev_pstatus,
4992
      "sstatus": dev_sstatus,
4993
      "children": dev_children,
4994
      "mode": dev.mode,
4995
      }
4996

    
4997
    return data
4998

    
4999
  def Exec(self, feedback_fn):
5000
    """Gather and return data"""
5001
    result = {}
5002

    
5003
    cluster = self.cfg.GetClusterInfo()
5004

    
5005
    for instance in self.wanted_instances:
5006
      if not self.op.static:
5007
        remote_info = self.rpc.call_instance_info(instance.primary_node,
5008
                                                  instance.name,
5009
                                                  instance.hypervisor)
5010
        remote_info.Raise()
5011
        remote_info = remote_info.data
5012
        if remote_info and "state" in remote_info:
5013
          remote_state = "up"
5014
        else:
5015
          remote_state = "down"
5016
      else:
5017
        remote_state = None
5018
      if instance.status == "down":
5019
        config_state = "down"
5020
      else:
5021
        config_state = "up"
5022

    
5023
      disks = [self._ComputeDiskStatus(instance, None, device)
5024
               for device in instance.disks]
5025

    
5026
      idict = {
5027
        "name": instance.name,
5028
        "config_state": config_state,
5029
        "run_state": remote_state,
5030
        "pnode": instance.primary_node,
5031
        "snodes": instance.secondary_nodes,
5032
        "os": instance.os,
5033
        "nics": [(nic.mac, nic.ip, nic.bridge) for nic in instance.nics],
5034
        "disks": disks,
5035
        "hypervisor": instance.hypervisor,
5036
        "network_port": instance.network_port,
5037
        "hv_instance": instance.hvparams,
5038
        "hv_actual": cluster.FillHV(instance),
5039
        "be_instance": instance.beparams,
5040
        "be_actual": cluster.FillBE(instance),
5041
        }
5042

    
5043
      result[instance.name] = idict
5044

    
5045
    return result
5046

    
5047

    
5048
class LUSetInstanceParams(LogicalUnit):
5049
  """Modifies an instances's parameters.
5050

5051
  """
5052
  HPATH = "instance-modify"
5053
  HTYPE = constants.HTYPE_INSTANCE
5054
  _OP_REQP = ["instance_name"]
5055
  REQ_BGL = False
5056

    
5057
  def CheckArguments(self):
5058
    if not hasattr(self.op, 'nics'):
5059
      self.op.nics = []
5060
    if not hasattr(self.op, 'disks'):
5061
      self.op.disks = []
5062
    if not hasattr(self.op, 'beparams'):
5063
      self.op.beparams = {}
5064
    if not hasattr(self.op, 'hvparams'):
5065
      self.op.hvparams = {}
5066
    self.op.force = getattr(self.op, "force", False)
5067
    if not (self.op.nics or self.op.disks or
5068
            self.op.hvparams or self.op.beparams):
5069
      raise errors.OpPrereqError("No changes submitted")
5070

    
5071
    utils.CheckBEParams(self.op.beparams)
5072

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

    
5103
    if disk_addremove > 1:
5104
      raise errors.OpPrereqError("Only one disk add or remove operation"
5105
                                 " supported at a time")
5106

    
5107
    # NIC validation
5108
    nic_addremove = 0
5109
    for nic_op, nic_dict in self.op.nics:
5110
      if nic_op == constants.DDM_REMOVE:
5111
        nic_addremove += 1
5112
        continue
5113
      elif nic_op == constants.DDM_ADD:
5114
        nic_addremove += 1
5115
      else:
5116
        if not isinstance(nic_op, int):
5117
          raise errors.OpPrereqError("Invalid nic index")
5118

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

    
5144
  def ExpandNames(self):
5145
    self._ExpandAndLockInstance()
5146
    self.needed_locks[locking.LEVEL_NODE] = []
5147
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5148

    
5149
  def DeclareLocks(self, level):
5150
    if level == locking.LEVEL_NODE:
5151
      self._LockInstancesNodes()
5152

    
5153
  def BuildHooksEnv(self):
5154
    """Build hooks env.
5155

5156
    This runs on the master, primary and secondaries.
5157

5158
    """
5159
    args = dict()
5160
    if constants.BE_MEMORY in self.be_new:
5161
      args['memory'] = self.be_new[constants.BE_MEMORY]
5162
    if constants.BE_VCPUS in self.be_new:
5163
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
5164
    # FIXME: readd disk/nic changes
5165
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
5166
    nl = [self.cfg.GetMasterNode(),
5167
          self.instance.primary_node] + list(self.instance.secondary_nodes)
5168
    return env, nl, nl
5169

    
5170
  def CheckPrereq(self):
5171
    """Check prerequisites.
5172

5173
    This only checks the instance list against the existing names.
5174

5175
    """
5176
    force = self.force = self.op.force
5177

    
5178
    # checking the new params on the primary/secondary nodes
5179

    
5180
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5181
    assert self.instance is not None, \
5182
      "Cannot retrieve locked instance %s" % self.op.instance_name
5183
    pnode = self.instance.primary_node
5184
    nodelist = [pnode]
5185
    nodelist.extend(instance.secondary_nodes)
5186

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

    
5212
    # beparams processing
5213
    if self.op.beparams:
5214
      i_bedict = copy.deepcopy(instance.beparams)
5215
      for key, val in self.op.beparams.iteritems():
5216
        if val == constants.VALUE_DEFAULT:
5217
          try:
5218
            del i_bedict[key]
5219
          except KeyError:
5220
            pass
5221
        else:
5222
          i_bedict[key] = val
5223
      cluster = self.cfg.GetClusterInfo()
5224
      be_new = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
5225
                                i_bedict)
5226
      self.be_new = be_new # the new actual values
5227
      self.be_inst = i_bedict # the new dict (without defaults)
5228
    else:
5229
      self.be_new = self.be_inst = {}
5230

    
5231
    self.warn = []
5232

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

    
5260
      if be_new[constants.BE_AUTO_BALANCE]:
5261
        for node, nres in instance.secondary_nodes.iteritems():
5262
          if nres.failed or not isinstance(nres.data, dict):
5263
            self.warn.append("Can't get info from secondary node %s" % node)
5264
          elif be_new[constants.BE_MEMORY] > nres.data['memory_free']:
5265
            self.warn.append("Not enough memory to failover instance to"
5266
                             " secondary node %s" % node)
5267

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

    
5290
    # DISK processing
5291
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
5292
      raise errors.OpPrereqError("Disk operations not supported for"
5293
                                 " diskless instances")
5294
    for disk_op, disk_dict in self.op.disks:
5295
      if disk_op == constants.DDM_REMOVE:
5296
        if len(instance.disks) == 1:
5297
          raise errors.OpPrereqError("Cannot remove the last disk of"
5298
                                     " an instance")
5299
        ins_l = self.rpc.call_instance_list([pnode], [instance.hypervisor])
5300
        ins_l = ins_l[pnode]
5301
        if not type(ins_l) is list:
5302
          raise errors.OpPrereqError("Can't contact node '%s'" % pnode)
5303
        if instance.name in ins_l:
5304
          raise errors.OpPrereqError("Instance is running, can't remove"
5305
                                     " disks.")
5306

    
5307
      if (disk_op == constants.DDM_ADD and
5308
          len(instance.nics) >= constants.MAX_DISKS):
5309
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
5310
                                   " add more" % constants.MAX_DISKS)
5311
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
5312
        # an existing disk
5313
        if disk_op < 0 or disk_op >= len(instance.disks):
5314
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
5315
                                     " are 0 to %d" %
5316
                                     (disk_op, len(instance.disks)))
5317

    
5318
    return
5319

    
5320
  def Exec(self, feedback_fn):
5321
    """Modifies an instance.
5322

5323
    All parameters take effect only at the next restart of the instance.
5324

5325
    """
5326
    # Process here the warnings from CheckPrereq, as we don't have a
5327
    # feedback_fn there.
5328
    for warn in self.warn:
5329
      feedback_fn("WARNING: %s" % warn)
5330

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

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

    
5414
    # hvparams changes
5415
    if self.op.hvparams:
5416
      instance.hvparams = self.hv_new
5417
      for key, val in self.op.hvparams.iteritems():
5418
        result.append(("hv/%s" % key, val))
5419

    
5420
    # beparams changes
5421
    if self.op.beparams:
5422
      instance.beparams = self.be_inst
5423
      for key, val in self.op.beparams.iteritems():
5424
        result.append(("be/%s" % key, val))
5425

    
5426
    self.cfg.Update(instance)
5427

    
5428
    return result
5429

    
5430

    
5431
class LUQueryExports(NoHooksLU):
5432
  """Query the exports list
5433

5434
  """
5435
  _OP_REQP = ['nodes']
5436
  REQ_BGL = False
5437

    
5438
  def ExpandNames(self):
5439
    self.needed_locks = {}
5440
    self.share_locks[locking.LEVEL_NODE] = 1
5441
    if not self.op.nodes:
5442
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5443
    else:
5444
      self.needed_locks[locking.LEVEL_NODE] = \
5445
        _GetWantedNodes(self, self.op.nodes)
5446

    
5447
  def CheckPrereq(self):
5448
    """Check prerequisites.
5449

5450
    """
5451
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
5452

    
5453
  def Exec(self, feedback_fn):
5454
    """Compute the list of all the exported system images.
5455

5456
    @rtype: dict
5457
    @return: a dictionary with the structure node->(export-list)
5458
        where export-list is a list of the instances exported on
5459
        that node.
5460

5461
    """
5462
    rpcresult = self.rpc.call_export_list(self.nodes)
5463
    result = {}
5464
    for node in rpcresult:
5465
      if rpcresult[node].failed:
5466
        result[node] = False
5467
      else:
5468
        result[node] = rpcresult[node].data
5469

    
5470
    return result
5471

    
5472

    
5473
class LUExportInstance(LogicalUnit):
5474
  """Export an instance to an image in the cluster.
5475

5476
  """
5477
  HPATH = "instance-export"
5478
  HTYPE = constants.HTYPE_INSTANCE
5479
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
5480
  REQ_BGL = False
5481

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

    
5494
  def DeclareLocks(self, level):
5495
    """Last minute lock declaration."""
5496
    # All nodes are locked anyway, so nothing to do here.
5497

    
5498
  def BuildHooksEnv(self):
5499
    """Build hooks env.
5500

5501
    This will run on the master, primary node and target node.
5502

5503
    """
5504
    env = {
5505
      "EXPORT_NODE": self.op.target_node,
5506
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
5507
      }
5508
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5509
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node,
5510
          self.op.target_node]
5511
    return env, nl, nl
5512

    
5513
  def CheckPrereq(self):
5514
    """Check prerequisites.
5515

5516
    This checks that the instance and node names are valid.
5517

5518
    """
5519
    instance_name = self.op.instance_name
5520
    self.instance = self.cfg.GetInstanceInfo(instance_name)
5521
    assert self.instance is not None, \
5522
          "Cannot retrieve locked instance %s" % self.op.instance_name
5523
    _CheckNodeOnline(self, self.instance.primary_node)
5524

    
5525
    self.dst_node = self.cfg.GetNodeInfo(
5526
      self.cfg.ExpandNodeName(self.op.target_node))
5527

    
5528
    if self.dst_node is None:
5529
      # This is wrong node name, not a non-locked node
5530
      raise errors.OpPrereqError("Wrong node name %s" % self.op.target_node)
5531
    _CheckNodeOnline(self, self.op.target_node)
5532

    
5533
    # instance disk type verification
5534
    for disk in self.instance.disks:
5535
      if disk.dev_type == constants.LD_FILE:
5536
        raise errors.OpPrereqError("Export not supported for instances with"
5537
                                   " file-based disks")
5538

    
5539
  def Exec(self, feedback_fn):
5540
    """Export an instance to an image in the cluster.
5541

5542
    """
5543
    instance = self.instance
5544
    dst_node = self.dst_node
5545
    src_node = instance.primary_node
5546
    if self.op.shutdown:
5547
      # shutdown the instance, but not the disks
5548
      result = self.rpc.call_instance_shutdown(src_node, instance)
5549
      result.Raise()
5550
      if not result.data:
5551
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
5552
                                 (instance.name, src_node))
5553

    
5554
    vgname = self.cfg.GetVGName()
5555

    
5556
    snap_disks = []
5557

    
5558
    try:
5559
      for disk in instance.disks:
5560
        # new_dev_name will be a snapshot of an lvm leaf of the one we passed
5561
        new_dev_name = self.rpc.call_blockdev_snapshot(src_node, disk)
5562
        if new_dev_name.failed or not new_dev_name.data:
5563
          self.LogWarning("Could not snapshot block device %s on node %s",
5564
                          disk.logical_id[1], src_node)
5565
          snap_disks.append(False)
5566
        else:
5567
          new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
5568
                                 logical_id=(vgname, new_dev_name.data),
5569
                                 physical_id=(vgname, new_dev_name.data),
5570
                                 iv_name=disk.iv_name)
5571
          snap_disks.append(new_dev)
5572

    
5573
    finally:
5574
      if self.op.shutdown and instance.status == "up":
5575
        result = self.rpc.call_instance_start(src_node, instance, None)
5576
        if result.failed or not result.data:
5577
          _ShutdownInstanceDisks(self, instance)
5578
          raise errors.OpExecError("Could not start instance")
5579

    
5580
    # TODO: check for size
5581

    
5582
    cluster_name = self.cfg.GetClusterName()
5583
    for idx, dev in enumerate(snap_disks):
5584
      if dev:
5585
        result = self.rpc.call_snapshot_export(src_node, dev, dst_node.name,
5586
                                               instance, cluster_name, idx)
5587
        if result.failed or not result.data:
5588
          self.LogWarning("Could not export block device %s from node %s to"
5589
                          " node %s", dev.logical_id[1], src_node,
5590
                          dst_node.name)
5591
        result = self.rpc.call_blockdev_remove(src_node, dev)
5592
        if result.failed or not result.data:
5593
          self.LogWarning("Could not remove snapshot block device %s from node"
5594
                          " %s", dev.logical_id[1], src_node)
5595

    
5596
    result = self.rpc.call_finalize_export(dst_node.name, instance, snap_disks)
5597
    if result.failed or not result.data:
5598
      self.LogWarning("Could not finalize export for instance %s on node %s",
5599
                      instance.name, dst_node.name)
5600

    
5601
    nodelist = self.cfg.GetNodeList()
5602
    nodelist.remove(dst_node.name)
5603

    
5604
    # on one-node clusters nodelist will be empty after the removal
5605
    # if we proceed the backup would be removed because OpQueryExports
5606
    # substitutes an empty list with the full cluster node list.
5607
    if nodelist:
5608
      exportlist = self.rpc.call_export_list(nodelist)
5609
      for node in exportlist:
5610
        if exportlist[node].failed:
5611
          continue
5612
        if instance.name in exportlist[node].data:
5613
          if not self.rpc.call_export_remove(node, instance.name):
5614
            self.LogWarning("Could not remove older export for instance %s"
5615
                            " on node %s", instance.name, node)
5616

    
5617

    
5618
class LURemoveExport(NoHooksLU):
5619
  """Remove exports related to the named instance.
5620

5621
  """
5622
  _OP_REQP = ["instance_name"]
5623
  REQ_BGL = False
5624

    
5625
  def ExpandNames(self):
5626
    self.needed_locks = {}
5627
    # We need all nodes to be locked in order for RemoveExport to work, but we
5628
    # don't need to lock the instance itself, as nothing will happen to it (and
5629
    # we can remove exports also for a removed instance)
5630
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5631

    
5632
  def CheckPrereq(self):
5633
    """Check prerequisites.
5634
    """
5635
    pass
5636

    
5637
  def Exec(self, feedback_fn):
5638
    """Remove any export.
5639

5640
    """
5641
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
5642
    # If the instance was not found we'll try with the name that was passed in.
5643
    # This will only work if it was an FQDN, though.
5644
    fqdn_warn = False
5645
    if not instance_name:
5646
      fqdn_warn = True
5647
      instance_name = self.op.instance_name
5648

    
5649
    exportlist = self.rpc.call_export_list(self.acquired_locks[
5650
      locking.LEVEL_NODE])
5651
    found = False
5652
    for node in exportlist:
5653
      if exportlist[node].failed:
5654
        self.LogWarning("Failed to query node %s, continuing" % node)
5655
        continue
5656
      if instance_name in exportlist[node].data:
5657
        found = True
5658
        result = self.rpc.call_export_remove(node, instance_name)
5659
        if result.failed or not result.data:
5660
          logging.error("Could not remove export for instance %s"
5661
                        " on node %s", instance_name, node)
5662

    
5663
    if fqdn_warn and not found:
5664
      feedback_fn("Export not found. If trying to remove an export belonging"
5665
                  " to a deleted instance please use its Fully Qualified"
5666
                  " Domain Name.")
5667

    
5668

    
5669
class TagsLU(NoHooksLU):
5670
  """Generic tags LU.
5671

5672
  This is an abstract class which is the parent of all the other tags LUs.
5673

5674
  """
5675

    
5676
  def ExpandNames(self):
5677
    self.needed_locks = {}
5678
    if self.op.kind == constants.TAG_NODE:
5679
      name = self.cfg.ExpandNodeName(self.op.name)
5680
      if name is None:
5681
        raise errors.OpPrereqError("Invalid node name (%s)" %
5682
                                   (self.op.name,))
5683
      self.op.name = name
5684
      self.needed_locks[locking.LEVEL_NODE] = name
5685
    elif self.op.kind == constants.TAG_INSTANCE:
5686
      name = self.cfg.ExpandInstanceName(self.op.name)
5687
      if name is None:
5688
        raise errors.OpPrereqError("Invalid instance name (%s)" %
5689
                                   (self.op.name,))
5690
      self.op.name = name
5691
      self.needed_locks[locking.LEVEL_INSTANCE] = name
5692

    
5693
  def CheckPrereq(self):
5694
    """Check prerequisites.
5695

5696
    """
5697
    if self.op.kind == constants.TAG_CLUSTER:
5698
      self.target = self.cfg.GetClusterInfo()
5699
    elif self.op.kind == constants.TAG_NODE:
5700
      self.target = self.cfg.GetNodeInfo(self.op.name)
5701
    elif self.op.kind == constants.TAG_INSTANCE:
5702
      self.target = self.cfg.GetInstanceInfo(self.op.name)
5703
    else:
5704
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
5705
                                 str(self.op.kind))
5706

    
5707

    
5708
class LUGetTags(TagsLU):
5709
  """Returns the tags of a given object.
5710

5711
  """
5712
  _OP_REQP = ["kind", "name"]
5713
  REQ_BGL = False
5714

    
5715
  def Exec(self, feedback_fn):
5716
    """Returns the tag list.
5717

5718
    """
5719
    return list(self.target.GetTags())
5720

    
5721

    
5722
class LUSearchTags(NoHooksLU):
5723
  """Searches the tags for a given pattern.
5724

5725
  """
5726
  _OP_REQP = ["pattern"]
5727
  REQ_BGL = False
5728

    
5729
  def ExpandNames(self):
5730
    self.needed_locks = {}
5731

    
5732
  def CheckPrereq(self):
5733
    """Check prerequisites.
5734

5735
    This checks the pattern passed for validity by compiling it.
5736

5737
    """
5738
    try:
5739
      self.re = re.compile(self.op.pattern)
5740
    except re.error, err:
5741
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
5742
                                 (self.op.pattern, err))
5743

    
5744
  def Exec(self, feedback_fn):
5745
    """Returns the tag list.
5746

5747
    """
5748
    cfg = self.cfg
5749
    tgts = [("/cluster", cfg.GetClusterInfo())]
5750
    ilist = cfg.GetAllInstancesInfo().values()
5751
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
5752
    nlist = cfg.GetAllNodesInfo().values()
5753
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
5754
    results = []
5755
    for path, target in tgts:
5756
      for tag in target.GetTags():
5757
        if self.re.search(tag):
5758
          results.append((path, tag))
5759
    return results
5760

    
5761

    
5762
class LUAddTags(TagsLU):
5763
  """Sets a tag on a given object.
5764

5765
  """
5766
  _OP_REQP = ["kind", "name", "tags"]
5767
  REQ_BGL = False
5768

    
5769
  def CheckPrereq(self):
5770
    """Check prerequisites.
5771

5772
    This checks the type and length of the tag name and value.
5773

5774
    """
5775
    TagsLU.CheckPrereq(self)
5776
    for tag in self.op.tags:
5777
      objects.TaggableObject.ValidateTag(tag)
5778

    
5779
  def Exec(self, feedback_fn):
5780
    """Sets the tag.
5781

5782
    """
5783
    try:
5784
      for tag in self.op.tags:
5785
        self.target.AddTag(tag)
5786
    except errors.TagError, err:
5787
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
5788
    try:
5789
      self.cfg.Update(self.target)
5790
    except errors.ConfigurationError:
5791
      raise errors.OpRetryError("There has been a modification to the"
5792
                                " config file and the operation has been"
5793
                                " aborted. Please retry.")
5794

    
5795

    
5796
class LUDelTags(TagsLU):
5797
  """Delete a list of tags from a given object.
5798

5799
  """
5800
  _OP_REQP = ["kind", "name", "tags"]
5801
  REQ_BGL = False
5802

    
5803
  def CheckPrereq(self):
5804
    """Check prerequisites.
5805

5806
    This checks that we have the given tag.
5807

5808
    """
5809
    TagsLU.CheckPrereq(self)
5810
    for tag in self.op.tags:
5811
      objects.TaggableObject.ValidateTag(tag)
5812
    del_tags = frozenset(self.op.tags)
5813
    cur_tags = self.target.GetTags()
5814
    if not del_tags <= cur_tags:
5815
      diff_tags = del_tags - cur_tags
5816
      diff_names = ["'%s'" % tag for tag in diff_tags]
5817
      diff_names.sort()
5818
      raise errors.OpPrereqError("Tag(s) %s not found" %
5819
                                 (",".join(diff_names)))
5820

    
5821
  def Exec(self, feedback_fn):
5822
    """Remove the tag from the object.
5823

5824
    """
5825
    for tag in self.op.tags:
5826
      self.target.RemoveTag(tag)
5827
    try:
5828
      self.cfg.Update(self.target)
5829
    except errors.ConfigurationError:
5830
      raise errors.OpRetryError("There has been a modification to the"
5831
                                " config file and the operation has been"
5832
                                " aborted. Please retry.")
5833

    
5834

    
5835
class LUTestDelay(NoHooksLU):
5836
  """Sleep for a specified amount of time.
5837

5838
  This LU sleeps on the master and/or nodes for a specified amount of
5839
  time.
5840

5841
  """
5842
  _OP_REQP = ["duration", "on_master", "on_nodes"]
5843
  REQ_BGL = False
5844

    
5845
  def ExpandNames(self):
5846
    """Expand names and set required locks.
5847

5848
    This expands the node list, if any.
5849

5850
    """
5851
    self.needed_locks = {}
5852
    if self.op.on_nodes:
5853
      # _GetWantedNodes can be used here, but is not always appropriate to use
5854
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
5855
      # more information.
5856
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
5857
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
5858

    
5859
  def CheckPrereq(self):
5860
    """Check prerequisites.
5861

5862
    """
5863

    
5864
  def Exec(self, feedback_fn):
5865
    """Do the actual sleep.
5866

5867
    """
5868
    if self.op.on_master:
5869
      if not utils.TestDelay(self.op.duration):
5870
        raise errors.OpExecError("Error during master delay test")
5871
    if self.op.on_nodes:
5872
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
5873
      if not result:
5874
        raise errors.OpExecError("Complete failure from rpc call")
5875
      for node, node_result in result.items():
5876
        node_result.Raise()
5877
        if not node_result.data:
5878
          raise errors.OpExecError("Failure during rpc call to node %s,"
5879
                                   " result: %s" % (node, node_result.data))
5880

    
5881

    
5882
class IAllocator(object):
5883
  """IAllocator framework.
5884

5885
  An IAllocator instance has three sets of attributes:
5886
    - cfg that is needed to query the cluster
5887
    - input data (all members of the _KEYS class attribute are required)
5888
    - four buffer attributes (in|out_data|text), that represent the
5889
      input (to the external script) in text and data structure format,
5890
      and the output from it, again in two formats
5891
    - the result variables from the script (success, info, nodes) for
5892
      easy usage
5893

5894
  """
5895
  _ALLO_KEYS = [
5896
    "mem_size", "disks", "disk_template",
5897
    "os", "tags", "nics", "vcpus", "hypervisor",
5898
    ]
5899
  _RELO_KEYS = [
5900
    "relocate_from",
5901
    ]
5902

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

    
5936
  def _ComputeClusterData(self):
5937
    """Compute the generic allocator input data.
5938

5939
    This is the data that is independent of the actual operation.
5940

5941
    """
5942
    cfg = self.lu.cfg
5943
    cluster_info = cfg.GetClusterInfo()
5944
    # cluster data
5945
    data = {
5946
      "version": 1,
5947
      "cluster_name": cfg.GetClusterName(),
5948
      "cluster_tags": list(cluster_info.GetTags()),
5949
      "enable_hypervisors": list(cluster_info.enabled_hypervisors),
5950
      # we don't have job IDs
5951
      }
5952
    iinfo = cfg.GetAllInstancesInfo().values()
5953
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
5954

    
5955
    # node data
5956
    node_results = {}
5957
    node_list = cfg.GetNodeList()
5958

    
5959
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
5960
      hypervisor_name = self.hypervisor
5961
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
5962
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
5963

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

    
5996
          if iinfo.status == "up":
5997
            i_p_up_mem += beinfo[constants.BE_MEMORY]
5998

    
5999
      # compute memory used by instances
6000
      pnr = {
6001
        "tags": list(ninfo.GetTags()),
6002
        "total_memory": remote_info['memory_total'],
6003
        "reserved_memory": remote_info['memory_dom0'],
6004
        "free_memory": remote_info['memory_free'],
6005
        "i_pri_memory": i_p_mem,
6006
        "i_pri_up_memory": i_p_up_mem,
6007
        "total_disk": remote_info['vg_size'],
6008
        "free_disk": remote_info['vg_free'],
6009
        "primary_ip": ninfo.primary_ip,
6010
        "secondary_ip": ninfo.secondary_ip,
6011
        "total_cpus": remote_info['cpu_total'],
6012
        "offline": ninfo.offline,
6013
        }
6014
      node_results[nname] = pnr
6015
    data["nodes"] = node_results
6016

    
6017
    # instance data
6018
    instance_data = {}
6019
    for iinfo, beinfo in i_list:
6020
      nic_data = [{"mac": n.mac, "ip": n.ip, "bridge": n.bridge}
6021
                  for n in iinfo.nics]
6022
      pir = {
6023
        "tags": list(iinfo.GetTags()),
6024
        "should_run": iinfo.status == "up",
6025
        "vcpus": beinfo[constants.BE_VCPUS],
6026
        "memory": beinfo[constants.BE_MEMORY],
6027
        "os": iinfo.os,
6028
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
6029
        "nics": nic_data,
6030
        "disks": [{"size": dsk.size, "mode": "w"} for dsk in iinfo.disks],
6031
        "disk_template": iinfo.disk_template,
6032
        "hypervisor": iinfo.hypervisor,
6033
        }
6034
      instance_data[iinfo.name] = pir
6035

    
6036
    data["instances"] = instance_data
6037

    
6038
    self.in_data = data
6039

    
6040
  def _AddNewInstance(self):
6041
    """Add new instance data to allocator structure.
6042

6043
    This in combination with _AllocatorGetClusterData will create the
6044
    correct structure needed as input for the allocator.
6045

6046
    The checks for the completeness of the opcode must have already been
6047
    done.
6048

6049
    """
6050
    data = self.in_data
6051
    if len(self.disks) != 2:
6052
      raise errors.OpExecError("Only two-disk configurations supported")
6053

    
6054
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
6055

    
6056
    if self.disk_template in constants.DTS_NET_MIRROR:
6057
      self.required_nodes = 2
6058
    else:
6059
      self.required_nodes = 1
6060
    request = {
6061
      "type": "allocate",
6062
      "name": self.name,
6063
      "disk_template": self.disk_template,
6064
      "tags": self.tags,
6065
      "os": self.os,
6066
      "vcpus": self.vcpus,
6067
      "memory": self.mem_size,
6068
      "disks": self.disks,
6069
      "disk_space_total": disk_space,
6070
      "nics": self.nics,
6071
      "required_nodes": self.required_nodes,
6072
      }
6073
    data["request"] = request
6074

    
6075
  def _AddRelocateInstance(self):
6076
    """Add relocate instance data to allocator structure.
6077

6078
    This in combination with _IAllocatorGetClusterData will create the
6079
    correct structure needed as input for the allocator.
6080

6081
    The checks for the completeness of the opcode must have already been
6082
    done.
6083

6084
    """
6085
    instance = self.lu.cfg.GetInstanceInfo(self.name)
6086
    if instance is None:
6087
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
6088
                                   " IAllocator" % self.name)
6089

    
6090
    if instance.disk_template not in constants.DTS_NET_MIRROR:
6091
      raise errors.OpPrereqError("Can't relocate non-mirrored instances")
6092

    
6093
    if len(instance.secondary_nodes) != 1:
6094
      raise errors.OpPrereqError("Instance has not exactly one secondary node")
6095

    
6096
    self.required_nodes = 1
6097
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
6098
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
6099

    
6100
    request = {
6101
      "type": "relocate",
6102
      "name": self.name,
6103
      "disk_space_total": disk_space,
6104
      "required_nodes": self.required_nodes,
6105
      "relocate_from": self.relocate_from,
6106
      }
6107
    self.in_data["request"] = request
6108

    
6109
  def _BuildInputData(self):
6110
    """Build input data structures.
6111

6112
    """
6113
    self._ComputeClusterData()
6114

    
6115
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6116
      self._AddNewInstance()
6117
    else:
6118
      self._AddRelocateInstance()
6119

    
6120
    self.in_text = serializer.Dump(self.in_data)
6121

    
6122
  def Run(self, name, validate=True, call_fn=None):
6123
    """Run an instance allocator and return the results.
6124

6125
    """
6126
    if call_fn is None:
6127
      call_fn = self.lu.rpc.call_iallocator_runner
6128
    data = self.in_text
6129

    
6130
    result = call_fn(self.lu.cfg.GetMasterNode(), name, self.in_text)
6131
    result.Raise()
6132

    
6133
    if not isinstance(result.data, (list, tuple)) or len(result.data) != 4:
6134
      raise errors.OpExecError("Invalid result from master iallocator runner")
6135

    
6136
    rcode, stdout, stderr, fail = result.data
6137

    
6138
    if rcode == constants.IARUN_NOTFOUND:
6139
      raise errors.OpExecError("Can't find allocator '%s'" % name)
6140
    elif rcode == constants.IARUN_FAILURE:
6141
      raise errors.OpExecError("Instance allocator call failed: %s,"
6142
                               " output: %s" % (fail, stdout+stderr))
6143
    self.out_text = stdout
6144
    if validate:
6145
      self._ValidateResult()
6146

    
6147
  def _ValidateResult(self):
6148
    """Process the allocator results.
6149

6150
    This will process and if successful save the result in
6151
    self.out_data and the other parameters.
6152

6153
    """
6154
    try:
6155
      rdict = serializer.Load(self.out_text)
6156
    except Exception, err:
6157
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
6158

    
6159
    if not isinstance(rdict, dict):
6160
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
6161

    
6162
    for key in "success", "info", "nodes":
6163
      if key not in rdict:
6164
        raise errors.OpExecError("Can't parse iallocator results:"
6165
                                 " missing key '%s'" % key)
6166
      setattr(self, key, rdict[key])
6167

    
6168
    if not isinstance(rdict["nodes"], list):
6169
      raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
6170
                               " is not a list")
6171
    self.out_data = rdict
6172

    
6173

    
6174
class LUTestAllocator(NoHooksLU):
6175
  """Run allocator tests.
6176

6177
  This LU runs the allocator tests
6178

6179
  """
6180
  _OP_REQP = ["direction", "mode", "name"]
6181

    
6182
  def CheckPrereq(self):
6183
    """Check prerequisites.
6184

6185
    This checks the opcode parameters depending on the director and mode test.
6186

6187
    """
6188
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
6189
      for attr in ["name", "mem_size", "disks", "disk_template",
6190
                   "os", "tags", "nics", "vcpus"]:
6191
        if not hasattr(self.op, attr):
6192
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
6193
                                     attr)
6194
      iname = self.cfg.ExpandInstanceName(self.op.name)
6195
      if iname is not None:
6196
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
6197
                                   iname)
6198
      if not isinstance(self.op.nics, list):
6199
        raise errors.OpPrereqError("Invalid parameter 'nics'")
6200
      for row in self.op.nics:
6201
        if (not isinstance(row, dict) or
6202
            "mac" not in row or
6203
            "ip" not in row or
6204
            "bridge" not in row):
6205
          raise errors.OpPrereqError("Invalid contents of the"
6206
                                     " 'nics' parameter")
6207
      if not isinstance(self.op.disks, list):
6208
        raise errors.OpPrereqError("Invalid parameter 'disks'")
6209
      if len(self.op.disks) != 2:
6210
        raise errors.OpPrereqError("Only two-disk configurations supported")
6211
      for row in self.op.disks:
6212
        if (not isinstance(row, dict) or
6213
            "size" not in row or
6214
            not isinstance(row["size"], int) or
6215
            "mode" not in row or
6216
            row["mode"] not in ['r', 'w']):
6217
          raise errors.OpPrereqError("Invalid contents of the"
6218
                                     " 'disks' parameter")
6219
      if self.op.hypervisor is None:
6220
        self.op.hypervisor = self.cfg.GetHypervisorType()
6221
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
6222
      if not hasattr(self.op, "name"):
6223
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input")
6224
      fname = self.cfg.ExpandInstanceName(self.op.name)
6225
      if fname is None:
6226
        raise errors.OpPrereqError("Instance '%s' not found for relocation" %
6227
                                   self.op.name)
6228
      self.op.name = fname
6229
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
6230
    else:
6231
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
6232
                                 self.op.mode)
6233

    
6234
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
6235
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
6236
        raise errors.OpPrereqError("Missing allocator name")
6237
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
6238
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
6239
                                 self.op.direction)
6240

    
6241
  def Exec(self, feedback_fn):
6242
    """Run the allocator test.
6243

6244
    """
6245
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
6246
      ial = IAllocator(self,
6247
                       mode=self.op.mode,
6248
                       name=self.op.name,
6249
                       mem_size=self.op.mem_size,
6250
                       disks=self.op.disks,
6251
                       disk_template=self.op.disk_template,
6252
                       os=self.op.os,
6253
                       tags=self.op.tags,
6254
                       nics=self.op.nics,
6255
                       vcpus=self.op.vcpus,
6256
                       hypervisor=self.op.hypervisor,
6257
                       )
6258
    else:
6259
      ial = IAllocator(self,
6260
                       mode=self.op.mode,
6261
                       name=self.op.name,
6262
                       relocate_from=list(self.relocate_from),
6263
                       )
6264

    
6265
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
6266
      result = ial.in_text
6267
    else:
6268
      ial.Run(self.op.allocator, validate=False)
6269
      result = ial.out_text
6270
    return result