Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 0b2454b9

History | View | Annotate | Download (234.5 kB)

1
#
2
#
3

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

    
21

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

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

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

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

    
48

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

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

61
  Note that all commands require root permissions.
62

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

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

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

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

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

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

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

    
109
  ssh = property(fget=__GetSSH)
110

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

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

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

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

126
    """
127
    pass
128

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

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

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

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

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

150
    Examples::
151

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

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

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

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

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

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

189
    """
190

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

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

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

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

205
    """
206
    raise NotImplementedError
207

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

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

215
    """
216
    raise NotImplementedError
217

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

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

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

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

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

237
    """
238
    raise NotImplementedError
239

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

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

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

258
    """
259
    return lu_result
260

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
326
    del self.recalculate_locks[locking.LEVEL_NODE]
327

    
328

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

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

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

    
339

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

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

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

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

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

    
366
  return utils.NiceSort(wanted)
367

    
368

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

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

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

    
385
  if instances:
386
    wanted = []
387

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

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

    
398

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

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

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

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

    
417

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

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

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

    
431

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

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

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

    
443

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

448
  This builds the hook environment from individual variables.
449

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

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

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

    
497
  env["INSTANCE_NIC_COUNT"] = nic_count
498

    
499
  return env
500

    
501

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

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

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

    
532

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

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

    
548

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

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

    
562

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

566
  """
567
  _OP_REQP = []
568

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

572
    This checks whether the cluster is empty.
573

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

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

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

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

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

    
602

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

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

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

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

624
    Test list:
625

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

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

642
    """
643
    node = nodeinfo.name
644

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

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

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

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

    
665
    bad = False
666

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

    
673
    # checks vg existence and size > 20G
674

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

    
687
    # checks config file checksum
688

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

    
716
    # checks ssh to any
717

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

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

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

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

    
758
    return bad
759

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

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

767
    """
768
    bad = False
769

    
770
    node_current = instanceconfig.primary_node
771

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

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

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

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

    
800
    return bad
801

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

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

808
    """
809
    bad = False
810

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

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

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

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

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

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

840
    """
841
    bad = False
842

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

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

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

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

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

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

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

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

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

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

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

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

    
920
    local_checksums = utils.FingerprintFiles(file_names)
921

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

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

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

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

    
954
      if node == master_node:
955
        ntype = "master"
956
      elif node_i.master_candidate:
957
        ntype = "master candidate"
958
      else:
959
        ntype = "regular"
960
      feedback_fn("* Verifying node %s (%s)" % (node, ntype))
961

    
962
      if all_nvinfo[node].failed or not isinstance(nresult, dict):
963
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
964
        bad = True
965
        continue
966

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

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

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

    
997
      node_instance[node] = idata
998

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

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

    
1025
    node_vol_should = {}
1026

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

    
1035
      inst_config.MapLVsByNode(node_vol_should)
1036

    
1037
      instance_cfg[instance] = inst_config
1038

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

    
1047
      if pnode in n_offline:
1048
        inst_nodes_offline.append(pnode)
1049

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

    
1061
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1062
        i_non_a_balanced.append(instance)
1063

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

    
1077
      if inst_nodes_offline:
1078
        # warn that the instance lives on offline nodes, and set bad=True
1079
        feedback_fn("  - ERROR: instance lives on offline node(s) %s" %
1080
                    ", ".join(inst_nodes_offline))
1081
        bad = True
1082

    
1083
    feedback_fn("* Verifying orphan volumes")
1084
    result = self._VerifyOrphanVolumes(node_vol_should, node_volume,
1085
                                       feedback_fn)
1086
    bad = bad or result
1087

    
1088
    feedback_fn("* Verifying remaining instances")
1089
    result = self._VerifyOrphanInstances(instancelist, node_instance,
1090
                                         feedback_fn)
1091
    bad = bad or result
1092

    
1093
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1094
      feedback_fn("* Verifying N+1 Memory redundancy")
1095
      result = self._VerifyNPlusOneMemory(node_info, instance_cfg, feedback_fn)
1096
      bad = bad or result
1097

    
1098
    feedback_fn("* Other Notes")
1099
    if i_non_redundant:
1100
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1101
                  % len(i_non_redundant))
1102

    
1103
    if i_non_a_balanced:
1104
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1105
                  % len(i_non_a_balanced))
1106

    
1107
    if n_offline:
1108
      feedback_fn("  - NOTICE: %d offline node(s) found." % len(n_offline))
1109

    
1110
    return not bad
1111

    
1112
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1113
    """Analize the post-hooks' result
1114

1115
    This method analyses the hook result, handles it, and sends some
1116
    nicely-formatted feedback back to the user.
1117

1118
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1119
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1120
    @param hooks_results: the results of the multi-node hooks rpc call
1121
    @param feedback_fn: function used send feedback back to the caller
1122
    @param lu_result: previous Exec result
1123
    @return: the new Exec result, based on the previous result
1124
        and hook results
1125

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

    
1159
      return lu_result
1160

    
1161

    
1162
class LUVerifyDisks(NoHooksLU):
1163
  """Verifies the cluster disks status.
1164

1165
  """
1166
  _OP_REQP = []
1167
  REQ_BGL = False
1168

    
1169
  def ExpandNames(self):
1170
    self.needed_locks = {
1171
      locking.LEVEL_NODE: locking.ALL_SET,
1172
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1173
    }
1174
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
1175

    
1176
  def CheckPrereq(self):
1177
    """Check prerequisites.
1178

1179
    This has no prerequisites.
1180

1181
    """
1182
    pass
1183

    
1184
  def Exec(self, feedback_fn):
1185
    """Verify integrity of cluster disks.
1186

1187
    """
1188
    result = res_nodes, res_nlvm, res_instances, res_missing = [], {}, [], {}
1189

    
1190
    vg_name = self.cfg.GetVGName()
1191
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1192
    instances = [self.cfg.GetInstanceInfo(name)
1193
                 for name in self.cfg.GetInstanceList()]
1194

    
1195
    nv_dict = {}
1196
    for inst in instances:
1197
      inst_lvs = {}
1198
      if (not inst.admin_up or
1199
          inst.disk_template not in constants.DTS_NET_MIRROR):
1200
        continue
1201
      inst.MapLVsByNode(inst_lvs)
1202
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1203
      for node, vol_list in inst_lvs.iteritems():
1204
        for vol in vol_list:
1205
          nv_dict[(node, vol)] = inst
1206

    
1207
    if not nv_dict:
1208
      return result
1209

    
1210
    node_lvs = self.rpc.call_volume_list(nodes, vg_name)
1211

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

    
1231
      for lv_name, (_, lv_inactive, lv_online) in lvs.iteritems():
1232
        inst = nv_dict.pop((node, lv_name), None)
1233
        if (not lv_online and inst is not None
1234
            and inst.name not in res_instances):
1235
          res_instances.append(inst.name)
1236

    
1237
    # any leftover items in nv_dict are missing LVs, let's arrange the
1238
    # data better
1239
    for key, inst in nv_dict.iteritems():
1240
      if inst.name not in res_missing:
1241
        res_missing[inst.name] = []
1242
      res_missing[inst.name].append(key)
1243

    
1244
    return result
1245

    
1246

    
1247
class LURenameCluster(LogicalUnit):
1248
  """Rename the cluster.
1249

1250
  """
1251
  HPATH = "cluster-rename"
1252
  HTYPE = constants.HTYPE_CLUSTER
1253
  _OP_REQP = ["name"]
1254

    
1255
  def BuildHooksEnv(self):
1256
    """Build hooks env.
1257

1258
    """
1259
    env = {
1260
      "OP_TARGET": self.cfg.GetClusterName(),
1261
      "NEW_NAME": self.op.name,
1262
      }
1263
    mn = self.cfg.GetMasterNode()
1264
    return env, [mn], [mn]
1265

    
1266
  def CheckPrereq(self):
1267
    """Verify that the passed name is a valid one.
1268

1269
    """
1270
    hostname = utils.HostInfo(self.op.name)
1271

    
1272
    new_name = hostname.name
1273
    self.ip = new_ip = hostname.ip
1274
    old_name = self.cfg.GetClusterName()
1275
    old_ip = self.cfg.GetMasterIP()
1276
    if new_name == old_name and new_ip == old_ip:
1277
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1278
                                 " cluster has changed")
1279
    if new_ip != old_ip:
1280
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1281
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1282
                                   " reachable on the network. Aborting." %
1283
                                   new_ip)
1284

    
1285
    self.op.name = new_name
1286

    
1287
  def Exec(self, feedback_fn):
1288
    """Rename the cluster.
1289

1290
    """
1291
    clustername = self.op.name
1292
    ip = self.ip
1293

    
1294
    # shutdown the master IP
1295
    master = self.cfg.GetMasterNode()
1296
    result = self.rpc.call_node_stop_master(master, False)
1297
    if result.failed or not result.data:
1298
      raise errors.OpExecError("Could not disable the master role")
1299

    
1300
    try:
1301
      cluster = self.cfg.GetClusterInfo()
1302
      cluster.cluster_name = clustername
1303
      cluster.master_ip = ip
1304
      self.cfg.Update(cluster)
1305

    
1306
      # update the known hosts file
1307
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
1308
      node_list = self.cfg.GetNodeList()
1309
      try:
1310
        node_list.remove(master)
1311
      except ValueError:
1312
        pass
1313
      result = self.rpc.call_upload_file(node_list,
1314
                                         constants.SSH_KNOWN_HOSTS_FILE)
1315
      for to_node, to_result in result.iteritems():
1316
        if to_result.failed or not to_result.data:
1317
          logging.error("Copy of file %s to node %s failed",
1318
                        constants.SSH_KNOWN_HOSTS_FILE, to_node)
1319

    
1320
    finally:
1321
      result = self.rpc.call_node_start_master(master, False)
1322
      if result.failed or not result.data:
1323
        self.LogWarning("Could not re-enable the master role on"
1324
                        " the master, please restart manually.")
1325

    
1326

    
1327
def _RecursiveCheckIfLVMBased(disk):
1328
  """Check if the given disk or its children are lvm-based.
1329

1330
  @type disk: L{objects.Disk}
1331
  @param disk: the disk to check
1332
  @rtype: booleean
1333
  @return: boolean indicating whether a LD_LV dev_type was found or not
1334

1335
  """
1336
  if disk.children:
1337
    for chdisk in disk.children:
1338
      if _RecursiveCheckIfLVMBased(chdisk):
1339
        return True
1340
  return disk.dev_type == constants.LD_LV
1341

    
1342

    
1343
class LUSetClusterParams(LogicalUnit):
1344
  """Change the parameters of the cluster.
1345

1346
  """
1347
  HPATH = "cluster-modify"
1348
  HTYPE = constants.HTYPE_CLUSTER
1349
  _OP_REQP = []
1350
  REQ_BGL = False
1351

    
1352
  def CheckParameters(self):
1353
    """Check parameters
1354

1355
    """
1356
    if not hasattr(self.op, "candidate_pool_size"):
1357
      self.op.candidate_pool_size = None
1358
    if self.op.candidate_pool_size is not None:
1359
      try:
1360
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
1361
      except ValueError, err:
1362
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
1363
                                   str(err))
1364
      if self.op.candidate_pool_size < 1:
1365
        raise errors.OpPrereqError("At least one master candidate needed")
1366

    
1367
  def ExpandNames(self):
1368
    # FIXME: in the future maybe other cluster params won't require checking on
1369
    # all nodes to be modified.
1370
    self.needed_locks = {
1371
      locking.LEVEL_NODE: locking.ALL_SET,
1372
    }
1373
    self.share_locks[locking.LEVEL_NODE] = 1
1374

    
1375
  def BuildHooksEnv(self):
1376
    """Build hooks env.
1377

1378
    """
1379
    env = {
1380
      "OP_TARGET": self.cfg.GetClusterName(),
1381
      "NEW_VG_NAME": self.op.vg_name,
1382
      }
1383
    mn = self.cfg.GetMasterNode()
1384
    return env, [mn], [mn]
1385

    
1386
  def CheckPrereq(self):
1387
    """Check prerequisites.
1388

1389
    This checks whether the given params don't conflict and
1390
    if the given volume group is valid.
1391

1392
    """
1393
    # FIXME: This only works because there is only one parameter that can be
1394
    # changed or removed.
1395
    if self.op.vg_name is not None and not self.op.vg_name:
1396
      instances = self.cfg.GetAllInstancesInfo().values()
1397
      for inst in instances:
1398
        for disk in inst.disks:
1399
          if _RecursiveCheckIfLVMBased(disk):
1400
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1401
                                       " lvm-based instances exist")
1402

    
1403
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1404

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

    
1420
    self.cluster = cluster = self.cfg.GetClusterInfo()
1421
    # validate beparams changes
1422
    if self.op.beparams:
1423
      utils.CheckBEParams(self.op.beparams)
1424
      self.new_beparams = cluster.FillDict(
1425
        cluster.beparams[constants.BEGR_DEFAULT], self.op.beparams)
1426

    
1427
    # hypervisor list/parameters
1428
    self.new_hvparams = cluster.FillDict(cluster.hvparams, {})
1429
    if self.op.hvparams:
1430
      if not isinstance(self.op.hvparams, dict):
1431
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input")
1432
      for hv_name, hv_dict in self.op.hvparams.items():
1433
        if hv_name not in self.new_hvparams:
1434
          self.new_hvparams[hv_name] = hv_dict
1435
        else:
1436
          self.new_hvparams[hv_name].update(hv_dict)
1437

    
1438
    if self.op.enabled_hypervisors is not None:
1439
      self.hv_list = self.op.enabled_hypervisors
1440
    else:
1441
      self.hv_list = cluster.enabled_hypervisors
1442

    
1443
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
1444
      # either the enabled list has changed, or the parameters have, validate
1445
      for hv_name, hv_params in self.new_hvparams.items():
1446
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
1447
            (self.op.enabled_hypervisors and
1448
             hv_name in self.op.enabled_hypervisors)):
1449
          # either this is a new hypervisor, or its parameters have changed
1450
          hv_class = hypervisor.GetHypervisor(hv_name)
1451
          hv_class.CheckParameterSyntax(hv_params)
1452
          _CheckHVParams(self, node_list, hv_name, hv_params)
1453

    
1454
  def Exec(self, feedback_fn):
1455
    """Change the parameters of the cluster.
1456

1457
    """
1458
    if self.op.vg_name is not None:
1459
      if self.op.vg_name != self.cfg.GetVGName():
1460
        self.cfg.SetVGName(self.op.vg_name)
1461
      else:
1462
        feedback_fn("Cluster LVM configuration already in desired"
1463
                    " state, not changing")
1464
    if self.op.hvparams:
1465
      self.cluster.hvparams = self.new_hvparams
1466
    if self.op.enabled_hypervisors is not None:
1467
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
1468
    if self.op.beparams:
1469
      self.cluster.beparams[constants.BEGR_DEFAULT] = self.new_beparams
1470
    if self.op.candidate_pool_size is not None:
1471
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
1472

    
1473
    self.cfg.Update(self.cluster)
1474

    
1475
    # we want to update nodes after the cluster so that if any errors
1476
    # happen, we have recorded and saved the cluster info
1477
    if self.op.candidate_pool_size is not None:
1478
      _AdjustCandidatePool(self)
1479

    
1480

    
1481
class LURedistributeConfig(NoHooksLU):
1482
  """Force the redistribution of cluster configuration.
1483

1484
  This is a very simple LU.
1485

1486
  """
1487
  _OP_REQP = []
1488
  REQ_BGL = False
1489

    
1490
  def ExpandNames(self):
1491
    self.needed_locks = {
1492
      locking.LEVEL_NODE: locking.ALL_SET,
1493
    }
1494
    self.share_locks[locking.LEVEL_NODE] = 1
1495

    
1496
  def CheckPrereq(self):
1497
    """Check prerequisites.
1498

1499
    """
1500

    
1501
  def Exec(self, feedback_fn):
1502
    """Redistribute the configuration.
1503

1504
    """
1505
    self.cfg.Update(self.cfg.GetClusterInfo())
1506

    
1507

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

1511
  """
1512
  if not instance.disks:
1513
    return True
1514

    
1515
  if not oneshot:
1516
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
1517

    
1518
  node = instance.primary_node
1519

    
1520
  for dev in instance.disks:
1521
    lu.cfg.SetDiskID(dev, node)
1522

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

    
1559
    time.sleep(min(60, max_time))
1560

    
1561
  if done:
1562
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
1563
  return not cumul_degraded
1564

    
1565

    
1566
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
1567
  """Check that mirrors are not degraded.
1568

1569
  The ldisk parameter, if True, will change the test from the
1570
  is_degraded attribute (which represents overall non-ok status for
1571
  the device(s)) to the ldisk (representing the local storage status).
1572

1573
  """
1574
  lu.cfg.SetDiskID(dev, node)
1575
  if ldisk:
1576
    idx = 6
1577
  else:
1578
    idx = 5
1579

    
1580
  result = True
1581
  if on_primary or dev.AssembleOnSecondary():
1582
    rstats = lu.rpc.call_blockdev_find(node, dev)
1583
    msg = rstats.RemoteFailMsg()
1584
    if msg:
1585
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
1586
      result = False
1587
    elif not rstats.payload:
1588
      lu.LogWarning("Can't find disk on node %s", node)
1589
      result = False
1590
    else:
1591
      result = result and (not rstats.payload[idx])
1592
  if dev.children:
1593
    for child in dev.children:
1594
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
1595

    
1596
  return result
1597

    
1598

    
1599
class LUDiagnoseOS(NoHooksLU):
1600
  """Logical unit for OS diagnose/query.
1601

1602
  """
1603
  _OP_REQP = ["output_fields", "names"]
1604
  REQ_BGL = False
1605
  _FIELDS_STATIC = utils.FieldSet()
1606
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status")
1607

    
1608
  def ExpandNames(self):
1609
    if self.op.names:
1610
      raise errors.OpPrereqError("Selective OS query not supported")
1611

    
1612
    _CheckOutputFields(static=self._FIELDS_STATIC,
1613
                       dynamic=self._FIELDS_DYNAMIC,
1614
                       selected=self.op.output_fields)
1615

    
1616
    # Lock all nodes, in shared mode
1617
    self.needed_locks = {}
1618
    self.share_locks[locking.LEVEL_NODE] = 1
1619
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1620

    
1621
  def CheckPrereq(self):
1622
    """Check prerequisites.
1623

1624
    """
1625

    
1626
  @staticmethod
1627
  def _DiagnoseByOS(node_list, rlist):
1628
    """Remaps a per-node return list into an a per-os per-node dictionary
1629

1630
    @param node_list: a list with the names of all nodes
1631
    @param rlist: a map with node names as keys and OS objects as values
1632

1633
    @rtype: dict
1634
    @returns: a dictionary with osnames as keys and as value another map, with
1635
        nodes as keys and list of OS objects as values, eg::
1636

1637
          {"debian-etch": {"node1": [<object>,...],
1638
                           "node2": [<object>,]}
1639
          }
1640

1641
    """
1642
    all_os = {}
1643
    for node_name, nr in rlist.iteritems():
1644
      if nr.failed or not nr.data:
1645
        continue
1646
      for os_obj in nr.data:
1647
        if os_obj.name not in all_os:
1648
          # build a list of nodes for this os containing empty lists
1649
          # for each node in node_list
1650
          all_os[os_obj.name] = {}
1651
          for nname in node_list:
1652
            all_os[os_obj.name][nname] = []
1653
        all_os[os_obj.name][node_name].append(os_obj)
1654
    return all_os
1655

    
1656
  def Exec(self, feedback_fn):
1657
    """Compute the list of OSes.
1658

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

    
1684
    return output
1685

    
1686

    
1687
class LURemoveNode(LogicalUnit):
1688
  """Logical unit for removing a node.
1689

1690
  """
1691
  HPATH = "node-remove"
1692
  HTYPE = constants.HTYPE_NODE
1693
  _OP_REQP = ["node_name"]
1694

    
1695
  def BuildHooksEnv(self):
1696
    """Build hooks env.
1697

1698
    This doesn't run on the target node in the pre phase as a failed
1699
    node would then be impossible to remove.
1700

1701
    """
1702
    env = {
1703
      "OP_TARGET": self.op.node_name,
1704
      "NODE_NAME": self.op.node_name,
1705
      }
1706
    all_nodes = self.cfg.GetNodeList()
1707
    all_nodes.remove(self.op.node_name)
1708
    return env, all_nodes, all_nodes
1709

    
1710
  def CheckPrereq(self):
1711
    """Check prerequisites.
1712

1713
    This checks:
1714
     - the node exists in the configuration
1715
     - it does not have primary or secondary instances
1716
     - it's not the master
1717

1718
    Any errors are signalled by raising errors.OpPrereqError.
1719

1720
    """
1721
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
1722
    if node is None:
1723
      raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name)
1724

    
1725
    instance_list = self.cfg.GetInstanceList()
1726

    
1727
    masternode = self.cfg.GetMasterNode()
1728
    if node.name == masternode:
1729
      raise errors.OpPrereqError("Node is the master node,"
1730
                                 " you need to failover first.")
1731

    
1732
    for instance_name in instance_list:
1733
      instance = self.cfg.GetInstanceInfo(instance_name)
1734
      if node.name in instance.all_nodes:
1735
        raise errors.OpPrereqError("Instance %s is still running on the node,"
1736
                                   " please remove first." % instance_name)
1737
    self.op.node_name = node.name
1738
    self.node = node
1739

    
1740
  def Exec(self, feedback_fn):
1741
    """Removes the node from the cluster.
1742

1743
    """
1744
    node = self.node
1745
    logging.info("Stopping the node daemon and removing configs from node %s",
1746
                 node.name)
1747

    
1748
    self.context.RemoveNode(node.name)
1749

    
1750
    self.rpc.call_node_leave_cluster(node.name)
1751

    
1752
    # Promote nodes to master candidate as needed
1753
    _AdjustCandidatePool(self)
1754

    
1755

    
1756
class LUQueryNodes(NoHooksLU):
1757
  """Logical unit for querying nodes.
1758

1759
  """
1760
  _OP_REQP = ["output_fields", "names", "use_locking"]
1761
  REQ_BGL = False
1762
  _FIELDS_DYNAMIC = utils.FieldSet(
1763
    "dtotal", "dfree",
1764
    "mtotal", "mnode", "mfree",
1765
    "bootid",
1766
    "ctotal", "cnodes", "csockets",
1767
    )
1768

    
1769
  _FIELDS_STATIC = utils.FieldSet(
1770
    "name", "pinst_cnt", "sinst_cnt",
1771
    "pinst_list", "sinst_list",
1772
    "pip", "sip", "tags",
1773
    "serial_no",
1774
    "master_candidate",
1775
    "master",
1776
    "offline",
1777
    "drained",
1778
    )
1779

    
1780
  def ExpandNames(self):
1781
    _CheckOutputFields(static=self._FIELDS_STATIC,
1782
                       dynamic=self._FIELDS_DYNAMIC,
1783
                       selected=self.op.output_fields)
1784

    
1785
    self.needed_locks = {}
1786
    self.share_locks[locking.LEVEL_NODE] = 1
1787

    
1788
    if self.op.names:
1789
      self.wanted = _GetWantedNodes(self, self.op.names)
1790
    else:
1791
      self.wanted = locking.ALL_SET
1792

    
1793
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
1794
    self.do_locking = self.do_node_query and self.op.use_locking
1795
    if self.do_locking:
1796
      # if we don't request only static fields, we need to lock the nodes
1797
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
1798

    
1799

    
1800
  def CheckPrereq(self):
1801
    """Check prerequisites.
1802

1803
    """
1804
    # The validation of the node list is done in the _GetWantedNodes,
1805
    # if non empty, and if empty, there's no validation to do
1806
    pass
1807

    
1808
  def Exec(self, feedback_fn):
1809
    """Computes the list of nodes and their attributes.
1810

1811
    """
1812
    all_info = self.cfg.GetAllNodesInfo()
1813
    if self.do_locking:
1814
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
1815
    elif self.wanted != locking.ALL_SET:
1816
      nodenames = self.wanted
1817
      missing = set(nodenames).difference(all_info.keys())
1818
      if missing:
1819
        raise errors.OpExecError(
1820
          "Some nodes were removed before retrieving their data: %s" % missing)
1821
    else:
1822
      nodenames = all_info.keys()
1823

    
1824
    nodenames = utils.NiceSort(nodenames)
1825
    nodelist = [all_info[name] for name in nodenames]
1826

    
1827
    # begin data gathering
1828

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

    
1854
    node_to_primary = dict([(name, set()) for name in nodenames])
1855
    node_to_secondary = dict([(name, set()) for name in nodenames])
1856

    
1857
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
1858
                             "sinst_cnt", "sinst_list"))
1859
    if inst_fields & frozenset(self.op.output_fields):
1860
      instancelist = self.cfg.GetInstanceList()
1861

    
1862
      for instance_name in instancelist:
1863
        inst = self.cfg.GetInstanceInfo(instance_name)
1864
        if inst.primary_node in node_to_primary:
1865
          node_to_primary[inst.primary_node].add(inst.name)
1866
        for secnode in inst.secondary_nodes:
1867
          if secnode in node_to_secondary:
1868
            node_to_secondary[secnode].add(inst.name)
1869

    
1870
    master_node = self.cfg.GetMasterNode()
1871

    
1872
    # end data gathering
1873

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

    
1911
    return output
1912

    
1913

    
1914
class LUQueryNodeVolumes(NoHooksLU):
1915
  """Logical unit for getting volumes on node(s).
1916

1917
  """
1918
  _OP_REQP = ["nodes", "output_fields"]
1919
  REQ_BGL = False
1920
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
1921
  _FIELDS_STATIC = utils.FieldSet("node")
1922

    
1923
  def ExpandNames(self):
1924
    _CheckOutputFields(static=self._FIELDS_STATIC,
1925
                       dynamic=self._FIELDS_DYNAMIC,
1926
                       selected=self.op.output_fields)
1927

    
1928
    self.needed_locks = {}
1929
    self.share_locks[locking.LEVEL_NODE] = 1
1930
    if not self.op.nodes:
1931
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1932
    else:
1933
      self.needed_locks[locking.LEVEL_NODE] = \
1934
        _GetWantedNodes(self, self.op.nodes)
1935

    
1936
  def CheckPrereq(self):
1937
    """Check prerequisites.
1938

1939
    This checks that the fields required are valid output fields.
1940

1941
    """
1942
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
1943

    
1944
  def Exec(self, feedback_fn):
1945
    """Computes the list of nodes and their attributes.
1946

1947
    """
1948
    nodenames = self.nodes
1949
    volumes = self.rpc.call_node_volumes(nodenames)
1950

    
1951
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
1952
             in self.cfg.GetInstanceList()]
1953

    
1954
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
1955

    
1956
    output = []
1957
    for node in nodenames:
1958
      if node not in volumes or volumes[node].failed or not volumes[node].data:
1959
        continue
1960

    
1961
      node_vols = volumes[node].data[:]
1962
      node_vols.sort(key=lambda vol: vol['dev'])
1963

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

    
1990
        output.append(node_output)
1991

    
1992
    return output
1993

    
1994

    
1995
class LUAddNode(LogicalUnit):
1996
  """Logical unit for adding node to the cluster.
1997

1998
  """
1999
  HPATH = "node-add"
2000
  HTYPE = constants.HTYPE_NODE
2001
  _OP_REQP = ["node_name"]
2002

    
2003
  def BuildHooksEnv(self):
2004
    """Build hooks env.
2005

2006
    This will run on all nodes before, and on all nodes + the new node after.
2007

2008
    """
2009
    env = {
2010
      "OP_TARGET": self.op.node_name,
2011
      "NODE_NAME": self.op.node_name,
2012
      "NODE_PIP": self.op.primary_ip,
2013
      "NODE_SIP": self.op.secondary_ip,
2014
      }
2015
    nodes_0 = self.cfg.GetNodeList()
2016
    nodes_1 = nodes_0 + [self.op.node_name, ]
2017
    return env, nodes_0, nodes_1
2018

    
2019
  def CheckPrereq(self):
2020
    """Check prerequisites.
2021

2022
    This checks:
2023
     - the new node is not already in the config
2024
     - it is resolvable
2025
     - its parameters (single/dual homed) matches the cluster
2026

2027
    Any errors are signalled by raising errors.OpPrereqError.
2028

2029
    """
2030
    node_name = self.op.node_name
2031
    cfg = self.cfg
2032

    
2033
    dns_data = utils.HostInfo(node_name)
2034

    
2035
    node = dns_data.name
2036
    primary_ip = self.op.primary_ip = dns_data.ip
2037
    secondary_ip = getattr(self.op, "secondary_ip", None)
2038
    if secondary_ip is None:
2039
      secondary_ip = primary_ip
2040
    if not utils.IsValidIP(secondary_ip):
2041
      raise errors.OpPrereqError("Invalid secondary IP given")
2042
    self.op.secondary_ip = secondary_ip
2043

    
2044
    node_list = cfg.GetNodeList()
2045
    if not self.op.readd and node in node_list:
2046
      raise errors.OpPrereqError("Node %s is already in the configuration" %
2047
                                 node)
2048
    elif self.op.readd and node not in node_list:
2049
      raise errors.OpPrereqError("Node %s is not in the configuration" % node)
2050

    
2051
    for existing_node_name in node_list:
2052
      existing_node = cfg.GetNodeInfo(existing_node_name)
2053

    
2054
      if self.op.readd and node == existing_node_name:
2055
        if (existing_node.primary_ip != primary_ip or
2056
            existing_node.secondary_ip != secondary_ip):
2057
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
2058
                                     " address configuration as before")
2059
        continue
2060

    
2061
      if (existing_node.primary_ip == primary_ip or
2062
          existing_node.secondary_ip == primary_ip or
2063
          existing_node.primary_ip == secondary_ip or
2064
          existing_node.secondary_ip == secondary_ip):
2065
        raise errors.OpPrereqError("New node ip address(es) conflict with"
2066
                                   " existing node %s" % existing_node.name)
2067

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

    
2081
    # checks reachablity
2082
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
2083
      raise errors.OpPrereqError("Node not reachable by ping")
2084

    
2085
    if not newbie_singlehomed:
2086
      # check reachability from my secondary ip to newbie's secondary ip
2087
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
2088
                           source=myself.secondary_ip):
2089
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
2090
                                   " based ping to noded port")
2091

    
2092
    cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2093
    mc_now, _ = self.cfg.GetMasterCandidateStats()
2094
    master_candidate = mc_now < cp_size
2095

    
2096
    self.new_node = objects.Node(name=node,
2097
                                 primary_ip=primary_ip,
2098
                                 secondary_ip=secondary_ip,
2099
                                 master_candidate=master_candidate,
2100
                                 offline=False, drained=False)
2101

    
2102
  def Exec(self, feedback_fn):
2103
    """Adds the new node to the cluster.
2104

2105
    """
2106
    new_node = self.new_node
2107
    node = new_node.name
2108

    
2109
    # check connectivity
2110
    result = self.rpc.call_version([node])[node]
2111
    result.Raise()
2112
    if result.data:
2113
      if constants.PROTOCOL_VERSION == result.data:
2114
        logging.info("Communication to node %s fine, sw version %s match",
2115
                     node, result.data)
2116
      else:
2117
        raise errors.OpExecError("Version mismatch master version %s,"
2118
                                 " node version %s" %
2119
                                 (constants.PROTOCOL_VERSION, result.data))
2120
    else:
2121
      raise errors.OpExecError("Cannot get version from the new node")
2122

    
2123
    # setup ssh on node
2124
    logging.info("Copy ssh key to node %s", node)
2125
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
2126
    keyarray = []
2127
    keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
2128
                constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
2129
                priv_key, pub_key]
2130

    
2131
    for i in keyfiles:
2132
      f = open(i, 'r')
2133
      try:
2134
        keyarray.append(f.read())
2135
      finally:
2136
        f.close()
2137

    
2138
    result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
2139
                                    keyarray[2],
2140
                                    keyarray[3], keyarray[4], keyarray[5])
2141

    
2142
    msg = result.RemoteFailMsg()
2143
    if msg:
2144
      raise errors.OpExecError("Cannot transfer ssh keys to the"
2145
                               " new node: %s" % msg)
2146

    
2147
    # Add node to our /etc/hosts, and add key to known_hosts
2148
    utils.AddHostToEtcHosts(new_node.name)
2149

    
2150
    if new_node.secondary_ip != new_node.primary_ip:
2151
      result = self.rpc.call_node_has_ip_address(new_node.name,
2152
                                                 new_node.secondary_ip)
2153
      if result.failed or not result.data:
2154
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
2155
                                 " you gave (%s). Please fix and re-run this"
2156
                                 " command." % new_node.secondary_ip)
2157

    
2158
    node_verify_list = [self.cfg.GetMasterNode()]
2159
    node_verify_param = {
2160
      'nodelist': [node],
2161
      # TODO: do a node-net-test as well?
2162
    }
2163

    
2164
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
2165
                                       self.cfg.GetClusterName())
2166
    for verifier in node_verify_list:
2167
      if result[verifier].failed or not result[verifier].data:
2168
        raise errors.OpExecError("Cannot communicate with %s's node daemon"
2169
                                 " for remote verification" % verifier)
2170
      if result[verifier].data['nodelist']:
2171
        for failed in result[verifier].data['nodelist']:
2172
          feedback_fn("ssh/hostname verification failed %s -> %s" %
2173
                      (verifier, result[verifier].data['nodelist'][failed]))
2174
        raise errors.OpExecError("ssh/hostname verification failed.")
2175

    
2176
    # Distribute updated /etc/hosts and known_hosts to all nodes,
2177
    # including the node just added
2178
    myself = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
2179
    dist_nodes = self.cfg.GetNodeList()
2180
    if not self.op.readd:
2181
      dist_nodes.append(node)
2182
    if myself.name in dist_nodes:
2183
      dist_nodes.remove(myself.name)
2184

    
2185
    logging.debug("Copying hosts and known_hosts to all nodes")
2186
    for fname in (constants.ETC_HOSTS, constants.SSH_KNOWN_HOSTS_FILE):
2187
      result = self.rpc.call_upload_file(dist_nodes, fname)
2188
      for to_node, to_result in result.iteritems():
2189
        if to_result.failed or not to_result.data:
2190
          logging.error("Copy of file %s to node %s failed", fname, to_node)
2191

    
2192
    to_copy = []
2193
    enabled_hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
2194
    if constants.HTS_USE_VNC.intersection(enabled_hypervisors):
2195
      to_copy.append(constants.VNC_PASSWORD_FILE)
2196

    
2197
    for fname in to_copy:
2198
      result = self.rpc.call_upload_file([node], fname)
2199
      if result[node].failed or not result[node]:
2200
        logging.error("Could not copy file %s to node %s", fname, node)
2201

    
2202
    if self.op.readd:
2203
      self.context.ReaddNode(new_node)
2204
    else:
2205
      self.context.AddNode(new_node)
2206

    
2207

    
2208
class LUSetNodeParams(LogicalUnit):
2209
  """Modifies the parameters of a node.
2210

2211
  """
2212
  HPATH = "node-modify"
2213
  HTYPE = constants.HTYPE_NODE
2214
  _OP_REQP = ["node_name"]
2215
  REQ_BGL = False
2216

    
2217
  def CheckArguments(self):
2218
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2219
    if node_name is None:
2220
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
2221
    self.op.node_name = node_name
2222
    _CheckBooleanOpField(self.op, 'master_candidate')
2223
    _CheckBooleanOpField(self.op, 'offline')
2224
    if self.op.master_candidate is None and self.op.offline is None:
2225
      raise errors.OpPrereqError("Please pass at least one modification")
2226
    if self.op.offline == True and self.op.master_candidate == True:
2227
      raise errors.OpPrereqError("Can't set the node into offline and"
2228
                                 " master_candidate at the same time")
2229

    
2230
  def ExpandNames(self):
2231
    self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
2232

    
2233
  def BuildHooksEnv(self):
2234
    """Build hooks env.
2235

2236
    This runs on the master node.
2237

2238
    """
2239
    env = {
2240
      "OP_TARGET": self.op.node_name,
2241
      "MASTER_CANDIDATE": str(self.op.master_candidate),
2242
      "OFFLINE": str(self.op.offline),
2243
      }
2244
    nl = [self.cfg.GetMasterNode(),
2245
          self.op.node_name]
2246
    return env, nl, nl
2247

    
2248
  def CheckPrereq(self):
2249
    """Check prerequisites.
2250

2251
    This only checks the instance list against the existing names.
2252

2253
    """
2254
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
2255

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

    
2272
    if (self.op.master_candidate == True and node.offline and
2273
        not self.op.offline == False):
2274
      raise errors.OpPrereqError("Can't set an offline node to"
2275
                                 " master_candidate")
2276

    
2277
    return
2278

    
2279
  def Exec(self, feedback_fn):
2280
    """Modifies a node.
2281

2282
    """
2283
    node = self.node
2284

    
2285
    result = []
2286

    
2287
    if self.op.offline is not None:
2288
      node.offline = self.op.offline
2289
      result.append(("offline", str(self.op.offline)))
2290
      if self.op.offline == True and node.master_candidate:
2291
        node.master_candidate = False
2292
        result.append(("master_candidate", "auto-demotion due to offline"))
2293

    
2294
    if self.op.master_candidate is not None:
2295
      node.master_candidate = self.op.master_candidate
2296
      result.append(("master_candidate", str(self.op.master_candidate)))
2297
      if self.op.master_candidate == False:
2298
        rrc = self.rpc.call_node_demote_from_mc(node.name)
2299
        msg = rrc.RemoteFailMsg()
2300
        if msg:
2301
          self.LogWarning("Node failed to demote itself: %s" % msg)
2302

    
2303
    # this will trigger configuration file update, if needed
2304
    self.cfg.Update(node)
2305
    # this will trigger job queue propagation or cleanup
2306
    if self.op.node_name != self.cfg.GetMasterNode():
2307
      self.context.ReaddNode(node)
2308

    
2309
    return result
2310

    
2311

    
2312
class LUQueryClusterInfo(NoHooksLU):
2313
  """Query cluster configuration.
2314

2315
  """
2316
  _OP_REQP = []
2317
  REQ_BGL = False
2318

    
2319
  def ExpandNames(self):
2320
    self.needed_locks = {}
2321

    
2322
  def CheckPrereq(self):
2323
    """No prerequsites needed for this LU.
2324

2325
    """
2326
    pass
2327

    
2328
  def Exec(self, feedback_fn):
2329
    """Return cluster config.
2330

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

    
2350
    return result
2351

    
2352

    
2353
class LUQueryConfigValues(NoHooksLU):
2354
  """Return configuration values.
2355

2356
  """
2357
  _OP_REQP = []
2358
  REQ_BGL = False
2359
  _FIELDS_DYNAMIC = utils.FieldSet()
2360
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag")
2361

    
2362
  def ExpandNames(self):
2363
    self.needed_locks = {}
2364

    
2365
    _CheckOutputFields(static=self._FIELDS_STATIC,
2366
                       dynamic=self._FIELDS_DYNAMIC,
2367
                       selected=self.op.output_fields)
2368

    
2369
  def CheckPrereq(self):
2370
    """No prerequisites.
2371

2372
    """
2373
    pass
2374

    
2375
  def Exec(self, feedback_fn):
2376
    """Dump a representation of the cluster config to the standard output.
2377

2378
    """
2379
    values = []
2380
    for field in self.op.output_fields:
2381
      if field == "cluster_name":
2382
        entry = self.cfg.GetClusterName()
2383
      elif field == "master_node":
2384
        entry = self.cfg.GetMasterNode()
2385
      elif field == "drain_flag":
2386
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
2387
      else:
2388
        raise errors.ParameterError(field)
2389
      values.append(entry)
2390
    return values
2391

    
2392

    
2393
class LUActivateInstanceDisks(NoHooksLU):
2394
  """Bring up an instance's disks.
2395

2396
  """
2397
  _OP_REQP = ["instance_name"]
2398
  REQ_BGL = False
2399

    
2400
  def ExpandNames(self):
2401
    self._ExpandAndLockInstance()
2402
    self.needed_locks[locking.LEVEL_NODE] = []
2403
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2404

    
2405
  def DeclareLocks(self, level):
2406
    if level == locking.LEVEL_NODE:
2407
      self._LockInstancesNodes()
2408

    
2409
  def CheckPrereq(self):
2410
    """Check prerequisites.
2411

2412
    This checks that the instance is in the cluster.
2413

2414
    """
2415
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2416
    assert self.instance is not None, \
2417
      "Cannot retrieve locked instance %s" % self.op.instance_name
2418
    _CheckNodeOnline(self, self.instance.primary_node)
2419

    
2420
  def Exec(self, feedback_fn):
2421
    """Activate the disks.
2422

2423
    """
2424
    disks_ok, disks_info = _AssembleInstanceDisks(self, self.instance)
2425
    if not disks_ok:
2426
      raise errors.OpExecError("Cannot activate block devices")
2427

    
2428
    return disks_info
2429

    
2430

    
2431
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False):
2432
  """Prepare the block devices for an instance.
2433

2434
  This sets up the block devices on all nodes.
2435

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

2447
  """
2448
  device_info = []
2449
  disks_ok = True
2450
  iname = instance.name
2451
  # With the two passes mechanism we try to reduce the window of
2452
  # opportunity for the race condition of switching DRBD to primary
2453
  # before handshaking occured, but we do not eliminate it
2454

    
2455
  # The proper fix would be to wait (with some limits) until the
2456
  # connection has been made and drbd transitions from WFConnection
2457
  # into any other network-connected state (Connected, SyncTarget,
2458
  # SyncSource, etc.)
2459

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

    
2473
  # FIXME: race condition on drbd migration to primary
2474

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

    
2490
  # leave the disks configured for the primary node
2491
  # this is a workaround that would be fixed better by
2492
  # improving the logical/physical id handling
2493
  for disk in instance.disks:
2494
    lu.cfg.SetDiskID(disk, instance.primary_node)
2495

    
2496
  return disks_ok, device_info
2497

    
2498

    
2499
def _StartInstanceDisks(lu, instance, force):
2500
  """Start the disks of an instance.
2501

2502
  """
2503
  disks_ok, dummy = _AssembleInstanceDisks(lu, instance,
2504
                                           ignore_secondaries=force)
2505
  if not disks_ok:
2506
    _ShutdownInstanceDisks(lu, instance)
2507
    if force is not None and not force:
2508
      lu.proc.LogWarning("", hint="If the message above refers to a"
2509
                         " secondary node,"
2510
                         " you can retry the operation using '--force'.")
2511
    raise errors.OpExecError("Disk consistency error")
2512

    
2513

    
2514
class LUDeactivateInstanceDisks(NoHooksLU):
2515
  """Shutdown an instance's disks.
2516

2517
  """
2518
  _OP_REQP = ["instance_name"]
2519
  REQ_BGL = False
2520

    
2521
  def ExpandNames(self):
2522
    self._ExpandAndLockInstance()
2523
    self.needed_locks[locking.LEVEL_NODE] = []
2524
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2525

    
2526
  def DeclareLocks(self, level):
2527
    if level == locking.LEVEL_NODE:
2528
      self._LockInstancesNodes()
2529

    
2530
  def CheckPrereq(self):
2531
    """Check prerequisites.
2532

2533
    This checks that the instance is in the cluster.
2534

2535
    """
2536
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2537
    assert self.instance is not None, \
2538
      "Cannot retrieve locked instance %s" % self.op.instance_name
2539

    
2540
  def Exec(self, feedback_fn):
2541
    """Deactivate the disks
2542

2543
    """
2544
    instance = self.instance
2545
    _SafeShutdownInstanceDisks(self, instance)
2546

    
2547

    
2548
def _SafeShutdownInstanceDisks(lu, instance):
2549
  """Shutdown block devices of an instance.
2550

2551
  This function checks if an instance is running, before calling
2552
  _ShutdownInstanceDisks.
2553

2554
  """
2555
  ins_l = lu.rpc.call_instance_list([instance.primary_node],
2556
                                      [instance.hypervisor])
2557
  ins_l = ins_l[instance.primary_node]
2558
  if ins_l.failed or not isinstance(ins_l.data, list):
2559
    raise errors.OpExecError("Can't contact node '%s'" %
2560
                             instance.primary_node)
2561

    
2562
  if instance.name in ins_l.data:
2563
    raise errors.OpExecError("Instance is running, can't shutdown"
2564
                             " block devices.")
2565

    
2566
  _ShutdownInstanceDisks(lu, instance)
2567

    
2568

    
2569
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
2570
  """Shutdown block devices of an instance.
2571

2572
  This does the shutdown on all nodes of the instance.
2573

2574
  If the ignore_primary is false, errors on the primary node are
2575
  ignored.
2576

2577
  """
2578
  all_result = True
2579
  for disk in instance.disks:
2580
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
2581
      lu.cfg.SetDiskID(top_disk, node)
2582
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
2583
      msg = result.RemoteFailMsg()
2584
      if msg:
2585
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
2586
                      disk.iv_name, node, msg)
2587
        if not ignore_primary or node != instance.primary_node:
2588
          all_result = False
2589
  return all_result
2590

    
2591

    
2592
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
2593
  """Checks if a node has enough free memory.
2594

2595
  This function check if a given node has the needed amount of free
2596
  memory. In case the node has less memory or we cannot get the
2597
  information from the node, this function raise an OpPrereqError
2598
  exception.
2599

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

2613
  """
2614
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
2615
  nodeinfo[node].Raise()
2616
  free_mem = nodeinfo[node].data.get('memory_free')
2617
  if not isinstance(free_mem, int):
2618
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
2619
                             " was '%s'" % (node, free_mem))
2620
  if requested > free_mem:
2621
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
2622
                             " needed %s MiB, available %s MiB" %
2623
                             (node, reason, requested, free_mem))
2624

    
2625

    
2626
class LUStartupInstance(LogicalUnit):
2627
  """Starts an instance.
2628

2629
  """
2630
  HPATH = "instance-start"
2631
  HTYPE = constants.HTYPE_INSTANCE
2632
  _OP_REQP = ["instance_name", "force"]
2633
  REQ_BGL = False
2634

    
2635
  def ExpandNames(self):
2636
    self._ExpandAndLockInstance()
2637

    
2638
  def BuildHooksEnv(self):
2639
    """Build hooks env.
2640

2641
    This runs on master, primary and secondary nodes of the instance.
2642

2643
    """
2644
    env = {
2645
      "FORCE": self.op.force,
2646
      }
2647
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2648
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2649
    return env, nl, nl
2650

    
2651
  def CheckPrereq(self):
2652
    """Check prerequisites.
2653

2654
    This checks that the instance is in the cluster.
2655

2656
    """
2657
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2658
    assert self.instance is not None, \
2659
      "Cannot retrieve locked instance %s" % self.op.instance_name
2660

    
2661
    _CheckNodeOnline(self, instance.primary_node)
2662

    
2663
    bep = self.cfg.GetClusterInfo().FillBE(instance)
2664
    # check bridges existance
2665
    _CheckInstanceBridgesExist(self, instance)
2666

    
2667
    _CheckNodeFreeMemory(self, instance.primary_node,
2668
                         "starting instance %s" % instance.name,
2669
                         bep[constants.BE_MEMORY], instance.hypervisor)
2670

    
2671
  def Exec(self, feedback_fn):
2672
    """Start the instance.
2673

2674
    """
2675
    instance = self.instance
2676
    force = self.op.force
2677
    extra_args = getattr(self.op, "extra_args", "")
2678

    
2679
    self.cfg.MarkInstanceUp(instance.name)
2680

    
2681
    node_current = instance.primary_node
2682

    
2683
    _StartInstanceDisks(self, instance, force)
2684

    
2685
    result = self.rpc.call_instance_start(node_current, instance, extra_args)
2686
    msg = result.RemoteFailMsg()
2687
    if msg:
2688
      _ShutdownInstanceDisks(self, instance)
2689
      raise errors.OpExecError("Could not start instance: %s" % msg)
2690

    
2691

    
2692
class LURebootInstance(LogicalUnit):
2693
  """Reboot an instance.
2694

2695
  """
2696
  HPATH = "instance-reboot"
2697
  HTYPE = constants.HTYPE_INSTANCE
2698
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
2699
  REQ_BGL = False
2700

    
2701
  def ExpandNames(self):
2702
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
2703
                                   constants.INSTANCE_REBOOT_HARD,
2704
                                   constants.INSTANCE_REBOOT_FULL]:
2705
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
2706
                                  (constants.INSTANCE_REBOOT_SOFT,
2707
                                   constants.INSTANCE_REBOOT_HARD,
2708
                                   constants.INSTANCE_REBOOT_FULL))
2709
    self._ExpandAndLockInstance()
2710

    
2711
  def BuildHooksEnv(self):
2712
    """Build hooks env.
2713

2714
    This runs on master, primary and secondary nodes of the instance.
2715

2716
    """
2717
    env = {
2718
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
2719
      }
2720
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2721
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2722
    return env, nl, nl
2723

    
2724
  def CheckPrereq(self):
2725
    """Check prerequisites.
2726

2727
    This checks that the instance is in the cluster.
2728

2729
    """
2730
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2731
    assert self.instance is not None, \
2732
      "Cannot retrieve locked instance %s" % self.op.instance_name
2733

    
2734
    _CheckNodeOnline(self, instance.primary_node)
2735

    
2736
    # check bridges existance
2737
    _CheckInstanceBridgesExist(self, instance)
2738

    
2739
  def Exec(self, feedback_fn):
2740
    """Reboot the instance.
2741

2742
    """
2743
    instance = self.instance
2744
    ignore_secondaries = self.op.ignore_secondaries
2745
    reboot_type = self.op.reboot_type
2746
    extra_args = getattr(self.op, "extra_args", "")
2747

    
2748
    node_current = instance.primary_node
2749

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

    
2768
    self.cfg.MarkInstanceUp(instance.name)
2769

    
2770

    
2771
class LUShutdownInstance(LogicalUnit):
2772
  """Shutdown an instance.
2773

2774
  """
2775
  HPATH = "instance-stop"
2776
  HTYPE = constants.HTYPE_INSTANCE
2777
  _OP_REQP = ["instance_name"]
2778
  REQ_BGL = False
2779

    
2780
  def ExpandNames(self):
2781
    self._ExpandAndLockInstance()
2782

    
2783
  def BuildHooksEnv(self):
2784
    """Build hooks env.
2785

2786
    This runs on master, primary and secondary nodes of the instance.
2787

2788
    """
2789
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2790
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2791
    return env, nl, nl
2792

    
2793
  def CheckPrereq(self):
2794
    """Check prerequisites.
2795

2796
    This checks that the instance is in the cluster.
2797

2798
    """
2799
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2800
    assert self.instance is not None, \
2801
      "Cannot retrieve locked instance %s" % self.op.instance_name
2802
    _CheckNodeOnline(self, self.instance.primary_node)
2803

    
2804
  def Exec(self, feedback_fn):
2805
    """Shutdown the instance.
2806

2807
    """
2808
    instance = self.instance
2809
    node_current = instance.primary_node
2810
    self.cfg.MarkInstanceDown(instance.name)
2811
    result = self.rpc.call_instance_shutdown(node_current, instance)
2812
    if result.failed or not result.data:
2813
      self.proc.LogWarning("Could not shutdown instance")
2814

    
2815
    _ShutdownInstanceDisks(self, instance)
2816

    
2817

    
2818
class LUReinstallInstance(LogicalUnit):
2819
  """Reinstall an instance.
2820

2821
  """
2822
  HPATH = "instance-reinstall"
2823
  HTYPE = constants.HTYPE_INSTANCE
2824
  _OP_REQP = ["instance_name"]
2825
  REQ_BGL = False
2826

    
2827
  def ExpandNames(self):
2828
    self._ExpandAndLockInstance()
2829

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

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

2835
    """
2836
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2837
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2838
    return env, nl, nl
2839

    
2840
  def CheckPrereq(self):
2841
    """Check prerequisites.
2842

2843
    This checks that the instance is in the cluster and is not running.
2844

2845
    """
2846
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2847
    assert instance is not None, \
2848
      "Cannot retrieve locked instance %s" % self.op.instance_name
2849
    _CheckNodeOnline(self, instance.primary_node)
2850

    
2851
    if instance.disk_template == constants.DT_DISKLESS:
2852
      raise errors.OpPrereqError("Instance '%s' has no disks" %
2853
                                 self.op.instance_name)
2854
    if instance.admin_up:
2855
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2856
                                 self.op.instance_name)
2857
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2858
                                              instance.name,
2859
                                              instance.hypervisor)
2860
    if remote_info.failed or remote_info.data:
2861
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2862
                                 (self.op.instance_name,
2863
                                  instance.primary_node))
2864

    
2865
    self.op.os_type = getattr(self.op, "os_type", None)
2866
    if self.op.os_type is not None:
2867
      # OS verification
2868
      pnode = self.cfg.GetNodeInfo(
2869
        self.cfg.ExpandNodeName(instance.primary_node))
2870
      if pnode is None:
2871
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
2872
                                   self.op.pnode)
2873
      result = self.rpc.call_os_get(pnode.name, self.op.os_type)
2874
      result.Raise()
2875
      if not isinstance(result.data, objects.OS):
2876
        raise errors.OpPrereqError("OS '%s' not in supported OS list for"
2877
                                   " primary node"  % self.op.os_type)
2878

    
2879
    self.instance = instance
2880

    
2881
  def Exec(self, feedback_fn):
2882
    """Reinstall the instance.
2883

2884
    """
2885
    inst = self.instance
2886

    
2887
    if self.op.os_type is not None:
2888
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
2889
      inst.os = self.op.os_type
2890
      self.cfg.Update(inst)
2891

    
2892
    _StartInstanceDisks(self, inst, None)
2893
    try:
2894
      feedback_fn("Running the instance OS create scripts...")
2895
      result = self.rpc.call_instance_os_add(inst.primary_node, inst)
2896
      msg = result.RemoteFailMsg()
2897
      if msg:
2898
        raise errors.OpExecError("Could not install OS for instance %s"
2899
                                 " on node %s: %s" %
2900
                                 (inst.name, inst.primary_node, msg))
2901
    finally:
2902
      _ShutdownInstanceDisks(self, inst)
2903

    
2904

    
2905
class LURenameInstance(LogicalUnit):
2906
  """Rename an instance.
2907

2908
  """
2909
  HPATH = "instance-rename"
2910
  HTYPE = constants.HTYPE_INSTANCE
2911
  _OP_REQP = ["instance_name", "new_name"]
2912

    
2913
  def BuildHooksEnv(self):
2914
    """Build hooks env.
2915

2916
    This runs on master, primary and secondary nodes of the instance.
2917

2918
    """
2919
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2920
    env["INSTANCE_NEW_NAME"] = self.op.new_name
2921
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2922
    return env, nl, nl
2923

    
2924
  def CheckPrereq(self):
2925
    """Check prerequisites.
2926

2927
    This checks that the instance is in the cluster and is not running.
2928

2929
    """
2930
    instance = self.cfg.GetInstanceInfo(
2931
      self.cfg.ExpandInstanceName(self.op.instance_name))
2932
    if instance is None:
2933
      raise errors.OpPrereqError("Instance '%s' not known" %
2934
                                 self.op.instance_name)
2935
    _CheckNodeOnline(self, instance.primary_node)
2936

    
2937
    if instance.admin_up:
2938
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2939
                                 self.op.instance_name)
2940
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2941
                                              instance.name,
2942
                                              instance.hypervisor)
2943
    remote_info.Raise()
2944
    if remote_info.data:
2945
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2946
                                 (self.op.instance_name,
2947
                                  instance.primary_node))
2948
    self.instance = instance
2949

    
2950
    # new name verification
2951
    name_info = utils.HostInfo(self.op.new_name)
2952

    
2953
    self.op.new_name = new_name = name_info.name
2954
    instance_list = self.cfg.GetInstanceList()
2955
    if new_name in instance_list:
2956
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
2957
                                 new_name)
2958

    
2959
    if not getattr(self.op, "ignore_ip", False):
2960
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
2961
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
2962
                                   (name_info.ip, new_name))
2963

    
2964

    
2965
  def Exec(self, feedback_fn):
2966
    """Reinstall the instance.
2967

2968
    """
2969
    inst = self.instance
2970
    old_name = inst.name
2971

    
2972
    if inst.disk_template == constants.DT_FILE:
2973
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2974

    
2975
    self.cfg.RenameInstance(inst.name, self.op.new_name)
2976
    # Change the instance lock. This is definitely safe while we hold the BGL
2977
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
2978
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
2979

    
2980
    # re-read the instance from the configuration after rename
2981
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
2982

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

    
2996
      if not result.data[0]:
2997
        raise errors.OpExecError("Could not rename directory '%s' to '%s'"
2998
                                 " (but the instance has been renamed in"
2999
                                 " Ganeti)" % (old_file_storage_dir,
3000
                                               new_file_storage_dir))
3001

    
3002
    _StartInstanceDisks(self, inst, None)
3003
    try:
3004
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
3005
                                                 old_name)
3006
      msg = result.RemoteFailMsg()
3007
      if msg:
3008
        msg = ("Could not run OS rename script for instance %s on node %s"
3009
               " (but the instance has been renamed in Ganeti): %s" %
3010
               (inst.name, inst.primary_node, msg))
3011
        self.proc.LogWarning(msg)
3012
    finally:
3013
      _ShutdownInstanceDisks(self, inst)
3014

    
3015

    
3016
class LURemoveInstance(LogicalUnit):
3017
  """Remove an instance.
3018

3019
  """
3020
  HPATH = "instance-remove"
3021
  HTYPE = constants.HTYPE_INSTANCE
3022
  _OP_REQP = ["instance_name", "ignore_failures"]
3023
  REQ_BGL = False
3024

    
3025
  def ExpandNames(self):
3026
    self._ExpandAndLockInstance()
3027
    self.needed_locks[locking.LEVEL_NODE] = []
3028
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3029

    
3030
  def DeclareLocks(self, level):
3031
    if level == locking.LEVEL_NODE:
3032
      self._LockInstancesNodes()
3033

    
3034
  def BuildHooksEnv(self):
3035
    """Build hooks env.
3036

3037
    This runs on master, primary and secondary nodes of the instance.
3038

3039
    """
3040
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3041
    nl = [self.cfg.GetMasterNode()]
3042
    return env, nl, nl
3043

    
3044
  def CheckPrereq(self):
3045
    """Check prerequisites.
3046

3047
    This checks that the instance is in the cluster.
3048

3049
    """
3050
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3051
    assert self.instance is not None, \
3052
      "Cannot retrieve locked instance %s" % self.op.instance_name
3053

    
3054
  def Exec(self, feedback_fn):
3055
    """Remove the instance.
3056

3057
    """
3058
    instance = self.instance
3059
    logging.info("Shutting down instance %s on node %s",
3060
                 instance.name, instance.primary_node)
3061

    
3062
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance)
3063
    if result.failed or not result.data:
3064
      if self.op.ignore_failures:
3065
        feedback_fn("Warning: can't shutdown instance")
3066
      else:
3067
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
3068
                                 (instance.name, instance.primary_node))
3069

    
3070
    logging.info("Removing block devices for instance %s", instance.name)
3071

    
3072
    if not _RemoveDisks(self, instance):
3073
      if self.op.ignore_failures:
3074
        feedback_fn("Warning: can't remove instance's disks")
3075
      else:
3076
        raise errors.OpExecError("Can't remove instance's disks")
3077

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

    
3080
    self.cfg.RemoveInstance(instance.name)
3081
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
3082

    
3083

    
3084
class LUQueryInstances(NoHooksLU):
3085
  """Logical unit for querying instances.
3086

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

    
3107

    
3108
  def ExpandNames(self):
3109
    _CheckOutputFields(static=self._FIELDS_STATIC,
3110
                       dynamic=self._FIELDS_DYNAMIC,
3111
                       selected=self.op.output_fields)
3112

    
3113
    self.needed_locks = {}
3114
    self.share_locks[locking.LEVEL_INSTANCE] = 1
3115
    self.share_locks[locking.LEVEL_NODE] = 1
3116

    
3117
    if self.op.names:
3118
      self.wanted = _GetWantedInstances(self, self.op.names)
3119
    else:
3120
      self.wanted = locking.ALL_SET
3121

    
3122
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3123
    self.do_locking = self.do_node_query and self.op.use_locking
3124
    if self.do_locking:
3125
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
3126
      self.needed_locks[locking.LEVEL_NODE] = []
3127
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3128

    
3129
  def DeclareLocks(self, level):
3130
    if level == locking.LEVEL_NODE and self.do_locking:
3131
      self._LockInstancesNodes()
3132

    
3133
  def CheckPrereq(self):
3134
    """Check prerequisites.
3135

3136
    """
3137
    pass
3138

    
3139
  def Exec(self, feedback_fn):
3140
    """Computes the list of nodes and their attributes.
3141

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

    
3163
    instance_list = [all_info[iname] for iname in instance_names]
3164

    
3165
    # begin data gathering
3166

    
3167
    nodes = frozenset([inst.primary_node for inst in instance_list])
3168
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
3169

    
3170
    bad_nodes = []
3171
    off_nodes = []
3172
    if self.do_node_query:
3173
      live_data = {}
3174
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
3175
      for name in nodes:
3176
        result = node_data[name]
3177
        if result.offline:
3178
          # offline nodes will be in both lists
3179
          off_nodes.append(name)
3180
        if result.failed:
3181
          bad_nodes.append(name)
3182
        else:
3183
          if result.data:
3184
            live_data.update(result.data)
3185
            # else no instance is alive
3186
    else:
3187
      live_data = dict([(name, {}) for name in instance_names])
3188

    
3189
    # end data gathering
3190

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

    
3319
    return output
3320

    
3321

    
3322
class LUFailoverInstance(LogicalUnit):
3323
  """Failover an instance.
3324

3325
  """
3326
  HPATH = "instance-failover"
3327
  HTYPE = constants.HTYPE_INSTANCE
3328
  _OP_REQP = ["instance_name", "ignore_consistency"]
3329
  REQ_BGL = False
3330

    
3331
  def ExpandNames(self):
3332
    self._ExpandAndLockInstance()
3333
    self.needed_locks[locking.LEVEL_NODE] = []
3334
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3335

    
3336
  def DeclareLocks(self, level):
3337
    if level == locking.LEVEL_NODE:
3338
      self._LockInstancesNodes()
3339

    
3340
  def BuildHooksEnv(self):
3341
    """Build hooks env.
3342

3343
    This runs on master, primary and secondary nodes of the instance.
3344

3345
    """
3346
    env = {
3347
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
3348
      }
3349
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3350
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
3351
    return env, nl, nl
3352

    
3353
  def CheckPrereq(self):
3354
    """Check prerequisites.
3355

3356
    This checks that the instance is in the cluster.
3357

3358
    """
3359
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3360
    assert self.instance is not None, \
3361
      "Cannot retrieve locked instance %s" % self.op.instance_name
3362

    
3363
    bep = self.cfg.GetClusterInfo().FillBE(instance)
3364
    if instance.disk_template not in constants.DTS_NET_MIRROR:
3365
      raise errors.OpPrereqError("Instance's disk layout is not"
3366
                                 " network mirrored, cannot failover.")
3367

    
3368
    secondary_nodes = instance.secondary_nodes
3369
    if not secondary_nodes:
3370
      raise errors.ProgrammerError("no secondary node but using "
3371
                                   "a mirrored disk template")
3372

    
3373
    target_node = secondary_nodes[0]
3374
    _CheckNodeOnline(self, target_node)
3375
    # check memory requirements on the secondary node
3376
    _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
3377
                         instance.name, bep[constants.BE_MEMORY],
3378
                         instance.hypervisor)
3379

    
3380
    # check bridge existance
3381
    brlist = [nic.bridge for nic in instance.nics]
3382
    result = self.rpc.call_bridges_exist(target_node, brlist)
3383
    result.Raise()
3384
    if not result.data:
3385
      raise errors.OpPrereqError("One or more target bridges %s does not"
3386
                                 " exist on destination node '%s'" %
3387
                                 (brlist, target_node))
3388

    
3389
  def Exec(self, feedback_fn):
3390
    """Failover an instance.
3391

3392
    The failover is done by shutting it down on its present node and
3393
    starting it on the secondary.
3394

3395
    """
3396
    instance = self.instance
3397

    
3398
    source_node = instance.primary_node
3399
    target_node = instance.secondary_nodes[0]
3400

    
3401
    feedback_fn("* checking disk consistency between source and target")
3402
    for dev in instance.disks:
3403
      # for drbd, these are drbd over lvm
3404
      if not _CheckDiskConsistency(self, dev, target_node, False):
3405
        if instance.admin_up and not self.op.ignore_consistency:
3406
          raise errors.OpExecError("Disk %s is degraded on target node,"
3407
                                   " aborting failover." % dev.iv_name)
3408

    
3409
    feedback_fn("* shutting down instance on source node")
3410
    logging.info("Shutting down instance %s on node %s",
3411
                 instance.name, source_node)
3412

    
3413
    result = self.rpc.call_instance_shutdown(source_node, instance)
3414
    if result.failed or not result.data:
3415
      if self.op.ignore_consistency:
3416
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
3417
                             " Proceeding"
3418
                             " anyway. Please make sure node %s is down",
3419
                             instance.name, source_node, source_node)
3420
      else:
3421
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
3422
                                 (instance.name, source_node))
3423

    
3424
    feedback_fn("* deactivating the instance's disks on source node")
3425
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
3426
      raise errors.OpExecError("Can't shut down the instance's disks.")
3427

    
3428
    instance.primary_node = target_node
3429
    # distribute new instance config to the other nodes
3430
    self.cfg.Update(instance)
3431

    
3432
    # Only start the instance if it's marked as up
3433
    if instance.admin_up:
3434
      feedback_fn("* activating the instance's disks on target node")
3435
      logging.info("Starting instance %s on node %s",
3436
                   instance.name, target_node)
3437

    
3438
      disks_ok, dummy = _AssembleInstanceDisks(self, instance,
3439
                                               ignore_secondaries=True)
3440
      if not disks_ok:
3441
        _ShutdownInstanceDisks(self, instance)
3442
        raise errors.OpExecError("Can't activate the instance's disks")
3443

    
3444
      feedback_fn("* starting the instance on the target node")
3445
      result = self.rpc.call_instance_start(target_node, instance, None)
3446
      msg = result.RemoteFailMsg()
3447
      if msg:
3448
        _ShutdownInstanceDisks(self, instance)
3449
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
3450
                                 (instance.name, target_node, msg))
3451

    
3452

    
3453
class LUMigrateInstance(LogicalUnit):
3454
  """Migrate an instance.
3455

3456
  This is migration without shutting down, compared to the failover,
3457
  which is done with shutdown.
3458

3459
  """
3460
  HPATH = "instance-migrate"
3461
  HTYPE = constants.HTYPE_INSTANCE
3462
  _OP_REQP = ["instance_name", "live", "cleanup"]
3463

    
3464
  REQ_BGL = False
3465

    
3466
  def ExpandNames(self):
3467
    self._ExpandAndLockInstance()
3468
    self.needed_locks[locking.LEVEL_NODE] = []
3469
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3470

    
3471
  def DeclareLocks(self, level):
3472
    if level == locking.LEVEL_NODE:
3473
      self._LockInstancesNodes()
3474

    
3475
  def BuildHooksEnv(self):
3476
    """Build hooks env.
3477

3478
    This runs on master, primary and secondary nodes of the instance.
3479

3480
    """
3481
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3482
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
3483
    return env, nl, nl
3484

    
3485
  def CheckPrereq(self):
3486
    """Check prerequisites.
3487

3488
    This checks that the instance is in the cluster.
3489

3490
    """
3491
    instance = self.cfg.GetInstanceInfo(
3492
      self.cfg.ExpandInstanceName(self.op.instance_name))
3493
    if instance is None:
3494
      raise errors.OpPrereqError("Instance '%s' not known" %
3495
                                 self.op.instance_name)
3496

    
3497
    if instance.disk_template != constants.DT_DRBD8:
3498
      raise errors.OpPrereqError("Instance's disk layout is not"
3499
                                 " drbd8, cannot migrate.")
3500

    
3501
    secondary_nodes = instance.secondary_nodes
3502
    if not secondary_nodes:
3503
      raise errors.ProgrammerError("no secondary node but using "
3504
                                   "drbd8 disk template")
3505

    
3506
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
3507

    
3508
    target_node = secondary_nodes[0]
3509
    # check memory requirements on the secondary node
3510
    _CheckNodeFreeMemory(self, target_node, "migrating instance %s" %
3511
                         instance.name, i_be[constants.BE_MEMORY],
3512
                         instance.hypervisor)
3513

    
3514
    # check bridge existance
3515
    brlist = [nic.bridge for nic in instance.nics]
3516
    result = self.rpc.call_bridges_exist(target_node, brlist)
3517
    if result.failed or not result.data:
3518
      raise errors.OpPrereqError("One or more target bridges %s does not"
3519
                                 " exist on destination node '%s'" %
3520
                                 (brlist, target_node))
3521

    
3522
    if not self.op.cleanup:
3523
      result = self.rpc.call_instance_migratable(instance.primary_node,
3524
                                                 instance)
3525
      msg = result.RemoteFailMsg()
3526
      if msg:
3527
        raise errors.OpPrereqError("Can't migrate: %s - please use failover" %
3528
                                   msg)
3529

    
3530
    self.instance = instance
3531

    
3532
  def _WaitUntilSync(self):
3533
    """Poll with custom rpc for disk sync.
3534

3535
    This uses our own step-based rpc call.
3536

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

    
3560
  def _EnsureSecondary(self, node):
3561
    """Demote a node to secondary.
3562

3563
    """
3564
    self.feedback_fn("* switching node %s to secondary mode" % node)
3565

    
3566
    for dev in self.instance.disks:
3567
      self.cfg.SetDiskID(dev, node)
3568

    
3569
    result = self.rpc.call_blockdev_close(node, self.instance.name,
3570
                                          self.instance.disks)
3571
    msg = result.RemoteFailMsg()
3572
    if msg:
3573
      raise errors.OpExecError("Cannot change disk to secondary on node %s,"
3574
                               " error %s" % (node, msg))
3575

    
3576
  def _GoStandalone(self):
3577
    """Disconnect from the network.
3578

3579
    """
3580
    self.feedback_fn("* changing into standalone mode")
3581
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
3582
                                               self.instance.disks)
3583
    for node, nres in result.items():
3584
      msg = nres.RemoteFailMsg()
3585
      if msg:
3586
        raise errors.OpExecError("Cannot disconnect disks node %s,"
3587
                                 " error %s" % (node, msg))
3588

    
3589
  def _GoReconnect(self, multimaster):
3590
    """Reconnect to the network.
3591

3592
    """
3593
    if multimaster:
3594
      msg = "dual-master"
3595
    else:
3596
      msg = "single-master"
3597
    self.feedback_fn("* changing disks into %s mode" % msg)
3598
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
3599
                                           self.instance.disks,
3600
                                           self.instance.name, multimaster)
3601
    for node, nres in result.items():
3602
      msg = nres.RemoteFailMsg()
3603
      if msg:
3604
        raise errors.OpExecError("Cannot change disks config on node %s,"
3605
                                 " error: %s" % (node, msg))
3606

    
3607
  def _ExecCleanup(self):
3608
    """Try to cleanup after a failed migration.
3609

3610
    The cleanup is done by:
3611
      - check that the instance is running only on one node
3612
        (and update the config if needed)
3613
      - change disks on its secondary node to secondary
3614
      - wait until disks are fully synchronized
3615
      - disconnect from the network
3616
      - change disks into single-master mode
3617
      - wait again until disks are fully synchronized
3618

3619
    """
3620
    instance = self.instance
3621
    target_node = self.target_node
3622
    source_node = self.source_node
3623

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

    
3634
    runningon_source = instance.name in ins_l[source_node].data
3635
    runningon_target = instance.name in ins_l[target_node].data
3636

    
3637
    if runningon_source and runningon_target:
3638
      raise errors.OpExecError("Instance seems to be running on two nodes,"
3639
                               " or the hypervisor is confused. You will have"
3640
                               " to ensure manually that it runs only on one"
3641
                               " and restart this operation.")
3642

    
3643
    if not (runningon_source or runningon_target):
3644
      raise errors.OpExecError("Instance does not seem to be running at all."
3645
                               " In this case, it's safer to repair by"
3646
                               " running 'gnt-instance stop' to ensure disk"
3647
                               " shutdown, and then restarting it.")
3648

    
3649
    if runningon_target:
3650
      # the migration has actually succeeded, we need to update the config
3651
      self.feedback_fn("* instance running on secondary node (%s),"
3652
                       " updating config" % target_node)
3653
      instance.primary_node = target_node
3654
      self.cfg.Update(instance)
3655
      demoted_node = source_node
3656
    else:
3657
      self.feedback_fn("* instance confirmed to be running on its"
3658
                       " primary node (%s)" % source_node)
3659
      demoted_node = target_node
3660

    
3661
    self._EnsureSecondary(demoted_node)
3662
    try:
3663
      self._WaitUntilSync()
3664
    except errors.OpExecError:
3665
      # we ignore here errors, since if the device is standalone, it
3666
      # won't be able to sync
3667
      pass
3668
    self._GoStandalone()
3669
    self._GoReconnect(False)
3670
    self._WaitUntilSync()
3671

    
3672
    self.feedback_fn("* done")
3673

    
3674
  def _RevertDiskStatus(self):
3675
    """Try to revert the disk status after a failed migration.
3676

3677
    """
3678
    target_node = self.target_node
3679
    try:
3680
      self._EnsureSecondary(target_node)
3681
      self._GoStandalone()
3682
      self._GoReconnect(False)
3683
      self._WaitUntilSync()
3684
    except errors.OpExecError, err:
3685
      self.LogWarning("Migration failed and I can't reconnect the"
3686
                      " drives: error '%s'\n"
3687
                      "Please look and recover the instance status" %
3688
                      str(err))
3689

    
3690
  def _AbortMigration(self):
3691
    """Call the hypervisor code to abort a started migration.
3692

3693
    """
3694
    instance = self.instance
3695
    target_node = self.target_node
3696
    migration_info = self.migration_info
3697

    
3698
    abort_result = self.rpc.call_finalize_migration(target_node,
3699
                                                    instance,
3700
                                                    migration_info,
3701
                                                    False)
3702
    abort_msg = abort_result.RemoteFailMsg()
3703
    if abort_msg:
3704
      logging.error("Aborting migration failed on target node %s: %s" %
3705
                    (target_node, abort_msg))
3706
      # Don't raise an exception here, as we stil have to try to revert the
3707
      # disk status, even if this step failed.
3708

    
3709
  def _ExecMigration(self):
3710
    """Migrate an instance.
3711

3712
    The migrate is done by:
3713
      - change the disks into dual-master mode
3714
      - wait until disks are fully synchronized again
3715
      - migrate the instance
3716
      - change disks on the new secondary node (the old primary) to secondary
3717
      - wait until disks are fully synchronized
3718
      - change disks into single-master mode
3719

3720
    """
3721
    instance = self.instance
3722
    target_node = self.target_node
3723
    source_node = self.source_node
3724

    
3725
    self.feedback_fn("* checking disk consistency between source and target")
3726
    for dev in instance.disks:
3727
      if not _CheckDiskConsistency(self, dev, target_node, False):
3728
        raise errors.OpExecError("Disk %s is degraded or not fully"
3729
                                 " synchronized on target node,"
3730
                                 " aborting migrate." % dev.iv_name)
3731

    
3732
    # First get the migration information from the remote node
3733
    result = self.rpc.call_migration_info(source_node, instance)
3734
    msg = result.RemoteFailMsg()
3735
    if msg:
3736
      log_err = ("Failed fetching source migration information from %s: %s" %
3737
                 (source_node, msg))
3738
      logging.error(log_err)
3739
      raise errors.OpExecError(log_err)
3740

    
3741
    self.migration_info = migration_info = result.payload
3742

    
3743
    # Then switch the disks to master/master mode
3744
    self._EnsureSecondary(target_node)
3745
    self._GoStandalone()
3746
    self._GoReconnect(True)
3747
    self._WaitUntilSync()
3748

    
3749
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
3750
    result = self.rpc.call_accept_instance(target_node,
3751
                                           instance,
3752
                                           migration_info,
3753
                                           self.nodes_ip[target_node])
3754

    
3755
    msg = result.RemoteFailMsg()
3756
    if msg:
3757
      logging.error("Instance pre-migration failed, trying to revert"
3758
                    " disk status: %s", msg)
3759
      self._AbortMigration()
3760
      self._RevertDiskStatus()
3761
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
3762
                               (instance.name, msg))
3763

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

    
3779
    instance.primary_node = target_node
3780
    # distribute new instance config to the other nodes
3781
    self.cfg.Update(instance)
3782

    
3783
    result = self.rpc.call_finalize_migration(target_node,
3784
                                              instance,
3785
                                              migration_info,
3786
                                              True)
3787
    msg = result.RemoteFailMsg()
3788
    if msg:
3789
      logging.error("Instance migration succeeded, but finalization failed:"
3790
                    " %s" % msg)
3791
      raise errors.OpExecError("Could not finalize instance migration: %s" %
3792
                               msg)
3793

    
3794
    self._EnsureSecondary(source_node)
3795
    self._WaitUntilSync()
3796
    self._GoStandalone()
3797
    self._GoReconnect(False)
3798
    self._WaitUntilSync()
3799

    
3800
    self.feedback_fn("* done")
3801

    
3802
  def Exec(self, feedback_fn):
3803
    """Perform the migration.
3804

3805
    """
3806
    self.feedback_fn = feedback_fn
3807

    
3808
    self.source_node = self.instance.primary_node
3809
    self.target_node = self.instance.secondary_nodes[0]
3810
    self.all_nodes = [self.source_node, self.target_node]
3811
    self.nodes_ip = {
3812
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
3813
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
3814
      }
3815
    if self.op.cleanup:
3816
      return self._ExecCleanup()
3817
    else:
3818
      return self._ExecMigration()
3819

    
3820

    
3821
def _CreateBlockDev(lu, node, instance, device, force_create,
3822
                    info, force_open):
3823
  """Create a tree of block devices on a given node.
3824

3825
  If this device type has to be created on secondaries, create it and
3826
  all its children.
3827

3828
  If not, just recurse to children keeping the same 'force' value.
3829

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

3848
  """
3849
  if device.CreateOnSecondary():
3850
    force_create = True
3851

    
3852
  if device.children:
3853
    for child in device.children:
3854
      _CreateBlockDev(lu, node, instance, child, force_create,
3855
                      info, force_open)
3856

    
3857
  if not force_create:
3858
    return
3859

    
3860
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
3861

    
3862

    
3863
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
3864
  """Create a single block device on a given node.
3865

3866
  This will not recurse over children of the device, so they must be
3867
  created in advance.
3868

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

3883
  """
3884
  lu.cfg.SetDiskID(device, node)
3885
  result = lu.rpc.call_blockdev_create(node, device, device.size,
3886
                                       instance.name, force_open, info)
3887
  msg = result.RemoteFailMsg()
3888
  if msg:
3889
    raise errors.OpExecError("Can't create block device %s on"
3890
                             " node %s for instance %s: %s" %
3891
                             (device, node, instance.name, msg))
3892
  if device.physical_id is None:
3893
    device.physical_id = result.payload
3894

    
3895

    
3896
def _GenerateUniqueNames(lu, exts):
3897
  """Generate a suitable LV name.
3898

3899
  This will generate a logical volume name for the given instance.
3900

3901
  """
3902
  results = []
3903
  for val in exts:
3904
    new_id = lu.cfg.GenerateUniqueID()
3905
    results.append("%s%s" % (new_id, val))
3906
  return results
3907

    
3908

    
3909
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
3910
                         p_minor, s_minor):
3911
  """Generate a drbd8 device complete with its children.
3912

3913
  """
3914
  port = lu.cfg.AllocatePort()
3915
  vgname = lu.cfg.GetVGName()
3916
  shared_secret = lu.cfg.GenerateDRBDSecret()
3917
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
3918
                          logical_id=(vgname, names[0]))
3919
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
3920
                          logical_id=(vgname, names[1]))
3921
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
3922
                          logical_id=(primary, secondary, port,
3923
                                      p_minor, s_minor,
3924
                                      shared_secret),
3925
                          children=[dev_data, dev_meta],
3926
                          iv_name=iv_name)
3927
  return drbd_dev
3928

    
3929

    
3930
def _GenerateDiskTemplate(lu, template_name,
3931
                          instance_name, primary_node,
3932
                          secondary_nodes, disk_info,
3933
                          file_storage_dir, file_driver,
3934
                          base_index):
3935
  """Generate the entire disk layout for a given template type.
3936

3937
  """
3938
  #TODO: compute space requirements
3939

    
3940
  vgname = lu.cfg.GetVGName()
3941
  disk_count = len(disk_info)
3942
  disks = []
3943
  if template_name == constants.DT_DISKLESS:
3944
    pass
3945
  elif template_name == constants.DT_PLAIN:
3946
    if len(secondary_nodes) != 0:
3947
      raise errors.ProgrammerError("Wrong template configuration")
3948

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

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

    
3982
    for idx, disk in enumerate(disk_info):
3983
      disk_index = idx + base_index
3984
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
3985
                              iv_name="disk/%d" % disk_index,
3986
                              logical_id=(file_driver,
3987
                                          "%s/disk%d" % (file_storage_dir,
3988
                                                         idx)),
3989
                              mode=disk["mode"])
3990
      disks.append(disk_dev)
3991
  else:
3992
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
3993