Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ a2d59d8b

History | View | Annotate | Download (218.2 kB)

1
#
2
#
3

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

    
21

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

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

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

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

    
48

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

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

61
  Note that all commands require root permissions.
62

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

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

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

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

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

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

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

    
109
  ssh = property(fget=__GetSSH)
110

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

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

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

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

126
    """
127
    pass
128

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

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

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

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

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

150
    Examples::
151

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

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

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

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

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

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

189
    """
190

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

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

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

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

205
    """
206
    raise NotImplementedError
207

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

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

215
    """
216
    raise NotImplementedError
217

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

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

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

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

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

237
    """
238
    raise NotImplementedError
239

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

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

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

258
    """
259
    return lu_result
260

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
326
    del self.recalculate_locks[locking.LEVEL_NODE]
327

    
328

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

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

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

    
339

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

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

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

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

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

    
366
  return utils.NiceSort(wanted)
367

    
368

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

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

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

    
385
  if instances:
386
    wanted = []
387

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

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

    
398

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

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

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

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

    
417

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

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

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

    
431

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

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

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

    
443

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

448
  This builds the hook environment from individual variables.
449

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

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

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

    
493
  env["INSTANCE_NIC_COUNT"] = nic_count
494

    
495
  return env
496

    
497

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

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

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

    
528

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

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

    
544

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

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

    
558

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

562
  """
563
  _OP_REQP = []
564

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

568
    This checks whether the cluster is empty.
569

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

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

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

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

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

    
598

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

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

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

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

619
    Test list:
620

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

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

634
    """
635
    node = nodeinfo.name
636

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

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

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

    
654
    # checks vg existance and size > 20G
655

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

    
669
    # checks config file checksum
670

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

    
698
    # checks ssh to any
699

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

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

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

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

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

736
    """
737
    bad = False
738

    
739
    node_current = instanceconfig.primary_node
740

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

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

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

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

    
769
    return bad
770

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

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

777
    """
778
    bad = False
779

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

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

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

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

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

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

809
    """
810
    bad = False
811

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

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

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

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

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

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

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

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

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

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

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

    
882
    file_names = ssconf.SimpleStore().GetFileList()
883
    file_names.append(constants.SSL_CERT_FILE)
884
    file_names.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
class LURedistributeConfig(NoHooksLU):
1441
  """Force the redistribution of cluster configuration.
1442

1443
  This is a very simple LU.
1444

1445
  """
1446
  _OP_REQP = []
1447
  REQ_BGL = False
1448

    
1449
  def ExpandNames(self):
1450
    self.needed_locks = {
1451
      locking.LEVEL_NODE: locking.ALL_SET,
1452
    }
1453
    self.share_locks[locking.LEVEL_NODE] = 1
1454

    
1455
  def CheckPrereq(self):
1456
    """Check prerequisites.
1457

1458
    """
1459

    
1460
  def Exec(self, feedback_fn):
1461
    """Redistribute the configuration.
1462

1463
    """
1464
    self.cfg.Update(self.cfg.GetClusterInfo())
1465

    
1466

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

1470
  """
1471
  if not instance.disks:
1472
    return True
1473

    
1474
  if not oneshot:
1475
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
1476

    
1477
  node = instance.primary_node
1478

    
1479
  for dev in instance.disks:
1480
    lu.cfg.SetDiskID(dev, node)
1481

    
1482
  retries = 0
1483
  while True:
1484
    max_time = 0
1485
    done = True
1486
    cumul_degraded = False
1487
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
1488
    if rstats.failed or not rstats.data:
1489
      lu.LogWarning("Can't get any data from node %s", node)
1490
      retries += 1
1491
      if retries >= 10:
1492
        raise errors.RemoteError("Can't contact node %s for mirror data,"
1493
                                 " aborting." % node)
1494
      time.sleep(6)
1495
      continue
1496
    rstats = rstats.data
1497
    retries = 0
1498
    for i in range(len(rstats)):
1499
      mstat = rstats[i]
1500
      if mstat is None:
1501
        lu.LogWarning("Can't compute data for node %s/%s",
1502
                           node, instance.disks[i].iv_name)
1503
        continue
1504
      # we ignore the ldisk parameter
1505
      perc_done, est_time, is_degraded, _ = mstat
1506
      cumul_degraded = cumul_degraded or (is_degraded and perc_done is None)
1507
      if perc_done is not None:
1508
        done = False
1509
        if est_time is not None:
1510
          rem_time = "%d estimated seconds remaining" % est_time
1511
          max_time = est_time
1512
        else:
1513
          rem_time = "no time estimate"
1514
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
1515
                        (instance.disks[i].iv_name, perc_done, rem_time))
1516
    if done or oneshot:
1517
      break
1518

    
1519
    time.sleep(min(60, max_time))
1520

    
1521
  if done:
1522
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
1523
  return not cumul_degraded
1524

    
1525

    
1526
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
1527
  """Check that mirrors are not degraded.
1528

1529
  The ldisk parameter, if True, will change the test from the
1530
  is_degraded attribute (which represents overall non-ok status for
1531
  the device(s)) to the ldisk (representing the local storage status).
1532

1533
  """
1534
  lu.cfg.SetDiskID(dev, node)
1535
  if ldisk:
1536
    idx = 6
1537
  else:
1538
    idx = 5
1539

    
1540
  result = True
1541
  if on_primary or dev.AssembleOnSecondary():
1542
    rstats = lu.rpc.call_blockdev_find(node, dev)
1543
    if rstats.failed or not rstats.data:
1544
      logging.warning("Node %s: disk degraded, not found or node down", node)
1545
      result = False
1546
    else:
1547
      result = result and (not rstats.data[idx])
1548
  if dev.children:
1549
    for child in dev.children:
1550
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
1551

    
1552
  return result
1553

    
1554

    
1555
class LUDiagnoseOS(NoHooksLU):
1556
  """Logical unit for OS diagnose/query.
1557

1558
  """
1559
  _OP_REQP = ["output_fields", "names"]
1560
  REQ_BGL = False
1561
  _FIELDS_STATIC = utils.FieldSet()
1562
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status")
1563

    
1564
  def ExpandNames(self):
1565
    if self.op.names:
1566
      raise errors.OpPrereqError("Selective OS query not supported")
1567

    
1568
    _CheckOutputFields(static=self._FIELDS_STATIC,
1569
                       dynamic=self._FIELDS_DYNAMIC,
1570
                       selected=self.op.output_fields)
1571

    
1572
    # Lock all nodes, in shared mode
1573
    self.needed_locks = {}
1574
    self.share_locks[locking.LEVEL_NODE] = 1
1575
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1576

    
1577
  def CheckPrereq(self):
1578
    """Check prerequisites.
1579

1580
    """
1581

    
1582
  @staticmethod
1583
  def _DiagnoseByOS(node_list, rlist):
1584
    """Remaps a per-node return list into an a per-os per-node dictionary
1585

1586
    @param node_list: a list with the names of all nodes
1587
    @param rlist: a map with node names as keys and OS objects as values
1588

1589
    @rtype: dict
1590
    @returns: a dictionary with osnames as keys and as value another map, with
1591
        nodes as keys and list of OS objects as values, eg::
1592

1593
          {"debian-etch": {"node1": [<object>,...],
1594
                           "node2": [<object>,]}
1595
          }
1596

1597
    """
1598
    all_os = {}
1599
    for node_name, nr in rlist.iteritems():
1600
      if nr.failed or not nr.data:
1601
        continue
1602
      for os_obj in nr.data:
1603
        if os_obj.name not in all_os:
1604
          # build a list of nodes for this os containing empty lists
1605
          # for each node in node_list
1606
          all_os[os_obj.name] = {}
1607
          for nname in node_list:
1608
            all_os[os_obj.name][nname] = []
1609
        all_os[os_obj.name][node_name].append(os_obj)
1610
    return all_os
1611

    
1612
  def Exec(self, feedback_fn):
1613
    """Compute the list of OSes.
1614

1615
    """
1616
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1617
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()
1618
                   if node in node_list]
1619
    node_data = self.rpc.call_os_diagnose(valid_nodes)
1620
    if node_data == False:
1621
      raise errors.OpExecError("Can't gather the list of OSes")
1622
    pol = self._DiagnoseByOS(valid_nodes, node_data)
1623
    output = []
1624
    for os_name, os_data in pol.iteritems():
1625
      row = []
1626
      for field in self.op.output_fields:
1627
        if field == "name":
1628
          val = os_name
1629
        elif field == "valid":
1630
          val = utils.all([osl and osl[0] for osl in os_data.values()])
1631
        elif field == "node_status":
1632
          val = {}
1633
          for node_name, nos_list in os_data.iteritems():
1634
            val[node_name] = [(v.status, v.path) for v in nos_list]
1635
        else:
1636
          raise errors.ParameterError(field)
1637
        row.append(val)
1638
      output.append(row)
1639

    
1640
    return output
1641

    
1642

    
1643
class LURemoveNode(LogicalUnit):
1644
  """Logical unit for removing a node.
1645

1646
  """
1647
  HPATH = "node-remove"
1648
  HTYPE = constants.HTYPE_NODE
1649
  _OP_REQP = ["node_name"]
1650

    
1651
  def BuildHooksEnv(self):
1652
    """Build hooks env.
1653

1654
    This doesn't run on the target node in the pre phase as a failed
1655
    node would then be impossible to remove.
1656

1657
    """
1658
    env = {
1659
      "OP_TARGET": self.op.node_name,
1660
      "NODE_NAME": self.op.node_name,
1661
      }
1662
    all_nodes = self.cfg.GetNodeList()
1663
    all_nodes.remove(self.op.node_name)
1664
    return env, all_nodes, all_nodes
1665

    
1666
  def CheckPrereq(self):
1667
    """Check prerequisites.
1668

1669
    This checks:
1670
     - the node exists in the configuration
1671
     - it does not have primary or secondary instances
1672
     - it's not the master
1673

1674
    Any errors are signalled by raising errors.OpPrereqError.
1675

1676
    """
1677
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
1678
    if node is None:
1679
      raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name)
1680

    
1681
    instance_list = self.cfg.GetInstanceList()
1682

    
1683
    masternode = self.cfg.GetMasterNode()
1684
    if node.name == masternode:
1685
      raise errors.OpPrereqError("Node is the master node,"
1686
                                 " you need to failover first.")
1687

    
1688
    for instance_name in instance_list:
1689
      instance = self.cfg.GetInstanceInfo(instance_name)
1690
      if node.name == instance.primary_node:
1691
        raise errors.OpPrereqError("Instance %s still running on the node,"
1692
                                   " please remove first." % instance_name)
1693
      if node.name in instance.secondary_nodes:
1694
        raise errors.OpPrereqError("Instance %s has node as a secondary,"
1695
                                   " please remove first." % instance_name)
1696
    self.op.node_name = node.name
1697
    self.node = node
1698

    
1699
  def Exec(self, feedback_fn):
1700
    """Removes the node from the cluster.
1701

1702
    """
1703
    node = self.node
1704
    logging.info("Stopping the node daemon and removing configs from node %s",
1705
                 node.name)
1706

    
1707
    self.context.RemoveNode(node.name)
1708

    
1709
    self.rpc.call_node_leave_cluster(node.name)
1710

    
1711
    # Promote nodes to master candidate as needed
1712
    _AdjustCandidatePool(self)
1713

    
1714

    
1715
class LUQueryNodes(NoHooksLU):
1716
  """Logical unit for querying nodes.
1717

1718
  """
1719
  _OP_REQP = ["output_fields", "names"]
1720
  REQ_BGL = False
1721
  _FIELDS_DYNAMIC = utils.FieldSet(
1722
    "dtotal", "dfree",
1723
    "mtotal", "mnode", "mfree",
1724
    "bootid",
1725
    "ctotal",
1726
    )
1727

    
1728
  _FIELDS_STATIC = utils.FieldSet(
1729
    "name", "pinst_cnt", "sinst_cnt",
1730
    "pinst_list", "sinst_list",
1731
    "pip", "sip", "tags",
1732
    "serial_no",
1733
    "master_candidate",
1734
    "master",
1735
    "offline",
1736
    )
1737

    
1738
  def ExpandNames(self):
1739
    _CheckOutputFields(static=self._FIELDS_STATIC,
1740
                       dynamic=self._FIELDS_DYNAMIC,
1741
                       selected=self.op.output_fields)
1742

    
1743
    self.needed_locks = {}
1744
    self.share_locks[locking.LEVEL_NODE] = 1
1745

    
1746
    if self.op.names:
1747
      self.wanted = _GetWantedNodes(self, self.op.names)
1748
    else:
1749
      self.wanted = locking.ALL_SET
1750

    
1751
    self.do_locking = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
1752
    if self.do_locking:
1753
      # if we don't request only static fields, we need to lock the nodes
1754
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
1755

    
1756

    
1757
  def CheckPrereq(self):
1758
    """Check prerequisites.
1759

1760
    """
1761
    # The validation of the node list is done in the _GetWantedNodes,
1762
    # if non empty, and if empty, there's no validation to do
1763
    pass
1764

    
1765
  def Exec(self, feedback_fn):
1766
    """Computes the list of nodes and their attributes.
1767

1768
    """
1769
    all_info = self.cfg.GetAllNodesInfo()
1770
    if self.do_locking:
1771
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
1772
    elif self.wanted != locking.ALL_SET:
1773
      nodenames = self.wanted
1774
      missing = set(nodenames).difference(all_info.keys())
1775
      if missing:
1776
        raise errors.OpExecError(
1777
          "Some nodes were removed before retrieving their data: %s" % missing)
1778
    else:
1779
      nodenames = all_info.keys()
1780

    
1781
    nodenames = utils.NiceSort(nodenames)
1782
    nodelist = [all_info[name] for name in nodenames]
1783

    
1784
    # begin data gathering
1785

    
1786
    if self.do_locking:
1787
      live_data = {}
1788
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
1789
                                          self.cfg.GetHypervisorType())
1790
      for name in nodenames:
1791
        nodeinfo = node_data[name]
1792
        if not nodeinfo.failed and nodeinfo.data:
1793
          nodeinfo = nodeinfo.data
1794
          fn = utils.TryConvert
1795
          live_data[name] = {
1796
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
1797
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
1798
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
1799
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
1800
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
1801
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
1802
            "bootid": nodeinfo.get('bootid', None),
1803
            }
1804
        else:
1805
          live_data[name] = {}
1806
    else:
1807
      live_data = dict.fromkeys(nodenames, {})
1808

    
1809
    node_to_primary = dict([(name, set()) for name in nodenames])
1810
    node_to_secondary = dict([(name, set()) for name in nodenames])
1811

    
1812
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
1813
                             "sinst_cnt", "sinst_list"))
1814
    if inst_fields & frozenset(self.op.output_fields):
1815
      instancelist = self.cfg.GetInstanceList()
1816

    
1817
      for instance_name in instancelist:
1818
        inst = self.cfg.GetInstanceInfo(instance_name)
1819
        if inst.primary_node in node_to_primary:
1820
          node_to_primary[inst.primary_node].add(inst.name)
1821
        for secnode in inst.secondary_nodes:
1822
          if secnode in node_to_secondary:
1823
            node_to_secondary[secnode].add(inst.name)
1824

    
1825
    master_node = self.cfg.GetMasterNode()
1826

    
1827
    # end data gathering
1828

    
1829
    output = []
1830
    for node in nodelist:
1831
      node_output = []
1832
      for field in self.op.output_fields:
1833
        if field == "name":
1834
          val = node.name
1835
        elif field == "pinst_list":
1836
          val = list(node_to_primary[node.name])
1837
        elif field == "sinst_list":
1838
          val = list(node_to_secondary[node.name])
1839
        elif field == "pinst_cnt":
1840
          val = len(node_to_primary[node.name])
1841
        elif field == "sinst_cnt":
1842
          val = len(node_to_secondary[node.name])
1843
        elif field == "pip":
1844
          val = node.primary_ip
1845
        elif field == "sip":
1846
          val = node.secondary_ip
1847
        elif field == "tags":
1848
          val = list(node.GetTags())
1849
        elif field == "serial_no":
1850
          val = node.serial_no
1851
        elif field == "master_candidate":
1852
          val = node.master_candidate
1853
        elif field == "master":
1854
          val = node.name == master_node
1855
        elif field == "offline":
1856
          val = node.offline
1857
        elif self._FIELDS_DYNAMIC.Matches(field):
1858
          val = live_data[node.name].get(field, None)
1859
        else:
1860
          raise errors.ParameterError(field)
1861
        node_output.append(val)
1862
      output.append(node_output)
1863

    
1864
    return output
1865

    
1866

    
1867
class LUQueryNodeVolumes(NoHooksLU):
1868
  """Logical unit for getting volumes on node(s).
1869

1870
  """
1871
  _OP_REQP = ["nodes", "output_fields"]
1872
  REQ_BGL = False
1873
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
1874
  _FIELDS_STATIC = utils.FieldSet("node")
1875

    
1876
  def ExpandNames(self):
1877
    _CheckOutputFields(static=self._FIELDS_STATIC,
1878
                       dynamic=self._FIELDS_DYNAMIC,
1879
                       selected=self.op.output_fields)
1880

    
1881
    self.needed_locks = {}
1882
    self.share_locks[locking.LEVEL_NODE] = 1
1883
    if not self.op.nodes:
1884
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1885
    else:
1886
      self.needed_locks[locking.LEVEL_NODE] = \
1887
        _GetWantedNodes(self, self.op.nodes)
1888

    
1889
  def CheckPrereq(self):
1890
    """Check prerequisites.
1891

1892
    This checks that the fields required are valid output fields.
1893

1894
    """
1895
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
1896

    
1897
  def Exec(self, feedback_fn):
1898
    """Computes the list of nodes and their attributes.
1899

1900
    """
1901
    nodenames = self.nodes
1902
    volumes = self.rpc.call_node_volumes(nodenames)
1903

    
1904
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
1905
             in self.cfg.GetInstanceList()]
1906

    
1907
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
1908

    
1909
    output = []
1910
    for node in nodenames:
1911
      if node not in volumes or volumes[node].failed or not volumes[node].data:
1912
        continue
1913

    
1914
      node_vols = volumes[node].data[:]
1915
      node_vols.sort(key=lambda vol: vol['dev'])
1916

    
1917
      for vol in node_vols:
1918
        node_output = []
1919
        for field in self.op.output_fields:
1920
          if field == "node":
1921
            val = node
1922
          elif field == "phys":
1923
            val = vol['dev']
1924
          elif field == "vg":
1925
            val = vol['vg']
1926
          elif field == "name":
1927
            val = vol['name']
1928
          elif field == "size":
1929
            val = int(float(vol['size']))
1930
          elif field == "instance":
1931
            for inst in ilist:
1932
              if node not in lv_by_node[inst]:
1933
                continue
1934
              if vol['name'] in lv_by_node[inst][node]:
1935
                val = inst.name
1936
                break
1937
            else:
1938
              val = '-'
1939
          else:
1940
            raise errors.ParameterError(field)
1941
          node_output.append(str(val))
1942

    
1943
        output.append(node_output)
1944

    
1945
    return output
1946

    
1947

    
1948
class LUAddNode(LogicalUnit):
1949
  """Logical unit for adding node to the cluster.
1950

1951
  """
1952
  HPATH = "node-add"
1953
  HTYPE = constants.HTYPE_NODE
1954
  _OP_REQP = ["node_name"]
1955

    
1956
  def BuildHooksEnv(self):
1957
    """Build hooks env.
1958

1959
    This will run on all nodes before, and on all nodes + the new node after.
1960

1961
    """
1962
    env = {
1963
      "OP_TARGET": self.op.node_name,
1964
      "NODE_NAME": self.op.node_name,
1965
      "NODE_PIP": self.op.primary_ip,
1966
      "NODE_SIP": self.op.secondary_ip,
1967
      }
1968
    nodes_0 = self.cfg.GetNodeList()
1969
    nodes_1 = nodes_0 + [self.op.node_name, ]
1970
    return env, nodes_0, nodes_1
1971

    
1972
  def CheckPrereq(self):
1973
    """Check prerequisites.
1974

1975
    This checks:
1976
     - the new node is not already in the config
1977
     - it is resolvable
1978
     - its parameters (single/dual homed) matches the cluster
1979

1980
    Any errors are signalled by raising errors.OpPrereqError.
1981

1982
    """
1983
    node_name = self.op.node_name
1984
    cfg = self.cfg
1985

    
1986
    dns_data = utils.HostInfo(node_name)
1987

    
1988
    node = dns_data.name
1989
    primary_ip = self.op.primary_ip = dns_data.ip
1990
    secondary_ip = getattr(self.op, "secondary_ip", None)
1991
    if secondary_ip is None:
1992
      secondary_ip = primary_ip
1993
    if not utils.IsValidIP(secondary_ip):
1994
      raise errors.OpPrereqError("Invalid secondary IP given")
1995
    self.op.secondary_ip = secondary_ip
1996

    
1997
    node_list = cfg.GetNodeList()
1998
    if not self.op.readd and node in node_list:
1999
      raise errors.OpPrereqError("Node %s is already in the configuration" %
2000
                                 node)
2001
    elif self.op.readd and node not in node_list:
2002
      raise errors.OpPrereqError("Node %s is not in the configuration" % node)
2003

    
2004
    for existing_node_name in node_list:
2005
      existing_node = cfg.GetNodeInfo(existing_node_name)
2006

    
2007
      if self.op.readd and node == existing_node_name:
2008
        if (existing_node.primary_ip != primary_ip or
2009
            existing_node.secondary_ip != secondary_ip):
2010
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
2011
                                     " address configuration as before")
2012
        continue
2013

    
2014
      if (existing_node.primary_ip == primary_ip or
2015
          existing_node.secondary_ip == primary_ip or
2016
          existing_node.primary_ip == secondary_ip or
2017
          existing_node.secondary_ip == secondary_ip):
2018
        raise errors.OpPrereqError("New node ip address(es) conflict with"
2019
                                   " existing node %s" % existing_node.name)
2020

    
2021
    # check that the type of the node (single versus dual homed) is the
2022
    # same as for the master
2023
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
2024
    master_singlehomed = myself.secondary_ip == myself.primary_ip
2025
    newbie_singlehomed = secondary_ip == primary_ip
2026
    if master_singlehomed != newbie_singlehomed:
2027
      if master_singlehomed:
2028
        raise errors.OpPrereqError("The master has no private ip but the"
2029
                                   " new node has one")
2030
      else:
2031
        raise errors.OpPrereqError("The master has a private ip but the"
2032
                                   " new node doesn't have one")
2033

    
2034
    # checks reachablity
2035
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
2036
      raise errors.OpPrereqError("Node not reachable by ping")
2037

    
2038
    if not newbie_singlehomed:
2039
      # check reachability from my secondary ip to newbie's secondary ip
2040
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
2041
                           source=myself.secondary_ip):
2042
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
2043
                                   " based ping to noded port")
2044

    
2045
    cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2046
    mc_now, _ = self.cfg.GetMasterCandidateStats()
2047
    master_candidate = mc_now < cp_size
2048

    
2049
    self.new_node = objects.Node(name=node,
2050
                                 primary_ip=primary_ip,
2051
                                 secondary_ip=secondary_ip,
2052
                                 master_candidate=master_candidate,
2053
                                 offline=False)
2054

    
2055
  def Exec(self, feedback_fn):
2056
    """Adds the new node to the cluster.
2057

2058
    """
2059
    new_node = self.new_node
2060
    node = new_node.name
2061

    
2062
    # check connectivity
2063
    result = self.rpc.call_version([node])[node]
2064
    result.Raise()
2065
    if result.data:
2066
      if constants.PROTOCOL_VERSION == result.data:
2067
        logging.info("Communication to node %s fine, sw version %s match",
2068
                     node, result.data)
2069
      else:
2070
        raise errors.OpExecError("Version mismatch master version %s,"
2071
                                 " node version %s" %
2072
                                 (constants.PROTOCOL_VERSION, result.data))
2073
    else:
2074
      raise errors.OpExecError("Cannot get version from the new node")
2075

    
2076
    # setup ssh on node
2077
    logging.info("Copy ssh key to node %s", node)
2078
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
2079
    keyarray = []
2080
    keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
2081
                constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
2082
                priv_key, pub_key]
2083

    
2084
    for i in keyfiles:
2085
      f = open(i, 'r')
2086
      try:
2087
        keyarray.append(f.read())
2088
      finally:
2089
        f.close()
2090

    
2091
    result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
2092
                                    keyarray[2],
2093
                                    keyarray[3], keyarray[4], keyarray[5])
2094

    
2095
    if result.failed or not result.data:
2096
      raise errors.OpExecError("Cannot transfer ssh keys to the new node")
2097

    
2098
    # Add node to our /etc/hosts, and add key to known_hosts
2099
    utils.AddHostToEtcHosts(new_node.name)
2100

    
2101
    if new_node.secondary_ip != new_node.primary_ip:
2102
      result = self.rpc.call_node_has_ip_address(new_node.name,
2103
                                                 new_node.secondary_ip)
2104
      if result.failed or not result.data:
2105
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
2106
                                 " you gave (%s). Please fix and re-run this"
2107
                                 " command." % new_node.secondary_ip)
2108

    
2109
    node_verify_list = [self.cfg.GetMasterNode()]
2110
    node_verify_param = {
2111
      'nodelist': [node],
2112
      # TODO: do a node-net-test as well?
2113
    }
2114

    
2115
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
2116
                                       self.cfg.GetClusterName())
2117
    for verifier in node_verify_list:
2118
      if result[verifier].failed or not result[verifier].data:
2119
        raise errors.OpExecError("Cannot communicate with %s's node daemon"
2120
                                 " for remote verification" % verifier)
2121
      if result[verifier].data['nodelist']:
2122
        for failed in result[verifier].data['nodelist']:
2123
          feedback_fn("ssh/hostname verification failed %s -> %s" %
2124
                      (verifier, result[verifier]['nodelist'][failed]))
2125
        raise errors.OpExecError("ssh/hostname verification failed.")
2126

    
2127
    # Distribute updated /etc/hosts and known_hosts to all nodes,
2128
    # including the node just added
2129
    myself = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
2130
    dist_nodes = self.cfg.GetNodeList()
2131
    if not self.op.readd:
2132
      dist_nodes.append(node)
2133
    if myself.name in dist_nodes:
2134
      dist_nodes.remove(myself.name)
2135

    
2136
    logging.debug("Copying hosts and known_hosts to all nodes")
2137
    for fname in (constants.ETC_HOSTS, constants.SSH_KNOWN_HOSTS_FILE):
2138
      result = self.rpc.call_upload_file(dist_nodes, fname)
2139
      for to_node, to_result in result.iteritems():
2140
        if to_result.failed or not to_result.data:
2141
          logging.error("Copy of file %s to node %s failed", fname, to_node)
2142

    
2143
    to_copy = []
2144
    if constants.HT_XEN_HVM in self.cfg.GetClusterInfo().enabled_hypervisors:
2145
      to_copy.append(constants.VNC_PASSWORD_FILE)
2146
    for fname in to_copy:
2147
      result = self.rpc.call_upload_file([node], fname)
2148
      if result[node].failed or not result[node]:
2149
        logging.error("Could not copy file %s to node %s", fname, node)
2150

    
2151
    if self.op.readd:
2152
      self.context.ReaddNode(new_node)
2153
    else:
2154
      self.context.AddNode(new_node)
2155

    
2156

    
2157
class LUSetNodeParams(LogicalUnit):
2158
  """Modifies the parameters of a node.
2159

2160
  """
2161
  HPATH = "node-modify"
2162
  HTYPE = constants.HTYPE_NODE
2163
  _OP_REQP = ["node_name"]
2164
  REQ_BGL = False
2165

    
2166
  def CheckArguments(self):
2167
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2168
    if node_name is None:
2169
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
2170
    self.op.node_name = node_name
2171
    _CheckBooleanOpField(self.op, 'master_candidate')
2172
    _CheckBooleanOpField(self.op, 'offline')
2173
    if self.op.master_candidate is None and self.op.offline is None:
2174
      raise errors.OpPrereqError("Please pass at least one modification")
2175
    if self.op.offline == True and self.op.master_candidate == True:
2176
      raise errors.OpPrereqError("Can't set the node into offline and"
2177
                                 " master_candidate at the same time")
2178

    
2179
  def ExpandNames(self):
2180
    self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
2181

    
2182
  def BuildHooksEnv(self):
2183
    """Build hooks env.
2184

2185
    This runs on the master node.
2186

2187
    """
2188
    env = {
2189
      "OP_TARGET": self.op.node_name,
2190
      "MASTER_CANDIDATE": str(self.op.master_candidate),
2191
      "OFFLINE": str(self.op.offline),
2192
      }
2193
    nl = [self.cfg.GetMasterNode(),
2194
          self.op.node_name]
2195
    return env, nl, nl
2196

    
2197
  def CheckPrereq(self):
2198
    """Check prerequisites.
2199

2200
    This only checks the instance list against the existing names.
2201

2202
    """
2203
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
2204

    
2205
    if ((self.op.master_candidate == False or self.op.offline == True)
2206
        and node.master_candidate):
2207
      # we will demote the node from master_candidate
2208
      if self.op.node_name == self.cfg.GetMasterNode():
2209
        raise errors.OpPrereqError("The master node has to be a"
2210
                                   " master candidate and online")
2211
      cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2212
      num_candidates, _ = self.cfg.GetMasterCandidateStats()
2213
      if num_candidates <= cp_size:
2214
        msg = ("Not enough master candidates (desired"
2215
               " %d, new value will be %d)" % (cp_size, num_candidates-1))
2216
        if self.op.force:
2217
          self.LogWarning(msg)
2218
        else:
2219
          raise errors.OpPrereqError(msg)
2220

    
2221
    if (self.op.master_candidate == True and node.offline and
2222
        not self.op.offline == False):
2223
      raise errors.OpPrereqError("Can't set an offline node to"
2224
                                 " master_candidate")
2225

    
2226
    return
2227

    
2228
  def Exec(self, feedback_fn):
2229
    """Modifies a node.
2230

2231
    """
2232
    node = self.node
2233

    
2234
    result = []
2235

    
2236
    if self.op.offline is not None:
2237
      node.offline = self.op.offline
2238
      result.append(("offline", str(self.op.offline)))
2239
      if self.op.offline == True and node.master_candidate:
2240
        node.master_candidate = False
2241
        result.append(("master_candidate", "auto-demotion due to offline"))
2242

    
2243
    if self.op.master_candidate is not None:
2244
      node.master_candidate = self.op.master_candidate
2245
      result.append(("master_candidate", str(self.op.master_candidate)))
2246
      if self.op.master_candidate == False:
2247
        rrc = self.rpc.call_node_demote_from_mc(node.name)
2248
        if (rrc.failed or not isinstance(rrc.data, (tuple, list))
2249
            or len(rrc.data) != 2):
2250
          self.LogWarning("Node rpc error: %s" % rrc.error)
2251
        elif not rrc.data[0]:
2252
          self.LogWarning("Node failed to demote itself: %s" % rrc.data[1])
2253

    
2254
    # this will trigger configuration file update, if needed
2255
    self.cfg.Update(node)
2256
    # this will trigger job queue propagation or cleanup
2257
    if self.op.node_name != self.cfg.GetMasterNode():
2258
      self.context.ReaddNode(node)
2259

    
2260
    return result
2261

    
2262

    
2263
class LUQueryClusterInfo(NoHooksLU):
2264
  """Query cluster configuration.
2265

2266
  """
2267
  _OP_REQP = []
2268
  REQ_BGL = False
2269

    
2270
  def ExpandNames(self):
2271
    self.needed_locks = {}
2272

    
2273
  def CheckPrereq(self):
2274
    """No prerequsites needed for this LU.
2275

2276
    """
2277
    pass
2278

    
2279
  def Exec(self, feedback_fn):
2280
    """Return cluster config.
2281

2282
    """
2283
    cluster = self.cfg.GetClusterInfo()
2284
    result = {
2285
      "software_version": constants.RELEASE_VERSION,
2286
      "protocol_version": constants.PROTOCOL_VERSION,
2287
      "config_version": constants.CONFIG_VERSION,
2288
      "os_api_version": constants.OS_API_VERSION,
2289
      "export_version": constants.EXPORT_VERSION,
2290
      "architecture": (platform.architecture()[0], platform.machine()),
2291
      "name": cluster.cluster_name,
2292
      "master": cluster.master_node,
2293
      "default_hypervisor": cluster.default_hypervisor,
2294
      "enabled_hypervisors": cluster.enabled_hypervisors,
2295
      "hvparams": cluster.hvparams,
2296
      "beparams": cluster.beparams,
2297
      "candidate_pool_size": cluster.candidate_pool_size,
2298
      }
2299

    
2300
    return result
2301

    
2302

    
2303
class LUQueryConfigValues(NoHooksLU):
2304
  """Return configuration values.
2305

2306
  """
2307
  _OP_REQP = []
2308
  REQ_BGL = False
2309
  _FIELDS_DYNAMIC = utils.FieldSet()
2310
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag")
2311

    
2312
  def ExpandNames(self):
2313
    self.needed_locks = {}
2314

    
2315
    _CheckOutputFields(static=self._FIELDS_STATIC,
2316
                       dynamic=self._FIELDS_DYNAMIC,
2317
                       selected=self.op.output_fields)
2318

    
2319
  def CheckPrereq(self):
2320
    """No prerequisites.
2321

2322
    """
2323
    pass
2324

    
2325
  def Exec(self, feedback_fn):
2326
    """Dump a representation of the cluster config to the standard output.
2327

2328
    """
2329
    values = []
2330
    for field in self.op.output_fields:
2331
      if field == "cluster_name":
2332
        entry = self.cfg.GetClusterName()
2333
      elif field == "master_node":
2334
        entry = self.cfg.GetMasterNode()
2335
      elif field == "drain_flag":
2336
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
2337
      else:
2338
        raise errors.ParameterError(field)
2339
      values.append(entry)
2340
    return values
2341

    
2342

    
2343
class LUActivateInstanceDisks(NoHooksLU):
2344
  """Bring up an instance's disks.
2345

2346
  """
2347
  _OP_REQP = ["instance_name"]
2348
  REQ_BGL = False
2349

    
2350
  def ExpandNames(self):
2351
    self._ExpandAndLockInstance()
2352
    self.needed_locks[locking.LEVEL_NODE] = []
2353
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2354

    
2355
  def DeclareLocks(self, level):
2356
    if level == locking.LEVEL_NODE:
2357
      self._LockInstancesNodes()
2358

    
2359
  def CheckPrereq(self):
2360
    """Check prerequisites.
2361

2362
    This checks that the instance is in the cluster.
2363

2364
    """
2365
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2366
    assert self.instance is not None, \
2367
      "Cannot retrieve locked instance %s" % self.op.instance_name
2368
    _CheckNodeOnline(self, self.instance.primary_node)
2369

    
2370
  def Exec(self, feedback_fn):
2371
    """Activate the disks.
2372

2373
    """
2374
    disks_ok, disks_info = _AssembleInstanceDisks(self, self.instance)
2375
    if not disks_ok:
2376
      raise errors.OpExecError("Cannot activate block devices")
2377

    
2378
    return disks_info
2379

    
2380

    
2381
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False):
2382
  """Prepare the block devices for an instance.
2383

2384
  This sets up the block devices on all nodes.
2385

2386
  @type lu: L{LogicalUnit}
2387
  @param lu: the logical unit on whose behalf we execute
2388
  @type instance: L{objects.Instance}
2389
  @param instance: the instance for whose disks we assemble
2390
  @type ignore_secondaries: boolean
2391
  @param ignore_secondaries: if true, errors on secondary nodes
2392
      won't result in an error return from the function
2393
  @return: False if the operation failed, otherwise a list of
2394
      (host, instance_visible_name, node_visible_name)
2395
      with the mapping from node devices to instance devices
2396

2397
  """
2398
  device_info = []
2399
  disks_ok = True
2400
  iname = instance.name
2401
  # With the two passes mechanism we try to reduce the window of
2402
  # opportunity for the race condition of switching DRBD to primary
2403
  # before handshaking occured, but we do not eliminate it
2404

    
2405
  # The proper fix would be to wait (with some limits) until the
2406
  # connection has been made and drbd transitions from WFConnection
2407
  # into any other network-connected state (Connected, SyncTarget,
2408
  # SyncSource, etc.)
2409

    
2410
  # 1st pass, assemble on all nodes in secondary mode
2411
  for inst_disk in instance.disks:
2412
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2413
      lu.cfg.SetDiskID(node_disk, node)
2414
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
2415
      if result.failed or not result:
2416
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2417
                           " (is_primary=False, pass=1)",
2418
                           inst_disk.iv_name, node)
2419
        if not ignore_secondaries:
2420
          disks_ok = False
2421

    
2422
  # FIXME: race condition on drbd migration to primary
2423

    
2424
  # 2nd pass, do only the primary node
2425
  for inst_disk in instance.disks:
2426
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2427
      if node != instance.primary_node:
2428
        continue
2429
      lu.cfg.SetDiskID(node_disk, node)
2430
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
2431
      if result.failed or not result:
2432
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2433
                           " (is_primary=True, pass=2)",
2434
                           inst_disk.iv_name, node)
2435
        disks_ok = False
2436
    device_info.append((instance.primary_node, inst_disk.iv_name, result.data))
2437

    
2438
  # leave the disks configured for the primary node
2439
  # this is a workaround that would be fixed better by
2440
  # improving the logical/physical id handling
2441
  for disk in instance.disks:
2442
    lu.cfg.SetDiskID(disk, instance.primary_node)
2443

    
2444
  return disks_ok, device_info
2445

    
2446

    
2447
def _StartInstanceDisks(lu, instance, force):
2448
  """Start the disks of an instance.
2449

2450
  """
2451
  disks_ok, dummy = _AssembleInstanceDisks(lu, instance,
2452
                                           ignore_secondaries=force)
2453
  if not disks_ok:
2454
    _ShutdownInstanceDisks(lu, instance)
2455
    if force is not None and not force:
2456
      lu.proc.LogWarning("", hint="If the message above refers to a"
2457
                         " secondary node,"
2458
                         " you can retry the operation using '--force'.")
2459
    raise errors.OpExecError("Disk consistency error")
2460

    
2461

    
2462
class LUDeactivateInstanceDisks(NoHooksLU):
2463
  """Shutdown an instance's disks.
2464

2465
  """
2466
  _OP_REQP = ["instance_name"]
2467
  REQ_BGL = False
2468

    
2469
  def ExpandNames(self):
2470
    self._ExpandAndLockInstance()
2471
    self.needed_locks[locking.LEVEL_NODE] = []
2472
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2473

    
2474
  def DeclareLocks(self, level):
2475
    if level == locking.LEVEL_NODE:
2476
      self._LockInstancesNodes()
2477

    
2478
  def CheckPrereq(self):
2479
    """Check prerequisites.
2480

2481
    This checks that the instance is in the cluster.
2482

2483
    """
2484
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2485
    assert self.instance is not None, \
2486
      "Cannot retrieve locked instance %s" % self.op.instance_name
2487

    
2488
  def Exec(self, feedback_fn):
2489
    """Deactivate the disks
2490

2491
    """
2492
    instance = self.instance
2493
    _SafeShutdownInstanceDisks(self, instance)
2494

    
2495

    
2496
def _SafeShutdownInstanceDisks(lu, instance):
2497
  """Shutdown block devices of an instance.
2498

2499
  This function checks if an instance is running, before calling
2500
  _ShutdownInstanceDisks.
2501

2502
  """
2503
  ins_l = lu.rpc.call_instance_list([instance.primary_node],
2504
                                      [instance.hypervisor])
2505
  ins_l = ins_l[instance.primary_node]
2506
  if ins_l.failed or not isinstance(ins_l.data, list):
2507
    raise errors.OpExecError("Can't contact node '%s'" %
2508
                             instance.primary_node)
2509

    
2510
  if instance.name in ins_l.data:
2511
    raise errors.OpExecError("Instance is running, can't shutdown"
2512
                             " block devices.")
2513

    
2514
  _ShutdownInstanceDisks(lu, instance)
2515

    
2516

    
2517
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
2518
  """Shutdown block devices of an instance.
2519

2520
  This does the shutdown on all nodes of the instance.
2521

2522
  If the ignore_primary is false, errors on the primary node are
2523
  ignored.
2524

2525
  """
2526
  result = True
2527
  for disk in instance.disks:
2528
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
2529
      lu.cfg.SetDiskID(top_disk, node)
2530
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
2531
      if result.failed or not result.data:
2532
        logging.error("Could not shutdown block device %s on node %s",
2533
                      disk.iv_name, node)
2534
        if not ignore_primary or node != instance.primary_node:
2535
          result = False
2536
  return result
2537

    
2538

    
2539
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
2540
  """Checks if a node has enough free memory.
2541

2542
  This function check if a given node has the needed amount of free
2543
  memory. In case the node has less memory or we cannot get the
2544
  information from the node, this function raise an OpPrereqError
2545
  exception.
2546

2547
  @type lu: C{LogicalUnit}
2548
  @param lu: a logical unit from which we get configuration data
2549
  @type node: C{str}
2550
  @param node: the node to check
2551
  @type reason: C{str}
2552
  @param reason: string to use in the error message
2553
  @type requested: C{int}
2554
  @param requested: the amount of memory in MiB to check for
2555
  @type hypervisor_name: C{str}
2556
  @param hypervisor_name: the hypervisor to ask for memory stats
2557
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
2558
      we cannot check the node
2559

2560
  """
2561
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
2562
  nodeinfo[node].Raise()
2563
  free_mem = nodeinfo[node].data.get('memory_free')
2564
  if not isinstance(free_mem, int):
2565
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
2566
                             " was '%s'" % (node, free_mem))
2567
  if requested > free_mem:
2568
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
2569
                             " needed %s MiB, available %s MiB" %
2570
                             (node, reason, requested, free_mem))
2571

    
2572

    
2573
class LUStartupInstance(LogicalUnit):
2574
  """Starts an instance.
2575

2576
  """
2577
  HPATH = "instance-start"
2578
  HTYPE = constants.HTYPE_INSTANCE
2579
  _OP_REQP = ["instance_name", "force"]
2580
  REQ_BGL = False
2581

    
2582
  def ExpandNames(self):
2583
    self._ExpandAndLockInstance()
2584

    
2585
  def BuildHooksEnv(self):
2586
    """Build hooks env.
2587

2588
    This runs on master, primary and secondary nodes of the instance.
2589

2590
    """
2591
    env = {
2592
      "FORCE": self.op.force,
2593
      }
2594
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2595
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2596
          list(self.instance.secondary_nodes))
2597
    return env, nl, nl
2598

    
2599
  def CheckPrereq(self):
2600
    """Check prerequisites.
2601

2602
    This checks that the instance is in the cluster.
2603

2604
    """
2605
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2606
    assert self.instance is not None, \
2607
      "Cannot retrieve locked instance %s" % self.op.instance_name
2608

    
2609
    _CheckNodeOnline(self, instance.primary_node)
2610

    
2611
    bep = self.cfg.GetClusterInfo().FillBE(instance)
2612
    # check bridges existance
2613
    _CheckInstanceBridgesExist(self, instance)
2614

    
2615
    _CheckNodeFreeMemory(self, instance.primary_node,
2616
                         "starting instance %s" % instance.name,
2617
                         bep[constants.BE_MEMORY], instance.hypervisor)
2618

    
2619
  def Exec(self, feedback_fn):
2620
    """Start the instance.
2621

2622
    """
2623
    instance = self.instance
2624
    force = self.op.force
2625
    extra_args = getattr(self.op, "extra_args", "")
2626

    
2627
    self.cfg.MarkInstanceUp(instance.name)
2628

    
2629
    node_current = instance.primary_node
2630

    
2631
    _StartInstanceDisks(self, instance, force)
2632

    
2633
    result = self.rpc.call_instance_start(node_current, instance, extra_args)
2634
    if result.failed or not result.data:
2635
      _ShutdownInstanceDisks(self, instance)
2636
      raise errors.OpExecError("Could not start instance")
2637

    
2638

    
2639
class LURebootInstance(LogicalUnit):
2640
  """Reboot an instance.
2641

2642
  """
2643
  HPATH = "instance-reboot"
2644
  HTYPE = constants.HTYPE_INSTANCE
2645
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
2646
  REQ_BGL = False
2647

    
2648
  def ExpandNames(self):
2649
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
2650
                                   constants.INSTANCE_REBOOT_HARD,
2651
                                   constants.INSTANCE_REBOOT_FULL]:
2652
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
2653
                                  (constants.INSTANCE_REBOOT_SOFT,
2654
                                   constants.INSTANCE_REBOOT_HARD,
2655
                                   constants.INSTANCE_REBOOT_FULL))
2656
    self._ExpandAndLockInstance()
2657

    
2658
  def BuildHooksEnv(self):
2659
    """Build hooks env.
2660

2661
    This runs on master, primary and secondary nodes of the instance.
2662

2663
    """
2664
    env = {
2665
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
2666
      }
2667
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2668
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2669
          list(self.instance.secondary_nodes))
2670
    return env, nl, nl
2671

    
2672
  def CheckPrereq(self):
2673
    """Check prerequisites.
2674

2675
    This checks that the instance is in the cluster.
2676

2677
    """
2678
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2679
    assert self.instance is not None, \
2680
      "Cannot retrieve locked instance %s" % self.op.instance_name
2681

    
2682
    _CheckNodeOnline(self, instance.primary_node)
2683

    
2684
    # check bridges existance
2685
    _CheckInstanceBridgesExist(self, instance)
2686

    
2687
  def Exec(self, feedback_fn):
2688
    """Reboot the instance.
2689

2690
    """
2691
    instance = self.instance
2692
    ignore_secondaries = self.op.ignore_secondaries
2693
    reboot_type = self.op.reboot_type
2694
    extra_args = getattr(self.op, "extra_args", "")
2695

    
2696
    node_current = instance.primary_node
2697

    
2698
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
2699
                       constants.INSTANCE_REBOOT_HARD]:
2700
      result = self.rpc.call_instance_reboot(node_current, instance,
2701
                                             reboot_type, extra_args)
2702
      if result.failed or not result.data:
2703
        raise errors.OpExecError("Could not reboot instance")
2704
    else:
2705
      if not self.rpc.call_instance_shutdown(node_current, instance):
2706
        raise errors.OpExecError("could not shutdown instance for full reboot")
2707
      _ShutdownInstanceDisks(self, instance)
2708
      _StartInstanceDisks(self, instance, ignore_secondaries)
2709
      result = self.rpc.call_instance_start(node_current, instance, extra_args)
2710
      if result.failed or not result.data:
2711
        _ShutdownInstanceDisks(self, instance)
2712
        raise errors.OpExecError("Could not start instance for full reboot")
2713

    
2714
    self.cfg.MarkInstanceUp(instance.name)
2715

    
2716

    
2717
class LUShutdownInstance(LogicalUnit):
2718
  """Shutdown an instance.
2719

2720
  """
2721
  HPATH = "instance-stop"
2722
  HTYPE = constants.HTYPE_INSTANCE
2723
  _OP_REQP = ["instance_name"]
2724
  REQ_BGL = False
2725

    
2726
  def ExpandNames(self):
2727
    self._ExpandAndLockInstance()
2728

    
2729
  def BuildHooksEnv(self):
2730
    """Build hooks env.
2731

2732
    This runs on master, primary and secondary nodes of the instance.
2733

2734
    """
2735
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2736
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2737
          list(self.instance.secondary_nodes))
2738
    return env, nl, nl
2739

    
2740
  def CheckPrereq(self):
2741
    """Check prerequisites.
2742

2743
    This checks that the instance is in the cluster.
2744

2745
    """
2746
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2747
    assert self.instance is not None, \
2748
      "Cannot retrieve locked instance %s" % self.op.instance_name
2749
    _CheckNodeOnline(self, self.instance.primary_node)
2750

    
2751
  def Exec(self, feedback_fn):
2752
    """Shutdown the instance.
2753

2754
    """
2755
    instance = self.instance
2756
    node_current = instance.primary_node
2757
    self.cfg.MarkInstanceDown(instance.name)
2758
    result = self.rpc.call_instance_shutdown(node_current, instance)
2759
    if result.failed or not result.data:
2760
      self.proc.LogWarning("Could not shutdown instance")
2761

    
2762
    _ShutdownInstanceDisks(self, instance)
2763

    
2764

    
2765
class LUReinstallInstance(LogicalUnit):
2766
  """Reinstall an instance.
2767

2768
  """
2769
  HPATH = "instance-reinstall"
2770
  HTYPE = constants.HTYPE_INSTANCE
2771
  _OP_REQP = ["instance_name"]
2772
  REQ_BGL = False
2773

    
2774
  def ExpandNames(self):
2775
    self._ExpandAndLockInstance()
2776

    
2777
  def BuildHooksEnv(self):
2778
    """Build hooks env.
2779

2780
    This runs on master, primary and secondary nodes of the instance.
2781

2782
    """
2783
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2784
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2785
          list(self.instance.secondary_nodes))
2786
    return env, nl, nl
2787

    
2788
  def CheckPrereq(self):
2789
    """Check prerequisites.
2790

2791
    This checks that the instance is in the cluster and is not running.
2792

2793
    """
2794
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2795
    assert instance is not None, \
2796
      "Cannot retrieve locked instance %s" % self.op.instance_name
2797
    _CheckNodeOnline(self, instance.primary_node)
2798

    
2799
    if instance.disk_template == constants.DT_DISKLESS:
2800
      raise errors.OpPrereqError("Instance '%s' has no disks" %
2801
                                 self.op.instance_name)
2802
    if instance.status != "down":
2803
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2804
                                 self.op.instance_name)
2805
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2806
                                              instance.name,
2807
                                              instance.hypervisor)
2808
    if remote_info.failed or remote_info.data:
2809
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2810
                                 (self.op.instance_name,
2811
                                  instance.primary_node))
2812

    
2813
    self.op.os_type = getattr(self.op, "os_type", None)
2814
    if self.op.os_type is not None:
2815
      # OS verification
2816
      pnode = self.cfg.GetNodeInfo(
2817
        self.cfg.ExpandNodeName(instance.primary_node))
2818
      if pnode is None:
2819
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
2820
                                   self.op.pnode)
2821
      result = self.rpc.call_os_get(pnode.name, self.op.os_type)
2822
      result.Raise()
2823
      if not isinstance(result.data, objects.OS):
2824
        raise errors.OpPrereqError("OS '%s' not in supported OS list for"
2825
                                   " primary node"  % self.op.os_type)
2826

    
2827
    self.instance = instance
2828

    
2829
  def Exec(self, feedback_fn):
2830
    """Reinstall the instance.
2831

2832
    """
2833
    inst = self.instance
2834

    
2835
    if self.op.os_type is not None:
2836
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
2837
      inst.os = self.op.os_type
2838
      self.cfg.Update(inst)
2839

    
2840
    _StartInstanceDisks(self, inst, None)
2841
    try:
2842
      feedback_fn("Running the instance OS create scripts...")
2843
      result = self.rpc.call_instance_os_add(inst.primary_node, inst)
2844
      result.Raise()
2845
      if not result.data:
2846
        raise errors.OpExecError("Could not install OS for instance %s"
2847
                                 " on node %s" %
2848
                                 (inst.name, inst.primary_node))
2849
    finally:
2850
      _ShutdownInstanceDisks(self, inst)
2851

    
2852

    
2853
class LURenameInstance(LogicalUnit):
2854
  """Rename an instance.
2855

2856
  """
2857
  HPATH = "instance-rename"
2858
  HTYPE = constants.HTYPE_INSTANCE
2859
  _OP_REQP = ["instance_name", "new_name"]
2860

    
2861
  def BuildHooksEnv(self):
2862
    """Build hooks env.
2863

2864
    This runs on master, primary and secondary nodes of the instance.
2865

2866
    """
2867
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2868
    env["INSTANCE_NEW_NAME"] = self.op.new_name
2869
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2870
          list(self.instance.secondary_nodes))
2871
    return env, nl, nl
2872

    
2873
  def CheckPrereq(self):
2874
    """Check prerequisites.
2875

2876
    This checks that the instance is in the cluster and is not running.
2877

2878
    """
2879
    instance = self.cfg.GetInstanceInfo(
2880
      self.cfg.ExpandInstanceName(self.op.instance_name))
2881
    if instance is None:
2882
      raise errors.OpPrereqError("Instance '%s' not known" %
2883
                                 self.op.instance_name)
2884
    _CheckNodeOnline(self, instance.primary_node)
2885

    
2886
    if instance.status != "down":
2887
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2888
                                 self.op.instance_name)
2889
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2890
                                              instance.name,
2891
                                              instance.hypervisor)
2892
    remote_info.Raise()
2893
    if remote_info.data:
2894
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2895
                                 (self.op.instance_name,
2896
                                  instance.primary_node))
2897
    self.instance = instance
2898

    
2899
    # new name verification
2900
    name_info = utils.HostInfo(self.op.new_name)
2901

    
2902
    self.op.new_name = new_name = name_info.name
2903
    instance_list = self.cfg.GetInstanceList()
2904
    if new_name in instance_list:
2905
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
2906
                                 new_name)
2907

    
2908
    if not getattr(self.op, "ignore_ip", False):
2909
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
2910
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
2911
                                   (name_info.ip, new_name))
2912

    
2913

    
2914
  def Exec(self, feedback_fn):
2915
    """Reinstall the instance.
2916

2917
    """
2918
    inst = self.instance
2919
    old_name = inst.name
2920

    
2921
    if inst.disk_template == constants.DT_FILE:
2922
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2923

    
2924
    self.cfg.RenameInstance(inst.name, self.op.new_name)
2925
    # Change the instance lock. This is definitely safe while we hold the BGL
2926
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
2927
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
2928

    
2929
    # re-read the instance from the configuration after rename
2930
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
2931

    
2932
    if inst.disk_template == constants.DT_FILE:
2933
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2934
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
2935
                                                     old_file_storage_dir,
2936
                                                     new_file_storage_dir)
2937
      result.Raise()
2938
      if not result.data:
2939
        raise errors.OpExecError("Could not connect to node '%s' to rename"
2940
                                 " directory '%s' to '%s' (but the instance"
2941
                                 " has been renamed in Ganeti)" % (
2942
                                 inst.primary_node, old_file_storage_dir,
2943
                                 new_file_storage_dir))
2944

    
2945
      if not result.data[0]:
2946
        raise errors.OpExecError("Could not rename directory '%s' to '%s'"
2947
                                 " (but the instance has been renamed in"
2948
                                 " Ganeti)" % (old_file_storage_dir,
2949
                                               new_file_storage_dir))
2950

    
2951
    _StartInstanceDisks(self, inst, None)
2952
    try:
2953
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
2954
                                                 old_name)
2955
      if result.failed or not result.data:
2956
        msg = ("Could not run OS rename script for instance %s on node %s"
2957
               " (but the instance has been renamed in Ganeti)" %
2958
               (inst.name, inst.primary_node))
2959
        self.proc.LogWarning(msg)
2960
    finally:
2961
      _ShutdownInstanceDisks(self, inst)
2962

    
2963

    
2964
class LURemoveInstance(LogicalUnit):
2965
  """Remove an instance.
2966

2967
  """
2968
  HPATH = "instance-remove"
2969
  HTYPE = constants.HTYPE_INSTANCE
2970
  _OP_REQP = ["instance_name", "ignore_failures"]
2971
  REQ_BGL = False
2972

    
2973
  def ExpandNames(self):
2974
    self._ExpandAndLockInstance()
2975
    self.needed_locks[locking.LEVEL_NODE] = []
2976
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2977

    
2978
  def DeclareLocks(self, level):
2979
    if level == locking.LEVEL_NODE:
2980
      self._LockInstancesNodes()
2981

    
2982
  def BuildHooksEnv(self):
2983
    """Build hooks env.
2984

2985
    This runs on master, primary and secondary nodes of the instance.
2986

2987
    """
2988
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2989
    nl = [self.cfg.GetMasterNode()]
2990
    return env, nl, nl
2991

    
2992
  def CheckPrereq(self):
2993
    """Check prerequisites.
2994

2995
    This checks that the instance is in the cluster.
2996

2997
    """
2998
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2999
    assert self.instance is not None, \
3000
      "Cannot retrieve locked instance %s" % self.op.instance_name
3001

    
3002
  def Exec(self, feedback_fn):
3003
    """Remove the instance.
3004

3005
    """
3006
    instance = self.instance
3007
    logging.info("Shutting down instance %s on node %s",
3008
                 instance.name, instance.primary_node)
3009

    
3010
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance)
3011
    if result.failed or not result.data:
3012
      if self.op.ignore_failures:
3013
        feedback_fn("Warning: can't shutdown instance")
3014
      else:
3015
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
3016
                                 (instance.name, instance.primary_node))
3017

    
3018
    logging.info("Removing block devices for instance %s", instance.name)
3019

    
3020
    if not _RemoveDisks(self, instance):
3021
      if self.op.ignore_failures:
3022
        feedback_fn("Warning: can't remove instance's disks")
3023
      else:
3024
        raise errors.OpExecError("Can't remove instance's disks")
3025

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

    
3028
    self.cfg.RemoveInstance(instance.name)
3029
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
3030

    
3031

    
3032
class LUQueryInstances(NoHooksLU):
3033
  """Logical unit for querying instances.
3034

3035
  """
3036
  _OP_REQP = ["output_fields", "names"]
3037
  REQ_BGL = False
3038
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
3039
                                    "admin_state", "admin_ram",
3040
                                    "disk_template", "ip", "mac", "bridge",
3041
                                    "sda_size", "sdb_size", "vcpus", "tags",
3042
                                    "network_port", "beparams",
3043
                                    "(disk).(size)/([0-9]+)",
3044
                                    "(disk).(sizes)",
3045
                                    "(nic).(mac|ip|bridge)/([0-9]+)",
3046
                                    "(nic).(macs|ips|bridges)",
3047
                                    "(disk|nic).(count)",
3048
                                    "serial_no", "hypervisor", "hvparams",] +
3049
                                  ["hv/%s" % name
3050
                                   for name in constants.HVS_PARAMETERS] +
3051
                                  ["be/%s" % name
3052
                                   for name in constants.BES_PARAMETERS])
3053
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
3054

    
3055

    
3056
  def ExpandNames(self):
3057
    _CheckOutputFields(static=self._FIELDS_STATIC,
3058
                       dynamic=self._FIELDS_DYNAMIC,
3059
                       selected=self.op.output_fields)
3060

    
3061
    self.needed_locks = {}
3062
    self.share_locks[locking.LEVEL_INSTANCE] = 1
3063
    self.share_locks[locking.LEVEL_NODE] = 1
3064

    
3065
    if self.op.names:
3066
      self.wanted = _GetWantedInstances(self, self.op.names)
3067
    else:
3068
      self.wanted = locking.ALL_SET
3069

    
3070
    self.do_locking = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3071
    if self.do_locking:
3072
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
3073
      self.needed_locks[locking.LEVEL_NODE] = []
3074
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3075

    
3076
  def DeclareLocks(self, level):
3077
    if level == locking.LEVEL_NODE and self.do_locking:
3078
      self._LockInstancesNodes()
3079

    
3080
  def CheckPrereq(self):
3081
    """Check prerequisites.
3082

3083
    """
3084
    pass
3085

    
3086
  def Exec(self, feedback_fn):
3087
    """Computes the list of nodes and their attributes.
3088

3089
    """
3090
    all_info = self.cfg.GetAllInstancesInfo()
3091
    if self.do_locking:
3092
      instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
3093
    elif self.wanted != locking.ALL_SET:
3094
      instance_names = self.wanted
3095
      missing = set(instance_names).difference(all_info.keys())
3096
      if missing:
3097
        raise errors.OpExecError(
3098
          "Some instances were removed before retrieving their data: %s"
3099
          % missing)
3100
    else:
3101
      instance_names = all_info.keys()
3102

    
3103
    instance_names = utils.NiceSort(instance_names)
3104
    instance_list = [all_info[iname] for iname in instance_names]
3105

    
3106
    # begin data gathering
3107

    
3108
    nodes = frozenset([inst.primary_node for inst in instance_list])
3109
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
3110

    
3111
    bad_nodes = []
3112
    off_nodes = []
3113
    if self.do_locking:
3114
      live_data = {}
3115
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
3116
      for name in nodes:
3117
        result = node_data[name]
3118
        if result.offline:
3119
          # offline nodes will be in both lists
3120
          off_nodes.append(name)
3121
        if result.failed:
3122
          bad_nodes.append(name)
3123
        else:
3124
          if result.data:
3125
            live_data.update(result.data)
3126
            # else no instance is alive
3127
    else:
3128
      live_data = dict([(name, {}) for name in instance_names])
3129

    
3130
    # end data gathering
3131

    
3132
    HVPREFIX = "hv/"
3133
    BEPREFIX = "be/"
3134
    output = []
3135
    for instance in instance_list:
3136
      iout = []
3137
      i_hv = self.cfg.GetClusterInfo().FillHV(instance)
3138
      i_be = self.cfg.GetClusterInfo().FillBE(instance)
3139
      for field in self.op.output_fields:
3140
        st_match = self._FIELDS_STATIC.Matches(field)
3141
        if field == "name":
3142
          val = instance.name
3143
        elif field == "os":
3144
          val = instance.os
3145
        elif field == "pnode":
3146
          val = instance.primary_node
3147
        elif field == "snodes":
3148
          val = list(instance.secondary_nodes)
3149
        elif field == "admin_state":
3150
          val = (instance.status != "down")
3151
        elif field == "oper_state":
3152
          if instance.primary_node in bad_nodes:
3153
            val = None
3154
          else:
3155
            val = bool(live_data.get(instance.name))
3156
        elif field == "status":
3157
          if instance.primary_node in off_nodes:
3158
            val = "ERROR_nodeoffline"
3159
          elif instance.primary_node in bad_nodes:
3160
            val = "ERROR_nodedown"
3161
          else:
3162
            running = bool(live_data.get(instance.name))
3163
            if running:
3164
              if instance.status != "down":
3165
                val = "running"
3166
              else:
3167
                val = "ERROR_up"
3168
            else:
3169
              if instance.status != "down":
3170
                val = "ERROR_down"
3171
              else:
3172
                val = "ADMIN_down"
3173
        elif field == "oper_ram":
3174
          if instance.primary_node in bad_nodes:
3175
            val = None
3176
          elif instance.name in live_data:
3177
            val = live_data[instance.name].get("memory", "?")
3178
          else:
3179
            val = "-"
3180
        elif field == "disk_template":
3181
          val = instance.disk_template
3182
        elif field == "ip":
3183
          val = instance.nics[0].ip
3184
        elif field == "bridge":
3185
          val = instance.nics[0].bridge
3186
        elif field == "mac":
3187
          val = instance.nics[0].mac
3188
        elif field == "sda_size" or field == "sdb_size":
3189
          idx = ord(field[2]) - ord('a')
3190
          try:
3191
            val = instance.FindDisk(idx).size
3192
          except errors.OpPrereqError:
3193
            val = None
3194
        elif field == "tags":
3195
          val = list(instance.GetTags())
3196
        elif field == "serial_no":
3197
          val = instance.serial_no
3198
        elif field == "network_port":
3199
          val = instance.network_port
3200
        elif field == "hypervisor":
3201
          val = instance.hypervisor
3202
        elif field == "hvparams":
3203
          val = i_hv
3204
        elif (field.startswith(HVPREFIX) and
3205
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS):
3206
          val = i_hv.get(field[len(HVPREFIX):], None)
3207
        elif field == "beparams":
3208
          val = i_be
3209
        elif (field.startswith(BEPREFIX) and
3210
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
3211
          val = i_be.get(field[len(BEPREFIX):], None)
3212
        elif st_match and st_match.groups():
3213
          # matches a variable list
3214
          st_groups = st_match.groups()
3215
          if st_groups and st_groups[0] == "disk":
3216
            if st_groups[1] == "count":
3217
              val = len(instance.disks)
3218
            elif st_groups[1] == "sizes":
3219
              val = [disk.size for disk in instance.disks]
3220
            elif st_groups[1] == "size":
3221
              try:
3222
                val = instance.FindDisk(st_groups[2]).size
3223
              except errors.OpPrereqError:
3224
                val = None
3225
            else:
3226
              assert False, "Unhandled disk parameter"
3227
          elif st_groups[0] == "nic":
3228
            if st_groups[1] == "count":
3229
              val = len(instance.nics)
3230
            elif st_groups[1] == "macs":
3231
              val = [nic.mac for nic in instance.nics]
3232
            elif st_groups[1] == "ips":
3233
              val = [nic.ip for nic in instance.nics]
3234
            elif st_groups[1] == "bridges":
3235
              val = [nic.bridge for nic in instance.nics]
3236
            else:
3237
              # index-based item
3238
              nic_idx = int(st_groups[2])
3239
              if nic_idx >= len(instance.nics):
3240
                val = None
3241
              else:
3242
                if st_groups[1] == "mac":
3243
                  val = instance.nics[nic_idx].mac
3244
                elif st_groups[1] == "ip":
3245
                  val = instance.nics[nic_idx].ip
3246
                elif st_groups[1] == "bridge":
3247
                  val = instance.nics[nic_idx].bridge
3248
                else:
3249
                  assert False, "Unhandled NIC parameter"
3250
          else:
3251
            assert False, "Unhandled variable parameter"
3252
        else:
3253
          raise errors.ParameterError(field)
3254
        iout.append(val)
3255
      output.append(iout)
3256

    
3257
    return output
3258

    
3259

    
3260
class LUFailoverInstance(LogicalUnit):
3261
  """Failover an instance.
3262

3263
  """
3264
  HPATH = "instance-failover"
3265
  HTYPE = constants.HTYPE_INSTANCE
3266
  _OP_REQP = ["instance_name", "ignore_consistency"]
3267
  REQ_BGL = False
3268

    
3269
  def ExpandNames(self):
3270
    self._ExpandAndLockInstance()
3271
    self.needed_locks[locking.LEVEL_NODE] = []
3272
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3273

    
3274
  def DeclareLocks(self, level):
3275
    if level == locking.LEVEL_NODE:
3276
      self._LockInstancesNodes()
3277

    
3278
  def BuildHooksEnv(self):
3279
    """Build hooks env.
3280

3281
    This runs on master, primary and secondary nodes of the instance.
3282

3283
    """
3284
    env = {
3285
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
3286
      }
3287
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3288
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
3289
    return env, nl, nl
3290

    
3291
  def CheckPrereq(self):
3292
    """Check prerequisites.
3293

3294
    This checks that the instance is in the cluster.
3295

3296
    """
3297
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3298
    assert self.instance is not None, \
3299
      "Cannot retrieve locked instance %s" % self.op.instance_name
3300

    
3301
    bep = self.cfg.GetClusterInfo().FillBE(instance)
3302
    if instance.disk_template not in constants.DTS_NET_MIRROR:
3303
      raise errors.OpPrereqError("Instance's disk layout is not"
3304
                                 " network mirrored, cannot failover.")
3305

    
3306
    secondary_nodes = instance.secondary_nodes
3307
    if not secondary_nodes:
3308
      raise errors.ProgrammerError("no secondary node but using "
3309
                                   "a mirrored disk template")
3310

    
3311
    target_node = secondary_nodes[0]
3312
    _CheckNodeOnline(self, target_node)
3313
    # check memory requirements on the secondary node
3314
    _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
3315
                         instance.name, bep[constants.BE_MEMORY],
3316
                         instance.hypervisor)
3317

    
3318
    # check bridge existance
3319
    brlist = [nic.bridge for nic in instance.nics]
3320
    result = self.rpc.call_bridges_exist(target_node, brlist)
3321
    result.Raise()
3322
    if not result.data:
3323
      raise errors.OpPrereqError("One or more target bridges %s does not"
3324
                                 " exist on destination node '%s'" %
3325
                                 (brlist, target_node))
3326

    
3327
  def Exec(self, feedback_fn):
3328
    """Failover an instance.
3329

3330
    The failover is done by shutting it down on its present node and
3331
    starting it on the secondary.
3332

3333
    """
3334
    instance = self.instance
3335

    
3336
    source_node = instance.primary_node
3337
    target_node = instance.secondary_nodes[0]
3338

    
3339
    feedback_fn("* checking disk consistency between source and target")
3340
    for dev in instance.disks:
3341
      # for drbd, these are drbd over lvm
3342
      if not _CheckDiskConsistency(self, dev, target_node, False):
3343
        if instance.status == "up" and not self.op.ignore_consistency:
3344
          raise errors.OpExecError("Disk %s is degraded on target node,"
3345
                                   " aborting failover." % dev.iv_name)
3346

    
3347
    feedback_fn("* shutting down instance on source node")
3348
    logging.info("Shutting down instance %s on node %s",
3349
                 instance.name, source_node)
3350

    
3351
    result = self.rpc.call_instance_shutdown(source_node, instance)
3352
    if result.failed or not result.data:
3353
      if self.op.ignore_consistency:
3354
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
3355
                             " Proceeding"
3356
                             " anyway. Please make sure node %s is down",
3357
                             instance.name, source_node, source_node)
3358
      else:
3359
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
3360
                                 (instance.name, source_node))
3361

    
3362
    feedback_fn("* deactivating the instance's disks on source node")
3363
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
3364
      raise errors.OpExecError("Can't shut down the instance's disks.")
3365

    
3366
    instance.primary_node = target_node
3367
    # distribute new instance config to the other nodes
3368
    self.cfg.Update(instance)
3369

    
3370
    # Only start the instance if it's marked as up
3371
    if instance.status == "up":
3372
      feedback_fn("* activating the instance's disks on target node")
3373
      logging.info("Starting instance %s on node %s",
3374
                   instance.name, target_node)
3375

    
3376
      disks_ok, dummy = _AssembleInstanceDisks(self, instance,
3377
                                               ignore_secondaries=True)
3378
      if not disks_ok:
3379
        _ShutdownInstanceDisks(self, instance)
3380
        raise errors.OpExecError("Can't activate the instance's disks")
3381

    
3382
      feedback_fn("* starting the instance on the target node")
3383
      result = self.rpc.call_instance_start(target_node, instance, None)
3384
      if result.failed or not result.data:
3385
        _ShutdownInstanceDisks(self, instance)
3386
        raise errors.OpExecError("Could not start instance %s on node %s." %
3387
                                 (instance.name, target_node))
3388

    
3389

    
3390
def _CreateBlockDevOnPrimary(lu, node, instance, device, info):
3391
  """Create a tree of block devices on the primary node.
3392

3393
  This always creates all devices.
3394

3395
  """
3396
  if device.children:
3397
    for child in device.children:
3398
      if not _CreateBlockDevOnPrimary(lu, node, instance, child, info):
3399
        return False
3400

    
3401
  lu.cfg.SetDiskID(device, node)
3402
  new_id = lu.rpc.call_blockdev_create(node, device, device.size,
3403
                                       instance.name, True, 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 _CreateBlockDevOnSecondary(lu, node, instance, device, force, info):
3412
  """Create a tree of block devices on a secondary node.
3413

3414
  If this device type has to be created on secondaries, create it and
3415
  all its children.
3416

3417
  If not, just recurse to children keeping the same 'force' value.
3418

3419
  """
3420
  if device.CreateOnSecondary():
3421
    force = True
3422
  if device.children:
3423
    for child in device.children:
3424
      if not _CreateBlockDevOnSecondary(lu, node, instance,
3425
                                        child, force, info):
3426
        return False
3427

    
3428
  if not force:
3429
    return True
3430
  lu.cfg.SetDiskID(device, node)
3431
  new_id = lu.rpc.call_blockdev_create(node, device, device.size,
3432
                                       instance.name, False, info)
3433
  if new_id.failed or not new_id.data:
3434
    return False
3435
  if device.physical_id is None:
3436
    device.physical_id = new_id
3437
  return True
3438

    
3439

    
3440
def _GenerateUniqueNames(lu, exts):
3441
  """Generate a suitable LV name.
3442

3443
  This will generate a logical volume name for the given instance.
3444

3445
  """
3446
  results = []
3447
  for val in exts:
3448
    new_id = lu.cfg.GenerateUniqueID()
3449
    results.append("%s%s" % (new_id, val))
3450
  return results
3451

    
3452

    
3453
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
3454
                         p_minor, s_minor):
3455
  """Generate a drbd8 device complete with its children.
3456

3457
  """
3458
  port = lu.cfg.AllocatePort()
3459
  vgname = lu.cfg.GetVGName()
3460
  shared_secret = lu.cfg.GenerateDRBDSecret()
3461
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
3462
                          logical_id=(vgname, names[0]))
3463
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
3464
                          logical_id=(vgname, names[1]))
3465
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
3466
                          logical_id=(primary, secondary, port,
3467
                                      p_minor, s_minor,
3468
                                      shared_secret),
3469
                          children=[dev_data, dev_meta],
3470
                          iv_name=iv_name)
3471
  return drbd_dev
3472

    
3473

    
3474
def _GenerateDiskTemplate(lu, template_name,
3475
                          instance_name, primary_node,
3476
                          secondary_nodes, disk_info,
3477
                          file_storage_dir, file_driver,
3478
                          base_index):
3479
  """Generate the entire disk layout for a given template type.
3480

3481
  """
3482
  #TODO: compute space requirements
3483

    
3484
  vgname = lu.cfg.GetVGName()
3485
  disk_count = len(disk_info)
3486
  disks = []
3487
  if template_name == constants.DT_DISKLESS:
3488
    pass
3489
  elif template_name == constants.DT_PLAIN:
3490
    if len(secondary_nodes) != 0:
3491
      raise errors.ProgrammerError("Wrong template configuration")
3492

    
3493
    names = _GenerateUniqueNames(lu, [".disk%d" % i
3494
                                      for i in range(disk_count)])
3495
    for idx, disk in enumerate(disk_info):
3496
      disk_index = idx + base_index
3497
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
3498
                              logical_id=(vgname, names[idx]),
3499
                              iv_name="disk/%d" % disk_index)
3500
      disks.append(disk_dev)
3501
  elif template_name == constants.DT_DRBD8:
3502
    if len(secondary_nodes) != 1:
3503
      raise errors.ProgrammerError("Wrong template configuration")
3504
    remote_node = secondary_nodes[0]
3505
    minors = lu.cfg.AllocateDRBDMinor(
3506
      [primary_node, remote_node] * len(disk_info), instance_name)
3507

    
3508
    names = _GenerateUniqueNames(lu,
3509
                                 [".disk%d_%s" % (i, s)
3510
                                  for i in range(disk_count)
3511
                                  for s in ("data", "meta")
3512
                                  ])
3513
    for idx, disk in enumerate(disk_info):
3514
      disk_index = idx + base_index
3515
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
3516
                                      disk["size"], names[idx*2:idx*2+2],
3517
                                      "disk/%d" % disk_index,
3518
                                      minors[idx*2], minors[idx*2+1])
3519
      disks.append(disk_dev)
3520
  elif template_name == constants.DT_FILE:
3521
    if len(secondary_nodes) != 0:
3522
      raise errors.ProgrammerError("Wrong template configuration")
3523

    
3524
    for idx, disk in enumerate(disk_info):
3525
      disk_index = idx + base_index
3526
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
3527
                              iv_name="disk/%d" % disk_index,
3528
                              logical_id=(file_driver,
3529
                                          "%s/disk%d" % (file_storage_dir,
3530
                                                         idx)))
3531
      disks.append(disk_dev)
3532
  else:
3533
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
3534
  return disks
3535

    
3536

    
3537
def _GetInstanceInfoText(instance):
3538
  """Compute that text that should be added to the disk's metadata.
3539

3540
  """
3541
  return "originstname+%s" % instance.name
3542

    
3543

    
3544
def _CreateDisks(lu, instance):
3545
  """Create all disks for an instance.
3546

3547
  This abstracts away some work from AddInstance.
3548

3549
  @type lu: L{LogicalUnit}
3550
  @param lu: the logical unit on whose behalf we execute
3551
  @type instance: L{objects.Instance}
3552
  @param instance: the instance whose disks we should create
3553
  @rtype: boolean
3554
  @return: the success of the creation
3555

3556
  """
3557
  info = _GetInstanceInfoText(instance)
3558

    
3559
  if instance.disk_template == constants.DT_FILE:
3560
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
3561
    result = lu.rpc.call_file_storage_dir_create(instance.primary_node,
3562
                                                 file_storage_dir)
3563

    
3564
    if result.failed or not result.data:
3565
      logging.error("Could not connect to node '%s'", instance.primary_node)
3566
      return False
3567

    
3568
    if not result.data[0]:
3569
      logging.error("Failed to create directory '%s'", file_storage_dir)
3570
      return False
3571

    
3572
  # Note: this needs to be kept in sync with adding of disks in
3573
  # LUSetInstanceParams
3574
  for device in instance.disks:
3575
    logging.info("Creating volume %s for instance %s",
3576
                 device.iv_name, instance.name)
3577
    #HARDCODE
3578
    for secondary_node in instance.secondary_nodes:
3579
      if not _CreateBlockDevOnSecondary(lu, secondary_node, instance,
3580
                                        device, False, info):
3581
        logging.error("Failed to create volume %s (%s) on secondary node %s!",
3582
                      device.iv_name, device, secondary_node)
3583
        return False
3584
    #HARDCODE
3585
    if not _CreateBlockDevOnPrimary(lu, instance.primary_node,
3586
                                    instance, device, info):
3587
      logging.error("Failed to create volume %s on primary!", device.iv_name)
3588
      return False
3589

    
3590
  return True
3591

    
3592

    
3593
def _RemoveDisks(lu, instance):
3594
  """Remove all disks for an instance.
3595

3596
  This abstracts away some work from `AddInstance()` and
3597
  `RemoveInstance()`. Note that in case some of the devices couldn't
3598
  be removed, the removal will continue with the other ones (compare
3599
  with `_CreateDisks()`).
3600

3601
  @type lu: L{LogicalUnit}
3602
  @param lu: the logical unit on whose behalf we execute
3603
  @type instance: L{objects.Instance}
3604
  @param instance: the instance whose disks we should remove
3605
  @rtype: boolean
3606
  @return: the success of the removal
3607

3608
  """
3609
  logging.info("Removing block devices for instance %s", instance.name)
3610

    
3611
  result = True
3612
  for device in instance.disks:
3613
    for node, disk in device.ComputeNodeTree(instance.primary_node):
3614
      lu.cfg.SetDiskID(disk, node)
3615
      result = lu.rpc.call_blockdev_remove(node, disk)
3616
      if result.failed or not result.data:
3617
        lu.proc.LogWarning("Could not remove block device %s on node %s,"
3618
                           " continuing anyway", device.iv_name, node)
3619
        result = False
3620

    
3621
  if instance.disk_template == constants.DT_FILE:
3622
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
3623
    result = lu.rpc.call_file_storage_dir_remove(instance.primary_node,
3624
                                                 file_storage_dir)
3625
    if result.failed or not result.data:
3626
      logging.error("Could not remove directory '%s'", file_storage_dir)
3627
      result = False
3628

    
3629
  return result
3630

    
3631

    
3632
def _ComputeDiskSize(disk_template, disks):
3633
  """Compute disk size requirements in the volume group
3634

3635
  """
3636
  # Required free disk space as a function of disk and swap space
3637
  req_size_dict = {
3638
    constants.DT_DISKLESS: None,
3639
    constants.DT_PLAIN: sum(d["size"] for d in disks),
3640
    # 128 MB are added for drbd metadata for each disk
3641
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
3642
    constants.DT_FILE: None,
3643
  }
3644

    
3645
  if disk_template not in req_size_dict:
3646
    raise errors.ProgrammerError("Disk template '%s' size requirement"
3647
                                 " is unknown" %  disk_template)
3648

    
3649
  return req_size_dict[disk_template]
3650

    
3651

    
3652
def _CheckHVParams(lu, nodenames, hvname, hvparams):
3653
  """Hypervisor parameter validation.
3654

3655
  This function abstract the hypervisor parameter validation to be
3656
  used in both instance create and instance modify.
3657

3658
  @type lu: L{LogicalUnit}
3659
  @param lu: the logical unit for which we check
3660
  @type nodenames: list
3661
  @param nodenames: the list of nodes on which we should check
3662
  @type hvname: string
3663
  @param hvname: the name of the hypervisor we should use
3664
  @type hvparams: dict
3665
  @param hvparams: the parameters which we need to check
3666
  @raise errors.OpPrereqError: if the parameters are not valid
3667

3668
  """
3669
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
3670
                                                  hvname,
3671
                                                  hvparams)
3672
  for node in nodenames:
3673
    info = hvinfo[node]
3674
    info.Raise()
3675
    if not info.data or not isinstance(info.data, (tuple, list)):
3676
      raise errors.OpPrereqError("Cannot get current information"
3677
                                 " from node '%s' (%s)" % (node, info.data))
3678
    if not info.data[0]:
3679
      raise errors.OpPrereqError("Hypervisor parameter validation failed:"
3680
                                 " %s" % info.data[1])
3681

    
3682

    
3683
class LUCreateInstance(LogicalUnit):
3684
  """Create an instance.
3685

3686
  """
3687
  HPATH = "instance-add"
3688
  HTYPE = constants.HTYPE_INSTANCE
3689
  _OP_REQP = ["instance_name", "disks", "disk_template",
3690
              "mode", "start",
3691
              "wait_for_sync", "ip_check", "nics",
3692
              "hvparams", "beparams"]
3693
  REQ_BGL = False
3694

    
3695
  def _ExpandNode(self, node):
3696
    """Expands and checks one node name.
3697

3698
    """
3699
    node_full = self.cfg.ExpandNodeName(node)
3700
    if node_full is None:
3701
      raise errors.OpPrereqError("Unknown node %s" % node)
3702
    return node_full
3703

    
3704
  def ExpandNames(self):
3705
    """ExpandNames for CreateInstance.
3706

3707
    Figure out the right locks for instance creation.
3708

3709
    """
3710
    self.needed_locks = {}
3711

    
3712
    # set optional parameters to none if they don't exist
3713
    for attr in ["pnode", "snode", "iallocator", "hypervisor"]:
3714
      if not hasattr(self.op, attr):
3715
        setattr(self.op, attr, None)
3716

    
3717
    # cheap checks, mostly valid constants given
3718

    
3719
    # verify creation mode
3720
    if self.op.mode not in (constants.INSTANCE_CREATE,
3721
                            constants.INSTANCE_IMPORT):
3722
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
3723
                                 self.op.mode)
3724

    
3725
    # disk template and mirror node verification
3726
    if self.op.disk_template not in constants.DISK_TEMPLATES:
3727
      raise errors.OpPrereqError("Invalid disk template name")
3728

    
3729
    if self.op.hypervisor is None:
3730
      self.op.hypervisor = self.cfg.GetHypervisorType()
3731

    
3732
    cluster = self.cfg.GetClusterInfo()
3733
    enabled_hvs = cluster.enabled_hypervisors
3734
    if self.op.hypervisor not in enabled_hvs:
3735
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
3736
                                 " cluster (%s)" % (self.op.hypervisor,
3737
                                  ",".join(enabled_hvs)))
3738

    
3739
    # check hypervisor parameter syntax (locally)
3740

    
3741
    filled_hvp = cluster.FillDict(cluster.hvparams[self.op.hypervisor],
3742
                                  self.op.hvparams)
3743
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
3744
    hv_type.CheckParameterSyntax(filled_hvp)
3745

    
3746
    # fill and remember the beparams dict
3747
    utils.CheckBEParams(self.op.beparams)
3748
    self.be_full = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
3749
                                    self.op.beparams)
3750

    
3751
    #### instance parameters check
3752

    
3753
    # instance name verification
3754
    hostname1 = utils.HostInfo(self.op.instance_name)
3755
    self.op.instance_name = instance_name = hostname1.name
3756

    
3757
    # this is just a preventive check, but someone might still add this
3758
    # instance in the meantime, and creation will fail at lock-add time
3759
    if instance_name in self.cfg.GetInstanceList():
3760
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
3761
                                 instance_name)
3762

    
3763
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
3764

    
3765
    # NIC buildup
3766
    self.nics = []
3767
    for nic in self.op.nics:
3768
      # ip validity checks
3769
      ip = nic.get("ip", None)
3770
      if ip is None or ip.lower() == "none":
3771
        nic_ip = None
3772
      elif ip.lower() == constants.VALUE_AUTO:
3773
        nic_ip = hostname1.ip
3774
      else:
3775
        if not utils.IsValidIP(ip):
3776
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
3777
                                     " like a valid IP" % ip)
3778
        nic_ip = ip
3779

    
3780
      # MAC address verification
3781
      mac = nic.get("mac", constants.VALUE_AUTO)
3782
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
3783
        if not utils.IsValidMac(mac.lower()):
3784
          raise errors.OpPrereqError("Invalid MAC address specified: %s" %
3785
                                     mac)
3786
      # bridge verification
3787
      bridge = nic.get("bridge", self.cfg.GetDefBridge())
3788
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, bridge=bridge))
3789

    
3790
    # disk checks/pre-build
3791
    self.disks = []
3792
    for disk in self.op.disks:
3793
      mode = disk.get("mode", constants.DISK_RDWR)
3794
      if mode not in constants.DISK_ACCESS_SET:
3795
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
3796
                                   mode)
3797
      size = disk.get("size", None)
3798
      if size is None:
3799
        raise errors.OpPrereqError("Missing disk size")
3800
      try:
3801
        size = int(size)
3802
      except ValueError:
3803
        raise errors.OpPrereqError("Invalid disk size '%s'" % size)
3804
      self.disks.append({"size": size, "mode": mode})
3805

    
3806
    # used in CheckPrereq for ip ping check
3807
    self.check_ip = hostname1.ip
3808

    
3809
    # file storage checks
3810
    if (self.op.file_driver and
3811
        not self.op.file_driver in constants.FILE_DRIVER):
3812
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
3813
                                 self.op.file_driver)
3814

    
3815
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
3816
      raise errors.OpPrereqError("File storage directory path not absolute")
3817

    
3818
    ### Node/iallocator related checks
3819
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
3820
      raise errors.OpPrereqError("One and only one of iallocator and primary"
3821
                                 " node must be given")
3822

    
3823
    if self.op.iallocator:
3824
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3825
    else:
3826
      self.op.pnode = self._ExpandNode(self.op.pnode)
3827
      nodelist = [self.op.pnode]
3828
      if self.op.snode is not None:
3829
        self.op.snode = self._ExpandNode(self.op.snode)
3830
        nodelist.append(self.op.snode)
3831
      self.needed_locks[locking.LEVEL_NODE] = nodelist
3832

    
3833
    # in case of import lock the source node too
3834
    if self.op.mode == constants.INSTANCE_IMPORT:
3835
      src_node = getattr(self.op, "src_node", None)
3836
      src_path = getattr(self.op, "src_path", None)
3837

    
3838
      if src_path is None:
3839
        self.op.src_path = src_path = self.op.instance_name
3840

    
3841
      if src_node is None:
3842
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3843
        self.op.src_node = None
3844
        if os.path.isabs(src_path):
3845
          raise errors.OpPrereqError("Importing an instance from an absolute"
3846
                                     " path requires a source node option.")
3847
      else:
3848
        self.op.src_node = src_node = self._ExpandNode(src_node)
3849
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
3850
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
3851
        if not os.path.isabs(src_path):
3852
          self.op.src_path = src_path = \
3853
            os.path.join(constants.EXPORT_DIR, src_path)
3854

    
3855
    else: # INSTANCE_CREATE
3856
      if getattr(self.op, "os_type", None) is None:
3857
        raise errors.OpPrereqError("No guest OS specified")
3858

    
3859
  def _RunAllocator(self):
3860
    """Run the allocator based on input opcode.
3861

3862
    """
3863
    nics = [n.ToDict() for n in self.nics]
3864
    ial = IAllocator(self,
3865
                     mode=constants.IALLOCATOR_MODE_ALLOC,
3866
                     name=self.op.instance_name,
3867
                     disk_template=self.op.disk_template,
3868
                     tags=[],
3869
                     os=self.op.os_type,
3870
                     vcpus=self.be_full[constants.BE_VCPUS],
3871
                     mem_size=self.be_full[constants.BE_MEMORY],
3872
                     disks=self.disks,
3873
                     nics=nics,
3874
                     hypervisor=self.op.hypervisor,
3875
                     )
3876

    
3877
    ial.Run(self.op.iallocator)
3878

    
3879
    if not ial.success:
3880
      raise errors.OpPrereqError("Can't compute nodes using"
3881
                                 " iallocator '%s': %s" % (self.op.iallocator,
3882
                                                           ial.info))
3883
    if len(ial.nodes) != ial.required_nodes:
3884
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
3885
                                 " of nodes (%s), required %s" %
3886
                                 (self.op.iallocator, len(ial.nodes),
3887
                                  ial.required_nodes))
3888
    self.op.pnode = ial.nodes[0]
3889
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
3890
                 self.op.instance_name, self.op.iallocator,
3891
                 ", ".join(ial.nodes))
3892
    if ial.required_nodes == 2:
3893
      self.op.snode = ial.nodes[1]
3894

    
3895
  def BuildHooksEnv(self):
3896
    """Build hooks env.
3897

3898
    This runs on master, primary and secondary nodes of the instance.
3899

3900
    """
3901
    env = {
3902
      "INSTANCE_DISK_TEMPLATE": self.op.disk_template,
3903
      "INSTANCE_DISK_SIZE": ",".join(str(d["size"]) for d in self.disks),
3904
      "INSTANCE_ADD_MODE": self.op.mode,
3905
      }
3906
    if self.op.mode == constants.INSTANCE_IMPORT:
3907
      env["INSTANCE_SRC_NODE"] = self.op.src_node
3908
      env["INSTANCE_SRC_PATH"] = self.op.src_path
3909
      env["INSTANCE_SRC_IMAGES"] = self.src_images
3910

    
3911
    env.update(_BuildInstanceHookEnv(name=self.op.instance_name,
3912
      primary_node=self.op.pnode,
3913
      secondary_nodes=self.secondaries,
3914
      status=self.instance_status,
3915
      os_type=self.op.os_type,
3916
      memory=self.be_full[constants.BE_MEMORY],
3917
      vcpus=self.be_full[constants.BE_VCPUS],
3918
      nics=[(n.ip, n.bridge, n.mac) for n in self.nics],
3919
    ))
3920

    
3921
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
3922
          self.secondaries)
3923
    return env, nl, nl
3924

    
3925

    
3926
  def CheckPrereq(self):
3927
    """Check prerequisites.
3928

3929
    """
3930
    if (not self.cfg.GetVGName() and
3931
        self.op.disk_template not in constants.DTS_NOT_LVM):
3932
      raise errors.OpPrereqError("Cluster does not support lvm-based"
3933
                                 " instances")
3934

    
3935

    
3936
    if self.op.mode == constants.INSTANCE_IMPORT:
3937
      src_node = self.op.src_node
3938
      src_path = self.op.src_path
3939

    
3940
      if src_node is None:
3941
        exp_list = self.rpc.call_export_list(
3942
          self.acquired_locks[locking.LEVEL_NODE])
3943
        found = False
3944
        for node in exp_list:
3945
          if not exp_list[node].failed and src_path in exp_list[node].data:
3946
            found = True
3947
            self.op.src_node = src_node = node
3948
            self.op.src_path = src_path = os.path.join(constants.EXPORT_DIR,
3949
                                                       src_path)
3950
            break
3951
        if not found:
3952
          raise errors.OpPrereqError("No export found for relative path %s" %
3953
                                      src_path)
3954

    
3955
      _CheckNodeOnline(self, src_node)
3956
      result = self.rpc.call_export_info(src_node, src_path)
3957
      result.Raise()
3958
      if not result.data:
3959
        raise errors.OpPrereqError("No export found in dir %s" % src_path)
3960

    
3961
      export_info = result.data
3962
      if not export_info.has_section(constants.INISECT_EXP):
3963
        raise errors.ProgrammerError("Corrupted export config")
3964

    
3965
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
3966
      if (int(ei_version) != constants.EXPORT_VERSION):
3967
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
3968
                                   (ei_version, constants.EXPORT_VERSION))
3969

    
3970
      # Check that the new instance doesn't have less disks than the export
3971
      instance_disks = len(self.disks)
3972
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
3973
      if instance_disks < export_disks:
3974
        raise errors.OpPrereqError("Not enough disks to import."
3975
                                   " (instance: %d, export: %d)" %
3976
                                   (instance_disks, export_disks))
3977

    
3978
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
3979
      disk_images = []
3980
      for idx in range(export_disks):
3981
        option = 'disk%d_dump' % idx
3982
        if export_info.has_option(constants.INISECT_INS, option):
3983
          # FIXME: are the old os-es, disk sizes, etc. useful?
3984
          export_name = export_info.get(constants.INISECT_INS, option)
3985
          image = os.path.join(src_path, export_name)
3986
          disk_images.append(image)
3987
        else:
3988
          disk_images.append(False)
3989

    
3990
      self.src_images = disk_images
3991

    
3992
      old_name = export_info.get(constants.INISECT_INS, 'name')
3993
      # FIXME: int() here could throw a ValueError on broken exports
3994
      exp_nic_count = int(export_info.get(constants.INISECT_INS, 'nic_count'))
3995
      if self.op.instance_name == old_name:
3996
        for idx, nic in enumerate(self.nics):
3997
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
3998
            nic_mac_ini = 'nic%d_mac' % idx
3999
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
4000

    
4001
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
4002
    if self.op.start and not self.op.ip_check:
4003
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
4004
                                 " adding an instance in start mode")
4005

    
4006
    if self.op.ip_check:
4007
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
4008
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4009
                                   (self.check_ip, self.op.instance_name))
4010

    
4011
    #### allocator run
4012

    
4013
    if self.op.iallocator is not None:
4014
      self._RunAllocator()
4015

    
4016
    #### node related checks
4017

    
4018
    # check primary node
4019
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
4020
    assert self.pnode is not None, \
4021
      "Cannot retrieve locked node %s" % self.op.pnode
4022
    if pnode.offline:
4023
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
4024
                                 pnode.name)
4025

    
4026
    self.secondaries = []
4027

    
4028
    # mirror node verification
4029
    if self.op.disk_template in constants.DTS_NET_MIRROR:
4030
      if self.op.snode is None:
4031
        raise errors.OpPrereqError("The networked disk templates need"
4032
                                   " a mirror node")
4033
      if self.op.snode == pnode.name:
4034
        raise errors.OpPrereqError("The secondary node cannot be"
4035
                                   " the primary node.")
4036
      self.secondaries.append(self.op.snode)
4037
      _CheckNodeOnline(self, self.op.snode)
4038

    
4039
    nodenames = [pnode.name] + self.secondaries
4040

    
4041
    req_size = _ComputeDiskSize(self.op.disk_template,
4042
                                self.disks)
4043

    
4044
    # Check lv size requirements
4045
    if req_size is not None:
4046
      nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
4047
                                         self.op.hypervisor)
4048
      for node in nodenames:
4049
        info = nodeinfo[node]
4050
        info.Raise()
4051
        info = info.data
4052
        if not info:
4053
          raise errors.OpPrereqError("Cannot get current information"
4054
                                     " from node '%s'" % node)
4055
        vg_free = info.get('vg_free', None)
4056
        if not isinstance(vg_free, int):
4057
          raise errors.OpPrereqError("Can't compute free disk space on"
4058
                                     " node %s" % node)
4059
        if req_size > info['vg_free']:
4060
          raise errors.OpPrereqError("Not enough disk space on target node %s."
4061
                                     " %d MB available, %d MB required" %
4062
                                     (node, info['vg_free'], req_size))
4063

    
4064
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
4065

    
4066
    # os verification
4067
    result = self.rpc.call_os_get(pnode.name, self.op.os_type)
4068
    result.Raise()
4069
    if not isinstance(result.data, objects.OS):
4070
      raise errors.OpPrereqError("OS '%s' not in supported os list for"
4071
                                 " primary node"  % self.op.os_type)
4072

    
4073
    # bridge check on primary node
4074
    bridges = [n.bridge for n in self.nics]
4075
    result = self.rpc.call_bridges_exist(self.pnode.name, bridges)
4076
    result.Raise()
4077
    if not result.data:
4078
      raise errors.OpPrereqError("One of the target bridges '%s' does not"
4079
                                 " exist on destination node '%s'" %
4080
                                 (",".join(bridges), pnode.name))
4081

    
4082
    # memory check on primary node
4083
    if self.op.start:
4084
      _CheckNodeFreeMemory(self, self.pnode.name,
4085
                           "creating instance %s" % self.op.instance_name,
4086
                           self.be_full[constants.BE_MEMORY],
4087
                           self.op.hypervisor)
4088

    
4089
    if self.op.start:
4090
      self.instance_status = 'up'
4091
    else:
4092
      self.instance_status = 'down'
4093

    
4094
  def Exec(self, feedback_fn):
4095
    """Create and add the instance to the cluster.
4096

4097
    """
4098
    instance = self.op.instance_name
4099
    pnode_name = self.pnode.name
4100

    
4101
    for nic in self.nics:
4102
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
4103
        nic.mac = self.cfg.GenerateMAC()
4104

    
4105
    ht_kind = self.op.hypervisor
4106
    if ht_kind in constants.HTS_REQ_PORT:
4107
      network_port = self.cfg.AllocatePort()
4108
    else:
4109
      network_port = None
4110

    
4111
    ##if self.op.vnc_bind_address is None:
4112
    ##  self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
4113

    
4114
    # this is needed because os.path.join does not accept None arguments
4115
    if self.op.file_storage_dir is None:
4116
      string_file_storage_dir = ""
4117
    else:
4118
      string_file_storage_dir = self.op.file_storage_dir
4119

    
4120
    # build the full file storage dir path
4121
    file_storage_dir = os.path.normpath(os.path.join(
4122
                                        self.cfg.GetFileStorageDir(),
4123
                                        string_file_storage_dir, instance))
4124

    
4125

    
4126
    disks = _GenerateDiskTemplate(self,
4127
                                  self.op.disk_template,
4128
                                  instance, pnode_name,
4129
                                  self.secondaries,
4130
                                  self.disks,
4131
                                  file_storage_dir,
4132
                                  self.op.file_driver,
4133
                                  0)
4134

    
4135
    iobj = objects.Instance(name=instance, os=self.op.os_type,
4136
                            primary_node=pnode_name,
4137
                            nics=self.nics, disks=disks,
4138
                            disk_template=self.op.disk_template,
4139
                            status=self.instance_status,
4140
                            network_port=network_port,
4141
                            beparams=self.op.beparams,
4142
                            hvparams=self.op.hvparams,
4143
                            hypervisor=self.op.hypervisor,
4144
                            )
4145

    
4146
    feedback_fn("* creating instance disks...")
4147
    if not _CreateDisks(self, iobj):
4148
      _RemoveDisks(self, iobj)
4149
      self.cfg.ReleaseDRBDMinors(instance)
4150
      raise errors.OpExecError("Device creation failed, reverting...")
4151

    
4152
    feedback_fn("adding instance %s to cluster config" % instance)
4153

    
4154
    self.cfg.AddInstance(iobj)
4155
    # Declare that we don't want to remove the instance lock anymore, as we've
4156
    # added the instance to the config
4157
    del self.remove_locks[locking.LEVEL_INSTANCE]
4158
    # Remove the temp. assignements for the instance's drbds
4159
    self.cfg.ReleaseDRBDMinors(instance)
4160
    # Unlock all the nodes
4161
    if self.op.mode == constants.INSTANCE_IMPORT:
4162
      nodes_keep = [self.op.src_node]
4163
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
4164
                       if node != self.op.src_node]
4165
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
4166
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
4167
    else:
4168
      self.context.glm.release(locking.LEVEL_NODE)
4169
      del self.acquired_locks[locking.LEVEL_NODE]
4170

    
4171
    if self.op.wait_for_sync:
4172
      disk_abort = not _WaitForSync(self, iobj)
4173
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
4174
      # make sure the disks are not degraded (still sync-ing is ok)
4175
      time.sleep(15)
4176
      feedback_fn("* checking mirrors status")
4177
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
4178
    else:
4179
      disk_abort = False
4180

    
4181
    if disk_abort:
4182
      _RemoveDisks(self, iobj)
4183
      self.cfg.RemoveInstance(iobj.name)
4184
      # Make sure the instance lock gets removed
4185
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
4186
      raise errors.OpExecError("There are some degraded disks for"
4187
                               " this instance")
4188

    
4189
    feedback_fn("creating os for instance %s on node %s" %
4190
                (instance, pnode_name))
4191

    
4192
    if iobj.disk_template != constants.DT_DISKLESS:
4193
      if self.op.mode == constants.INSTANCE_CREATE:
4194
        feedback_fn("* running the instance OS create scripts...")
4195
        result = self.rpc.call_instance_os_add(pnode_name, iobj)
4196
        result.Raise()
4197
        if not result.data:
4198
          raise errors.OpExecError("Could not add os for instance %s"
4199
                                   " on node %s" %
4200
                                   (instance, pnode_name))
4201

    
4202
      elif self.op.mode == constants.INSTANCE_IMPORT:
4203
        feedback_fn("* running the instance OS import scripts...")
4204
        src_node = self.op.src_node
4205
        src_images = self.src_images
4206
        cluster_name = self.cfg.GetClusterName()
4207
        import_result = self.rpc.call_instance_os_import(pnode_name, iobj,
4208
                                                         src_node, src_images,
4209
                                                         cluster_name)
4210
        import_result.Raise()
4211
        for idx, result in enumerate(import_result.data):
4212
          if not result:
4213
            self.LogWarning("Could not import the image %s for instance"
4214
                            " %s, disk %d, on node %s" %
4215
                            (src_images[idx], instance, idx, pnode_name))
4216
      else:
4217
        # also checked in the prereq part
4218
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
4219
                                     % self.op.mode)
4220

    
4221
    if self.op.start:
4222
      logging.info("Starting instance %s on node %s", instance, pnode_name)
4223
      feedback_fn("* starting instance...")
4224
      result = self.rpc.call_instance_start(pnode_name, iobj, None)
4225
      result.Raise()
4226
      if not result.data:
4227
        raise errors.OpExecError("Could not start instance")
4228

    
4229

    
4230
class LUConnectConsole(NoHooksLU):
4231
  """Connect to an instance's console.
4232

4233
  This is somewhat special in that it returns the command line that
4234
  you need to run on the master node in order to connect to the
4235
  console.
4236

4237
  """
4238
  _OP_REQP = ["instance_name"]
4239
  REQ_BGL = False
4240

    
4241
  def ExpandNames(self):
4242
    self._ExpandAndLockInstance()
4243

    
4244
  def CheckPrereq(self):
4245
    """Check prerequisites.
4246

4247
    This checks that the instance is in the cluster.
4248

4249
    """
4250
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4251
    assert self.instance is not None, \
4252
      "Cannot retrieve locked instance %s" % self.op.instance_name
4253
    _CheckNodeOnline(self, self.instance.primary_node)
4254

    
4255
  def Exec(self, feedback_fn):
4256
    """Connect to the console of an instance
4257

4258
    """
4259
    instance = self.instance
4260
    node = instance.primary_node
4261

    
4262
    node_insts = self.rpc.call_instance_list([node],
4263
                                             [instance.hypervisor])[node]
4264
    node_insts.Raise()
4265

    
4266
    if instance.name not in node_insts.data:
4267
      raise errors.OpExecError("Instance %s is not running." % instance.name)
4268

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

    
4271
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
4272
    console_cmd = hyper.GetShellCommandForConsole(instance)
4273

    
4274
    # build ssh cmdline
4275
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
4276

    
4277

    
4278
class LUReplaceDisks(LogicalUnit):
4279
  """Replace the disks of an instance.
4280

4281
  """
4282
  HPATH = "mirrors-replace"
4283
  HTYPE = constants.HTYPE_INSTANCE
4284
  _OP_REQP = ["instance_name", "mode", "disks"]
4285
  REQ_BGL = False
4286

    
4287
  def CheckArguments(self):
4288
    if not hasattr(self.op, "remote_node"):
4289
      self.op.remote_node = None
4290
    if not hasattr(self.op, "iallocator"):
4291
      self.op.iallocator = None
4292

    
4293
    # check for valid parameter combination
4294
    cnt = [self.op.remote_node, self.op.iallocator].count(None)
4295
    if self.op.mode == constants.REPLACE_DISK_CHG:
4296
      if cnt == 2:
4297
        raise errors.OpPrereqError("When changing the secondary either an"
4298
                                   " iallocator script must be used or the"
4299
                                   " new node given")
4300
      elif cnt == 0:
4301
        raise errors.OpPrereqError("Give either the iallocator or the new"
4302
                                   " secondary, not both")
4303
    else: # not replacing the secondary
4304
      if cnt != 2:
4305
        raise errors.OpPrereqError("The iallocator and new node options can"
4306
                                   " be used only when changing the"
4307
                                   " secondary node")
4308

    
4309
  def ExpandNames(self):
4310
    self._ExpandAndLockInstance()
4311

    
4312
    if self.op.iallocator is not None:
4313
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4314
    elif self.op.remote_node is not None:
4315
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
4316
      if remote_node is None:
4317
        raise errors.OpPrereqError("Node '%s' not known" %
4318
                                   self.op.remote_node)
4319
      self.op.remote_node = remote_node
4320
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
4321
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4322
    else:
4323
      self.needed_locks[locking.LEVEL_NODE] = []
4324
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4325

    
4326
  def DeclareLocks(self, level):
4327
    # If we're not already locking all nodes in the set we have to declare the
4328
    # instance's primary/secondary nodes.
4329
    if (level == locking.LEVEL_NODE and
4330
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
4331
      self._LockInstancesNodes()
4332

    
4333
  def _RunAllocator(self):
4334
    """Compute a new secondary node using an IAllocator.
4335

4336
    """
4337
    ial = IAllocator(self,
4338
                     mode=constants.IALLOCATOR_MODE_RELOC,
4339
                     name=self.op.instance_name,
4340
                     relocate_from=[self.sec_node])
4341

    
4342
    ial.Run(self.op.iallocator)
4343

    
4344
    if not ial.success:
4345
      raise errors.OpPrereqError("Can't compute nodes using"
4346
                                 " iallocator '%s': %s" % (self.op.iallocator,
4347
                                                           ial.info))
4348
    if len(ial.nodes) != ial.required_nodes:
4349
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
4350
                                 " of nodes (%s), required %s" %
4351
                                 (len(ial.nodes), ial.required_nodes))
4352
    self.op.remote_node = ial.nodes[0]
4353
    self.LogInfo("Selected new secondary for the instance: %s",
4354
                 self.op.remote_node)
4355

    
4356
  def BuildHooksEnv(self):
4357
    """Build hooks env.
4358

4359
    This runs on the master, the primary and all the secondaries.
4360

4361
    """
4362
    env = {
4363
      "MODE": self.op.mode,
4364
      "NEW_SECONDARY": self.op.remote_node,
4365
      "OLD_SECONDARY": self.instance.secondary_nodes[0],
4366
      }
4367
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4368
    nl = [
4369
      self.cfg.GetMasterNode(),
4370
      self.instance.primary_node,
4371
      ]
4372
    if self.op.remote_node is not None:
4373
      nl.append(self.op.remote_node)
4374
    return env, nl, nl
4375

    
4376
  def CheckPrereq(self):
4377
    """Check prerequisites.
4378

4379
    This checks that the instance is in the cluster.
4380

4381
    """
4382
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4383
    assert instance is not None, \
4384
      "Cannot retrieve locked instance %s" % self.op.instance_name
4385
    self.instance = instance
4386

    
4387
    if instance.disk_template != constants.DT_DRBD8:
4388
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
4389
                                 " instances")
4390

    
4391
    if len(instance.secondary_nodes) != 1:
4392
      raise errors.OpPrereqError("The instance has a strange layout,"
4393
                                 " expected one secondary but found %d" %
4394
                                 len(instance.secondary_nodes))
4395

    
4396
    self.sec_node = instance.secondary_nodes[0]
4397

    
4398
    if self.op.iallocator is not None:
4399
      self._RunAllocator()
4400

    
4401
    remote_node = self.op.remote_node
4402
    if remote_node is not None:
4403
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
4404
      assert self.remote_node_info is not None, \
4405
        "Cannot retrieve locked node %s" % remote_node
4406
    else:
4407
      self.remote_node_info = None
4408
    if remote_node == instance.primary_node:
4409
      raise errors.OpPrereqError("The specified node is the primary node of"
4410
                                 " the instance.")
4411
    elif remote_node == self.sec_node:
4412
      raise errors.OpPrereqError("The specified node is already the"
4413
                                 " secondary node of the instance.")
4414

    
4415
    if self.op.mode == constants.REPLACE_DISK_PRI:
4416
      n1 = self.tgt_node = instance.primary_node
4417
      n2 = self.oth_node = self.sec_node
4418
    elif self.op.mode == constants.REPLACE_DISK_SEC:
4419
      n1 = self.tgt_node = self.sec_node
4420
      n2 = self.oth_node = instance.primary_node
4421
    elif self.op.mode == constants.REPLACE_DISK_CHG:
4422
      n1 = self.new_node = remote_node
4423
      n2 = self.oth_node = instance.primary_node
4424
      self.tgt_node = self.sec_node
4425
    else:
4426
      raise errors.ProgrammerError("Unhandled disk replace mode")
4427

    
4428
    _CheckNodeOnline(self, n1)
4429
    _CheckNodeOnline(self, n2)
4430

    
4431
    if not self.op.disks:
4432
      self.op.disks = range(len(instance.disks))
4433

    
4434
    for disk_idx in self.op.disks:
4435
      instance.FindDisk(disk_idx)
4436

    
4437
  def _ExecD8DiskOnly(self, feedback_fn):
4438
    """Replace a disk on the primary or secondary for dbrd8.
4439

4440
    The algorithm for replace is quite complicated:
4441

4442
      1. for each disk to be replaced:
4443

4444
        1. create new LVs on the target node with unique names
4445
        1. detach old LVs from the drbd device
4446
        1. rename old LVs to name_replaced.<time_t>
4447
        1. rename new LVs to old LVs
4448
        1. attach the new LVs (with the old names now) to the drbd device
4449

4450
      1. wait for sync across all devices
4451

4452
      1. for each modified disk:
4453

4454
        1. remove old LVs (which have the name name_replaces.<time_t>)
4455

4456
    Failures are not very well handled.
4457

4458
    """
4459
    steps_total = 6
4460
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
4461
    instance = self.instance
4462
    iv_names = {}
4463
    vgname = self.cfg.GetVGName()
4464
    # start of work
4465
    cfg = self.cfg
4466
    tgt_node = self.tgt_node
4467
    oth_node = self.oth_node
4468

    
4469
    # Step: check device activation
4470
    self.proc.LogStep(1, steps_total, "check device existence")
4471
    info("checking volume groups")
4472
    my_vg = cfg.GetVGName()
4473
    results = self.rpc.call_vg_list([oth_node, tgt_node])
4474
    if not results:
4475
      raise errors.OpExecError("Can't list volume groups on the nodes")
4476
    for node in oth_node, tgt_node:
4477
      res = results[node]
4478
      if res.failed or not res.data or my_vg not in res.data:
4479
        raise errors.OpExecError("Volume group '%s' not found on %s" %
4480
                                 (my_vg, node))
4481
    for idx, dev in enumerate(instance.disks):
4482
      if idx not in self.op.disks:
4483
        continue
4484
      for node in tgt_node, oth_node:
4485
        info("checking disk/%d on %s" % (idx, node))
4486
        cfg.SetDiskID(dev, node)
4487
        if not self.rpc.call_blockdev_find(node, dev):
4488
          raise errors.OpExecError("Can't find disk/%d on node %s" %
4489
                                   (idx, node))
4490

    
4491
    # Step: check other node consistency
4492
    self.proc.LogStep(2, steps_total, "check peer consistency")
4493
    for idx, dev in enumerate(instance.disks):
4494
      if idx not in self.op.disks:
4495
        continue
4496
      info("checking disk/%d consistency on %s" % (idx, oth_node))
4497
      if not _CheckDiskConsistency(self, dev, oth_node,
4498
                                   oth_node==instance.primary_node):
4499
        raise errors.OpExecError("Peer node (%s) has degraded storage, unsafe"
4500
                                 " to replace disks on this node (%s)" %
4501
                                 (oth_node, tgt_node))
4502

    
4503
    # Step: create new storage
4504
    self.proc.LogStep(3, steps_total, "allocate new storage")
4505
    for idx, dev in enumerate(instance.disks):
4506
      if idx not in self.op.disks:
4507
        continue
4508
      size = dev.size
4509
      cfg.SetDiskID(dev, tgt_node)
4510
      lv_names = [".disk%d_%s" % (idx, suf)
4511
                  for suf in ["data", "meta"]]
4512
      names = _GenerateUniqueNames(self, lv_names)
4513
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=size,
4514
                             logical_id=(vgname, names[0]))
4515
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
4516
                             logical_id=(vgname, names[1]))
4517
      new_lvs = [lv_data, lv_meta]
4518
      old_lvs = dev.children
4519
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
4520
      info("creating new local storage on %s for %s" %
4521
           (tgt_node, dev.iv_name))
4522
      # since we *always* want to create this LV, we use the
4523
      # _Create...OnPrimary (which forces the creation), even if we
4524
      # are talking about the secondary node
4525
      for new_lv in new_lvs:
4526
        if not _CreateBlockDevOnPrimary(self, tgt_node, instance, new_lv,
4527
                                        _GetInstanceInfoText(instance)):
4528
          raise errors.OpExecError("Failed to create new LV named '%s' on"
4529
                                   " node '%s'" %
4530
                                   (new_lv.logical_id[1], tgt_node))
4531

    
4532
    # Step: for each lv, detach+rename*2+attach
4533
    self.proc.LogStep(4, steps_total, "change drbd configuration")
4534
    for dev, old_lvs, new_lvs in iv_names.itervalues():
4535
      info("detaching %s drbd from local storage" % dev.iv_name)
4536
      result = self.rpc.call_blockdev_removechildren(tgt_node, dev, old_lvs)
4537
      result.Raise()
4538
      if not result.data:
4539
        raise errors.OpExecError("Can't detach drbd from local storage on node"
4540
                                 " %s for device %s" % (tgt_node, dev.iv_name))
4541
      #dev.children = []
4542
      #cfg.Update(instance)
4543

    
4544
      # ok, we created the new LVs, so now we know we have the needed
4545
      # storage; as such, we proceed on the target node to rename
4546
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
4547
      # using the assumption that logical_id == physical_id (which in
4548
      # turn is the unique_id on that node)
4549

    
4550
      # FIXME(iustin): use a better name for the replaced LVs
4551
      temp_suffix = int(time.time())
4552
      ren_fn = lambda d, suff: (d.physical_id[0],
4553
                                d.physical_id[1] + "_replaced-%s" % suff)
4554
      # build the rename list based on what LVs exist on the node
4555
      rlist = []
4556
      for to_ren in old_lvs:
4557
        find_res = self.rpc.call_blockdev_find(tgt_node, to_ren)
4558
        if not find_res.failed and find_res.data is not None: # device exists
4559
          rlist.append((to_ren, ren_fn(to_ren, temp_suffix)))
4560

    
4561
      info("renaming the old LVs on the target node")
4562
      result = self.rpc.call_blockdev_rename(tgt_node, rlist)
4563
      result.Raise()
4564
      if not result.data:
4565
        raise errors.OpExecError("Can't rename old LVs on node %s" % tgt_node)
4566
      # now we rename the new LVs to the old LVs
4567
      info("renaming the new LVs on the target node")
4568
      rlist = [(new, old.physical_id) for old, new in zip(old_lvs, new_lvs)]
4569
      result = self.rpc.call_blockdev_rename(tgt_node, rlist)
4570
      result.Raise()
4571
      if not result.data:
4572
        raise errors.OpExecError("Can't rename new LVs on node %s" % tgt_node)
4573

    
4574
      for old, new in zip(old_lvs, new_lvs):
4575
        new.logical_id = old.logical_id
4576
        cfg.SetDiskID(new, tgt_node)
4577

    
4578
      for disk in old_lvs:
4579
        disk.logical_id = ren_fn(disk, temp_suffix)
4580
        cfg.SetDiskID(disk, tgt_node)
4581

    
4582
      # now that the new lvs have the old name, we can add them to the device
4583
      info("adding new mirror component on %s" % tgt_node)
4584
      result = self.rpc.call_blockdev_addchildren(tgt_node, dev, new_lvs)
4585
      if result.failed or not result.data:
4586
        for new_lv in new_lvs:
4587
          result = self.rpc.call_blockdev_remove(tgt_node, new_lv)
4588
          if result.failed or not result.data:
4589
            warning("Can't rollback device %s", hint="manually cleanup unused"
4590
                    " logical volumes")
4591
        raise errors.OpExecError("Can't add local storage to drbd")
4592

    
4593
      dev.children = new_lvs
4594
      cfg.Update(instance)
4595

    
4596
    # Step: wait for sync
4597

    
4598
    # this can fail as the old devices are degraded and _WaitForSync
4599
    # does a combined result over all disks, so we don't check its
4600
    # return value
4601
    self.proc.LogStep(5, steps_total, "sync devices")
4602
    _WaitForSync(self, instance, unlock=True)
4603

    
4604
    # so check manually all the devices
4605
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
4606
      cfg.SetDiskID(dev, instance.primary_node)
4607
      result = self.rpc.call_blockdev_find(instance.primary_node, dev)
4608
      if result.failed or result.data[5]:
4609
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
4610

    
4611
    # Step: remove old storage
4612
    self.proc.LogStep(6, steps_total, "removing old storage")
4613
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
4614
      info("remove logical volumes for %s" % name)
4615
      for lv in old_lvs:
4616
        cfg.SetDiskID(lv, tgt_node)
4617
        result = self.rpc.call_blockdev_remove(tgt_node, lv)
4618
        if result.failed or not result.data:
4619
          warning("Can't remove old LV", hint="manually remove unused LVs")
4620
          continue
4621

    
4622
  def _ExecD8Secondary(self, feedback_fn):
4623
    """Replace the secondary node for drbd8.
4624

4625
    The algorithm for replace is quite complicated:
4626
      - for all disks of the instance:
4627
        - create new LVs on the new node with same names
4628
        - shutdown the drbd device on the old secondary
4629
        - disconnect the drbd network on the primary
4630
        - create the drbd device on the new secondary
4631
        - network attach the drbd on the primary, using an artifice:
4632
          the drbd code for Attach() will connect to the network if it
4633
          finds a device which is connected to the good local disks but
4634
          not network enabled
4635
      - wait for sync across all devices
4636
      - remove all disks from the old secondary
4637

4638
    Failures are not very well handled.
4639

4640
    """
4641
    steps_total = 6
4642
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
4643
    instance = self.instance
4644
    iv_names = {}
4645
    # start of work
4646
    cfg = self.cfg
4647
    old_node = self.tgt_node
4648
    new_node = self.new_node
4649
    pri_node = instance.primary_node
4650
    nodes_ip = {
4651
      old_node: self.cfg.GetNodeInfo(old_node).secondary_ip,
4652
      new_node: self.cfg.GetNodeInfo(new_node).secondary_ip,
4653
      pri_node: self.cfg.GetNodeInfo(pri_node).secondary_ip,
4654
      }
4655

    
4656
    # Step: check device activation
4657
    self.proc.LogStep(1, steps_total, "check device existence")
4658
    info("checking volume groups")
4659
    my_vg = cfg.GetVGName()
4660
    results = self.rpc.call_vg_list([pri_node, new_node])
4661
    for node in pri_node, new_node:
4662
      res = results[node]
4663
      if res.failed or not res.data or my_vg not in res.data:
4664
        raise errors.OpExecError("Volume group '%s' not found on %s" %
4665
                                 (my_vg, node))
4666
    for idx, dev in enumerate(instance.disks):
4667
      if idx not in self.op.disks:
4668
        continue
4669
      info("checking disk/%d on %s" % (idx, pri_node))
4670
      cfg.SetDiskID(dev, pri_node)
4671
      result = self.rpc.call_blockdev_find(pri_node, dev)
4672
      result.Raise()
4673
      if not result.data:
4674
        raise errors.OpExecError("Can't find disk/%d on node %s" %
4675
                                 (idx, pri_node))
4676

    
4677
    # Step: check other node consistency
4678
    self.proc.LogStep(2, steps_total, "check peer consistency")
4679
    for idx, dev in enumerate(instance.disks):
4680
      if idx not in self.op.disks:
4681
        continue
4682
      info("checking disk/%d consistency on %s" % (idx, pri_node))
4683
      if not _CheckDiskConsistency(self, dev, pri_node, True, ldisk=True):
4684
        raise errors.OpExecError("Primary node (%s) has degraded storage,"
4685
                                 " unsafe to replace the secondary" %
4686
                                 pri_node)
4687

    
4688
    # Step: create new storage
4689
    self.proc.LogStep(3, steps_total, "allocate new storage")
4690
    for idx, dev in enumerate(instance.disks):
4691
      info("adding new local storage on %s for disk/%d" %
4692
           (new_node, idx))
4693
      # since we *always* want to create this LV, we use the
4694
      # _Create...OnPrimary (which forces the creation), even if we
4695
      # are talking about the secondary node
4696
      for new_lv in dev.children:
4697
        if not _CreateBlockDevOnPrimary(self, new_node, instance, new_lv,
4698
                                        _GetInstanceInfoText(instance)):
4699
          raise errors.OpExecError("Failed to create new LV named '%s' on"
4700
                                   " node '%s'" %
4701
                                   (new_lv.logical_id[1], new_node))
4702

    
4703
    # Step 4: dbrd minors and drbd setups changes
4704
    # after this, we must manually remove the drbd minors on both the
4705
    # error and the success paths
4706
    minors = cfg.AllocateDRBDMinor([new_node for dev in instance.disks],
4707
                                   instance.name)
4708
    logging.debug("Allocated minors %s" % (minors,))
4709
    self.proc.LogStep(4, steps_total, "changing drbd configuration")
4710
    for idx, (dev, new_minor) in enumerate(zip(instance.disks, minors)):
4711
      size = dev.size
4712
      info("activating a new drbd on %s for disk/%d" % (new_node, idx))
4713
      # create new devices on new_node; note that we create two IDs:
4714
      # one without port, so the drbd will be activated without
4715
      # networking information on the new node at this stage, and one
4716
      # with network, for the latter activation in step 4
4717
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
4718
      if pri_node == o_node1:
4719
        p_minor = o_minor1
4720
      else:
4721
        p_minor = o_minor2
4722

    
4723
      new_alone_id = (pri_node, new_node, None, p_minor, new_minor, o_secret)
4724
      new_net_id = (pri_node, new_node, o_port, p_minor, new_minor, o_secret)
4725

    
4726
      iv_names[idx] = (dev, dev.children, new_net_id)
4727
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
4728
                    new_net_id)
4729
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
4730
                              logical_id=new_alone_id,
4731
                              children=dev.children)
4732
      if not _CreateBlockDevOnSecondary(self, new_node, instance,
4733
                                        new_drbd, False,
4734
                                        _GetInstanceInfoText(instance)):
4735
        self.cfg.ReleaseDRBDMinors(instance.name)
4736
        raise errors.OpExecError("Failed to create new DRBD on"
4737
                                 " node '%s'" % new_node)
4738

    
4739
    for idx, dev in enumerate(instance.disks):
4740
      # we have new devices, shutdown the drbd on the old secondary
4741
      info("shutting down drbd for disk/%d on old node" % idx)
4742
      cfg.SetDiskID(dev, old_node)
4743
      result = self.rpc.call_blockdev_shutdown(old_node, dev)
4744
      if result.failed or not result.data:
4745
        warning("Failed to shutdown drbd for disk/%d on old node" % idx,
4746
                hint="Please cleanup this device manually as soon as possible")
4747

    
4748
    info("detaching primary drbds from the network (=> standalone)")
4749
    result = self.rpc.call_drbd_disconnect_net([pri_node], nodes_ip,
4750
                                               instance.disks)[pri_node]
4751

    
4752
    msg = result.RemoteFailMsg()
4753
    if msg:
4754
      # detaches didn't succeed (unlikely)
4755
      self.cfg.ReleaseDRBDMinors(instance.name)
4756
      raise errors.OpExecError("Can't detach the disks from the network on"
4757
                               " old node: %s" % (msg,))
4758

    
4759
    # if we managed to detach at least one, we update all the disks of
4760
    # the instance to point to the new secondary
4761
    info("updating instance configuration")
4762
    for dev, _, new_logical_id in iv_names.itervalues():
4763
      dev.logical_id = new_logical_id
4764
      cfg.SetDiskID(dev, pri_node)
4765
    cfg.Update(instance)
4766
    # we can remove now the temp minors as now the new values are
4767
    # written to the config file (and therefore stable)
4768
    self.cfg.ReleaseDRBDMinors(instance.name)
4769

    
4770
    # and now perform the drbd attach
4771
    info("attaching primary drbds to new secondary (standalone => connected)")
4772
    result = self.rpc.call_drbd_attach_net([pri_node, new_node], nodes_ip,
4773
                                           instance.disks, instance.name,
4774
                                           False)
4775
    for to_node, to_result in result.items():
4776
      msg = to_result.RemoteFailMsg()
4777
      if msg:
4778
        warning("can't attach drbd disks on node %s: %s", to_node, msg,
4779
                hint="please do a gnt-instance info to see the"
4780
                " status of disks")
4781

    
4782
    # this can fail as the old devices are degraded and _WaitForSync
4783
    # does a combined result over all disks, so we don't check its
4784
    # return value
4785
    self.proc.LogStep(5, steps_total, "sync devices")
4786
    _WaitForSync(self, instance, unlock=True)
4787

    
4788
    # so check manually all the devices
4789
    for idx, (dev, old_lvs, _) in iv_names.iteritems():
4790
      cfg.SetDiskID(dev, pri_node)
4791
      result = self.rpc.call_blockdev_find(pri_node, dev)
4792
      result.Raise()
4793
      if result.data[5]:
4794
        raise errors.OpExecError("DRBD device disk/%d is degraded!" % idx)
4795

    
4796
    self.proc.LogStep(6, steps_total, "removing old storage")
4797
    for idx, (dev, old_lvs, _) in iv_names.iteritems():
4798
      info("remove logical volumes for disk/%d" % idx)
4799
      for lv in old_lvs:
4800
        cfg.SetDiskID(lv, old_node)
4801
        result = self.rpc.call_blockdev_remove(old_node, lv)
4802
        if result.failed or not result.data:
4803
          warning("Can't remove LV on old secondary",
4804
                  hint="Cleanup stale volumes by hand")
4805

    
4806
  def Exec(self, feedback_fn):
4807
    """Execute disk replacement.
4808

4809
    This dispatches the disk replacement to the appropriate handler.
4810

4811
    """
4812
    instance = self.instance
4813

    
4814
    # Activate the instance disks if we're replacing them on a down instance
4815
    if instance.status == "down":
4816
      _StartInstanceDisks(self, instance, True)
4817

    
4818
    if self.op.mode == constants.REPLACE_DISK_CHG:
4819
      fn = self._ExecD8Secondary
4820
    else:
4821
      fn = self._ExecD8DiskOnly
4822

    
4823
    ret = fn(feedback_fn)
4824

    
4825
    # Deactivate the instance disks if we're replacing them on a down instance
4826
    if instance.status == "down":
4827
      _SafeShutdownInstanceDisks(self, instance)
4828

    
4829
    return ret
4830

    
4831

    
4832
class LUGrowDisk(LogicalUnit):
4833
  """Grow a disk of an instance.
4834

4835
  """
4836
  HPATH = "disk-grow"
4837
  HTYPE = constants.HTYPE_INSTANCE
4838
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
4839
  REQ_BGL = False
4840

    
4841
  def ExpandNames(self):
4842
    self._ExpandAndLockInstance()
4843
    self.needed_locks[locking.LEVEL_NODE] = []
4844
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4845

    
4846
  def DeclareLocks(self, level):
4847
    if level == locking.LEVEL_NODE:
4848
      self._LockInstancesNodes()
4849

    
4850
  def BuildHooksEnv(self):
4851
    """Build hooks env.
4852

4853
    This runs on the master, the primary and all the secondaries.
4854

4855
    """
4856
    env = {
4857
      "DISK": self.op.disk,
4858
      "AMOUNT": self.op.amount,
4859
      }
4860
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4861
    nl = [
4862
      self.cfg.GetMasterNode(),
4863
      self.instance.primary_node,
4864
      ]
4865
    return env, nl, nl
4866

    
4867
  def CheckPrereq(self):
4868
    """Check prerequisites.
4869

4870
    This checks that the instance is in the cluster.
4871

4872
    """
4873
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4874
    assert instance is not None, \
4875
      "Cannot retrieve locked instance %s" % self.op.instance_name
4876
    _CheckNodeOnline(self, instance.primary_node)
4877
    for node in instance.secondary_nodes:
4878
      _CheckNodeOnline(self, node)
4879

    
4880

    
4881
    self.instance = instance
4882

    
4883
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
4884
      raise errors.OpPrereqError("Instance's disk layout does not support"
4885
                                 " growing.")
4886

    
4887
    self.disk = instance.FindDisk(self.op.disk)
4888

    
4889
    nodenames = [instance.primary_node] + list(instance.secondary_nodes)
4890
    nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
4891
                                       instance.hypervisor)
4892
    for node in nodenames:
4893
      info = nodeinfo[node]
4894
      if info.failed or not info.data:
4895
        raise errors.OpPrereqError("Cannot get current information"
4896
                                   " from node '%s'" % node)
4897
      vg_free = info.data.get('vg_free', None)
4898
      if not isinstance(vg_free, int):
4899
        raise errors.OpPrereqError("Can't compute free disk space on"
4900
                                   " node %s" % node)
4901
      if self.op.amount > vg_free:
4902
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
4903
                                   " %d MiB available, %d MiB required" %
4904
                                   (node, vg_free, self.op.amount))
4905

    
4906
  def Exec(self, feedback_fn):
4907
    """Execute disk grow.
4908

4909
    """
4910
    instance = self.instance
4911
    disk = self.disk
4912
    for node in (instance.secondary_nodes + (instance.primary_node,)):
4913
      self.cfg.SetDiskID(disk, node)
4914
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
4915
      result.Raise()
4916
      if (not result.data or not isinstance(result.data, (list, tuple)) or
4917
          len(result.data) != 2):
4918
        raise errors.OpExecError("Grow request failed to node %s" % node)
4919
      elif not result.data[0]:
4920
        raise errors.OpExecError("Grow request failed to node %s: %s" %
4921
                                 (node, result.data[1]))
4922
    disk.RecordGrow(self.op.amount)
4923
    self.cfg.Update(instance)
4924
    if self.op.wait_for_sync:
4925
      disk_abort = not _WaitForSync(self, instance)
4926
      if disk_abort:
4927
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
4928
                             " status.\nPlease check the instance.")
4929

    
4930

    
4931
class LUQueryInstanceData(NoHooksLU):
4932
  """Query runtime instance data.
4933

4934
  """
4935
  _OP_REQP = ["instances", "static"]
4936
  REQ_BGL = False
4937

    
4938
  def ExpandNames(self):
4939
    self.needed_locks = {}
4940
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
4941

    
4942
    if not isinstance(self.op.instances, list):
4943
      raise errors.OpPrereqError("Invalid argument type 'instances'")
4944

    
4945
    if self.op.instances:
4946
      self.wanted_names = []
4947
      for name in self.op.instances:
4948
        full_name = self.cfg.ExpandInstanceName(name)
4949
        if full_name is None:
4950
          raise errors.OpPrereqError("Instance '%s' not known" % name)
4951
        self.wanted_names.append(full_name)
4952
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
4953
    else:
4954
      self.wanted_names = None
4955
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4956

    
4957
    self.needed_locks[locking.LEVEL_NODE] = []
4958
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4959

    
4960
  def DeclareLocks(self, level):
4961
    if level == locking.LEVEL_NODE:
4962
      self._LockInstancesNodes()
4963

    
4964
  def CheckPrereq(self):
4965
    """Check prerequisites.
4966

4967
    This only checks the optional instance list against the existing names.
4968

4969
    """
4970
    if self.wanted_names is None:
4971
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
4972

    
4973
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
4974
                             in self.wanted_names]
4975
    return
4976

    
4977
  def _ComputeDiskStatus(self, instance, snode, dev):
4978
    """Compute block device status.
4979

4980
    """
4981
    static = self.op.static
4982
    if not static:
4983
      self.cfg.SetDiskID(dev, instance.primary_node)
4984
      dev_pstatus = self.rpc.call_blockdev_find(instance.primary_node, dev)
4985
      dev_pstatus.Raise()
4986
      dev_pstatus = dev_pstatus.data
4987
    else:
4988
      dev_pstatus = None
4989

    
4990
    if dev.dev_type in constants.LDS_DRBD:
4991
      # we change the snode then (otherwise we use the one passed in)
4992
      if dev.logical_id[0] == instance.primary_node:
4993
        snode = dev.logical_id[1]
4994
      else:
4995
        snode = dev.logical_id[0]
4996

    
4997
    if snode and not static:
4998
      self.cfg.SetDiskID(dev, snode)
4999
      dev_sstatus = self.rpc.call_blockdev_find(snode, dev)
5000
      dev_sstatus.Raise()
5001
      dev_sstatus = dev_sstatus.data
5002
    else:
5003
      dev_sstatus = None
5004

    
5005
    if dev.children:
5006
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
5007
                      for child in dev.children]
5008
    else:
5009
      dev_children = []
5010

    
5011
    data = {
5012
      "iv_name": dev.iv_name,
5013
      "dev_type": dev.dev_type,
5014
      "logical_id": dev.logical_id,
5015
      "physical_id": dev.physical_id,
5016
      "pstatus": dev_pstatus,
5017
      "sstatus": dev_sstatus,
5018
      "children": dev_children,
5019
      "mode": dev.mode,
5020
      }
5021

    
5022
    return data
5023

    
5024
  def Exec(self, feedback_fn):
5025
    """Gather and return data"""
5026
    result = {}
5027

    
5028
    cluster = self.cfg.GetClusterInfo()
5029

    
5030
    for instance in self.wanted_instances:
5031
      if not self.op.static:
5032
        remote_info = self.rpc.call_instance_info(instance.primary_node,
5033
                                                  instance.name,
5034
                                                  instance.hypervisor)
5035
        remote_info.Raise()
5036
        remote_info = remote_info.data
5037
        if remote_info and "state" in remote_info:
5038
          remote_state = "up"
5039
        else:
5040
          remote_state = "down"
5041
      else:
5042
        remote_state = None
5043
      if instance.status == "down":
5044
        config_state = "down"
5045
      else:
5046
        config_state = "up"
5047

    
5048
      disks = [self._ComputeDiskStatus(instance, None, device)
5049
               for device in instance.disks]
5050

    
5051
      idict = {
5052
        "name": instance.name,
5053
        "config_state": config_state,
5054
        "run_state": remote_state,
5055
        "pnode": instance.primary_node,
5056
        "snodes": instance.secondary_nodes,
5057
        "os": instance.os,
5058
        "nics": [(nic.mac, nic.ip, nic.bridge) for nic in instance.nics],
5059
        "disks": disks,
5060
        "hypervisor": instance.hypervisor,
5061
        "network_port": instance.network_port,
5062
        "hv_instance": instance.hvparams,
5063
        "hv_actual": cluster.FillHV(instance),
5064
        "be_instance": instance.beparams,
5065
        "be_actual": cluster.FillBE(instance),
5066
        }
5067

    
5068
      result[instance.name] = idict
5069

    
5070
    return result
5071

    
5072

    
5073
class LUSetInstanceParams(LogicalUnit):
5074
  """Modifies an instances's parameters.
5075

5076
  """
5077
  HPATH = "instance-modify"
5078
  HTYPE = constants.HTYPE_INSTANCE
5079
  _OP_REQP = ["instance_name"]
5080
  REQ_BGL = False
5081

    
5082
  def CheckArguments(self):
5083
    if not hasattr(self.op, 'nics'):
5084
      self.op.nics = []
5085
    if not hasattr(self.op, 'disks'):
5086
      self.op.disks = []
5087
    if not hasattr(self.op, 'beparams'):
5088
      self.op.beparams = {}
5089
    if not hasattr(self.op, 'hvparams'):
5090
      self.op.hvparams = {}
5091
    self.op.force = getattr(self.op, "force", False)
5092
    if not (self.op.nics or self.op.disks or
5093
            self.op.hvparams or self.op.beparams):
5094
      raise errors.OpPrereqError("No changes submitted")
5095

    
5096
    utils.CheckBEParams(self.op.beparams)
5097

    
5098
    # Disk validation
5099
    disk_addremove = 0
5100
    for disk_op, disk_dict in self.op.disks:
5101
      if disk_op == constants.DDM_REMOVE:
5102
        disk_addremove += 1
5103
        continue
5104
      elif disk_op == constants.DDM_ADD:
5105
        disk_addremove += 1
5106
      else:
5107
        if not isinstance(disk_op, int):
5108
          raise errors.OpPrereqError("Invalid disk index")
5109
      if disk_op == constants.DDM_ADD:
5110
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
5111
        if mode not in (constants.DISK_RDONLY, constants.DISK_RDWR):
5112
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode)
5113
        size = disk_dict.get('size', None)
5114
        if size is None:
5115
          raise errors.OpPrereqError("Required disk parameter size missing")
5116
        try:
5117
          size = int(size)
5118
        except ValueError, err:
5119
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
5120
                                     str(err))
5121
        disk_dict['size'] = size
5122
      else:
5123
        # modification of disk
5124
        if 'size' in disk_dict:
5125
          raise errors.OpPrereqError("Disk size change not possible, use"
5126
                                     " grow-disk")
5127

    
5128
    if disk_addremove > 1:
5129
      raise errors.OpPrereqError("Only one disk add or remove operation"
5130
                                 " supported at a time")
5131

    
5132
    # NIC validation
5133
    nic_addremove = 0
5134
    for nic_op, nic_dict in self.op.nics:
5135
      if nic_op == constants.DDM_REMOVE:
5136
        nic_addremove += 1
5137
        continue
5138
      elif nic_op == constants.DDM_ADD:
5139
        nic_addremove += 1
5140
      else:
5141
        if not isinstance(nic_op, int):
5142
          raise errors.OpPrereqError("Invalid nic index")
5143

    
5144
      # nic_dict should be a dict
5145
      nic_ip = nic_dict.get('ip', None)
5146
      if nic_ip is not None:
5147
        if nic_ip.lower() == "none":
5148
          nic_dict['ip'] = None
5149
        else:
5150
          if not utils.IsValidIP(nic_ip):
5151
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip)
5152
      # we can only check None bridges and assign the default one
5153
      nic_bridge = nic_dict.get('bridge', None)
5154
      if nic_bridge is None:
5155
        nic_dict['bridge'] = self.cfg.GetDefBridge()
5156
      # but we can validate MACs
5157
      nic_mac = nic_dict.get('mac', None)
5158
      if nic_mac is not None:
5159
        if self.cfg.IsMacInUse(nic_mac):
5160
          raise errors.OpPrereqError("MAC address %s already in use"
5161
                                     " in cluster" % nic_mac)
5162
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5163
          if not utils.IsValidMac(nic_mac):
5164
            raise errors.OpPrereqError("Invalid MAC address %s" % nic_mac)
5165
    if nic_addremove > 1:
5166
      raise errors.OpPrereqError("Only one NIC add or remove operation"
5167
                                 " supported at a time")
5168

    
5169
  def ExpandNames(self):
5170
    self._ExpandAndLockInstance()
5171
    self.needed_locks[locking.LEVEL_NODE] = []
5172
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5173

    
5174
  def DeclareLocks(self, level):
5175
    if level == locking.LEVEL_NODE:
5176
      self._LockInstancesNodes()
5177

    
5178
  def BuildHooksEnv(self):
5179
    """Build hooks env.
5180

5181
    This runs on the master, primary and secondaries.
5182

5183
    """
5184
    args = dict()
5185
    if constants.BE_MEMORY in self.be_new:
5186
      args['memory'] = self.be_new[constants.BE_MEMORY]
5187
    if constants.BE_VCPUS in self.be_new:
5188
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
5189
    # FIXME: readd disk/nic changes
5190
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
5191
    nl = [self.cfg.GetMasterNode(),
5192
          self.instance.primary_node] + list(self.instance.secondary_nodes)
5193
    return env, nl, nl
5194

    
5195
  def CheckPrereq(self):
5196
    """Check prerequisites.
5197

5198
    This only checks the instance list against the existing names.
5199

5200
    """
5201
    force = self.force = self.op.force
5202

    
5203
    # checking the new params on the primary/secondary nodes
5204

    
5205
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5206
    assert self.instance is not None, \
5207
      "Cannot retrieve locked instance %s" % self.op.instance_name
5208
    pnode = self.instance.primary_node
5209
    nodelist = [pnode]
5210
    nodelist.extend(instance.secondary_nodes)
5211

    
5212
    # hvparams processing
5213
    if self.op.hvparams:
5214
      i_hvdict = copy.deepcopy(instance.hvparams)
5215
      for key, val in self.op.hvparams.iteritems():
5216
        if val == constants.VALUE_DEFAULT:
5217
          try:
5218
            del i_hvdict[key]
5219
          except KeyError:
5220
            pass
5221
        elif val == constants.VALUE_NONE:
5222
          i_hvdict[key] = None
5223
        else:
5224
          i_hvdict[key] = val
5225
      cluster = self.cfg.GetClusterInfo()
5226
      hv_new = cluster.FillDict(cluster.hvparams[instance.hypervisor],
5227
                                i_hvdict)
5228
      # local check
5229
      hypervisor.GetHypervisor(
5230
        instance.hypervisor).CheckParameterSyntax(hv_new)
5231
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
5232
      self.hv_new = hv_new # the new actual values
5233
      self.hv_inst = i_hvdict # the new dict (without defaults)
5234
    else:
5235
      self.hv_new = self.hv_inst = {}
5236

    
5237
    # beparams processing
5238
    if self.op.beparams:
5239
      i_bedict = copy.deepcopy(instance.beparams)
5240
      for key, val in self.op.beparams.iteritems():
5241
        if val == constants.VALUE_DEFAULT:
5242
          try:
5243
            del i_bedict[key]
5244
          except KeyError:
5245
            pass
5246
        else:
5247
          i_bedict[key] = val
5248
      cluster = self.cfg.GetClusterInfo()
5249
      be_new = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
5250
                                i_bedict)
5251
      self.be_new = be_new # the new actual values
5252
      self.be_inst = i_bedict # the new dict (without defaults)
5253
    else:
5254
      self.be_new = self.be_inst = {}
5255

    
5256
    self.warn = []
5257

    
5258
    if constants.BE_MEMORY in self.op.beparams and not self.force:
5259
      mem_check_list = [pnode]
5260
      if be_new[constants.BE_AUTO_BALANCE]:
5261
        # either we changed auto_balance to yes or it was from before
5262
        mem_check_list.extend(instance.secondary_nodes)
5263
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
5264
                                                  instance.hypervisor)
5265
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
5266
                                         instance.hypervisor)
5267
      if nodeinfo[pnode].failed or not isinstance(nodeinfo[pnode].data, dict):
5268
        # Assume the primary node is unreachable and go ahead
5269
        self.warn.append("Can't get info from primary node %s" % pnode)
5270
      else:
5271
        if not instance_info.failed and instance_info.data:
5272
          current_mem = instance_info.data['memory']
5273
        else:
5274
          # Assume instance not running
5275
          # (there is a slight race condition here, but it's not very probable,
5276
          # and we have no other way to check)
5277
          current_mem = 0
5278
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
5279
                    nodeinfo[pnode].data['memory_free'])
5280
        if miss_mem > 0:
5281
          raise errors.OpPrereqError("This change will prevent the instance"
5282
                                     " from starting, due to %d MB of memory"
5283
                                     " missing on its primary node" % miss_mem)
5284

    
5285
      if be_new[constants.BE_AUTO_BALANCE]:
5286
        for node, nres in nodeinfo.iteritems():
5287
          if node not in instance.secondary_nodes:
5288
            continue
5289
          if nres.failed or not isinstance(nres.data, dict):
5290
            self.warn.append("Can't get info from secondary node %s" % node)
5291
          elif be_new[constants.BE_MEMORY] > nres.data['memory_free']:
5292
            self.warn.append("Not enough memory to failover instance to"
5293
                             " secondary node %s" % node)
5294

    
5295
    # NIC processing
5296
    for nic_op, nic_dict in self.op.nics:
5297
      if nic_op == constants.DDM_REMOVE:
5298
        if not instance.nics:
5299
          raise errors.OpPrereqError("Instance has no NICs, cannot remove")
5300
        continue
5301
      if nic_op != constants.DDM_ADD:
5302
        # an existing nic
5303
        if nic_op < 0 or nic_op >= len(instance.nics):
5304
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
5305
                                     " are 0 to %d" %
5306
                                     (nic_op, len(instance.nics)))
5307
      nic_bridge = nic_dict.get('bridge', None)
5308
      if nic_bridge is not None:
5309
        if not self.rpc.call_bridges_exist(pnode, [nic_bridge]):
5310
          msg = ("Bridge '%s' doesn't exist on one of"
5311
                 " the instance nodes" % nic_bridge)
5312
          if self.force:
5313
            self.warn.append(msg)
5314
          else:
5315
            raise errors.OpPrereqError(msg)
5316

    
5317
    # DISK processing
5318
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
5319
      raise errors.OpPrereqError("Disk operations not supported for"
5320
                                 " diskless instances")
5321
    for disk_op, disk_dict in self.op.disks:
5322
      if disk_op == constants.DDM_REMOVE:
5323
        if len(instance.disks) == 1:
5324
          raise errors.OpPrereqError("Cannot remove the last disk of"
5325
                                     " an instance")
5326
        ins_l = self.rpc.call_instance_list([pnode], [instance.hypervisor])
5327
        ins_l = ins_l[pnode]
5328
        if ins_l.failed or not isinstance(ins_l.data, list):
5329
          raise errors.OpPrereqError("Can't contact node '%s'" % pnode)
5330
        if instance.name in ins_l.data:
5331
          raise errors.OpPrereqError("Instance is running, can't remove"
5332
                                     " disks.")
5333

    
5334
      if (disk_op == constants.DDM_ADD and
5335
          len(instance.nics) >= constants.MAX_DISKS):
5336
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
5337
                                   " add more" % constants.MAX_DISKS)
5338
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
5339
        # an existing disk
5340
        if disk_op < 0 or disk_op >= len(instance.disks):
5341
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
5342
                                     " are 0 to %d" %
5343
                                     (disk_op, len(instance.disks)))
5344

    
5345
    return
5346

    
5347
  def Exec(self, feedback_fn):
5348
    """Modifies an instance.
5349

5350
    All parameters take effect only at the next restart of the instance.
5351

5352
    """
5353
    # Process here the warnings from CheckPrereq, as we don't have a
5354
    # feedback_fn there.
5355
    for warn in self.warn:
5356
      feedback_fn("WARNING: %s" % warn)
5357

    
5358
    result = []
5359
    instance = self.instance
5360
    # disk changes
5361
    for disk_op, disk_dict in self.op.disks:
5362
      if disk_op == constants.DDM_REMOVE:
5363
        # remove the last disk
5364
        device = instance.disks.pop()
5365
        device_idx = len(instance.disks)
5366
        for node, disk in device.ComputeNodeTree(instance.primary_node):
5367
          self.cfg.SetDiskID(disk, node)
5368
          rpc_result = self.rpc.call_blockdev_remove(node, disk)
5369
          if rpc_result.failed or not rpc_result.data:
5370
            self.proc.LogWarning("Could not remove disk/%d on node %s,"
5371
                                 " continuing anyway", device_idx, node)
5372
        result.append(("disk/%d" % device_idx, "remove"))
5373
      elif disk_op == constants.DDM_ADD:
5374
        # add a new disk
5375
        if instance.disk_template == constants.DT_FILE:
5376
          file_driver, file_path = instance.disks[0].logical_id
5377
          file_path = os.path.dirname(file_path)
5378
        else:
5379
          file_driver = file_path = None
5380
        disk_idx_base = len(instance.disks)
5381
        new_disk = _GenerateDiskTemplate(self,
5382
                                         instance.disk_template,
5383
                                         instance, instance.primary_node,
5384
                                         instance.secondary_nodes,
5385
                                         [disk_dict],
5386
                                         file_path,
5387
                                         file_driver,
5388
                                         disk_idx_base)[0]
5389
        new_disk.mode = disk_dict['mode']
5390
        instance.disks.append(new_disk)
5391
        info = _GetInstanceInfoText(instance)
5392

    
5393
        logging.info("Creating volume %s for instance %s",
5394
                     new_disk.iv_name, instance.name)
5395
        # Note: this needs to be kept in sync with _CreateDisks
5396
        #HARDCODE
5397
        for secondary_node in instance.secondary_nodes:
5398
          if not _CreateBlockDevOnSecondary(self, secondary_node, instance,
5399
                                            new_disk, False, info):
5400
            self.LogWarning("Failed to create volume %s (%s) on"
5401
                            " secondary node %s!",
5402
                            new_disk.iv_name, new_disk, secondary_node)
5403
        #HARDCODE
5404
        if not _CreateBlockDevOnPrimary(self, instance.primary_node,
5405
                                        instance, new_disk, info):
5406
          self.LogWarning("Failed to create volume %s on primary!",
5407
                          new_disk.iv_name)
5408
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
5409
                       (new_disk.size, new_disk.mode)))
5410
      else:
5411
        # change a given disk
5412
        instance.disks[disk_op].mode = disk_dict['mode']
5413
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
5414
    # NIC changes
5415
    for nic_op, nic_dict in self.op.nics:
5416
      if nic_op == constants.DDM_REMOVE:
5417
        # remove the last nic
5418
        del instance.nics[-1]
5419
        result.append(("nic.%d" % len(instance.nics), "remove"))
5420
      elif nic_op == constants.DDM_ADD:
5421
        # add a new nic
5422
        if 'mac' not in nic_dict:
5423
          mac = constants.VALUE_GENERATE
5424
        else:
5425
          mac = nic_dict['mac']
5426
        if mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5427
          mac = self.cfg.GenerateMAC()
5428
        new_nic = objects.NIC(mac=mac, ip=nic_dict.get('ip', None),
5429
                              bridge=nic_dict.get('bridge', None))
5430
        instance.nics.append(new_nic)
5431
        result.append(("nic.%d" % (len(instance.nics) - 1),
5432
                       "add:mac=%s,ip=%s,bridge=%s" %
5433
                       (new_nic.mac, new_nic.ip, new_nic.bridge)))
5434
      else:
5435
        # change a given nic
5436
        for key in 'mac', 'ip', 'bridge':
5437
          if key in nic_dict:
5438
            setattr(instance.nics[nic_op], key, nic_dict[key])
5439
            result.append(("nic.%s/%d" % (key, nic_op), nic_dict[key]))
5440

    
5441
    # hvparams changes
5442
    if self.op.hvparams:
5443
      instance.hvparams = self.hv_new
5444
      for key, val in self.op.hvparams.iteritems():
5445
        result.append(("hv/%s" % key, val))
5446

    
5447
    # beparams changes
5448
    if self.op.beparams:
5449
      instance.beparams = self.be_inst
5450
      for key, val in self.op.beparams.iteritems():
5451
        result.append(("be/%s" % key, val))
5452

    
5453
    self.cfg.Update(instance)
5454

    
5455
    return result
5456

    
5457

    
5458
class LUQueryExports(NoHooksLU):
5459
  """Query the exports list
5460

5461
  """
5462
  _OP_REQP = ['nodes']
5463
  REQ_BGL = False
5464

    
5465
  def ExpandNames(self):
5466
    self.needed_locks = {}
5467
    self.share_locks[locking.LEVEL_NODE] = 1
5468
    if not self.op.nodes:
5469
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5470
    else:
5471
      self.needed_locks[locking.LEVEL_NODE] = \
5472
        _GetWantedNodes(self, self.op.nodes)
5473

    
5474
  def CheckPrereq(self):
5475
    """Check prerequisites.
5476

5477
    """
5478
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
5479

    
5480
  def Exec(self, feedback_fn):
5481
    """Compute the list of all the exported system images.
5482

5483
    @rtype: dict
5484
    @return: a dictionary with the structure node->(export-list)
5485
        where export-list is a list of the instances exported on
5486
        that node.
5487

5488
    """
5489
    rpcresult = self.rpc.call_export_list(self.nodes)
5490
    result = {}
5491
    for node in rpcresult:
5492
      if rpcresult[node].failed:
5493
        result[node] = False
5494
      else:
5495
        result[node] = rpcresult[node].data
5496

    
5497
    return result
5498

    
5499

    
5500
class LUExportInstance(LogicalUnit):
5501
  """Export an instance to an image in the cluster.
5502

5503
  """
5504
  HPATH = "instance-export"
5505
  HTYPE = constants.HTYPE_INSTANCE
5506
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
5507
  REQ_BGL = False
5508

    
5509
  def ExpandNames(self):
5510
    self._ExpandAndLockInstance()
5511
    # FIXME: lock only instance primary and destination node
5512
    #
5513
    # Sad but true, for now we have do lock all nodes, as we don't know where
5514
    # the previous export might be, and and in this LU we search for it and
5515
    # remove it from its current node. In the future we could fix this by:
5516
    #  - making a tasklet to search (share-lock all), then create the new one,
5517
    #    then one to remove, after
5518
    #  - removing the removal operation altoghether
5519
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5520

    
5521
  def DeclareLocks(self, level):
5522
    """Last minute lock declaration."""
5523
    # All nodes are locked anyway, so nothing to do here.
5524

    
5525
  def BuildHooksEnv(self):
5526
    """Build hooks env.
5527

5528
    This will run on the master, primary node and target node.
5529

5530
    """
5531
    env = {
5532
      "EXPORT_NODE": self.op.target_node,
5533
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
5534
      }
5535
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5536
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node,
5537
          self.op.target_node]
5538
    return env, nl, nl
5539

    
5540
  def CheckPrereq(self):
5541
    """Check prerequisites.
5542

5543
    This checks that the instance and node names are valid.
5544

5545
    """
5546
    instance_name = self.op.instance_name
5547
    self.instance = self.cfg.GetInstanceInfo(instance_name)
5548
    assert self.instance is not None, \
5549
          "Cannot retrieve locked instance %s" % self.op.instance_name
5550
    _CheckNodeOnline(self, self.instance.primary_node)
5551

    
5552
    self.dst_node = self.cfg.GetNodeInfo(
5553
      self.cfg.ExpandNodeName(self.op.target_node))
5554

    
5555
    if self.dst_node is None:
5556
      # This is wrong node name, not a non-locked node
5557
      raise errors.OpPrereqError("Wrong node name %s" % self.op.target_node)
5558
    _CheckNodeOnline(self, self.op.target_node)
5559

    
5560
    # instance disk type verification
5561
    for disk in self.instance.disks:
5562
      if disk.dev_type == constants.LD_FILE:
5563
        raise errors.OpPrereqError("Export not supported for instances with"
5564
                                   " file-based disks")
5565

    
5566
  def Exec(self, feedback_fn):
5567
    """Export an instance to an image in the cluster.
5568

5569
    """
5570
    instance = self.instance
5571
    dst_node = self.dst_node
5572
    src_node = instance.primary_node
5573
    if self.op.shutdown:
5574
      # shutdown the instance, but not the disks
5575
      result = self.rpc.call_instance_shutdown(src_node, instance)
5576
      result.Raise()
5577
      if not result.data:
5578
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
5579
                                 (instance.name, src_node))
5580

    
5581
    vgname = self.cfg.GetVGName()
5582

    
5583
    snap_disks = []
5584

    
5585
    try:
5586
      for disk in instance.disks:
5587
        # new_dev_name will be a snapshot of an lvm leaf of the one we passed
5588
        new_dev_name = self.rpc.call_blockdev_snapshot(src_node, disk)
5589
        if new_dev_name.failed or not new_dev_name.data:
5590
          self.LogWarning("Could not snapshot block device %s on node %s",
5591
                          disk.logical_id[1], src_node)
5592
          snap_disks.append(False)
5593
        else:
5594
          new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
5595
                                 logical_id=(vgname, new_dev_name.data),
5596
                                 physical_id=(vgname, new_dev_name.data),
5597
                                 iv_name=disk.iv_name)
5598
          snap_disks.append(new_dev)
5599

    
5600
    finally:
5601
      if self.op.shutdown and instance.status == "up":
5602
        result = self.rpc.call_instance_start(src_node, instance, None)
5603
        if result.failed or not result.data:
5604
          _ShutdownInstanceDisks(self, instance)
5605
          raise errors.OpExecError("Could not start instance")
5606

    
5607
    # TODO: check for size
5608

    
5609
    cluster_name = self.cfg.GetClusterName()
5610
    for idx, dev in enumerate(snap_disks):
5611
      if dev:
5612
        result = self.rpc.call_snapshot_export(src_node, dev, dst_node.name,
5613
                                               instance, cluster_name, idx)
5614
        if result.failed or not result.data:
5615
          self.LogWarning("Could not export block device %s from node %s to"
5616
                          " node %s", dev.logical_id[1], src_node,
5617
                          dst_node.name)
5618
        result = self.rpc.call_blockdev_remove(src_node, dev)
5619
        if result.failed or not result.data:
5620
          self.LogWarning("Could not remove snapshot block device %s from node"
5621
                          " %s", dev.logical_id[1], src_node)
5622

    
5623
    result = self.rpc.call_finalize_export(dst_node.name, instance, snap_disks)
5624
    if result.failed or not result.data:
5625
      self.LogWarning("Could not finalize export for instance %s on node %s",
5626
                      instance.name, dst_node.name)
5627

    
5628
    nodelist = self.cfg.GetNodeList()
5629
    nodelist.remove(dst_node.name)
5630

    
5631
    # on one-node clusters nodelist will be empty after the removal
5632
    # if we proceed the backup would be removed because OpQueryExports
5633
    # substitutes an empty list with the full cluster node list.
5634
    if nodelist:
5635
      exportlist = self.rpc.call_export_list(nodelist)
5636
      for node in exportlist:
5637
        if exportlist[node].failed:
5638
          continue
5639
        if instance.name in exportlist[node].data:
5640
          if not self.rpc.call_export_remove(node, instance.name):
5641
            self.LogWarning("Could not remove older export for instance %s"
5642
                            " on node %s", instance.name, node)
5643

    
5644

    
5645
class LURemoveExport(NoHooksLU):
5646
  """Remove exports related to the named instance.
5647

5648
  """
5649
  _OP_REQP = ["instance_name"]
5650
  REQ_BGL = False
5651

    
5652
  def ExpandNames(self):
5653
    self.needed_locks = {}
5654
    # We need all nodes to be locked in order for RemoveExport to work, but we
5655
    # don't need to lock the instance itself, as nothing will happen to it (and
5656
    # we can remove exports also for a removed instance)
5657
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5658

    
5659
  def CheckPrereq(self):
5660
    """Check prerequisites.
5661
    """
5662
    pass
5663

    
5664
  def Exec(self, feedback_fn):
5665
    """Remove any export.
5666

5667
    """
5668
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
5669
    # If the instance was not found we'll try with the name that was passed in.
5670
    # This will only work if it was an FQDN, though.
5671
    fqdn_warn = False
5672
    if not instance_name:
5673
      fqdn_warn = True
5674
      instance_name = self.op.instance_name
5675

    
5676
    exportlist = self.rpc.call_export_list(self.acquired_locks[
5677
      locking.LEVEL_NODE])
5678
    found = False
5679
    for node in exportlist:
5680
      if exportlist[node].failed:
5681
        self.LogWarning("Failed to query node %s, continuing" % node)
5682
        continue
5683
      if instance_name in exportlist[node].data:
5684
        found = True
5685
        result = self.rpc.call_export_remove(node, instance_name)
5686
        if result.failed or not result.data:
5687
          logging.error("Could not remove export for instance %s"
5688
                        " on node %s", instance_name, node)
5689

    
5690
    if fqdn_warn and not found:
5691
      feedback_fn("Export not found. If trying to remove an export belonging"
5692
                  " to a deleted instance please use its Fully Qualified"
5693
                  " Domain Name.")
5694

    
5695

    
5696
class TagsLU(NoHooksLU):
5697
  """Generic tags LU.
5698

5699
  This is an abstract class which is the parent of all the other tags LUs.
5700

5701
  """
5702

    
5703
  def ExpandNames(self):
5704
    self.needed_locks = {}
5705
    if self.op.kind == constants.TAG_NODE:
5706
      name = self.cfg.ExpandNodeName(self.op.name)
5707
      if name is None:
5708
        raise errors.OpPrereqError("Invalid node name (%s)" %
5709
                                   (self.op.name,))
5710
      self.op.name = name
5711
      self.needed_locks[locking.LEVEL_NODE] = name
5712
    elif self.op.kind == constants.TAG_INSTANCE:
5713
      name = self.cfg.ExpandInstanceName(self.op.name)
5714
      if name is None:
5715
        raise errors.OpPrereqError("Invalid instance name (%s)" %
5716
                                   (self.op.name,))
5717
      self.op.name = name
5718
      self.needed_locks[locking.LEVEL_INSTANCE] = name
5719

    
5720
  def CheckPrereq(self):
5721
    """Check prerequisites.
5722

5723
    """
5724
    if self.op.kind == constants.TAG_CLUSTER:
5725
      self.target = self.cfg.GetClusterInfo()
5726
    elif self.op.kind == constants.TAG_NODE:
5727
      self.target = self.cfg.GetNodeInfo(self.op.name)
5728
    elif self.op.kind == constants.TAG_INSTANCE:
5729
      self.target = self.cfg.GetInstanceInfo(self.op.name)
5730
    else:
5731
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
5732
                                 str(self.op.kind))
5733

    
5734

    
5735
class LUGetTags(TagsLU):
5736
  """Returns the tags of a given object.
5737

5738
  """
5739
  _OP_REQP = ["kind", "name"]
5740
  REQ_BGL = False
5741

    
5742
  def Exec(self, feedback_fn):
5743
    """Returns the tag list.
5744

5745
    """
5746
    return list(self.target.GetTags())
5747

    
5748

    
5749
class LUSearchTags(NoHooksLU):
5750
  """Searches the tags for a given pattern.
5751

5752
  """
5753
  _OP_REQP = ["pattern"]
5754
  REQ_BGL = False
5755

    
5756
  def ExpandNames(self):
5757
    self.needed_locks = {}
5758

    
5759
  def CheckPrereq(self):
5760
    """Check prerequisites.
5761

5762
    This checks the pattern passed for validity by compiling it.
5763

5764
    """
5765
    try:
5766
      self.re = re.compile(self.op.pattern)
5767
    except re.error, err:
5768
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
5769
                                 (self.op.pattern, err))
5770

    
5771
  def Exec(self, feedback_fn):
5772
    """Returns the tag list.
5773

5774
    """
5775
    cfg = self.cfg
5776
    tgts = [("/cluster", cfg.GetClusterInfo())]
5777
    ilist = cfg.GetAllInstancesInfo().values()
5778
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
5779
    nlist = cfg.GetAllNodesInfo().values()
5780
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
5781
    results = []
5782
    for path, target in tgts:
5783
      for tag in target.GetTags():
5784
        if self.re.search(tag):
5785
          results.append((path, tag))
5786
    return results
5787

    
5788

    
5789
class LUAddTags(TagsLU):
5790
  """Sets a tag on a given object.
5791

5792
  """
5793
  _OP_REQP = ["kind", "name", "tags"]
5794
  REQ_BGL = False
5795

    
5796
  def CheckPrereq(self):
5797
    """Check prerequisites.
5798

5799
    This checks the type and length of the tag name and value.
5800

5801
    """
5802
    TagsLU.CheckPrereq(self)
5803
    for tag in self.op.tags:
5804
      objects.TaggableObject.ValidateTag(tag)
5805

    
5806
  def Exec(self, feedback_fn):
5807
    """Sets the tag.
5808

5809
    """
5810
    try:
5811
      for tag in self.op.tags:
5812
        self.target.AddTag(tag)
5813
    except errors.TagError, err:
5814
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
5815
    try:
5816
      self.cfg.Update(self.target)
5817
    except errors.ConfigurationError:
5818
      raise errors.OpRetryError("There has been a modification to the"
5819
                                " config file and the operation has been"
5820
                                " aborted. Please retry.")
5821

    
5822

    
5823
class LUDelTags(TagsLU):
5824
  """Delete a list of tags from a given object.
5825

5826
  """
5827
  _OP_REQP = ["kind", "name", "tags"]
5828
  REQ_BGL = False
5829

    
5830
  def CheckPrereq(self):
5831
    """Check prerequisites.
5832

5833
    This checks that we have the given tag.
5834

5835
    """
5836
    TagsLU.CheckPrereq(self)
5837
    for tag in self.op.tags:
5838
      objects.TaggableObject.ValidateTag(tag)
5839
    del_tags = frozenset(self.op.tags)
5840
    cur_tags = self.target.GetTags()
5841
    if not del_tags <= cur_tags:
5842
      diff_tags = del_tags - cur_tags
5843
      diff_names = ["'%s'" % tag for tag in diff_tags]
5844
      diff_names.sort()
5845
      raise errors.OpPrereqError("Tag(s) %s not found" %
5846
                                 (",".join(diff_names)))
5847

    
5848
  def Exec(self, feedback_fn):
5849
    """Remove the tag from the object.
5850

5851
    """
5852
    for tag in self.op.tags:
5853
      self.target.RemoveTag(tag)
5854
    try:
5855
      self.cfg.Update(self.target)
5856
    except errors.ConfigurationError:
5857
      raise errors.OpRetryError("There has been a modification to the"
5858
                                " config file and the operation has been"
5859
                                " aborted. Please retry.")
5860

    
5861

    
5862
class LUTestDelay(NoHooksLU):
5863
  """Sleep for a specified amount of time.
5864

5865
  This LU sleeps on the master and/or nodes for a specified amount of
5866
  time.
5867

5868
  """
5869
  _OP_REQP = ["duration", "on_master", "on_nodes"]
5870
  REQ_BGL = False
5871

    
5872
  def ExpandNames(self):
5873
    """Expand names and set required locks.
5874

5875
    This expands the node list, if any.
5876

5877
    """
5878
    self.needed_locks = {}
5879
    if self.op.on_nodes:
5880
      # _GetWantedNodes can be used here, but is not always appropriate to use
5881
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
5882
      # more information.
5883
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
5884
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
5885

    
5886
  def CheckPrereq(self):
5887
    """Check prerequisites.
5888

5889
    """
5890

    
5891
  def Exec(self, feedback_fn):
5892
    """Do the actual sleep.
5893

5894
    """
5895
    if self.op.on_master:
5896
      if not utils.TestDelay(self.op.duration):
5897
        raise errors.OpExecError("Error during master delay test")
5898
    if self.op.on_nodes:
5899
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
5900
      if not result:
5901
        raise errors.OpExecError("Complete failure from rpc call")
5902
      for node, node_result in result.items():
5903
        node_result.Raise()
5904
        if not node_result.data:
5905
          raise errors.OpExecError("Failure during rpc call to node %s,"
5906
                                   " result: %s" % (node, node_result.data))
5907

    
5908

    
5909
class IAllocator(object):
5910
  """IAllocator framework.
5911

5912
  An IAllocator instance has three sets of attributes:
5913
    - cfg that is needed to query the cluster
5914
    - input data (all members of the _KEYS class attribute are required)
5915
    - four buffer attributes (in|out_data|text), that represent the
5916
      input (to the external script) in text and data structure format,
5917
      and the output from it, again in two formats
5918
    - the result variables from the script (success, info, nodes) for
5919
      easy usage
5920

5921
  """
5922
  _ALLO_KEYS = [
5923
    "mem_size", "disks", "disk_template",
5924
    "os", "tags", "nics", "vcpus", "hypervisor",
5925
    ]
5926
  _RELO_KEYS = [
5927
    "relocate_from",
5928
    ]
5929

    
5930
  def __init__(self, lu, mode, name, **kwargs):
5931
    self.lu = lu
5932
    # init buffer variables
5933
    self.in_text = self.out_text = self.in_data = self.out_data = None
5934
    # init all input fields so that pylint is happy
5935
    self.mode = mode
5936
    self.name = name
5937
    self.mem_size = self.disks = self.disk_template = None
5938
    self.os = self.tags = self.nics = self.vcpus = None
5939
    self.hypervisor = None
5940
    self.relocate_from = None
5941
    # computed fields
5942
    self.required_nodes = None
5943
    # init result fields
5944
    self.success = self.info = self.nodes = None
5945
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
5946
      keyset = self._ALLO_KEYS
5947
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
5948
      keyset = self._RELO_KEYS
5949
    else:
5950
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
5951
                                   " IAllocator" % self.mode)
5952
    for key in kwargs:
5953
      if key not in keyset:
5954
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
5955
                                     " IAllocator" % key)
5956
      setattr(self, key, kwargs[key])
5957
    for key in keyset:
5958
      if key not in kwargs:
5959
        raise errors.ProgrammerError("Missing input parameter '%s' to"
5960
                                     " IAllocator" % key)
5961
    self._BuildInputData()
5962

    
5963
  def _ComputeClusterData(self):
5964
    """Compute the generic allocator input data.
5965

5966
    This is the data that is independent of the actual operation.
5967

5968
    """
5969
    cfg = self.lu.cfg
5970
    cluster_info = cfg.GetClusterInfo()
5971
    # cluster data
5972
    data = {
5973
      "version": 1,
5974
      "cluster_name": cfg.GetClusterName(),
5975
      "cluster_tags": list(cluster_info.GetTags()),
5976
      "enable_hypervisors": list(cluster_info.enabled_hypervisors),
5977
      # we don't have job IDs
5978
      }
5979
    iinfo = cfg.GetAllInstancesInfo().values()
5980
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
5981

    
5982
    # node data
5983
    node_results = {}
5984
    node_list = cfg.GetNodeList()
5985

    
5986
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
5987
      hypervisor_name = self.hypervisor
5988
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
5989
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
5990

    
5991
    node_data = self.lu.rpc.call_node_info(node_list, cfg.GetVGName(),
5992
                                           hypervisor_name)
5993
    node_iinfo = self.lu.rpc.call_all_instances_info(node_list,
5994
                       cluster_info.enabled_hypervisors)
5995
    for nname in node_list:
5996
      ninfo = cfg.GetNodeInfo(nname)
5997
      node_data[nname].Raise()
5998
      if not isinstance(node_data[nname].data, dict):
5999
        raise errors.OpExecError("Can't get data for node %s" % nname)
6000
      remote_info = node_data[nname].data
6001
      for attr in ['memory_total', 'memory_free', 'memory_dom0',
6002
                   'vg_size', 'vg_free', 'cpu_total']:
6003
        if attr not in remote_info:
6004
          raise errors.OpExecError("Node '%s' didn't return attribute '%s'" %
6005
                                   (nname, attr))
6006
        try:
6007
          remote_info[attr] = int(remote_info[attr])
6008
        except ValueError, err:
6009
          raise errors.OpExecError("Node '%s' returned invalid value for '%s':"
6010
                                   " %s" % (nname, attr, str(err)))
6011
      # compute memory used by primary instances
6012
      i_p_mem = i_p_up_mem = 0
6013
      for iinfo, beinfo in i_list:
6014
        if iinfo.primary_node == nname:
6015
          i_p_mem += beinfo[constants.BE_MEMORY]
6016
          if iinfo.name not in node_iinfo[nname]:
6017
            i_used_mem = 0
6018
          else:
6019
            i_used_mem = int(node_iinfo[nname][iinfo.name]['memory'])
6020
          i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
6021
          remote_info['memory_free'] -= max(0, i_mem_diff)
6022

    
6023
          if iinfo.status == "up":
6024
            i_p_up_mem += beinfo[constants.BE_MEMORY]
6025

    
6026
      # compute memory used by instances
6027
      pnr = {
6028
        "tags": list(ninfo.GetTags()),
6029
        "total_memory": remote_info['memory_total'],
6030
        "reserved_memory": remote_info['memory_dom0'],
6031
        "free_memory": remote_info['memory_free'],
6032
        "i_pri_memory": i_p_mem,
6033
        "i_pri_up_memory": i_p_up_mem,
6034
        "total_disk": remote_info['vg_size'],
6035
        "free_disk": remote_info['vg_free'],
6036
        "primary_ip": ninfo.primary_ip,
6037
        "secondary_ip": ninfo.secondary_ip,
6038
        "total_cpus": remote_info['cpu_total'],
6039
        "offline": ninfo.offline,
6040
        }
6041
      node_results[nname] = pnr
6042
    data["nodes"] = node_results
6043

    
6044
    # instance data
6045
    instance_data = {}
6046
    for iinfo, beinfo in i_list:
6047
      nic_data = [{"mac": n.mac, "ip": n.ip, "bridge": n.bridge}
6048
                  for n in iinfo.nics]
6049
      pir = {
6050
        "tags": list(iinfo.GetTags()),
6051
        "should_run": iinfo.status == "up",
6052
        "vcpus": beinfo[constants.BE_VCPUS],
6053
        "memory": beinfo[constants.BE_MEMORY],
6054
        "os": iinfo.os,
6055
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
6056
        "nics": nic_data,
6057
        "disks": [{"size": dsk.size, "mode": "w"} for dsk in iinfo.disks],
6058
        "disk_template": iinfo.disk_template,
6059
        "hypervisor": iinfo.hypervisor,
6060
        }
6061
      instance_data[iinfo.name] = pir
6062

    
6063
    data["instances"] = instance_data
6064

    
6065
    self.in_data = data
6066

    
6067
  def _AddNewInstance(self):
6068
    """Add new instance data to allocator structure.
6069

6070
    This in combination with _AllocatorGetClusterData will create the
6071
    correct structure needed as input for the allocator.
6072

6073
    The checks for the completeness of the opcode must have already been
6074
    done.
6075

6076
    """
6077
    data = self.in_data
6078
    if len(self.disks) != 2:
6079
      raise errors.OpExecError("Only two-disk configurations supported")
6080

    
6081
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
6082

    
6083
    if self.disk_template in constants.DTS_NET_MIRROR:
6084
      self.required_nodes = 2
6085
    else:
6086
      self.required_nodes = 1
6087
    request = {
6088
      "type": "allocate",
6089
      "name": self.name,
6090
      "disk_template": self.disk_template,
6091
      "tags": self.tags,
6092
      "os": self.os,
6093
      "vcpus": self.vcpus,
6094
      "memory": self.mem_size,
6095
      "disks": self.disks,
6096
      "disk_space_total": disk_space,
6097
      "nics": self.nics,
6098
      "required_nodes": self.required_nodes,
6099
      }
6100
    data["request"] = request
6101

    
6102
  def _AddRelocateInstance(self):
6103
    """Add relocate instance data to allocator structure.
6104

6105
    This in combination with _IAllocatorGetClusterData will create the
6106
    correct structure needed as input for the allocator.
6107

6108
    The checks for the completeness of the opcode must have already been
6109
    done.
6110

6111
    """
6112
    instance = self.lu.cfg.GetInstanceInfo(self.name)
6113
    if instance is None:
6114
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
6115
                                   " IAllocator" % self.name)
6116

    
6117
    if instance.disk_template not in constants.DTS_NET_MIRROR:
6118
      raise errors.OpPrereqError("Can't relocate non-mirrored instances")
6119

    
6120
    if len(instance.secondary_nodes) != 1:
6121
      raise errors.OpPrereqError("Instance has not exactly one secondary node")
6122

    
6123
    self.required_nodes = 1
6124
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
6125
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
6126

    
6127
    request = {
6128
      "type": "relocate",
6129
      "name": self.name,
6130
      "disk_space_total": disk_space,
6131
      "required_nodes": self.required_nodes,
6132
      "relocate_from": self.relocate_from,
6133
      }
6134
    self.in_data["request"] = request
6135

    
6136
  def _BuildInputData(self):
6137
    """Build input data structures.
6138

6139
    """
6140
    self._ComputeClusterData()
6141

    
6142
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6143
      self._AddNewInstance()
6144
    else:
6145
      self._AddRelocateInstance()
6146

    
6147
    self.in_text = serializer.Dump(self.in_data)
6148

    
6149
  def Run(self, name, validate=True, call_fn=None):
6150
    """Run an instance allocator and return the results.
6151

6152
    """
6153
    if call_fn is None:
6154
      call_fn = self.lu.rpc.call_iallocator_runner
6155
    data = self.in_text
6156

    
6157
    result = call_fn(self.lu.cfg.GetMasterNode(), name, self.in_text)
6158
    result.Raise()
6159

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

    
6163
    rcode, stdout, stderr, fail = result.data
6164

    
6165
    if rcode == constants.IARUN_NOTFOUND:
6166
      raise errors.OpExecError("Can't find allocator '%s'" % name)
6167
    elif rcode == constants.IARUN_FAILURE:
6168
      raise errors.OpExecError("Instance allocator call failed: %s,"
6169
                               " output: %s" % (fail, stdout+stderr))
6170
    self.out_text = stdout
6171
    if validate:
6172
      self._ValidateResult()
6173

    
6174
  def _ValidateResult(self):
6175
    """Process the allocator results.
6176

6177
    This will process and if successful save the result in
6178
    self.out_data and the other parameters.
6179

6180
    """
6181
    try:
6182
      rdict = serializer.Load(self.out_text)
6183
    except Exception, err:
6184
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
6185

    
6186
    if not isinstance(rdict, dict):
6187
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
6188

    
6189
    for key in "success", "info", "nodes":
6190
      if key not in rdict:
6191
        raise errors.OpExecError("Can't parse iallocator results:"
6192
                                 " missing key '%s'" % key)
6193
      setattr(self, key, rdict[key])
6194

    
6195
    if not isinstance(rdict["nodes"], list):
6196
      raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
6197
                               " is not a list")
6198
    self.out_data = rdict
6199

    
6200

    
6201
class LUTestAllocator(NoHooksLU):
6202
  """Run allocator tests.
6203

6204
  This LU runs the allocator tests
6205

6206
  """
6207
  _OP_REQP = ["direction", "mode", "name"]
6208

    
6209
  def CheckPrereq(self):
6210
    """Check prerequisites.
6211

6212
    This checks the opcode parameters depending on the director and mode test.
6213

6214
    """
6215
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
6216
      for attr in ["name", "mem_size", "disks", "disk_template",
6217
                   "os", "tags", "nics", "vcpus"]:
6218
        if not hasattr(self.op, attr):
6219
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
6220
                                     attr)
6221
      iname = self.cfg.ExpandInstanceName(self.op.name)
6222
      if iname is not None:
6223
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
6224
                                   iname)
6225
      if not isinstance(self.op.nics, list):
6226
        raise errors.OpPrereqError("Invalid parameter 'nics'")
6227
      for row in self.op.nics:
6228
        if (not isinstance(row, dict) or
6229
            "mac" not in row or
6230
            "ip" not in row or
6231
            "bridge" not in row):
6232
          raise errors.OpPrereqError("Invalid contents of the"
6233
                                     " 'nics' parameter")
6234
      if not isinstance(self.op.disks, list):
6235
        raise errors.OpPrereqError("Invalid parameter 'disks'")
6236
      if len(self.op.disks) != 2:
6237
        raise errors.OpPrereqError("Only two-disk configurations supported")
6238
      for row in self.op.disks:
6239
        if (not isinstance(row, dict) or
6240
            "size" not in row or
6241
            not isinstance(row["size"], int) or
6242
            "mode" not in row or
6243
            row["mode"] not in ['r', 'w']):
6244
          raise errors.OpPrereqError("Invalid contents of the"
6245
                                     " 'disks' parameter")
6246
      if self.op.hypervisor is None:
6247
        self.op.hypervisor = self.cfg.GetHypervisorType()
6248
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
6249
      if not hasattr(self.op, "name"):
6250
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input")
6251
      fname = self.cfg.ExpandInstanceName(self.op.name)
6252
      if fname is None:
6253
        raise errors.OpPrereqError("Instance '%s' not found for relocation" %
6254
                                   self.op.name)
6255
      self.op.name = fname
6256
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
6257
    else:
6258
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
6259
                                 self.op.mode)
6260

    
6261
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
6262
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
6263
        raise errors.OpPrereqError("Missing allocator name")
6264
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
6265
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
6266
                                 self.op.direction)
6267

    
6268
  def Exec(self, feedback_fn):
6269
    """Run the allocator test.
6270

6271
    """
6272
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
6273
      ial = IAllocator(self,
6274
                       mode=self.op.mode,
6275
                       name=self.op.name,
6276
                       mem_size=self.op.mem_size,
6277
                       disks=self.op.disks,
6278
                       disk_template=self.op.disk_template,
6279
                       os=self.op.os,
6280
                       tags=self.op.tags,
6281
                       nics=self.op.nics,
6282
                       vcpus=self.op.vcpus,
6283
                       hypervisor=self.op.hypervisor,
6284
                       )
6285
    else:
6286
      ial = IAllocator(self,
6287
                       mode=self.op.mode,
6288
                       name=self.op.name,
6289
                       relocate_from=list(self.relocate_from),
6290
                       )
6291

    
6292
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
6293
      result = ial.in_text
6294
    else:
6295
      ial.Run(self.op.allocator, validate=False)
6296
      result = ial.out_text
6297
    return result