Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 489fcbe9

History | View | Annotate | Download (236.4 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 node 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 _CheckNodeNotDrained(lu, node):
445
  """Ensure that a given node is not drained.
446

447
  @param lu: the LU on behalf of which we make the check
448
  @param node: the node to check
449
  @raise errors.OpPrereqError: if the node is drained
450

451
  """
452
  if lu.cfg.GetNodeInfo(node).drained:
453
    raise errors.OpPrereqError("Can't use drained node %s" % node)
454

    
455

    
456
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
457
                          memory, vcpus, nics):
458
  """Builds instance related env variables for hooks
459

460
  This builds the hook environment from individual variables.
461

462
  @type name: string
463
  @param name: the name of the instance
464
  @type primary_node: string
465
  @param primary_node: the name of the instance's primary node
466
  @type secondary_nodes: list
467
  @param secondary_nodes: list of secondary nodes as strings
468
  @type os_type: string
469
  @param os_type: the name of the instance's OS
470
  @type status: boolean
471
  @param status: the should_run status of the instance
472
  @type memory: string
473
  @param memory: the memory size of the instance
474
  @type vcpus: string
475
  @param vcpus: the count of VCPUs the instance has
476
  @type nics: list
477
  @param nics: list of tuples (ip, bridge, mac) representing
478
      the NICs the instance  has
479
  @rtype: dict
480
  @return: the hook environment for this instance
481

482
  """
483
  if status:
484
    str_status = "up"
485
  else:
486
    str_status = "down"
487
  env = {
488
    "OP_TARGET": name,
489
    "INSTANCE_NAME": name,
490
    "INSTANCE_PRIMARY": primary_node,
491
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
492
    "INSTANCE_OS_TYPE": os_type,
493
    "INSTANCE_STATUS": str_status,
494
    "INSTANCE_MEMORY": memory,
495
    "INSTANCE_VCPUS": vcpus,
496
  }
497

    
498
  if nics:
499
    nic_count = len(nics)
500
    for idx, (ip, bridge, mac) in enumerate(nics):
501
      if ip is None:
502
        ip = ""
503
      env["INSTANCE_NIC%d_IP" % idx] = ip
504
      env["INSTANCE_NIC%d_BRIDGE" % idx] = bridge
505
      env["INSTANCE_NIC%d_HWADDR" % idx] = mac
506
  else:
507
    nic_count = 0
508

    
509
  env["INSTANCE_NIC_COUNT"] = nic_count
510

    
511
  return env
512

    
513

    
514
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
515
  """Builds instance related env variables for hooks from an object.
516

517
  @type lu: L{LogicalUnit}
518
  @param lu: the logical unit on whose behalf we execute
519
  @type instance: L{objects.Instance}
520
  @param instance: the instance for which we should build the
521
      environment
522
  @type override: dict
523
  @param override: dictionary with key/values that will override
524
      our values
525
  @rtype: dict
526
  @return: the hook environment dictionary
527

528
  """
529
  bep = lu.cfg.GetClusterInfo().FillBE(instance)
530
  args = {
531
    'name': instance.name,
532
    'primary_node': instance.primary_node,
533
    'secondary_nodes': instance.secondary_nodes,
534
    'os_type': instance.os,
535
    'status': instance.admin_up,
536
    'memory': bep[constants.BE_MEMORY],
537
    'vcpus': bep[constants.BE_VCPUS],
538
    'nics': [(nic.ip, nic.bridge, nic.mac) for nic in instance.nics],
539
  }
540
  if override:
541
    args.update(override)
542
  return _BuildInstanceHookEnv(**args)
543

    
544

    
545
def _AdjustCandidatePool(lu):
546
  """Adjust the candidate pool after node operations.
547

548
  """
549
  mod_list = lu.cfg.MaintainCandidatePool()
550
  if mod_list:
551
    lu.LogInfo("Promoted nodes to master candidate role: %s",
552
               ", ".join(node.name for node in mod_list))
553
    for name in mod_list:
554
      lu.context.ReaddNode(name)
555
  mc_now, mc_max = lu.cfg.GetMasterCandidateStats()
556
  if mc_now > mc_max:
557
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
558
               (mc_now, mc_max))
559

    
560

    
561
def _CheckInstanceBridgesExist(lu, instance):
562
  """Check that the brigdes needed by an instance exist.
563

564
  """
565
  # check bridges existance
566
  brlist = [nic.bridge for nic in instance.nics]
567
  result = lu.rpc.call_bridges_exist(instance.primary_node, brlist)
568
  result.Raise()
569
  if not result.data:
570
    raise errors.OpPrereqError("One or more target bridges %s does not"
571
                               " exist on destination node '%s'" %
572
                               (brlist, instance.primary_node))
573

    
574

    
575
class LUDestroyCluster(NoHooksLU):
576
  """Logical unit for destroying the cluster.
577

578
  """
579
  _OP_REQP = []
580

    
581
  def CheckPrereq(self):
582
    """Check prerequisites.
583

584
    This checks whether the cluster is empty.
585

586
    Any errors are signalled by raising errors.OpPrereqError.
587

588
    """
589
    master = self.cfg.GetMasterNode()
590

    
591
    nodelist = self.cfg.GetNodeList()
592
    if len(nodelist) != 1 or nodelist[0] != master:
593
      raise errors.OpPrereqError("There are still %d node(s) in"
594
                                 " this cluster." % (len(nodelist) - 1))
595
    instancelist = self.cfg.GetInstanceList()
596
    if instancelist:
597
      raise errors.OpPrereqError("There are still %d instance(s) in"
598
                                 " this cluster." % len(instancelist))
599

    
600
  def Exec(self, feedback_fn):
601
    """Destroys the cluster.
602

603
    """
604
    master = self.cfg.GetMasterNode()
605
    result = self.rpc.call_node_stop_master(master, False)
606
    result.Raise()
607
    if not result.data:
608
      raise errors.OpExecError("Could not disable the master role")
609
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
610
    utils.CreateBackup(priv_key)
611
    utils.CreateBackup(pub_key)
612
    return master
613

    
614

    
615
class LUVerifyCluster(LogicalUnit):
616
  """Verifies the cluster status.
617

618
  """
619
  HPATH = "cluster-verify"
620
  HTYPE = constants.HTYPE_CLUSTER
621
  _OP_REQP = ["skip_checks"]
622
  REQ_BGL = False
623

    
624
  def ExpandNames(self):
625
    self.needed_locks = {
626
      locking.LEVEL_NODE: locking.ALL_SET,
627
      locking.LEVEL_INSTANCE: locking.ALL_SET,
628
    }
629
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
630

    
631
  def _VerifyNode(self, nodeinfo, file_list, local_cksum,
632
                  node_result, feedback_fn, master_files,
633
                  drbd_map):
634
    """Run multiple tests against a node.
635

636
    Test list:
637

638
      - compares ganeti version
639
      - checks vg existance and size > 20G
640
      - checks config file checksum
641
      - checks ssh to other nodes
642

643
    @type nodeinfo: L{objects.Node}
644
    @param nodeinfo: the node to check
645
    @param file_list: required list of files
646
    @param local_cksum: dictionary of local files and their checksums
647
    @param node_result: the results from the node
648
    @param feedback_fn: function used to accumulate results
649
    @param master_files: list of files that only masters should have
650
    @param drbd_map: the useddrbd minors for this node, in
651
        form of minor: (instance, must_exist) which correspond to instances
652
        and their running status
653

654
    """
655
    node = nodeinfo.name
656

    
657
    # main result, node_result should be a non-empty dict
658
    if not node_result or not isinstance(node_result, dict):
659
      feedback_fn("  - ERROR: unable to verify node %s." % (node,))
660
      return True
661

    
662
    # compares ganeti version
663
    local_version = constants.PROTOCOL_VERSION
664
    remote_version = node_result.get('version', None)
665
    if not (remote_version and isinstance(remote_version, (list, tuple)) and
666
            len(remote_version) == 2):
667
      feedback_fn("  - ERROR: connection to %s failed" % (node))
668
      return True
669

    
670
    if local_version != remote_version[0]:
671
      feedback_fn("  - ERROR: incompatible protocol versions: master %s,"
672
                  " node %s %s" % (local_version, node, remote_version[0]))
673
      return True
674

    
675
    # node seems compatible, we can actually try to look into its results
676

    
677
    bad = False
678

    
679
    # full package version
680
    if constants.RELEASE_VERSION != remote_version[1]:
681
      feedback_fn("  - WARNING: software version mismatch: master %s,"
682
                  " node %s %s" %
683
                  (constants.RELEASE_VERSION, node, remote_version[1]))
684

    
685
    # checks vg existence and size > 20G
686

    
687
    vglist = node_result.get(constants.NV_VGLIST, None)
688
    if not vglist:
689
      feedback_fn("  - ERROR: unable to check volume groups on node %s." %
690
                      (node,))
691
      bad = True
692
    else:
693
      vgstatus = utils.CheckVolumeGroupSize(vglist, self.cfg.GetVGName(),
694
                                            constants.MIN_VG_SIZE)
695
      if vgstatus:
696
        feedback_fn("  - ERROR: %s on node %s" % (vgstatus, node))
697
        bad = True
698

    
699
    # checks config file checksum
700

    
701
    remote_cksum = node_result.get(constants.NV_FILELIST, None)
702
    if not isinstance(remote_cksum, dict):
703
      bad = True
704
      feedback_fn("  - ERROR: node hasn't returned file checksum data")
705
    else:
706
      for file_name in file_list:
707
        node_is_mc = nodeinfo.master_candidate
708
        must_have_file = file_name not in master_files
709
        if file_name not in remote_cksum:
710
          if node_is_mc or must_have_file:
711
            bad = True
712
            feedback_fn("  - ERROR: file '%s' missing" % file_name)
713
        elif remote_cksum[file_name] != local_cksum[file_name]:
714
          if node_is_mc or must_have_file:
715
            bad = True
716
            feedback_fn("  - ERROR: file '%s' has wrong checksum" % file_name)
717
          else:
718
            # not candidate and this is not a must-have file
719
            bad = True
720
            feedback_fn("  - ERROR: non master-candidate has old/wrong file"
721
                        " '%s'" % file_name)
722
        else:
723
          # all good, except non-master/non-must have combination
724
          if not node_is_mc and not must_have_file:
725
            feedback_fn("  - ERROR: file '%s' should not exist on non master"
726
                        " candidates" % file_name)
727

    
728
    # checks ssh to any
729

    
730
    if constants.NV_NODELIST not in node_result:
731
      bad = True
732
      feedback_fn("  - ERROR: node hasn't returned node ssh connectivity data")
733
    else:
734
      if node_result[constants.NV_NODELIST]:
735
        bad = True
736
        for node in node_result[constants.NV_NODELIST]:
737
          feedback_fn("  - ERROR: ssh communication with node '%s': %s" %
738
                          (node, node_result[constants.NV_NODELIST][node]))
739

    
740
    if constants.NV_NODENETTEST not in node_result:
741
      bad = True
742
      feedback_fn("  - ERROR: node hasn't returned node tcp connectivity data")
743
    else:
744
      if node_result[constants.NV_NODENETTEST]:
745
        bad = True
746
        nlist = utils.NiceSort(node_result[constants.NV_NODENETTEST].keys())
747
        for node in nlist:
748
          feedback_fn("  - ERROR: tcp communication with node '%s': %s" %
749
                          (node, node_result[constants.NV_NODENETTEST][node]))
750

    
751
    hyp_result = node_result.get(constants.NV_HYPERVISOR, None)
752
    if isinstance(hyp_result, dict):
753
      for hv_name, hv_result in hyp_result.iteritems():
754
        if hv_result is not None:
755
          feedback_fn("  - ERROR: hypervisor %s verify failure: '%s'" %
756
                      (hv_name, hv_result))
757

    
758
    # check used drbd list
759
    used_minors = node_result.get(constants.NV_DRBDLIST, [])
760
    for minor, (iname, must_exist) in drbd_map.items():
761
      if minor not in used_minors and must_exist:
762
        feedback_fn("  - ERROR: drbd minor %d of instance %s is not active" %
763
                    (minor, iname))
764
        bad = True
765
    for minor in used_minors:
766
      if minor not in drbd_map:
767
        feedback_fn("  - ERROR: unallocated drbd minor %d is in use" % minor)
768
        bad = True
769

    
770
    return bad
771

    
772
  def _VerifyInstance(self, instance, instanceconfig, node_vol_is,
773
                      node_instance, feedback_fn, n_offline):
774
    """Verify an instance.
775

776
    This function checks to see if the required block devices are
777
    available on the instance's node.
778

779
    """
780
    bad = False
781

    
782
    node_current = instanceconfig.primary_node
783

    
784
    node_vol_should = {}
785
    instanceconfig.MapLVsByNode(node_vol_should)
786

    
787
    for node in node_vol_should:
788
      if node in n_offline:
789
        # ignore missing volumes on offline nodes
790
        continue
791
      for volume in node_vol_should[node]:
792
        if node not in node_vol_is or volume not in node_vol_is[node]:
793
          feedback_fn("  - ERROR: volume %s missing on node %s" %
794
                          (volume, node))
795
          bad = True
796

    
797
    if instanceconfig.admin_up:
798
      if ((node_current not in node_instance or
799
          not instance in node_instance[node_current]) and
800
          node_current not in n_offline):
801
        feedback_fn("  - ERROR: instance %s not running on node %s" %
802
                        (instance, node_current))
803
        bad = True
804

    
805
    for node in node_instance:
806
      if (not node == node_current):
807
        if instance in node_instance[node]:
808
          feedback_fn("  - ERROR: instance %s should not run on node %s" %
809
                          (instance, node))
810
          bad = True
811

    
812
    return bad
813

    
814
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is, feedback_fn):
815
    """Verify if there are any unknown volumes in the cluster.
816

817
    The .os, .swap and backup volumes are ignored. All other volumes are
818
    reported as unknown.
819

820
    """
821
    bad = False
822

    
823
    for node in node_vol_is:
824
      for volume in node_vol_is[node]:
825
        if node not in node_vol_should or volume not in node_vol_should[node]:
826
          feedback_fn("  - ERROR: volume %s on node %s should not exist" %
827
                      (volume, node))
828
          bad = True
829
    return bad
830

    
831
  def _VerifyOrphanInstances(self, instancelist, node_instance, feedback_fn):
832
    """Verify the list of running instances.
833

834
    This checks what instances are running but unknown to the cluster.
835

836
    """
837
    bad = False
838
    for node in node_instance:
839
      for runninginstance in node_instance[node]:
840
        if runninginstance not in instancelist:
841
          feedback_fn("  - ERROR: instance %s on node %s should not exist" %
842
                          (runninginstance, node))
843
          bad = True
844
    return bad
845

    
846
  def _VerifyNPlusOneMemory(self, node_info, instance_cfg, feedback_fn):
847
    """Verify N+1 Memory Resilience.
848

849
    Check that if one single node dies we can still start all the instances it
850
    was primary for.
851

852
    """
853
    bad = False
854

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

    
876
  def CheckPrereq(self):
877
    """Check prerequisites.
878

879
    Transform the list of checks we're going to skip into a set and check that
880
    all its members are valid.
881

882
    """
883
    self.skip_set = frozenset(self.op.skip_checks)
884
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
885
      raise errors.OpPrereqError("Invalid checks to be skipped specified")
886

    
887
  def BuildHooksEnv(self):
888
    """Build hooks env.
889

890
    Cluster-Verify hooks just rone in the post phase and their failure makes
891
    the output be logged in the verify output and the verification to fail.
892

893
    """
894
    all_nodes = self.cfg.GetNodeList()
895
    # TODO: populate the environment with useful information for verify hooks
896
    env = {}
897
    return env, [], all_nodes
898

    
899
  def Exec(self, feedback_fn):
900
    """Verify integrity of cluster, performing various test on nodes.
901

902
    """
903
    bad = False
904
    feedback_fn("* Verifying global settings")
905
    for msg in self.cfg.VerifyConfig():
906
      feedback_fn("  - ERROR: %s" % msg)
907

    
908
    vg_name = self.cfg.GetVGName()
909
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
910
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
911
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
912
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
913
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
914
                        for iname in instancelist)
915
    i_non_redundant = [] # Non redundant instances
916
    i_non_a_balanced = [] # Non auto-balanced instances
917
    n_offline = [] # List of offline nodes
918
    n_drained = [] # List of nodes being drained
919
    node_volume = {}
920
    node_instance = {}
921
    node_info = {}
922
    instance_cfg = {}
923

    
924
    # FIXME: verify OS list
925
    # do local checksums
926
    master_files = [constants.CLUSTER_CONF_FILE]
927

    
928
    file_names = ssconf.SimpleStore().GetFileList()
929
    file_names.append(constants.SSL_CERT_FILE)
930
    file_names.append(constants.RAPI_CERT_FILE)
931
    file_names.extend(master_files)
932

    
933
    local_checksums = utils.FingerprintFiles(file_names)
934

    
935
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
936
    node_verify_param = {
937
      constants.NV_FILELIST: file_names,
938
      constants.NV_NODELIST: [node.name for node in nodeinfo
939
                              if not node.offline],
940
      constants.NV_HYPERVISOR: hypervisors,
941
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
942
                                  node.secondary_ip) for node in nodeinfo
943
                                 if not node.offline],
944
      constants.NV_LVLIST: vg_name,
945
      constants.NV_INSTANCELIST: hypervisors,
946
      constants.NV_VGLIST: None,
947
      constants.NV_VERSION: None,
948
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
949
      constants.NV_DRBDLIST: None,
950
      }
951
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
952
                                           self.cfg.GetClusterName())
953

    
954
    cluster = self.cfg.GetClusterInfo()
955
    master_node = self.cfg.GetMasterNode()
956
    all_drbd_map = self.cfg.ComputeDRBDMap()
957

    
958
    for node_i in nodeinfo:
959
      node = node_i.name
960
      nresult = all_nvinfo[node].data
961

    
962
      if node_i.offline:
963
        feedback_fn("* Skipping offline node %s" % (node,))
964
        n_offline.append(node)
965
        continue
966

    
967
      if node == master_node:
968
        ntype = "master"
969
      elif node_i.master_candidate:
970
        ntype = "master candidate"
971
      elif node_i.drained:
972
        ntype = "drained"
973
        n_drained.append(node)
974
      else:
975
        ntype = "regular"
976
      feedback_fn("* Verifying node %s (%s)" % (node, ntype))
977

    
978
      if all_nvinfo[node].failed or not isinstance(nresult, dict):
979
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
980
        bad = True
981
        continue
982

    
983
      node_drbd = {}
984
      for minor, instance in all_drbd_map[node].items():
985
        instance = instanceinfo[instance]
986
        node_drbd[minor] = (instance.name, instance.admin_up)
987
      result = self._VerifyNode(node_i, file_names, local_checksums,
988
                                nresult, feedback_fn, master_files,
989
                                node_drbd)
990
      bad = bad or result
991

    
992
      lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
993
      if isinstance(lvdata, basestring):
994
        feedback_fn("  - ERROR: LVM problem on node %s: %s" %
995
                    (node, utils.SafeEncode(lvdata)))
996
        bad = True
997
        node_volume[node] = {}
998
      elif not isinstance(lvdata, dict):
999
        feedback_fn("  - ERROR: connection to %s failed (lvlist)" % (node,))
1000
        bad = True
1001
        continue
1002
      else:
1003
        node_volume[node] = lvdata
1004

    
1005
      # node_instance
1006
      idata = nresult.get(constants.NV_INSTANCELIST, None)
1007
      if not isinstance(idata, list):
1008
        feedback_fn("  - ERROR: connection to %s failed (instancelist)" %
1009
                    (node,))
1010
        bad = True
1011
        continue
1012

    
1013
      node_instance[node] = idata
1014

    
1015
      # node_info
1016
      nodeinfo = nresult.get(constants.NV_HVINFO, None)
1017
      if not isinstance(nodeinfo, dict):
1018
        feedback_fn("  - ERROR: connection to %s failed (hvinfo)" % (node,))
1019
        bad = True
1020
        continue
1021

    
1022
      try:
1023
        node_info[node] = {
1024
          "mfree": int(nodeinfo['memory_free']),
1025
          "dfree": int(nresult[constants.NV_VGLIST][vg_name]),
1026
          "pinst": [],
1027
          "sinst": [],
1028
          # dictionary holding all instances this node is secondary for,
1029
          # grouped by their primary node. Each key is a cluster node, and each
1030
          # value is a list of instances which have the key as primary and the
1031
          # current node as secondary.  this is handy to calculate N+1 memory
1032
          # availability if you can only failover from a primary to its
1033
          # secondary.
1034
          "sinst-by-pnode": {},
1035
        }
1036
      except ValueError:
1037
        feedback_fn("  - ERROR: invalid value returned from node %s" % (node,))
1038
        bad = True
1039
        continue
1040

    
1041
    node_vol_should = {}
1042

    
1043
    for instance in instancelist:
1044
      feedback_fn("* Verifying instance %s" % instance)
1045
      inst_config = instanceinfo[instance]
1046
      result =  self._VerifyInstance(instance, inst_config, node_volume,
1047
                                     node_instance, feedback_fn, n_offline)
1048
      bad = bad or result
1049
      inst_nodes_offline = []
1050

    
1051
      inst_config.MapLVsByNode(node_vol_should)
1052

    
1053
      instance_cfg[instance] = inst_config
1054

    
1055
      pnode = inst_config.primary_node
1056
      if pnode in node_info:
1057
        node_info[pnode]['pinst'].append(instance)
1058
      elif pnode not in n_offline:
1059
        feedback_fn("  - ERROR: instance %s, connection to primary node"
1060
                    " %s failed" % (instance, pnode))
1061
        bad = True
1062

    
1063
      if pnode in n_offline:
1064
        inst_nodes_offline.append(pnode)
1065

    
1066
      # If the instance is non-redundant we cannot survive losing its primary
1067
      # node, so we are not N+1 compliant. On the other hand we have no disk
1068
      # templates with more than one secondary so that situation is not well
1069
      # supported either.
1070
      # FIXME: does not support file-backed instances
1071
      if len(inst_config.secondary_nodes) == 0:
1072
        i_non_redundant.append(instance)
1073
      elif len(inst_config.secondary_nodes) > 1:
1074
        feedback_fn("  - WARNING: multiple secondaries for instance %s"
1075
                    % instance)
1076

    
1077
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1078
        i_non_a_balanced.append(instance)
1079

    
1080
      for snode in inst_config.secondary_nodes:
1081
        if snode in node_info:
1082
          node_info[snode]['sinst'].append(instance)
1083
          if pnode not in node_info[snode]['sinst-by-pnode']:
1084
            node_info[snode]['sinst-by-pnode'][pnode] = []
1085
          node_info[snode]['sinst-by-pnode'][pnode].append(instance)
1086
        elif snode not in n_offline:
1087
          feedback_fn("  - ERROR: instance %s, connection to secondary node"
1088
                      " %s failed" % (instance, snode))
1089
          bad = True
1090
        if snode in n_offline:
1091
          inst_nodes_offline.append(snode)
1092

    
1093
      if inst_nodes_offline:
1094
        # warn that the instance lives on offline nodes, and set bad=True
1095
        feedback_fn("  - ERROR: instance lives on offline node(s) %s" %
1096
                    ", ".join(inst_nodes_offline))
1097
        bad = True
1098

    
1099
    feedback_fn("* Verifying orphan volumes")
1100
    result = self._VerifyOrphanVolumes(node_vol_should, node_volume,
1101
                                       feedback_fn)
1102
    bad = bad or result
1103

    
1104
    feedback_fn("* Verifying remaining instances")
1105
    result = self._VerifyOrphanInstances(instancelist, node_instance,
1106
                                         feedback_fn)
1107
    bad = bad or result
1108

    
1109
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1110
      feedback_fn("* Verifying N+1 Memory redundancy")
1111
      result = self._VerifyNPlusOneMemory(node_info, instance_cfg, feedback_fn)
1112
      bad = bad or result
1113

    
1114
    feedback_fn("* Other Notes")
1115
    if i_non_redundant:
1116
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1117
                  % len(i_non_redundant))
1118

    
1119
    if i_non_a_balanced:
1120
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1121
                  % len(i_non_a_balanced))
1122

    
1123
    if n_offline:
1124
      feedback_fn("  - NOTICE: %d offline node(s) found." % len(n_offline))
1125

    
1126
    if n_drained:
1127
      feedback_fn("  - NOTICE: %d drained node(s) found." % len(n_drained))
1128

    
1129
    return not bad
1130

    
1131
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1132
    """Analize the post-hooks' result
1133

1134
    This method analyses the hook result, handles it, and sends some
1135
    nicely-formatted feedback back to the user.
1136

1137
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1138
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1139
    @param hooks_results: the results of the multi-node hooks rpc call
1140
    @param feedback_fn: function used send feedback back to the caller
1141
    @param lu_result: previous Exec result
1142
    @return: the new Exec result, based on the previous result
1143
        and hook results
1144

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

    
1178
      return lu_result
1179

    
1180

    
1181
class LUVerifyDisks(NoHooksLU):
1182
  """Verifies the cluster disks status.
1183

1184
  """
1185
  _OP_REQP = []
1186
  REQ_BGL = False
1187

    
1188
  def ExpandNames(self):
1189
    self.needed_locks = {
1190
      locking.LEVEL_NODE: locking.ALL_SET,
1191
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1192
    }
1193
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
1194

    
1195
  def CheckPrereq(self):
1196
    """Check prerequisites.
1197

1198
    This has no prerequisites.
1199

1200
    """
1201
    pass
1202

    
1203
  def Exec(self, feedback_fn):
1204
    """Verify integrity of cluster disks.
1205

1206
    """
1207
    result = res_nodes, res_nlvm, res_instances, res_missing = [], {}, [], {}
1208

    
1209
    vg_name = self.cfg.GetVGName()
1210
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1211
    instances = [self.cfg.GetInstanceInfo(name)
1212
                 for name in self.cfg.GetInstanceList()]
1213

    
1214
    nv_dict = {}
1215
    for inst in instances:
1216
      inst_lvs = {}
1217
      if (not inst.admin_up or
1218
          inst.disk_template not in constants.DTS_NET_MIRROR):
1219
        continue
1220
      inst.MapLVsByNode(inst_lvs)
1221
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1222
      for node, vol_list in inst_lvs.iteritems():
1223
        for vol in vol_list:
1224
          nv_dict[(node, vol)] = inst
1225

    
1226
    if not nv_dict:
1227
      return result
1228

    
1229
    node_lvs = self.rpc.call_volume_list(nodes, vg_name)
1230

    
1231
    to_act = set()
1232
    for node in nodes:
1233
      # node_volume
1234
      lvs = node_lvs[node]
1235
      if lvs.failed:
1236
        if not lvs.offline:
1237
          self.LogWarning("Connection to node %s failed: %s" %
1238
                          (node, lvs.data))
1239
        continue
1240
      lvs = lvs.data
1241
      if isinstance(lvs, basestring):
1242
        logging.warning("Error enumerating LVs on node %s: %s", node, lvs)
1243
        res_nlvm[node] = lvs
1244
      elif not isinstance(lvs, dict):
1245
        logging.warning("Connection to node %s failed or invalid data"
1246
                        " returned", node)
1247
        res_nodes.append(node)
1248
        continue
1249

    
1250
      for lv_name, (_, lv_inactive, lv_online) in lvs.iteritems():
1251
        inst = nv_dict.pop((node, lv_name), None)
1252
        if (not lv_online and inst is not None
1253
            and inst.name not in res_instances):
1254
          res_instances.append(inst.name)
1255

    
1256
    # any leftover items in nv_dict are missing LVs, let's arrange the
1257
    # data better
1258
    for key, inst in nv_dict.iteritems():
1259
      if inst.name not in res_missing:
1260
        res_missing[inst.name] = []
1261
      res_missing[inst.name].append(key)
1262

    
1263
    return result
1264

    
1265

    
1266
class LURenameCluster(LogicalUnit):
1267
  """Rename the cluster.
1268

1269
  """
1270
  HPATH = "cluster-rename"
1271
  HTYPE = constants.HTYPE_CLUSTER
1272
  _OP_REQP = ["name"]
1273

    
1274
  def BuildHooksEnv(self):
1275
    """Build hooks env.
1276

1277
    """
1278
    env = {
1279
      "OP_TARGET": self.cfg.GetClusterName(),
1280
      "NEW_NAME": self.op.name,
1281
      }
1282
    mn = self.cfg.GetMasterNode()
1283
    return env, [mn], [mn]
1284

    
1285
  def CheckPrereq(self):
1286
    """Verify that the passed name is a valid one.
1287

1288
    """
1289
    hostname = utils.HostInfo(self.op.name)
1290

    
1291
    new_name = hostname.name
1292
    self.ip = new_ip = hostname.ip
1293
    old_name = self.cfg.GetClusterName()
1294
    old_ip = self.cfg.GetMasterIP()
1295
    if new_name == old_name and new_ip == old_ip:
1296
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1297
                                 " cluster has changed")
1298
    if new_ip != old_ip:
1299
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1300
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1301
                                   " reachable on the network. Aborting." %
1302
                                   new_ip)
1303

    
1304
    self.op.name = new_name
1305

    
1306
  def Exec(self, feedback_fn):
1307
    """Rename the cluster.
1308

1309
    """
1310
    clustername = self.op.name
1311
    ip = self.ip
1312

    
1313
    # shutdown the master IP
1314
    master = self.cfg.GetMasterNode()
1315
    result = self.rpc.call_node_stop_master(master, False)
1316
    if result.failed or not result.data:
1317
      raise errors.OpExecError("Could not disable the master role")
1318

    
1319
    try:
1320
      cluster = self.cfg.GetClusterInfo()
1321
      cluster.cluster_name = clustername
1322
      cluster.master_ip = ip
1323
      self.cfg.Update(cluster)
1324

    
1325
      # update the known hosts file
1326
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
1327
      node_list = self.cfg.GetNodeList()
1328
      try:
1329
        node_list.remove(master)
1330
      except ValueError:
1331
        pass
1332
      result = self.rpc.call_upload_file(node_list,
1333
                                         constants.SSH_KNOWN_HOSTS_FILE)
1334
      for to_node, to_result in result.iteritems():
1335
        if to_result.failed or not to_result.data:
1336
          logging.error("Copy of file %s to node %s failed",
1337
                        constants.SSH_KNOWN_HOSTS_FILE, to_node)
1338

    
1339
    finally:
1340
      result = self.rpc.call_node_start_master(master, False)
1341
      if result.failed or not result.data:
1342
        self.LogWarning("Could not re-enable the master role on"
1343
                        " the master, please restart manually.")
1344

    
1345

    
1346
def _RecursiveCheckIfLVMBased(disk):
1347
  """Check if the given disk or its children are lvm-based.
1348

1349
  @type disk: L{objects.Disk}
1350
  @param disk: the disk to check
1351
  @rtype: booleean
1352
  @return: boolean indicating whether a LD_LV dev_type was found or not
1353

1354
  """
1355
  if disk.children:
1356
    for chdisk in disk.children:
1357
      if _RecursiveCheckIfLVMBased(chdisk):
1358
        return True
1359
  return disk.dev_type == constants.LD_LV
1360

    
1361

    
1362
class LUSetClusterParams(LogicalUnit):
1363
  """Change the parameters of the cluster.
1364

1365
  """
1366
  HPATH = "cluster-modify"
1367
  HTYPE = constants.HTYPE_CLUSTER
1368
  _OP_REQP = []
1369
  REQ_BGL = False
1370

    
1371
  def CheckParameters(self):
1372
    """Check parameters
1373

1374
    """
1375
    if not hasattr(self.op, "candidate_pool_size"):
1376
      self.op.candidate_pool_size = None
1377
    if self.op.candidate_pool_size is not None:
1378
      try:
1379
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
1380
      except ValueError, err:
1381
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
1382
                                   str(err))
1383
      if self.op.candidate_pool_size < 1:
1384
        raise errors.OpPrereqError("At least one master candidate needed")
1385

    
1386
  def ExpandNames(self):
1387
    # FIXME: in the future maybe other cluster params won't require checking on
1388
    # all nodes to be modified.
1389
    self.needed_locks = {
1390
      locking.LEVEL_NODE: locking.ALL_SET,
1391
    }
1392
    self.share_locks[locking.LEVEL_NODE] = 1
1393

    
1394
  def BuildHooksEnv(self):
1395
    """Build hooks env.
1396

1397
    """
1398
    env = {
1399
      "OP_TARGET": self.cfg.GetClusterName(),
1400
      "NEW_VG_NAME": self.op.vg_name,
1401
      }
1402
    mn = self.cfg.GetMasterNode()
1403
    return env, [mn], [mn]
1404

    
1405
  def CheckPrereq(self):
1406
    """Check prerequisites.
1407

1408
    This checks whether the given params don't conflict and
1409
    if the given volume group is valid.
1410

1411
    """
1412
    if self.op.vg_name is not None and not self.op.vg_name:
1413
      instances = self.cfg.GetAllInstancesInfo().values()
1414
      for inst in instances:
1415
        for disk in inst.disks:
1416
          if _RecursiveCheckIfLVMBased(disk):
1417
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1418
                                       " lvm-based instances exist")
1419

    
1420
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1421

    
1422
    # if vg_name not None, checks given volume group on all nodes
1423
    if self.op.vg_name:
1424
      vglist = self.rpc.call_vg_list(node_list)
1425
      for node in node_list:
1426
        if vglist[node].failed:
1427
          # ignoring down node
1428
          self.LogWarning("Node %s unreachable/error, ignoring" % node)
1429
          continue
1430
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].data,
1431
                                              self.op.vg_name,
1432
                                              constants.MIN_VG_SIZE)
1433
        if vgstatus:
1434
          raise errors.OpPrereqError("Error on node '%s': %s" %
1435
                                     (node, vgstatus))
1436

    
1437
    self.cluster = cluster = self.cfg.GetClusterInfo()
1438
    # validate beparams changes
1439
    if self.op.beparams:
1440
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
1441
      self.new_beparams = cluster.FillDict(
1442
        cluster.beparams[constants.BEGR_DEFAULT], self.op.beparams)
1443

    
1444
    # hypervisor list/parameters
1445
    self.new_hvparams = cluster.FillDict(cluster.hvparams, {})
1446
    if self.op.hvparams:
1447
      if not isinstance(self.op.hvparams, dict):
1448
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input")
1449
      for hv_name, hv_dict in self.op.hvparams.items():
1450
        if hv_name not in self.new_hvparams:
1451
          self.new_hvparams[hv_name] = hv_dict
1452
        else:
1453
          self.new_hvparams[hv_name].update(hv_dict)
1454

    
1455
    if self.op.enabled_hypervisors is not None:
1456
      self.hv_list = self.op.enabled_hypervisors
1457
    else:
1458
      self.hv_list = cluster.enabled_hypervisors
1459

    
1460
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
1461
      # either the enabled list has changed, or the parameters have, validate
1462
      for hv_name, hv_params in self.new_hvparams.items():
1463
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
1464
            (self.op.enabled_hypervisors and
1465
             hv_name in self.op.enabled_hypervisors)):
1466
          # either this is a new hypervisor, or its parameters have changed
1467
          hv_class = hypervisor.GetHypervisor(hv_name)
1468
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
1469
          hv_class.CheckParameterSyntax(hv_params)
1470
          _CheckHVParams(self, node_list, hv_name, hv_params)
1471

    
1472
  def Exec(self, feedback_fn):
1473
    """Change the parameters of the cluster.
1474

1475
    """
1476
    if self.op.vg_name is not None:
1477
      if self.op.vg_name != self.cfg.GetVGName():
1478
        self.cfg.SetVGName(self.op.vg_name)
1479
      else:
1480
        feedback_fn("Cluster LVM configuration already in desired"
1481
                    " state, not changing")
1482
    if self.op.hvparams:
1483
      self.cluster.hvparams = self.new_hvparams
1484
    if self.op.enabled_hypervisors is not None:
1485
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
1486
    if self.op.beparams:
1487
      self.cluster.beparams[constants.BEGR_DEFAULT] = self.new_beparams
1488
    if self.op.candidate_pool_size is not None:
1489
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
1490

    
1491
    self.cfg.Update(self.cluster)
1492

    
1493
    # we want to update nodes after the cluster so that if any errors
1494
    # happen, we have recorded and saved the cluster info
1495
    if self.op.candidate_pool_size is not None:
1496
      _AdjustCandidatePool(self)
1497

    
1498

    
1499
class LURedistributeConfig(NoHooksLU):
1500
  """Force the redistribution of cluster configuration.
1501

1502
  This is a very simple LU.
1503

1504
  """
1505
  _OP_REQP = []
1506
  REQ_BGL = False
1507

    
1508
  def ExpandNames(self):
1509
    self.needed_locks = {
1510
      locking.LEVEL_NODE: locking.ALL_SET,
1511
    }
1512
    self.share_locks[locking.LEVEL_NODE] = 1
1513

    
1514
  def CheckPrereq(self):
1515
    """Check prerequisites.
1516

1517
    """
1518

    
1519
  def Exec(self, feedback_fn):
1520
    """Redistribute the configuration.
1521

1522
    """
1523
    self.cfg.Update(self.cfg.GetClusterInfo())
1524

    
1525

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

1529
  """
1530
  if not instance.disks:
1531
    return True
1532

    
1533
  if not oneshot:
1534
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
1535

    
1536
  node = instance.primary_node
1537

    
1538
  for dev in instance.disks:
1539
    lu.cfg.SetDiskID(dev, node)
1540

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

    
1577
    time.sleep(min(60, max_time))
1578

    
1579
  if done:
1580
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
1581
  return not cumul_degraded
1582

    
1583

    
1584
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
1585
  """Check that mirrors are not degraded.
1586

1587
  The ldisk parameter, if True, will change the test from the
1588
  is_degraded attribute (which represents overall non-ok status for
1589
  the device(s)) to the ldisk (representing the local storage status).
1590

1591
  """
1592
  lu.cfg.SetDiskID(dev, node)
1593
  if ldisk:
1594
    idx = 6
1595
  else:
1596
    idx = 5
1597

    
1598
  result = True
1599
  if on_primary or dev.AssembleOnSecondary():
1600
    rstats = lu.rpc.call_blockdev_find(node, dev)
1601
    msg = rstats.RemoteFailMsg()
1602
    if msg:
1603
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
1604
      result = False
1605
    elif not rstats.payload:
1606
      lu.LogWarning("Can't find disk on node %s", node)
1607
      result = False
1608
    else:
1609
      result = result and (not rstats.payload[idx])
1610
  if dev.children:
1611
    for child in dev.children:
1612
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
1613

    
1614
  return result
1615

    
1616

    
1617
class LUDiagnoseOS(NoHooksLU):
1618
  """Logical unit for OS diagnose/query.
1619

1620
  """
1621
  _OP_REQP = ["output_fields", "names"]
1622
  REQ_BGL = False
1623
  _FIELDS_STATIC = utils.FieldSet()
1624
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status")
1625

    
1626
  def ExpandNames(self):
1627
    if self.op.names:
1628
      raise errors.OpPrereqError("Selective OS query not supported")
1629

    
1630
    _CheckOutputFields(static=self._FIELDS_STATIC,
1631
                       dynamic=self._FIELDS_DYNAMIC,
1632
                       selected=self.op.output_fields)
1633

    
1634
    # Lock all nodes, in shared mode
1635
    self.needed_locks = {}
1636
    self.share_locks[locking.LEVEL_NODE] = 1
1637
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1638

    
1639
  def CheckPrereq(self):
1640
    """Check prerequisites.
1641

1642
    """
1643

    
1644
  @staticmethod
1645
  def _DiagnoseByOS(node_list, rlist):
1646
    """Remaps a per-node return list into an a per-os per-node dictionary
1647

1648
    @param node_list: a list with the names of all nodes
1649
    @param rlist: a map with node names as keys and OS objects as values
1650

1651
    @rtype: dict
1652
    @returns: a dictionary with osnames as keys and as value another map, with
1653
        nodes as keys and list of OS objects as values, eg::
1654

1655
          {"debian-etch": {"node1": [<object>,...],
1656
                           "node2": [<object>,]}
1657
          }
1658

1659
    """
1660
    all_os = {}
1661
    for node_name, nr in rlist.iteritems():
1662
      if nr.failed or not nr.data:
1663
        continue
1664
      for os_obj in nr.data:
1665
        if os_obj.name not in all_os:
1666
          # build a list of nodes for this os containing empty lists
1667
          # for each node in node_list
1668
          all_os[os_obj.name] = {}
1669
          for nname in node_list:
1670
            all_os[os_obj.name][nname] = []
1671
        all_os[os_obj.name][node_name].append(os_obj)
1672
    return all_os
1673

    
1674
  def Exec(self, feedback_fn):
1675
    """Compute the list of OSes.
1676

1677
    """
1678
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1679
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()
1680
                   if node in node_list]
1681
    node_data = self.rpc.call_os_diagnose(valid_nodes)
1682
    if node_data == False:
1683
      raise errors.OpExecError("Can't gather the list of OSes")
1684
    pol = self._DiagnoseByOS(valid_nodes, node_data)
1685
    output = []
1686
    for os_name, os_data in pol.iteritems():
1687
      row = []
1688
      for field in self.op.output_fields:
1689
        if field == "name":
1690
          val = os_name
1691
        elif field == "valid":
1692
          val = utils.all([osl and osl[0] for osl in os_data.values()])
1693
        elif field == "node_status":
1694
          val = {}
1695
          for node_name, nos_list in os_data.iteritems():
1696
            val[node_name] = [(v.status, v.path) for v in nos_list]
1697
        else:
1698
          raise errors.ParameterError(field)
1699
        row.append(val)
1700
      output.append(row)
1701

    
1702
    return output
1703

    
1704

    
1705
class LURemoveNode(LogicalUnit):
1706
  """Logical unit for removing a node.
1707

1708
  """
1709
  HPATH = "node-remove"
1710
  HTYPE = constants.HTYPE_NODE
1711
  _OP_REQP = ["node_name"]
1712

    
1713
  def BuildHooksEnv(self):
1714
    """Build hooks env.
1715

1716
    This doesn't run on the target node in the pre phase as a failed
1717
    node would then be impossible to remove.
1718

1719
    """
1720
    env = {
1721
      "OP_TARGET": self.op.node_name,
1722
      "NODE_NAME": self.op.node_name,
1723
      }
1724
    all_nodes = self.cfg.GetNodeList()
1725
    all_nodes.remove(self.op.node_name)
1726
    return env, all_nodes, all_nodes
1727

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

1731
    This checks:
1732
     - the node exists in the configuration
1733
     - it does not have primary or secondary instances
1734
     - it's not the master
1735

1736
    Any errors are signalled by raising errors.OpPrereqError.
1737

1738
    """
1739
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
1740
    if node is None:
1741
      raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name)
1742

    
1743
    instance_list = self.cfg.GetInstanceList()
1744

    
1745
    masternode = self.cfg.GetMasterNode()
1746
    if node.name == masternode:
1747
      raise errors.OpPrereqError("Node is the master node,"
1748
                                 " you need to failover first.")
1749

    
1750
    for instance_name in instance_list:
1751
      instance = self.cfg.GetInstanceInfo(instance_name)
1752
      if node.name in instance.all_nodes:
1753
        raise errors.OpPrereqError("Instance %s is still running on the node,"
1754
                                   " please remove first." % instance_name)
1755
    self.op.node_name = node.name
1756
    self.node = node
1757

    
1758
  def Exec(self, feedback_fn):
1759
    """Removes the node from the cluster.
1760

1761
    """
1762
    node = self.node
1763
    logging.info("Stopping the node daemon and removing configs from node %s",
1764
                 node.name)
1765

    
1766
    self.context.RemoveNode(node.name)
1767

    
1768
    self.rpc.call_node_leave_cluster(node.name)
1769

    
1770
    # Promote nodes to master candidate as needed
1771
    _AdjustCandidatePool(self)
1772

    
1773

    
1774
class LUQueryNodes(NoHooksLU):
1775
  """Logical unit for querying nodes.
1776

1777
  """
1778
  _OP_REQP = ["output_fields", "names", "use_locking"]
1779
  REQ_BGL = False
1780
  _FIELDS_DYNAMIC = utils.FieldSet(
1781
    "dtotal", "dfree",
1782
    "mtotal", "mnode", "mfree",
1783
    "bootid",
1784
    "ctotal", "cnodes", "csockets",
1785
    )
1786

    
1787
  _FIELDS_STATIC = utils.FieldSet(
1788
    "name", "pinst_cnt", "sinst_cnt",
1789
    "pinst_list", "sinst_list",
1790
    "pip", "sip", "tags",
1791
    "serial_no",
1792
    "master_candidate",
1793
    "master",
1794
    "offline",
1795
    "drained",
1796
    )
1797

    
1798
  def ExpandNames(self):
1799
    _CheckOutputFields(static=self._FIELDS_STATIC,
1800
                       dynamic=self._FIELDS_DYNAMIC,
1801
                       selected=self.op.output_fields)
1802

    
1803
    self.needed_locks = {}
1804
    self.share_locks[locking.LEVEL_NODE] = 1
1805

    
1806
    if self.op.names:
1807
      self.wanted = _GetWantedNodes(self, self.op.names)
1808
    else:
1809
      self.wanted = locking.ALL_SET
1810

    
1811
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
1812
    self.do_locking = self.do_node_query and self.op.use_locking
1813
    if self.do_locking:
1814
      # if we don't request only static fields, we need to lock the nodes
1815
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
1816

    
1817

    
1818
  def CheckPrereq(self):
1819
    """Check prerequisites.
1820

1821
    """
1822
    # The validation of the node list is done in the _GetWantedNodes,
1823
    # if non empty, and if empty, there's no validation to do
1824
    pass
1825

    
1826
  def Exec(self, feedback_fn):
1827
    """Computes the list of nodes and their attributes.
1828

1829
    """
1830
    all_info = self.cfg.GetAllNodesInfo()
1831
    if self.do_locking:
1832
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
1833
    elif self.wanted != locking.ALL_SET:
1834
      nodenames = self.wanted
1835
      missing = set(nodenames).difference(all_info.keys())
1836
      if missing:
1837
        raise errors.OpExecError(
1838
          "Some nodes were removed before retrieving their data: %s" % missing)
1839
    else:
1840
      nodenames = all_info.keys()
1841

    
1842
    nodenames = utils.NiceSort(nodenames)
1843
    nodelist = [all_info[name] for name in nodenames]
1844

    
1845
    # begin data gathering
1846

    
1847
    if self.do_node_query:
1848
      live_data = {}
1849
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
1850
                                          self.cfg.GetHypervisorType())
1851
      for name in nodenames:
1852
        nodeinfo = node_data[name]
1853
        if not nodeinfo.failed and nodeinfo.data:
1854
          nodeinfo = nodeinfo.data
1855
          fn = utils.TryConvert
1856
          live_data[name] = {
1857
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
1858
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
1859
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
1860
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
1861
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
1862
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
1863
            "bootid": nodeinfo.get('bootid', None),
1864
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
1865
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
1866
            }
1867
        else:
1868
          live_data[name] = {}
1869
    else:
1870
      live_data = dict.fromkeys(nodenames, {})
1871

    
1872
    node_to_primary = dict([(name, set()) for name in nodenames])
1873
    node_to_secondary = dict([(name, set()) for name in nodenames])
1874

    
1875
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
1876
                             "sinst_cnt", "sinst_list"))
1877
    if inst_fields & frozenset(self.op.output_fields):
1878
      instancelist = self.cfg.GetInstanceList()
1879

    
1880
      for instance_name in instancelist:
1881
        inst = self.cfg.GetInstanceInfo(instance_name)
1882
        if inst.primary_node in node_to_primary:
1883
          node_to_primary[inst.primary_node].add(inst.name)
1884
        for secnode in inst.secondary_nodes:
1885
          if secnode in node_to_secondary:
1886
            node_to_secondary[secnode].add(inst.name)
1887

    
1888
    master_node = self.cfg.GetMasterNode()
1889

    
1890
    # end data gathering
1891

    
1892
    output = []
1893
    for node in nodelist:
1894
      node_output = []
1895
      for field in self.op.output_fields:
1896
        if field == "name":
1897
          val = node.name
1898
        elif field == "pinst_list":
1899
          val = list(node_to_primary[node.name])
1900
        elif field == "sinst_list":
1901
          val = list(node_to_secondary[node.name])
1902
        elif field == "pinst_cnt":
1903
          val = len(node_to_primary[node.name])
1904
        elif field == "sinst_cnt":
1905
          val = len(node_to_secondary[node.name])
1906
        elif field == "pip":
1907
          val = node.primary_ip
1908
        elif field == "sip":
1909
          val = node.secondary_ip
1910
        elif field == "tags":
1911
          val = list(node.GetTags())
1912
        elif field == "serial_no":
1913
          val = node.serial_no
1914
        elif field == "master_candidate":
1915
          val = node.master_candidate
1916
        elif field == "master":
1917
          val = node.name == master_node
1918
        elif field == "offline":
1919
          val = node.offline
1920
        elif field == "drained":
1921
          val = node.drained
1922
        elif self._FIELDS_DYNAMIC.Matches(field):
1923
          val = live_data[node.name].get(field, None)
1924
        else:
1925
          raise errors.ParameterError(field)
1926
        node_output.append(val)
1927
      output.append(node_output)
1928

    
1929
    return output
1930

    
1931

    
1932
class LUQueryNodeVolumes(NoHooksLU):
1933
  """Logical unit for getting volumes on node(s).
1934

1935
  """
1936
  _OP_REQP = ["nodes", "output_fields"]
1937
  REQ_BGL = False
1938
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
1939
  _FIELDS_STATIC = utils.FieldSet("node")
1940

    
1941
  def ExpandNames(self):
1942
    _CheckOutputFields(static=self._FIELDS_STATIC,
1943
                       dynamic=self._FIELDS_DYNAMIC,
1944
                       selected=self.op.output_fields)
1945

    
1946
    self.needed_locks = {}
1947
    self.share_locks[locking.LEVEL_NODE] = 1
1948
    if not self.op.nodes:
1949
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1950
    else:
1951
      self.needed_locks[locking.LEVEL_NODE] = \
1952
        _GetWantedNodes(self, self.op.nodes)
1953

    
1954
  def CheckPrereq(self):
1955
    """Check prerequisites.
1956

1957
    This checks that the fields required are valid output fields.
1958

1959
    """
1960
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
1961

    
1962
  def Exec(self, feedback_fn):
1963
    """Computes the list of nodes and their attributes.
1964

1965
    """
1966
    nodenames = self.nodes
1967
    volumes = self.rpc.call_node_volumes(nodenames)
1968

    
1969
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
1970
             in self.cfg.GetInstanceList()]
1971

    
1972
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
1973

    
1974
    output = []
1975
    for node in nodenames:
1976
      if node not in volumes or volumes[node].failed or not volumes[node].data:
1977
        continue
1978

    
1979
      node_vols = volumes[node].data[:]
1980
      node_vols.sort(key=lambda vol: vol['dev'])
1981

    
1982
      for vol in node_vols:
1983
        node_output = []
1984
        for field in self.op.output_fields:
1985
          if field == "node":
1986
            val = node
1987
          elif field == "phys":
1988
            val = vol['dev']
1989
          elif field == "vg":
1990
            val = vol['vg']
1991
          elif field == "name":
1992
            val = vol['name']
1993
          elif field == "size":
1994
            val = int(float(vol['size']))
1995
          elif field == "instance":
1996
            for inst in ilist:
1997
              if node not in lv_by_node[inst]:
1998
                continue
1999
              if vol['name'] in lv_by_node[inst][node]:
2000
                val = inst.name
2001
                break
2002
            else:
2003
              val = '-'
2004
          else:
2005
            raise errors.ParameterError(field)
2006
          node_output.append(str(val))
2007

    
2008
        output.append(node_output)
2009

    
2010
    return output
2011

    
2012

    
2013
class LUAddNode(LogicalUnit):
2014
  """Logical unit for adding node to the cluster.
2015

2016
  """
2017
  HPATH = "node-add"
2018
  HTYPE = constants.HTYPE_NODE
2019
  _OP_REQP = ["node_name"]
2020

    
2021
  def BuildHooksEnv(self):
2022
    """Build hooks env.
2023

2024
    This will run on all nodes before, and on all nodes + the new node after.
2025

2026
    """
2027
    env = {
2028
      "OP_TARGET": self.op.node_name,
2029
      "NODE_NAME": self.op.node_name,
2030
      "NODE_PIP": self.op.primary_ip,
2031
      "NODE_SIP": self.op.secondary_ip,
2032
      }
2033
    nodes_0 = self.cfg.GetNodeList()
2034
    nodes_1 = nodes_0 + [self.op.node_name, ]
2035
    return env, nodes_0, nodes_1
2036

    
2037
  def CheckPrereq(self):
2038
    """Check prerequisites.
2039

2040
    This checks:
2041
     - the new node is not already in the config
2042
     - it is resolvable
2043
     - its parameters (single/dual homed) matches the cluster
2044

2045
    Any errors are signalled by raising errors.OpPrereqError.
2046

2047
    """
2048
    node_name = self.op.node_name
2049
    cfg = self.cfg
2050

    
2051
    dns_data = utils.HostInfo(node_name)
2052

    
2053
    node = dns_data.name
2054
    primary_ip = self.op.primary_ip = dns_data.ip
2055
    secondary_ip = getattr(self.op, "secondary_ip", None)
2056
    if secondary_ip is None:
2057
      secondary_ip = primary_ip
2058
    if not utils.IsValidIP(secondary_ip):
2059
      raise errors.OpPrereqError("Invalid secondary IP given")
2060
    self.op.secondary_ip = secondary_ip
2061

    
2062
    node_list = cfg.GetNodeList()
2063
    if not self.op.readd and node in node_list:
2064
      raise errors.OpPrereqError("Node %s is already in the configuration" %
2065
                                 node)
2066
    elif self.op.readd and node not in node_list:
2067
      raise errors.OpPrereqError("Node %s is not in the configuration" % node)
2068

    
2069
    for existing_node_name in node_list:
2070
      existing_node = cfg.GetNodeInfo(existing_node_name)
2071

    
2072
      if self.op.readd and node == existing_node_name:
2073
        if (existing_node.primary_ip != primary_ip or
2074
            existing_node.secondary_ip != secondary_ip):
2075
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
2076
                                     " address configuration as before")
2077
        continue
2078

    
2079
      if (existing_node.primary_ip == primary_ip or
2080
          existing_node.secondary_ip == primary_ip or
2081
          existing_node.primary_ip == secondary_ip or
2082
          existing_node.secondary_ip == secondary_ip):
2083
        raise errors.OpPrereqError("New node ip address(es) conflict with"
2084
                                   " existing node %s" % existing_node.name)
2085

    
2086
    # check that the type of the node (single versus dual homed) is the
2087
    # same as for the master
2088
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
2089
    master_singlehomed = myself.secondary_ip == myself.primary_ip
2090
    newbie_singlehomed = secondary_ip == primary_ip
2091
    if master_singlehomed != newbie_singlehomed:
2092
      if master_singlehomed:
2093
        raise errors.OpPrereqError("The master has no private ip but the"
2094
                                   " new node has one")
2095
      else:
2096
        raise errors.OpPrereqError("The master has a private ip but the"
2097
                                   " new node doesn't have one")
2098

    
2099
    # checks reachablity
2100
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
2101
      raise errors.OpPrereqError("Node not reachable by ping")
2102

    
2103
    if not newbie_singlehomed:
2104
      # check reachability from my secondary ip to newbie's secondary ip
2105
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
2106
                           source=myself.secondary_ip):
2107
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
2108
                                   " based ping to noded port")
2109

    
2110
    cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2111
    mc_now, _ = self.cfg.GetMasterCandidateStats()
2112
    master_candidate = mc_now < cp_size
2113

    
2114
    self.new_node = objects.Node(name=node,
2115
                                 primary_ip=primary_ip,
2116
                                 secondary_ip=secondary_ip,
2117
                                 master_candidate=master_candidate,
2118
                                 offline=False, drained=False)
2119

    
2120
  def Exec(self, feedback_fn):
2121
    """Adds the new node to the cluster.
2122

2123
    """
2124
    new_node = self.new_node
2125
    node = new_node.name
2126

    
2127
    # check connectivity
2128
    result = self.rpc.call_version([node])[node]
2129
    result.Raise()
2130
    if result.data:
2131
      if constants.PROTOCOL_VERSION == result.data:
2132
        logging.info("Communication to node %s fine, sw version %s match",
2133
                     node, result.data)
2134
      else:
2135
        raise errors.OpExecError("Version mismatch master version %s,"
2136
                                 " node version %s" %
2137
                                 (constants.PROTOCOL_VERSION, result.data))
2138
    else:
2139
      raise errors.OpExecError("Cannot get version from the new node")
2140

    
2141
    # setup ssh on node
2142
    logging.info("Copy ssh key to node %s", node)
2143
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
2144
    keyarray = []
2145
    keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
2146
                constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
2147
                priv_key, pub_key]
2148

    
2149
    for i in keyfiles:
2150
      f = open(i, 'r')
2151
      try:
2152
        keyarray.append(f.read())
2153
      finally:
2154
        f.close()
2155

    
2156
    result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
2157
                                    keyarray[2],
2158
                                    keyarray[3], keyarray[4], keyarray[5])
2159

    
2160
    msg = result.RemoteFailMsg()
2161
    if msg:
2162
      raise errors.OpExecError("Cannot transfer ssh keys to the"
2163
                               " new node: %s" % msg)
2164

    
2165
    # Add node to our /etc/hosts, and add key to known_hosts
2166
    utils.AddHostToEtcHosts(new_node.name)
2167

    
2168
    if new_node.secondary_ip != new_node.primary_ip:
2169
      result = self.rpc.call_node_has_ip_address(new_node.name,
2170
                                                 new_node.secondary_ip)
2171
      if result.failed or not result.data:
2172
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
2173
                                 " you gave (%s). Please fix and re-run this"
2174
                                 " command." % new_node.secondary_ip)
2175

    
2176
    node_verify_list = [self.cfg.GetMasterNode()]
2177
    node_verify_param = {
2178
      'nodelist': [node],
2179
      # TODO: do a node-net-test as well?
2180
    }
2181

    
2182
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
2183
                                       self.cfg.GetClusterName())
2184
    for verifier in node_verify_list:
2185
      if result[verifier].failed or not result[verifier].data:
2186
        raise errors.OpExecError("Cannot communicate with %s's node daemon"
2187
                                 " for remote verification" % verifier)
2188
      if result[verifier].data['nodelist']:
2189
        for failed in result[verifier].data['nodelist']:
2190
          feedback_fn("ssh/hostname verification failed %s -> %s" %
2191
                      (verifier, result[verifier].data['nodelist'][failed]))
2192
        raise errors.OpExecError("ssh/hostname verification failed.")
2193

    
2194
    # Distribute updated /etc/hosts and known_hosts to all nodes,
2195
    # including the node just added
2196
    myself = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
2197
    dist_nodes = self.cfg.GetNodeList()
2198
    if not self.op.readd:
2199
      dist_nodes.append(node)
2200
    if myself.name in dist_nodes:
2201
      dist_nodes.remove(myself.name)
2202

    
2203
    logging.debug("Copying hosts and known_hosts to all nodes")
2204
    for fname in (constants.ETC_HOSTS, constants.SSH_KNOWN_HOSTS_FILE):
2205
      result = self.rpc.call_upload_file(dist_nodes, fname)
2206
      for to_node, to_result in result.iteritems():
2207
        if to_result.failed or not to_result.data:
2208
          logging.error("Copy of file %s to node %s failed", fname, to_node)
2209

    
2210
    to_copy = []
2211
    enabled_hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
2212
    if constants.HTS_COPY_VNC_PASSWORD.intersection(enabled_hypervisors):
2213
      to_copy.append(constants.VNC_PASSWORD_FILE)
2214

    
2215
    for fname in to_copy:
2216
      result = self.rpc.call_upload_file([node], fname)
2217
      if result[node].failed or not result[node]:
2218
        logging.error("Could not copy file %s to node %s", fname, node)
2219

    
2220
    if self.op.readd:
2221
      self.context.ReaddNode(new_node)
2222
    else:
2223
      self.context.AddNode(new_node)
2224

    
2225

    
2226
class LUSetNodeParams(LogicalUnit):
2227
  """Modifies the parameters of a node.
2228

2229
  """
2230
  HPATH = "node-modify"
2231
  HTYPE = constants.HTYPE_NODE
2232
  _OP_REQP = ["node_name"]
2233
  REQ_BGL = False
2234

    
2235
  def CheckArguments(self):
2236
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2237
    if node_name is None:
2238
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
2239
    self.op.node_name = node_name
2240
    _CheckBooleanOpField(self.op, 'master_candidate')
2241
    _CheckBooleanOpField(self.op, 'offline')
2242
    _CheckBooleanOpField(self.op, 'drained')
2243
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
2244
    if all_mods.count(None) == 3:
2245
      raise errors.OpPrereqError("Please pass at least one modification")
2246
    if all_mods.count(True) > 1:
2247
      raise errors.OpPrereqError("Can't set the node into more than one"
2248
                                 " state at the same time")
2249

    
2250
  def ExpandNames(self):
2251
    self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
2252

    
2253
  def BuildHooksEnv(self):
2254
    """Build hooks env.
2255

2256
    This runs on the master node.
2257

2258
    """
2259
    env = {
2260
      "OP_TARGET": self.op.node_name,
2261
      "MASTER_CANDIDATE": str(self.op.master_candidate),
2262
      "OFFLINE": str(self.op.offline),
2263
      "DRAINED": str(self.op.drained),
2264
      }
2265
    nl = [self.cfg.GetMasterNode(),
2266
          self.op.node_name]
2267
    return env, nl, nl
2268

    
2269
  def CheckPrereq(self):
2270
    """Check prerequisites.
2271

2272
    This only checks the instance list against the existing names.
2273

2274
    """
2275
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
2276

    
2277
    if ((self.op.master_candidate == False or self.op.offline == True or
2278
         self.op.drained == True) and node.master_candidate):
2279
      # we will demote the node from master_candidate
2280
      if self.op.node_name == self.cfg.GetMasterNode():
2281
        raise errors.OpPrereqError("The master node has to be a"
2282
                                   " master candidate, online and not drained")
2283
      cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2284
      num_candidates, _ = self.cfg.GetMasterCandidateStats()
2285
      if num_candidates <= cp_size:
2286
        msg = ("Not enough master candidates (desired"
2287
               " %d, new value will be %d)" % (cp_size, num_candidates-1))
2288
        if self.op.force:
2289
          self.LogWarning(msg)
2290
        else:
2291
          raise errors.OpPrereqError(msg)
2292

    
2293
    if (self.op.master_candidate == True and
2294
        ((node.offline and not self.op.offline == False) or
2295
         (node.drained and not self.op.drained == False))):
2296
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
2297
                                 " to master_candidate")
2298

    
2299
    return
2300

    
2301
  def Exec(self, feedback_fn):
2302
    """Modifies a node.
2303

2304
    """
2305
    node = self.node
2306

    
2307
    result = []
2308
    changed_mc = False
2309

    
2310
    if self.op.offline is not None:
2311
      node.offline = self.op.offline
2312
      result.append(("offline", str(self.op.offline)))
2313
      if self.op.offline == True:
2314
        if node.master_candidate:
2315
          node.master_candidate = False
2316
          changed_mc = True
2317
          result.append(("master_candidate", "auto-demotion due to offline"))
2318
        if node.drained:
2319
          node.drained = False
2320
          result.append(("drained", "clear drained status due to offline"))
2321

    
2322
    if self.op.master_candidate is not None:
2323
      node.master_candidate = self.op.master_candidate
2324
      changed_mc = True
2325
      result.append(("master_candidate", str(self.op.master_candidate)))
2326
      if self.op.master_candidate == False:
2327
        rrc = self.rpc.call_node_demote_from_mc(node.name)
2328
        msg = rrc.RemoteFailMsg()
2329
        if msg:
2330
          self.LogWarning("Node failed to demote itself: %s" % msg)
2331

    
2332
    if self.op.drained is not None:
2333
      node.drained = self.op.drained
2334
      result.append(("drained", str(self.op.drained)))
2335
      if self.op.drained == True:
2336
        if node.master_candidate:
2337
          node.master_candidate = False
2338
          changed_mc = True
2339
          result.append(("master_candidate", "auto-demotion due to drain"))
2340
        if node.offline:
2341
          node.offline = False
2342
          result.append(("offline", "clear offline status due to drain"))
2343

    
2344
    # this will trigger configuration file update, if needed
2345
    self.cfg.Update(node)
2346
    # this will trigger job queue propagation or cleanup
2347
    if changed_mc:
2348
      self.context.ReaddNode(node)
2349

    
2350
    return result
2351

    
2352

    
2353
class LUQueryClusterInfo(NoHooksLU):
2354
  """Query cluster configuration.
2355

2356
  """
2357
  _OP_REQP = []
2358
  REQ_BGL = False
2359

    
2360
  def ExpandNames(self):
2361
    self.needed_locks = {}
2362

    
2363
  def CheckPrereq(self):
2364
    """No prerequsites needed for this LU.
2365

2366
    """
2367
    pass
2368

    
2369
  def Exec(self, feedback_fn):
2370
    """Return cluster config.
2371

2372
    """
2373
    cluster = self.cfg.GetClusterInfo()
2374
    result = {
2375
      "software_version": constants.RELEASE_VERSION,
2376
      "protocol_version": constants.PROTOCOL_VERSION,
2377
      "config_version": constants.CONFIG_VERSION,
2378
      "os_api_version": constants.OS_API_VERSION,
2379
      "export_version": constants.EXPORT_VERSION,
2380
      "architecture": (platform.architecture()[0], platform.machine()),
2381
      "name": cluster.cluster_name,
2382
      "master": cluster.master_node,
2383
      "default_hypervisor": cluster.default_hypervisor,
2384
      "enabled_hypervisors": cluster.enabled_hypervisors,
2385
      "hvparams": dict([(hypervisor, cluster.hvparams[hypervisor])
2386
                        for hypervisor in cluster.enabled_hypervisors]),
2387
      "beparams": cluster.beparams,
2388
      "candidate_pool_size": cluster.candidate_pool_size,
2389
      }
2390

    
2391
    return result
2392

    
2393

    
2394
class LUQueryConfigValues(NoHooksLU):
2395
  """Return configuration values.
2396

2397
  """
2398
  _OP_REQP = []
2399
  REQ_BGL = False
2400
  _FIELDS_DYNAMIC = utils.FieldSet()
2401
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag")
2402

    
2403
  def ExpandNames(self):
2404
    self.needed_locks = {}
2405

    
2406
    _CheckOutputFields(static=self._FIELDS_STATIC,
2407
                       dynamic=self._FIELDS_DYNAMIC,
2408
                       selected=self.op.output_fields)
2409

    
2410
  def CheckPrereq(self):
2411
    """No prerequisites.
2412

2413
    """
2414
    pass
2415

    
2416
  def Exec(self, feedback_fn):
2417
    """Dump a representation of the cluster config to the standard output.
2418

2419
    """
2420
    values = []
2421
    for field in self.op.output_fields:
2422
      if field == "cluster_name":
2423
        entry = self.cfg.GetClusterName()
2424
      elif field == "master_node":
2425
        entry = self.cfg.GetMasterNode()
2426
      elif field == "drain_flag":
2427
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
2428
      else:
2429
        raise errors.ParameterError(field)
2430
      values.append(entry)
2431
    return values
2432

    
2433

    
2434
class LUActivateInstanceDisks(NoHooksLU):
2435
  """Bring up an instance's disks.
2436

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

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

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

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

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

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

    
2461
  def Exec(self, feedback_fn):
2462
    """Activate the disks.
2463

2464
    """
2465
    disks_ok, disks_info = _AssembleInstanceDisks(self, self.instance)
2466
    if not disks_ok:
2467
      raise errors.OpExecError("Cannot activate block devices")
2468

    
2469
    return disks_info
2470

    
2471

    
2472
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False):
2473
  """Prepare the block devices for an instance.
2474

2475
  This sets up the block devices on all nodes.
2476

2477
  @type lu: L{LogicalUnit}
2478
  @param lu: the logical unit on whose behalf we execute
2479
  @type instance: L{objects.Instance}
2480
  @param instance: the instance for whose disks we assemble
2481
  @type ignore_secondaries: boolean
2482
  @param ignore_secondaries: if true, errors on secondary nodes
2483
      won't result in an error return from the function
2484
  @return: False if the operation failed, otherwise a list of
2485
      (host, instance_visible_name, node_visible_name)
2486
      with the mapping from node devices to instance devices
2487

2488
  """
2489
  device_info = []
2490
  disks_ok = True
2491
  iname = instance.name
2492
  # With the two passes mechanism we try to reduce the window of
2493
  # opportunity for the race condition of switching DRBD to primary
2494
  # before handshaking occured, but we do not eliminate it
2495

    
2496
  # The proper fix would be to wait (with some limits) until the
2497
  # connection has been made and drbd transitions from WFConnection
2498
  # into any other network-connected state (Connected, SyncTarget,
2499
  # SyncSource, etc.)
2500

    
2501
  # 1st pass, assemble on all nodes in secondary mode
2502
  for inst_disk in instance.disks:
2503
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2504
      lu.cfg.SetDiskID(node_disk, node)
2505
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
2506
      msg = result.RemoteFailMsg()
2507
      if msg:
2508
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2509
                           " (is_primary=False, pass=1): %s",
2510
                           inst_disk.iv_name, node, msg)
2511
        if not ignore_secondaries:
2512
          disks_ok = False
2513

    
2514
  # FIXME: race condition on drbd migration to primary
2515

    
2516
  # 2nd pass, do only the primary node
2517
  for inst_disk in instance.disks:
2518
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2519
      if node != instance.primary_node:
2520
        continue
2521
      lu.cfg.SetDiskID(node_disk, node)
2522
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
2523
      msg = result.RemoteFailMsg()
2524
      if msg:
2525
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2526
                           " (is_primary=True, pass=2): %s",
2527
                           inst_disk.iv_name, node, msg)
2528
        disks_ok = False
2529
    device_info.append((instance.primary_node, inst_disk.iv_name, result.data))
2530

    
2531
  # leave the disks configured for the primary node
2532
  # this is a workaround that would be fixed better by
2533
  # improving the logical/physical id handling
2534
  for disk in instance.disks:
2535
    lu.cfg.SetDiskID(disk, instance.primary_node)
2536

    
2537
  return disks_ok, device_info
2538

    
2539

    
2540
def _StartInstanceDisks(lu, instance, force):
2541
  """Start the disks of an instance.
2542

2543
  """
2544
  disks_ok, dummy = _AssembleInstanceDisks(lu, instance,
2545
                                           ignore_secondaries=force)
2546
  if not disks_ok:
2547
    _ShutdownInstanceDisks(lu, instance)
2548
    if force is not None and not force:
2549
      lu.proc.LogWarning("", hint="If the message above refers to a"
2550
                         " secondary node,"
2551
                         " you can retry the operation using '--force'.")
2552
    raise errors.OpExecError("Disk consistency error")
2553

    
2554

    
2555
class LUDeactivateInstanceDisks(NoHooksLU):
2556
  """Shutdown an instance's disks.
2557

2558
  """
2559
  _OP_REQP = ["instance_name"]
2560
  REQ_BGL = False
2561

    
2562
  def ExpandNames(self):
2563
    self._ExpandAndLockInstance()
2564
    self.needed_locks[locking.LEVEL_NODE] = []
2565
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2566

    
2567
  def DeclareLocks(self, level):
2568
    if level == locking.LEVEL_NODE:
2569
      self._LockInstancesNodes()
2570

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

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

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

    
2581
  def Exec(self, feedback_fn):
2582
    """Deactivate the disks
2583

2584
    """
2585
    instance = self.instance
2586
    _SafeShutdownInstanceDisks(self, instance)
2587

    
2588

    
2589
def _SafeShutdownInstanceDisks(lu, instance):
2590
  """Shutdown block devices of an instance.
2591

2592
  This function checks if an instance is running, before calling
2593
  _ShutdownInstanceDisks.
2594

2595
  """
2596
  ins_l = lu.rpc.call_instance_list([instance.primary_node],
2597
                                      [instance.hypervisor])
2598
  ins_l = ins_l[instance.primary_node]
2599
  if ins_l.failed or not isinstance(ins_l.data, list):
2600
    raise errors.OpExecError("Can't contact node '%s'" %
2601
                             instance.primary_node)
2602

    
2603
  if instance.name in ins_l.data:
2604
    raise errors.OpExecError("Instance is running, can't shutdown"
2605
                             " block devices.")
2606

    
2607
  _ShutdownInstanceDisks(lu, instance)
2608

    
2609

    
2610
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
2611
  """Shutdown block devices of an instance.
2612

2613
  This does the shutdown on all nodes of the instance.
2614

2615
  If the ignore_primary is false, errors on the primary node are
2616
  ignored.
2617

2618
  """
2619
  all_result = True
2620
  for disk in instance.disks:
2621
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
2622
      lu.cfg.SetDiskID(top_disk, node)
2623
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
2624
      msg = result.RemoteFailMsg()
2625
      if msg:
2626
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
2627
                      disk.iv_name, node, msg)
2628
        if not ignore_primary or node != instance.primary_node:
2629
          all_result = False
2630
  return all_result
2631

    
2632

    
2633
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
2634
  """Checks if a node has enough free memory.
2635

2636
  This function check if a given node has the needed amount of free
2637
  memory. In case the node has less memory or we cannot get the
2638
  information from the node, this function raise an OpPrereqError
2639
  exception.
2640

2641
  @type lu: C{LogicalUnit}
2642
  @param lu: a logical unit from which we get configuration data
2643
  @type node: C{str}
2644
  @param node: the node to check
2645
  @type reason: C{str}
2646
  @param reason: string to use in the error message
2647
  @type requested: C{int}
2648
  @param requested: the amount of memory in MiB to check for
2649
  @type hypervisor_name: C{str}
2650
  @param hypervisor_name: the hypervisor to ask for memory stats
2651
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
2652
      we cannot check the node
2653

2654
  """
2655
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
2656
  nodeinfo[node].Raise()
2657
  free_mem = nodeinfo[node].data.get('memory_free')
2658
  if not isinstance(free_mem, int):
2659
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
2660
                             " was '%s'" % (node, free_mem))
2661
  if requested > free_mem:
2662
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
2663
                             " needed %s MiB, available %s MiB" %
2664
                             (node, reason, requested, free_mem))
2665

    
2666

    
2667
class LUStartupInstance(LogicalUnit):
2668
  """Starts an instance.
2669

2670
  """
2671
  HPATH = "instance-start"
2672
  HTYPE = constants.HTYPE_INSTANCE
2673
  _OP_REQP = ["instance_name", "force"]
2674
  REQ_BGL = False
2675

    
2676
  def ExpandNames(self):
2677
    self._ExpandAndLockInstance()
2678

    
2679
  def BuildHooksEnv(self):
2680
    """Build hooks env.
2681

2682
    This runs on master, primary and secondary nodes of the instance.
2683

2684
    """
2685
    env = {
2686
      "FORCE": self.op.force,
2687
      }
2688
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2689
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2690
    return env, nl, nl
2691

    
2692
  def CheckPrereq(self):
2693
    """Check prerequisites.
2694

2695
    This checks that the instance is in the cluster.
2696

2697
    """
2698
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2699
    assert self.instance is not None, \
2700
      "Cannot retrieve locked instance %s" % self.op.instance_name
2701

    
2702
    _CheckNodeOnline(self, instance.primary_node)
2703

    
2704
    bep = self.cfg.GetClusterInfo().FillBE(instance)
2705
    # check bridges existance
2706
    _CheckInstanceBridgesExist(self, instance)
2707

    
2708
    _CheckNodeFreeMemory(self, instance.primary_node,
2709
                         "starting instance %s" % instance.name,
2710
                         bep[constants.BE_MEMORY], instance.hypervisor)
2711

    
2712
  def Exec(self, feedback_fn):
2713
    """Start the instance.
2714

2715
    """
2716
    instance = self.instance
2717
    force = self.op.force
2718
    extra_args = getattr(self.op, "extra_args", "")
2719

    
2720
    self.cfg.MarkInstanceUp(instance.name)
2721

    
2722
    node_current = instance.primary_node
2723

    
2724
    _StartInstanceDisks(self, instance, force)
2725

    
2726
    result = self.rpc.call_instance_start(node_current, instance, extra_args)
2727
    msg = result.RemoteFailMsg()
2728
    if msg:
2729
      _ShutdownInstanceDisks(self, instance)
2730
      raise errors.OpExecError("Could not start instance: %s" % msg)
2731

    
2732

    
2733
class LURebootInstance(LogicalUnit):
2734
  """Reboot an instance.
2735

2736
  """
2737
  HPATH = "instance-reboot"
2738
  HTYPE = constants.HTYPE_INSTANCE
2739
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
2740
  REQ_BGL = False
2741

    
2742
  def ExpandNames(self):
2743
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
2744
                                   constants.INSTANCE_REBOOT_HARD,
2745
                                   constants.INSTANCE_REBOOT_FULL]:
2746
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
2747
                                  (constants.INSTANCE_REBOOT_SOFT,
2748
                                   constants.INSTANCE_REBOOT_HARD,
2749
                                   constants.INSTANCE_REBOOT_FULL))
2750
    self._ExpandAndLockInstance()
2751

    
2752
  def BuildHooksEnv(self):
2753
    """Build hooks env.
2754

2755
    This runs on master, primary and secondary nodes of the instance.
2756

2757
    """
2758
    env = {
2759
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
2760
      }
2761
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2762
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2763
    return env, nl, nl
2764

    
2765
  def CheckPrereq(self):
2766
    """Check prerequisites.
2767

2768
    This checks that the instance is in the cluster.
2769

2770
    """
2771
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2772
    assert self.instance is not None, \
2773
      "Cannot retrieve locked instance %s" % self.op.instance_name
2774

    
2775
    _CheckNodeOnline(self, instance.primary_node)
2776

    
2777
    # check bridges existance
2778
    _CheckInstanceBridgesExist(self, instance)
2779

    
2780
  def Exec(self, feedback_fn):
2781
    """Reboot the instance.
2782

2783
    """
2784
    instance = self.instance
2785
    ignore_secondaries = self.op.ignore_secondaries
2786
    reboot_type = self.op.reboot_type
2787
    extra_args = getattr(self.op, "extra_args", "")
2788

    
2789
    node_current = instance.primary_node
2790

    
2791
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
2792
                       constants.INSTANCE_REBOOT_HARD]:
2793
      result = self.rpc.call_instance_reboot(node_current, instance,
2794
                                             reboot_type, extra_args)
2795
      msg = result.RemoteFailMsg()
2796
      if msg:
2797
        raise errors.OpExecError("Could not reboot instance: %s" % msg)
2798
    else:
2799
      if not self.rpc.call_instance_shutdown(node_current, instance):
2800
        raise errors.OpExecError("could not shutdown instance for full reboot")
2801
      _ShutdownInstanceDisks(self, instance)
2802
      _StartInstanceDisks(self, instance, ignore_secondaries)
2803
      result = self.rpc.call_instance_start(node_current, instance, extra_args)
2804
      msg = result.RemoteFailMsg()
2805
      if msg:
2806
        _ShutdownInstanceDisks(self, instance)
2807
        raise errors.OpExecError("Could not start instance for"
2808
                                 " full reboot: %s" % msg)
2809

    
2810
    self.cfg.MarkInstanceUp(instance.name)
2811

    
2812

    
2813
class LUShutdownInstance(LogicalUnit):
2814
  """Shutdown an instance.
2815

2816
  """
2817
  HPATH = "instance-stop"
2818
  HTYPE = constants.HTYPE_INSTANCE
2819
  _OP_REQP = ["instance_name"]
2820
  REQ_BGL = False
2821

    
2822
  def ExpandNames(self):
2823
    self._ExpandAndLockInstance()
2824

    
2825
  def BuildHooksEnv(self):
2826
    """Build hooks env.
2827

2828
    This runs on master, primary and secondary nodes of the instance.
2829

2830
    """
2831
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2832
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2833
    return env, nl, nl
2834

    
2835
  def CheckPrereq(self):
2836
    """Check prerequisites.
2837

2838
    This checks that the instance is in the cluster.
2839

2840
    """
2841
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2842
    assert self.instance is not None, \
2843
      "Cannot retrieve locked instance %s" % self.op.instance_name
2844
    _CheckNodeOnline(self, self.instance.primary_node)
2845

    
2846
  def Exec(self, feedback_fn):
2847
    """Shutdown the instance.
2848

2849
    """
2850
    instance = self.instance
2851
    node_current = instance.primary_node
2852
    self.cfg.MarkInstanceDown(instance.name)
2853
    result = self.rpc.call_instance_shutdown(node_current, instance)
2854
    if result.failed or not result.data:
2855
      self.proc.LogWarning("Could not shutdown instance")
2856

    
2857
    _ShutdownInstanceDisks(self, instance)
2858

    
2859

    
2860
class LUReinstallInstance(LogicalUnit):
2861
  """Reinstall an instance.
2862

2863
  """
2864
  HPATH = "instance-reinstall"
2865
  HTYPE = constants.HTYPE_INSTANCE
2866
  _OP_REQP = ["instance_name"]
2867
  REQ_BGL = False
2868

    
2869
  def ExpandNames(self):
2870
    self._ExpandAndLockInstance()
2871

    
2872
  def BuildHooksEnv(self):
2873
    """Build hooks env.
2874

2875
    This runs on master, primary and secondary nodes of the instance.
2876

2877
    """
2878
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2879
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2880
    return env, nl, nl
2881

    
2882
  def CheckPrereq(self):
2883
    """Check prerequisites.
2884

2885
    This checks that the instance is in the cluster and is not running.
2886

2887
    """
2888
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2889
    assert instance is not None, \
2890
      "Cannot retrieve locked instance %s" % self.op.instance_name
2891
    _CheckNodeOnline(self, instance.primary_node)
2892

    
2893
    if instance.disk_template == constants.DT_DISKLESS:
2894
      raise errors.OpPrereqError("Instance '%s' has no disks" %
2895
                                 self.op.instance_name)
2896
    if instance.admin_up:
2897
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2898
                                 self.op.instance_name)
2899
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2900
                                              instance.name,
2901
                                              instance.hypervisor)
2902
    if remote_info.failed or remote_info.data:
2903
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2904
                                 (self.op.instance_name,
2905
                                  instance.primary_node))
2906

    
2907
    self.op.os_type = getattr(self.op, "os_type", None)
2908
    if self.op.os_type is not None:
2909
      # OS verification
2910
      pnode = self.cfg.GetNodeInfo(
2911
        self.cfg.ExpandNodeName(instance.primary_node))
2912
      if pnode is None:
2913
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
2914
                                   self.op.pnode)
2915
      result = self.rpc.call_os_get(pnode.name, self.op.os_type)
2916
      result.Raise()
2917
      if not isinstance(result.data, objects.OS):
2918
        raise errors.OpPrereqError("OS '%s' not in supported OS list for"
2919
                                   " primary node"  % self.op.os_type)
2920

    
2921
    self.instance = instance
2922

    
2923
  def Exec(self, feedback_fn):
2924
    """Reinstall the instance.
2925

2926
    """
2927
    inst = self.instance
2928

    
2929
    if self.op.os_type is not None:
2930
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
2931
      inst.os = self.op.os_type
2932
      self.cfg.Update(inst)
2933

    
2934
    _StartInstanceDisks(self, inst, None)
2935
    try:
2936
      feedback_fn("Running the instance OS create scripts...")
2937
      result = self.rpc.call_instance_os_add(inst.primary_node, inst)
2938
      msg = result.RemoteFailMsg()
2939
      if msg:
2940
        raise errors.OpExecError("Could not install OS for instance %s"
2941
                                 " on node %s: %s" %
2942
                                 (inst.name, inst.primary_node, msg))
2943
    finally:
2944
      _ShutdownInstanceDisks(self, inst)
2945

    
2946

    
2947
class LURenameInstance(LogicalUnit):
2948
  """Rename an instance.
2949

2950
  """
2951
  HPATH = "instance-rename"
2952
  HTYPE = constants.HTYPE_INSTANCE
2953
  _OP_REQP = ["instance_name", "new_name"]
2954

    
2955
  def BuildHooksEnv(self):
2956
    """Build hooks env.
2957

2958
    This runs on master, primary and secondary nodes of the instance.
2959

2960
    """
2961
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2962
    env["INSTANCE_NEW_NAME"] = self.op.new_name
2963
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2964
    return env, nl, nl
2965

    
2966
  def CheckPrereq(self):
2967
    """Check prerequisites.
2968

2969
    This checks that the instance is in the cluster and is not running.
2970

2971
    """
2972
    instance = self.cfg.GetInstanceInfo(
2973
      self.cfg.ExpandInstanceName(self.op.instance_name))
2974
    if instance is None:
2975
      raise errors.OpPrereqError("Instance '%s' not known" %
2976
                                 self.op.instance_name)
2977
    _CheckNodeOnline(self, instance.primary_node)
2978

    
2979
    if instance.admin_up:
2980
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2981
                                 self.op.instance_name)
2982
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2983
                                              instance.name,
2984
                                              instance.hypervisor)
2985
    remote_info.Raise()
2986
    if remote_info.data:
2987
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2988
                                 (self.op.instance_name,
2989
                                  instance.primary_node))
2990
    self.instance = instance
2991

    
2992
    # new name verification
2993
    name_info = utils.HostInfo(self.op.new_name)
2994

    
2995
    self.op.new_name = new_name = name_info.name
2996
    instance_list = self.cfg.GetInstanceList()
2997
    if new_name in instance_list:
2998
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
2999
                                 new_name)
3000

    
3001
    if not getattr(self.op, "ignore_ip", False):
3002
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
3003
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
3004
                                   (name_info.ip, new_name))
3005

    
3006

    
3007
  def Exec(self, feedback_fn):
3008
    """Reinstall the instance.
3009

3010
    """
3011
    inst = self.instance
3012
    old_name = inst.name
3013

    
3014
    if inst.disk_template == constants.DT_FILE:
3015
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
3016

    
3017
    self.cfg.RenameInstance(inst.name, self.op.new_name)
3018
    # Change the instance lock. This is definitely safe while we hold the BGL
3019
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
3020
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
3021

    
3022
    # re-read the instance from the configuration after rename
3023
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
3024

    
3025
    if inst.disk_template == constants.DT_FILE:
3026
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
3027
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
3028
                                                     old_file_storage_dir,
3029
                                                     new_file_storage_dir)
3030
      result.Raise()
3031
      if not result.data:
3032
        raise errors.OpExecError("Could not connect to node '%s' to rename"
3033
                                 " directory '%s' to '%s' (but the instance"
3034
                                 " has been renamed in Ganeti)" % (
3035
                                 inst.primary_node, old_file_storage_dir,
3036
                                 new_file_storage_dir))
3037

    
3038
      if not result.data[0]:
3039
        raise errors.OpExecError("Could not rename directory '%s' to '%s'"
3040
                                 " (but the instance has been renamed in"
3041
                                 " Ganeti)" % (old_file_storage_dir,
3042
                                               new_file_storage_dir))
3043

    
3044
    _StartInstanceDisks(self, inst, None)
3045
    try:
3046
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
3047
                                                 old_name)
3048
      msg = result.RemoteFailMsg()
3049
      if msg:
3050
        msg = ("Could not run OS rename script for instance %s on node %s"
3051
               " (but the instance has been renamed in Ganeti): %s" %
3052
               (inst.name, inst.primary_node, msg))
3053
        self.proc.LogWarning(msg)
3054
    finally:
3055
      _ShutdownInstanceDisks(self, inst)
3056

    
3057

    
3058
class LURemoveInstance(LogicalUnit):
3059
  """Remove an instance.
3060

3061
  """
3062
  HPATH = "instance-remove"
3063
  HTYPE = constants.HTYPE_INSTANCE
3064
  _OP_REQP = ["instance_name", "ignore_failures"]
3065
  REQ_BGL = False
3066

    
3067
  def ExpandNames(self):
3068
    self._ExpandAndLockInstance()
3069
    self.needed_locks[locking.LEVEL_NODE] = []
3070
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3071

    
3072
  def DeclareLocks(self, level):
3073
    if level == locking.LEVEL_NODE:
3074
      self._LockInstancesNodes()
3075

    
3076
  def BuildHooksEnv(self):
3077
    """Build hooks env.
3078

3079
    This runs on master, primary and secondary nodes of the instance.
3080

3081
    """
3082
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3083
    nl = [self.cfg.GetMasterNode()]
3084
    return env, nl, nl
3085

    
3086
  def CheckPrereq(self):
3087
    """Check prerequisites.
3088

3089
    This checks that the instance is in the cluster.
3090

3091
    """
3092
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3093
    assert self.instance is not None, \
3094
      "Cannot retrieve locked instance %s" % self.op.instance_name
3095

    
3096
  def Exec(self, feedback_fn):
3097
    """Remove the instance.
3098

3099
    """
3100
    instance = self.instance
3101
    logging.info("Shutting down instance %s on node %s",
3102
                 instance.name, instance.primary_node)
3103

    
3104
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance)
3105
    if result.failed or not result.data:
3106
      if self.op.ignore_failures:
3107
        feedback_fn("Warning: can't shutdown instance")
3108
      else:
3109
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
3110
                                 (instance.name, instance.primary_node))
3111

    
3112
    logging.info("Removing block devices for instance %s", instance.name)
3113

    
3114
    if not _RemoveDisks(self, instance):
3115
      if self.op.ignore_failures:
3116
        feedback_fn("Warning: can't remove instance's disks")
3117
      else:
3118
        raise errors.OpExecError("Can't remove instance's disks")
3119

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

    
3122
    self.cfg.RemoveInstance(instance.name)
3123
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
3124

    
3125

    
3126
class LUQueryInstances(NoHooksLU):
3127
  """Logical unit for querying instances.
3128

3129
  """
3130
  _OP_REQP = ["output_fields", "names", "use_locking"]
3131
  REQ_BGL = False
3132
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
3133
                                    "admin_state", "admin_ram",
3134
                                    "disk_template", "ip", "mac", "bridge",
3135
                                    "sda_size", "sdb_size", "vcpus", "tags",
3136
                                    "network_port", "beparams",
3137
                                    "(disk).(size)/([0-9]+)",
3138
                                    "(disk).(sizes)", "disk_usage",
3139
                                    "(nic).(mac|ip|bridge)/([0-9]+)",
3140
                                    "(nic).(macs|ips|bridges)",
3141
                                    "(disk|nic).(count)",
3142
                                    "serial_no", "hypervisor", "hvparams",] +
3143
                                  ["hv/%s" % name
3144
                                   for name in constants.HVS_PARAMETERS] +
3145
                                  ["be/%s" % name
3146
                                   for name in constants.BES_PARAMETERS])
3147
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
3148

    
3149

    
3150
  def ExpandNames(self):
3151
    _CheckOutputFields(static=self._FIELDS_STATIC,
3152
                       dynamic=self._FIELDS_DYNAMIC,
3153
                       selected=self.op.output_fields)
3154

    
3155
    self.needed_locks = {}
3156
    self.share_locks[locking.LEVEL_INSTANCE] = 1
3157
    self.share_locks[locking.LEVEL_NODE] = 1
3158

    
3159
    if self.op.names:
3160
      self.wanted = _GetWantedInstances(self, self.op.names)
3161
    else:
3162
      self.wanted = locking.ALL_SET
3163

    
3164
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3165
    self.do_locking = self.do_node_query and self.op.use_locking
3166
    if self.do_locking:
3167
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
3168
      self.needed_locks[locking.LEVEL_NODE] = []
3169
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3170

    
3171
  def DeclareLocks(self, level):
3172
    if level == locking.LEVEL_NODE and self.do_locking:
3173
      self._LockInstancesNodes()
3174

    
3175
  def CheckPrereq(self):
3176
    """Check prerequisites.
3177

3178
    """
3179
    pass
3180

    
3181
  def Exec(self, feedback_fn):
3182
    """Computes the list of nodes and their attributes.
3183

3184
    """
3185
    all_info = self.cfg.GetAllInstancesInfo()
3186
    if self.wanted == locking.ALL_SET:
3187
      # caller didn't specify instance names, so ordering is not important
3188
      if self.do_locking:
3189
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
3190
      else:
3191
        instance_names = all_info.keys()
3192
      instance_names = utils.NiceSort(instance_names)
3193
    else:
3194
      # caller did specify names, so we must keep the ordering
3195
      if self.do_locking:
3196
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
3197
      else:
3198
        tgt_set = all_info.keys()
3199
      missing = set(self.wanted).difference(tgt_set)
3200
      if missing:
3201
        raise errors.OpExecError("Some instances were removed before"
3202
                                 " retrieving their data: %s" % missing)
3203
      instance_names = self.wanted
3204

    
3205
    instance_list = [all_info[iname] for iname in instance_names]
3206

    
3207
    # begin data gathering
3208

    
3209
    nodes = frozenset([inst.primary_node for inst in instance_list])
3210
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
3211

    
3212
    bad_nodes = []
3213
    off_nodes = []
3214
    if self.do_node_query:
3215
      live_data = {}
3216
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
3217
      for name in nodes:
3218
        result = node_data[name]
3219
        if result.offline:
3220
          # offline nodes will be in both lists
3221
          off_nodes.append(name)
3222
        if result.failed:
3223
          bad_nodes.append(name)
3224
        else:
3225
          if result.data:
3226
            live_data.update(result.data)
3227
            # else no instance is alive
3228
    else:
3229
      live_data = dict([(name, {}) for name in instance_names])
3230

    
3231
    # end data gathering
3232

    
3233
    HVPREFIX = "hv/"
3234
    BEPREFIX = "be/"
3235
    output = []
3236
    for instance in instance_list:
3237
      iout = []
3238
      i_hv = self.cfg.GetClusterInfo().FillHV(instance)
3239
      i_be = self.cfg.GetClusterInfo().FillBE(instance)
3240
      for field in self.op.output_fields:
3241
        st_match = self._FIELDS_STATIC.Matches(field)
3242
        if field == "name":
3243
          val = instance.name
3244
        elif field == "os":
3245
          val = instance.os
3246
        elif field == "pnode":
3247
          val = instance.primary_node
3248
        elif field == "snodes":
3249
          val = list(instance.secondary_nodes)
3250
        elif field == "admin_state":
3251
          val = instance.admin_up
3252
        elif field == "oper_state":
3253
          if instance.primary_node in bad_nodes:
3254
            val = None
3255
          else:
3256
            val = bool(live_data.get(instance.name))
3257
        elif field == "status":
3258
          if instance.primary_node in off_nodes:
3259
            val = "ERROR_nodeoffline"
3260
          elif instance.primary_node in bad_nodes:
3261
            val = "ERROR_nodedown"
3262
          else:
3263
            running = bool(live_data.get(instance.name))
3264
            if running:
3265
              if instance.admin_up:
3266
                val = "running"
3267
              else:
3268
                val = "ERROR_up"
3269
            else:
3270
              if instance.admin_up:
3271
                val = "ERROR_down"
3272
              else:
3273
                val = "ADMIN_down"
3274
        elif field == "oper_ram":
3275
          if instance.primary_node in bad_nodes:
3276
            val = None
3277
          elif instance.name in live_data:
3278
            val = live_data[instance.name].get("memory", "?")
3279
          else:
3280
            val = "-"
3281
        elif field == "disk_template":
3282
          val = instance.disk_template
3283
        elif field == "ip":
3284
          val = instance.nics[0].ip
3285
        elif field == "bridge":
3286
          val = instance.nics[0].bridge
3287
        elif field == "mac":
3288
          val = instance.nics[0].mac
3289
        elif field == "sda_size" or field == "sdb_size":
3290
          idx = ord(field[2]) - ord('a')
3291
          try:
3292
            val = instance.FindDisk(idx).size
3293
          except errors.OpPrereqError:
3294
            val = None
3295
        elif field == "disk_usage": # total disk usage per node
3296
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
3297
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
3298
        elif field == "tags":
3299
          val = list(instance.GetTags())
3300
        elif field == "serial_no":
3301
          val = instance.serial_no
3302
        elif field == "network_port":
3303
          val = instance.network_port
3304
        elif field == "hypervisor":
3305
          val = instance.hypervisor
3306
        elif field == "hvparams":
3307
          val = i_hv
3308
        elif (field.startswith(HVPREFIX) and
3309
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS):
3310
          val = i_hv.get(field[len(HVPREFIX):], None)
3311
        elif field == "beparams":
3312
          val = i_be
3313
        elif (field.startswith(BEPREFIX) and
3314
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
3315
          val = i_be.get(field[len(BEPREFIX):], None)
3316
        elif st_match and st_match.groups():
3317
          # matches a variable list
3318
          st_groups = st_match.groups()
3319
          if st_groups and st_groups[0] == "disk":
3320
            if st_groups[1] == "count":
3321
              val = len(instance.disks)
3322
            elif st_groups[1] == "sizes":
3323
              val = [disk.size for disk in instance.disks]
3324
            elif st_groups[1] == "size":
3325
              try:
3326
                val = instance.FindDisk(st_groups[2]).size
3327
              except errors.OpPrereqError:
3328
                val = None
3329
            else:
3330
              assert False, "Unhandled disk parameter"
3331
          elif st_groups[0] == "nic":
3332
            if st_groups[1] == "count":
3333
              val = len(instance.nics)
3334
            elif st_groups[1] == "macs":
3335
              val = [nic.mac for nic in instance.nics]
3336
            elif st_groups[1] == "ips":
3337
              val = [nic.ip for nic in instance.nics]
3338
            elif st_groups[1] == "bridges":
3339
              val = [nic.bridge for nic in instance.nics]
3340
            else:
3341
              # index-based item
3342
              nic_idx = int(st_groups[2])
3343
              if nic_idx >= len(instance.nics):
3344
                val = None
3345
              else:
3346
                if st_groups[1] == "mac":
3347
                  val = instance.nics[nic_idx].mac
3348
                elif st_groups[1] == "ip":
3349
                  val = instance.nics[nic_idx].ip
3350
                elif st_groups[1] == "bridge":
3351
                  val = instance.nics[nic_idx].bridge
3352
                else:
3353
                  assert False, "Unhandled NIC parameter"
3354
          else:
3355
            assert False, "Unhandled variable parameter"
3356
        else:
3357
          raise errors.ParameterError(field)
3358
        iout.append(val)
3359
      output.append(iout)
3360

    
3361
    return output
3362

    
3363

    
3364
class LUFailoverInstance(LogicalUnit):
3365
  """Failover an instance.
3366

3367
  """
3368
  HPATH = "instance-failover"
3369
  HTYPE = constants.HTYPE_INSTANCE
3370
  _OP_REQP = ["instance_name", "ignore_consistency"]
3371
  REQ_BGL = False
3372

    
3373
  def ExpandNames(self):
3374
    self._ExpandAndLockInstance()
3375
    self.needed_locks[locking.LEVEL_NODE] = []
3376
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3377

    
3378
  def DeclareLocks(self, level):
3379
    if level == locking.LEVEL_NODE:
3380
      self._LockInstancesNodes()
3381

    
3382
  def BuildHooksEnv(self):
3383
    """Build hooks env.
3384

3385
    This runs on master, primary and secondary nodes of the instance.
3386

3387
    """
3388
    env = {
3389
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
3390
      }
3391
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3392
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
3393
    return env, nl, nl
3394

    
3395
  def CheckPrereq(self):
3396
    """Check prerequisites.
3397

3398
    This checks that the instance is in the cluster.
3399

3400
    """
3401
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3402
    assert self.instance is not None, \
3403
      "Cannot retrieve locked instance %s" % self.op.instance_name
3404

    
3405
    bep = self.cfg.GetClusterInfo().FillBE(instance)
3406
    if instance.disk_template not in constants.DTS_NET_MIRROR:
3407
      raise errors.OpPrereqError("Instance's disk layout is not"
3408
                                 " network mirrored, cannot failover.")
3409

    
3410
    secondary_nodes = instance.secondary_nodes
3411
    if not secondary_nodes:
3412
      raise errors.ProgrammerError("no secondary node but using "
3413
                                   "a mirrored disk template")
3414

    
3415
    target_node = secondary_nodes[0]
3416
    _CheckNodeOnline(self, target_node)
3417
    _CheckNodeNotDrained(self, target_node)
3418
    # check memory requirements on the secondary node
3419
    _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
3420
                         instance.name, bep[constants.BE_MEMORY],
3421
                         instance.hypervisor)
3422

    
3423
    # check bridge existance
3424
    brlist = [nic.bridge for nic in instance.nics]
3425
    result = self.rpc.call_bridges_exist(target_node, brlist)
3426
    result.Raise()
3427
    if not result.data:
3428
      raise errors.OpPrereqError("One or more target bridges %s does not"
3429
                                 " exist on destination node '%s'" %
3430
                                 (brlist, target_node))
3431

    
3432
  def Exec(self, feedback_fn):
3433
    """Failover an instance.
3434

3435
    The failover is done by shutting it down on its present node and
3436
    starting it on the secondary.
3437

3438
    """
3439
    instance = self.instance
3440

    
3441
    source_node = instance.primary_node
3442
    target_node = instance.secondary_nodes[0]
3443

    
3444
    feedback_fn("* checking disk consistency between source and target")
3445
    for dev in instance.disks:
3446
      # for drbd, these are drbd over lvm
3447
      if not _CheckDiskConsistency(self, dev, target_node, False):
3448
        if instance.admin_up and not self.op.ignore_consistency:
3449
          raise errors.OpExecError("Disk %s is degraded on target node,"
3450
                                   " aborting failover." % dev.iv_name)
3451

    
3452
    feedback_fn("* shutting down instance on source node")
3453
    logging.info("Shutting down instance %s on node %s",
3454
                 instance.name, source_node)
3455

    
3456
    result = self.rpc.call_instance_shutdown(source_node, instance)
3457
    if result.failed or not result.data:
3458
      if self.op.ignore_consistency:
3459
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
3460
                             " Proceeding"
3461
                             " anyway. Please make sure node %s is down",
3462
                             instance.name, source_node, source_node)
3463
      else:
3464
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
3465
                                 (instance.name, source_node))
3466

    
3467
    feedback_fn("* deactivating the instance's disks on source node")
3468
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
3469
      raise errors.OpExecError("Can't shut down the instance's disks.")
3470

    
3471
    instance.primary_node = target_node
3472
    # distribute new instance config to the other nodes
3473
    self.cfg.Update(instance)
3474

    
3475
    # Only start the instance if it's marked as up
3476
    if instance.admin_up:
3477
      feedback_fn("* activating the instance's disks on target node")
3478
      logging.info("Starting instance %s on node %s",
3479
                   instance.name, target_node)
3480

    
3481
      disks_ok, dummy = _AssembleInstanceDisks(self, instance,
3482
                                               ignore_secondaries=True)
3483
      if not disks_ok:
3484
        _ShutdownInstanceDisks(self, instance)
3485
        raise errors.OpExecError("Can't activate the instance's disks")
3486

    
3487
      feedback_fn("* starting the instance on the target node")
3488
      result = self.rpc.call_instance_start(target_node, instance, None)
3489
      msg = result.RemoteFailMsg()
3490
      if msg:
3491
        _ShutdownInstanceDisks(self, instance)
3492
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
3493
                                 (instance.name, target_node, msg))
3494

    
3495

    
3496
class LUMigrateInstance(LogicalUnit):
3497
  """Migrate an instance.
3498

3499
  This is migration without shutting down, compared to the failover,
3500
  which is done with shutdown.
3501

3502
  """
3503
  HPATH = "instance-migrate"
3504
  HTYPE = constants.HTYPE_INSTANCE
3505
  _OP_REQP = ["instance_name", "live", "cleanup"]
3506

    
3507
  REQ_BGL = False
3508

    
3509
  def ExpandNames(self):
3510
    self._ExpandAndLockInstance()
3511
    self.needed_locks[locking.LEVEL_NODE] = []
3512
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3513

    
3514
  def DeclareLocks(self, level):
3515
    if level == locking.LEVEL_NODE:
3516
      self._LockInstancesNodes()
3517

    
3518
  def BuildHooksEnv(self):
3519
    """Build hooks env.
3520

3521
    This runs on master, primary and secondary nodes of the instance.
3522

3523
    """
3524
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3525
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
3526
    return env, nl, nl
3527

    
3528
  def CheckPrereq(self):
3529
    """Check prerequisites.
3530

3531
    This checks that the instance is in the cluster.
3532

3533
    """
3534
    instance = self.cfg.GetInstanceInfo(
3535
      self.cfg.ExpandInstanceName(self.op.instance_name))
3536
    if instance is None:
3537
      raise errors.OpPrereqError("Instance '%s' not known" %
3538
                                 self.op.instance_name)
3539

    
3540
    if instance.disk_template != constants.DT_DRBD8:
3541
      raise errors.OpPrereqError("Instance's disk layout is not"
3542
                                 " drbd8, cannot migrate.")
3543

    
3544
    secondary_nodes = instance.secondary_nodes
3545
    if not secondary_nodes:
3546
      raise errors.ConfigurationError("No secondary node but using"
3547
                                      " drbd8 disk template")
3548

    
3549
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
3550

    
3551
    target_node = secondary_nodes[0]
3552
    # check memory requirements on the secondary node
3553
    _CheckNodeFreeMemory(self, target_node, "migrating instance %s" %
3554
                         instance.name, i_be[constants.BE_MEMORY],
3555
                         instance.hypervisor)
3556

    
3557
    # check bridge existance
3558
    brlist = [nic.bridge for nic in instance.nics]
3559
    result = self.rpc.call_bridges_exist(target_node, brlist)
3560
    if result.failed or not result.data:
3561
      raise errors.OpPrereqError("One or more target bridges %s does not"
3562
                                 " exist on destination node '%s'" %
3563
                                 (brlist, target_node))
3564

    
3565
    if not self.op.cleanup:
3566
      _CheckNodeNotDrained(self, target_node)
3567
      result = self.rpc.call_instance_migratable(instance.primary_node,
3568
                                                 instance)
3569
      msg = result.RemoteFailMsg()
3570
      if msg:
3571
        raise errors.OpPrereqError("Can't migrate: %s - please use failover" %
3572
                                   msg)
3573

    
3574
    self.instance = instance
3575

    
3576
  def _WaitUntilSync(self):
3577
    """Poll with custom rpc for disk sync.
3578

3579
    This uses our own step-based rpc call.
3580

3581
    """
3582
    self.feedback_fn("* wait until resync is done")
3583
    all_done = False
3584
    while not all_done:
3585
      all_done = True
3586
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
3587
                                            self.nodes_ip,
3588
                                            self.instance.disks)
3589
      min_percent = 100
3590
      for node, nres in result.items():
3591
        msg = nres.RemoteFailMsg()
3592
        if msg:
3593
          raise errors.OpExecError("Cannot resync disks on node %s: %s" %
3594
                                   (node, msg))
3595
        node_done, node_percent = nres.payload
3596
        all_done = all_done and node_done
3597
        if node_percent is not None:
3598
          min_percent = min(min_percent, node_percent)
3599
      if not all_done:
3600
        if min_percent < 100:
3601
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
3602
        time.sleep(2)
3603

    
3604
  def _EnsureSecondary(self, node):
3605
    """Demote a node to secondary.
3606

3607
    """
3608
    self.feedback_fn("* switching node %s to secondary mode" % node)
3609

    
3610
    for dev in self.instance.disks:
3611
      self.cfg.SetDiskID(dev, node)
3612

    
3613
    result = self.rpc.call_blockdev_close(node, self.instance.name,
3614
                                          self.instance.disks)
3615
    msg = result.RemoteFailMsg()
3616
    if msg:
3617
      raise errors.OpExecError("Cannot change disk to secondary on node %s,"
3618
                               " error %s" % (node, msg))
3619

    
3620
  def _GoStandalone(self):
3621
    """Disconnect from the network.
3622

3623
    """
3624
    self.feedback_fn("* changing into standalone mode")
3625
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
3626
                                               self.instance.disks)
3627
    for node, nres in result.items():
3628
      msg = nres.RemoteFailMsg()
3629
      if msg:
3630
        raise errors.OpExecError("Cannot disconnect disks node %s,"
3631
                                 " error %s" % (node, msg))
3632

    
3633
  def _GoReconnect(self, multimaster):
3634
    """Reconnect to the network.
3635

3636
    """
3637
    if multimaster:
3638
      msg = "dual-master"
3639
    else:
3640
      msg = "single-master"
3641
    self.feedback_fn("* changing disks into %s mode" % msg)
3642
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
3643
                                           self.instance.disks,
3644
                                           self.instance.name, multimaster)
3645
    for node, nres in result.items():
3646
      msg = nres.RemoteFailMsg()
3647
      if msg:
3648
        raise errors.OpExecError("Cannot change disks config on node %s,"
3649
                                 " error: %s" % (node, msg))
3650

    
3651
  def _ExecCleanup(self):
3652
    """Try to cleanup after a failed migration.
3653

3654
    The cleanup is done by:
3655
      - check that the instance is running only on one node
3656
        (and update the config if needed)
3657
      - change disks on its secondary node to secondary
3658
      - wait until disks are fully synchronized
3659
      - disconnect from the network
3660
      - change disks into single-master mode
3661
      - wait again until disks are fully synchronized
3662

3663
    """
3664
    instance = self.instance
3665
    target_node = self.target_node
3666
    source_node = self.source_node
3667

    
3668
    # check running on only one node
3669
    self.feedback_fn("* checking where the instance actually runs"
3670
                     " (if this hangs, the hypervisor might be in"
3671
                     " a bad state)")
3672
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
3673
    for node, result in ins_l.items():
3674
      result.Raise()
3675
      if not isinstance(result.data, list):
3676
        raise errors.OpExecError("Can't contact node '%s'" % node)
3677

    
3678
    runningon_source = instance.name in ins_l[source_node].data
3679
    runningon_target = instance.name in ins_l[target_node].data
3680

    
3681
    if runningon_source and runningon_target:
3682
      raise errors.OpExecError("Instance seems to be running on two nodes,"
3683
                               " or the hypervisor is confused. You will have"
3684
                               " to ensure manually that it runs only on one"
3685
                               " and restart this operation.")
3686

    
3687
    if not (runningon_source or runningon_target):
3688
      raise errors.OpExecError("Instance does not seem to be running at all."
3689
                               " In this case, it's safer to repair by"
3690
                               " running 'gnt-instance stop' to ensure disk"
3691
                               " shutdown, and then restarting it.")
3692

    
3693
    if runningon_target:
3694
      # the migration has actually succeeded, we need to update the config
3695
      self.feedback_fn("* instance running on secondary node (%s),"
3696
                       " updating config" % target_node)
3697
      instance.primary_node = target_node
3698
      self.cfg.Update(instance)
3699
      demoted_node = source_node
3700
    else:
3701
      self.feedback_fn("* instance confirmed to be running on its"
3702
                       " primary node (%s)" % source_node)
3703
      demoted_node = target_node
3704

    
3705
    self._EnsureSecondary(demoted_node)
3706
    try:
3707
      self._WaitUntilSync()
3708
    except errors.OpExecError:
3709
      # we ignore here errors, since if the device is standalone, it
3710
      # won't be able to sync
3711
      pass
3712
    self._GoStandalone()
3713
    self._GoReconnect(False)
3714
    self._WaitUntilSync()
3715

    
3716
    self.feedback_fn("* done")
3717

    
3718
  def _RevertDiskStatus(self):
3719
    """Try to revert the disk status after a failed migration.
3720

3721
    """
3722
    target_node = self.target_node
3723
    try:
3724
      self._EnsureSecondary(target_node)
3725
      self._GoStandalone()
3726
      self._GoReconnect(False)
3727
      self._WaitUntilSync()
3728
    except errors.OpExecError, err:
3729
      self.LogWarning("Migration failed and I can't reconnect the"
3730
                      " drives: error '%s'\n"
3731
                      "Please look and recover the instance status" %
3732
                      str(err))
3733

    
3734
  def _AbortMigration(self):
3735
    """Call the hypervisor code to abort a started migration.
3736

3737
    """
3738
    instance = self.instance
3739
    target_node = self.target_node
3740
    migration_info = self.migration_info
3741

    
3742
    abort_result = self.rpc.call_finalize_migration(target_node,
3743
                                                    instance,
3744
                                                    migration_info,
3745
                                                    False)
3746
    abort_msg = abort_result.RemoteFailMsg()
3747
    if abort_msg:
3748
      logging.error("Aborting migration failed on target node %s: %s" %
3749
                    (target_node, abort_msg))
3750
      # Don't raise an exception here, as we stil have to try to revert the
3751
      # disk status, even if this step failed.
3752

    
3753
  def _ExecMigration(self):
3754
    """Migrate an instance.
3755

3756
    The migrate is done by:
3757
      - change the disks into dual-master mode
3758
      - wait until disks are fully synchronized again
3759
      - migrate the instance
3760
      - change disks on the new secondary node (the old primary) to secondary
3761
      - wait until disks are fully synchronized
3762
      - change disks into single-master mode
3763

3764
    """
3765
    instance = self.instance
3766
    target_node = self.target_node
3767
    source_node = self.source_node
3768

    
3769
    self.feedback_fn("* checking disk consistency between source and target")
3770
    for dev in instance.disks:
3771
      if not _CheckDiskConsistency(self, dev, target_node, False):
3772
        raise errors.OpExecError("Disk %s is degraded or not fully"
3773
                                 " synchronized on target node,"
3774
                                 " aborting migrate." % dev.iv_name)
3775

    
3776
    # First get the migration information from the remote node
3777
    result = self.rpc.call_migration_info(source_node, instance)
3778
    msg = result.RemoteFailMsg()
3779
    if msg:
3780
      log_err = ("Failed fetching source migration information from %s: %s" %
3781
                 (source_node, msg))
3782
      logging.error(log_err)
3783
      raise errors.OpExecError(log_err)
3784

    
3785
    self.migration_info = migration_info = result.payload
3786

    
3787
    # Then switch the disks to master/master mode
3788
    self._EnsureSecondary(target_node)
3789
    self._GoStandalone()
3790
    self._GoReconnect(True)
3791
    self._WaitUntilSync()
3792

    
3793
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
3794
    result = self.rpc.call_accept_instance(target_node,
3795
                                           instance,
3796
                                           migration_info,
3797
                                           self.nodes_ip[target_node])
3798

    
3799
    msg = result.RemoteFailMsg()
3800
    if msg:
3801
      logging.error("Instance pre-migration failed, trying to revert"
3802
                    " disk status: %s", msg)
3803
      self._AbortMigration()
3804
      self._RevertDiskStatus()
3805
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
3806
                               (instance.name, msg))
3807

    
3808
    self.feedback_fn("* migrating instance to %s" % target_node)
3809
    time.sleep(10)
3810
    result = self.rpc.call_instance_migrate(source_node, instance,
3811
                                            self.nodes_ip[target_node],
3812
                                            self.op.live)
3813
    msg = result.RemoteFailMsg()
3814
    if msg:
3815
      logging.error("Instance migration failed, trying to revert"
3816
                    " disk status: %s", msg)
3817
      self._AbortMigration()
3818
      self._RevertDiskStatus()
3819
      raise errors.OpExecError("Could not migrate instance %s: %s" %
3820
                               (instance.name, msg))
3821
    time.sleep(10)
3822

    
3823
    instance.primary_node = target_node
3824
    # distribute new instance config to the other nodes
3825
    self.cfg.Update(instance)
3826

    
3827
    result = self.rpc.call_finalize_migration(target_node,
3828
                                              instance,
3829
                                              migration_info,
3830
                                              True)
3831
    msg = result.RemoteFailMsg()
3832
    if msg:
3833
      logging.error("Instance migration succeeded, but finalization failed:"
3834
                    " %s" % msg)
3835
      raise errors.OpExecError("Could not finalize instance migration: %s" %
3836
                               msg)
3837

    
3838
    self._EnsureSecondary(source_node)
3839
    self._WaitUntilSync()
3840
    self._GoStandalone()
3841
    self._GoReconnect(False)
3842
    self._WaitUntilSync()
3843

    
3844
    self.feedback_fn("* done")
3845

    
3846
  def Exec(self, feedback_fn):
3847
    """Perform the migration.
3848

3849
    """
3850
    self.feedback_fn = feedback_fn
3851

    
3852
    self.source_node = self.instance.primary_node
3853
    self.target_node = self.instance.secondary_nodes[0]
3854
    self.all_nodes = [self.source_node, self.target_node]
3855
    self.nodes_ip = {
3856
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
3857
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
3858
      }
3859
    if self.op.cleanup:
3860
      return self._ExecCleanup()
3861
    else:
3862
      return self._ExecMigration()
3863

    
3864

    
3865
def _CreateBlockDev(lu, node, instance, device, force_create,
3866
                    info, force_open):
3867
  """Create a tree of block devices on a given node.
3868

3869
  If this device type has to be created on secondaries, create it and
3870
  all its children.
3871

3872
  If not, just recurse to children keeping the same 'force' value.
3873

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

3892
  """
3893
  if device.CreateOnSecondary():
3894
    force_create = True
3895

    
3896
  if device.children:
3897
    for child in device.children:
3898
      _CreateBlockDev(lu, node, instance, child, force_create,
3899
                      info, force_open)
3900

    
3901
  if not force_create:
3902
    return
3903

    
3904
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
3905

    
3906

    
3907
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
3908
  """Create a single block device on a given node.
3909

3910
  This will not recurse over children of the device, so they must be
3911
  created in advance.
3912

3913
  @param lu: the lu on whose behalf we execute
3914
  @param node: the node on which to create the device
3915
  @type instance: L{objects.Instance}
3916
  @param instance: the instance which owns the device
3917
  @type device: L{objects.Disk}
3918
  @param device: the device to create
3919
  @param info: the extra 'metadata' we should attach to the device
3920
      (this will be represented as a LVM tag)
3921
  @type force_open: boolean
3922
  @param force_open: this parameter will be passes to the
3923
      L{backend.BlockdevCreate} function where it specifies
3924
      whether we run on primary or not, and it affects both
3925
      the child assembly and the device own Open() execution
3926

3927
  """
3928
  lu.cfg.SetDiskID(device, node)
3929
  result = lu.rpc.call_blockdev_create(node, device, device.size,
3930
                                       instance.name, force_open, info)
3931
  msg = result.RemoteFailMsg()
3932
  if msg:
3933
    raise errors.OpExecError("Can't create block device %s on"
3934
                             " node %s for instance %s: %s" %
3935
                             (device, node, instance.name, msg))
3936
  if device.physical_id is None:
3937
    device.physical_id = result.payload
3938

    
3939

    
3940
def _GenerateUniqueNames(lu, exts):
3941
  """Generate a suitable LV name.
3942

3943
  This will generate a logical volume name for the given instance.
3944

3945
  """
3946
  results = []
3947
  for val in exts:
3948
    new_id = lu.cfg.GenerateUniqueID()
3949
    results.append("%s%s" % (new_id, val))
3950
  return results
3951

    
3952

    
3953
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
3954
                         p_minor, s_minor):
3955
  """Generate a drbd8 device complete with its children.
3956

3957
  """
3958
  port = lu.cfg.AllocatePort()
3959
  vgname = lu.cfg.GetVGName()
3960
  shared_secret = lu.cfg.GenerateDRBDSecret()
3961
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
3962
                          logical_id=(vgname, names[0]))
3963
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
3964
                          logical_id=(vgname, names[1]))
3965
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
3966
                          logical_id=(primary, secondary, port,
3967
                                      p_minor, s_minor,
3968
                                      shared_secret),
3969
                          children=[dev_data, dev_meta],
3970
                          iv_name=iv_name)
3971
  return drbd_dev
3972

    
3973

    
3974
def _GenerateDiskTemplate(lu, template_name,
3975
                          instance_name, primary_node,
3976
                          secondary_nodes, disk_info,
3977
                          file_storage_dir, file_driver,
3978
                          base_index):
3979
  """Generate the entire disk layout for a given template type.
3980

3981
  """
3982
  #TODO: compute space requirements
3983

    
3984
  vgname = lu.cfg.GetVGName()
3985
  disk_count = len(disk_info)
3986
  disks = []
3987
  if template_name == constants.DT_DISKLESS:
3988
    pass
3989
  elif template_name == constants.DT_PLAIN:
3990
    if len(secondary_nodes) != 0:
3991
      raise errors.ProgrammerError("Wrong template configuration")
3992

    
3993
    names = _GenerateUniqueNames(lu, [".disk%d" % i
3994
                                      for i in range(disk_count)])
3995
    for idx, disk in enumerate(disk_info):
3996
      disk_index = idx + base_index
3997
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
3998
                              logical_id=(vgname, names[idx]),
3999
                              iv_name="disk/%d" % disk_index,
4000
                              mode=disk["mode"])
4001
      disks.append(disk_dev)
4002
  elif template_name == constants.DT_DRBD8:
4003
    if len(secondary_nodes) != 1:
4004
      raise errors.ProgrammerError("Wrong template configuration")
4005
    remote_node = secondary_nodes[0]
4006
    minors = lu.cfg.AllocateDRBDMinor(
4007
      [primary_node, remote_node] * len(disk_info), instance_name)
4008

    
4009
    names = []
4010
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % i
4011
                                               for i in range(disk_count)]):
4012
      names.append(lv_prefix + "_data")
4013
      names.append(lv_prefix + "_meta")
4014
    for idx, disk in enumerate(disk_info):
4015
      disk_index = idx + base_index
4016
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
4017
                                      disk["size"], names[idx*2:idx*2+2],
4018
                                      "disk/%d" % disk_index,
4019
                                      minors[idx*2], minors[idx*2+1])
4020
      disk_dev.mode = disk["mode"]
4021
      disks.append(disk_dev)
4022
  elif template_name == constants.DT_FILE:
4023
    if len(secondary_nodes) != 0:
4024
      raise errors.ProgrammerError("Wrong template configuration")
4025

    
4026
    for idx, disk in enumerate(disk_info):
4027
      disk_index = idx + base_index
4028
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
4029
                              iv_name="disk/%d" % disk_index,
4030
                              logical_id=(file_driver,
4031
                                          "%s/disk%d" % (file_storage_dir,
4032
                                                         disk_index)),
4033
                              mode=disk["mode"])
4034
      disks.append(disk_dev)
4035
  else:
4036
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
4037
  return disks
4038

    
4039

    
4040
def _GetInstanceInfoText(instance):
4041
  """Compute that text that should be added to the disk's metadata.
4042

4043
  """
4044
  return "originstname+%s" % instance.name
4045

    
4046

    
4047
def _CreateDisks(lu, instance):
4048
  """Create all disks for an instance.
4049

4050
  This abstracts away some work from AddInstance.
4051

4052
  @type lu: L{LogicalUnit}
4053
  @param lu: the logical unit on whose behalf we execute
4054
  @type instance: L{objects.Instance}
4055
  @param instance: the instance whose disks we should create
4056
  @rtype: boolean
4057
  @return: the success of the creation
4058

4059
  """
4060
  info = _GetInstanceInfoText(instance)
4061
  pnode = instance.primary_node
4062

    
4063
  if instance.disk_template == constants.DT_FILE:
4064
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
4065
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
4066

    
4067
    if result.failed or not result.data:
4068
      raise errors.OpExecError("Could not connect to node '%s'" % pnode)
4069

    
4070
    if not result.data[0]:
4071
      raise errors.OpExecError("Failed to create directory '%s'" %
4072
                               file_storage_dir)
4073

    
4074
  # Note: this needs to be kept in sync with adding of disks in
4075
  # LUSetInstanceParams
4076
  for device in instance.disks:
4077
    logging.info("Creating volume %s for instance %s",
4078
                 device.iv_name, instance.name)
4079
    #HARDCODE
4080
    for node in instance.all_nodes:
4081
      f_create = node == pnode
4082
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
4083

    
4084

    
4085
def _RemoveDisks(lu, instance):
4086
  """Remove all disks for an instance.
4087

4088
  This abstracts away some work from `AddInstance()` and
4089
  `RemoveInstance()`. Note that in case some of the devices couldn't
4090
  be removed, the removal will continue with the other ones (compare
4091
  with `_CreateDisks()`).
4092

4093
  @type lu: L{LogicalUnit}
4094
  @param lu: the logical unit on whose behalf we execute
4095
  @type instance: L{objects.Instance}
4096
  @param instance: the instance whose disks we should remove
4097
  @rtype: boolean
4098
  @return: the success of the removal
4099

4100
  """
4101
  logging.info("Removing block devices for instance %s", instance.name)
4102

    
4103
  all_result = True
4104
  for device in instance.disks:
4105
    for node, disk in device.ComputeNodeTree(instance.primary_node):
4106
      lu.cfg.SetDiskID(disk, node)
4107
      msg = lu.rpc.call_blockdev_remove(node, disk).RemoteFailMsg()
4108
      if msg:
4109
        lu.LogWarning("Could not remove block device %s on node %s,"
4110
                      " continuing anyway: %s", device.iv_name, node, msg)
4111
        all_result = False
4112

    
4113
  if instance.disk_template == constants.DT_FILE:
4114
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
4115
    result = lu.rpc.call_file_storage_dir_remove(instance.primary_node,
4116
                                                 file_storage_dir)
4117
    if result.failed or not result.data:
4118
      logging.error("Could not remove directory '%s'", file_storage_dir)
4119
      all_result = False
4120

    
4121
  return all_result
4122

    
4123

    
4124
def _ComputeDiskSize(disk_template, disks):
4125
  """Compute disk size requirements in the volume group
4126

4127
  """
4128
  # Required free disk space as a function of disk and swap space
4129
  req_size_dict = {
4130
    constants.DT_DISKLESS: None,
4131
    constants.DT_PLAIN: sum(d["size"] for d in disks),
4132
    # 128 MB are added for drbd metadata for each disk
4133
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
4134
    constants.DT_FILE: None,
4135
  }
4136

    
4137
  if disk_template not in req_size_dict:
4138
    raise errors.ProgrammerError("Disk template '%s' size requirement"
4139
                                 " is unknown" %  disk_template)
4140

    
4141
  return req_size_dict[disk_template]
4142

    
4143

    
4144
def _CheckHVParams(lu, nodenames, hvname, hvparams):
4145
  """Hypervisor parameter validation.
4146

4147
  This function abstract the hypervisor parameter validation to be
4148
  used in both instance create and instance modify.
4149

4150
  @type lu: L{LogicalUnit}
4151
  @param lu: the logical unit for which we check
4152
  @type nodenames: list
4153
  @param nodenames: the list of nodes on which we should check
4154
  @type hvname: string
4155
  @param hvname: the name of the hypervisor we should use
4156
  @type hvparams: dict
4157
  @param hvparams: the parameters which we need to check
4158
  @raise errors.OpPrereqError: if the parameters are not valid
4159

4160
  """
4161
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
4162
                                                  hvname,
4163
                                                  hvparams)
4164
  for node in nodenames:
4165
    info = hvinfo[node]
4166
    if info.offline:
4167
      continue
4168
    msg = info.RemoteFailMsg()
4169
    if msg:
4170
      raise errors.OpPrereqError("Hypervisor parameter validation failed:"
4171
                                 " %s" % msg)
4172

    
4173

    
4174
class LUCreateInstance(LogicalUnit):
4175
  """Create an instance.
4176

4177
  """
4178
  HPATH = "instance-add"
4179
  HTYPE = constants.HTYPE_INSTANCE
4180
  _OP_REQP = ["instance_name", "disks", "disk_template",
4181
              "mode", "start",
4182
              "wait_for_sync", "ip_check", "nics",
4183
              "hvparams", "beparams"]
4184
  REQ_BGL = False
4185

    
4186
  def _ExpandNode(self, node):
4187
    """Expands and checks one node name.
4188

4189
    """
4190
    node_full = self.cfg.ExpandNodeName(node)
4191
    if node_full is None:
4192
      raise errors.OpPrereqError("Unknown node %s" % node)
4193
    return node_full
4194

    
4195
  def ExpandNames(self):
4196
    """ExpandNames for CreateInstance.
4197

4198
    Figure out the right locks for instance creation.
4199

4200
    """
4201
    self.needed_locks = {}
4202

    
4203
    # set optional parameters to none if they don't exist
4204
    for attr in ["pnode", "snode", "iallocator", "hypervisor"]:
4205
      if not hasattr(self.op, attr):
4206
        setattr(self.op, attr, None)
4207

    
4208
    # cheap checks, mostly valid constants given
4209

    
4210
    # verify creation mode
4211
    if self.op.mode not in (constants.INSTANCE_CREATE,
4212
                            constants.INSTANCE_IMPORT):
4213
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
4214
                                 self.op.mode)
4215

    
4216
    # disk template and mirror node verification
4217
    if self.op.disk_template not in constants.DISK_TEMPLATES:
4218
      raise errors.OpPrereqError("Invalid disk template name")
4219

    
4220
    if self.op.hypervisor is None:
4221
      self.op.hypervisor = self.cfg.GetHypervisorType()
4222

    
4223
    cluster = self.cfg.GetClusterInfo()
4224
    enabled_hvs = cluster.enabled_hypervisors
4225
    if self.op.hypervisor not in enabled_hvs:
4226
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
4227
                                 " cluster (%s)" % (self.op.hypervisor,
4228
                                  ",".join(enabled_hvs)))
4229

    
4230
    # check hypervisor parameter syntax (locally)
4231
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
4232
    filled_hvp = cluster.FillDict(cluster.hvparams[self.op.hypervisor],
4233
                                  self.op.hvparams)
4234
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
4235
    hv_type.CheckParameterSyntax(filled_hvp)
4236

    
4237
    # fill and remember the beparams dict
4238
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
4239
    self.be_full = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
4240
                                    self.op.beparams)
4241

    
4242
    #### instance parameters check
4243

    
4244
    # instance name verification
4245
    hostname1 = utils.HostInfo(self.op.instance_name)
4246
    self.op.instance_name = instance_name = hostname1.name
4247

    
4248
    # this is just a preventive check, but someone might still add this
4249
    # instance in the meantime, and creation will fail at lock-add time
4250
    if instance_name in self.cfg.GetInstanceList():
4251
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4252
                                 instance_name)
4253

    
4254
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
4255

    
4256
    # NIC buildup
4257
    self.nics = []
4258
    for nic in self.op.nics:
4259
      # ip validity checks
4260
      ip = nic.get("ip", None)
4261
      if ip is None or ip.lower() == "none":
4262
        nic_ip = None
4263
      elif ip.lower() == constants.VALUE_AUTO:
4264
        nic_ip = hostname1.ip
4265
      else:
4266
        if not utils.IsValidIP(ip):
4267
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
4268
                                     " like a valid IP" % ip)
4269
        nic_ip = ip
4270

    
4271
      # MAC address verification
4272
      mac = nic.get("mac", constants.VALUE_AUTO)
4273
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
4274
        if not utils.IsValidMac(mac.lower()):
4275
          raise errors.OpPrereqError("Invalid MAC address specified: %s" %
4276
                                     mac)
4277
      # bridge verification
4278
      bridge = nic.get("bridge", None)
4279
      if bridge is None:
4280
        bridge = self.cfg.GetDefBridge()
4281
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, bridge=bridge))
4282

    
4283
    # disk checks/pre-build
4284
    self.disks = []
4285
    for disk in self.op.disks:
4286
      mode = disk.get("mode", constants.DISK_RDWR)
4287
      if mode not in constants.DISK_ACCESS_SET:
4288
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
4289
                                   mode)
4290
      size = disk.get("size", None)
4291
      if size is None:
4292
        raise errors.OpPrereqError("Missing disk size")
4293
      try:
4294
        size = int(size)
4295
      except ValueError:
4296
        raise errors.OpPrereqError("Invalid disk size '%s'" % size)
4297
      self.disks.append({"size": size, "mode": mode})
4298

    
4299
    # used in CheckPrereq for ip ping check
4300
    self.check_ip = hostname1.ip
4301

    
4302
    # file storage checks
4303
    if (self.op.file_driver and
4304
        not self.op.file_driver in constants.FILE_DRIVER):
4305
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
4306
                                 self.op.file_driver)
4307

    
4308
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
4309
      raise errors.OpPrereqError("File storage directory path not absolute")
4310

    
4311
    ### Node/iallocator related checks
4312
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
4313
      raise errors.OpPrereqError("One and only one of iallocator and primary"
4314
                                 " node must be given")
4315

    
4316
    if self.op.iallocator:
4317
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4318
    else:
4319
      self.op.pnode = self._ExpandNode(self.op.pnode)
4320
      nodelist = [self.op.pnode]
4321
      if self.op.snode is not None:
4322
        self.op.snode = self._ExpandNode(self.op.snode)
4323
        nodelist.append(self.op.snode)
4324
      self.needed_locks[locking.LEVEL_NODE] = nodelist
4325

    
4326
    # in case of import lock the source node too
4327
    if self.op.mode == constants.INSTANCE_IMPORT:
4328
      src_node = getattr(self.op, "src_node", None)
4329
      src_path = getattr(self.op, "src_path", None)
4330

    
4331
      if src_path is None:
4332
        self.op.src_path = src_path = self.op.instance_name
4333

    
4334
      if src_node is None:
4335
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4336
        self.op.src_node = None
4337
        if os.path.isabs(src_path):
4338
          raise errors.OpPrereqError("Importing an instance from an absolute"
4339
                                     " path requires a source node option.")
4340
      else:
4341
        self.op.src_node = src_node = self._ExpandNode(src_node)
4342
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4343
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
4344
        if not os.path.isabs(src_path):
4345
          self.op.src_path = src_path = \
4346
            os.path.join(constants.EXPORT_DIR, src_path)
4347

    
4348
    else: # INSTANCE_CREATE
4349
      if getattr(self.op, "os_type", None) is None:
4350
        raise errors.OpPrereqError("No guest OS specified")
4351

    
4352
  def _RunAllocator(self):
4353
    """Run the allocator based on input opcode.
4354

4355
    """
4356
    nics = [n.ToDict() for n in self.nics]
4357
    ial = IAllocator(self,
4358
                     mode=constants.IALLOCATOR_MODE_ALLOC,
4359
                     name=self.op.instance_name,
4360
                     disk_template=self.op.disk_template,
4361
                     tags=[],
4362
                     os=self.op.os_type,
4363
                     vcpus=self.be_full[constants.BE_VCPUS],
4364
                     mem_size=self.be_full[constants.BE_MEMORY],
4365
                     disks=self.disks,
4366
                     nics=nics,
4367
                     hypervisor=self.op.hypervisor,
4368
                     )
4369

    
4370
    ial.Run(self.op.iallocator)
4371

    
4372
    if not ial.success:
4373
      raise errors.OpPrereqError("Can't compute nodes using"
4374
                                 " iallocator '%s': %s" % (self.op.iallocator,
4375
                                                           ial.info))
4376
    if len(ial.nodes) != ial.required_nodes:
4377
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
4378
                                 " of nodes (%s), required %s" %
4379
                                 (self.op.iallocator, len(ial.nodes),
4380
                                  ial.required_nodes))
4381
    self.op.pnode = ial.nodes[0]
4382
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
4383
                 self.op.instance_name, self.op.iallocator,
4384
                 ", ".join(ial.nodes))
4385
    if ial.required_nodes == 2:
4386
      self.op.snode = ial.nodes[1]
4387

    
4388
  def BuildHooksEnv(self):
4389
    """Build hooks env.
4390

4391
    This runs on master, primary and secondary nodes of the instance.
4392

4393
    """
4394
    env = {
4395
      "INSTANCE_DISK_TEMPLATE": self.op.disk_template,
4396
      "INSTANCE_DISK_SIZE": ",".join(str(d["size"]) for d in self.disks),
4397
      "INSTANCE_ADD_MODE": self.op.mode,
4398
      }
4399
    if self.op.mode == constants.INSTANCE_IMPORT:
4400
      env["INSTANCE_SRC_NODE"] = self.op.src_node
4401
      env["INSTANCE_SRC_PATH"] = self.op.src_path
4402
      env["INSTANCE_SRC_IMAGES"] = self.src_images
4403

    
4404
    env.update(_BuildInstanceHookEnv(name=self.op.instance_name,
4405
      primary_node=self.op.pnode,
4406
      secondary_nodes=self.secondaries,
4407
      status=self.op.start,
4408
      os_type=self.op.os_type,
4409
      memory=self.be_full[constants.BE_MEMORY],
4410
      vcpus=self.be_full[constants.BE_VCPUS],
4411
      nics=[(n.ip, n.bridge, n.mac) for n in self.nics],
4412
    ))
4413

    
4414
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
4415
          self.secondaries)
4416
    return env, nl, nl
4417

    
4418

    
4419
  def CheckPrereq(self):
4420
    """Check prerequisites.
4421

4422
    """
4423
    if (not self.cfg.GetVGName() and
4424
        self.op.disk_template not in constants.DTS_NOT_LVM):
4425
      raise errors.OpPrereqError("Cluster does not support lvm-based"
4426
                                 " instances")
4427

    
4428

    
4429
    if self.op.mode == constants.INSTANCE_IMPORT:
4430
      src_node = self.op.src_node
4431
      src_path = self.op.src_path
4432

    
4433
      if src_node is None:
4434
        exp_list = self.rpc.call_export_list(
4435
          self.acquired_locks[locking.LEVEL_NODE])
4436
        found = False
4437
        for node in exp_list:
4438
          if not exp_list[node].failed and src_path in exp_list[node].data:
4439
            found = True
4440
            self.op.src_node = src_node = node
4441
            self.op.src_path = src_path = os.path.join(constants.EXPORT_DIR,
4442
                                                       src_path)
4443
            break
4444
        if not found:
4445
          raise errors.OpPrereqError("No export found for relative path %s" %
4446
                                      src_path)
4447

    
4448
      _CheckNodeOnline(self, src_node)
4449
      result = self.rpc.call_export_info(src_node, src_path)
4450
      result.Raise()
4451
      if not result.data:
4452
        raise errors.OpPrereqError("No export found in dir %s" % src_path)
4453

    
4454
      export_info = result.data
4455
      if not export_info.has_section(constants.INISECT_EXP):
4456
        raise errors.ProgrammerError("Corrupted export config")
4457

    
4458
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
4459
      if (int(ei_version) != constants.EXPORT_VERSION):
4460
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
4461
                                   (ei_version, constants.EXPORT_VERSION))
4462

    
4463
      # Check that the new instance doesn't have less disks than the export
4464
      instance_disks = len(self.disks)
4465
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
4466
      if instance_disks < export_disks:
4467
        raise errors.OpPrereqError("Not enough disks to import."
4468
                                   " (instance: %d, export: %d)" %
4469
                                   (instance_disks, export_disks))
4470

    
4471
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
4472
      disk_images = []
4473
      for idx in range(export_disks):
4474
        option = 'disk%d_dump' % idx
4475
        if export_info.has_option(constants.INISECT_INS, option):
4476
          # FIXME: are the old os-es, disk sizes, etc. useful?
4477
          export_name = export_info.get(constants.INISECT_INS, option)
4478
          image = os.path.join(src_path, export_name)
4479
          disk_images.append(image)
4480
        else:
4481
          disk_images.append(False)
4482

    
4483
      self.src_images = disk_images
4484

    
4485
      old_name = export_info.get(constants.INISECT_INS, 'name')
4486
      # FIXME: int() here could throw a ValueError on broken exports
4487
      exp_nic_count = int(export_info.get(constants.INISECT_INS, 'nic_count'))
4488
      if self.op.instance_name == old_name:
4489
        for idx, nic in enumerate(self.nics):
4490
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
4491
            nic_mac_ini = 'nic%d_mac' % idx
4492
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
4493

    
4494
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
4495
    if self.op.start and not self.op.ip_check:
4496
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
4497
                                 " adding an instance in start mode")
4498

    
4499
    if self.op.ip_check:
4500
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
4501
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4502
                                   (self.check_ip, self.op.instance_name))
4503

    
4504
    #### allocator run
4505

    
4506
    if self.op.iallocator is not None:
4507
      self._RunAllocator()
4508

    
4509
    #### node related checks
4510

    
4511
    # check primary node
4512
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
4513
    assert self.pnode is not None, \
4514
      "Cannot retrieve locked node %s" % self.op.pnode
4515
    if pnode.offline:
4516
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
4517
                                 pnode.name)
4518
    if pnode.drained:
4519
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
4520
                                 pnode.name)
4521

    
4522
    self.secondaries = []
4523

    
4524
    # mirror node verification
4525
    if self.op.disk_template in constants.DTS_NET_MIRROR:
4526
      if self.op.snode is None:
4527
        raise errors.OpPrereqError("The networked disk templates need"
4528
                                   " a mirror node")
4529
      if self.op.snode == pnode.name:
4530
        raise errors.OpPrereqError("The secondary node cannot be"
4531
                                   " the primary node.")
4532
      _CheckNodeOnline(self, self.op.snode)
4533
      _CheckNodeNotDrained(self, self.op.snode)
4534
      self.secondaries.append(self.op.snode)
4535

    
4536
    nodenames = [pnode.name] + self.secondaries
4537

    
4538
    req_size = _ComputeDiskSize(self.op.disk_template,
4539
                                self.disks)
4540

    
4541
    # Check lv size requirements
4542
    if req_size is not None:
4543
      nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
4544
                                         self.op.hypervisor)
4545
      for node in nodenames:
4546
        info = nodeinfo[node]
4547
        info.Raise()
4548
        info = info.data
4549
        if not info:
4550
          raise errors.OpPrereqError("Cannot get current information"
4551
                                     " from node '%s'" % node)
4552
        vg_free = info.get('vg_free', None)
4553
        if not isinstance(vg_free, int):
4554
          raise errors.OpPrereqError("Can't compute free disk space on"
4555
                                     " node %s" % node)
4556
        if req_size > info['vg_free']:
4557
          raise errors.OpPrereqError("Not enough disk space on target node %s."
4558
                                     " %d MB available, %d MB required" %
4559
                                     (node, info['vg_free'], req_size))
4560

    
4561
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
4562

    
4563
    # os verification
4564
    result = self.rpc.call_os_get(pnode.name, self.op.os_type)
4565
    result.Raise()
4566
    if not isinstance(result.data, objects.OS):
4567
      raise errors.OpPrereqError("OS '%s' not in supported os list for"
4568
                                 " primary node"  % self.op.os_type)
4569

    
4570
    # bridge check on primary node
4571
    bridges = [n.bridge for n in self.nics]
4572
    result = self.rpc.call_bridges_exist(self.pnode.name, bridges)
4573
    result.Raise()
4574
    if not result.data:
4575
      raise errors.OpPrereqError("One of the target bridges '%s' does not"
4576
                                 " exist on destination node '%s'" %
4577
                                 (",".join(bridges), pnode.name))
4578

    
4579
    # memory check on primary node
4580
    if self.op.start:
4581
      _CheckNodeFreeMemory(self, self.pnode.name,
4582
                           "creating instance %s" % self.op.instance_name,
4583
                           self.be_full[constants.BE_MEMORY],
4584
                           self.op.hypervisor)
4585

    
4586
  def Exec(self, feedback_fn):
4587
    """Create and add the instance to the cluster.
4588

4589
    """
4590
    instance = self.op.instance_name
4591
    pnode_name = self.pnode.name
4592

    
4593
    for nic in self.nics:
4594
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
4595
        nic.mac = self.cfg.GenerateMAC()
4596

    
4597
    ht_kind = self.op.hypervisor
4598
    if ht_kind in constants.HTS_REQ_PORT:
4599
      network_port = self.cfg.AllocatePort()
4600
    else:
4601
      network_port = None
4602

    
4603
    ##if self.op.vnc_bind_address is None:
4604
    ##  self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
4605

    
4606
    # this is needed because os.path.join does not accept None arguments
4607
    if self.op.file_storage_dir is None:
4608
      string_file_storage_dir = ""
4609
    else:
4610
      string_file_storage_dir = self.op.file_storage_dir
4611

    
4612
    # build the full file storage dir path
4613
    file_storage_dir = os.path.normpath(os.path.join(
4614
                                        self.cfg.GetFileStorageDir(),
4615
                                        string_file_storage_dir, instance))
4616

    
4617

    
4618
    disks = _GenerateDiskTemplate(self,
4619
                                  self.op.disk_template,
4620
                                  instance, pnode_name,
4621
                                  self.secondaries,
4622
                                  self.disks,
4623
                                  file_storage_dir,
4624
                                  self.op.file_driver,
4625
                                  0)
4626

    
4627
    iobj = objects.Instance(name=instance, os=self.op.os_type,
4628
                            primary_node=pnode_name,
4629
                            nics=self.nics, disks=disks,
4630
                            disk_template=self.op.disk_template,
4631
                            admin_up=False,
4632
                            network_port=network_port,
4633
                            beparams=self.op.beparams,
4634
                            hvparams=self.op.hvparams,
4635
                            hypervisor=self.op.hypervisor,
4636
                            )
4637

    
4638
    feedback_fn("* creating instance disks...")
4639
    try:
4640
      _CreateDisks(self, iobj)
4641
    except errors.OpExecError:
4642
      self.LogWarning("Device creation failed, reverting...")
4643
      try:
4644
        _RemoveDisks(self, iobj)
4645
      finally:
4646
        self.cfg.ReleaseDRBDMinors(instance)
4647
        raise
4648

    
4649
    feedback_fn("adding instance %s to cluster config" % instance)
4650

    
4651
    self.cfg.AddInstance(iobj)
4652
    # Declare that we don't want to remove the instance lock anymore, as we've
4653
    # added the instance to the config
4654
    del self.remove_locks[locking.LEVEL_INSTANCE]
4655
    # Unlock all the nodes
4656
    if self.op.mode == constants.INSTANCE_IMPORT:
4657
      nodes_keep = [self.op.src_node]
4658
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
4659
                       if node != self.op.src_node]
4660
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
4661
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
4662
    else:
4663
      self.context.glm.release(locking.LEVEL_NODE)
4664
      del self.acquired_locks[locking.LEVEL_NODE]
4665

    
4666
    if self.op.wait_for_sync:
4667
      disk_abort = not _WaitForSync(self, iobj)
4668
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
4669
      # make sure the disks are not degraded (still sync-ing is ok)
4670
      time.sleep(15)
4671
      feedback_fn("* checking mirrors status")
4672
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
4673
    else:
4674
      disk_abort = False
4675

    
4676
    if disk_abort:
4677
      _RemoveDisks(self, iobj)
4678
      self.cfg.RemoveInstance(iobj.name)
4679
      # Make sure the instance lock gets removed
4680
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
4681
      raise errors.OpExecError("There are some degraded disks for"
4682
                               " this instance")
4683

    
4684
    feedback_fn("creating os for instance %s on node %s" %
4685
                (instance, pnode_name))
4686

    
4687
    if iobj.disk_template != constants.DT_DISKLESS:
4688
      if self.op.mode == constants.INSTANCE_CREATE:
4689
        feedback_fn("* running the instance OS create scripts...")
4690
        result = self.rpc.call_instance_os_add(pnode_name, iobj)
4691
        msg = result.RemoteFailMsg()
4692
        if msg:
4693
          raise errors.OpExecError("Could not add os for instance %s"
4694
                                   " on node %s: %s" %
4695
                                   (instance, pnode_name, msg))
4696

    
4697
      elif self.op.mode == constants.INSTANCE_IMPORT:
4698
        feedback_fn("* running the instance OS import scripts...")
4699
        src_node = self.op.src_node
4700
        src_images = self.src_images
4701
        cluster_name = self.cfg.GetClusterName()
4702
        import_result = self.rpc.call_instance_os_import(pnode_name, iobj,
4703
                                                         src_node, src_images,
4704
                                                         cluster_name)
4705
        import_result.Raise()
4706
        for idx, result in enumerate(import_result.data):
4707
          if not result:
4708
            self.LogWarning("Could not import the image %s for instance"
4709
                            " %s, disk %d, on node %s" %
4710
                            (src_images[idx], instance, idx, pnode_name))
4711
      else:
4712
        # also checked in the prereq part
4713
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
4714
                                     % self.op.mode)
4715

    
4716
    if self.op.start:
4717
      iobj.admin_up = True
4718
      self.cfg.Update(iobj)
4719
      logging.info("Starting instance %s on node %s", instance, pnode_name)
4720
      feedback_fn("* starting instance...")
4721
      result = self.rpc.call_instance_start(pnode_name, iobj, None)
4722
      msg = result.RemoteFailMsg()
4723
      if msg:
4724
        raise errors.OpExecError("Could not start instance: %s" % msg)
4725

    
4726

    
4727
class LUConnectConsole(NoHooksLU):
4728
  """Connect to an instance's console.
4729

4730
  This is somewhat special in that it returns the command line that
4731
  you need to run on the master node in order to connect to the
4732
  console.
4733

4734
  """
4735
  _OP_REQP = ["instance_name"]
4736
  REQ_BGL = False
4737

    
4738
  def ExpandNames(self):
4739
    self._ExpandAndLockInstance()
4740

    
4741
  def CheckPrereq(self):
4742
    """Check prerequisites.
4743

4744
    This checks that the instance is in the cluster.
4745

4746
    """
4747
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4748
    assert self.instance is not None, \
4749
      "Cannot retrieve locked instance %s" % self.op.instance_name
4750
    _CheckNodeOnline(self, self.instance.primary_node)
4751

    
4752
  def Exec(self, feedback_fn):
4753
    """Connect to the console of an instance
4754

4755
    """
4756
    instance = self.instance
4757
    node = instance.primary_node
4758

    
4759
    node_insts = self.rpc.call_instance_list([node],
4760
                                             [instance.hypervisor])[node]
4761
    node_insts.Raise()
4762

    
4763
    if instance.name not in node_insts.data:
4764
      raise errors.OpExecError("Instance %s is not running." % instance.name)
4765

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

    
4768
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
4769
    cluster = self.cfg.GetClusterInfo()
4770
    # beparams and hvparams are passed separately, to avoid editing the
4771
    # instance and then saving the defaults in the instance itself.
4772
    hvparams = cluster.FillHV(instance)
4773
    beparams = cluster.FillBE(instance)
4774
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
4775

    
4776
    # build ssh cmdline
4777
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
4778

    
4779

    
4780
class LUReplaceDisks(LogicalUnit):
4781
  """Replace the disks of an instance.
4782

4783
  """
4784
  HPATH = "mirrors-replace"
4785
  HTYPE = constants.HTYPE_INSTANCE
4786
  _OP_REQP = ["instance_name", "mode", "disks"]
4787
  REQ_BGL = False
4788

    
4789
  def CheckArguments(self):
4790
    if not hasattr(self.op, "remote_node"):
4791
      self.op.remote_node = None
4792
    if not hasattr(self.op, "iallocator"):
4793
      self.op.iallocator = None
4794

    
4795
    # check for valid parameter combination
4796
    cnt = [self.op.remote_node, self.op.iallocator].count(None)
4797
    if self.op.mode == constants.REPLACE_DISK_CHG:
4798
      if cnt == 2:
4799
        raise errors.OpPrereqError("When changing the secondary either an"
4800
                                   " iallocator script must be used or the"
4801
                                   " new node given")
4802
      elif cnt == 0:
4803
        raise errors.OpPrereqError("Give either the iallocator or the new"
4804
                                   " secondary, not both")
4805
    else: # not replacing the secondary
4806
      if cnt != 2:
4807
        raise errors.OpPrereqError("The iallocator and new node options can"
4808
                                   " be used only when changing the"
4809
                                   " secondary node")
4810

    
4811
  def ExpandNames(self):
4812
    self._ExpandAndLockInstance()
4813

    
4814
    if self.op.iallocator is not None:
4815
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4816
    elif self.op.remote_node is not None:
4817
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
4818
      if remote_node is None:
4819
        raise errors.OpPrereqError("Node '%s' not known" %
4820
                                   self.op.remote_node)
4821
      self.op.remote_node = remote_node
4822
      # Warning: do not remove the locking of the new secondary here
4823
      # unless DRBD8.AddChildren is changed to work in parallel;
4824
      # currently it doesn't since parallel invocations of
4825
      # FindUnusedMinor will conflict
4826
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
4827
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4828
    else:
4829
      self.needed_locks[locking.LEVEL_NODE] = []
4830
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4831

    
4832
  def DeclareLocks(self, level):
4833
    # If we're not already locking all nodes in the set we have to declare the
4834
    # instance's primary/secondary nodes.
4835
    if (level == locking.LEVEL_NODE and
4836
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
4837
      self._LockInstancesNodes()
4838

    
4839
  def _RunAllocator(self):
4840
    """Compute a new secondary node using an IAllocator.
4841

4842
    """
4843
    ial = IAllocator(self,
4844
                     mode=constants.IALLOCATOR_MODE_RELOC,
4845
                     name=self.op.instance_name,
4846
                     relocate_from=[self.sec_node])
4847

    
4848
    ial.Run(self.op.iallocator)
4849

    
4850
    if not ial.success:
4851
      raise errors.OpPrereqError("Can't compute nodes using"
4852
                                 " iallocator '%s': %s" % (self.op.iallocator,
4853
                                                           ial.info))
4854
    if len(ial.nodes) != ial.required_nodes:
4855
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
4856
                                 " of nodes (%s), required %s" %
4857
                                 (len(ial.nodes), ial.required_nodes))
4858
    self.op.remote_node = ial.nodes[0]
4859
    self.LogInfo("Selected new secondary for the instance: %s",
4860
                 self.op.remote_node)
4861

    
4862
  def BuildHooksEnv(self):
4863
    """Build hooks env.
4864

4865
    This runs on the master, the primary and all the secondaries.
4866

4867
    """
4868
    env = {
4869
      "MODE": self.op.mode,
4870
      "NEW_SECONDARY": self.op.remote_node,
4871
      "OLD_SECONDARY": self.instance.secondary_nodes[0],
4872
      }
4873
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4874
    nl = [
4875
      self.cfg.GetMasterNode(),
4876
      self.instance.primary_node,
4877
      ]
4878
    if self.op.remote_node is not None:
4879
      nl.append(self.op.remote_node)
4880
    return env, nl, nl
4881

    
4882
  def CheckPrereq(self):
4883
    """Check prerequisites.
4884

4885
    This checks that the instance is in the cluster.
4886

4887
    """
4888
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4889
    assert instance is not None, \
4890
      "Cannot retrieve locked instance %s" % self.op.instance_name
4891
    self.instance = instance
4892

    
4893
    if instance.disk_template != constants.DT_DRBD8:
4894
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
4895
                                 " instances")
4896

    
4897
    if len(instance.secondary_nodes) != 1:
4898
      raise errors.OpPrereqError("The instance has a strange layout,"
4899
                                 " expected one secondary but found %d" %
4900
                                 len(instance.secondary_nodes))
4901

    
4902
    self.sec_node = instance.secondary_nodes[0]
4903

    
4904
    if self.op.iallocator is not None:
4905
      self._RunAllocator()
4906

    
4907
    remote_node = self.op.remote_node
4908
    if remote_node is not None:
4909
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
4910
      assert self.remote_node_info is not None, \
4911
        "Cannot retrieve locked node %s" % remote_node
4912
    else:
4913
      self.remote_node_info = None
4914
    if remote_node == instance.primary_node:
4915
      raise errors.OpPrereqError("The specified node is the primary node of"
4916
                                 " the instance.")
4917
    elif remote_node == self.sec_node:
4918
      raise errors.OpPrereqError("The specified node is already the"
4919
                                 " secondary node of the instance.")
4920

    
4921
    if self.op.mode == constants.REPLACE_DISK_PRI:
4922
      n1 = self.tgt_node = instance.primary_node
4923
      n2 = self.oth_node = self.sec_node
4924
    elif self.op.mode == constants.REPLACE_DISK_SEC:
4925
      n1 = self.tgt_node = self.sec_node
4926
      n2 = self.oth_node = instance.primary_node
4927
    elif self.op.mode == constants.REPLACE_DISK_CHG:
4928
      n1 = self.new_node = remote_node
4929
      n2 = self.oth_node = instance.primary_node
4930
      self.tgt_node = self.sec_node
4931
      _CheckNodeNotDrained(self, remote_node)
4932
    else:
4933
      raise errors.ProgrammerError("Unhandled disk replace mode")
4934

    
4935
    _CheckNodeOnline(self, n1)
4936
    _CheckNodeOnline(self, n2)
4937

    
4938
    if not self.op.disks:
4939
      self.op.disks = range(len(instance.disks))
4940

    
4941
    for disk_idx in self.op.disks:
4942
      instance.FindDisk(disk_idx)
4943

    
4944
  def _ExecD8DiskOnly(self, feedback_fn):
4945
    """Replace a disk on the primary or secondary for dbrd8.
4946

4947
    The algorithm for replace is quite complicated:
4948

4949
      1. for each disk to be replaced:
4950

4951
        1. create new LVs on the target node with unique names
4952
        1. detach old LVs from the drbd device
4953
        1. rename old LVs to name_replaced.<time_t>
4954
        1. rename new LVs to old LVs
4955
        1. attach the new LVs (with the old names now) to the drbd device
4956

4957
      1. wait for sync across all devices
4958

4959
      1. for each modified disk:
4960

4961
        1. remove old LVs (which have the name name_replaces.<time_t>)
4962

4963
    Failures are not very well handled.
4964

4965
    """
4966
    steps_total = 6
4967
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
4968
    instance = self.instance
4969
    iv_names = {}
4970
    vgname = self.cfg.GetVGName()
4971
    # start of work
4972
    cfg = self.cfg
4973
    tgt_node = self.tgt_node
4974
    oth_node = self.oth_node
4975

    
4976
    # Step: check device activation
4977
    self.proc.LogStep(1, steps_total, "check device existence")
4978
    info("checking volume groups")
4979
    my_vg = cfg.GetVGName()
4980
    results = self.rpc.call_vg_list([oth_node, tgt_node])
4981
    if not results:
4982
      raise errors.OpExecError("Can't list volume groups on the nodes")
4983
    for node in oth_node, tgt_node:
4984
      res = results[node]
4985
      if res.failed or not res.data or my_vg not in res.data:
4986
        raise errors.OpExecError("Volume group '%s' not found on %s" %
4987
                                 (my_vg, node))
4988
    for idx, dev in enumerate(instance.disks):
4989
      if idx not in self.op.disks:
4990
        continue
4991
      for node in tgt_node, oth_node:
4992
        info("checking disk/%d on %s" % (idx, node))
4993
        cfg.SetDiskID(dev, node)
4994
        result = self.rpc.call_blockdev_find(node, dev)
4995
        msg = result.RemoteFailMsg()
4996
        if not msg and not result.payload:
4997
          msg = "disk not found"
4998
        if msg:
4999
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
5000
                                   (idx, node, msg))
5001

    
5002
    # Step: check other node consistency
5003
    self.proc.LogStep(2, steps_total, "check peer consistency")
5004
    for idx, dev in enumerate(instance.disks):
5005
      if idx not in self.op.disks:
5006
        continue
5007
      info("checking disk/%d consistency on %s" % (idx, oth_node))
5008
      if not _CheckDiskConsistency(self, dev, oth_node,
5009
                                   oth_node==instance.primary_node):
5010
        raise errors.OpExecError("Peer node (%s) has degraded storage, unsafe"
5011
                                 " to replace disks on this node (%s)" %
5012
                                 (oth_node, tgt_node))
5013

    
5014
    # Step: create new storage
5015
    self.proc.LogStep(3, steps_total, "allocate new storage")
5016
    for idx, dev in enumerate(instance.disks):
5017
      if idx not in self.op.disks:
5018
        continue
5019
      size = dev.size
5020
      cfg.SetDiskID(dev, tgt_node)
5021
      lv_names = [".disk%d_%s" % (idx, suf)
5022
                  for suf in ["data", "meta"]]
5023
      names = _GenerateUniqueNames(self, lv_names)
5024
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=size,
5025
                             logical_id=(vgname, names[0]))
5026
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
5027
                             logical_id=(vgname, names[1]))
5028
      new_lvs = [lv_data, lv_meta]
5029
      old_lvs = dev.children
5030
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
5031
      info("creating new local storage on %s for %s" %
5032
           (tgt_node, dev.iv_name))
5033
      # we pass force_create=True to force the LVM creation
5034
      for new_lv in new_lvs:
5035
        _CreateBlockDev(self, tgt_node, instance, new_lv, True,
5036
                        _GetInstanceInfoText(instance), False)
5037

    
5038
    # Step: for each lv, detach+rename*2+attach
5039
    self.proc.LogStep(4, steps_total, "change drbd configuration")
5040
    for dev, old_lvs, new_lvs in iv_names.itervalues():
5041
      info("detaching %s drbd from local storage" % dev.iv_name)
5042
      result = self.rpc.call_blockdev_removechildren(tgt_node, dev, old_lvs)
5043
      result.Raise()
5044
      if not result.data:
5045
        raise errors.OpExecError("Can't detach drbd from local storage on node"
5046
                                 " %s for device %s" % (tgt_node, dev.iv_name))
5047
      #dev.children = []
5048
      #cfg.Update(instance)
5049

    
5050
      # ok, we created the new LVs, so now we know we have the needed
5051
      # storage; as such, we proceed on the target node to rename
5052
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
5053
      # using the assumption that logical_id == physical_id (which in
5054
      # turn is the unique_id on that node)
5055

    
5056
      # FIXME(iustin): use a better name for the replaced LVs
5057
      temp_suffix = int(time.time())
5058
      ren_fn = lambda d, suff: (d.physical_id[0],
5059
                                d.physical_id[1] + "_replaced-%s" % suff)
5060
      # build the rename list based on what LVs exist on the node
5061
      rlist = []
5062
      for to_ren in old_lvs:
5063
        result = self.rpc.call_blockdev_find(tgt_node, to_ren)
5064
        if not result.RemoteFailMsg() and result.payload:
5065
          # device exists
5066
          rlist.append((to_ren, ren_fn(to_ren, temp_suffix)))
5067

    
5068
      info("renaming the old LVs on the target node")
5069
      result = self.rpc.call_blockdev_rename(tgt_node, rlist)
5070
      result.Raise()
5071
      if not result.data:
5072
        raise errors.OpExecError("Can't rename old LVs on node %s" % tgt_node)
5073
      # now we rename the new LVs to the old LVs
5074
      info("renaming the new LVs on the target node")
5075
      rlist = [(new, old.physical_id) for old, new in zip(old_lvs, new_lvs)]
5076
      result = self.rpc.call_blockdev_rename(tgt_node, rlist)
5077
      result.Raise()
5078
      if not result.data:
5079
        raise errors.OpExecError("Can't rename new LVs on node %s" % tgt_node)
5080

    
5081
      for old, new in zip(old_lvs, new_lvs):
5082
        new.logical_id = old.logical_id
5083
        cfg.SetDiskID(new, tgt_node)
5084

    
5085
      for disk in old_lvs:
5086
        disk.logical_id = ren_fn(disk, temp_suffix)
5087
        cfg.SetDiskID(disk, tgt_node)
5088

    
5089
      # now that the new lvs have the old name, we can add them to the device
5090
      info("adding new mirror component on %s" % tgt_node)
5091
      result = self.rpc.call_blockdev_addchildren(tgt_node, dev, new_lvs)
5092
      if result.failed or not result.data:
5093
        for new_lv in new_lvs:
5094
          msg = self.rpc.call_blockdev_remove(tgt_node, new_lv).RemoteFailMsg()
5095
          if msg:
5096
            warning("Can't rollback device %s: %s", dev, msg,
5097
                    hint="cleanup manually the unused logical volumes")
5098
        raise errors.OpExecError("Can't add local storage to drbd")
5099

    
5100
      dev.children = new_lvs
5101
      cfg.Update(instance)
5102

    
5103
    # Step: wait for sync
5104

    
5105
    # this can fail as the old devices are degraded and _WaitForSync
5106
    # does a combined result over all disks, so we don't check its
5107
    # return value
5108
    self.proc.LogStep(5, steps_total, "sync devices")
5109
    _WaitForSync(self, instance, unlock=True)
5110

    
5111
    # so check manually all the devices
5112
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
5113
      cfg.SetDiskID(dev, instance.primary_node)
5114
      result = self.rpc.call_blockdev_find(instance.primary_node, dev)
5115
      msg = result.RemoteFailMsg()
5116
      if not msg and not result.payload:
5117
        msg = "disk not found"
5118
      if msg:
5119
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
5120
                                 (name, msg))
5121
      if result.payload[5]:
5122
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
5123

    
5124
    # Step: remove old storage
5125
    self.proc.LogStep(6, steps_total, "removing old storage")
5126
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
5127
      info("remove logical volumes for %s" % name)
5128
      for lv in old_lvs:
5129
        cfg.SetDiskID(lv, tgt_node)
5130
        msg = self.rpc.call_blockdev_remove(tgt_node, lv).RemoteFailMsg()
5131
        if msg:
5132
          warning("Can't remove old LV: %s" % msg,
5133
                  hint="manually remove unused LVs")
5134
          continue
5135

    
5136
  def _ExecD8Secondary(self, feedback_fn):
5137
    """Replace the secondary node for drbd8.
5138

5139
    The algorithm for replace is quite complicated:
5140
      - for all disks of the instance:
5141
        - create new LVs on the new node with same names
5142
        - shutdown the drbd device on the old secondary
5143
        - disconnect the drbd network on the primary
5144
        - create the drbd device on the new secondary
5145
        - network attach the drbd on the primary, using an artifice:
5146
          the drbd code for Attach() will connect to the network if it
5147
          finds a device which is connected to the good local disks but
5148
          not network enabled
5149
      - wait for sync across all devices
5150
      - remove all disks from the old secondary
5151

5152
    Failures are not very well handled.
5153

5154
    """
5155
    steps_total = 6
5156
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
5157
    instance = self.instance
5158
    iv_names = {}
5159
    # start of work
5160
    cfg = self.cfg
5161
    old_node = self.tgt_node
5162
    new_node = self.new_node
5163
    pri_node = instance.primary_node
5164
    nodes_ip = {
5165
      old_node: self.cfg.GetNodeInfo(old_node).secondary_ip,
5166
      new_node: self.cfg.GetNodeInfo(new_node).secondary_ip,
5167
      pri_node: self.cfg.GetNodeInfo(pri_node).secondary_ip,
5168
      }
5169

    
5170
    # Step: check device activation
5171
    self.proc.LogStep(1, steps_total, "check device existence")
5172
    info("checking volume groups")
5173
    my_vg = cfg.GetVGName()
5174
    results = self.rpc.call_vg_list([pri_node, new_node])
5175
    for node in pri_node, new_node:
5176
      res = results[node]
5177
      if res.failed or not res.data or my_vg not in res.data:
5178
        raise errors.OpExecError("Volume group '%s' not found on %s" %
5179
                                 (my_vg, node))
5180
    for idx, dev in enumerate(instance.disks):
5181
      if idx not in self.op.disks:
5182
        continue
5183
      info("checking disk/%d on %s" % (idx, pri_node))
5184
      cfg.SetDiskID(dev, pri_node)
5185
      result = self.rpc.call_blockdev_find(pri_node, dev)
5186
      msg = result.RemoteFailMsg()
5187
      if not msg and not result.payload:
5188
        msg = "disk not found"
5189
      if msg:
5190
        raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
5191
                                 (idx, pri_node, msg))
5192

    
5193
    # Step: check other node consistency
5194
    self.proc.LogStep(2, steps_total, "check peer consistency")
5195
    for idx, dev in enumerate(instance.disks):
5196
      if idx not in self.op.disks:
5197
        continue
5198
      info("checking disk/%d consistency on %s" % (idx, pri_node))
5199
      if not _CheckDiskConsistency(self, dev, pri_node, True, ldisk=True):
5200
        raise errors.OpExecError("Primary node (%s) has degraded storage,"
5201
                                 " unsafe to replace the secondary" %
5202
                                 pri_node)
5203

    
5204
    # Step: create new storage
5205
    self.proc.LogStep(3, steps_total, "allocate new storage")
5206
    for idx, dev in enumerate(instance.disks):
5207
      info("adding new local storage on %s for disk/%d" %
5208
           (new_node, idx))
5209
      # we pass force_create=True to force LVM creation
5210
      for new_lv in dev.children:
5211
        _CreateBlockDev(self, new_node, instance, new_lv, True,
5212
                        _GetInstanceInfoText(instance), False)
5213

    
5214
    # Step 4: dbrd minors and drbd setups changes
5215
    # after this, we must manually remove the drbd minors on both the
5216
    # error and the success paths
5217
    minors = cfg.AllocateDRBDMinor([new_node for dev in instance.disks],
5218
                                   instance.name)
5219
    logging.debug("Allocated minors %s" % (minors,))
5220
    self.proc.LogStep(4, steps_total, "changing drbd configuration")
5221
    for idx, (dev, new_minor) in enumerate(zip(instance.disks, minors)):
5222
      size = dev.size
5223
      info("activating a new drbd on %s for disk/%d" % (new_node, idx))
5224
      # create new devices on new_node; note that we create two IDs:
5225
      # one without port, so the drbd will be activated without
5226
      # networking information on the new node at this stage, and one
5227
      # with network, for the latter activation in step 4
5228
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
5229
      if pri_node == o_node1:
5230
        p_minor = o_minor1
5231
      else:
5232
        p_minor = o_minor2
5233

    
5234
      new_alone_id = (pri_node, new_node, None, p_minor, new_minor, o_secret)
5235
      new_net_id = (pri_node, new_node, o_port, p_minor, new_minor, o_secret)
5236

    
5237
      iv_names[idx] = (dev, dev.children, new_net_id)
5238
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
5239
                    new_net_id)
5240
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
5241
                              logical_id=new_alone_id,
5242
                              children=dev.children)
5243
      try:
5244
        _CreateSingleBlockDev(self, new_node, instance, new_drbd,
5245
                              _GetInstanceInfoText(instance), False)
5246
      except errors.BlockDeviceError:
5247
        self.cfg.ReleaseDRBDMinors(instance.name)
5248
        raise
5249

    
5250
    for idx, dev in enumerate(instance.disks):
5251
      # we have new devices, shutdown the drbd on the old secondary
5252
      info("shutting down drbd for disk/%d on old node" % idx)
5253
      cfg.SetDiskID(dev, old_node)
5254
      msg = self.rpc.call_blockdev_shutdown(old_node, dev).RemoteFailMsg()
5255
      if msg:
5256
        warning("Failed to shutdown drbd for disk/%d on old node: %s" %
5257
                (idx, msg),
5258
                hint="Please cleanup this device manually as soon as possible")
5259

    
5260
    info("detaching primary drbds from the network (=> standalone)")
5261
    result = self.rpc.call_drbd_disconnect_net([pri_node], nodes_ip,
5262
                                               instance.disks)[pri_node]
5263

    
5264
    msg = result.RemoteFailMsg()
5265
    if msg:
5266
      # detaches didn't succeed (unlikely)
5267
      self.cfg.ReleaseDRBDMinors(instance.name)
5268
      raise errors.OpExecError("Can't detach the disks from the network on"
5269
                               " old node: %s" % (msg,))
5270

    
5271
    # if we managed to detach at least one, we update all the disks of
5272
    # the instance to point to the new secondary
5273
    info("updating instance configuration")
5274
    for dev, _, new_logical_id in iv_names.itervalues():
5275
      dev.logical_id = new_logical_id
5276
      cfg.SetDiskID(dev, pri_node)
5277
    cfg.Update(instance)
5278

    
5279
    # and now perform the drbd attach
5280
    info("attaching primary drbds to new secondary (standalone => connected)")
5281
    result = self.rpc.call_drbd_attach_net([pri_node, new_node], nodes_ip,
5282
                                           instance.disks, instance.name,
5283
                                           False)
5284
    for to_node, to_result in result.items():
5285
      msg = to_result.RemoteFailMsg()
5286
      if msg:
5287
        warning("can't attach drbd disks on node %s: %s", to_node, msg,
5288
                hint="please do a gnt-instance info to see the"
5289
                " status of disks")
5290

    
5291
    # this can fail as the old devices are degraded and _WaitForSync
5292
    # does a combined result over all disks, so we don't check its
5293
    # return value
5294
    self.proc.LogStep(5, steps_total, "sync devices")
5295
    _WaitForSync(self, instance, unlock=True)
5296

    
5297
    # so check manually all the devices
5298
    for idx, (dev, old_lvs, _) in iv_names.iteritems():
5299
      cfg.SetDiskID(dev, pri_node)
5300
      result = self.rpc.call_blockdev_find(pri_node, dev)
5301
      msg = result.RemoteFailMsg()
5302
      if not msg and not result.payload:
5303
        msg = "disk not found"
5304
      if msg:
5305
        raise errors.OpExecError("Can't find DRBD device disk/%d: %s" %
5306
                                 (idx, msg))
5307
      if result.payload[5]:
5308
        raise errors.OpExecError("DRBD device disk/%d is degraded!" % idx)
5309

    
5310
    self.proc.LogStep(6, steps_total, "removing old storage")
5311
    for idx, (dev, old_lvs, _) in iv_names.iteritems():
5312
      info("remove logical volumes for disk/%d" % idx)
5313
      for lv in old_lvs:
5314
        cfg.SetDiskID(lv, old_node)
5315
        msg = self.rpc.call_blockdev_remove(old_node, lv).RemoteFailMsg()
5316
        if msg:
5317
          warning("Can't remove LV on old secondary: %s", msg,
5318
                  hint="Cleanup stale volumes by hand")
5319

    
5320
  def Exec(self, feedback_fn):
5321
    """Execute disk replacement.
5322

5323
    This dispatches the disk replacement to the appropriate handler.
5324

5325
    """
5326
    instance = self.instance
5327

    
5328
    # Activate the instance disks if we're replacing them on a down instance
5329
    if not instance.admin_up:
5330
      _StartInstanceDisks(self, instance, True)
5331

    
5332
    if self.op.mode == constants.REPLACE_DISK_CHG:
5333
      fn = self._ExecD8Secondary
5334
    else:
5335
      fn = self._ExecD8DiskOnly
5336

    
5337
    ret = fn(feedback_fn)
5338

    
5339
    # Deactivate the instance disks if we're replacing them on a down instance
5340
    if not instance.admin_up:
5341
      _SafeShutdownInstanceDisks(self, instance)
5342

    
5343
    return ret
5344

    
5345

    
5346
class LUGrowDisk(LogicalUnit):
5347
  """Grow a disk of an instance.
5348

5349
  """
5350
  HPATH = "disk-grow"
5351
  HTYPE = constants.HTYPE_INSTANCE
5352
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
5353
  REQ_BGL = False
5354

    
5355
  def ExpandNames(self):
5356
    self._ExpandAndLockInstance()
5357
    self.needed_locks[locking.LEVEL_NODE] = []
5358
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5359

    
5360
  def DeclareLocks(self, level):
5361
    if level == locking.LEVEL_NODE:
5362
      self._LockInstancesNodes()
5363

    
5364
  def BuildHooksEnv(self):
5365
    """Build hooks env.
5366

5367
    This runs on the master, the primary and all the secondaries.
5368

5369
    """
5370
    env = {
5371
      "DISK": self.op.disk,
5372
      "AMOUNT": self.op.amount,
5373
      }
5374
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5375
    nl = [
5376
      self.cfg.GetMasterNode(),
5377
      self.instance.primary_node,
5378
      ]
5379
    return env, nl, nl
5380

    
5381
  def CheckPrereq(self):
5382
    """Check prerequisites.
5383

5384
    This checks that the instance is in the cluster.
5385

5386
    """
5387
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5388
    assert instance is not None, \
5389
      "Cannot retrieve locked instance %s" % self.op.instance_name
5390
    nodenames = list(instance.all_nodes)
5391
    for node in nodenames:
5392
      _CheckNodeOnline(self, node)
5393

    
5394

    
5395
    self.instance = instance
5396

    
5397
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
5398
      raise errors.OpPrereqError("Instance's disk layout does not support"
5399
                                 " growing.")
5400

    
5401
    self.disk = instance.FindDisk(self.op.disk)
5402

    
5403
    nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
5404
                                       instance.hypervisor)
5405
    for node in nodenames:
5406
      info = nodeinfo[node]
5407
      if info.failed or not info.data:
5408
        raise errors.OpPrereqError("Cannot get current information"
5409
                                   " from node '%s'" % node)
5410
      vg_free = info.data.get('vg_free', None)
5411
      if not isinstance(vg_free, int):
5412
        raise errors.OpPrereqError("Can't compute free disk space on"
5413
                                   " node %s" % node)
5414
      if self.op.amount > vg_free:
5415
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
5416
                                   " %d MiB available, %d MiB required" %
5417
                                   (node, vg_free, self.op.amount))
5418

    
5419
  def Exec(self, feedback_fn):
5420
    """Execute disk grow.
5421

5422
    """
5423
    instance = self.instance
5424
    disk = self.disk
5425
    for node in instance.all_nodes:
5426
      self.cfg.SetDiskID(disk, node)
5427
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
5428
      msg = result.RemoteFailMsg()
5429
      if msg:
5430
        raise errors.OpExecError("Grow request failed to node %s: %s" %
5431
                                 (node, msg))
5432
    disk.RecordGrow(self.op.amount)
5433
    self.cfg.Update(instance)
5434
    if self.op.wait_for_sync:
5435
      disk_abort = not _WaitForSync(self, instance)
5436
      if disk_abort:
5437
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
5438
                             " status.\nPlease check the instance.")
5439

    
5440

    
5441
class LUQueryInstanceData(NoHooksLU):
5442
  """Query runtime instance data.
5443

5444
  """
5445
  _OP_REQP = ["instances", "static"]
5446
  REQ_BGL = False
5447

    
5448
  def ExpandNames(self):
5449
    self.needed_locks = {}
5450
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
5451

    
5452
    if not isinstance(self.op.instances, list):
5453
      raise errors.OpPrereqError("Invalid argument type 'instances'")
5454

    
5455
    if self.op.instances:
5456
      self.wanted_names = []
5457
      for name in self.op.instances:
5458
        full_name = self.cfg.ExpandInstanceName(name)
5459
        if full_name is None:
5460
          raise errors.OpPrereqError("Instance '%s' not known" % name)
5461
        self.wanted_names.append(full_name)
5462
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
5463
    else:
5464
      self.wanted_names = None
5465
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
5466

    
5467
    self.needed_locks[locking.LEVEL_NODE] = []
5468
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5469

    
5470
  def DeclareLocks(self, level):
5471
    if level == locking.LEVEL_NODE:
5472
      self._LockInstancesNodes()
5473

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

5477
    This only checks the optional instance list against the existing names.
5478

5479
    """
5480
    if self.wanted_names is None:
5481
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5482

    
5483
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
5484
                             in self.wanted_names]
5485
    return
5486

    
5487
  def _ComputeDiskStatus(self, instance, snode, dev):
5488
    """Compute block device status.
5489

5490
    """
5491
    static = self.op.static
5492
    if not static:
5493
      self.cfg.SetDiskID(dev, instance.primary_node)
5494
      dev_pstatus = self.rpc.call_blockdev_find(instance.primary_node, dev)
5495
      msg = dev_pstatus.RemoteFailMsg()
5496
      if msg:
5497
        raise errors.OpExecError("Can't compute disk status for %s: %s" %
5498
                                 (instance.name, msg))
5499
      dev_pstatus = dev_pstatus.payload
5500
    else:
5501
      dev_pstatus = None
5502

    
5503
    if dev.dev_type in constants.LDS_DRBD:
5504
      # we change the snode then (otherwise we use the one passed in)
5505
      if dev.logical_id[0] == instance.primary_node:
5506
        snode = dev.logical_id[1]
5507
      else:
5508
        snode = dev.logical_id[0]
5509

    
5510
    if snode and not static:
5511
      self.cfg.SetDiskID(dev, snode)
5512
      dev_sstatus = self.rpc.call_blockdev_find(snode, dev)
5513
      msg = dev_sstatus.RemoteFailMsg()
5514
      if msg:
5515
        raise errors.OpExecError("Can't compute disk status for %s: %s" %
5516
                                 (instance.name, msg))
5517
      dev_sstatus = dev_sstatus.payload
5518
    else:
5519
      dev_sstatus = None
5520

    
5521
    if dev.children:
5522
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
5523
                      for child in dev.children]
5524
    else:
5525
      dev_children = []
5526

    
5527
    data = {
5528
      "iv_name": dev.iv_name,
5529
      "dev_type": dev.dev_type,
5530
      "logical_id": dev.logical_id,
5531
      "physical_id": dev.physical_id,
5532
      "pstatus": dev_pstatus,
5533
      "sstatus": dev_sstatus,
5534
      "children": dev_children,
5535
      "mode": dev.mode,
5536
      }
5537

    
5538
    return data
5539

    
5540
  def Exec(self, feedback_fn):
5541
    """Gather and return data"""
5542
    result = {}
5543

    
5544
    cluster = self.cfg.GetClusterInfo()
5545

    
5546
    for instance in self.wanted_instances:
5547
      if not self.op.static:
5548
        remote_info = self.rpc.call_instance_info(instance.primary_node,
5549
                                                  instance.name,
5550
                                                  instance.hypervisor)
5551
        remote_info.Raise()
5552
        remote_info = remote_info.data
5553
        if remote_info and "state" in remote_info:
5554
          remote_state = "up"
5555
        else:
5556
          remote_state = "down"
5557
      else:
5558
        remote_state = None
5559
      if instance.admin_up:
5560
        config_state = "up"
5561
      else:
5562
        config_state = "down"
5563

    
5564
      disks = [self._ComputeDiskStatus(instance, None, device)
5565
               for device in instance.disks]
5566

    
5567
      idict = {
5568
        "name": instance.name,
5569
        "config_state": config_state,
5570
        "run_state": remote_state,
5571
        "pnode": instance.primary_node,
5572
        "snodes": instance.secondary_nodes,
5573
        "os": instance.os,
5574
        "nics": [(nic.mac, nic.ip, nic.bridge) for nic in instance.nics],
5575
        "disks": disks,
5576
        "hypervisor": instance.hypervisor,
5577
        "network_port": instance.network_port,
5578
        "hv_instance": instance.hvparams,
5579
        "hv_actual": cluster.FillHV(instance),
5580
        "be_instance": instance.beparams,
5581
        "be_actual": cluster.FillBE(instance),
5582
        }
5583

    
5584
      result[instance.name] = idict
5585

    
5586
    return result
5587

    
5588

    
5589
class LUSetInstanceParams(LogicalUnit):
5590
  """Modifies an instances's parameters.
5591

5592
  """
5593
  HPATH = "instance-modify"
5594
  HTYPE = constants.HTYPE_INSTANCE
5595
  _OP_REQP = ["instance_name"]
5596
  REQ_BGL = False
5597

    
5598
  def CheckArguments(self):
5599
    if not hasattr(self.op, 'nics'):
5600
      self.op.nics = []
5601
    if not hasattr(self.op, 'disks'):
5602
      self.op.disks = []
5603
    if not hasattr(self.op, 'beparams'):
5604
      self.op.beparams = {}
5605
    if not hasattr(self.op, 'hvparams'):
5606
      self.op.hvparams = {}
5607
    self.op.force = getattr(self.op, "force", False)
5608
    if not (self.op.nics or self.op.disks or
5609
            self.op.hvparams or self.op.beparams):
5610
      raise errors.OpPrereqError("No changes submitted")
5611

    
5612
    # Disk validation
5613
    disk_addremove = 0
5614
    for disk_op, disk_dict in self.op.disks:
5615
      if disk_op == constants.DDM_REMOVE:
5616
        disk_addremove += 1
5617
        continue
5618
      elif disk_op == constants.DDM_ADD:
5619
        disk_addremove += 1
5620
      else:
5621
        if not isinstance(disk_op, int):
5622
          raise errors.OpPrereqError("Invalid disk index")
5623
      if disk_op == constants.DDM_ADD:
5624
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
5625
        if mode not in constants.DISK_ACCESS_SET:
5626
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode)
5627
        size = disk_dict.get('size', None)
5628
        if size is None:
5629
          raise errors.OpPrereqError("Required disk parameter size missing")
5630
        try:
5631
          size = int(size)
5632
        except ValueError, err:
5633
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
5634
                                     str(err))
5635
        disk_dict['size'] = size
5636
      else:
5637
        # modification of disk
5638
        if 'size' in disk_dict:
5639
          raise errors.OpPrereqError("Disk size change not possible, use"
5640
                                     " grow-disk")
5641

    
5642
    if disk_addremove > 1:
5643
      raise errors.OpPrereqError("Only one disk add or remove operation"
5644
                                 " supported at a time")
5645

    
5646
    # NIC validation
5647
    nic_addremove = 0
5648
    for nic_op, nic_dict in self.op.nics:
5649
      if nic_op == constants.DDM_REMOVE:
5650
        nic_addremove += 1
5651
        continue
5652
      elif nic_op == constants.DDM_ADD:
5653
        nic_addremove += 1
5654
      else:
5655
        if not isinstance(nic_op, int):
5656
          raise errors.OpPrereqError("Invalid nic index")
5657

    
5658
      # nic_dict should be a dict
5659
      nic_ip = nic_dict.get('ip', None)
5660
      if nic_ip is not None:
5661
        if nic_ip.lower() == "none":
5662
          nic_dict['ip'] = None
5663
        else:
5664
          if not utils.IsValidIP(nic_ip):
5665
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip)
5666
      # we can only check None bridges and assign the default one
5667
      nic_bridge = nic_dict.get('bridge', None)
5668
      if nic_bridge is None:
5669
        nic_dict['bridge'] = self.cfg.GetDefBridge()
5670
      # but we can validate MACs
5671
      nic_mac = nic_dict.get('mac', None)
5672
      if nic_mac is not None:
5673
        if self.cfg.IsMacInUse(nic_mac):
5674
          raise errors.OpPrereqError("MAC address %s already in use"
5675
                                     " in cluster" % nic_mac)
5676
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5677
          if not utils.IsValidMac(nic_mac):
5678
            raise errors.OpPrereqError("Invalid MAC address %s" % nic_mac)
5679
    if nic_addremove > 1:
5680
      raise errors.OpPrereqError("Only one NIC add or remove operation"
5681
                                 " supported at a time")
5682

    
5683
  def ExpandNames(self):
5684
    self._ExpandAndLockInstance()
5685
    self.needed_locks[locking.LEVEL_NODE] = []
5686
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5687

    
5688
  def DeclareLocks(self, level):
5689
    if level == locking.LEVEL_NODE:
5690
      self._LockInstancesNodes()
5691

    
5692
  def BuildHooksEnv(self):
5693
    """Build hooks env.
5694

5695
    This runs on the master, primary and secondaries.
5696

5697
    """
5698
    args = dict()
5699
    if constants.BE_MEMORY in self.be_new:
5700
      args['memory'] = self.be_new[constants.BE_MEMORY]
5701
    if constants.BE_VCPUS in self.be_new:
5702
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
5703
    # FIXME: readd disk/nic changes
5704
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
5705
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5706
    return env, nl, nl
5707

    
5708
  def CheckPrereq(self):
5709
    """Check prerequisites.
5710

5711
    This only checks the instance list against the existing names.
5712

5713
    """
5714
    force = self.force = self.op.force
5715

    
5716
    # checking the new params on the primary/secondary nodes
5717

    
5718
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5719
    assert self.instance is not None, \
5720
      "Cannot retrieve locked instance %s" % self.op.instance_name
5721
    pnode = instance.primary_node
5722
    nodelist = list(instance.all_nodes)
5723

    
5724
    # hvparams processing
5725
    if self.op.hvparams:
5726
      i_hvdict = copy.deepcopy(instance.hvparams)
5727
      for key, val in self.op.hvparams.iteritems():
5728
        if val == constants.VALUE_DEFAULT:
5729
          try:
5730
            del i_hvdict[key]
5731
          except KeyError:
5732
            pass
5733
        else:
5734
          i_hvdict[key] = val
5735
      cluster = self.cfg.GetClusterInfo()
5736
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
5737
      hv_new = cluster.FillDict(cluster.hvparams[instance.hypervisor],
5738
                                i_hvdict)
5739
      # local check
5740
      hypervisor.GetHypervisor(
5741
        instance.hypervisor).CheckParameterSyntax(hv_new)
5742
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
5743
      self.hv_new = hv_new # the new actual values
5744
      self.hv_inst = i_hvdict # the new dict (without defaults)
5745
    else:
5746
      self.hv_new = self.hv_inst = {}
5747

    
5748
    # beparams processing
5749
    if self.op.beparams:
5750
      i_bedict = copy.deepcopy(instance.beparams)
5751
      for key, val in self.op.beparams.iteritems():
5752
        if val == constants.VALUE_DEFAULT:
5753
          try:
5754
            del i_bedict[key]
5755
          except KeyError:
5756
            pass
5757
        else:
5758
          i_bedict[key] = val
5759
      cluster = self.cfg.GetClusterInfo()
5760
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
5761
      be_new = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
5762
                                i_bedict)
5763
      self.be_new = be_new # the new actual values
5764
      self.be_inst = i_bedict # the new dict (without defaults)
5765
    else:
5766
      self.be_new = self.be_inst = {}
5767

    
5768
    self.warn = []
5769

    
5770
    if constants.BE_MEMORY in self.op.beparams and not self.force:
5771
      mem_check_list = [pnode]
5772
      if be_new[constants.BE_AUTO_BALANCE]:
5773
        # either we changed auto_balance to yes or it was from before
5774
        mem_check_list.extend(instance.secondary_nodes)
5775
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
5776
                                                  instance.hypervisor)
5777
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
5778
                                         instance.hypervisor)
5779
      if nodeinfo[pnode].failed or not isinstance(nodeinfo[pnode].data, dict):
5780
        # Assume the primary node is unreachable and go ahead
5781
        self.warn.append("Can't get info from primary node %s" % pnode)
5782
      else:
5783
        if not instance_info.failed and instance_info.data:
5784
          current_mem = instance_info.data['memory']
5785
        else:
5786
          # Assume instance not running
5787
          # (there is a slight race condition here, but it's not very probable,
5788
          # and we have no other way to check)
5789
          current_mem = 0
5790
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
5791
                    nodeinfo[pnode].data['memory_free'])
5792
        if miss_mem > 0:
5793
          raise errors.OpPrereqError("This change will prevent the instance"
5794
                                     " from starting, due to %d MB of memory"
5795
                                     " missing on its primary node" % miss_mem)
5796

    
5797
      if be_new[constants.BE_AUTO_BALANCE]:
5798
        for node, nres in nodeinfo.iteritems():
5799
          if node not in instance.secondary_nodes:
5800
            continue
5801
          if nres.failed or not isinstance(nres.data, dict):
5802
            self.warn.append("Can't get info from secondary node %s" % node)
5803
          elif be_new[constants.BE_MEMORY] > nres.data['memory_free']:
5804
            self.warn.append("Not enough memory to failover instance to"
5805
                             " secondary node %s" % node)
5806

    
5807
    # NIC processing
5808
    for nic_op, nic_dict in self.op.nics:
5809
      if nic_op == constants.DDM_REMOVE:
5810
        if not instance.nics:
5811
          raise errors.OpPrereqError("Instance has no NICs, cannot remove")
5812
        continue
5813
      if nic_op != constants.DDM_ADD:
5814
        # an existing nic
5815
        if nic_op < 0 or nic_op >= len(instance.nics):
5816
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
5817
                                     " are 0 to %d" %
5818
                                     (nic_op, len(instance.nics)))
5819
      nic_bridge = nic_dict.get('bridge', None)
5820
      if nic_bridge is not None:
5821
        if not self.rpc.call_bridges_exist(pnode, [nic_bridge]):
5822
          msg = ("Bridge '%s' doesn't exist on one of"
5823
                 " the instance nodes" % nic_bridge)
5824
          if self.force:
5825
            self.warn.append(msg)
5826
          else:
5827
            raise errors.OpPrereqError(msg)
5828

    
5829
    # DISK processing
5830
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
5831
      raise errors.OpPrereqError("Disk operations not supported for"
5832
                                 " diskless instances")
5833
    for disk_op, disk_dict in self.op.disks:
5834
      if disk_op == constants.DDM_REMOVE:
5835
        if len(instance.disks) == 1:
5836
          raise errors.OpPrereqError("Cannot remove the last disk of"
5837
                                     " an instance")
5838
        ins_l = self.rpc.call_instance_list([pnode], [instance.hypervisor])
5839
        ins_l = ins_l[pnode]
5840
        if ins_l.failed or not isinstance(ins_l.data, list):
5841
          raise errors.OpPrereqError("Can't contact node '%s'" % pnode)
5842
        if instance.name in ins_l.data:
5843
          raise errors.OpPrereqError("Instance is running, can't remove"
5844
                                     " disks.")
5845

    
5846
      if (disk_op == constants.DDM_ADD and
5847
          len(instance.nics) >= constants.MAX_DISKS):
5848
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
5849
                                   " add more" % constants.MAX_DISKS)
5850
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
5851
        # an existing disk
5852
        if disk_op < 0 or disk_op >= len(instance.disks):
5853
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
5854
                                     " are 0 to %d" %
5855
                                     (disk_op, len(instance.disks)))
5856

    
5857
    return
5858

    
5859
  def Exec(self, feedback_fn):
5860
    """Modifies an instance.
5861

5862
    All parameters take effect only at the next restart of the instance.
5863

5864
    """
5865
    # Process here the warnings from CheckPrereq, as we don't have a
5866
    # feedback_fn there.
5867
    for warn in self.warn:
5868
      feedback_fn("WARNING: %s" % warn)
5869

    
5870
    result = []
5871
    instance = self.instance
5872
    # disk changes
5873
    for disk_op, disk_dict in self.op.disks:
5874
      if disk_op == constants.DDM_REMOVE:
5875
        # remove the last disk
5876
        device = instance.disks.pop()
5877
        device_idx = len(instance.disks)
5878
        for node, disk in device.ComputeNodeTree(instance.primary_node):
5879
          self.cfg.SetDiskID(disk, node)
5880
          msg = self.rpc.call_blockdev_remove(node, disk).RemoteFailMsg()
5881
          if msg:
5882
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
5883
                            " continuing anyway", device_idx, node, msg)
5884
        result.append(("disk/%d" % device_idx, "remove"))
5885
      elif disk_op == constants.DDM_ADD:
5886
        # add a new disk
5887
        if instance.disk_template == constants.DT_FILE:
5888
          file_driver, file_path = instance.disks[0].logical_id
5889
          file_path = os.path.dirname(file_path)
5890
        else:
5891
          file_driver = file_path = None
5892
        disk_idx_base = len(instance.disks)
5893
        new_disk = _GenerateDiskTemplate(self,
5894
                                         instance.disk_template,
5895
                                         instance.name, instance.primary_node,
5896
                                         instance.secondary_nodes,
5897
                                         [disk_dict],
5898
                                         file_path,
5899
                                         file_driver,
5900
                                         disk_idx_base)[0]
5901
        instance.disks.append(new_disk)
5902
        info = _GetInstanceInfoText(instance)
5903

    
5904
        logging.info("Creating volume %s for instance %s",
5905
                     new_disk.iv_name, instance.name)
5906
        # Note: this needs to be kept in sync with _CreateDisks
5907
        #HARDCODE
5908
        for node in instance.all_nodes:
5909
          f_create = node == instance.primary_node
5910
          try:
5911
            _CreateBlockDev(self, node, instance, new_disk,
5912
                            f_create, info, f_create)
5913
          except errors.OpExecError, err:
5914
            self.LogWarning("Failed to create volume %s (%s) on"
5915
                            " node %s: %s",
5916
                            new_disk.iv_name, new_disk, node, err)
5917
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
5918
                       (new_disk.size, new_disk.mode)))
5919
      else:
5920
        # change a given disk
5921
        instance.disks[disk_op].mode = disk_dict['mode']
5922
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
5923
    # NIC changes
5924
    for nic_op, nic_dict in self.op.nics:
5925
      if nic_op == constants.DDM_REMOVE:
5926
        # remove the last nic
5927
        del instance.nics[-1]
5928
        result.append(("nic.%d" % len(instance.nics), "remove"))
5929
      elif nic_op == constants.DDM_ADD:
5930
        # add a new nic
5931
        if 'mac' not in nic_dict:
5932
          mac = constants.VALUE_GENERATE
5933
        else:
5934
          mac = nic_dict['mac']
5935
        if mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5936
          mac = self.cfg.GenerateMAC()
5937
        new_nic = objects.NIC(mac=mac, ip=nic_dict.get('ip', None),
5938
                              bridge=nic_dict.get('bridge', None))
5939
        instance.nics.append(new_nic)
5940
        result.append(("nic.%d" % (len(instance.nics) - 1),
5941
                       "add:mac=%s,ip=%s,bridge=%s" %
5942
                       (new_nic.mac, new_nic.ip, new_nic.bridge)))
5943
      else:
5944
        # change a given nic
5945
        for key in 'mac', 'ip', 'bridge':
5946
          if key in nic_dict:
5947
            setattr(instance.nics[nic_op], key, nic_dict[key])
5948
            result.append(("nic.%s/%d" % (key, nic_op), nic_dict[key]))
5949

    
5950
    # hvparams changes
5951
    if self.op.hvparams:
5952
      instance.hvparams = self.hv_inst
5953
      for key, val in self.op.hvparams.iteritems():
5954
        result.append(("hv/%s" % key, val))
5955

    
5956
    # beparams changes
5957
    if self.op.beparams:
5958
      instance.beparams = self.be_inst
5959
      for key, val in self.op.beparams.iteritems():
5960
        result.append(("be/%s" % key, val))
5961

    
5962
    self.cfg.Update(instance)
5963

    
5964
    return result
5965

    
5966

    
5967
class LUQueryExports(NoHooksLU):
5968
  """Query the exports list
5969

5970
  """
5971
  _OP_REQP = ['nodes']
5972
  REQ_BGL = False
5973

    
5974
  def ExpandNames(self):
5975
    self.needed_locks = {}
5976
    self.share_locks[locking.LEVEL_NODE] = 1
5977
    if not self.op.nodes:
5978
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5979
    else:
5980
      self.needed_locks[locking.LEVEL_NODE] = \
5981
        _GetWantedNodes(self, self.op.nodes)
5982

    
5983
  def CheckPrereq(self):
5984
    """Check prerequisites.
5985

5986
    """
5987
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
5988

    
5989
  def Exec(self, feedback_fn):
5990
    """Compute the list of all the exported system images.
5991

5992
    @rtype: dict
5993
    @return: a dictionary with the structure node->(export-list)
5994
        where export-list is a list of the instances exported on
5995
        that node.
5996

5997
    """
5998
    rpcresult = self.rpc.call_export_list(self.nodes)
5999
    result = {}
6000
    for node in rpcresult:
6001
      if rpcresult[node].failed:
6002
        result[node] = False
6003
      else:
6004
        result[node] = rpcresult[node].data
6005

    
6006
    return result
6007

    
6008

    
6009
class LUExportInstance(LogicalUnit):
6010
  """Export an instance to an image in the cluster.
6011

6012
  """
6013
  HPATH = "instance-export"
6014
  HTYPE = constants.HTYPE_INSTANCE
6015
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
6016
  REQ_BGL = False
6017

    
6018
  def ExpandNames(self):
6019
    self._ExpandAndLockInstance()
6020
    # FIXME: lock only instance primary and destination node
6021
    #
6022
    # Sad but true, for now we have do lock all nodes, as we don't know where
6023
    # the previous export might be, and and in this LU we search for it and
6024
    # remove it from its current node. In the future we could fix this by:
6025
    #  - making a tasklet to search (share-lock all), then create the new one,
6026
    #    then one to remove, after
6027
    #  - removing the removal operation altoghether
6028
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6029

    
6030
  def DeclareLocks(self, level):
6031
    """Last minute lock declaration."""
6032
    # All nodes are locked anyway, so nothing to do here.
6033

    
6034
  def BuildHooksEnv(self):
6035
    """Build hooks env.
6036

6037
    This will run on the master, primary node and target node.
6038

6039
    """
6040
    env = {
6041
      "EXPORT_NODE": self.op.target_node,
6042
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
6043
      }
6044
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6045
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node,
6046
          self.op.target_node]
6047
    return env, nl, nl
6048

    
6049
  def CheckPrereq(self):
6050
    """Check prerequisites.
6051

6052
    This checks that the instance and node names are valid.
6053

6054
    """
6055
    instance_name = self.op.instance_name
6056
    self.instance = self.cfg.GetInstanceInfo(instance_name)
6057
    assert self.instance is not None, \
6058
          "Cannot retrieve locked instance %s" % self.op.instance_name
6059
    _CheckNodeOnline(self, self.instance.primary_node)
6060

    
6061
    self.dst_node = self.cfg.GetNodeInfo(
6062
      self.cfg.ExpandNodeName(self.op.target_node))
6063

    
6064
    if self.dst_node is None:
6065
      # This is wrong node name, not a non-locked node
6066
      raise errors.OpPrereqError("Wrong node name %s" % self.op.target_node)
6067
    _CheckNodeOnline(self, self.dst_node.name)
6068
    _CheckNodeNotDrained(self, self.dst_node.name)
6069

    
6070
    # instance disk type verification
6071
    for disk in self.instance.disks:
6072
      if disk.dev_type == constants.LD_FILE:
6073
        raise errors.OpPrereqError("Export not supported for instances with"
6074
                                   " file-based disks")
6075

    
6076
  def Exec(self, feedback_fn):
6077
    """Export an instance to an image in the cluster.
6078

6079
    """
6080
    instance = self.instance
6081
    dst_node = self.dst_node
6082
    src_node = instance.primary_node
6083
    if self.op.shutdown:
6084
      # shutdown the instance, but not the disks
6085
      result = self.rpc.call_instance_shutdown(src_node, instance)
6086
      result.Raise()
6087
      if not result.data:
6088
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
6089
                                 (instance.name, src_node))
6090

    
6091
    vgname = self.cfg.GetVGName()
6092

    
6093
    snap_disks = []
6094

    
6095
    # set the disks ID correctly since call_instance_start needs the
6096
    # correct drbd minor to create the symlinks
6097
    for disk in instance.disks:
6098
      self.cfg.SetDiskID(disk, src_node)
6099

    
6100
    try:
6101
      for disk in instance.disks:
6102
        # new_dev_name will be a snapshot of an lvm leaf of the one we passed
6103
        new_dev_name = self.rpc.call_blockdev_snapshot(src_node, disk)
6104
        if new_dev_name.failed or not new_dev_name.data:
6105
          self.LogWarning("Could not snapshot block device %s on node %s",
6106
                          disk.logical_id[1], src_node)
6107
          snap_disks.append(False)
6108
        else:
6109
          new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
6110
                                 logical_id=(vgname, new_dev_name.data),
6111
                                 physical_id=(vgname, new_dev_name.data),
6112
                                 iv_name=disk.iv_name)
6113
          snap_disks.append(new_dev)
6114

    
6115
    finally:
6116
      if self.op.shutdown and instance.admin_up:
6117
        result = self.rpc.call_instance_start(src_node, instance, None)
6118
        msg = result.RemoteFailMsg()
6119
        if msg:
6120
          _ShutdownInstanceDisks(self, instance)
6121
          raise errors.OpExecError("Could not start instance: %s" % msg)
6122

    
6123
    # TODO: check for size
6124

    
6125
    cluster_name = self.cfg.GetClusterName()
6126
    for idx, dev in enumerate(snap_disks):
6127
      if dev:
6128
        result = self.rpc.call_snapshot_export(src_node, dev, dst_node.name,
6129
                                               instance, cluster_name, idx)
6130
        if result.failed or not result.data:
6131
          self.LogWarning("Could not export block device %s from node %s to"
6132
                          " node %s", dev.logical_id[1], src_node,
6133
                          dst_node.name)
6134
        msg = self.rpc.call_blockdev_remove(src_node, dev).RemoteFailMsg()
6135
        if msg:
6136
          self.LogWarning("Could not remove snapshot block device %s from node"
6137
                          " %s: %s", dev.logical_id[1], src_node, msg)
6138

    
6139
    result = self.rpc.call_finalize_export(dst_node.name, instance, snap_disks)
6140
    if result.failed or not result.data:
6141
      self.LogWarning("Could not finalize export for instance %s on node %s",
6142
                      instance.name, dst_node.name)
6143

    
6144
    nodelist = self.cfg.GetNodeList()
6145
    nodelist.remove(dst_node.name)
6146

    
6147
    # on one-node clusters nodelist will be empty after the removal
6148
    # if we proceed the backup would be removed because OpQueryExports
6149
    # substitutes an empty list with the full cluster node list.
6150
    if nodelist:
6151
      exportlist = self.rpc.call_export_list(nodelist)
6152
      for node in exportlist:
6153
        if exportlist[node].failed:
6154
          continue
6155
        if instance.name in exportlist[node].data:
6156
          if not self.rpc.call_export_remove(node, instance.name):
6157
            self.LogWarning("Could not remove older export for instance %s"
6158
                            " on node %s", instance.name, node)
6159

    
6160

    
6161
class LURemoveExport(NoHooksLU):
6162
  """Remove exports related to the named instance.
6163

6164
  """
6165
  _OP_REQP = ["instance_name"]
6166
  REQ_BGL = False
6167

    
6168
  def ExpandNames(self):
6169
    self.needed_locks = {}
6170
    # We need all nodes to be locked in order for RemoveExport to work, but we
6171
    # don't need to lock the instance itself, as nothing will happen to it (and
6172
    # we can remove exports also for a removed instance)
6173
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6174

    
6175
  def CheckPrereq(self):
6176
    """Check prerequisites.
6177
    """
6178
    pass
6179

    
6180
  def Exec(self, feedback_fn):
6181
    """Remove any export.
6182

6183
    """
6184
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
6185
    # If the instance was not found we'll try with the name that was passed in.
6186
    # This will only work if it was an FQDN, though.
6187
    fqdn_warn = False
6188
    if not instance_name:
6189
      fqdn_warn = True
6190
      instance_name = self.op.instance_name
6191

    
6192
    exportlist = self.rpc.call_export_list(self.acquired_locks[
6193
      locking.LEVEL_NODE])
6194
    found = False
6195
    for node in exportlist:
6196
      if exportlist[node].failed:
6197
        self.LogWarning("Failed to query node %s, continuing" % node)
6198
        continue
6199
      if instance_name in exportlist[node].data:
6200
        found = True
6201
        result = self.rpc.call_export_remove(node, instance_name)
6202
        if result.failed or not result.data:
6203
          logging.error("Could not remove export for instance %s"
6204
                        " on node %s", instance_name, node)
6205

    
6206
    if fqdn_warn and not found:
6207
      feedback_fn("Export not found. If trying to remove an export belonging"
6208
                  " to a deleted instance please use its Fully Qualified"
6209
                  " Domain Name.")
6210

    
6211

    
6212
class TagsLU(NoHooksLU):
6213
  """Generic tags LU.
6214

6215
  This is an abstract class which is the parent of all the other tags LUs.
6216

6217
  """
6218

    
6219
  def ExpandNames(self):
6220
    self.needed_locks = {}
6221
    if self.op.kind == constants.TAG_NODE:
6222
      name = self.cfg.ExpandNodeName(self.op.name)
6223
      if name is None:
6224
        raise errors.OpPrereqError("Invalid node name (%s)" %
6225
                                   (self.op.name,))
6226
      self.op.name = name
6227
      self.needed_locks[locking.LEVEL_NODE] = name
6228
    elif self.op.kind == constants.TAG_INSTANCE:
6229
      name = self.cfg.ExpandInstanceName(self.op.name)
6230
      if name is None:
6231
        raise errors.OpPrereqError("Invalid instance name (%s)" %
6232
                                   (self.op.name,))
6233
      self.op.name = name
6234
      self.needed_locks[locking.LEVEL_INSTANCE] = name
6235

    
6236
  def CheckPrereq(self):
6237
    """Check prerequisites.
6238

6239
    """
6240
    if self.op.kind == constants.TAG_CLUSTER:
6241
      self.target = self.cfg.GetClusterInfo()
6242
    elif self.op.kind == constants.TAG_NODE:
6243
      self.target = self.cfg.GetNodeInfo(self.op.name)
6244
    elif self.op.kind == constants.TAG_INSTANCE:
6245
      self.target = self.cfg.GetInstanceInfo(self.op.name)
6246
    else:
6247
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
6248
                                 str(self.op.kind))
6249

    
6250

    
6251
class LUGetTags(TagsLU):
6252
  """Returns the tags of a given object.
6253

6254
  """
6255
  _OP_REQP = ["kind", "name"]
6256
  REQ_BGL = False
6257

    
6258
  def Exec(self, feedback_fn):
6259
    """Returns the tag list.
6260

6261
    """
6262
    return list(self.target.GetTags())
6263

    
6264

    
6265
class LUSearchTags(NoHooksLU):
6266
  """Searches the tags for a given pattern.
6267

6268
  """
6269
  _OP_REQP = ["pattern"]
6270
  REQ_BGL = False
6271

    
6272
  def ExpandNames(self):
6273
    self.needed_locks = {}
6274

    
6275
  def CheckPrereq(self):
6276
    """Check prerequisites.
6277

6278
    This checks the pattern passed for validity by compiling it.
6279

6280
    """
6281
    try:
6282
      self.re = re.compile(self.op.pattern)
6283
    except re.error, err:
6284
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
6285
                                 (self.op.pattern, err))
6286

    
6287
  def Exec(self, feedback_fn):
6288
    """Returns the tag list.
6289

6290
    """
6291
    cfg = self.cfg
6292
    tgts = [("/cluster", cfg.GetClusterInfo())]
6293
    ilist = cfg.GetAllInstancesInfo().values()
6294
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
6295
    nlist = cfg.GetAllNodesInfo().values()
6296
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
6297
    results = []
6298
    for path, target in tgts:
6299
      for tag in target.GetTags():
6300
        if self.re.search(tag):
6301
          results.append((path, tag))
6302
    return results
6303

    
6304

    
6305
class LUAddTags(TagsLU):
6306
  """Sets a tag on a given object.
6307

6308
  """
6309
  _OP_REQP = ["kind", "name", "tags"]
6310
  REQ_BGL = False
6311

    
6312
  def CheckPrereq(self):
6313
    """Check prerequisites.
6314

6315
    This checks the type and length of the tag name and value.
6316

6317
    """
6318
    TagsLU.CheckPrereq(self)
6319
    for tag in self.op.tags:
6320
      objects.TaggableObject.ValidateTag(tag)
6321

    
6322
  def Exec(self, feedback_fn):
6323
    """Sets the tag.
6324

6325
    """
6326
    try:
6327
      for tag in self.op.tags:
6328
        self.target.AddTag(tag)
6329
    except errors.TagError, err:
6330
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
6331
    try:
6332
      self.cfg.Update(self.target)
6333
    except errors.ConfigurationError:
6334
      raise errors.OpRetryError("There has been a modification to the"
6335
                                " config file and the operation has been"
6336
                                " aborted. Please retry.")
6337

    
6338

    
6339
class LUDelTags(TagsLU):
6340
  """Delete a list of tags from a given object.
6341

6342
  """
6343
  _OP_REQP = ["kind", "name", "tags"]
6344
  REQ_BGL = False
6345

    
6346
  def CheckPrereq(self):
6347
    """Check prerequisites.
6348

6349
    This checks that we have the given tag.
6350

6351
    """
6352
    TagsLU.CheckPrereq(self)
6353
    for tag in self.op.tags:
6354
      objects.TaggableObject.ValidateTag(tag)
6355
    del_tags = frozenset(self.op.tags)
6356
    cur_tags = self.target.GetTags()
6357
    if not del_tags <= cur_tags:
6358
      diff_tags = del_tags - cur_tags
6359
      diff_names = ["'%s'" % tag for tag in diff_tags]
6360
      diff_names.sort()
6361
      raise errors.OpPrereqError("Tag(s) %s not found" %
6362
                                 (",".join(diff_names)))
6363

    
6364
  def Exec(self, feedback_fn):
6365
    """Remove the tag from the object.
6366

6367
    """
6368
    for tag in self.op.tags:
6369
      self.target.RemoveTag(tag)
6370
    try:
6371
      self.cfg.Update(self.target)
6372
    except errors.ConfigurationError:
6373
      raise errors.OpRetryError("There has been a modification to the"
6374
                                " config file and the operation has been"
6375
                                " aborted. Please retry.")
6376

    
6377

    
6378
class LUTestDelay(NoHooksLU):
6379
  """Sleep for a specified amount of time.
6380

6381
  This LU sleeps on the master and/or nodes for a specified amount of
6382
  time.
6383

6384
  """
6385
  _OP_REQP = ["duration", "on_master", "on_nodes"]
6386
  REQ_BGL = False
6387

    
6388
  def ExpandNames(self):
6389
    """Expand names and set required locks.
6390

6391
    This expands the node list, if any.
6392

6393
    """
6394
    self.needed_locks = {}
6395
    if self.op.on_nodes:
6396
      # _GetWantedNodes can be used here, but is not always appropriate to use
6397
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
6398
      # more information.
6399
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
6400
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
6401

    
6402
  def CheckPrereq(self):
6403
    """Check prerequisites.
6404

6405
    """
6406

    
6407
  def Exec(self, feedback_fn):
6408
    """Do the actual sleep.
6409

6410
    """
6411
    if self.op.on_master:
6412
      if not utils.TestDelay(self.op.duration):
6413
        raise errors.OpExecError("Error during master delay test")
6414
    if self.op.on_nodes:
6415
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
6416
      if not result:
6417
        raise errors.OpExecError("Complete failure from rpc call")
6418
      for node, node_result in result.items():
6419
        node_result.Raise()
6420
        if not node_result.data:
6421
          raise errors.OpExecError("Failure during rpc call to node %s,"
6422
                                   " result: %s" % (node, node_result.data))
6423

    
6424

    
6425
class IAllocator(object):
6426
  """IAllocator framework.
6427

6428
  An IAllocator instance has three sets of attributes:
6429
    - cfg that is needed to query the cluster
6430
    - input data (all members of the _KEYS class attribute are required)
6431
    - four buffer attributes (in|out_data|text), that represent the
6432
      input (to the external script) in text and data structure format,
6433
      and the output from it, again in two formats
6434
    - the result variables from the script (success, info, nodes) for
6435
      easy usage
6436

6437
  """
6438
  _ALLO_KEYS = [
6439
    "mem_size", "disks", "disk_template",
6440
    "os", "tags", "nics", "vcpus", "hypervisor",
6441
    ]
6442
  _RELO_KEYS = [
6443
    "relocate_from",
6444
    ]
6445

    
6446
  def __init__(self, lu, mode, name, **kwargs):
6447
    self.lu = lu
6448
    # init buffer variables
6449
    self.in_text = self.out_text = self.in_data = self.out_data = None
6450
    # init all input fields so that pylint is happy
6451
    self.mode = mode
6452
    self.name = name
6453
    self.mem_size = self.disks = self.disk_template = None
6454
    self.os = self.tags = self.nics = self.vcpus = None
6455
    self.hypervisor = None
6456
    self.relocate_from = None
6457
    # computed fields
6458
    self.required_nodes = None
6459
    # init result fields
6460
    self.success = self.info = self.nodes = None
6461
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6462
      keyset = self._ALLO_KEYS
6463
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
6464
      keyset = self._RELO_KEYS
6465
    else:
6466
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
6467
                                   " IAllocator" % self.mode)
6468
    for key in kwargs:
6469
      if key not in keyset:
6470
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
6471
                                     " IAllocator" % key)
6472
      setattr(self, key, kwargs[key])
6473
    for key in keyset:
6474
      if key not in kwargs:
6475
        raise errors.ProgrammerError("Missing input parameter '%s' to"
6476
                                     " IAllocator" % key)
6477
    self._BuildInputData()
6478

    
6479
  def _ComputeClusterData(self):
6480
    """Compute the generic allocator input data.
6481

6482
    This is the data that is independent of the actual operation.
6483

6484
    """
6485
    cfg = self.lu.cfg
6486
    cluster_info = cfg.GetClusterInfo()
6487
    # cluster data
6488
    data = {
6489
      "version": 1,
6490
      "cluster_name": cfg.GetClusterName(),
6491
      "cluster_tags": list(cluster_info.GetTags()),
6492
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
6493
      # we don't have job IDs
6494
      }
6495
    iinfo = cfg.GetAllInstancesInfo().values()
6496
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
6497

    
6498
    # node data
6499
    node_results = {}
6500
    node_list = cfg.GetNodeList()
6501

    
6502
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6503
      hypervisor_name = self.hypervisor
6504
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
6505
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
6506

    
6507
    node_data = self.lu.rpc.call_node_info(node_list, cfg.GetVGName(),
6508
                                           hypervisor_name)
6509
    node_iinfo = self.lu.rpc.call_all_instances_info(node_list,
6510
                       cluster_info.enabled_hypervisors)
6511
    for nname, nresult in node_data.items():
6512
      # first fill in static (config-based) values
6513
      ninfo = cfg.GetNodeInfo(nname)
6514
      pnr = {
6515
        "tags": list(ninfo.GetTags()),
6516
        "primary_ip": ninfo.primary_ip,
6517
        "secondary_ip": ninfo.secondary_ip,
6518
        "offline": ninfo.offline,
6519
        "drained": ninfo.drained,
6520
        "master_candidate": ninfo.master_candidate,
6521
        }
6522

    
6523
      if not ninfo.offline:
6524
        nresult.Raise()
6525
        if not isinstance(nresult.data, dict):
6526
          raise errors.OpExecError("Can't get data for node %s" % nname)
6527
        remote_info = nresult.data
6528
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
6529
                     'vg_size', 'vg_free', 'cpu_total']:
6530
          if attr not in remote_info:
6531
            raise errors.OpExecError("Node '%s' didn't return attribute"
6532
                                     " '%s'" % (nname, attr))
6533
          try:
6534
            remote_info[attr] = int(remote_info[attr])
6535
          except ValueError, err:
6536
            raise errors.OpExecError("Node '%s' returned invalid value"
6537
                                     " for '%s': %s" % (nname, attr, err))
6538
        # compute memory used by primary instances
6539
        i_p_mem = i_p_up_mem = 0
6540
        for iinfo, beinfo in i_list:
6541
          if iinfo.primary_node == nname:
6542
            i_p_mem += beinfo[constants.BE_MEMORY]
6543
            if iinfo.name not in node_iinfo[nname].data:
6544
              i_used_mem = 0
6545
            else:
6546
              i_used_mem = int(node_iinfo[nname].data[iinfo.name]['memory'])
6547
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
6548
            remote_info['memory_free'] -= max(0, i_mem_diff)
6549

    
6550
            if iinfo.admin_up:
6551
              i_p_up_mem += beinfo[constants.BE_MEMORY]
6552

    
6553
        # compute memory used by instances
6554
        pnr_dyn = {
6555
          "total_memory": remote_info['memory_total'],
6556
          "reserved_memory": remote_info['memory_dom0'],
6557
          "free_memory": remote_info['memory_free'],
6558
          "total_disk": remote_info['vg_size'],
6559
          "free_disk": remote_info['vg_free'],
6560
          "total_cpus": remote_info['cpu_total'],
6561
          "i_pri_memory": i_p_mem,
6562
          "i_pri_up_memory": i_p_up_mem,
6563
          }
6564
        pnr.update(pnr_dyn)
6565

    
6566
      node_results[nname] = pnr
6567
    data["nodes"] = node_results
6568

    
6569
    # instance data
6570
    instance_data = {}
6571
    for iinfo, beinfo in i_list:
6572
      nic_data = [{"mac": n.mac, "ip": n.ip, "bridge": n.bridge}
6573
                  for n in iinfo.nics]
6574
      pir = {
6575
        "tags": list(iinfo.GetTags()),
6576
        "admin_up": iinfo.admin_up,
6577
        "vcpus": beinfo[constants.BE_VCPUS],
6578
        "memory": beinfo[constants.BE_MEMORY],
6579
        "os": iinfo.os,
6580
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
6581
        "nics": nic_data,
6582
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
6583
        "disk_template": iinfo.disk_template,
6584
        "hypervisor": iinfo.hypervisor,
6585
        }
6586
      instance_data[iinfo.name] = pir
6587

    
6588
    data["instances"] = instance_data
6589

    
6590
    self.in_data = data
6591

    
6592
  def _AddNewInstance(self):
6593
    """Add new instance data to allocator structure.
6594

6595
    This in combination with _AllocatorGetClusterData will create the
6596
    correct structure needed as input for the allocator.
6597

6598
    The checks for the completeness of the opcode must have already been
6599
    done.
6600

6601
    """
6602
    data = self.in_data
6603

    
6604
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
6605

    
6606
    if self.disk_template in constants.DTS_NET_MIRROR:
6607
      self.required_nodes = 2
6608
    else:
6609
      self.required_nodes = 1
6610
    request = {
6611
      "type": "allocate",
6612
      "name": self.name,
6613
      "disk_template": self.disk_template,
6614
      "tags": self.tags,
6615
      "os": self.os,
6616
      "vcpus": self.vcpus,
6617
      "memory": self.mem_size,
6618
      "disks": self.disks,
6619
      "disk_space_total": disk_space,
6620
      "nics": self.nics,
6621
      "required_nodes": self.required_nodes,
6622
      }
6623
    data["request"] = request
6624

    
6625
  def _AddRelocateInstance(self):
6626
    """Add relocate instance data to allocator structure.
6627

6628
    This in combination with _IAllocatorGetClusterData will create the
6629
    correct structure needed as input for the allocator.
6630

6631
    The checks for the completeness of the opcode must have already been
6632
    done.
6633

6634
    """
6635
    instance = self.lu.cfg.GetInstanceInfo(self.name)
6636
    if instance is None:
6637
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
6638
                                   " IAllocator" % self.name)
6639

    
6640
    if instance.disk_template not in constants.DTS_NET_MIRROR:
6641
      raise errors.OpPrereqError("Can't relocate non-mirrored instances")
6642

    
6643
    if len(instance.secondary_nodes) != 1:
6644
      raise errors.OpPrereqError("Instance has not exactly one secondary node")
6645

    
6646
    self.required_nodes = 1
6647
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
6648
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
6649

    
6650
    request = {
6651
      "type": "relocate",
6652
      "name": self.name,
6653
      "disk_space_total": disk_space,
6654
      "required_nodes": self.required_nodes,
6655
      "relocate_from": self.relocate_from,
6656
      }
6657
    self.in_data["request"] = request
6658

    
6659
  def _BuildInputData(self):
6660
    """Build input data structures.
6661

6662
    """
6663
    self._ComputeClusterData()
6664

    
6665
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6666
      self._AddNewInstance()
6667
    else:
6668
      self._AddRelocateInstance()
6669

    
6670
    self.in_text = serializer.Dump(self.in_data)
6671

    
6672
  def Run(self, name, validate=True, call_fn=None):
6673
    """Run an instance allocator and return the results.
6674

6675
    """
6676
    if call_fn is None:
6677
      call_fn = self.lu.rpc.call_iallocator_runner
6678
    data = self.in_text
6679

    
6680
    result = call_fn(self.lu.cfg.GetMasterNode(), name, self.in_text)
6681
    result.Raise()
6682

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

    
6686
    rcode, stdout, stderr, fail = result.data
6687

    
6688
    if rcode == constants.IARUN_NOTFOUND:
6689
      raise errors.OpExecError("Can't find allocator '%s'" % name)
6690
    elif rcode == constants.IARUN_FAILURE:
6691
      raise errors.OpExecError("Instance allocator call failed: %s,"
6692
                               " output: %s" % (fail, stdout+stderr))
6693
    self.out_text = stdout
6694
    if validate:
6695
      self._ValidateResult()
6696

    
6697
  def _ValidateResult(self):
6698
    """Process the allocator results.
6699

6700
    This will process and if successful save the result in
6701
    self.out_data and the other parameters.
6702

6703
    """
6704
    try:
6705
      rdict = serializer.Load(self.out_text)
6706
    except Exception, err:
6707
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
6708

    
6709
    if not isinstance(rdict, dict):
6710
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
6711

    
6712
    for key in "success", "info", "nodes":
6713
      if key not in rdict:
6714
        raise errors.OpExecError("Can't parse iallocator results:"
6715
                                 " missing key '%s'" % key)
6716
      setattr(self, key, rdict[key])
6717

    
6718
    if not isinstance(rdict["nodes"], list):
6719
      raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
6720
                               " is not a list")
6721
    self.out_data = rdict
6722

    
6723

    
6724
class LUTestAllocator(NoHooksLU):
6725
  """Run allocator tests.
6726

6727
  This LU runs the allocator tests
6728

6729
  """
6730
  _OP_REQP = ["direction", "mode", "name"]
6731

    
6732
  def CheckPrereq(self):
6733
    """Check prerequisites.
6734

6735
    This checks the opcode parameters depending on the director and mode test.
6736

6737
    """
6738
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
6739
      for attr in ["name", "mem_size", "disks", "disk_template",
6740
                   "os", "tags", "nics", "vcpus"]:
6741
        if not hasattr(self.op, attr):
6742
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
6743
                                     attr)
6744
      iname = self.cfg.ExpandInstanceName(self.op.name)
6745
      if iname is not None:
6746
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
6747
                                   iname)
6748
      if not isinstance(self.op.nics, list):
6749
        raise errors.OpPrereqError("Invalid parameter 'nics'")
6750
      for row in self.op.nics:
6751
        if (not isinstance(row, dict) or
6752
            "mac" not in row or
6753
            "ip" not in row or
6754
            "bridge" not in row):
6755
          raise errors.OpPrereqError("Invalid contents of the"
6756
                                     " 'nics' parameter")
6757
      if not isinstance(self.op.disks, list):
6758
        raise errors.OpPrereqError("Invalid parameter 'disks'")
6759
      for row in self.op.disks:
6760
        if (not isinstance(row, dict) or
6761
            "size" not in row or
6762
            not isinstance(row["size"], int) or
6763
            "mode" not in row or
6764
            row["mode"] not in ['r', 'w']):
6765
          raise errors.OpPrereqError("Invalid contents of the"
6766
                                     " 'disks' parameter")
6767
      if not hasattr(self.op, "hypervisor") or self.op.hypervisor is None:
6768
        self.op.hypervisor = self.cfg.GetHypervisorType()
6769
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
6770
      if not hasattr(self.op, "name"):
6771
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input")
6772
      fname = self.cfg.ExpandInstanceName(self.op.name)
6773
      if fname is None:
6774
        raise errors.OpPrereqError("Instance '%s' not found for relocation" %
6775
                                   self.op.name)
6776
      self.op.name = fname
6777
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
6778
    else:
6779
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
6780
                                 self.op.mode)
6781

    
6782
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
6783
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
6784
        raise errors.OpPrereqError("Missing allocator name")
6785
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
6786
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
6787
                                 self.op.direction)
6788

    
6789
  def Exec(self, feedback_fn):
6790
    """Run the allocator test.
6791

6792
    """
6793
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
6794
      ial = IAllocator(self,
6795
                       mode=self.op.mode,
6796
                       name=self.op.name,
6797
                       mem_size=self.op.mem_size,
6798
                       disks=self.op.disks,
6799
                       disk_template=self.op.disk_template,
6800
                       os=self.op.os,
6801
                       tags=self.op.tags,
6802
                       nics=self.op.nics,
6803
                       vcpus=self.op.vcpus,
6804
                       hypervisor=self.op.hypervisor,
6805
                       )
6806
    else:
6807
      ial = IAllocator(self,
6808
                       mode=self.op.mode,
6809
                       name=self.op.name,
6810
                       relocate_from=list(self.relocate_from),
6811
                       )
6812

    
6813
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
6814
      result = ial.in_text
6815
    else:
6816
      ial.Run(self.op.allocator, validate=False)
6817
      result = ial.out_text
6818
    return result