Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 22f0f71d

History | View | Annotate | Download (234.7 kB)

1
#
2
#
3

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

    
21

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

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

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

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

    
48

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

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

61
  Note that all commands require root permissions.
62

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

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

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

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

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

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

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

    
109
  ssh = property(fget=__GetSSH)
110

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

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

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

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

126
    """
127
    pass
128

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

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

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

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

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

150
    Examples::
151

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

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

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

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

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

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

189
    """
190

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

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

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

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

205
    """
206
    raise NotImplementedError
207

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

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

215
    """
216
    raise NotImplementedError
217

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

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

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

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

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

237
    """
238
    raise NotImplementedError
239

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

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

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

258
    """
259
    return lu_result
260

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
326
    del self.recalculate_locks[locking.LEVEL_NODE]
327

    
328

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

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

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

    
339

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

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

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

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

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

    
366
  return utils.NiceSort(wanted)
367

    
368

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

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

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

    
385
  if instances:
386
    wanted = []
387

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

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

    
398

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

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

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

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

    
417

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

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

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

    
431

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

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

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

    
443

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

448
  This builds the hook environment from individual variables.
449

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

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

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

    
497
  env["INSTANCE_NIC_COUNT"] = nic_count
498

    
499
  return env
500

    
501

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

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

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

    
532

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

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

    
548

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

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

    
562

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

566
  """
567
  _OP_REQP = []
568

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

572
    This checks whether the cluster is empty.
573

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

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

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

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

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

    
602

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

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

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

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

624
    Test list:
625

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

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

642
    """
643
    node = nodeinfo.name
644

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

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

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

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

    
665
    bad = False
666

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

    
673
    # checks vg existence and size > 20G
674

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

    
687
    # checks config file checksum
688

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

    
716
    # checks ssh to any
717

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

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

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

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

    
758
    return bad
759

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

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

767
    """
768
    bad = False
769

    
770
    node_current = instanceconfig.primary_node
771

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

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

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

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

    
800
    return bad
801

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

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

808
    """
809
    bad = False
810

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

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

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

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

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

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

840
    """
841
    bad = False
842

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

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

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

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

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

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

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

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

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

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

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

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

    
921
    local_checksums = utils.FingerprintFiles(file_names)
922

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

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

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

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

    
955
      if node == master_node:
956
        ntype = "master"
957
      elif node_i.master_candidate:
958
        ntype = "master candidate"
959
      elif node_i.drained:
960
        ntype = "drained"
961
        n_drained.append(node)
962
      else:
963
        ntype = "regular"
964
      feedback_fn("* Verifying node %s (%s)" % (node, ntype))
965

    
966
      if all_nvinfo[node].failed or not isinstance(nresult, dict):
967
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
968
        bad = True
969
        continue
970

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

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

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

    
1001
      node_instance[node] = idata
1002

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

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

    
1029
    node_vol_should = {}
1030

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

    
1039
      inst_config.MapLVsByNode(node_vol_should)
1040

    
1041
      instance_cfg[instance] = inst_config
1042

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

    
1051
      if pnode in n_offline:
1052
        inst_nodes_offline.append(pnode)
1053

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

    
1065
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1066
        i_non_a_balanced.append(instance)
1067

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

    
1081
      if inst_nodes_offline:
1082
        # warn that the instance lives on offline nodes, and set bad=True
1083
        feedback_fn("  - ERROR: instance lives on offline node(s) %s" %
1084
                    ", ".join(inst_nodes_offline))
1085
        bad = True
1086

    
1087
    feedback_fn("* Verifying orphan volumes")
1088
    result = self._VerifyOrphanVolumes(node_vol_should, node_volume,
1089
                                       feedback_fn)
1090
    bad = bad or result
1091

    
1092
    feedback_fn("* Verifying remaining instances")
1093
    result = self._VerifyOrphanInstances(instancelist, node_instance,
1094
                                         feedback_fn)
1095
    bad = bad or result
1096

    
1097
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1098
      feedback_fn("* Verifying N+1 Memory redundancy")
1099
      result = self._VerifyNPlusOneMemory(node_info, instance_cfg, feedback_fn)
1100
      bad = bad or result
1101

    
1102
    feedback_fn("* Other Notes")
1103
    if i_non_redundant:
1104
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1105
                  % len(i_non_redundant))
1106

    
1107
    if i_non_a_balanced:
1108
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1109
                  % len(i_non_a_balanced))
1110

    
1111
    if n_offline:
1112
      feedback_fn("  - NOTICE: %d offline node(s) found." % len(n_offline))
1113

    
1114
    if n_drained:
1115
      feedback_fn("  - NOTICE: %d drained node(s) found." % len(n_drained))
1116

    
1117
    return not bad
1118

    
1119
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1120
    """Analize the post-hooks' result
1121

1122
    This method analyses the hook result, handles it, and sends some
1123
    nicely-formatted feedback back to the user.
1124

1125
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1126
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1127
    @param hooks_results: the results of the multi-node hooks rpc call
1128
    @param feedback_fn: function used send feedback back to the caller
1129
    @param lu_result: previous Exec result
1130
    @return: the new Exec result, based on the previous result
1131
        and hook results
1132

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

    
1166
      return lu_result
1167

    
1168

    
1169
class LUVerifyDisks(NoHooksLU):
1170
  """Verifies the cluster disks status.
1171

1172
  """
1173
  _OP_REQP = []
1174
  REQ_BGL = False
1175

    
1176
  def ExpandNames(self):
1177
    self.needed_locks = {
1178
      locking.LEVEL_NODE: locking.ALL_SET,
1179
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1180
    }
1181
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
1182

    
1183
  def CheckPrereq(self):
1184
    """Check prerequisites.
1185

1186
    This has no prerequisites.
1187

1188
    """
1189
    pass
1190

    
1191
  def Exec(self, feedback_fn):
1192
    """Verify integrity of cluster disks.
1193

1194
    """
1195
    result = res_nodes, res_nlvm, res_instances, res_missing = [], {}, [], {}
1196

    
1197
    vg_name = self.cfg.GetVGName()
1198
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1199
    instances = [self.cfg.GetInstanceInfo(name)
1200
                 for name in self.cfg.GetInstanceList()]
1201

    
1202
    nv_dict = {}
1203
    for inst in instances:
1204
      inst_lvs = {}
1205
      if (not inst.admin_up or
1206
          inst.disk_template not in constants.DTS_NET_MIRROR):
1207
        continue
1208
      inst.MapLVsByNode(inst_lvs)
1209
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1210
      for node, vol_list in inst_lvs.iteritems():
1211
        for vol in vol_list:
1212
          nv_dict[(node, vol)] = inst
1213

    
1214
    if not nv_dict:
1215
      return result
1216

    
1217
    node_lvs = self.rpc.call_volume_list(nodes, vg_name)
1218

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

    
1238
      for lv_name, (_, lv_inactive, lv_online) in lvs.iteritems():
1239
        inst = nv_dict.pop((node, lv_name), None)
1240
        if (not lv_online and inst is not None
1241
            and inst.name not in res_instances):
1242
          res_instances.append(inst.name)
1243

    
1244
    # any leftover items in nv_dict are missing LVs, let's arrange the
1245
    # data better
1246
    for key, inst in nv_dict.iteritems():
1247
      if inst.name not in res_missing:
1248
        res_missing[inst.name] = []
1249
      res_missing[inst.name].append(key)
1250

    
1251
    return result
1252

    
1253

    
1254
class LURenameCluster(LogicalUnit):
1255
  """Rename the cluster.
1256

1257
  """
1258
  HPATH = "cluster-rename"
1259
  HTYPE = constants.HTYPE_CLUSTER
1260
  _OP_REQP = ["name"]
1261

    
1262
  def BuildHooksEnv(self):
1263
    """Build hooks env.
1264

1265
    """
1266
    env = {
1267
      "OP_TARGET": self.cfg.GetClusterName(),
1268
      "NEW_NAME": self.op.name,
1269
      }
1270
    mn = self.cfg.GetMasterNode()
1271
    return env, [mn], [mn]
1272

    
1273
  def CheckPrereq(self):
1274
    """Verify that the passed name is a valid one.
1275

1276
    """
1277
    hostname = utils.HostInfo(self.op.name)
1278

    
1279
    new_name = hostname.name
1280
    self.ip = new_ip = hostname.ip
1281
    old_name = self.cfg.GetClusterName()
1282
    old_ip = self.cfg.GetMasterIP()
1283
    if new_name == old_name and new_ip == old_ip:
1284
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1285
                                 " cluster has changed")
1286
    if new_ip != old_ip:
1287
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1288
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1289
                                   " reachable on the network. Aborting." %
1290
                                   new_ip)
1291

    
1292
    self.op.name = new_name
1293

    
1294
  def Exec(self, feedback_fn):
1295
    """Rename the cluster.
1296

1297
    """
1298
    clustername = self.op.name
1299
    ip = self.ip
1300

    
1301
    # shutdown the master IP
1302
    master = self.cfg.GetMasterNode()
1303
    result = self.rpc.call_node_stop_master(master, False)
1304
    if result.failed or not result.data:
1305
      raise errors.OpExecError("Could not disable the master role")
1306

    
1307
    try:
1308
      cluster = self.cfg.GetClusterInfo()
1309
      cluster.cluster_name = clustername
1310
      cluster.master_ip = ip
1311
      self.cfg.Update(cluster)
1312

    
1313
      # update the known hosts file
1314
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
1315
      node_list = self.cfg.GetNodeList()
1316
      try:
1317
        node_list.remove(master)
1318
      except ValueError:
1319
        pass
1320
      result = self.rpc.call_upload_file(node_list,
1321
                                         constants.SSH_KNOWN_HOSTS_FILE)
1322
      for to_node, to_result in result.iteritems():
1323
        if to_result.failed or not to_result.data:
1324
          logging.error("Copy of file %s to node %s failed",
1325
                        constants.SSH_KNOWN_HOSTS_FILE, to_node)
1326

    
1327
    finally:
1328
      result = self.rpc.call_node_start_master(master, False)
1329
      if result.failed or not result.data:
1330
        self.LogWarning("Could not re-enable the master role on"
1331
                        " the master, please restart manually.")
1332

    
1333

    
1334
def _RecursiveCheckIfLVMBased(disk):
1335
  """Check if the given disk or its children are lvm-based.
1336

1337
  @type disk: L{objects.Disk}
1338
  @param disk: the disk to check
1339
  @rtype: booleean
1340
  @return: boolean indicating whether a LD_LV dev_type was found or not
1341

1342
  """
1343
  if disk.children:
1344
    for chdisk in disk.children:
1345
      if _RecursiveCheckIfLVMBased(chdisk):
1346
        return True
1347
  return disk.dev_type == constants.LD_LV
1348

    
1349

    
1350
class LUSetClusterParams(LogicalUnit):
1351
  """Change the parameters of the cluster.
1352

1353
  """
1354
  HPATH = "cluster-modify"
1355
  HTYPE = constants.HTYPE_CLUSTER
1356
  _OP_REQP = []
1357
  REQ_BGL = False
1358

    
1359
  def CheckParameters(self):
1360
    """Check parameters
1361

1362
    """
1363
    if not hasattr(self.op, "candidate_pool_size"):
1364
      self.op.candidate_pool_size = None
1365
    if self.op.candidate_pool_size is not None:
1366
      try:
1367
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
1368
      except ValueError, err:
1369
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
1370
                                   str(err))
1371
      if self.op.candidate_pool_size < 1:
1372
        raise errors.OpPrereqError("At least one master candidate needed")
1373

    
1374
  def ExpandNames(self):
1375
    # FIXME: in the future maybe other cluster params won't require checking on
1376
    # all nodes to be modified.
1377
    self.needed_locks = {
1378
      locking.LEVEL_NODE: locking.ALL_SET,
1379
    }
1380
    self.share_locks[locking.LEVEL_NODE] = 1
1381

    
1382
  def BuildHooksEnv(self):
1383
    """Build hooks env.
1384

1385
    """
1386
    env = {
1387
      "OP_TARGET": self.cfg.GetClusterName(),
1388
      "NEW_VG_NAME": self.op.vg_name,
1389
      }
1390
    mn = self.cfg.GetMasterNode()
1391
    return env, [mn], [mn]
1392

    
1393
  def CheckPrereq(self):
1394
    """Check prerequisites.
1395

1396
    This checks whether the given params don't conflict and
1397
    if the given volume group is valid.
1398

1399
    """
1400
    # FIXME: This only works because there is only one parameter that can be
1401
    # changed or removed.
1402
    if self.op.vg_name is not None and not self.op.vg_name:
1403
      instances = self.cfg.GetAllInstancesInfo().values()
1404
      for inst in instances:
1405
        for disk in inst.disks:
1406
          if _RecursiveCheckIfLVMBased(disk):
1407
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1408
                                       " lvm-based instances exist")
1409

    
1410
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1411

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

    
1427
    self.cluster = cluster = self.cfg.GetClusterInfo()
1428
    # validate beparams changes
1429
    if self.op.beparams:
1430
      utils.CheckBEParams(self.op.beparams)
1431
      self.new_beparams = cluster.FillDict(
1432
        cluster.beparams[constants.BEGR_DEFAULT], self.op.beparams)
1433

    
1434
    # hypervisor list/parameters
1435
    self.new_hvparams = cluster.FillDict(cluster.hvparams, {})
1436
    if self.op.hvparams:
1437
      if not isinstance(self.op.hvparams, dict):
1438
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input")
1439
      for hv_name, hv_dict in self.op.hvparams.items():
1440
        if hv_name not in self.new_hvparams:
1441
          self.new_hvparams[hv_name] = hv_dict
1442
        else:
1443
          self.new_hvparams[hv_name].update(hv_dict)
1444

    
1445
    if self.op.enabled_hypervisors is not None:
1446
      self.hv_list = self.op.enabled_hypervisors
1447
    else:
1448
      self.hv_list = cluster.enabled_hypervisors
1449

    
1450
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
1451
      # either the enabled list has changed, or the parameters have, validate
1452
      for hv_name, hv_params in self.new_hvparams.items():
1453
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
1454
            (self.op.enabled_hypervisors and
1455
             hv_name in self.op.enabled_hypervisors)):
1456
          # either this is a new hypervisor, or its parameters have changed
1457
          hv_class = hypervisor.GetHypervisor(hv_name)
1458
          hv_class.CheckParameterSyntax(hv_params)
1459
          _CheckHVParams(self, node_list, hv_name, hv_params)
1460

    
1461
  def Exec(self, feedback_fn):
1462
    """Change the parameters of the cluster.
1463

1464
    """
1465
    if self.op.vg_name is not None:
1466
      if self.op.vg_name != self.cfg.GetVGName():
1467
        self.cfg.SetVGName(self.op.vg_name)
1468
      else:
1469
        feedback_fn("Cluster LVM configuration already in desired"
1470
                    " state, not changing")
1471
    if self.op.hvparams:
1472
      self.cluster.hvparams = self.new_hvparams
1473
    if self.op.enabled_hypervisors is not None:
1474
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
1475
    if self.op.beparams:
1476
      self.cluster.beparams[constants.BEGR_DEFAULT] = self.new_beparams
1477
    if self.op.candidate_pool_size is not None:
1478
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
1479

    
1480
    self.cfg.Update(self.cluster)
1481

    
1482
    # we want to update nodes after the cluster so that if any errors
1483
    # happen, we have recorded and saved the cluster info
1484
    if self.op.candidate_pool_size is not None:
1485
      _AdjustCandidatePool(self)
1486

    
1487

    
1488
class LURedistributeConfig(NoHooksLU):
1489
  """Force the redistribution of cluster configuration.
1490

1491
  This is a very simple LU.
1492

1493
  """
1494
  _OP_REQP = []
1495
  REQ_BGL = False
1496

    
1497
  def ExpandNames(self):
1498
    self.needed_locks = {
1499
      locking.LEVEL_NODE: locking.ALL_SET,
1500
    }
1501
    self.share_locks[locking.LEVEL_NODE] = 1
1502

    
1503
  def CheckPrereq(self):
1504
    """Check prerequisites.
1505

1506
    """
1507

    
1508
  def Exec(self, feedback_fn):
1509
    """Redistribute the configuration.
1510

1511
    """
1512
    self.cfg.Update(self.cfg.GetClusterInfo())
1513

    
1514

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

1518
  """
1519
  if not instance.disks:
1520
    return True
1521

    
1522
  if not oneshot:
1523
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
1524

    
1525
  node = instance.primary_node
1526

    
1527
  for dev in instance.disks:
1528
    lu.cfg.SetDiskID(dev, node)
1529

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

    
1566
    time.sleep(min(60, max_time))
1567

    
1568
  if done:
1569
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
1570
  return not cumul_degraded
1571

    
1572

    
1573
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
1574
  """Check that mirrors are not degraded.
1575

1576
  The ldisk parameter, if True, will change the test from the
1577
  is_degraded attribute (which represents overall non-ok status for
1578
  the device(s)) to the ldisk (representing the local storage status).
1579

1580
  """
1581
  lu.cfg.SetDiskID(dev, node)
1582
  if ldisk:
1583
    idx = 6
1584
  else:
1585
    idx = 5
1586

    
1587
  result = True
1588
  if on_primary or dev.AssembleOnSecondary():
1589
    rstats = lu.rpc.call_blockdev_find(node, dev)
1590
    msg = rstats.RemoteFailMsg()
1591
    if msg:
1592
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
1593
      result = False
1594
    elif not rstats.payload:
1595
      lu.LogWarning("Can't find disk on node %s", node)
1596
      result = False
1597
    else:
1598
      result = result and (not rstats.payload[idx])
1599
  if dev.children:
1600
    for child in dev.children:
1601
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
1602

    
1603
  return result
1604

    
1605

    
1606
class LUDiagnoseOS(NoHooksLU):
1607
  """Logical unit for OS diagnose/query.
1608

1609
  """
1610
  _OP_REQP = ["output_fields", "names"]
1611
  REQ_BGL = False
1612
  _FIELDS_STATIC = utils.FieldSet()
1613
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status")
1614

    
1615
  def ExpandNames(self):
1616
    if self.op.names:
1617
      raise errors.OpPrereqError("Selective OS query not supported")
1618

    
1619
    _CheckOutputFields(static=self._FIELDS_STATIC,
1620
                       dynamic=self._FIELDS_DYNAMIC,
1621
                       selected=self.op.output_fields)
1622

    
1623
    # Lock all nodes, in shared mode
1624
    self.needed_locks = {}
1625
    self.share_locks[locking.LEVEL_NODE] = 1
1626
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1627

    
1628
  def CheckPrereq(self):
1629
    """Check prerequisites.
1630

1631
    """
1632

    
1633
  @staticmethod
1634
  def _DiagnoseByOS(node_list, rlist):
1635
    """Remaps a per-node return list into an a per-os per-node dictionary
1636

1637
    @param node_list: a list with the names of all nodes
1638
    @param rlist: a map with node names as keys and OS objects as values
1639

1640
    @rtype: dict
1641
    @returns: a dictionary with osnames as keys and as value another map, with
1642
        nodes as keys and list of OS objects as values, eg::
1643

1644
          {"debian-etch": {"node1": [<object>,...],
1645
                           "node2": [<object>,]}
1646
          }
1647

1648
    """
1649
    all_os = {}
1650
    for node_name, nr in rlist.iteritems():
1651
      if nr.failed or not nr.data:
1652
        continue
1653
      for os_obj in nr.data:
1654
        if os_obj.name not in all_os:
1655
          # build a list of nodes for this os containing empty lists
1656
          # for each node in node_list
1657
          all_os[os_obj.name] = {}
1658
          for nname in node_list:
1659
            all_os[os_obj.name][nname] = []
1660
        all_os[os_obj.name][node_name].append(os_obj)
1661
    return all_os
1662

    
1663
  def Exec(self, feedback_fn):
1664
    """Compute the list of OSes.
1665

1666
    """
1667
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1668
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()
1669
                   if node in node_list]
1670
    node_data = self.rpc.call_os_diagnose(valid_nodes)
1671
    if node_data == False:
1672
      raise errors.OpExecError("Can't gather the list of OSes")
1673
    pol = self._DiagnoseByOS(valid_nodes, node_data)
1674
    output = []
1675
    for os_name, os_data in pol.iteritems():
1676
      row = []
1677
      for field in self.op.output_fields:
1678
        if field == "name":
1679
          val = os_name
1680
        elif field == "valid":
1681
          val = utils.all([osl and osl[0] for osl in os_data.values()])
1682
        elif field == "node_status":
1683
          val = {}
1684
          for node_name, nos_list in os_data.iteritems():
1685
            val[node_name] = [(v.status, v.path) for v in nos_list]
1686
        else:
1687
          raise errors.ParameterError(field)
1688
        row.append(val)
1689
      output.append(row)
1690

    
1691
    return output
1692

    
1693

    
1694
class LURemoveNode(LogicalUnit):
1695
  """Logical unit for removing a node.
1696

1697
  """
1698
  HPATH = "node-remove"
1699
  HTYPE = constants.HTYPE_NODE
1700
  _OP_REQP = ["node_name"]
1701

    
1702
  def BuildHooksEnv(self):
1703
    """Build hooks env.
1704

1705
    This doesn't run on the target node in the pre phase as a failed
1706
    node would then be impossible to remove.
1707

1708
    """
1709
    env = {
1710
      "OP_TARGET": self.op.node_name,
1711
      "NODE_NAME": self.op.node_name,
1712
      }
1713
    all_nodes = self.cfg.GetNodeList()
1714
    all_nodes.remove(self.op.node_name)
1715
    return env, all_nodes, all_nodes
1716

    
1717
  def CheckPrereq(self):
1718
    """Check prerequisites.
1719

1720
    This checks:
1721
     - the node exists in the configuration
1722
     - it does not have primary or secondary instances
1723
     - it's not the master
1724

1725
    Any errors are signalled by raising errors.OpPrereqError.
1726

1727
    """
1728
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
1729
    if node is None:
1730
      raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name)
1731

    
1732
    instance_list = self.cfg.GetInstanceList()
1733

    
1734
    masternode = self.cfg.GetMasterNode()
1735
    if node.name == masternode:
1736
      raise errors.OpPrereqError("Node is the master node,"
1737
                                 " you need to failover first.")
1738

    
1739
    for instance_name in instance_list:
1740
      instance = self.cfg.GetInstanceInfo(instance_name)
1741
      if node.name in instance.all_nodes:
1742
        raise errors.OpPrereqError("Instance %s is still running on the node,"
1743
                                   " please remove first." % instance_name)
1744
    self.op.node_name = node.name
1745
    self.node = node
1746

    
1747
  def Exec(self, feedback_fn):
1748
    """Removes the node from the cluster.
1749

1750
    """
1751
    node = self.node
1752
    logging.info("Stopping the node daemon and removing configs from node %s",
1753
                 node.name)
1754

    
1755
    self.context.RemoveNode(node.name)
1756

    
1757
    self.rpc.call_node_leave_cluster(node.name)
1758

    
1759
    # Promote nodes to master candidate as needed
1760
    _AdjustCandidatePool(self)
1761

    
1762

    
1763
class LUQueryNodes(NoHooksLU):
1764
  """Logical unit for querying nodes.
1765

1766
  """
1767
  _OP_REQP = ["output_fields", "names", "use_locking"]
1768
  REQ_BGL = False
1769
  _FIELDS_DYNAMIC = utils.FieldSet(
1770
    "dtotal", "dfree",
1771
    "mtotal", "mnode", "mfree",
1772
    "bootid",
1773
    "ctotal", "cnodes", "csockets",
1774
    )
1775

    
1776
  _FIELDS_STATIC = utils.FieldSet(
1777
    "name", "pinst_cnt", "sinst_cnt",
1778
    "pinst_list", "sinst_list",
1779
    "pip", "sip", "tags",
1780
    "serial_no",
1781
    "master_candidate",
1782
    "master",
1783
    "offline",
1784
    "drained",
1785
    )
1786

    
1787
  def ExpandNames(self):
1788
    _CheckOutputFields(static=self._FIELDS_STATIC,
1789
                       dynamic=self._FIELDS_DYNAMIC,
1790
                       selected=self.op.output_fields)
1791

    
1792
    self.needed_locks = {}
1793
    self.share_locks[locking.LEVEL_NODE] = 1
1794

    
1795
    if self.op.names:
1796
      self.wanted = _GetWantedNodes(self, self.op.names)
1797
    else:
1798
      self.wanted = locking.ALL_SET
1799

    
1800
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
1801
    self.do_locking = self.do_node_query and self.op.use_locking
1802
    if self.do_locking:
1803
      # if we don't request only static fields, we need to lock the nodes
1804
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
1805

    
1806

    
1807
  def CheckPrereq(self):
1808
    """Check prerequisites.
1809

1810
    """
1811
    # The validation of the node list is done in the _GetWantedNodes,
1812
    # if non empty, and if empty, there's no validation to do
1813
    pass
1814

    
1815
  def Exec(self, feedback_fn):
1816
    """Computes the list of nodes and their attributes.
1817

1818
    """
1819
    all_info = self.cfg.GetAllNodesInfo()
1820
    if self.do_locking:
1821
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
1822
    elif self.wanted != locking.ALL_SET:
1823
      nodenames = self.wanted
1824
      missing = set(nodenames).difference(all_info.keys())
1825
      if missing:
1826
        raise errors.OpExecError(
1827
          "Some nodes were removed before retrieving their data: %s" % missing)
1828
    else:
1829
      nodenames = all_info.keys()
1830

    
1831
    nodenames = utils.NiceSort(nodenames)
1832
    nodelist = [all_info[name] for name in nodenames]
1833

    
1834
    # begin data gathering
1835

    
1836
    if self.do_node_query:
1837
      live_data = {}
1838
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
1839
                                          self.cfg.GetHypervisorType())
1840
      for name in nodenames:
1841
        nodeinfo = node_data[name]
1842
        if not nodeinfo.failed and nodeinfo.data:
1843
          nodeinfo = nodeinfo.data
1844
          fn = utils.TryConvert
1845
          live_data[name] = {
1846
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
1847
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
1848
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
1849
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
1850
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
1851
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
1852
            "bootid": nodeinfo.get('bootid', None),
1853
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
1854
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
1855
            }
1856
        else:
1857
          live_data[name] = {}
1858
    else:
1859
      live_data = dict.fromkeys(nodenames, {})
1860

    
1861
    node_to_primary = dict([(name, set()) for name in nodenames])
1862
    node_to_secondary = dict([(name, set()) for name in nodenames])
1863

    
1864
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
1865
                             "sinst_cnt", "sinst_list"))
1866
    if inst_fields & frozenset(self.op.output_fields):
1867
      instancelist = self.cfg.GetInstanceList()
1868

    
1869
      for instance_name in instancelist:
1870
        inst = self.cfg.GetInstanceInfo(instance_name)
1871
        if inst.primary_node in node_to_primary:
1872
          node_to_primary[inst.primary_node].add(inst.name)
1873
        for secnode in inst.secondary_nodes:
1874
          if secnode in node_to_secondary:
1875
            node_to_secondary[secnode].add(inst.name)
1876

    
1877
    master_node = self.cfg.GetMasterNode()
1878

    
1879
    # end data gathering
1880

    
1881
    output = []
1882
    for node in nodelist:
1883
      node_output = []
1884
      for field in self.op.output_fields:
1885
        if field == "name":
1886
          val = node.name
1887
        elif field == "pinst_list":
1888
          val = list(node_to_primary[node.name])
1889
        elif field == "sinst_list":
1890
          val = list(node_to_secondary[node.name])
1891
        elif field == "pinst_cnt":
1892
          val = len(node_to_primary[node.name])
1893
        elif field == "sinst_cnt":
1894
          val = len(node_to_secondary[node.name])
1895
        elif field == "pip":
1896
          val = node.primary_ip
1897
        elif field == "sip":
1898
          val = node.secondary_ip
1899
        elif field == "tags":
1900
          val = list(node.GetTags())
1901
        elif field == "serial_no":
1902
          val = node.serial_no
1903
        elif field == "master_candidate":
1904
          val = node.master_candidate
1905
        elif field == "master":
1906
          val = node.name == master_node
1907
        elif field == "offline":
1908
          val = node.offline
1909
        elif field == "drained":
1910
          val = node.drained
1911
        elif self._FIELDS_DYNAMIC.Matches(field):
1912
          val = live_data[node.name].get(field, None)
1913
        else:
1914
          raise errors.ParameterError(field)
1915
        node_output.append(val)
1916
      output.append(node_output)
1917

    
1918
    return output
1919

    
1920

    
1921
class LUQueryNodeVolumes(NoHooksLU):
1922
  """Logical unit for getting volumes on node(s).
1923

1924
  """
1925
  _OP_REQP = ["nodes", "output_fields"]
1926
  REQ_BGL = False
1927
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
1928
  _FIELDS_STATIC = utils.FieldSet("node")
1929

    
1930
  def ExpandNames(self):
1931
    _CheckOutputFields(static=self._FIELDS_STATIC,
1932
                       dynamic=self._FIELDS_DYNAMIC,
1933
                       selected=self.op.output_fields)
1934

    
1935
    self.needed_locks = {}
1936
    self.share_locks[locking.LEVEL_NODE] = 1
1937
    if not self.op.nodes:
1938
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1939
    else:
1940
      self.needed_locks[locking.LEVEL_NODE] = \
1941
        _GetWantedNodes(self, self.op.nodes)
1942

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

1946
    This checks that the fields required are valid output fields.
1947

1948
    """
1949
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
1950

    
1951
  def Exec(self, feedback_fn):
1952
    """Computes the list of nodes and their attributes.
1953

1954
    """
1955
    nodenames = self.nodes
1956
    volumes = self.rpc.call_node_volumes(nodenames)
1957

    
1958
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
1959
             in self.cfg.GetInstanceList()]
1960

    
1961
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
1962

    
1963
    output = []
1964
    for node in nodenames:
1965
      if node not in volumes or volumes[node].failed or not volumes[node].data:
1966
        continue
1967

    
1968
      node_vols = volumes[node].data[:]
1969
      node_vols.sort(key=lambda vol: vol['dev'])
1970

    
1971
      for vol in node_vols:
1972
        node_output = []
1973
        for field in self.op.output_fields:
1974
          if field == "node":
1975
            val = node
1976
          elif field == "phys":
1977
            val = vol['dev']
1978
          elif field == "vg":
1979
            val = vol['vg']
1980
          elif field == "name":
1981
            val = vol['name']
1982
          elif field == "size":
1983
            val = int(float(vol['size']))
1984
          elif field == "instance":
1985
            for inst in ilist:
1986
              if node not in lv_by_node[inst]:
1987
                continue
1988
              if vol['name'] in lv_by_node[inst][node]:
1989
                val = inst.name
1990
                break
1991
            else:
1992
              val = '-'
1993
          else:
1994
            raise errors.ParameterError(field)
1995
          node_output.append(str(val))
1996

    
1997
        output.append(node_output)
1998

    
1999
    return output
2000

    
2001

    
2002
class LUAddNode(LogicalUnit):
2003
  """Logical unit for adding node to the cluster.
2004

2005
  """
2006
  HPATH = "node-add"
2007
  HTYPE = constants.HTYPE_NODE
2008
  _OP_REQP = ["node_name"]
2009

    
2010
  def BuildHooksEnv(self):
2011
    """Build hooks env.
2012

2013
    This will run on all nodes before, and on all nodes + the new node after.
2014

2015
    """
2016
    env = {
2017
      "OP_TARGET": self.op.node_name,
2018
      "NODE_NAME": self.op.node_name,
2019
      "NODE_PIP": self.op.primary_ip,
2020
      "NODE_SIP": self.op.secondary_ip,
2021
      }
2022
    nodes_0 = self.cfg.GetNodeList()
2023
    nodes_1 = nodes_0 + [self.op.node_name, ]
2024
    return env, nodes_0, nodes_1
2025

    
2026
  def CheckPrereq(self):
2027
    """Check prerequisites.
2028

2029
    This checks:
2030
     - the new node is not already in the config
2031
     - it is resolvable
2032
     - its parameters (single/dual homed) matches the cluster
2033

2034
    Any errors are signalled by raising errors.OpPrereqError.
2035

2036
    """
2037
    node_name = self.op.node_name
2038
    cfg = self.cfg
2039

    
2040
    dns_data = utils.HostInfo(node_name)
2041

    
2042
    node = dns_data.name
2043
    primary_ip = self.op.primary_ip = dns_data.ip
2044
    secondary_ip = getattr(self.op, "secondary_ip", None)
2045
    if secondary_ip is None:
2046
      secondary_ip = primary_ip
2047
    if not utils.IsValidIP(secondary_ip):
2048
      raise errors.OpPrereqError("Invalid secondary IP given")
2049
    self.op.secondary_ip = secondary_ip
2050

    
2051
    node_list = cfg.GetNodeList()
2052
    if not self.op.readd and node in node_list:
2053
      raise errors.OpPrereqError("Node %s is already in the configuration" %
2054
                                 node)
2055
    elif self.op.readd and node not in node_list:
2056
      raise errors.OpPrereqError("Node %s is not in the configuration" % node)
2057

    
2058
    for existing_node_name in node_list:
2059
      existing_node = cfg.GetNodeInfo(existing_node_name)
2060

    
2061
      if self.op.readd and node == existing_node_name:
2062
        if (existing_node.primary_ip != primary_ip or
2063
            existing_node.secondary_ip != secondary_ip):
2064
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
2065
                                     " address configuration as before")
2066
        continue
2067

    
2068
      if (existing_node.primary_ip == primary_ip or
2069
          existing_node.secondary_ip == primary_ip or
2070
          existing_node.primary_ip == secondary_ip or
2071
          existing_node.secondary_ip == secondary_ip):
2072
        raise errors.OpPrereqError("New node ip address(es) conflict with"
2073
                                   " existing node %s" % existing_node.name)
2074

    
2075
    # check that the type of the node (single versus dual homed) is the
2076
    # same as for the master
2077
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
2078
    master_singlehomed = myself.secondary_ip == myself.primary_ip
2079
    newbie_singlehomed = secondary_ip == primary_ip
2080
    if master_singlehomed != newbie_singlehomed:
2081
      if master_singlehomed:
2082
        raise errors.OpPrereqError("The master has no private ip but the"
2083
                                   " new node has one")
2084
      else:
2085
        raise errors.OpPrereqError("The master has a private ip but the"
2086
                                   " new node doesn't have one")
2087

    
2088
    # checks reachablity
2089
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
2090
      raise errors.OpPrereqError("Node not reachable by ping")
2091

    
2092
    if not newbie_singlehomed:
2093
      # check reachability from my secondary ip to newbie's secondary ip
2094
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
2095
                           source=myself.secondary_ip):
2096
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
2097
                                   " based ping to noded port")
2098

    
2099
    cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2100
    mc_now, _ = self.cfg.GetMasterCandidateStats()
2101
    master_candidate = mc_now < cp_size
2102

    
2103
    self.new_node = objects.Node(name=node,
2104
                                 primary_ip=primary_ip,
2105
                                 secondary_ip=secondary_ip,
2106
                                 master_candidate=master_candidate,
2107
                                 offline=False, drained=False)
2108

    
2109
  def Exec(self, feedback_fn):
2110
    """Adds the new node to the cluster.
2111

2112
    """
2113
    new_node = self.new_node
2114
    node = new_node.name
2115

    
2116
    # check connectivity
2117
    result = self.rpc.call_version([node])[node]
2118
    result.Raise()
2119
    if result.data:
2120
      if constants.PROTOCOL_VERSION == result.data:
2121
        logging.info("Communication to node %s fine, sw version %s match",
2122
                     node, result.data)
2123
      else:
2124
        raise errors.OpExecError("Version mismatch master version %s,"
2125
                                 " node version %s" %
2126
                                 (constants.PROTOCOL_VERSION, result.data))
2127
    else:
2128
      raise errors.OpExecError("Cannot get version from the new node")
2129

    
2130
    # setup ssh on node
2131
    logging.info("Copy ssh key to node %s", node)
2132
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
2133
    keyarray = []
2134
    keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
2135
                constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
2136
                priv_key, pub_key]
2137

    
2138
    for i in keyfiles:
2139
      f = open(i, 'r')
2140
      try:
2141
        keyarray.append(f.read())
2142
      finally:
2143
        f.close()
2144

    
2145
    result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
2146
                                    keyarray[2],
2147
                                    keyarray[3], keyarray[4], keyarray[5])
2148

    
2149
    msg = result.RemoteFailMsg()
2150
    if msg:
2151
      raise errors.OpExecError("Cannot transfer ssh keys to the"
2152
                               " new node: %s" % msg)
2153

    
2154
    # Add node to our /etc/hosts, and add key to known_hosts
2155
    utils.AddHostToEtcHosts(new_node.name)
2156

    
2157
    if new_node.secondary_ip != new_node.primary_ip:
2158
      result = self.rpc.call_node_has_ip_address(new_node.name,
2159
                                                 new_node.secondary_ip)
2160
      if result.failed or not result.data:
2161
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
2162
                                 " you gave (%s). Please fix and re-run this"
2163
                                 " command." % new_node.secondary_ip)
2164

    
2165
    node_verify_list = [self.cfg.GetMasterNode()]
2166
    node_verify_param = {
2167
      'nodelist': [node],
2168
      # TODO: do a node-net-test as well?
2169
    }
2170

    
2171
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
2172
                                       self.cfg.GetClusterName())
2173
    for verifier in node_verify_list:
2174
      if result[verifier].failed or not result[verifier].data:
2175
        raise errors.OpExecError("Cannot communicate with %s's node daemon"
2176
                                 " for remote verification" % verifier)
2177
      if result[verifier].data['nodelist']:
2178
        for failed in result[verifier].data['nodelist']:
2179
          feedback_fn("ssh/hostname verification failed %s -> %s" %
2180
                      (verifier, result[verifier].data['nodelist'][failed]))
2181
        raise errors.OpExecError("ssh/hostname verification failed.")
2182

    
2183
    # Distribute updated /etc/hosts and known_hosts to all nodes,
2184
    # including the node just added
2185
    myself = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
2186
    dist_nodes = self.cfg.GetNodeList()
2187
    if not self.op.readd:
2188
      dist_nodes.append(node)
2189
    if myself.name in dist_nodes:
2190
      dist_nodes.remove(myself.name)
2191

    
2192
    logging.debug("Copying hosts and known_hosts to all nodes")
2193
    for fname in (constants.ETC_HOSTS, constants.SSH_KNOWN_HOSTS_FILE):
2194
      result = self.rpc.call_upload_file(dist_nodes, fname)
2195
      for to_node, to_result in result.iteritems():
2196
        if to_result.failed or not to_result.data:
2197
          logging.error("Copy of file %s to node %s failed", fname, to_node)
2198

    
2199
    to_copy = []
2200
    enabled_hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
2201
    if constants.HTS_USE_VNC.intersection(enabled_hypervisors):
2202
      to_copy.append(constants.VNC_PASSWORD_FILE)
2203

    
2204
    for fname in to_copy:
2205
      result = self.rpc.call_upload_file([node], fname)
2206
      if result[node].failed or not result[node]:
2207
        logging.error("Could not copy file %s to node %s", fname, node)
2208

    
2209
    if self.op.readd:
2210
      self.context.ReaddNode(new_node)
2211
    else:
2212
      self.context.AddNode(new_node)
2213

    
2214

    
2215
class LUSetNodeParams(LogicalUnit):
2216
  """Modifies the parameters of a node.
2217

2218
  """
2219
  HPATH = "node-modify"
2220
  HTYPE = constants.HTYPE_NODE
2221
  _OP_REQP = ["node_name"]
2222
  REQ_BGL = False
2223

    
2224
  def CheckArguments(self):
2225
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2226
    if node_name is None:
2227
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
2228
    self.op.node_name = node_name
2229
    _CheckBooleanOpField(self.op, 'master_candidate')
2230
    _CheckBooleanOpField(self.op, 'offline')
2231
    if self.op.master_candidate is None and self.op.offline is None:
2232
      raise errors.OpPrereqError("Please pass at least one modification")
2233
    if self.op.offline == True and self.op.master_candidate == True:
2234
      raise errors.OpPrereqError("Can't set the node into offline and"
2235
                                 " master_candidate at the same time")
2236

    
2237
  def ExpandNames(self):
2238
    self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
2239

    
2240
  def BuildHooksEnv(self):
2241
    """Build hooks env.
2242

2243
    This runs on the master node.
2244

2245
    """
2246
    env = {
2247
      "OP_TARGET": self.op.node_name,
2248
      "MASTER_CANDIDATE": str(self.op.master_candidate),
2249
      "OFFLINE": str(self.op.offline),
2250
      }
2251
    nl = [self.cfg.GetMasterNode(),
2252
          self.op.node_name]
2253
    return env, nl, nl
2254

    
2255
  def CheckPrereq(self):
2256
    """Check prerequisites.
2257

2258
    This only checks the instance list against the existing names.
2259

2260
    """
2261
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
2262

    
2263
    if ((self.op.master_candidate == False or self.op.offline == True)
2264
        and node.master_candidate):
2265
      # we will demote the node from master_candidate
2266
      if self.op.node_name == self.cfg.GetMasterNode():
2267
        raise errors.OpPrereqError("The master node has to be a"
2268
                                   " master candidate and online")
2269
      cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2270
      num_candidates, _ = self.cfg.GetMasterCandidateStats()
2271
      if num_candidates <= cp_size:
2272
        msg = ("Not enough master candidates (desired"
2273
               " %d, new value will be %d)" % (cp_size, num_candidates-1))
2274
        if self.op.force:
2275
          self.LogWarning(msg)
2276
        else:
2277
          raise errors.OpPrereqError(msg)
2278

    
2279
    if (self.op.master_candidate == True and node.offline and
2280
        not self.op.offline == False):
2281
      raise errors.OpPrereqError("Can't set an offline node to"
2282
                                 " master_candidate")
2283

    
2284
    return
2285

    
2286
  def Exec(self, feedback_fn):
2287
    """Modifies a node.
2288

2289
    """
2290
    node = self.node
2291

    
2292
    result = []
2293

    
2294
    if self.op.offline is not None:
2295
      node.offline = self.op.offline
2296
      result.append(("offline", str(self.op.offline)))
2297
      if self.op.offline == True and node.master_candidate:
2298
        node.master_candidate = False
2299
        result.append(("master_candidate", "auto-demotion due to offline"))
2300

    
2301
    if self.op.master_candidate is not None:
2302
      node.master_candidate = self.op.master_candidate
2303
      result.append(("master_candidate", str(self.op.master_candidate)))
2304
      if self.op.master_candidate == False:
2305
        rrc = self.rpc.call_node_demote_from_mc(node.name)
2306
        msg = rrc.RemoteFailMsg()
2307
        if msg:
2308
          self.LogWarning("Node failed to demote itself: %s" % msg)
2309

    
2310
    # this will trigger configuration file update, if needed
2311
    self.cfg.Update(node)
2312
    # this will trigger job queue propagation or cleanup
2313
    if self.op.node_name != self.cfg.GetMasterNode():
2314
      self.context.ReaddNode(node)
2315

    
2316
    return result
2317

    
2318

    
2319
class LUQueryClusterInfo(NoHooksLU):
2320
  """Query cluster configuration.
2321

2322
  """
2323
  _OP_REQP = []
2324
  REQ_BGL = False
2325

    
2326
  def ExpandNames(self):
2327
    self.needed_locks = {}
2328

    
2329
  def CheckPrereq(self):
2330
    """No prerequsites needed for this LU.
2331

2332
    """
2333
    pass
2334

    
2335
  def Exec(self, feedback_fn):
2336
    """Return cluster config.
2337

2338
    """
2339
    cluster = self.cfg.GetClusterInfo()
2340
    result = {
2341
      "software_version": constants.RELEASE_VERSION,
2342
      "protocol_version": constants.PROTOCOL_VERSION,
2343
      "config_version": constants.CONFIG_VERSION,
2344
      "os_api_version": constants.OS_API_VERSION,
2345
      "export_version": constants.EXPORT_VERSION,
2346
      "architecture": (platform.architecture()[0], platform.machine()),
2347
      "name": cluster.cluster_name,
2348
      "master": cluster.master_node,
2349
      "default_hypervisor": cluster.default_hypervisor,
2350
      "enabled_hypervisors": cluster.enabled_hypervisors,
2351
      "hvparams": dict([(hypervisor, cluster.hvparams[hypervisor])
2352
                        for hypervisor in cluster.enabled_hypervisors]),
2353
      "beparams": cluster.beparams,
2354
      "candidate_pool_size": cluster.candidate_pool_size,
2355
      }
2356

    
2357
    return result
2358

    
2359

    
2360
class LUQueryConfigValues(NoHooksLU):
2361
  """Return configuration values.
2362

2363
  """
2364
  _OP_REQP = []
2365
  REQ_BGL = False
2366
  _FIELDS_DYNAMIC = utils.FieldSet()
2367
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag")
2368

    
2369
  def ExpandNames(self):
2370
    self.needed_locks = {}
2371

    
2372
    _CheckOutputFields(static=self._FIELDS_STATIC,
2373
                       dynamic=self._FIELDS_DYNAMIC,
2374
                       selected=self.op.output_fields)
2375

    
2376
  def CheckPrereq(self):
2377
    """No prerequisites.
2378

2379
    """
2380
    pass
2381

    
2382
  def Exec(self, feedback_fn):
2383
    """Dump a representation of the cluster config to the standard output.
2384

2385
    """
2386
    values = []
2387
    for field in self.op.output_fields:
2388
      if field == "cluster_name":
2389
        entry = self.cfg.GetClusterName()
2390
      elif field == "master_node":
2391
        entry = self.cfg.GetMasterNode()
2392
      elif field == "drain_flag":
2393
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
2394
      else:
2395
        raise errors.ParameterError(field)
2396
      values.append(entry)
2397
    return values
2398

    
2399

    
2400
class LUActivateInstanceDisks(NoHooksLU):
2401
  """Bring up an instance's disks.
2402

2403
  """
2404
  _OP_REQP = ["instance_name"]
2405
  REQ_BGL = False
2406

    
2407
  def ExpandNames(self):
2408
    self._ExpandAndLockInstance()
2409
    self.needed_locks[locking.LEVEL_NODE] = []
2410
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2411

    
2412
  def DeclareLocks(self, level):
2413
    if level == locking.LEVEL_NODE:
2414
      self._LockInstancesNodes()
2415

    
2416
  def CheckPrereq(self):
2417
    """Check prerequisites.
2418

2419
    This checks that the instance is in the cluster.
2420

2421
    """
2422
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2423
    assert self.instance is not None, \
2424
      "Cannot retrieve locked instance %s" % self.op.instance_name
2425
    _CheckNodeOnline(self, self.instance.primary_node)
2426

    
2427
  def Exec(self, feedback_fn):
2428
    """Activate the disks.
2429

2430
    """
2431
    disks_ok, disks_info = _AssembleInstanceDisks(self, self.instance)
2432
    if not disks_ok:
2433
      raise errors.OpExecError("Cannot activate block devices")
2434

    
2435
    return disks_info
2436

    
2437

    
2438
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False):
2439
  """Prepare the block devices for an instance.
2440

2441
  This sets up the block devices on all nodes.
2442

2443
  @type lu: L{LogicalUnit}
2444
  @param lu: the logical unit on whose behalf we execute
2445
  @type instance: L{objects.Instance}
2446
  @param instance: the instance for whose disks we assemble
2447
  @type ignore_secondaries: boolean
2448
  @param ignore_secondaries: if true, errors on secondary nodes
2449
      won't result in an error return from the function
2450
  @return: False if the operation failed, otherwise a list of
2451
      (host, instance_visible_name, node_visible_name)
2452
      with the mapping from node devices to instance devices
2453

2454
  """
2455
  device_info = []
2456
  disks_ok = True
2457
  iname = instance.name
2458
  # With the two passes mechanism we try to reduce the window of
2459
  # opportunity for the race condition of switching DRBD to primary
2460
  # before handshaking occured, but we do not eliminate it
2461

    
2462
  # The proper fix would be to wait (with some limits) until the
2463
  # connection has been made and drbd transitions from WFConnection
2464
  # into any other network-connected state (Connected, SyncTarget,
2465
  # SyncSource, etc.)
2466

    
2467
  # 1st pass, assemble on all nodes in secondary mode
2468
  for inst_disk in instance.disks:
2469
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2470
      lu.cfg.SetDiskID(node_disk, node)
2471
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
2472
      msg = result.RemoteFailMsg()
2473
      if msg:
2474
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2475
                           " (is_primary=False, pass=1): %s",
2476
                           inst_disk.iv_name, node, msg)
2477
        if not ignore_secondaries:
2478
          disks_ok = False
2479

    
2480
  # FIXME: race condition on drbd migration to primary
2481

    
2482
  # 2nd pass, do only the primary node
2483
  for inst_disk in instance.disks:
2484
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2485
      if node != instance.primary_node:
2486
        continue
2487
      lu.cfg.SetDiskID(node_disk, node)
2488
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
2489
      msg = result.RemoteFailMsg()
2490
      if msg:
2491
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2492
                           " (is_primary=True, pass=2): %s",
2493
                           inst_disk.iv_name, node, msg)
2494
        disks_ok = False
2495
    device_info.append((instance.primary_node, inst_disk.iv_name, result.data))
2496

    
2497
  # leave the disks configured for the primary node
2498
  # this is a workaround that would be fixed better by
2499
  # improving the logical/physical id handling
2500
  for disk in instance.disks:
2501
    lu.cfg.SetDiskID(disk, instance.primary_node)
2502

    
2503
  return disks_ok, device_info
2504

    
2505

    
2506
def _StartInstanceDisks(lu, instance, force):
2507
  """Start the disks of an instance.
2508

2509
  """
2510
  disks_ok, dummy = _AssembleInstanceDisks(lu, instance,
2511
                                           ignore_secondaries=force)
2512
  if not disks_ok:
2513
    _ShutdownInstanceDisks(lu, instance)
2514
    if force is not None and not force:
2515
      lu.proc.LogWarning("", hint="If the message above refers to a"
2516
                         " secondary node,"
2517
                         " you can retry the operation using '--force'.")
2518
    raise errors.OpExecError("Disk consistency error")
2519

    
2520

    
2521
class LUDeactivateInstanceDisks(NoHooksLU):
2522
  """Shutdown an instance's disks.
2523

2524
  """
2525
  _OP_REQP = ["instance_name"]
2526
  REQ_BGL = False
2527

    
2528
  def ExpandNames(self):
2529
    self._ExpandAndLockInstance()
2530
    self.needed_locks[locking.LEVEL_NODE] = []
2531
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2532

    
2533
  def DeclareLocks(self, level):
2534
    if level == locking.LEVEL_NODE:
2535
      self._LockInstancesNodes()
2536

    
2537
  def CheckPrereq(self):
2538
    """Check prerequisites.
2539

2540
    This checks that the instance is in the cluster.
2541

2542
    """
2543
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2544
    assert self.instance is not None, \
2545
      "Cannot retrieve locked instance %s" % self.op.instance_name
2546

    
2547
  def Exec(self, feedback_fn):
2548
    """Deactivate the disks
2549

2550
    """
2551
    instance = self.instance
2552
    _SafeShutdownInstanceDisks(self, instance)
2553

    
2554

    
2555
def _SafeShutdownInstanceDisks(lu, instance):
2556
  """Shutdown block devices of an instance.
2557

2558
  This function checks if an instance is running, before calling
2559
  _ShutdownInstanceDisks.
2560

2561
  """
2562
  ins_l = lu.rpc.call_instance_list([instance.primary_node],
2563
                                      [instance.hypervisor])
2564
  ins_l = ins_l[instance.primary_node]
2565
  if ins_l.failed or not isinstance(ins_l.data, list):
2566
    raise errors.OpExecError("Can't contact node '%s'" %
2567
                             instance.primary_node)
2568

    
2569
  if instance.name in ins_l.data:
2570
    raise errors.OpExecError("Instance is running, can't shutdown"
2571
                             " block devices.")
2572

    
2573
  _ShutdownInstanceDisks(lu, instance)
2574

    
2575

    
2576
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
2577
  """Shutdown block devices of an instance.
2578

2579
  This does the shutdown on all nodes of the instance.
2580

2581
  If the ignore_primary is false, errors on the primary node are
2582
  ignored.
2583

2584
  """
2585
  all_result = True
2586
  for disk in instance.disks:
2587
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
2588
      lu.cfg.SetDiskID(top_disk, node)
2589
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
2590
      msg = result.RemoteFailMsg()
2591
      if msg:
2592
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
2593
                      disk.iv_name, node, msg)
2594
        if not ignore_primary or node != instance.primary_node:
2595
          all_result = False
2596
  return all_result
2597

    
2598

    
2599
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
2600
  """Checks if a node has enough free memory.
2601

2602
  This function check if a given node has the needed amount of free
2603
  memory. In case the node has less memory or we cannot get the
2604
  information from the node, this function raise an OpPrereqError
2605
  exception.
2606

2607
  @type lu: C{LogicalUnit}
2608
  @param lu: a logical unit from which we get configuration data
2609
  @type node: C{str}
2610
  @param node: the node to check
2611
  @type reason: C{str}
2612
  @param reason: string to use in the error message
2613
  @type requested: C{int}
2614
  @param requested: the amount of memory in MiB to check for
2615
  @type hypervisor_name: C{str}
2616
  @param hypervisor_name: the hypervisor to ask for memory stats
2617
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
2618
      we cannot check the node
2619

2620
  """
2621
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
2622
  nodeinfo[node].Raise()
2623
  free_mem = nodeinfo[node].data.get('memory_free')
2624
  if not isinstance(free_mem, int):
2625
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
2626
                             " was '%s'" % (node, free_mem))
2627
  if requested > free_mem:
2628
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
2629
                             " needed %s MiB, available %s MiB" %
2630
                             (node, reason, requested, free_mem))
2631

    
2632

    
2633
class LUStartupInstance(LogicalUnit):
2634
  """Starts an instance.
2635

2636
  """
2637
  HPATH = "instance-start"
2638
  HTYPE = constants.HTYPE_INSTANCE
2639
  _OP_REQP = ["instance_name", "force"]
2640
  REQ_BGL = False
2641

    
2642
  def ExpandNames(self):
2643
    self._ExpandAndLockInstance()
2644

    
2645
  def BuildHooksEnv(self):
2646
    """Build hooks env.
2647

2648
    This runs on master, primary and secondary nodes of the instance.
2649

2650
    """
2651
    env = {
2652
      "FORCE": self.op.force,
2653
      }
2654
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2655
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2656
    return env, nl, nl
2657

    
2658
  def CheckPrereq(self):
2659
    """Check prerequisites.
2660

2661
    This checks that the instance is in the cluster.
2662

2663
    """
2664
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2665
    assert self.instance is not None, \
2666
      "Cannot retrieve locked instance %s" % self.op.instance_name
2667

    
2668
    _CheckNodeOnline(self, instance.primary_node)
2669

    
2670
    bep = self.cfg.GetClusterInfo().FillBE(instance)
2671
    # check bridges existance
2672
    _CheckInstanceBridgesExist(self, instance)
2673

    
2674
    _CheckNodeFreeMemory(self, instance.primary_node,
2675
                         "starting instance %s" % instance.name,
2676
                         bep[constants.BE_MEMORY], instance.hypervisor)
2677

    
2678
  def Exec(self, feedback_fn):
2679
    """Start the instance.
2680

2681
    """
2682
    instance = self.instance
2683
    force = self.op.force
2684
    extra_args = getattr(self.op, "extra_args", "")
2685

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

    
2688
    node_current = instance.primary_node
2689

    
2690
    _StartInstanceDisks(self, instance, force)
2691

    
2692
    result = self.rpc.call_instance_start(node_current, instance, extra_args)
2693
    msg = result.RemoteFailMsg()
2694
    if msg:
2695
      _ShutdownInstanceDisks(self, instance)
2696
      raise errors.OpExecError("Could not start instance: %s" % msg)
2697

    
2698

    
2699
class LURebootInstance(LogicalUnit):
2700
  """Reboot an instance.
2701

2702
  """
2703
  HPATH = "instance-reboot"
2704
  HTYPE = constants.HTYPE_INSTANCE
2705
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
2706
  REQ_BGL = False
2707

    
2708
  def ExpandNames(self):
2709
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
2710
                                   constants.INSTANCE_REBOOT_HARD,
2711
                                   constants.INSTANCE_REBOOT_FULL]:
2712
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
2713
                                  (constants.INSTANCE_REBOOT_SOFT,
2714
                                   constants.INSTANCE_REBOOT_HARD,
2715
                                   constants.INSTANCE_REBOOT_FULL))
2716
    self._ExpandAndLockInstance()
2717

    
2718
  def BuildHooksEnv(self):
2719
    """Build hooks env.
2720

2721
    This runs on master, primary and secondary nodes of the instance.
2722

2723
    """
2724
    env = {
2725
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
2726
      }
2727
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2728
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2729
    return env, nl, nl
2730

    
2731
  def CheckPrereq(self):
2732
    """Check prerequisites.
2733

2734
    This checks that the instance is in the cluster.
2735

2736
    """
2737
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2738
    assert self.instance is not None, \
2739
      "Cannot retrieve locked instance %s" % self.op.instance_name
2740

    
2741
    _CheckNodeOnline(self, instance.primary_node)
2742

    
2743
    # check bridges existance
2744
    _CheckInstanceBridgesExist(self, instance)
2745

    
2746
  def Exec(self, feedback_fn):
2747
    """Reboot the instance.
2748

2749
    """
2750
    instance = self.instance
2751
    ignore_secondaries = self.op.ignore_secondaries
2752
    reboot_type = self.op.reboot_type
2753
    extra_args = getattr(self.op, "extra_args", "")
2754

    
2755
    node_current = instance.primary_node
2756

    
2757
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
2758
                       constants.INSTANCE_REBOOT_HARD]:
2759
      result = self.rpc.call_instance_reboot(node_current, instance,
2760
                                             reboot_type, extra_args)
2761
      if result.failed or not result.data:
2762
        raise errors.OpExecError("Could not reboot instance")
2763
    else:
2764
      if not self.rpc.call_instance_shutdown(node_current, instance):
2765
        raise errors.OpExecError("could not shutdown instance for full reboot")
2766
      _ShutdownInstanceDisks(self, instance)
2767
      _StartInstanceDisks(self, instance, ignore_secondaries)
2768
      result = self.rpc.call_instance_start(node_current, instance, extra_args)
2769
      msg = result.RemoteFailMsg()
2770
      if msg:
2771
        _ShutdownInstanceDisks(self, instance)
2772
        raise errors.OpExecError("Could not start instance for"
2773
                                 " full reboot: %s" % msg)
2774

    
2775
    self.cfg.MarkInstanceUp(instance.name)
2776

    
2777

    
2778
class LUShutdownInstance(LogicalUnit):
2779
  """Shutdown an instance.
2780

2781
  """
2782
  HPATH = "instance-stop"
2783
  HTYPE = constants.HTYPE_INSTANCE
2784
  _OP_REQP = ["instance_name"]
2785
  REQ_BGL = False
2786

    
2787
  def ExpandNames(self):
2788
    self._ExpandAndLockInstance()
2789

    
2790
  def BuildHooksEnv(self):
2791
    """Build hooks env.
2792

2793
    This runs on master, primary and secondary nodes of the instance.
2794

2795
    """
2796
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2797
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2798
    return env, nl, nl
2799

    
2800
  def CheckPrereq(self):
2801
    """Check prerequisites.
2802

2803
    This checks that the instance is in the cluster.
2804

2805
    """
2806
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2807
    assert self.instance is not None, \
2808
      "Cannot retrieve locked instance %s" % self.op.instance_name
2809
    _CheckNodeOnline(self, self.instance.primary_node)
2810

    
2811
  def Exec(self, feedback_fn):
2812
    """Shutdown the instance.
2813

2814
    """
2815
    instance = self.instance
2816
    node_current = instance.primary_node
2817
    self.cfg.MarkInstanceDown(instance.name)
2818
    result = self.rpc.call_instance_shutdown(node_current, instance)
2819
    if result.failed or not result.data:
2820
      self.proc.LogWarning("Could not shutdown instance")
2821

    
2822
    _ShutdownInstanceDisks(self, instance)
2823

    
2824

    
2825
class LUReinstallInstance(LogicalUnit):
2826
  """Reinstall an instance.
2827

2828
  """
2829
  HPATH = "instance-reinstall"
2830
  HTYPE = constants.HTYPE_INSTANCE
2831
  _OP_REQP = ["instance_name"]
2832
  REQ_BGL = False
2833

    
2834
  def ExpandNames(self):
2835
    self._ExpandAndLockInstance()
2836

    
2837
  def BuildHooksEnv(self):
2838
    """Build hooks env.
2839

2840
    This runs on master, primary and secondary nodes of the instance.
2841

2842
    """
2843
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2844
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2845
    return env, nl, nl
2846

    
2847
  def CheckPrereq(self):
2848
    """Check prerequisites.
2849

2850
    This checks that the instance is in the cluster and is not running.
2851

2852
    """
2853
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2854
    assert instance is not None, \
2855
      "Cannot retrieve locked instance %s" % self.op.instance_name
2856
    _CheckNodeOnline(self, instance.primary_node)
2857

    
2858
    if instance.disk_template == constants.DT_DISKLESS:
2859
      raise errors.OpPrereqError("Instance '%s' has no disks" %
2860
                                 self.op.instance_name)
2861
    if instance.admin_up:
2862
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2863
                                 self.op.instance_name)
2864
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2865
                                              instance.name,
2866
                                              instance.hypervisor)
2867
    if remote_info.failed or remote_info.data:
2868
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2869
                                 (self.op.instance_name,
2870
                                  instance.primary_node))
2871

    
2872
    self.op.os_type = getattr(self.op, "os_type", None)
2873
    if self.op.os_type is not None:
2874
      # OS verification
2875
      pnode = self.cfg.GetNodeInfo(
2876
        self.cfg.ExpandNodeName(instance.primary_node))
2877
      if pnode is None:
2878
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
2879
                                   self.op.pnode)
2880
      result = self.rpc.call_os_get(pnode.name, self.op.os_type)
2881
      result.Raise()
2882
      if not isinstance(result.data, objects.OS):
2883
        raise errors.OpPrereqError("OS '%s' not in supported OS list for"
2884
                                   " primary node"  % self.op.os_type)
2885

    
2886
    self.instance = instance
2887

    
2888
  def Exec(self, feedback_fn):
2889
    """Reinstall the instance.
2890

2891
    """
2892
    inst = self.instance
2893

    
2894
    if self.op.os_type is not None:
2895
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
2896
      inst.os = self.op.os_type
2897
      self.cfg.Update(inst)
2898

    
2899
    _StartInstanceDisks(self, inst, None)
2900
    try:
2901
      feedback_fn("Running the instance OS create scripts...")
2902
      result = self.rpc.call_instance_os_add(inst.primary_node, inst)
2903
      msg = result.RemoteFailMsg()
2904
      if msg:
2905
        raise errors.OpExecError("Could not install OS for instance %s"
2906
                                 " on node %s: %s" %
2907
                                 (inst.name, inst.primary_node, msg))
2908
    finally:
2909
      _ShutdownInstanceDisks(self, inst)
2910

    
2911

    
2912
class LURenameInstance(LogicalUnit):
2913
  """Rename an instance.
2914

2915
  """
2916
  HPATH = "instance-rename"
2917
  HTYPE = constants.HTYPE_INSTANCE
2918
  _OP_REQP = ["instance_name", "new_name"]
2919

    
2920
  def BuildHooksEnv(self):
2921
    """Build hooks env.
2922

2923
    This runs on master, primary and secondary nodes of the instance.
2924

2925
    """
2926
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2927
    env["INSTANCE_NEW_NAME"] = self.op.new_name
2928
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2929
    return env, nl, nl
2930

    
2931
  def CheckPrereq(self):
2932
    """Check prerequisites.
2933

2934
    This checks that the instance is in the cluster and is not running.
2935

2936
    """
2937
    instance = self.cfg.GetInstanceInfo(
2938
      self.cfg.ExpandInstanceName(self.op.instance_name))
2939
    if instance is None:
2940
      raise errors.OpPrereqError("Instance '%s' not known" %
2941
                                 self.op.instance_name)
2942
    _CheckNodeOnline(self, instance.primary_node)
2943

    
2944
    if instance.admin_up:
2945
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2946
                                 self.op.instance_name)
2947
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2948
                                              instance.name,
2949
                                              instance.hypervisor)
2950
    remote_info.Raise()
2951
    if remote_info.data:
2952
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2953
                                 (self.op.instance_name,
2954
                                  instance.primary_node))
2955
    self.instance = instance
2956

    
2957
    # new name verification
2958
    name_info = utils.HostInfo(self.op.new_name)
2959

    
2960
    self.op.new_name = new_name = name_info.name
2961
    instance_list = self.cfg.GetInstanceList()
2962
    if new_name in instance_list:
2963
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
2964
                                 new_name)
2965

    
2966
    if not getattr(self.op, "ignore_ip", False):
2967
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
2968
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
2969
                                   (name_info.ip, new_name))
2970

    
2971

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

2975
    """
2976
    inst = self.instance
2977
    old_name = inst.name
2978

    
2979
    if inst.disk_template == constants.DT_FILE:
2980
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2981

    
2982
    self.cfg.RenameInstance(inst.name, self.op.new_name)
2983
    # Change the instance lock. This is definitely safe while we hold the BGL
2984
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
2985
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
2986

    
2987
    # re-read the instance from the configuration after rename
2988
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
2989

    
2990
    if inst.disk_template == constants.DT_FILE:
2991
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2992
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
2993
                                                     old_file_storage_dir,
2994
                                                     new_file_storage_dir)
2995
      result.Raise()
2996
      if not result.data:
2997
        raise errors.OpExecError("Could not connect to node '%s' to rename"
2998
                                 " directory '%s' to '%s' (but the instance"
2999
                                 " has been renamed in Ganeti)" % (
3000
                                 inst.primary_node, old_file_storage_dir,
3001
                                 new_file_storage_dir))
3002

    
3003
      if not result.data[0]:
3004
        raise errors.OpExecError("Could not rename directory '%s' to '%s'"
3005
                                 " (but the instance has been renamed in"
3006
                                 " Ganeti)" % (old_file_storage_dir,
3007
                                               new_file_storage_dir))
3008

    
3009
    _StartInstanceDisks(self, inst, None)
3010
    try:
3011
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
3012
                                                 old_name)
3013
      msg = result.RemoteFailMsg()
3014
      if msg:
3015
        msg = ("Could not run OS rename script for instance %s on node %s"
3016
               " (but the instance has been renamed in Ganeti): %s" %
3017
               (inst.name, inst.primary_node, msg))
3018
        self.proc.LogWarning(msg)
3019
    finally:
3020
      _ShutdownInstanceDisks(self, inst)
3021

    
3022

    
3023
class LURemoveInstance(LogicalUnit):
3024
  """Remove an instance.
3025

3026
  """
3027
  HPATH = "instance-remove"
3028
  HTYPE = constants.HTYPE_INSTANCE
3029
  _OP_REQP = ["instance_name", "ignore_failures"]
3030
  REQ_BGL = False
3031

    
3032
  def ExpandNames(self):
3033
    self._ExpandAndLockInstance()
3034
    self.needed_locks[locking.LEVEL_NODE] = []
3035
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3036

    
3037
  def DeclareLocks(self, level):
3038
    if level == locking.LEVEL_NODE:
3039
      self._LockInstancesNodes()
3040

    
3041
  def BuildHooksEnv(self):
3042
    """Build hooks env.
3043

3044
    This runs on master, primary and secondary nodes of the instance.
3045

3046
    """
3047
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3048
    nl = [self.cfg.GetMasterNode()]
3049
    return env, nl, nl
3050

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

3054
    This checks that the instance is in the cluster.
3055

3056
    """
3057
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3058
    assert self.instance is not None, \
3059
      "Cannot retrieve locked instance %s" % self.op.instance_name
3060

    
3061
  def Exec(self, feedback_fn):
3062
    """Remove the instance.
3063

3064
    """
3065
    instance = self.instance
3066
    logging.info("Shutting down instance %s on node %s",
3067
                 instance.name, instance.primary_node)
3068

    
3069
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance)
3070
    if result.failed or not result.data:
3071
      if self.op.ignore_failures:
3072
        feedback_fn("Warning: can't shutdown instance")
3073
      else:
3074
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
3075
                                 (instance.name, instance.primary_node))
3076

    
3077
    logging.info("Removing block devices for instance %s", instance.name)
3078

    
3079
    if not _RemoveDisks(self, instance):
3080
      if self.op.ignore_failures:
3081
        feedback_fn("Warning: can't remove instance's disks")
3082
      else:
3083
        raise errors.OpExecError("Can't remove instance's disks")
3084

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

    
3087
    self.cfg.RemoveInstance(instance.name)
3088
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
3089

    
3090

    
3091
class LUQueryInstances(NoHooksLU):
3092
  """Logical unit for querying instances.
3093

3094
  """
3095
  _OP_REQP = ["output_fields", "names", "use_locking"]
3096
  REQ_BGL = False
3097
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
3098
                                    "admin_state", "admin_ram",
3099
                                    "disk_template", "ip", "mac", "bridge",
3100
                                    "sda_size", "sdb_size", "vcpus", "tags",
3101
                                    "network_port", "beparams",
3102
                                    "(disk).(size)/([0-9]+)",
3103
                                    "(disk).(sizes)", "disk_usage",
3104
                                    "(nic).(mac|ip|bridge)/([0-9]+)",
3105
                                    "(nic).(macs|ips|bridges)",
3106
                                    "(disk|nic).(count)",
3107
                                    "serial_no", "hypervisor", "hvparams",] +
3108
                                  ["hv/%s" % name
3109
                                   for name in constants.HVS_PARAMETERS] +
3110
                                  ["be/%s" % name
3111
                                   for name in constants.BES_PARAMETERS])
3112
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
3113

    
3114

    
3115
  def ExpandNames(self):
3116
    _CheckOutputFields(static=self._FIELDS_STATIC,
3117
                       dynamic=self._FIELDS_DYNAMIC,
3118
                       selected=self.op.output_fields)
3119

    
3120
    self.needed_locks = {}
3121
    self.share_locks[locking.LEVEL_INSTANCE] = 1
3122
    self.share_locks[locking.LEVEL_NODE] = 1
3123

    
3124
    if self.op.names:
3125
      self.wanted = _GetWantedInstances(self, self.op.names)
3126
    else:
3127
      self.wanted = locking.ALL_SET
3128

    
3129
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3130
    self.do_locking = self.do_node_query and self.op.use_locking
3131
    if self.do_locking:
3132
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
3133
      self.needed_locks[locking.LEVEL_NODE] = []
3134
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3135

    
3136
  def DeclareLocks(self, level):
3137
    if level == locking.LEVEL_NODE and self.do_locking:
3138
      self._LockInstancesNodes()
3139

    
3140
  def CheckPrereq(self):
3141
    """Check prerequisites.
3142

3143
    """
3144
    pass
3145

    
3146
  def Exec(self, feedback_fn):
3147
    """Computes the list of nodes and their attributes.
3148

3149
    """
3150
    all_info = self.cfg.GetAllInstancesInfo()
3151
    if self.wanted == locking.ALL_SET:
3152
      # caller didn't specify instance names, so ordering is not important
3153
      if self.do_locking:
3154
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
3155
      else:
3156
        instance_names = all_info.keys()
3157
      instance_names = utils.NiceSort(instance_names)
3158
    else:
3159
      # caller did specify names, so we must keep the ordering
3160
      if self.do_locking:
3161
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
3162
      else:
3163
        tgt_set = all_info.keys()
3164
      missing = set(self.wanted).difference(tgt_set)
3165
      if missing:
3166
        raise errors.OpExecError("Some instances were removed before"
3167
                                 " retrieving their data: %s" % missing)
3168
      instance_names = self.wanted
3169

    
3170
    instance_list = [all_info[iname] for iname in instance_names]
3171

    
3172
    # begin data gathering
3173

    
3174
    nodes = frozenset([inst.primary_node for inst in instance_list])
3175
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
3176

    
3177
    bad_nodes = []
3178
    off_nodes = []
3179
    if self.do_node_query:
3180
      live_data = {}
3181
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
3182
      for name in nodes:
3183
        result = node_data[name]
3184
        if result.offline:
3185
          # offline nodes will be in both lists
3186
          off_nodes.append(name)
3187
        if result.failed:
3188
          bad_nodes.append(name)
3189
        else:
3190
          if result.data:
3191
            live_data.update(result.data)
3192
            # else no instance is alive
3193
    else:
3194
      live_data = dict([(name, {}) for name in instance_names])
3195

    
3196
    # end data gathering
3197

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

    
3326
    return output
3327

    
3328

    
3329
class LUFailoverInstance(LogicalUnit):
3330
  """Failover an instance.
3331

3332
  """
3333
  HPATH = "instance-failover"
3334
  HTYPE = constants.HTYPE_INSTANCE
3335
  _OP_REQP = ["instance_name", "ignore_consistency"]
3336
  REQ_BGL = False
3337

    
3338
  def ExpandNames(self):
3339
    self._ExpandAndLockInstance()
3340
    self.needed_locks[locking.LEVEL_NODE] = []
3341
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3342

    
3343
  def DeclareLocks(self, level):
3344
    if level == locking.LEVEL_NODE:
3345
      self._LockInstancesNodes()
3346

    
3347
  def BuildHooksEnv(self):
3348
    """Build hooks env.
3349

3350
    This runs on master, primary and secondary nodes of the instance.
3351

3352
    """
3353
    env = {
3354
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
3355
      }
3356
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3357
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
3358
    return env, nl, nl
3359

    
3360
  def CheckPrereq(self):
3361
    """Check prerequisites.
3362

3363
    This checks that the instance is in the cluster.
3364

3365
    """
3366
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3367
    assert self.instance is not None, \
3368
      "Cannot retrieve locked instance %s" % self.op.instance_name
3369

    
3370
    bep = self.cfg.GetClusterInfo().FillBE(instance)
3371
    if instance.disk_template not in constants.DTS_NET_MIRROR:
3372
      raise errors.OpPrereqError("Instance's disk layout is not"
3373
                                 " network mirrored, cannot failover.")
3374

    
3375
    secondary_nodes = instance.secondary_nodes
3376
    if not secondary_nodes:
3377
      raise errors.ProgrammerError("no secondary node but using "
3378
                                   "a mirrored disk template")
3379

    
3380
    target_node = secondary_nodes[0]
3381
    _CheckNodeOnline(self, target_node)
3382
    # check memory requirements on the secondary node
3383
    _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
3384
                         instance.name, bep[constants.BE_MEMORY],
3385
                         instance.hypervisor)
3386

    
3387
    # check bridge existance
3388
    brlist = [nic.bridge for nic in instance.nics]
3389
    result = self.rpc.call_bridges_exist(target_node, brlist)
3390
    result.Raise()
3391
    if not result.data:
3392
      raise errors.OpPrereqError("One or more target bridges %s does not"
3393
                                 " exist on destination node '%s'" %
3394
                                 (brlist, target_node))
3395

    
3396
  def Exec(self, feedback_fn):
3397
    """Failover an instance.
3398

3399
    The failover is done by shutting it down on its present node and
3400
    starting it on the secondary.
3401

3402
    """
3403
    instance = self.instance
3404

    
3405
    source_node = instance.primary_node
3406
    target_node = instance.secondary_nodes[0]
3407

    
3408
    feedback_fn("* checking disk consistency between source and target")
3409
    for dev in instance.disks:
3410
      # for drbd, these are drbd over lvm
3411
      if not _CheckDiskConsistency(self, dev, target_node, False):
3412
        if instance.admin_up and not self.op.ignore_consistency:
3413
          raise errors.OpExecError("Disk %s is degraded on target node,"
3414
                                   " aborting failover." % dev.iv_name)
3415

    
3416
    feedback_fn("* shutting down instance on source node")
3417
    logging.info("Shutting down instance %s on node %s",
3418
                 instance.name, source_node)
3419

    
3420
    result = self.rpc.call_instance_shutdown(source_node, instance)
3421
    if result.failed or not result.data:
3422
      if self.op.ignore_consistency:
3423
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
3424
                             " Proceeding"
3425
                             " anyway. Please make sure node %s is down",
3426
                             instance.name, source_node, source_node)
3427
      else:
3428
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
3429
                                 (instance.name, source_node))
3430

    
3431
    feedback_fn("* deactivating the instance's disks on source node")
3432
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
3433
      raise errors.OpExecError("Can't shut down the instance's disks.")
3434

    
3435
    instance.primary_node = target_node
3436
    # distribute new instance config to the other nodes
3437
    self.cfg.Update(instance)
3438

    
3439
    # Only start the instance if it's marked as up
3440
    if instance.admin_up:
3441
      feedback_fn("* activating the instance's disks on target node")
3442
      logging.info("Starting instance %s on node %s",
3443
                   instance.name, target_node)
3444

    
3445
      disks_ok, dummy = _AssembleInstanceDisks(self, instance,
3446
                                               ignore_secondaries=True)
3447
      if not disks_ok:
3448
        _ShutdownInstanceDisks(self, instance)
3449
        raise errors.OpExecError("Can't activate the instance's disks")
3450

    
3451
      feedback_fn("* starting the instance on the target node")
3452
      result = self.rpc.call_instance_start(target_node, instance, None)
3453
      msg = result.RemoteFailMsg()
3454
      if msg:
3455
        _ShutdownInstanceDisks(self, instance)
3456
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
3457
                                 (instance.name, target_node, msg))
3458

    
3459

    
3460
class LUMigrateInstance(LogicalUnit):
3461
  """Migrate an instance.
3462

3463
  This is migration without shutting down, compared to the failover,
3464
  which is done with shutdown.
3465

3466
  """
3467
  HPATH = "instance-migrate"
3468
  HTYPE = constants.HTYPE_INSTANCE
3469
  _OP_REQP = ["instance_name", "live", "cleanup"]
3470

    
3471
  REQ_BGL = False
3472

    
3473
  def ExpandNames(self):
3474
    self._ExpandAndLockInstance()
3475
    self.needed_locks[locking.LEVEL_NODE] = []
3476
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3477

    
3478
  def DeclareLocks(self, level):
3479
    if level == locking.LEVEL_NODE:
3480
      self._LockInstancesNodes()
3481

    
3482
  def BuildHooksEnv(self):
3483
    """Build hooks env.
3484

3485
    This runs on master, primary and secondary nodes of the instance.
3486

3487
    """
3488
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3489
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
3490
    return env, nl, nl
3491

    
3492
  def CheckPrereq(self):
3493
    """Check prerequisites.
3494

3495
    This checks that the instance is in the cluster.
3496

3497
    """
3498
    instance = self.cfg.GetInstanceInfo(
3499
      self.cfg.ExpandInstanceName(self.op.instance_name))
3500
    if instance is None:
3501
      raise errors.OpPrereqError("Instance '%s' not known" %
3502
                                 self.op.instance_name)
3503

    
3504
    if instance.disk_template != constants.DT_DRBD8:
3505
      raise errors.OpPrereqError("Instance's disk layout is not"
3506
                                 " drbd8, cannot migrate.")
3507

    
3508
    secondary_nodes = instance.secondary_nodes
3509
    if not secondary_nodes:
3510
      raise errors.ProgrammerError("no secondary node but using "
3511
                                   "drbd8 disk template")
3512

    
3513
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
3514

    
3515
    target_node = secondary_nodes[0]
3516
    # check memory requirements on the secondary node
3517
    _CheckNodeFreeMemory(self, target_node, "migrating instance %s" %
3518
                         instance.name, i_be[constants.BE_MEMORY],
3519
                         instance.hypervisor)
3520

    
3521
    # check bridge existance
3522
    brlist = [nic.bridge for nic in instance.nics]
3523
    result = self.rpc.call_bridges_exist(target_node, brlist)
3524
    if result.failed or not result.data:
3525
      raise errors.OpPrereqError("One or more target bridges %s does not"
3526
                                 " exist on destination node '%s'" %
3527
                                 (brlist, target_node))
3528

    
3529
    if not self.op.cleanup:
3530
      result = self.rpc.call_instance_migratable(instance.primary_node,
3531
                                                 instance)
3532
      msg = result.RemoteFailMsg()
3533
      if msg:
3534
        raise errors.OpPrereqError("Can't migrate: %s - please use failover" %
3535
                                   msg)
3536

    
3537
    self.instance = instance
3538

    
3539
  def _WaitUntilSync(self):
3540
    """Poll with custom rpc for disk sync.
3541

3542
    This uses our own step-based rpc call.
3543

3544
    """
3545
    self.feedback_fn("* wait until resync is done")
3546
    all_done = False
3547
    while not all_done:
3548
      all_done = True
3549
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
3550
                                            self.nodes_ip,
3551
                                            self.instance.disks)
3552
      min_percent = 100
3553
      for node, nres in result.items():
3554
        msg = nres.RemoteFailMsg()
3555
        if msg:
3556
          raise errors.OpExecError("Cannot resync disks on node %s: %s" %
3557
                                   (node, msg))
3558
        node_done, node_percent = nres.payload
3559
        all_done = all_done and node_done
3560
        if node_percent is not None:
3561
          min_percent = min(min_percent, node_percent)
3562
      if not all_done:
3563
        if min_percent < 100:
3564
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
3565
        time.sleep(2)
3566

    
3567
  def _EnsureSecondary(self, node):
3568
    """Demote a node to secondary.
3569

3570
    """
3571
    self.feedback_fn("* switching node %s to secondary mode" % node)
3572

    
3573
    for dev in self.instance.disks:
3574
      self.cfg.SetDiskID(dev, node)
3575

    
3576
    result = self.rpc.call_blockdev_close(node, self.instance.name,
3577
                                          self.instance.disks)
3578
    msg = result.RemoteFailMsg()
3579
    if msg:
3580
      raise errors.OpExecError("Cannot change disk to secondary on node %s,"
3581
                               " error %s" % (node, msg))
3582

    
3583
  def _GoStandalone(self):
3584
    """Disconnect from the network.
3585

3586
    """
3587
    self.feedback_fn("* changing into standalone mode")
3588
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
3589
                                               self.instance.disks)
3590
    for node, nres in result.items():
3591
      msg = nres.RemoteFailMsg()
3592
      if msg:
3593
        raise errors.OpExecError("Cannot disconnect disks node %s,"
3594
                                 " error %s" % (node, msg))
3595

    
3596
  def _GoReconnect(self, multimaster):
3597
    """Reconnect to the network.
3598

3599
    """
3600
    if multimaster:
3601
      msg = "dual-master"
3602
    else:
3603
      msg = "single-master"
3604
    self.feedback_fn("* changing disks into %s mode" % msg)
3605
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
3606
                                           self.instance.disks,
3607
                                           self.instance.name, multimaster)
3608
    for node, nres in result.items():
3609
      msg = nres.RemoteFailMsg()
3610
      if msg:
3611
        raise errors.OpExecError("Cannot change disks config on node %s,"
3612
                                 " error: %s" % (node, msg))
3613

    
3614
  def _ExecCleanup(self):
3615
    """Try to cleanup after a failed migration.
3616

3617
    The cleanup is done by:
3618
      - check that the instance is running only on one node
3619
        (and update the config if needed)
3620
      - change disks on its secondary node to secondary
3621
      - wait until disks are fully synchronized
3622
      - disconnect from the network
3623
      - change disks into single-master mode
3624
      - wait again until disks are fully synchronized
3625

3626
    """
3627
    instance = self.instance
3628
    target_node = self.target_node
3629
    source_node = self.source_node
3630

    
3631
    # check running on only one node
3632
    self.feedback_fn("* checking where the instance actually runs"
3633
                     " (if this hangs, the hypervisor might be in"
3634
                     " a bad state)")
3635
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
3636
    for node, result in ins_l.items():
3637
      result.Raise()
3638
      if not isinstance(result.data, list):
3639
        raise errors.OpExecError("Can't contact node '%s'" % node)
3640

    
3641
    runningon_source = instance.name in ins_l[source_node].data
3642
    runningon_target = instance.name in ins_l[target_node].data
3643

    
3644
    if runningon_source and runningon_target:
3645
      raise errors.OpExecError("Instance seems to be running on two nodes,"
3646
                               " or the hypervisor is confused. You will have"
3647
                               " to ensure manually that it runs only on one"
3648
                               " and restart this operation.")
3649

    
3650
    if not (runningon_source or runningon_target):
3651
      raise errors.OpExecError("Instance does not seem to be running at all."
3652
                               " In this case, it's safer to repair by"
3653
                               " running 'gnt-instance stop' to ensure disk"
3654
                               " shutdown, and then restarting it.")
3655

    
3656
    if runningon_target:
3657
      # the migration has actually succeeded, we need to update the config
3658
      self.feedback_fn("* instance running on secondary node (%s),"
3659
                       " updating config" % target_node)
3660
      instance.primary_node = target_node
3661
      self.cfg.Update(instance)
3662
      demoted_node = source_node
3663
    else:
3664
      self.feedback_fn("* instance confirmed to be running on its"
3665
                       " primary node (%s)" % source_node)
3666
      demoted_node = target_node
3667

    
3668
    self._EnsureSecondary(demoted_node)
3669
    try:
3670
      self._WaitUntilSync()
3671
    except errors.OpExecError:
3672
      # we ignore here errors, since if the device is standalone, it
3673
      # won't be able to sync
3674
      pass
3675
    self._GoStandalone()
3676
    self._GoReconnect(False)
3677
    self._WaitUntilSync()
3678

    
3679
    self.feedback_fn("* done")
3680

    
3681
  def _RevertDiskStatus(self):
3682
    """Try to revert the disk status after a failed migration.
3683

3684
    """
3685
    target_node = self.target_node
3686
    try:
3687
      self._EnsureSecondary(target_node)
3688
      self._GoStandalone()
3689
      self._GoReconnect(False)
3690
      self._WaitUntilSync()
3691
    except errors.OpExecError, err:
3692
      self.LogWarning("Migration failed and I can't reconnect the"
3693
                      " drives: error '%s'\n"
3694
                      "Please look and recover the instance status" %
3695
                      str(err))
3696

    
3697
  def _AbortMigration(self):
3698
    """Call the hypervisor code to abort a started migration.
3699

3700
    """
3701
    instance = self.instance
3702
    target_node = self.target_node
3703
    migration_info = self.migration_info
3704

    
3705
    abort_result = self.rpc.call_finalize_migration(target_node,
3706
                                                    instance,
3707
                                                    migration_info,
3708
                                                    False)
3709
    abort_msg = abort_result.RemoteFailMsg()
3710
    if abort_msg:
3711
      logging.error("Aborting migration failed on target node %s: %s" %
3712
                    (target_node, abort_msg))
3713
      # Don't raise an exception here, as we stil have to try to revert the
3714
      # disk status, even if this step failed.
3715

    
3716
  def _ExecMigration(self):
3717
    """Migrate an instance.
3718

3719
    The migrate is done by:
3720
      - change the disks into dual-master mode
3721
      - wait until disks are fully synchronized again
3722
      - migrate the instance
3723
      - change disks on the new secondary node (the old primary) to secondary
3724
      - wait until disks are fully synchronized
3725
      - change disks into single-master mode
3726

3727
    """
3728
    instance = self.instance
3729
    target_node = self.target_node
3730
    source_node = self.source_node
3731

    
3732
    self.feedback_fn("* checking disk consistency between source and target")
3733
    for dev in instance.disks:
3734
      if not _CheckDiskConsistency(self, dev, target_node, False):
3735
        raise errors.OpExecError("Disk %s is degraded or not fully"
3736
                                 " synchronized on target node,"
3737
                                 " aborting migrate." % dev.iv_name)
3738

    
3739
    # First get the migration information from the remote node
3740
    result = self.rpc.call_migration_info(source_node, instance)
3741
    msg = result.RemoteFailMsg()
3742
    if msg:
3743
      log_err = ("Failed fetching source migration information from %s: %s" %
3744
                 (source_node, msg))
3745
      logging.error(log_err)
3746
      raise errors.OpExecError(log_err)
3747

    
3748
    self.migration_info = migration_info = result.payload
3749

    
3750
    # Then switch the disks to master/master mode
3751
    self._EnsureSecondary(target_node)
3752
    self._GoStandalone()
3753
    self._GoReconnect(True)
3754
    self._WaitUntilSync()
3755

    
3756
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
3757
    result = self.rpc.call_accept_instance(target_node,
3758
                                           instance,
3759
                                           migration_info,
3760
                                           self.nodes_ip[target_node])
3761

    
3762
    msg = result.RemoteFailMsg()
3763
    if msg:
3764
      logging.error("Instance pre-migration failed, trying to revert"
3765
                    " disk status: %s", msg)
3766
      self._AbortMigration()
3767
      self._RevertDiskStatus()
3768
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
3769
                               (instance.name, msg))
3770

    
3771
    self.feedback_fn("* migrating instance to %s" % target_node)
3772
    time.sleep(10)
3773
    result = self.rpc.call_instance_migrate(source_node, instance,
3774
                                            self.nodes_ip[target_node],
3775
                                            self.op.live)
3776
    msg = result.RemoteFailMsg()
3777
    if msg:
3778
      logging.error("Instance migration failed, trying to revert"
3779
                    " disk status: %s", msg)
3780
      self._AbortMigration()
3781
      self._RevertDiskStatus()
3782
      raise errors.OpExecError("Could not migrate instance %s: %s" %
3783
                               (instance.name, msg))
3784
    time.sleep(10)
3785

    
3786
    instance.primary_node = target_node
3787
    # distribute new instance config to the other nodes
3788
    self.cfg.Update(instance)
3789

    
3790
    result = self.rpc.call_finalize_migration(target_node,
3791
                                              instance,
3792
                                              migration_info,
3793
                                              True)
3794
    msg = result.RemoteFailMsg()
3795
    if msg:
3796
      logging.error("Instance migration succeeded, but finalization failed:"
3797
                    " %s" % msg)
3798
      raise errors.OpExecError("Could not finalize instance migration: %s" %
3799
                               msg)
3800

    
3801
    self._EnsureSecondary(source_node)
3802
    self._WaitUntilSync()
3803
    self._GoStandalone()
3804
    self._GoReconnect(False)
3805
    self._WaitUntilSync()
3806

    
3807
    self.feedback_fn("* done")
3808

    
3809
  def Exec(self, feedback_fn):
3810
    """Perform the migration.
3811

3812
    """
3813
    self.feedback_fn = feedback_fn
3814

    
3815
    self.source_node = self.instance.primary_node
3816
    self.target_node = self.instance.secondary_nodes[0]
3817
    self.all_nodes = [self.source_node, self.target_node]
3818
    self.nodes_ip = {
3819
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
3820
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
3821
      }
3822
    if self.op.cleanup:
3823
      return self._ExecCleanup()
3824
    else:
3825
      return self._ExecMigration()
3826

    
3827

    
3828
def _CreateBlockDev(lu, node, instance, device, force_create,
3829
                    info, force_open):
3830
  """Create a tree of block devices on a given node.
3831

3832
  If this device type has to be created on secondaries, create it and
3833
  all its children.
3834

3835
  If not, just recurse to children keeping the same 'force' value.
3836

3837
  @param lu: the lu on whose behalf we execute
3838
  @param node: the node on which to create the device
3839
  @type instance: L{objects.Instance}
3840
  @param instance: the instance which owns the device
3841
  @type device: L{objects.Disk}
3842
  @param device: the device to create
3843
  @type force_create: boolean
3844
  @param force_create: whether to force creation of this device; this
3845
      will be change to True whenever we find a device which has
3846
      CreateOnSecondary() attribute
3847
  @param info: the extra 'metadata' we should attach to the device
3848
      (this will be represented as a LVM tag)
3849
  @type force_open: boolean
3850
  @param force_open: this parameter will be passes to the
3851
      L{backend.BlockdevCreate} function where it specifies
3852
      whether we run on primary or not, and it affects both
3853
      the child assembly and the device own Open() execution
3854

3855
  """
3856
  if device.CreateOnSecondary():
3857
    force_create = True
3858

    
3859
  if device.children:
3860
    for child in device.children:
3861
      _CreateBlockDev(lu, node, instance, child, force_create,
3862
                      info, force_open)
3863

    
3864
  if not force_create:
3865
    return
3866

    
3867
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
3868

    
3869

    
3870
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
3871
  """Create a single block device on a given node.
3872

3873
  This will not recurse over children of the device, so they must be
3874
  created in advance.
3875

3876
  @param lu: the lu on whose behalf we execute
3877
  @param node: the node on which to create the device
3878
  @type instance: L{objects.Instance}
3879
  @param instance: the instance which owns the device
3880
  @type device: L{objects.Disk}
3881
  @param device: the device to create
3882
  @param info: the extra 'metadata' we should attach to the device
3883
      (this will be represented as a LVM tag)
3884
  @type force_open: boolean
3885
  @param force_open: this parameter will be passes to the
3886
      L{backend.BlockdevCreate} function where it specifies
3887
      whether we run on primary or not, and it affects both
3888
      the child assembly and the device own Open() execution
3889

3890
  """
3891
  lu.cfg.SetDiskID(device, node)
3892
  result = lu.rpc.call_blockdev_create(node, device, device.size,
3893
                                       instance.name, force_open, info)
3894
  msg = result.RemoteFailMsg()
3895
  if msg:
3896
    raise errors.OpExecError("Can't create block device %s on"
3897
                             " node %s for instance %s: %s" %
3898
                             (device, node, instance.name, msg))
3899
  if device.physical_id is None:
3900
    device.physical_id = result.payload
3901

    
3902

    
3903
def _GenerateUniqueNames(lu, exts):
3904
  """Generate a suitable LV name.
3905

3906
  This will generate a logical volume name for the given instance.
3907

3908
  """
3909
  results = []
3910
  for val in exts:
3911
    new_id = lu.cfg.GenerateUniqueID()
3912
    results.append("%s%s" % (new_id, val))
3913
  return results
3914

    
3915

    
3916
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
3917
                         p_minor, s_minor):
3918
  """Generate a drbd8 device complete with its children.
3919

3920
  """
3921
  port = lu.cfg.AllocatePort()
3922
  vgname = lu.cfg.GetVGName()
3923
  shared_secret = lu.cfg.GenerateDRBDSecret()
3924
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
3925
                          logical_id=(vgname, names[0]))
3926
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
3927
                          logical_id=(vgname, names[1]))
3928
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
3929
                          logical_id=(primary, secondary, port,
3930
                                      p_minor, s_minor,
3931
                                      shared_secret),
3932
                          children=[dev_data, dev_meta],
3933
                          iv_name=iv_name)
3934
  return drbd_dev
3935

    
3936

    
3937
def _GenerateDiskTemplate(lu, template_name,
3938
                          instance_name, primary_node,
3939
                          secondary_nodes, disk_info,
3940
                          file_storage_dir, file_driver,
3941
                          base_index):
3942
  """Generate the entire disk layout for a given template type.
3943

3944
  """
3945
  #TODO: compute space requirements
3946

    
3947
  vgname = lu.cfg.GetVGName()
3948
  disk_count = len(disk_info)
3949
  disks = []
3950
  if template_name == constants.DT_DISKLESS:
3951
    pass
3952
  elif template_name == constants.DT_PLAIN:
3953
    if len(secondary_nodes) != 0:
3954
      raise errors.ProgrammerError("Wrong template configuration")
3955

    
3956
    names = _GenerateUniqueNames(lu, [".disk%d" % i
3957
                                      for i in range(disk_count)])
3958
    for idx, disk in enumerate(disk_info):
3959
      disk_index = idx + base_index
3960
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
3961
                              logical_id=(vgname, names[idx]),
3962
                              iv_name="disk/%d" % disk_index,
3963
                              mode=disk["mode"])
3964
      disks.append(disk_dev)
3965
  elif template_name == constants.DT_DRBD8:
3966
    if len(secondary_nodes) != 1:
3967
      raise errors.ProgrammerError("Wrong template configuration")
3968
    remote_node = secondary_nodes[0]
3969
    minors = lu.cfg.AllocateDRBDMinor(
3970
      [primary_node, remote_node] * len(disk_info), instance_name)
3971

    
3972
    names = []
3973
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % i
3974
                                               for i in range(disk_count)]):
3975
      names.append(lv_prefix + "_data")
3976
      names.append(lv_prefix + "_meta")
3977
    for idx, disk in enumerate(disk_info):
3978
      disk_index = idx + base_index
3979
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
3980
                                      disk["size"], names[idx*2:idx*2+2],
3981
                                      "disk/%d" % disk_index,
3982
                                      minors[idx*2], minors[idx*2+1])
3983
      disk_dev.mode = disk["mode"]
3984
      disks.append(disk_dev)
3985
  elif template_name == constants.DT_FILE:
3986
    if len(secondary_nodes) != 0:
3987
      raise errors.ProgrammerError("Wrong template configuration")
3988

    
3989
    for idx, disk in enumerate(disk_info):
3990
      disk_index = idx + base_index
3991
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
3992
                              iv_name="disk/%d" % disk_index,
3993
                              logical_id=(file_driver,
3994
                                          "%s/disk%d" % (file_storage_dir,
3995
                                                         idx)),
3996
                              mode=disk["mode"])
3997
      disks.append(disk_dev)
3998
  else:
3999
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
4000
  return disks
4001

    
4002

    
4003
def _GetInstanceInfoText(instance):
4004
  """Compute that text that should be added to the disk's metadata.
4005

4006
  """
4007
  return "originstname+%s" % instance.name
4008

    
4009

    
4010
def _CreateDisks(lu, instance):
4011
  """Create all disks for an instance.
4012

4013
  This abstracts away some work from AddInstance.
4014

4015
  @type lu: L{LogicalUnit}
4016
  @param lu: the logical unit on whose behalf we execute
4017
  @type instance: L{objects.Instance}
4018
  @param instance: the instance whose disks we should create
4019
  @rtype: boolean
4020
  @return: the success of the creation
4021

4022
  """
4023
  info = _GetInstanceInfoText(instance)
4024
  pnode = instance.primary_node
4025

    
4026
  if instance.disk_template == constants.DT_FILE:
4027
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
4028
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
4029

    
4030
    if result.failed or not result.data:
4031
      raise errors.OpExecError("Could not connect to node '%s'" % pnode)
4032

    
4033
    if not result.data[0]:
4034
      raise errors.OpExecError("Failed to create directory '%s'" %
4035
                               file_storage_dir)
4036

    
4037
  # Note: this needs to be kept in sync with adding of disks in
4038
  # LUSetInstanceParams
4039
  for device in instance.disks:
4040
    logging.info("Creating volume %s for instance %s",
4041
                 device.iv_name, instance.name)
4042
    #HARDCODE
4043
    for node in instance.all_nodes:
4044
      f_create = node == pnode
4045
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
4046

    
4047

    
4048
def _RemoveDisks(lu, instance):
4049
  """Remove all disks for an instance.
4050

4051
  This abstracts away some work from `AddInstance()` and
4052
  `RemoveInstance()`. Note that in case some of the devices couldn't
4053
  be removed, the removal will continue with the other ones (compare
4054
  with `_CreateDisks()`).
4055

4056
  @type lu: L{LogicalUnit}
4057
  @param lu: the logical unit on whose behalf we execute
4058
  @type instance: L{objects.Instance}
4059
  @param instance: the instance whose disks we should remove
4060
  @rtype: boolean
4061
  @return: the success of the removal
4062

4063
  """
4064
  logging.info("Removing block devices for instance %s", instance.name)
4065

    
4066
  all_result = True
4067
  for device in instance.disks:
4068
    for node, disk in device.ComputeNodeTree(instance.primary_node):
4069
      lu.cfg.SetDiskID(disk, node)
4070
      msg = lu.rpc.call_blockdev_remove(node, disk).RemoteFailMsg()
4071
      if msg:
4072
        lu.LogWarning("Could not remove block device %s on node %s,"
4073
                      " continuing anyway: %s", device.iv_name, node, msg)
4074
        all_result = False
4075

    
4076
  if instance.disk_template == constants.DT_FILE:
4077
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
4078
    result = lu.rpc.call_file_storage_dir_remove(instance.primary_node,
4079
                                                 file_storage_dir)
4080
    if result.failed or not result.data:
4081
      logging.error("Could not remove directory '%s'", file_storage_dir)
4082
      all_result = False
4083

    
4084
  return all_result
4085

    
4086

    
4087
def _ComputeDiskSize(disk_template, disks):
4088
  """Compute disk size requirements in the volume group
4089

4090
  """
4091
  # Required free disk space as a function of disk and swap space
4092
  req_size_dict = {
4093
    constants.DT_DISKLESS: None,
4094
    constants.DT_PLAIN: sum(d["size"] for d in disks),
4095
    # 128 MB are added for drbd metadata for each disk
4096
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
4097
    constants.DT_FILE: None,
4098
  }
4099

    
4100
  if disk_template not in req_size_dict:
4101
    raise errors.ProgrammerError("Disk template '%s' size requirement"
4102
                                 " is unknown" %  disk_template)
4103

    
4104
  return req_size_dict[disk_template]
4105

    
4106

    
4107
def _CheckHVParams(lu, nodenames, hvname, hvparams):
4108
  """Hypervisor parameter validation.
4109

4110
  This function abstract the hypervisor parameter validation to be
4111
  used in both instance create and instance modify.
4112

4113
  @type lu: L{LogicalUnit}
4114
  @param lu: the logical unit for which we check
4115
  @type nodenames: list
4116
  @param nodenames: the list of nodes on which we should check
4117
  @type hvname: string
4118
  @param hvname: the name of the hypervisor we should use
4119
  @type hvparams: dict
4120
  @param hvparams: the parameters which we need to check
4121
  @raise errors.OpPrereqError: if the parameters are not valid
4122

4123
  """
4124
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
4125
                                                  hvname,
4126
                                                  hvparams)
4127
  for node in nodenames:
4128
    info = hvinfo[node]
4129
    if info.offline:
4130
      continue
4131
    msg = info.RemoteFailMsg()
4132
    if msg:
4133
      raise errors.OpPrereqError("Hypervisor parameter validation failed:"
4134
                                 " %s" % msg)
4135

    
4136

    
4137
class LUCreateInstance(LogicalUnit):
4138
  """Create an instance.
4139

4140
  """
4141
  HPATH = "instance-add"
4142
  HTYPE = constants.HTYPE_INSTANCE
4143
  _OP_REQP = ["instance_name", "disks", "disk_template",
4144
              "mode", "start",
4145
              "wait_for_sync", "ip_check", "nics",
4146
              "hvparams", "beparams"]
4147
  REQ_BGL = False
4148

    
4149
  def _ExpandNode(self, node):
4150
    """Expands and checks one node name.
4151

4152
    """
4153
    node_full = self.cfg.ExpandNodeName(node)
4154
    if node_full is None:
4155
      raise errors.OpPrereqError("Unknown node %s" % node)
4156
    return node_full
4157

    
4158
  def ExpandNames(self):
4159
    """ExpandNames for CreateInstance.
4160

4161
    Figure out the right locks for instance creation.
4162

4163
    """
4164
    self.needed_locks = {}
4165

    
4166
    # set optional parameters to none if they don't exist
4167
    for attr in ["pnode", "snode", "iallocator", "hypervisor"]:
4168
      if not hasattr(self.op, attr):
4169
        setattr(self.op, attr, None)
4170

    
4171
    # cheap checks, mostly valid constants given
4172

    
4173
    # verify creation mode
4174
    if self.op.mode not in (constants.INSTANCE_CREATE,
4175
                            constants.INSTANCE_IMPORT):
4176
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
4177
                                 self.op.mode)
4178

    
4179
    # disk template and mirror node verification
4180
    if self.op.disk_template not in constants.DISK_TEMPLATES:
4181
      raise errors.OpPrereqError("Invalid disk template name")
4182

    
4183
    if self.op.hypervisor is None:
4184
      self.op.hypervisor = self.cfg.GetHypervisorType()
4185

    
4186
    cluster = self.cfg.GetClusterInfo()
4187
    enabled_hvs = cluster.enabled_hypervisors
4188
    if self.op.hypervisor not in enabled_hvs:
4189
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
4190
                                 " cluster (%s)" % (self.op.hypervisor,
4191
                                  ",".join(enabled_hvs)))
4192

    
4193
    # check hypervisor parameter syntax (locally)
4194

    
4195
    filled_hvp = cluster.FillDict(cluster.hvparams[self.op.hypervisor],
4196
                                  self.op.hvparams)
4197
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
4198
    hv_type.CheckParameterSyntax(filled_hvp)
4199

    
4200
    # fill and remember the beparams dict
4201
    utils.CheckBEParams(self.op.beparams)
4202
    self.be_full = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
4203
                                    self.op.beparams)
4204

    
4205
    #### instance parameters check
4206

    
4207
    # instance name verification
4208
    hostname1 = utils.HostInfo(self.op.instance_name)
4209
    self.op.instance_name = instance_name = hostname1.name
4210

    
4211
    # this is just a preventive check, but someone might still add this
4212
    # instance in the meantime, and creation will fail at lock-add time
4213
    if instance_name in self.cfg.GetInstanceList():
4214
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4215
                                 instance_name)
4216

    
4217
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
4218

    
4219
    # NIC buildup
4220
    self.nics = []
4221
    for nic in self.op.nics:
4222
      # ip validity checks
4223
      ip = nic.get("ip", None)
4224
      if ip is None or ip.lower() == "none":
4225
        nic_ip = None
4226
      elif ip.lower() == constants.VALUE_AUTO:
4227
        nic_ip = hostname1.ip
4228
      else:
4229
        if not utils.IsValidIP(ip):
4230
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
4231
                                     " like a valid IP" % ip)
4232
        nic_ip = ip
4233

    
4234
      # MAC address verification
4235
      mac = nic.get("mac", constants.VALUE_AUTO)
4236
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
4237
        if not utils.IsValidMac(mac.lower()):
4238
          raise errors.OpPrereqError("Invalid MAC address specified: %s" %
4239
                                     mac)
4240
      # bridge verification
4241
      bridge = nic.get("bridge", None)
4242
      if bridge is None:
4243
        bridge = self.cfg.GetDefBridge()
4244
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, bridge=bridge))
4245

    
4246
    # disk checks/pre-build
4247
    self.disks = []
4248
    for disk in self.op.disks:
4249
      mode = disk.get("mode", constants.DISK_RDWR)
4250
      if mode not in constants.DISK_ACCESS_SET:
4251
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
4252
                                   mode)
4253
      size = disk.get("size", None)
4254
      if size is None:
4255
        raise errors.OpPrereqError("Missing disk size")
4256
      try:
4257
        size = int(size)
4258
      except ValueError:
4259
        raise errors.OpPrereqError("Invalid disk size '%s'" % size)
4260
      self.disks.append({"size": size, "mode": mode})
4261

    
4262
    # used in CheckPrereq for ip ping check
4263
    self.check_ip = hostname1.ip
4264

    
4265
    # file storage checks
4266
    if (self.op.file_driver and
4267
        not self.op.file_driver in constants.FILE_DRIVER):
4268
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
4269
                                 self.op.file_driver)
4270

    
4271
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
4272
      raise errors.OpPrereqError("File storage directory path not absolute")
4273

    
4274
    ### Node/iallocator related checks
4275
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
4276
      raise errors.OpPrereqError("One and only one of iallocator and primary"
4277
                                 " node must be given")
4278

    
4279
    if self.op.iallocator:
4280
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4281
    else:
4282
      self.op.pnode = self._ExpandNode(self.op.pnode)
4283
      nodelist = [self.op.pnode]
4284
      if self.op.snode is not None:
4285
        self.op.snode = self._ExpandNode(self.op.snode)
4286
        nodelist.append(self.op.snode)
4287
      self.needed_locks[locking.LEVEL_NODE] = nodelist
4288

    
4289
    # in case of import lock the source node too
4290
    if self.op.mode == constants.INSTANCE_IMPORT:
4291
      src_node = getattr(self.op, "src_node", None)
4292
      src_path = getattr(self.op, "src_path", None)
4293

    
4294
      if src_path is None:
4295
        self.op.src_path = src_path = self.op.instance_name
4296

    
4297
      if src_node is None:
4298
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4299
        self.op.src_node = None
4300
        if os.path.isabs(src_path):
4301
          raise errors.OpPrereqError("Importing an instance from an absolute"
4302
                                     " path requires a source node option.")
4303
      else:
4304
        self.op.src_node = src_node = self._ExpandNode(src_node)
4305
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4306
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
4307
        if not os.path.isabs(src_path):
4308
          self.op.src_path = src_path = \
4309
            os.path.join(constants.EXPORT_DIR, src_path)
4310

    
4311
    else: # INSTANCE_CREATE
4312
      if getattr(self.op, "os_type", None) is None:
4313
        raise errors.OpPrereqError("No guest OS specified")
4314

    
4315
  def _RunAllocator(self):
4316
    """Run the allocator based on input opcode.
4317

4318
    """
4319
    nics = [n.ToDict() for n in self.nics]
4320
    ial = IAllocator(self,
4321
                     mode=constants.IALLOCATOR_MODE_ALLOC,
4322
                     name=self.op.instance_name,
4323
                     disk_template=self.op.disk_template,
4324
                     tags=[],
4325
                     os=self.op.os_type,
4326
                     vcpus=self.be_full[constants.BE_VCPUS],
4327
                     mem_size=self.be_full[constants.BE_MEMORY],
4328
                     disks=self.disks,
4329
                     nics=nics,
4330
                     hypervisor=self.op.hypervisor,
4331
                     )
4332

    
4333
    ial.Run(self.op.iallocator)
4334

    
4335
    if not ial.success:
4336
      raise errors.OpPrereqError("Can't compute nodes using"
4337
                                 " iallocator '%s': %s" % (self.op.iallocator,
4338
                                                           ial.info))
4339
    if len(ial.nodes) != ial.required_nodes:
4340
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
4341
                                 " of nodes (%s), required %s" %
4342
                                 (self.op.iallocator, len(ial.nodes),
4343
                                  ial.required_nodes))
4344
    self.op.pnode = ial.nodes[0]
4345
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
4346
                 self.op.instance_name, self.op.iallocator,
4347
                 ", ".join(ial.nodes))
4348
    if ial.required_nodes == 2:
4349
      self.op.snode = ial.nodes[1]
4350

    
4351
  def BuildHooksEnv(self):
4352
    """Build hooks env.
4353

4354
    This runs on master, primary and secondary nodes of the instance.
4355

4356
    """
4357
    env = {
4358
      "INSTANCE_DISK_TEMPLATE": self.op.disk_template,
4359
      "INSTANCE_DISK_SIZE": ",".join(str(d["size"]) for d in self.disks),
4360
      "INSTANCE_ADD_MODE": self.op.mode,
4361
      }
4362
    if self.op.mode == constants.INSTANCE_IMPORT:
4363
      env["INSTANCE_SRC_NODE"] = self.op.src_node
4364
      env["INSTANCE_SRC_PATH"] = self.op.src_path
4365
      env["INSTANCE_SRC_IMAGES"] = self.src_images
4366

    
4367
    env.update(_BuildInstanceHookEnv(name=self.op.instance_name,
4368
      primary_node=self.op.pnode,
4369
      secondary_nodes=self.secondaries,
4370
      status=self.op.start,
4371
      os_type=self.op.os_type,
4372
      memory=self.be_full[constants.BE_MEMORY],
4373
      vcpus=self.be_full[constants.BE_VCPUS],
4374
      nics=[(n.ip, n.bridge, n.mac) for n in self.nics],
4375
    ))
4376

    
4377
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
4378
          self.secondaries)
4379
    return env, nl, nl
4380

    
4381

    
4382
  def CheckPrereq(self):
4383
    """Check prerequisites.
4384

4385
    """
4386
    if (not self.cfg.GetVGName() and
4387
        self.op.disk_template not in constants.DTS_NOT_LVM):
4388
      raise errors.OpPrereqError("Cluster does not support lvm-based"
4389
                                 " instances")
4390

    
4391

    
4392
    if self.op.mode == constants.INSTANCE_IMPORT:
4393
      src_node = self.op.src_node
4394
      src_path = self.op.src_path
4395

    
4396
      if src_node is None:
4397
        exp_list = self.rpc.call_export_list(
4398
          self.acquired_locks[locking.LEVEL_NODE])
4399
        found = False
4400
        for node in exp_list:
4401
          if not exp_list[node].failed and src_path in exp_list[node].data:
4402
            found = True
4403
            self.op.src_node = src_node = node
4404
            self.op.src_path = src_path = os.path.join(constants.EXPORT_DIR,
4405
                                                       src_path)
4406
            break
4407
        if not found:
4408
          raise errors.OpPrereqError("No export found for relative path %s" %
4409
                                      src_path)
4410

    
4411
      _CheckNodeOnline(self, src_node)
4412
      result = self.rpc.call_export_info(src_node, src_path)
4413
      result.Raise()
4414
      if not result.data:
4415
        raise errors.OpPrereqError("No export found in dir %s" % src_path)
4416

    
4417
      export_info = result.data
4418
      if not export_info.has_section(constants.INISECT_EXP):
4419
        raise errors.ProgrammerError("Corrupted export config")
4420

    
4421
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
4422
      if (int(ei_version) != constants.EXPORT_VERSION):
4423
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
4424
                                   (ei_version, constants.EXPORT_VERSION))
4425

    
4426
      # Check that the new instance doesn't have less disks than the export
4427
      instance_disks = len(self.disks)
4428
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
4429
      if instance_disks < export_disks:
4430
        raise errors.OpPrereqError("Not enough disks to import."
4431
                                   " (instance: %d, export: %d)" %
4432
                                   (instance_disks, export_disks))
4433

    
4434
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
4435
      disk_images = []
4436
      for idx in range(export_disks):
4437
        option = 'disk%d_dump' % idx
4438
        if export_info.has_option(constants.INISECT_INS, option):
4439
          # FIXME: are the old os-es, disk sizes, etc. useful?
4440
          export_name = export_info.get(constants.INISECT_INS, option)
4441
          image = os.path.join(src_path, export_name)
4442
          disk_images.append(image)
4443
        else:
4444
          disk_images.append(False)
4445

    
4446
      self.src_images = disk_images
4447

    
4448
      old_name = export_info.get(constants.INISECT_INS, 'name')
4449
      # FIXME: int() here could throw a ValueError on broken exports
4450
      exp_nic_count = int(export_info.get(constants.INISECT_INS, 'nic_count'))
4451
      if self.op.instance_name == old_name:
4452
        for idx, nic in enumerate(self.nics):
4453
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
4454
            nic_mac_ini = 'nic%d_mac' % idx
4455
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
4456

    
4457
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
4458
    if self.op.start and not self.op.ip_check:
4459
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
4460
                                 " adding an instance in start mode")
4461

    
4462
    if self.op.ip_check:
4463
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
4464
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4465
                                   (self.check_ip, self.op.instance_name))
4466

    
4467
    #### allocator run
4468

    
4469
    if self.op.iallocator is not None:
4470
      self._RunAllocator()
4471

    
4472
    #### node related checks
4473

    
4474
    # check primary node
4475
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
4476
    assert self.pnode is not None, \
4477
      "Cannot retrieve locked node %s" % self.op.pnode
4478
    if pnode.offline:
4479
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
4480
                                 pnode.name)
4481

    
4482
    self.secondaries = []
4483

    
4484
    # mirror node verification
4485
    if self.op.disk_template in constants.DTS_NET_MIRROR:
4486
      if self.op.snode is None:
4487
        raise errors.OpPrereqError("The networked disk templates need"
4488
                                   " a mirror node")
4489
      if self.op.snode == pnode.name:
4490
        raise errors.OpPrereqError("The secondary node cannot be"
4491
                                   " the primary node.")
4492
      self.secondaries.append(self.op.snode)
4493
      _CheckNodeOnline(self, self.op.snode)
4494

    
4495
    nodenames = [pnode.name] + self.secondaries
4496

    
4497
    req_size = _ComputeDiskSize(self.op.disk_template,
4498
                                self.disks)
4499

    
4500
    # Check lv size requirements
4501
    if req_size is not None:
4502
      nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
4503
                                         self.op.hypervisor)
4504
      for node in nodenames:
4505
        info = nodeinfo[node]
4506
        info.Raise()
4507
        info = info.data
4508
        if not info:
4509
          raise errors.OpPrereqError("Cannot get current information"
4510
                                     " from node '%s'" % node)
4511
        vg_free = info.get('vg_free', None)
4512
        if not isinstance(vg_free, int):
4513
          raise errors.OpPrereqError("Can't compute free disk space on"
4514
                                     " node %s" % node)
4515
        if req_size > info['vg_free']:
4516
          raise errors.OpPrereqError("Not enough disk space on target node %s."
4517
                                     " %d MB available, %d MB required" %
4518
                                     (node, info['vg_free'], req_size))
4519

    
4520
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
4521

    
4522
    # os verification
4523
    result = self.rpc.call_os_get(pnode.name, self.op.os_type)
4524
    result.Raise()
4525
    if not isinstance(result.data, objects.OS):
4526
      raise errors.OpPrereqError("OS '%s' not in supported os list for"
4527
                                 " primary node"  % self.op.os_type)
4528

    
4529
    # bridge check on primary node
4530
    bridges = [n.bridge for n in self.nics]
4531
    result = self.rpc.call_bridges_exist(self.pnode.name, bridges)
4532
    result.Raise()
4533
    if not result.data:
4534
      raise errors.OpPrereqError("One of the target bridges '%s' does not"
4535
                                 " exist on destination node '%s'" %
4536
                                 (",".join(bridges), pnode.name))
4537

    
4538
    # memory check on primary node
4539
    if self.op.start:
4540
      _CheckNodeFreeMemory(self, self.pnode.name,
4541
                           "creating instance %s" % self.op.instance_name,
4542
                           self.be_full[constants.BE_MEMORY],
4543
                           self.op.hypervisor)
4544

    
4545
  def Exec(self, feedback_fn):
4546
    """Create and add the instance to the cluster.
4547

4548
    """
4549
    instance = self.op.instance_name
4550
    pnode_name = self.pnode.name
4551

    
4552
    for nic in self.nics:
4553
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
4554
        nic.mac = self.cfg.GenerateMAC()
4555

    
4556
    ht_kind = self.op.hypervisor
4557
    if ht_kind in constants.HTS_REQ_PORT:
4558
      network_port = self.cfg.AllocatePort()
4559
    else:
4560
      network_port = None
4561

    
4562
    ##if self.op.vnc_bind_address is None:
4563
    ##  self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
4564

    
4565
    # this is needed because os.path.join does not accept None arguments
4566
    if self.op.file_storage_dir is None:
4567
      string_file_storage_dir = ""
4568
    else:
4569
      string_file_storage_dir = self.op.file_storage_dir
4570

    
4571
    # build the full file storage dir path
4572
    file_storage_dir = os.path.normpath(os.path.join(
4573
                                        self.cfg.GetFileStorageDir(),
4574
                                        string_file_storage_dir, instance))
4575

    
4576

    
4577
    disks = _GenerateDiskTemplate(self,
4578
                                  self.op.disk_template,
4579
                                  instance, pnode_name,
4580
                                  self.secondaries,
4581
                                  self.disks,
4582
                                  file_storage_dir,
4583
                                  self.op.file_driver,
4584
                                  0)
4585

    
4586
    iobj = objects.Instance(name=instance, os=self.op.os_type,
4587
                            primary_node=pnode_name,
4588
                            nics=self.nics, disks=disks,
4589
                            disk_template=self.op.disk_template,
4590
                            admin_up=False,
4591
                            network_port=network_port,
4592
                            beparams=self.op.beparams,
4593
                            hvparams=self.op.hvparams,
4594
                            hypervisor=self.op.hypervisor,
4595
                            )
4596

    
4597
    feedback_fn("* creating instance disks...")
4598
    try:
4599
      _CreateDisks(self, iobj)
4600
    except errors.OpExecError:
4601
      self.LogWarning("Device creation failed, reverting...")
4602
      try:
4603
        _RemoveDisks(self, iobj)
4604
      finally:
4605
        self.cfg.ReleaseDRBDMinors(instance)
4606
        raise
4607

    
4608
    feedback_fn("adding instance %s to cluster config" % instance)
4609

    
4610
    self.cfg.AddInstance(iobj)
4611
    # Declare that we don't want to remove the instance lock anymore, as we've
4612
    # added the instance to the config
4613
    del self.remove_locks[locking.LEVEL_INSTANCE]
4614
    # Unlock all the nodes
4615
    if self.op.mode == constants.INSTANCE_IMPORT:
4616
      nodes_keep = [self.op.src_node]
4617
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
4618
                       if node != self.op.src_node]
4619
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
4620
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
4621
    else:
4622
      self.context.glm.release(locking.LEVEL_NODE)
4623
      del self.acquired_locks[locking.LEVEL_NODE]
4624

    
4625
    if self.op.wait_for_sync:
4626
      disk_abort = not _WaitForSync(self, iobj)
4627
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
4628
      # make sure the disks are not degraded (still sync-ing is ok)
4629
      time.sleep(15)
4630
      feedback_fn("* checking mirrors status")
4631
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
4632
    else:
4633
      disk_abort = False
4634

    
4635
    if disk_abort:
4636
      _RemoveDisks(self, iobj)
4637
      self.cfg.RemoveInstance(iobj.name)
4638
      # Make sure the instance lock gets removed
4639
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
4640
      raise errors.OpExecError("There are some degraded disks for"
4641
                               " this instance")
4642

    
4643
    feedback_fn("creating os for instance %s on node %s" %
4644
                (instance, pnode_name))
4645

    
4646
    if iobj.disk_template != constants.DT_DISKLESS:
4647
      if self.op.mode == constants.INSTANCE_CREATE:
4648
        feedback_fn("* running the instance OS create scripts...")
4649
        result = self.rpc.call_instance_os_add(pnode_name, iobj)
4650
        msg = result.RemoteFailMsg()
4651
        if msg:
4652
          raise errors.OpExecError("Could not add os for instance %s"
4653
                                   " on node %s: %s" %
4654
                                   (instance, pnode_name, msg))
4655

    
4656
      elif self.op.mode == constants.INSTANCE_IMPORT:
4657
        feedback_fn("* running the instance OS import scripts...")
4658
        src_node = self.op.src_node
4659
        src_images = self.src_images
4660
        cluster_name = self.cfg.GetClusterName()
4661
        import_result = self.rpc.call_instance_os_import(pnode_name, iobj,
4662
                                                         src_node, src_images,
4663
                                                         cluster_name)
4664
        import_result.Raise()
4665
        for idx, result in enumerate(import_result.data):
4666
          if not result:
4667
            self.LogWarning("Could not import the image %s for instance"
4668
                            " %s, disk %d, on node %s" %
4669
                            (src_images[idx], instance, idx, pnode_name))
4670
      else:
4671
        # also checked in the prereq part
4672
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
4673
                                     % self.op.mode)
4674

    
4675
    if self.op.start:
4676
      iobj.admin_up = True
4677
      self.cfg.Update(iobj)
4678
      logging.info("Starting instance %s on node %s", instance, pnode_name)
4679
      feedback_fn("* starting instance...")
4680
      result = self.rpc.call_instance_start(pnode_name, iobj, None)
4681
      msg = result.RemoteFailMsg()
4682
      if msg:
4683
        raise errors.OpExecError("Could not start instance: %s" % msg)
4684

    
4685

    
4686
class LUConnectConsole(NoHooksLU):
4687
  """Connect to an instance's console.
4688

4689
  This is somewhat special in that it returns the command line that
4690
  you need to run on the master node in order to connect to the
4691
  console.
4692

4693
  """
4694
  _OP_REQP = ["instance_name"]
4695
  REQ_BGL = False
4696

    
4697
  def ExpandNames(self):
4698
    self._ExpandAndLockInstance()
4699

    
4700
  def CheckPrereq(self):
4701
    """Check prerequisites.
4702

4703
    This checks that the instance is in the cluster.
4704

4705
    """
4706
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4707
    assert self.instance is not None, \
4708
      "Cannot retrieve locked instance %s" % self.op.instance_name
4709
    _CheckNodeOnline(self, self.instance.primary_node)
4710

    
4711
  def Exec(self, feedback_fn):
4712
    """Connect to the console of an instance
4713

4714
    """
4715
    instance = self.instance
4716
    node = instance.primary_node
4717

    
4718
    node_insts = self.rpc.call_instance_list([node],
4719
                                             [instance.hypervisor])[node]
4720
    node_insts.Raise()
4721

    
4722
    if instance.name not in node_insts.data:
4723
      raise errors.OpExecError("Instance %s is not running." % instance.name)
4724

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

    
4727
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
4728
    cluster = self.cfg.GetClusterInfo()
4729
    # beparams and hvparams are passed separately, to avoid editing the
4730
    # instance and then saving the defaults in the instance itself.
4731
    hvparams = cluster.FillHV(instance)
4732
    beparams = cluster.FillBE(instance)
4733
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
4734

    
4735
    # build ssh cmdline
4736
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
4737

    
4738

    
4739
class LUReplaceDisks(LogicalUnit):
4740
  """Replace the disks of an instance.
4741

4742
  """
4743
  HPATH = "mirrors-replace"
4744
  HTYPE = constants.HTYPE_INSTANCE
4745
  _OP_REQP = ["instance_name", "mode", "disks"]
4746
  REQ_BGL = False
4747

    
4748
  def CheckArguments(self):
4749
    if not hasattr(self.op, "remote_node"):
4750
      self.op.remote_node = None
4751
    if not hasattr(self.op, "iallocator"):
4752
      self.op.iallocator = None
4753

    
4754
    # check for valid parameter combination
4755
    cnt = [self.op.remote_node, self.op.iallocator].count(None)
4756
    if self.op.mode == constants.REPLACE_DISK_CHG:
4757
      if cnt == 2:
4758
        raise errors.OpPrereqError("When changing the secondary either an"
4759
                                   " iallocator script must be used or the"
4760
                                   " new node given")
4761
      elif cnt == 0:
4762
        raise errors.OpPrereqError("Give either the iallocator or the new"
4763
                                   " secondary, not both")
4764
    else: # not replacing the secondary
4765
      if cnt != 2:
4766
        raise errors.OpPrereqError("The iallocator and new node options can"
4767
                                   " be used only when changing the"
4768
                                   " secondary node")
4769

    
4770
  def ExpandNames(self):
4771
    self._ExpandAndLockInstance()
4772

    
4773
    if self.op.iallocator is not None:
4774
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4775
    elif self.op.remote_node is not None:
4776
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
4777
      if remote_node is None:
4778
        raise errors.OpPrereqError("Node '%s' not known" %
4779
                                   self.op.remote_node)
4780
      self.op.remote_node = remote_node
4781
      # Warning: do not remove the locking of the new secondary here
4782
      # unless DRBD8.AddChildren is changed to work in parallel;
4783
      # currently it doesn't since parallel invocations of
4784
      # FindUnusedMinor will conflict
4785
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
4786
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4787
    else:
4788
      self.needed_locks[locking.LEVEL_NODE] = []
4789
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4790

    
4791
  def DeclareLocks(self, level):
4792
    # If we're not already locking all nodes in the set we have to declare the
4793
    # instance's primary/secondary nodes.
4794
    if (level == locking.LEVEL_NODE and
4795
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
4796
      self._LockInstancesNodes()
4797

    
4798
  def _RunAllocator(self):
4799
    """Compute a new secondary node using an IAllocator.
4800

4801
    """
4802
    ial = IAllocator(self,
4803
                     mode=constants.IALLOCATOR_MODE_RELOC,
4804
                     name=self.op.instance_name,
4805
                     relocate_from=[self.sec_node])
4806

    
4807
    ial.Run(self.op.iallocator)
4808

    
4809
    if not ial.success:
4810
      raise errors.OpPrereqError("Can't compute nodes using"
4811
                                 " iallocator '%s': %s" % (self.op.iallocator,
4812
                                                           ial.info))
4813
    if len(ial.nodes) != ial.required_nodes:
4814
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
4815
                                 " of nodes (%s), required %s" %
4816
                                 (len(ial.nodes), ial.required_nodes))
4817
    self.op.remote_node = ial.nodes[0]
4818
    self.LogInfo("Selected new secondary for the instance: %s",
4819
                 self.op.remote_node)
4820

    
4821
  def BuildHooksEnv(self):
4822
    """Build hooks env.
4823

4824
    This runs on the master, the primary and all the secondaries.
4825

4826
    """
4827
    env = {
4828
      "MODE": self.op.mode,
4829
      "NEW_SECONDARY": self.op.remote_node,
4830
      "OLD_SECONDARY": self.instance.secondary_nodes[0],
4831
      }
4832
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4833
    nl = [
4834
      self.cfg.GetMasterNode(),
4835
      self.instance.primary_node,
4836
      ]
4837
    if self.op.remote_node is not None:
4838
      nl.append(self.op.remote_node)
4839
    return env, nl, nl
4840

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

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

4846
    """
4847
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4848
    assert instance is not None, \
4849
      "Cannot retrieve locked instance %s" % self.op.instance_name
4850
    self.instance = instance
4851

    
4852
    if instance.disk_template != constants.DT_DRBD8:
4853
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
4854
                                 " instances")
4855

    
4856
    if len(instance.secondary_nodes) != 1:
4857
      raise errors.OpPrereqError("The instance has a strange layout,"
4858
                                 " expected one secondary but found %d" %
4859
                                 len(instance.secondary_nodes))
4860

    
4861
    self.sec_node = instance.secondary_nodes[0]
4862

    
4863
    if self.op.iallocator is not None:
4864
      self._RunAllocator()
4865

    
4866
    remote_node = self.op.remote_node
4867
    if remote_node is not None:
4868
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
4869
      assert self.remote_node_info is not None, \
4870
        "Cannot retrieve locked node %s" % remote_node
4871
    else:
4872
      self.remote_node_info = None
4873
    if remote_node == instance.primary_node:
4874
      raise errors.OpPrereqError("The specified node is the primary node of"
4875
                                 " the instance.")
4876
    elif remote_node == self.sec_node:
4877
      raise errors.OpPrereqError("The specified node is already the"
4878
                                 " secondary node of the instance.")
4879

    
4880
    if self.op.mode == constants.REPLACE_DISK_PRI:
4881
      n1 = self.tgt_node = instance.primary_node
4882
      n2 = self.oth_node = self.sec_node
4883
    elif self.op.mode == constants.REPLACE_DISK_SEC:
4884
      n1 = self.tgt_node = self.sec_node
4885
      n2 = self.oth_node = instance.primary_node
4886
    elif self.op.mode == constants.REPLACE_DISK_CHG:
4887
      n1 = self.new_node = remote_node
4888
      n2 = self.oth_node = instance.primary_node
4889
      self.tgt_node = self.sec_node
4890
    else:
4891
      raise errors.ProgrammerError("Unhandled disk replace mode")
4892

    
4893
    _CheckNodeOnline(self, n1)
4894
    _CheckNodeOnline(self, n2)
4895

    
4896
    if not self.op.disks:
4897
      self.op.disks = range(len(instance.disks))
4898

    
4899
    for disk_idx in self.op.disks:
4900
      instance.FindDisk(disk_idx)
4901

    
4902
  def _ExecD8DiskOnly(self, feedback_fn):
4903
    """Replace a disk on the primary or secondary for dbrd8.
4904

4905
    The algorithm for replace is quite complicated:
4906

4907
      1. for each disk to be replaced:
4908

4909
        1. create new LVs on the target node with unique names
4910
        1. detach old LVs from the drbd device
4911
        1. rename old LVs to name_replaced.<time_t>
4912
        1. rename new LVs to old LVs
4913
        1. attach the new LVs (with the old names now) to the drbd device
4914

4915
      1. wait for sync across all devices
4916

4917
      1. for each modified disk:
4918

4919
        1. remove old LVs (which have the name name_replaces.<time_t>)
4920

4921
    Failures are not very well handled.
4922

4923
    """
4924
    steps_total = 6
4925
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
4926
    instance = self.instance
4927
    iv_names = {}
4928
    vgname = self.cfg.GetVGName()
4929
    # start of work
4930
    cfg = self.cfg
4931
    tgt_node = self.tgt_node
4932
    oth_node = self.oth_node
4933

    
4934
    # Step: check device activation
4935
    self.proc.LogStep(1, steps_total, "check device existence")
4936
    info("checking volume groups")
4937
    my_vg = cfg.GetVGName()
4938
    results = self.rpc.call_vg_list([oth_node, tgt_node])
4939
    if not results:
4940
      raise errors.OpExecError("Can't list volume groups on the nodes")
4941
    for node in oth_node, tgt_node:
4942
      res = results[node]
4943
      if res.failed or not res.data or my_vg not in res.data:
4944
        raise errors.OpExecError("Volume group '%s' not found on %s" %
4945
                                 (my_vg, node))
4946
    for idx, dev in enumerate(instance.disks):
4947
      if idx not in self.op.disks:
4948
        continue
4949
      for node in tgt_node, oth_node:
4950
        info("checking disk/%d on %s" % (idx, node))
4951
        cfg.SetDiskID(dev, node)
4952
        result = self.rpc.call_blockdev_find(node, dev)
4953
        msg = result.RemoteFailMsg()
4954
        if not msg and not result.payload:
4955
          msg = "disk not found"
4956
        if msg:
4957
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
4958
                                   (idx, node, msg))
4959

    
4960
    # Step: check other node consistency
4961
    self.proc.LogStep(2, steps_total, "check peer consistency")
4962
    for idx, dev in enumerate(instance.disks):
4963
      if idx not in self.op.disks:
4964
        continue
4965
      info("checking disk/%d consistency on %s" % (idx, oth_node))
4966
      if not _CheckDiskConsistency(self, dev, oth_node,
4967
                                   oth_node==instance.primary_node):
4968
        raise errors.OpExecError("Peer node (%s) has degraded storage, unsafe"
4969
                                 " to replace disks on this node (%s)" %
4970
                                 (oth_node, tgt_node))
4971

    
4972
    # Step: create new storage
4973
    self.proc.LogStep(3, steps_total, "allocate new storage")
4974
    for idx, dev in enumerate(instance.disks):
4975
      if idx not in self.op.disks:
4976
        continue
4977
      size = dev.size
4978
      cfg.SetDiskID(dev, tgt_node)
4979
      lv_names = [".disk%d_%s" % (idx, suf)
4980
                  for suf in ["data", "meta"]]
4981
      names = _GenerateUniqueNames(self, lv_names)
4982
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=size,
4983
                             logical_id=(vgname, names[0]))
4984
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
4985
                             logical_id=(vgname, names[1]))
4986
      new_lvs = [lv_data, lv_meta]
4987
      old_lvs = dev.children
4988
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
4989
      info("creating new local storage on %s for %s" %
4990
           (tgt_node, dev.iv_name))
4991
      # we pass force_create=True to force the LVM creation
4992
      for new_lv in new_lvs:
4993
        _CreateBlockDev(self, tgt_node, instance, new_lv, True,
4994
                        _GetInstanceInfoText(instance), False)
4995

    
4996
    # Step: for each lv, detach+rename*2+attach
4997
    self.proc.LogStep(4, steps_total, "change drbd configuration")
4998
    for dev, old_lvs, new_lvs in iv_names.itervalues():
4999
      info("detaching %s drbd from local storage" % dev.iv_name)
5000
      result = self.rpc.call_blockdev_removechildren(tgt_node, dev, old_lvs)
5001
      result.Raise()
5002
      if not result.data:
5003
        raise errors.OpExecError("Can't detach drbd from local storage on node"
5004
                                 " %s for device %s" % (tgt_node, dev.iv_name))
5005
      #dev.children = []
5006
      #cfg.Update(instance)
5007

    
5008
      # ok, we created the new LVs, so now we know we have the needed
5009
      # storage; as such, we proceed on the target node to rename
5010
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
5011
      # using the assumption that logical_id == physical_id (which in
5012
      # turn is the unique_id on that node)
5013

    
5014
      # FIXME(iustin): use a better name for the replaced LVs
5015
      temp_suffix = int(time.time())
5016
      ren_fn = lambda d, suff: (d.physical_id[0],
5017
                                d.physical_id[1] + "_replaced-%s" % suff)
5018
      # build the rename list based on what LVs exist on the node
5019
      rlist = []
5020
      for to_ren in old_lvs:
5021
        result = self.rpc.call_blockdev_find(tgt_node, to_ren)
5022
        if not result.RemoteFailMsg() and result.payload:
5023
          # device exists
5024
          rlist.append((to_ren, ren_fn(to_ren, temp_suffix)))
5025

    
5026
      info("renaming the old LVs on the target node")
5027
      result = self.rpc.call_blockdev_rename(tgt_node, rlist)
5028
      result.Raise()
5029
      if not result.data:
5030
        raise errors.OpExecError("Can't rename old LVs on node %s" % tgt_node)
5031
      # now we rename the new LVs to the old LVs
5032
      info("renaming the new LVs on the target node")
5033
      rlist = [(new, old.physical_id) for old, new in zip(old_lvs, new_lvs)]
5034
      result = self.rpc.call_blockdev_rename(tgt_node, rlist)
5035
      result.Raise()
5036
      if not result.data:
5037
        raise errors.OpExecError("Can't rename new LVs on node %s" % tgt_node)
5038

    
5039
      for old, new in zip(old_lvs, new_lvs):
5040
        new.logical_id = old.logical_id
5041
        cfg.SetDiskID(new, tgt_node)
5042

    
5043
      for disk in old_lvs:
5044
        disk.logical_id = ren_fn(disk, temp_suffix)
5045
        cfg.SetDiskID(disk, tgt_node)
5046

    
5047
      # now that the new lvs have the old name, we can add them to the device
5048
      info("adding new mirror component on %s" % tgt_node)
5049
      result = self.rpc.call_blockdev_addchildren(tgt_node, dev, new_lvs)
5050
      if result.failed or not result.data:
5051
        for new_lv in new_lvs:
5052
          msg = self.rpc.call_blockdev_remove(tgt_node, new_lv).RemoteFailMsg()
5053
          if msg:
5054
            warning("Can't rollback device %s: %s", dev, msg,
5055
                    hint="cleanup manually the unused logical volumes")
5056
        raise errors.OpExecError("Can't add local storage to drbd")
5057

    
5058
      dev.children = new_lvs
5059
      cfg.Update(instance)
5060

    
5061
    # Step: wait for sync
5062

    
5063
    # this can fail as the old devices are degraded and _WaitForSync
5064
    # does a combined result over all disks, so we don't check its
5065
    # return value
5066
    self.proc.LogStep(5, steps_total, "sync devices")
5067
    _WaitForSync(self, instance, unlock=True)
5068

    
5069
    # so check manually all the devices
5070
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
5071
      cfg.SetDiskID(dev, instance.primary_node)
5072
      result = self.rpc.call_blockdev_find(instance.primary_node, dev)
5073
      msg = result.RemoteFailMsg()
5074
      if not msg and not result.payload:
5075
        msg = "disk not found"
5076
      if msg:
5077
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
5078
                                 (name, msg))
5079
      if result.payload[5]:
5080
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
5081

    
5082
    # Step: remove old storage
5083
    self.proc.LogStep(6, steps_total, "removing old storage")
5084
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
5085
      info("remove logical volumes for %s" % name)
5086
      for lv in old_lvs:
5087
        cfg.SetDiskID(lv, tgt_node)
5088
        msg = self.rpc.call_blockdev_remove(tgt_node, lv).RemoteFailMsg()
5089
        if msg:
5090
          warning("Can't remove old LV: %s" % msg,
5091
                  hint="manually remove unused LVs")
5092
          continue
5093

    
5094
  def _ExecD8Secondary(self, feedback_fn):
5095
    """Replace the secondary node for drbd8.
5096

5097
    The algorithm for replace is quite complicated:
5098
      - for all disks of the instance:
5099
        - create new LVs on the new node with same names
5100
        - shutdown the drbd device on the old secondary
5101
        - disconnect the drbd network on the primary
5102
        - create the drbd device on the new secondary
5103
        - network attach the drbd on the primary, using an artifice:
5104
          the drbd code for Attach() will connect to the network if it
5105
          finds a device which is connected to the good local disks but
5106
          not network enabled
5107
      - wait for sync across all devices
5108
      - remove all disks from the old secondary
5109

5110
    Failures are not very well handled.
5111

5112
    """
5113
    steps_total = 6
5114
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
5115
    instance = self.instance
5116
    iv_names = {}
5117
    # start of work
5118
    cfg = self.cfg
5119
    old_node = self.tgt_node
5120
    new_node = self.new_node
5121
    pri_node = instance.primary_node
5122
    nodes_ip = {
5123
      old_node: self.cfg.GetNodeInfo(old_node).secondary_ip,
5124
      new_node: self.cfg.GetNodeInfo(new_node).secondary_ip,
5125
      pri_node: self.cfg.GetNodeInfo(pri_node).secondary_ip,
5126
      }
5127

    
5128
    # Step: check device activation
5129
    self.proc.LogStep(1, steps_total, "check device existence")
5130
    info("checking volume groups")
5131
    my_vg = cfg.GetVGName()
5132
    results = self.rpc.call_vg_list([pri_node, new_node])
5133
    for node in pri_node, new_node:
5134
      res = results[node]
5135
      if res.failed or not res.data or my_vg not in res.data:
5136
        raise errors.OpExecError("Volume group '%s' not found on %s" %
5137
                                 (my_vg, node))
5138
    for idx, dev in enumerate(instance.disks):
5139
      if idx not in self.op.disks:
5140
        continue
5141
      info("checking disk/%d on %s" % (idx, pri_node))
5142
      cfg.SetDiskID(dev, pri_node)
5143
      result = self.rpc.call_blockdev_find(pri_node, dev)
5144
      msg = result.RemoteFailMsg()
5145
      if not msg and not result.payload:
5146
        msg = "disk not found"
5147
      if msg:
5148
        raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
5149
                                 (idx, pri_node, msg))
5150

    
5151
    # Step: check other node consistency
5152
    self.proc.LogStep(2, steps_total, "check peer consistency")
5153
    for idx, dev in enumerate(instance.disks):
5154
      if idx not in self.op.disks:
5155
        continue
5156
      info("checking disk/%d consistency on %s" % (idx, pri_node))
5157
      if not _CheckDiskConsistency(self, dev, pri_node, True, ldisk=True):
5158
        raise errors.OpExecError("Primary node (%s) has degraded storage,"
5159
                                 " unsafe to replace the secondary" %
5160
                                 pri_node)
5161

    
5162
    # Step: create new storage
5163
    self.proc.LogStep(3, steps_total, "allocate new storage")
5164
    for idx, dev in enumerate(instance.disks):
5165
      info("adding new local storage on %s for disk/%d" %
5166
           (new_node, idx))
5167
      # we pass force_create=True to force LVM creation
5168
      for new_lv in dev.children:
5169
        _CreateBlockDev(self, new_node, instance, new_lv, True,
5170
                        _GetInstanceInfoText(instance), False)
5171

    
5172
    # Step 4: dbrd minors and drbd setups changes
5173
    # after this, we must manually remove the drbd minors on both the
5174
    # error and the success paths
5175
    minors = cfg.AllocateDRBDMinor([new_node for dev in instance.disks],
5176
                                   instance.name)
5177
    logging.debug("Allocated minors %s" % (minors,))
5178
    self.proc.LogStep(4, steps_total, "changing drbd configuration")
5179
    for idx, (dev, new_minor) in enumerate(zip(instance.disks, minors)):
5180
      size = dev.size
5181
      info("activating a new drbd on %s for disk/%d" % (new_node, idx))
5182
      # create new devices on new_node; note that we create two IDs:
5183
      # one without port, so the drbd will be activated without
5184
      # networking information on the new node at this stage, and one
5185
      # with network, for the latter activation in step 4
5186
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
5187
      if pri_node == o_node1:
5188
        p_minor = o_minor1
5189
      else:
5190
        p_minor = o_minor2
5191

    
5192
      new_alone_id = (pri_node, new_node, None, p_minor, new_minor, o_secret)
5193
      new_net_id = (pri_node, new_node, o_port, p_minor, new_minor, o_secret)
5194

    
5195
      iv_names[idx] = (dev, dev.children, new_net_id)
5196
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
5197
                    new_net_id)
5198
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
5199
                              logical_id=new_alone_id,
5200
                              children=dev.children)
5201
      try:
5202
        _CreateSingleBlockDev(self, new_node, instance, new_drbd,
5203
                              _GetInstanceInfoText(instance), False)
5204
      except errors.BlockDeviceError:
5205
        self.cfg.ReleaseDRBDMinors(instance.name)
5206
        raise
5207

    
5208
    for idx, dev in enumerate(instance.disks):
5209
      # we have new devices, shutdown the drbd on the old secondary
5210
      info("shutting down drbd for disk/%d on old node" % idx)
5211
      cfg.SetDiskID(dev, old_node)
5212
      msg = self.rpc.call_blockdev_shutdown(old_node, dev).RemoteFailMsg()
5213
      if msg:
5214
        warning("Failed to shutdown drbd for disk/%d on old node: %s" %
5215
                (idx, msg),
5216
                hint="Please cleanup this device manually as soon as possible")
5217

    
5218
    info("detaching primary drbds from the network (=> standalone)")
5219
    result = self.rpc.call_drbd_disconnect_net([pri_node], nodes_ip,
5220
                                               instance.disks)[pri_node]
5221

    
5222
    msg = result.RemoteFailMsg()
5223
    if msg:
5224
      # detaches didn't succeed (unlikely)
5225
      self.cfg.ReleaseDRBDMinors(instance.name)
5226
      raise errors.OpExecError("Can't detach the disks from the network on"
5227
                               " old node: %s" % (msg,))
5228

    
5229
    # if we managed to detach at least one, we update all the disks of
5230
    # the instance to point to the new secondary
5231
    info("updating instance configuration")
5232
    for dev, _, new_logical_id in iv_names.itervalues():
5233
      dev.logical_id = new_logical_id
5234
      cfg.SetDiskID(dev, pri_node)
5235
    cfg.Update(instance)
5236

    
5237
    # and now perform the drbd attach
5238
    info("attaching primary drbds to new secondary (standalone => connected)")
5239
    result = self.rpc.call_drbd_attach_net([pri_node, new_node], nodes_ip,
5240
                                           instance.disks, instance.name,
5241
                                           False)
5242
    for to_node, to_result in result.items():
5243
      msg = to_result.RemoteFailMsg()
5244
      if msg:
5245
        warning("can't attach drbd disks on node %s: %s", to_node, msg,
5246
                hint="please do a gnt-instance info to see the"
5247
                " status of disks")
5248

    
5249
    # this can fail as the old devices are degraded and _WaitForSync
5250
    # does a combined result over all disks, so we don't check its
5251
    # return value
5252
    self.proc.LogStep(5, steps_total, "sync devices")
5253
    _WaitForSync(self, instance, unlock=True)
5254

    
5255
    # so check manually all the devices
5256
    for idx, (dev, old_lvs, _) in iv_names.iteritems():
5257
      cfg.SetDiskID(dev, pri_node)
5258
      result = self.rpc.call_blockdev_find(pri_node, dev)
5259
      msg = result.RemoteFailMsg()
5260
      if not msg and not result.payload:
5261
        msg = "disk not found"
5262
      if msg:
5263
        raise errors.OpExecError("Can't find DRBD device disk/%d: %s" %
5264
                                 (idx, msg))
5265
      if result.payload[5]:
5266
        raise errors.OpExecError("DRBD device disk/%d is degraded!" % idx)
5267

    
5268
    self.proc.LogStep(6, steps_total, "removing old storage")
5269
    for idx, (dev, old_lvs, _) in iv_names.iteritems():
5270
      info("remove logical volumes for disk/%d" % idx)
5271
      for lv in old_lvs:
5272
        cfg.SetDiskID(lv, old_node)
5273
        msg = self.rpc.call_blockdev_remove(old_node, lv).RemoteFailMsg()
5274
        if msg:
5275
          warning("Can't remove LV on old secondary: %s", msg,
5276
                  hint="Cleanup stale volumes by hand")
5277

    
5278
  def Exec(self, feedback_fn):
5279
    """Execute disk replacement.
5280

5281
    This dispatches the disk replacement to the appropriate handler.
5282

5283
    """
5284
    instance = self.instance
5285

    
5286
    # Activate the instance disks if we're replacing them on a down instance
5287
    if not instance.admin_up:
5288
      _StartInstanceDisks(self, instance, True)
5289

    
5290
    if self.op.mode == constants.REPLACE_DISK_CHG:
5291
      fn = self._ExecD8Secondary
5292
    else:
5293
      fn = self._ExecD8DiskOnly
5294

    
5295
    ret = fn(feedback_fn)
5296

    
5297
    # Deactivate the instance disks if we're replacing them on a down instance
5298
    if not instance.admin_up:
5299
      _SafeShutdownInstanceDisks(self, instance)
5300

    
5301
    return ret
5302

    
5303

    
5304
class LUGrowDisk(LogicalUnit):
5305
  """Grow a disk of an instance.
5306

5307
  """
5308
  HPATH = "disk-grow"
5309
  HTYPE = constants.HTYPE_INSTANCE
5310
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
5311
  REQ_BGL = False
5312

    
5313
  def ExpandNames(self):
5314
    self._ExpandAndLockInstance()
5315
    self.needed_locks[locking.LEVEL_NODE] = []
5316
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5317

    
5318
  def DeclareLocks(self, level):
5319
    if level == locking.LEVEL_NODE:
5320
      self._LockInstancesNodes()
5321

    
5322
  def BuildHooksEnv(self):
5323
    """Build hooks env.
5324

5325
    This runs on the master, the primary and all the secondaries.
5326

5327
    """
5328
    env = {
5329
      "DISK": self.op.disk,
5330
      "AMOUNT": self.op.amount,
5331
      }
5332
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5333
    nl = [
5334
      self.cfg.GetMasterNode(),
5335
      self.instance.primary_node,
5336
      ]
5337
    return env, nl, nl
5338

    
5339
  def CheckPrereq(self):
5340
    """Check prerequisites.
5341

5342
    This checks that the instance is in the cluster.
5343

5344
    """
5345
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5346
    assert instance is not None, \
5347
      "Cannot retrieve locked instance %s" % self.op.instance_name
5348
    nodenames = list(instance.all_nodes)
5349
    for node in nodenames:
5350
      _CheckNodeOnline(self, node)
5351

    
5352

    
5353
    self.instance = instance
5354

    
5355
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
5356
      raise errors.OpPrereqError("Instance's disk layout does not support"
5357
                                 " growing.")
5358

    
5359
    self.disk = instance.FindDisk(self.op.disk)
5360

    
5361
    nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
5362
                                       instance.hypervisor)
5363
    for node in nodenames:
5364
      info = nodeinfo[node]
5365
      if info.failed or not info.data:
5366
        raise errors.OpPrereqError("Cannot get current information"
5367
                                   " from node '%s'" % node)
5368
      vg_free = info.data.get('vg_free', None)
5369
      if not isinstance(vg_free, int):
5370
        raise errors.OpPrereqError("Can't compute free disk space on"
5371
                                   " node %s" % node)
5372
      if self.op.amount > vg_free:
5373
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
5374
                                   " %d MiB available, %d MiB required" %
5375
                                   (node, vg_free, self.op.amount))
5376

    
5377
  def Exec(self, feedback_fn):
5378
    """Execute disk grow.
5379

5380
    """
5381
    instance = self.instance
5382
    disk = self.disk
5383
    for node in instance.all_nodes:
5384
      self.cfg.SetDiskID(disk, node)
5385
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
5386
      msg = result.RemoteFailMsg()
5387
      if msg:
5388
        raise errors.OpExecError("Grow request failed to node %s: %s" %
5389
                                 (node, msg))
5390
    disk.RecordGrow(self.op.amount)
5391
    self.cfg.Update(instance)
5392
    if self.op.wait_for_sync:
5393
      disk_abort = not _WaitForSync(self, instance)
5394
      if disk_abort:
5395
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
5396
                             " status.\nPlease check the instance.")
5397

    
5398

    
5399
class LUQueryInstanceData(NoHooksLU):
5400
  """Query runtime instance data.
5401

5402
  """
5403
  _OP_REQP = ["instances", "static"]
5404
  REQ_BGL = False
5405

    
5406
  def ExpandNames(self):
5407
    self.needed_locks = {}
5408
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
5409

    
5410
    if not isinstance(self.op.instances, list):
5411
      raise errors.OpPrereqError("Invalid argument type 'instances'")
5412

    
5413
    if self.op.instances:
5414
      self.wanted_names = []
5415
      for name in self.op.instances:
5416
        full_name = self.cfg.ExpandInstanceName(name)
5417
        if full_name is None:
5418
          raise errors.OpPrereqError("Instance '%s' not known" % name)
5419
        self.wanted_names.append(full_name)
5420
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
5421
    else:
5422
      self.wanted_names = None
5423
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
5424

    
5425
    self.needed_locks[locking.LEVEL_NODE] = []
5426
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5427

    
5428
  def DeclareLocks(self, level):
5429
    if level == locking.LEVEL_NODE:
5430
      self._LockInstancesNodes()
5431

    
5432
  def CheckPrereq(self):
5433
    """Check prerequisites.
5434

5435
    This only checks the optional instance list against the existing names.
5436

5437
    """
5438
    if self.wanted_names is None:
5439
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5440

    
5441
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
5442
                             in self.wanted_names]
5443
    return
5444

    
5445
  def _ComputeDiskStatus(self, instance, snode, dev):
5446
    """Compute block device status.
5447

5448
    """
5449
    static = self.op.static
5450
    if not static:
5451
      self.cfg.SetDiskID(dev, instance.primary_node)
5452
      dev_pstatus = self.rpc.call_blockdev_find(instance.primary_node, dev)
5453
      msg = dev_pstatus.RemoteFailMsg()
5454
      if msg:
5455
        raise errors.OpExecError("Can't compute disk status for %s: %s" %
5456
                                 (instance.name, msg))
5457
      dev_pstatus = dev_pstatus.payload
5458
    else:
5459
      dev_pstatus = None
5460

    
5461
    if dev.dev_type in constants.LDS_DRBD:
5462
      # we change the snode then (otherwise we use the one passed in)
5463
      if dev.logical_id[0] == instance.primary_node:
5464
        snode = dev.logical_id[1]
5465
      else:
5466
        snode = dev.logical_id[0]
5467

    
5468
    if snode and not static:
5469
      self.cfg.SetDiskID(dev, snode)
5470
      dev_sstatus = self.rpc.call_blockdev_find(snode, dev)
5471
      msg = dev_sstatus.RemoteFailMsg()
5472
      if msg:
5473
        raise errors.OpExecError("Can't compute disk status for %s: %s" %
5474
                                 (instance.name, msg))
5475
      dev_sstatus = dev_sstatus.payload
5476
    else:
5477
      dev_sstatus = None
5478

    
5479
    if dev.children:
5480
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
5481
                      for child in dev.children]
5482
    else:
5483
      dev_children = []
5484

    
5485
    data = {
5486
      "iv_name": dev.iv_name,
5487
      "dev_type": dev.dev_type,
5488
      "logical_id": dev.logical_id,
5489
      "physical_id": dev.physical_id,
5490
      "pstatus": dev_pstatus,
5491
      "sstatus": dev_sstatus,
5492
      "children": dev_children,
5493
      "mode": dev.mode,
5494
      }
5495

    
5496
    return data
5497

    
5498
  def Exec(self, feedback_fn):
5499
    """Gather and return data"""
5500
    result = {}
5501

    
5502
    cluster = self.cfg.GetClusterInfo()
5503

    
5504
    for instance in self.wanted_instances:
5505
      if not self.op.static:
5506
        remote_info = self.rpc.call_instance_info(instance.primary_node,
5507
                                                  instance.name,
5508
                                                  instance.hypervisor)
5509
        remote_info.Raise()
5510
        remote_info = remote_info.data
5511
        if remote_info and "state" in remote_info:
5512
          remote_state = "up"
5513
        else:
5514
          remote_state = "down"
5515
      else:
5516
        remote_state = None
5517
      if instance.admin_up:
5518
        config_state = "up"
5519
      else:
5520
        config_state = "down"
5521

    
5522
      disks = [self._ComputeDiskStatus(instance, None, device)
5523
               for device in instance.disks]
5524

    
5525
      idict = {
5526
        "name": instance.name,
5527
        "config_state": config_state,
5528
        "run_state": remote_state,
5529
        "pnode": instance.primary_node,
5530
        "snodes": instance.secondary_nodes,
5531
        "os": instance.os,
5532
        "nics": [(nic.mac, nic.ip, nic.bridge) for nic in instance.nics],
5533
        "disks": disks,
5534
        "hypervisor": instance.hypervisor,
5535
        "network_port": instance.network_port,
5536
        "hv_instance": instance.hvparams,
5537
        "hv_actual": cluster.FillHV(instance),
5538
        "be_instance": instance.beparams,
5539
        "be_actual": cluster.FillBE(instance),
5540
        }
5541

    
5542
      result[instance.name] = idict
5543

    
5544
    return result
5545

    
5546

    
5547
class LUSetInstanceParams(LogicalUnit):
5548
  """Modifies an instances's parameters.
5549

5550
  """
5551
  HPATH = "instance-modify"
5552
  HTYPE = constants.HTYPE_INSTANCE
5553
  _OP_REQP = ["instance_name"]
5554
  REQ_BGL = False
5555

    
5556
  def CheckArguments(self):
5557
    if not hasattr(self.op, 'nics'):
5558
      self.op.nics = []
5559
    if not hasattr(self.op, 'disks'):
5560
      self.op.disks = []
5561
    if not hasattr(self.op, 'beparams'):
5562
      self.op.beparams = {}
5563
    if not hasattr(self.op, 'hvparams'):
5564
      self.op.hvparams = {}
5565
    self.op.force = getattr(self.op, "force", False)
5566
    if not (self.op.nics or self.op.disks or
5567
            self.op.hvparams or self.op.beparams):
5568
      raise errors.OpPrereqError("No changes submitted")
5569

    
5570
    utils.CheckBEParams(self.op.beparams)
5571

    
5572
    # Disk validation
5573
    disk_addremove = 0
5574
    for disk_op, disk_dict in self.op.disks:
5575
      if disk_op == constants.DDM_REMOVE:
5576
        disk_addremove += 1
5577
        continue
5578
      elif disk_op == constants.DDM_ADD:
5579
        disk_addremove += 1
5580
      else:
5581
        if not isinstance(disk_op, int):
5582
          raise errors.OpPrereqError("Invalid disk index")
5583
      if disk_op == constants.DDM_ADD:
5584
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
5585
        if mode not in constants.DISK_ACCESS_SET:
5586
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode)
5587
        size = disk_dict.get('size', None)
5588
        if size is None:
5589
          raise errors.OpPrereqError("Required disk parameter size missing")
5590
        try:
5591
          size = int(size)
5592
        except ValueError, err:
5593
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
5594
                                     str(err))
5595
        disk_dict['size'] = size
5596
      else:
5597
        # modification of disk
5598
        if 'size' in disk_dict:
5599
          raise errors.OpPrereqError("Disk size change not possible, use"
5600
                                     " grow-disk")
5601

    
5602
    if disk_addremove > 1:
5603
      raise errors.OpPrereqError("Only one disk add or remove operation"
5604
                                 " supported at a time")
5605

    
5606
    # NIC validation
5607
    nic_addremove = 0
5608
    for nic_op, nic_dict in self.op.nics:
5609
      if nic_op == constants.DDM_REMOVE:
5610
        nic_addremove += 1
5611
        continue
5612
      elif nic_op == constants.DDM_ADD:
5613
        nic_addremove += 1
5614
      else:
5615
        if not isinstance(nic_op, int):
5616
          raise errors.OpPrereqError("Invalid nic index")
5617

    
5618
      # nic_dict should be a dict
5619
      nic_ip = nic_dict.get('ip', None)
5620
      if nic_ip is not None:
5621
        if nic_ip.lower() == "none":
5622
          nic_dict['ip'] = None
5623
        else:
5624
          if not utils.IsValidIP(nic_ip):
5625
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip)
5626
      # we can only check None bridges and assign the default one
5627
      nic_bridge = nic_dict.get('bridge', None)
5628
      if nic_bridge is None:
5629
        nic_dict['bridge'] = self.cfg.GetDefBridge()
5630
      # but we can validate MACs
5631
      nic_mac = nic_dict.get('mac', None)
5632
      if nic_mac is not None:
5633
        if self.cfg.IsMacInUse(nic_mac):
5634
          raise errors.OpPrereqError("MAC address %s already in use"
5635
                                     " in cluster" % nic_mac)
5636
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5637
          if not utils.IsValidMac(nic_mac):
5638
            raise errors.OpPrereqError("Invalid MAC address %s" % nic_mac)
5639
    if nic_addremove > 1:
5640
      raise errors.OpPrereqError("Only one NIC add or remove operation"
5641
                                 " supported at a time")
5642

    
5643
  def ExpandNames(self):
5644
    self._ExpandAndLockInstance()
5645
    self.needed_locks[locking.LEVEL_NODE] = []
5646
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5647

    
5648
  def DeclareLocks(self, level):
5649
    if level == locking.LEVEL_NODE:
5650
      self._LockInstancesNodes()
5651

    
5652
  def BuildHooksEnv(self):
5653
    """Build hooks env.
5654

5655
    This runs on the master, primary and secondaries.
5656

5657
    """
5658
    args = dict()
5659
    if constants.BE_MEMORY in self.be_new:
5660
      args['memory'] = self.be_new[constants.BE_MEMORY]
5661
    if constants.BE_VCPUS in self.be_new:
5662
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
5663
    # FIXME: readd disk/nic changes
5664
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
5665
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5666
    return env, nl, nl
5667

    
5668
  def CheckPrereq(self):
5669
    """Check prerequisites.
5670

5671
    This only checks the instance list against the existing names.
5672

5673
    """
5674
    force = self.force = self.op.force
5675

    
5676
    # checking the new params on the primary/secondary nodes
5677

    
5678
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5679
    assert self.instance is not None, \
5680
      "Cannot retrieve locked instance %s" % self.op.instance_name
5681
    pnode = instance.primary_node
5682
    nodelist = list(instance.all_nodes)
5683

    
5684
    # hvparams processing
5685
    if self.op.hvparams:
5686
      i_hvdict = copy.deepcopy(instance.hvparams)
5687
      for key, val in self.op.hvparams.iteritems():
5688
        if val == constants.VALUE_DEFAULT:
5689
          try:
5690
            del i_hvdict[key]
5691
          except KeyError:
5692
            pass
5693
        elif val == constants.VALUE_NONE:
5694
          i_hvdict[key] = None
5695
        else:
5696
          i_hvdict[key] = val
5697
      cluster = self.cfg.GetClusterInfo()
5698
      hv_new = cluster.FillDict(cluster.hvparams[instance.hypervisor],
5699
                                i_hvdict)
5700
      # local check
5701
      hypervisor.GetHypervisor(
5702
        instance.hypervisor).CheckParameterSyntax(hv_new)
5703
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
5704
      self.hv_new = hv_new # the new actual values
5705
      self.hv_inst = i_hvdict # the new dict (without defaults)
5706
    else:
5707
      self.hv_new = self.hv_inst = {}
5708

    
5709
    # beparams processing
5710
    if self.op.beparams:
5711
      i_bedict = copy.deepcopy(instance.beparams)
5712
      for key, val in self.op.beparams.iteritems():
5713
        if val == constants.VALUE_DEFAULT:
5714
          try:
5715
            del i_bedict[key]
5716
          except KeyError:
5717
            pass
5718
        else:
5719
          i_bedict[key] = val
5720
      cluster = self.cfg.GetClusterInfo()
5721
      be_new = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
5722
                                i_bedict)
5723
      self.be_new = be_new # the new actual values
5724
      self.be_inst = i_bedict # the new dict (without defaults)
5725
    else:
5726
      self.be_new = self.be_inst = {}
5727

    
5728
    self.warn = []
5729

    
5730
    if constants.BE_MEMORY in self.op.beparams and not self.force:
5731
      mem_check_list = [pnode]
5732
      if be_new[constants.BE_AUTO_BALANCE]:
5733
        # either we changed auto_balance to yes or it was from before
5734
        mem_check_list.extend(instance.secondary_nodes)
5735
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
5736
                                                  instance.hypervisor)
5737
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
5738
                                         instance.hypervisor)
5739
      if nodeinfo[pnode].failed or not isinstance(nodeinfo[pnode].data, dict):
5740
        # Assume the primary node is unreachable and go ahead
5741
        self.warn.append("Can't get info from primary node %s" % pnode)
5742
      else:
5743
        if not instance_info.failed and instance_info.data:
5744
          current_mem = instance_info.data['memory']
5745
        else:
5746
          # Assume instance not running
5747
          # (there is a slight race condition here, but it's not very probable,
5748
          # and we have no other way to check)
5749
          current_mem = 0
5750
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
5751
                    nodeinfo[pnode].data['memory_free'])
5752
        if miss_mem > 0:
5753
          raise errors.OpPrereqError("This change will prevent the instance"
5754
                                     " from starting, due to %d MB of memory"
5755
                                     " missing on its primary node" % miss_mem)
5756

    
5757
      if be_new[constants.BE_AUTO_BALANCE]:
5758
        for node, nres in nodeinfo.iteritems():
5759
          if node not in instance.secondary_nodes:
5760
            continue
5761
          if nres.failed or not isinstance(nres.data, dict):
5762
            self.warn.append("Can't get info from secondary node %s" % node)
5763
          elif be_new[constants.BE_MEMORY] > nres.data['memory_free']:
5764
            self.warn.append("Not enough memory to failover instance to"
5765
                             " secondary node %s" % node)
5766

    
5767
    # NIC processing
5768
    for nic_op, nic_dict in self.op.nics:
5769
      if nic_op == constants.DDM_REMOVE:
5770
        if not instance.nics:
5771
          raise errors.OpPrereqError("Instance has no NICs, cannot remove")
5772
        continue
5773
      if nic_op != constants.DDM_ADD:
5774
        # an existing nic
5775
        if nic_op < 0 or nic_op >= len(instance.nics):
5776
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
5777
                                     " are 0 to %d" %
5778
                                     (nic_op, len(instance.nics)))
5779
      nic_bridge = nic_dict.get('bridge', None)
5780
      if nic_bridge is not None:
5781
        if not self.rpc.call_bridges_exist(pnode, [nic_bridge]):
5782
          msg = ("Bridge '%s' doesn't exist on one of"
5783
                 " the instance nodes" % nic_bridge)
5784
          if self.force:
5785
            self.warn.append(msg)
5786
          else:
5787
            raise errors.OpPrereqError(msg)
5788

    
5789
    # DISK processing
5790
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
5791
      raise errors.OpPrereqError("Disk operations not supported for"
5792
                                 " diskless instances")
5793
    for disk_op, disk_dict in self.op.disks:
5794
      if disk_op == constants.DDM_REMOVE:
5795
        if len(instance.disks) == 1:
5796
          raise errors.OpPrereqError("Cannot remove the last disk of"
5797
                                     " an instance")
5798
        ins_l = self.rpc.call_instance_list([pnode], [instance.hypervisor])
5799
        ins_l = ins_l[pnode]
5800
        if ins_l.failed or not isinstance(ins_l.data, list):
5801
          raise errors.OpPrereqError("Can't contact node '%s'" % pnode)
5802
        if instance.name in ins_l.data:
5803
          raise errors.OpPrereqError("Instance is running, can't remove"
5804
                                     " disks.")
5805

    
5806
      if (disk_op == constants.DDM_ADD and
5807
          len(instance.nics) >= constants.MAX_DISKS):
5808
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
5809
                                   " add more" % constants.MAX_DISKS)
5810
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
5811
        # an existing disk
5812
        if disk_op < 0 or disk_op >= len(instance.disks):
5813
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
5814
                                     " are 0 to %d" %
5815
                                     (disk_op, len(instance.disks)))
5816

    
5817
    return
5818

    
5819
  def Exec(self, feedback_fn):
5820
    """Modifies an instance.
5821

5822
    All parameters take effect only at the next restart of the instance.
5823

5824
    """
5825
    # Process here the warnings from CheckPrereq, as we don't have a
5826
    # feedback_fn there.
5827
    for warn in self.warn:
5828
      feedback_fn("WARNING: %s" % warn)
5829

    
5830
    result = []
5831
    instance = self.instance
5832
    # disk changes
5833
    for disk_op, disk_dict in self.op.disks:
5834
      if disk_op == constants.DDM_REMOVE:
5835
        # remove the last disk
5836
        device = instance.disks.pop()
5837
        device_idx = len(instance.disks)
5838
        for node, disk in device.ComputeNodeTree(instance.primary_node):
5839
          self.cfg.SetDiskID(disk, node)
5840
          msg = self.rpc.call_blockdev_remove(node, disk).RemoteFailMsg()
5841
          if msg:
5842
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
5843
                            " continuing anyway", device_idx, node, msg)
5844
        result.append(("disk/%d" % device_idx, "remove"))
5845
      elif disk_op == constants.DDM_ADD:
5846
        # add a new disk
5847
        if instance.disk_template == constants.DT_FILE:
5848
          file_driver, file_path = instance.disks[0].logical_id
5849
          file_path = os.path.dirname(file_path)
5850
        else:
5851
          file_driver = file_path = None
5852
        disk_idx_base = len(instance.disks)
5853
        new_disk = _GenerateDiskTemplate(self,
5854
                                         instance.disk_template,
5855
                                         instance.name, instance.primary_node,
5856
                                         instance.secondary_nodes,
5857
                                         [disk_dict],
5858
                                         file_path,
5859
                                         file_driver,
5860
                                         disk_idx_base)[0]
5861
        instance.disks.append(new_disk)
5862
        info = _GetInstanceInfoText(instance)
5863

    
5864
        logging.info("Creating volume %s for instance %s",
5865
                     new_disk.iv_name, instance.name)
5866
        # Note: this needs to be kept in sync with _CreateDisks
5867
        #HARDCODE
5868
        for node in instance.all_nodes:
5869
          f_create = node == instance.primary_node
5870
          try:
5871
            _CreateBlockDev(self, node, instance, new_disk,
5872
                            f_create, info, f_create)
5873
          except errors.OpExecError, err:
5874
            self.LogWarning("Failed to create volume %s (%s) on"
5875
                            " node %s: %s",
5876
                            new_disk.iv_name, new_disk, node, err)
5877
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
5878
                       (new_disk.size, new_disk.mode)))
5879
      else:
5880
        # change a given disk
5881
        instance.disks[disk_op].mode = disk_dict['mode']
5882
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
5883
    # NIC changes
5884
    for nic_op, nic_dict in self.op.nics:
5885
      if nic_op == constants.DDM_REMOVE:
5886
        # remove the last nic
5887
        del instance.nics[-1]
5888
        result.append(("nic.%d" % len(instance.nics), "remove"))
5889
      elif nic_op == constants.DDM_ADD:
5890
        # add a new nic
5891
        if 'mac' not in nic_dict:
5892
          mac = constants.VALUE_GENERATE
5893
        else:
5894
          mac = nic_dict['mac']
5895
        if mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5896
          mac = self.cfg.GenerateMAC()
5897
        new_nic = objects.NIC(mac=mac, ip=nic_dict.get('ip', None),
5898
                              bridge=nic_dict.get('bridge', None))
5899
        instance.nics.append(new_nic)
5900
        result.append(("nic.%d" % (len(instance.nics) - 1),
5901
                       "add:mac=%s,ip=%s,bridge=%s" %
5902
                       (new_nic.mac, new_nic.ip, new_nic.bridge)))
5903
      else:
5904
        # change a given nic
5905
        for key in 'mac', 'ip', 'bridge':
5906
          if key in nic_dict:
5907
            setattr(instance.nics[nic_op], key, nic_dict[key])
5908
            result.append(("nic.%s/%d" % (key, nic_op), nic_dict[key]))
5909

    
5910
    # hvparams changes
5911
    if self.op.hvparams:
5912
      instance.hvparams = self.hv_inst
5913
      for key, val in self.op.hvparams.iteritems():
5914
        result.append(("hv/%s" % key, val))
5915

    
5916
    # beparams changes
5917
    if self.op.beparams:
5918
      instance.beparams = self.be_inst
5919
      for key, val in self.op.beparams.iteritems():
5920
        result.append(("be/%s" % key, val))
5921

    
5922
    self.cfg.Update(instance)
5923

    
5924
    return result
5925

    
5926

    
5927
class LUQueryExports(NoHooksLU):
5928
  """Query the exports list
5929

5930
  """
5931
  _OP_REQP = ['nodes']
5932
  REQ_BGL = False
5933

    
5934
  def ExpandNames(self):
5935
    self.needed_locks = {}
5936
    self.share_locks[locking.LEVEL_NODE] = 1
5937
    if not self.op.nodes:
5938
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5939
    else:
5940
      self.needed_locks[locking.LEVEL_NODE] = \
5941
        _GetWantedNodes(self, self.op.nodes)
5942

    
5943
  def CheckPrereq(self):
5944
    """Check prerequisites.
5945

5946
    """
5947
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
5948

    
5949
  def Exec(self, feedback_fn):
5950
    """Compute the list of all the exported system images.
5951

5952
    @rtype: dict
5953
    @return: a dictionary with the structure node->(export-list)
5954
        where export-list is a list of the instances exported on
5955
        that node.
5956

5957
    """
5958
    rpcresult = self.rpc.call_export_list(self.nodes)
5959
    result = {}
5960
    for node in rpcresult:
5961
      if rpcresult[node].failed:
5962
        result[node] = False
5963
      else:
5964
        result[node] = rpcresult[node].data
5965

    
5966
    return result
5967

    
5968

    
5969
class LUExportInstance(LogicalUnit):
5970
  """Export an instance to an image in the cluster.
5971

5972
  """
5973
  HPATH = "instance-export"
5974
  HTYPE = constants.HTYPE_INSTANCE
5975
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
5976
  REQ_BGL = False
5977

    
5978
  def ExpandNames(self):
5979
    self._ExpandAndLockInstance()
5980
    # FIXME: lock only instance primary and destination node
5981
    #
5982
    # Sad but true, for now we have do lock all nodes, as we don't know where
5983
    # the previous export might be, and and in this LU we search for it and
5984
    # remove it from its current node. In the future we could fix this by:
5985
    #  - making a tasklet to search (share-lock all), then create the new one,
5986
    #    then one to remove, after
5987
    #  - removing the removal operation altoghether
5988
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5989

    
5990
  def DeclareLocks(self, level):
5991
    """Last minute lock declaration."""
5992
    # All nodes are locked anyway, so nothing to do here.
5993

    
5994
  def BuildHooksEnv(self):
5995
    """Build hooks env.
5996

5997
    This will run on the master, primary node and target node.
5998

5999
    """
6000
    env = {
6001
      "EXPORT_NODE": self.op.target_node,
6002
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
6003
      }
6004
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6005
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node,
6006
          self.op.target_node]
6007
    return env, nl, nl
6008

    
6009
  def CheckPrereq(self):
6010
    """Check prerequisites.
6011

6012
    This checks that the instance and node names are valid.
6013

6014
    """
6015
    instance_name = self.op.instance_name
6016
    self.instance = self.cfg.GetInstanceInfo(instance_name)
6017
    assert self.instance is not None, \
6018
          "Cannot retrieve locked instance %s" % self.op.instance_name
6019
    _CheckNodeOnline(self, self.instance.primary_node)
6020

    
6021
    self.dst_node = self.cfg.GetNodeInfo(
6022
      self.cfg.ExpandNodeName(self.op.target_node))
6023

    
6024
    if self.dst_node is None:
6025
      # This is wrong node name, not a non-locked node
6026
      raise errors.OpPrereqError("Wrong node name %s" % self.op.target_node)
6027
    _CheckNodeOnline(self, self.dst_node.name)
6028

    
6029
    # instance disk type verification
6030
    for disk in self.instance.disks:
6031
      if disk.dev_type == constants.LD_FILE:
6032
        raise errors.OpPrereqError("Export not supported for instances with"
6033
                                   " file-based disks")
6034

    
6035
  def Exec(self, feedback_fn):
6036
    """Export an instance to an image in the cluster.
6037

6038
    """
6039
    instance = self.instance
6040
    dst_node = self.dst_node
6041
    src_node = instance.primary_node
6042
    if self.op.shutdown:
6043
      # shutdown the instance, but not the disks
6044
      result = self.rpc.call_instance_shutdown(src_node, instance)
6045
      result.Raise()
6046
      if not result.data:
6047
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
6048
                                 (instance.name, src_node))
6049

    
6050
    vgname = self.cfg.GetVGName()
6051

    
6052
    snap_disks = []
6053

    
6054
    # set the disks ID correctly since call_instance_start needs the
6055
    # correct drbd minor to create the symlinks
6056
    for disk in instance.disks:
6057
      self.cfg.SetDiskID(disk, src_node)
6058

    
6059
    try:
6060
      for disk in instance.disks:
6061
        # new_dev_name will be a snapshot of an lvm leaf of the one we passed
6062
        new_dev_name = self.rpc.call_blockdev_snapshot(src_node, disk)
6063
        if new_dev_name.failed or not new_dev_name.data:
6064
          self.LogWarning("Could not snapshot block device %s on node %s",
6065
                          disk.logical_id[1], src_node)
6066
          snap_disks.append(False)
6067
        else:
6068
          new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
6069
                                 logical_id=(vgname, new_dev_name.data),
6070
                                 physical_id=(vgname, new_dev_name.data),
6071
                                 iv_name=disk.iv_name)
6072
          snap_disks.append(new_dev)
6073

    
6074
    finally:
6075
      if self.op.shutdown and instance.admin_up:
6076
        result = self.rpc.call_instance_start(src_node, instance, None)
6077
        msg = result.RemoteFailMsg()
6078
        if msg:
6079
          _ShutdownInstanceDisks(self, instance)
6080
          raise errors.OpExecError("Could not start instance: %s" % msg)
6081

    
6082
    # TODO: check for size
6083

    
6084
    cluster_name = self.cfg.GetClusterName()
6085
    for idx, dev in enumerate(snap_disks):
6086
      if dev:
6087
        result = self.rpc.call_snapshot_export(src_node, dev, dst_node.name,
6088
                                               instance, cluster_name, idx)
6089
        if result.failed or not result.data:
6090
          self.LogWarning("Could not export block device %s from node %s to"
6091
                          " node %s", dev.logical_id[1], src_node,
6092
                          dst_node.name)
6093
        msg = self.rpc.call_blockdev_remove(src_node, dev).RemoteFailMsg()
6094
        if msg:
6095
          self.LogWarning("Could not remove snapshot block device %s from node"
6096
                          " %s: %s", dev.logical_id[1], src_node, msg)
6097

    
6098
    result = self.rpc.call_finalize_export(dst_node.name, instance, snap_disks)
6099
    if result.failed or not result.data:
6100
      self.LogWarning("Could not finalize export for instance %s on node %s",
6101
                      instance.name, dst_node.name)
6102

    
6103
    nodelist = self.cfg.GetNodeList()
6104
    nodelist.remove(dst_node.name)
6105

    
6106
    # on one-node clusters nodelist will be empty after the removal
6107
    # if we proceed the backup would be removed because OpQueryExports
6108
    # substitutes an empty list with the full cluster node list.
6109
    if nodelist:
6110
      exportlist = self.rpc.call_export_list(nodelist)
6111
      for node in exportlist:
6112
        if exportlist[node].failed:
6113
          continue
6114
        if instance.name in exportlist[node].data:
6115
          if not self.rpc.call_export_remove(node, instance.name):
6116
            self.LogWarning("Could not remove older export for instance %s"
6117
                            " on node %s", instance.name, node)
6118

    
6119

    
6120
class LURemoveExport(NoHooksLU):
6121
  """Remove exports related to the named instance.
6122

6123
  """
6124
  _OP_REQP = ["instance_name"]
6125
  REQ_BGL = False
6126

    
6127
  def ExpandNames(self):
6128
    self.needed_locks = {}
6129
    # We need all nodes to be locked in order for RemoveExport to work, but we
6130
    # don't need to lock the instance itself, as nothing will happen to it (and
6131
    # we can remove exports also for a removed instance)
6132
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6133

    
6134
  def CheckPrereq(self):
6135
    """Check prerequisites.
6136
    """
6137
    pass
6138

    
6139
  def Exec(self, feedback_fn):
6140
    """Remove any export.
6141

6142
    """
6143
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
6144
    # If the instance was not found we'll try with the name that was passed in.
6145
    # This will only work if it was an FQDN, though.
6146
    fqdn_warn = False
6147
    if not instance_name:
6148
      fqdn_warn = True
6149
      instance_name = self.op.instance_name
6150

    
6151
    exportlist = self.rpc.call_export_list(self.acquired_locks[
6152
      locking.LEVEL_NODE])
6153
    found = False
6154
    for node in exportlist:
6155
      if exportlist[node].failed:
6156
        self.LogWarning("Failed to query node %s, continuing" % node)
6157
        continue
6158
      if instance_name in exportlist[node].data:
6159
        found = True
6160
        result = self.rpc.call_export_remove(node, instance_name)
6161
        if result.failed or not result.data:
6162
          logging.error("Could not remove export for instance %s"
6163
                        " on node %s", instance_name, node)
6164

    
6165
    if fqdn_warn and not found:
6166
      feedback_fn("Export not found. If trying to remove an export belonging"
6167
                  " to a deleted instance please use its Fully Qualified"
6168
                  " Domain Name.")
6169

    
6170

    
6171
class TagsLU(NoHooksLU):
6172
  """Generic tags LU.
6173

6174
  This is an abstract class which is the parent of all the other tags LUs.
6175

6176
  """
6177

    
6178
  def ExpandNames(self):
6179
    self.needed_locks = {}
6180
    if self.op.kind == constants.TAG_NODE:
6181
      name = self.cfg.ExpandNodeName(self.op.name)
6182
      if name is None:
6183
        raise errors.OpPrereqError("Invalid node name (%s)" %
6184
                                   (self.op.name,))
6185
      self.op.name = name
6186
      self.needed_locks[locking.LEVEL_NODE] = name
6187
    elif self.op.kind == constants.TAG_INSTANCE:
6188
      name = self.cfg.ExpandInstanceName(self.op.name)
6189
      if name is None:
6190
        raise errors.OpPrereqError("Invalid instance name (%s)" %
6191
                                   (self.op.name,))
6192
      self.op.name = name
6193
      self.needed_locks[locking.LEVEL_INSTANCE] = name
6194

    
6195
  def CheckPrereq(self):
6196
    """Check prerequisites.
6197

6198
    """
6199
    if self.op.kind == constants.TAG_CLUSTER:
6200
      self.target = self.cfg.GetClusterInfo()
6201
    elif self.op.kind == constants.TAG_NODE:
6202
      self.target = self.cfg.GetNodeInfo(self.op.name)
6203
    elif self.op.kind == constants.TAG_INSTANCE:
6204
      self.target = self.cfg.GetInstanceInfo(self.op.name)
6205
    else:
6206
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
6207
                                 str(self.op.kind))
6208

    
6209

    
6210
class LUGetTags(TagsLU):
6211
  """Returns the tags of a given object.
6212

6213
  """
6214
  _OP_REQP = ["kind", "name"]
6215
  REQ_BGL = False
6216

    
6217
  def Exec(self, feedback_fn):
6218
    """Returns the tag list.
6219

6220
    """
6221
    return list(self.target.GetTags())
6222

    
6223

    
6224
class LUSearchTags(NoHooksLU):
6225
  """Searches the tags for a given pattern.
6226

6227
  """
6228
  _OP_REQP = ["pattern"]
6229
  REQ_BGL = False
6230

    
6231
  def ExpandNames(self):
6232
    self.needed_locks = {}
6233

    
6234
  def CheckPrereq(self):
6235
    """Check prerequisites.
6236

6237
    This checks the pattern passed for validity by compiling it.
6238

6239
    """
6240
    try:
6241
      self.re = re.compile(self.op.pattern)
6242
    except re.error, err:
6243
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
6244
                                 (self.op.pattern, err))
6245

    
6246
  def Exec(self, feedback_fn):
6247
    """Returns the tag list.
6248

6249
    """
6250
    cfg = self.cfg
6251
    tgts = [("/cluster", cfg.GetClusterInfo())]
6252
    ilist = cfg.GetAllInstancesInfo().values()
6253
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
6254
    nlist = cfg.GetAllNodesInfo().values()
6255
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
6256
    results = []
6257
    for path, target in tgts:
6258
      for tag in target.GetTags():
6259
        if self.re.search(tag):
6260
          results.append((path, tag))
6261
    return results
6262

    
6263

    
6264
class LUAddTags(TagsLU):
6265
  """Sets a tag on a given object.
6266

6267
  """
6268
  _OP_REQP = ["kind", "name", "tags"]
6269
  REQ_BGL = False
6270

    
6271
  def CheckPrereq(self):
6272
    """Check prerequisites.
6273

6274
    This checks the type and length of the tag name and value.
6275

6276
    """
6277
    TagsLU.CheckPrereq(self)
6278
    for tag in self.op.tags:
6279
      objects.TaggableObject.ValidateTag(tag)
6280

    
6281
  def Exec(self, feedback_fn):
6282
    """Sets the tag.
6283

6284
    """
6285
    try:
6286
      for tag in self.op.tags:
6287
        self.target.AddTag(tag)
6288
    except errors.TagError, err:
6289
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
6290
    try:
6291
      self.cfg.Update(self.target)
6292
    except errors.ConfigurationError:
6293
      raise errors.OpRetryError("There has been a modification to the"
6294
                                " config file and the operation has been"
6295
                                " aborted. Please retry.")
6296

    
6297

    
6298
class LUDelTags(TagsLU):
6299
  """Delete a list of tags from a given object.
6300

6301
  """
6302
  _OP_REQP = ["kind", "name", "tags"]
6303
  REQ_BGL = False
6304

    
6305
  def CheckPrereq(self):
6306
    """Check prerequisites.
6307

6308
    This checks that we have the given tag.
6309

6310
    """
6311
    TagsLU.CheckPrereq(self)
6312
    for tag in self.op.tags:
6313
      objects.TaggableObject.ValidateTag(tag)
6314
    del_tags = frozenset(self.op.tags)
6315
    cur_tags = self.target.GetTags()
6316
    if not del_tags <= cur_tags:
6317
      diff_tags = del_tags - cur_tags
6318
      diff_names = ["'%s'" % tag for tag in diff_tags]
6319
      diff_names.sort()
6320
      raise errors.OpPrereqError("Tag(s) %s not found" %
6321
                                 (",".join(diff_names)))
6322

    
6323
  def Exec(self, feedback_fn):
6324
    """Remove the tag from the object.
6325

6326
    """
6327
    for tag in self.op.tags:
6328
      self.target.RemoveTag(tag)
6329
    try:
6330
      self.cfg.Update(self.target)
6331
    except errors.ConfigurationError:
6332
      raise errors.OpRetryError("There has been a modification to the"
6333
                                " config file and the operation has been"
6334
                                " aborted. Please retry.")
6335

    
6336

    
6337
class LUTestDelay(NoHooksLU):
6338
  """Sleep for a specified amount of time.
6339

6340
  This LU sleeps on the master and/or nodes for a specified amount of
6341
  time.
6342

6343
  """
6344
  _OP_REQP = ["duration", "on_master", "on_nodes"]
6345
  REQ_BGL = False
6346

    
6347
  def ExpandNames(self):
6348
    """Expand names and set required locks.
6349

6350
    This expands the node list, if any.
6351

6352
    """
6353
    self.needed_locks = {}
6354
    if self.op.on_nodes:
6355
      # _GetWantedNodes can be used here, but is not always appropriate to use
6356
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
6357
      # more information.
6358
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
6359
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
6360

    
6361
  def CheckPrereq(self):
6362
    """Check prerequisites.
6363

6364
    """
6365

    
6366
  def Exec(self, feedback_fn):
6367
    """Do the actual sleep.
6368

6369
    """
6370
    if self.op.on_master:
6371
      if not utils.TestDelay(self.op.duration):
6372
        raise errors.OpExecError("Error during master delay test")
6373
    if self.op.on_nodes:
6374
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
6375
      if not result:
6376
        raise errors.OpExecError("Complete failure from rpc call")
6377
      for node, node_result in result.items():
6378
        node_result.Raise()
6379
        if not node_result.data:
6380
          raise errors.OpExecError("Failure during rpc call to node %s,"
6381
                                   " result: %s" % (node, node_result.data))
6382

    
6383

    
6384
class IAllocator(object):
6385
  """IAllocator framework.
6386

6387
  An IAllocator instance has three sets of attributes:
6388
    - cfg that is needed to query the cluster
6389
    - input data (all members of the _KEYS class attribute are required)
6390
    - four buffer attributes (in|out_data|text), that represent the
6391
      input (to the external script) in text and data structure format,
6392
      and the output from it, again in two formats
6393
    - the result variables from the script (success, info, nodes) for
6394
      easy usage
6395

6396
  """
6397
  _ALLO_KEYS = [
6398
    "mem_size", "disks", "disk_template",
6399
    "os", "tags", "nics", "vcpus", "hypervisor",
6400
    ]
6401
  _RELO_KEYS = [
6402
    "relocate_from",
6403
    ]
6404

    
6405
  def __init__(self, lu, mode, name, **kwargs):
6406
    self.lu = lu
6407
    # init buffer variables
6408
    self.in_text = self.out_text = self.in_data = self.out_data = None
6409
    # init all input fields so that pylint is happy
6410
    self.mode = mode
6411
    self.name = name
6412
    self.mem_size = self.disks = self.disk_template = None
6413
    self.os = self.tags = self.nics = self.vcpus = None
6414
    self.hypervisor = None
6415
    self.relocate_from = None
6416
    # computed fields
6417
    self.required_nodes = None
6418
    # init result fields
6419
    self.success = self.info = self.nodes = None
6420
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6421
      keyset = self._ALLO_KEYS
6422
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
6423
      keyset = self._RELO_KEYS
6424
    else:
6425
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
6426
                                   " IAllocator" % self.mode)
6427
    for key in kwargs:
6428
      if key not in keyset:
6429
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
6430
                                     " IAllocator" % key)
6431
      setattr(self, key, kwargs[key])
6432
    for key in keyset:
6433
      if key not in kwargs:
6434
        raise errors.ProgrammerError("Missing input parameter '%s' to"
6435
                                     " IAllocator" % key)
6436
    self._BuildInputData()
6437

    
6438
  def _ComputeClusterData(self):
6439
    """Compute the generic allocator input data.
6440

6441
    This is the data that is independent of the actual operation.
6442

6443
    """
6444
    cfg = self.lu.cfg
6445
    cluster_info = cfg.GetClusterInfo()
6446
    # cluster data
6447
    data = {
6448
      "version": 1,
6449
      "cluster_name": cfg.GetClusterName(),
6450
      "cluster_tags": list(cluster_info.GetTags()),
6451
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
6452
      # we don't have job IDs
6453
      }
6454
    iinfo = cfg.GetAllInstancesInfo().values()
6455
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
6456

    
6457
    # node data
6458
    node_results = {}
6459
    node_list = cfg.GetNodeList()
6460

    
6461
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6462
      hypervisor_name = self.hypervisor
6463
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
6464
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
6465

    
6466
    node_data = self.lu.rpc.call_node_info(node_list, cfg.GetVGName(),
6467
                                           hypervisor_name)
6468
    node_iinfo = self.lu.rpc.call_all_instances_info(node_list,
6469
                       cluster_info.enabled_hypervisors)
6470
    for nname, nresult in node_data.items():
6471
      # first fill in static (config-based) values
6472
      ninfo = cfg.GetNodeInfo(nname)
6473
      pnr = {
6474
        "tags": list(ninfo.GetTags()),
6475
        "primary_ip": ninfo.primary_ip,
6476
        "secondary_ip": ninfo.secondary_ip,
6477
        "offline": ninfo.offline,
6478
        "drained": ninfo.drained,
6479
        "master_candidate": ninfo.master_candidate,
6480
        }
6481

    
6482
      if not ninfo.offline:
6483
        nresult.Raise()
6484
        if not isinstance(nresult.data, dict):
6485
          raise errors.OpExecError("Can't get data for node %s" % nname)
6486
        remote_info = nresult.data
6487
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
6488
                     'vg_size', 'vg_free', 'cpu_total']:
6489
          if attr not in remote_info:
6490
            raise errors.OpExecError("Node '%s' didn't return attribute"
6491
                                     " '%s'" % (nname, attr))
6492
          try:
6493
            remote_info[attr] = int(remote_info[attr])
6494
          except ValueError, err:
6495
            raise errors.OpExecError("Node '%s' returned invalid value"
6496
                                     " for '%s': %s" % (nname, attr, err))
6497
        # compute memory used by primary instances
6498
        i_p_mem = i_p_up_mem = 0
6499
        for iinfo, beinfo in i_list:
6500
          if iinfo.primary_node == nname:
6501
            i_p_mem += beinfo[constants.BE_MEMORY]
6502
            if iinfo.name not in node_iinfo[nname].data:
6503
              i_used_mem = 0
6504
            else:
6505
              i_used_mem = int(node_iinfo[nname].data[iinfo.name]['memory'])
6506
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
6507
            remote_info['memory_free'] -= max(0, i_mem_diff)
6508

    
6509
            if iinfo.admin_up:
6510
              i_p_up_mem += beinfo[constants.BE_MEMORY]
6511

    
6512
        # compute memory used by instances
6513
        pnr_dyn = {
6514
          "total_memory": remote_info['memory_total'],
6515
          "reserved_memory": remote_info['memory_dom0'],
6516
          "free_memory": remote_info['memory_free'],
6517
          "total_disk": remote_info['vg_size'],
6518
          "free_disk": remote_info['vg_free'],
6519
          "total_cpus": remote_info['cpu_total'],
6520
          "i_pri_memory": i_p_mem,
6521
          "i_pri_up_memory": i_p_up_mem,
6522
          }
6523
        pnr.update(pnr_dyn)
6524

    
6525
      node_results[nname] = pnr
6526
    data["nodes"] = node_results
6527

    
6528
    # instance data
6529
    instance_data = {}
6530
    for iinfo, beinfo in i_list:
6531
      nic_data = [{"mac": n.mac, "ip": n.ip, "bridge": n.bridge}
6532
                  for n in iinfo.nics]
6533
      pir = {
6534
        "tags": list(iinfo.GetTags()),
6535
        "admin_up": iinfo.admin_up,
6536
        "vcpus": beinfo[constants.BE_VCPUS],
6537
        "memory": beinfo[constants.BE_MEMORY],
6538
        "os": iinfo.os,
6539
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
6540
        "nics": nic_data,
6541
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
6542
        "disk_template": iinfo.disk_template,
6543
        "hypervisor": iinfo.hypervisor,
6544
        }
6545
      instance_data[iinfo.name] = pir
6546

    
6547
    data["instances"] = instance_data
6548

    
6549
    self.in_data = data
6550

    
6551
  def _AddNewInstance(self):
6552
    """Add new instance data to allocator structure.
6553

6554
    This in combination with _AllocatorGetClusterData will create the
6555
    correct structure needed as input for the allocator.
6556

6557
    The checks for the completeness of the opcode must have already been
6558
    done.
6559

6560
    """
6561
    data = self.in_data
6562

    
6563
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
6564

    
6565
    if self.disk_template in constants.DTS_NET_MIRROR:
6566
      self.required_nodes = 2
6567
    else:
6568
      self.required_nodes = 1
6569
    request = {
6570
      "type": "allocate",
6571
      "name": self.name,
6572
      "disk_template": self.disk_template,
6573
      "tags": self.tags,
6574
      "os": self.os,
6575
      "vcpus": self.vcpus,
6576
      "memory": self.mem_size,
6577
      "disks": self.disks,
6578
      "disk_space_total": disk_space,
6579
      "nics": self.nics,
6580
      "required_nodes": self.required_nodes,
6581
      }
6582
    data["request"] = request
6583

    
6584
  def _AddRelocateInstance(self):
6585
    """Add relocate instance data to allocator structure.
6586

6587
    This in combination with _IAllocatorGetClusterData will create the
6588
    correct structure needed as input for the allocator.
6589

6590
    The checks for the completeness of the opcode must have already been
6591
    done.
6592

6593
    """
6594
    instance = self.lu.cfg.GetInstanceInfo(self.name)
6595
    if instance is None:
6596
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
6597
                                   " IAllocator" % self.name)
6598

    
6599
    if instance.disk_template not in constants.DTS_NET_MIRROR:
6600
      raise errors.OpPrereqError("Can't relocate non-mirrored instances")
6601

    
6602
    if len(instance.secondary_nodes) != 1:
6603
      raise errors.OpPrereqError("Instance has not exactly one secondary node")
6604

    
6605
    self.required_nodes = 1
6606
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
6607
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
6608

    
6609
    request = {
6610
      "type": "relocate",
6611
      "name": self.name,
6612
      "disk_space_total": disk_space,
6613
      "required_nodes": self.required_nodes,
6614
      "relocate_from": self.relocate_from,
6615
      }
6616
    self.in_data["request"] = request
6617

    
6618
  def _BuildInputData(self):
6619
    """Build input data structures.
6620

6621
    """
6622
    self._ComputeClusterData()
6623

    
6624
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6625
      self._AddNewInstance()
6626
    else:
6627
      self._AddRelocateInstance()
6628

    
6629
    self.in_text = serializer.Dump(self.in_data)
6630

    
6631
  def Run(self, name, validate=True, call_fn=None):
6632
    """Run an instance allocator and return the results.
6633

6634
    """
6635
    if call_fn is None:
6636
      call_fn = self.lu.rpc.call_iallocator_runner
6637
    data = self.in_text
6638

    
6639
    result = call_fn(self.lu.cfg.GetMasterNode(), name, self.in_text)
6640
    result.Raise()
6641

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

    
6645
    rcode, stdout, stderr, fail = result.data
6646

    
6647
    if rcode == constants.IARUN_NOTFOUND:
6648
      raise errors.OpExecError("Can't find allocator '%s'" % name)
6649
    elif rcode == constants.IARUN_FAILURE:
6650
      raise errors.OpExecError("Instance allocator call failed: %s,"
6651
                               " output: %s" % (fail, stdout+stderr))
6652
    self.out_text = stdout
6653
    if validate:
6654
      self._ValidateResult()
6655

    
6656
  def _ValidateResult(self):
6657
    """Process the allocator results.
6658

6659
    This will process and if successful save the result in
6660
    self.out_data and the other parameters.
6661

6662
    """
6663
    try:
6664
      rdict = serializer.Load(self.out_text)
6665
    except Exception, err:
6666
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
6667

    
6668
    if not isinstance(rdict, dict):
6669
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
6670

    
6671
    for key in "success", "info", "nodes":
6672
      if key not in rdict:
6673
        raise errors.OpExecError("Can't parse iallocator results:"
6674
                                 " missing key '%s'" % key)
6675
      setattr(self, key, rdict[key])
6676

    
6677
    if not isinstance(rdict["nodes"], list):
6678
      raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
6679
                               " is not a list")
6680
    self.out_data = rdict
6681

    
6682

    
6683
class LUTestAllocator(NoHooksLU):
6684
  """Run allocator tests.
6685

6686
  This LU runs the allocator tests
6687

6688
  """
6689
  _OP_REQP = ["direction", "mode", "name"]
6690

    
6691
  def CheckPrereq(self):
6692
    """Check prerequisites.
6693

6694
    This checks the opcode parameters depending on the director and mode test.
6695

6696
    """
6697
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
6698
      for attr in ["name", "mem_size", "disks", "disk_template",
6699
                   "os", "tags", "nics", "vcpus"]:
6700
        if not hasattr(self.op, attr):
6701
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
6702
                                     attr)
6703
      iname = self.cfg.ExpandInstanceName(self.op.name)
6704
      if iname is not None:
6705
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
6706
                                   iname)
6707
      if not isinstance(self.op.nics, list):
6708
        raise errors.OpPrereqError("Invalid parameter 'nics'")
6709
      for row in self.op.nics:
6710
        if (not isinstance(row, dict) or
6711
            "mac" not in row or
6712
            "ip" not in row or
6713
            "bridge" not in row):
6714
          raise errors.OpPrereqError("Invalid contents of the"
6715
                                     " 'nics' parameter")
6716
      if not isinstance(self.op.disks, list):
6717
        raise errors.OpPrereqError("Invalid parameter 'disks'")
6718
      for row in self.op.disks:
6719
        if (not isinstance(row, dict) or
6720
            "size" not in row or
6721
            not isinstance(row["size"], int) or
6722
            "mode" not in row or
6723
            row["mode"] not in ['r', 'w']):
6724
          raise errors.OpPrereqError("Invalid contents of the"
6725
                                     " 'disks' parameter")
6726
      if not hasattr(self.op, "hypervisor") or self.op.hypervisor is None:
6727
        self.op.hypervisor = self.cfg.GetHypervisorType()
6728
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
6729
      if not hasattr(self.op, "name"):
6730
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input")
6731
      fname = self.cfg.ExpandInstanceName(self.op.name)
6732
      if fname is None:
6733
        raise errors.OpPrereqError("Instance '%s' not found for relocation" %
6734
                                   self.op.name)
6735
      self.op.name = fname
6736
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
6737
    else:
6738
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
6739
                                 self.op.mode)
6740

    
6741
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
6742
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
6743
        raise errors.OpPrereqError("Missing allocator name")
6744
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
6745
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
6746
                                 self.op.direction)
6747

    
6748
  def Exec(self, feedback_fn):
6749
    """Run the allocator test.
6750

6751
    """
6752
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
6753
      ial = IAllocator(self,
6754
                       mode=self.op.mode,
6755
                       name=self.op.name,
6756
                       mem_size=self.op.mem_size,
6757
                       disks=self.op.disks,
6758
                       disk_template=self.op.disk_template,
6759
                       os=self.op.os,
6760
                       tags=self.op.tags,
6761
                       nics=self.op.nics,
6762
                       vcpus=self.op.vcpus,
6763
                       hypervisor=self.op.hypervisor,
6764
                       )
6765
    else:
6766
      ial = IAllocator(self,
6767
                       mode=self.op.mode,
6768
                       name=self.op.name,
6769
                       relocate_from=list(self.relocate_from),
6770
                       )
6771

    
6772
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
6773
      result = ial.in_text
6774
    else:
6775
      ial.Run(self.op.allocator, validate=False)
6776
      result = ial.out_text
6777
    return result