Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 32388e6d

History | View | Annotate | Download (229.4 kB)

1
#
2
#
3

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

    
21

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

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

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

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

    
48

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

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

61
  Note that all commands require root permissions.
62

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

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

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

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

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

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

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

    
109
  ssh = property(fget=__GetSSH)
110

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

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

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

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

126
    """
127
    pass
128

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

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

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

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

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

150
    Examples::
151

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

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

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

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

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

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

189
    """
190

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

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

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

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

205
    """
206
    raise NotImplementedError
207

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

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

215
    """
216
    raise NotImplementedError
217

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

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

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

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

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

237
    """
238
    raise NotImplementedError
239

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

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

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

258
    """
259
    return lu_result
260

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
326
    del self.recalculate_locks[locking.LEVEL_NODE]
327

    
328

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

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

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

    
339

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

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

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

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

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

    
366
  return utils.NiceSort(wanted)
367

    
368

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

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

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

    
385
  if instances:
386
    wanted = []
387

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

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

    
398

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

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

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

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

    
417

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

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

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

    
431

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

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

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

    
443

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

448
  This builds the hook environment from individual variables.
449

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

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

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

    
493
  env["INSTANCE_NIC_COUNT"] = nic_count
494

    
495
  return env
496

    
497

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

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

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

    
528

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

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

    
544

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

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

    
558

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

562
  """
563
  _OP_REQP = []
564

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

568
    This checks whether the cluster is empty.
569

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

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

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

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

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

    
598

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

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

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

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

620
    Test list:
621

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

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

638
    """
639
    node = nodeinfo.name
640

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

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

    
653
    if local_version != remote_version:
654
      feedback_fn("  - ERROR: sw version mismatch: master %s, node(%s) %s" %
655
                      (local_version, node, remote_version))
656
      return True
657

    
658
    # checks vg existance and size > 20G
659

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

    
673
    # checks config file checksum
674

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

    
702
    # checks ssh to any
703

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

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

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

    
732
    # check used drbd list
733
    used_minors = node_result.get(constants.NV_DRBDLIST, [])
734
    for minor, (iname, must_exist) in drbd_map.items():
735
      if minor not in used_minors and must_exist:
736
        feedback_fn("  - ERROR: drbd minor %d of instance %s is not active" %
737
                    (minor, iname))
738
        bad = True
739
    for minor in used_minors:
740
      if minor not in drbd_map:
741
        feedback_fn("  - ERROR: unallocated drbd minor %d is in use" % minor)
742
        bad = True
743

    
744
    return bad
745

    
746
  def _VerifyInstance(self, instance, instanceconfig, node_vol_is,
747
                      node_instance, feedback_fn, n_offline):
748
    """Verify an instance.
749

750
    This function checks to see if the required block devices are
751
    available on the instance's node.
752

753
    """
754
    bad = False
755

    
756
    node_current = instanceconfig.primary_node
757

    
758
    node_vol_should = {}
759
    instanceconfig.MapLVsByNode(node_vol_should)
760

    
761
    for node in node_vol_should:
762
      if node in n_offline:
763
        # ignore missing volumes on offline nodes
764
        continue
765
      for volume in node_vol_should[node]:
766
        if node not in node_vol_is or volume not in node_vol_is[node]:
767
          feedback_fn("  - ERROR: volume %s missing on node %s" %
768
                          (volume, node))
769
          bad = True
770

    
771
    if not instanceconfig.status == 'down':
772
      if ((node_current not in node_instance or
773
          not instance in node_instance[node_current]) and
774
          node_current not in n_offline):
775
        feedback_fn("  - ERROR: instance %s not running on node %s" %
776
                        (instance, node_current))
777
        bad = True
778

    
779
    for node in node_instance:
780
      if (not node == node_current):
781
        if instance in node_instance[node]:
782
          feedback_fn("  - ERROR: instance %s should not run on node %s" %
783
                          (instance, node))
784
          bad = True
785

    
786
    return bad
787

    
788
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is, feedback_fn):
789
    """Verify if there are any unknown volumes in the cluster.
790

791
    The .os, .swap and backup volumes are ignored. All other volumes are
792
    reported as unknown.
793

794
    """
795
    bad = False
796

    
797
    for node in node_vol_is:
798
      for volume in node_vol_is[node]:
799
        if node not in node_vol_should or volume not in node_vol_should[node]:
800
          feedback_fn("  - ERROR: volume %s on node %s should not exist" %
801
                      (volume, node))
802
          bad = True
803
    return bad
804

    
805
  def _VerifyOrphanInstances(self, instancelist, node_instance, feedback_fn):
806
    """Verify the list of running instances.
807

808
    This checks what instances are running but unknown to the cluster.
809

810
    """
811
    bad = False
812
    for node in node_instance:
813
      for runninginstance in node_instance[node]:
814
        if runninginstance not in instancelist:
815
          feedback_fn("  - ERROR: instance %s on node %s should not exist" %
816
                          (runninginstance, node))
817
          bad = True
818
    return bad
819

    
820
  def _VerifyNPlusOneMemory(self, node_info, instance_cfg, feedback_fn):
821
    """Verify N+1 Memory Resilience.
822

823
    Check that if one single node dies we can still start all the instances it
824
    was primary for.
825

826
    """
827
    bad = False
828

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

    
850
  def CheckPrereq(self):
851
    """Check prerequisites.
852

853
    Transform the list of checks we're going to skip into a set and check that
854
    all its members are valid.
855

856
    """
857
    self.skip_set = frozenset(self.op.skip_checks)
858
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
859
      raise errors.OpPrereqError("Invalid checks to be skipped specified")
860

    
861
  def BuildHooksEnv(self):
862
    """Build hooks env.
863

864
    Cluster-Verify hooks just rone in the post phase and their failure makes
865
    the output be logged in the verify output and the verification to fail.
866

867
    """
868
    all_nodes = self.cfg.GetNodeList()
869
    # TODO: populate the environment with useful information for verify hooks
870
    env = {}
871
    return env, [], all_nodes
872

    
873
  def Exec(self, feedback_fn):
874
    """Verify integrity of cluster, performing various test on nodes.
875

876
    """
877
    bad = False
878
    feedback_fn("* Verifying global settings")
879
    for msg in self.cfg.VerifyConfig():
880
      feedback_fn("  - ERROR: %s" % msg)
881

    
882
    vg_name = self.cfg.GetVGName()
883
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
884
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
885
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
886
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
887
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
888
                        for iname in instancelist)
889
    i_non_redundant = [] # Non redundant instances
890
    i_non_a_balanced = [] # Non auto-balanced instances
891
    n_offline = [] # List of offline nodes
892
    node_volume = {}
893
    node_instance = {}
894
    node_info = {}
895
    instance_cfg = {}
896

    
897
    # FIXME: verify OS list
898
    # do local checksums
899
    master_files = [constants.CLUSTER_CONF_FILE]
900

    
901
    file_names = ssconf.SimpleStore().GetFileList()
902
    file_names.append(constants.SSL_CERT_FILE)
903
    file_names.append(constants.RAPI_CERT_FILE)
904
    file_names.extend(master_files)
905

    
906
    local_checksums = utils.FingerprintFiles(file_names)
907

    
908
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
909
    node_verify_param = {
910
      constants.NV_FILELIST: file_names,
911
      constants.NV_NODELIST: [node.name for node in nodeinfo
912
                              if not node.offline],
913
      constants.NV_HYPERVISOR: hypervisors,
914
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
915
                                  node.secondary_ip) for node in nodeinfo
916
                                 if not node.offline],
917
      constants.NV_LVLIST: vg_name,
918
      constants.NV_INSTANCELIST: hypervisors,
919
      constants.NV_VGLIST: None,
920
      constants.NV_VERSION: None,
921
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
922
      constants.NV_DRBDLIST: None,
923
      }
924
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
925
                                           self.cfg.GetClusterName())
926

    
927
    cluster = self.cfg.GetClusterInfo()
928
    master_node = self.cfg.GetMasterNode()
929
    all_drbd_map = self.cfg.ComputeDRBDMap()
930

    
931
    for node_i in nodeinfo:
932
      node = node_i.name
933
      nresult = all_nvinfo[node].data
934

    
935
      if node_i.offline:
936
        feedback_fn("* Skipping offline node %s" % (node,))
937
        n_offline.append(node)
938
        continue
939

    
940
      if node == master_node:
941
        ntype = "master"
942
      elif node_i.master_candidate:
943
        ntype = "master candidate"
944
      else:
945
        ntype = "regular"
946
      feedback_fn("* Verifying node %s (%s)" % (node, ntype))
947

    
948
      if all_nvinfo[node].failed or not isinstance(nresult, dict):
949
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
950
        bad = True
951
        continue
952

    
953
      node_drbd = {}
954
      for minor, instance in all_drbd_map[node].items():
955
        instance = instanceinfo[instance]
956
        node_drbd[minor] = (instance.name, instance.status == "up")
957
      result = self._VerifyNode(node_i, file_names, local_checksums,
958
                                nresult, feedback_fn, master_files,
959
                                node_drbd)
960
      bad = bad or result
961

    
962
      lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
963
      if isinstance(lvdata, basestring):
964
        feedback_fn("  - ERROR: LVM problem on node %s: %s" %
965
                    (node, lvdata.encode('string_escape')))
966
        bad = True
967
        node_volume[node] = {}
968
      elif not isinstance(lvdata, dict):
969
        feedback_fn("  - ERROR: connection to %s failed (lvlist)" % (node,))
970
        bad = True
971
        continue
972
      else:
973
        node_volume[node] = lvdata
974

    
975
      # node_instance
976
      idata = nresult.get(constants.NV_INSTANCELIST, None)
977
      if not isinstance(idata, list):
978
        feedback_fn("  - ERROR: connection to %s failed (instancelist)" %
979
                    (node,))
980
        bad = True
981
        continue
982

    
983
      node_instance[node] = idata
984

    
985
      # node_info
986
      nodeinfo = nresult.get(constants.NV_HVINFO, None)
987
      if not isinstance(nodeinfo, dict):
988
        feedback_fn("  - ERROR: connection to %s failed (hvinfo)" % (node,))
989
        bad = True
990
        continue
991

    
992
      try:
993
        node_info[node] = {
994
          "mfree": int(nodeinfo['memory_free']),
995
          "dfree": int(nresult[constants.NV_VGLIST][vg_name]),
996
          "pinst": [],
997
          "sinst": [],
998
          # dictionary holding all instances this node is secondary for,
999
          # grouped by their primary node. Each key is a cluster node, and each
1000
          # value is a list of instances which have the key as primary and the
1001
          # current node as secondary.  this is handy to calculate N+1 memory
1002
          # availability if you can only failover from a primary to its
1003
          # secondary.
1004
          "sinst-by-pnode": {},
1005
        }
1006
      except ValueError:
1007
        feedback_fn("  - ERROR: invalid value returned from node %s" % (node,))
1008
        bad = True
1009
        continue
1010

    
1011
    node_vol_should = {}
1012

    
1013
    for instance in instancelist:
1014
      feedback_fn("* Verifying instance %s" % instance)
1015
      inst_config = instanceinfo[instance]
1016
      result =  self._VerifyInstance(instance, inst_config, node_volume,
1017
                                     node_instance, feedback_fn, n_offline)
1018
      bad = bad or result
1019
      inst_nodes_offline = []
1020

    
1021
      inst_config.MapLVsByNode(node_vol_should)
1022

    
1023
      instance_cfg[instance] = inst_config
1024

    
1025
      pnode = inst_config.primary_node
1026
      if pnode in node_info:
1027
        node_info[pnode]['pinst'].append(instance)
1028
      elif pnode not in n_offline:
1029
        feedback_fn("  - ERROR: instance %s, connection to primary node"
1030
                    " %s failed" % (instance, pnode))
1031
        bad = True
1032

    
1033
      if pnode in n_offline:
1034
        inst_nodes_offline.append(pnode)
1035

    
1036
      # If the instance is non-redundant we cannot survive losing its primary
1037
      # node, so we are not N+1 compliant. On the other hand we have no disk
1038
      # templates with more than one secondary so that situation is not well
1039
      # supported either.
1040
      # FIXME: does not support file-backed instances
1041
      if len(inst_config.secondary_nodes) == 0:
1042
        i_non_redundant.append(instance)
1043
      elif len(inst_config.secondary_nodes) > 1:
1044
        feedback_fn("  - WARNING: multiple secondaries for instance %s"
1045
                    % instance)
1046

    
1047
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1048
        i_non_a_balanced.append(instance)
1049

    
1050
      for snode in inst_config.secondary_nodes:
1051
        if snode in node_info:
1052
          node_info[snode]['sinst'].append(instance)
1053
          if pnode not in node_info[snode]['sinst-by-pnode']:
1054
            node_info[snode]['sinst-by-pnode'][pnode] = []
1055
          node_info[snode]['sinst-by-pnode'][pnode].append(instance)
1056
        elif snode not in n_offline:
1057
          feedback_fn("  - ERROR: instance %s, connection to secondary node"
1058
                      " %s failed" % (instance, snode))
1059
          bad = True
1060
        if snode in n_offline:
1061
          inst_nodes_offline.append(snode)
1062

    
1063
      if inst_nodes_offline:
1064
        # warn that the instance lives on offline nodes, and set bad=True
1065
        feedback_fn("  - ERROR: instance lives on offline node(s) %s" %
1066
                    ", ".join(inst_nodes_offline))
1067
        bad = True
1068

    
1069
    feedback_fn("* Verifying orphan volumes")
1070
    result = self._VerifyOrphanVolumes(node_vol_should, node_volume,
1071
                                       feedback_fn)
1072
    bad = bad or result
1073

    
1074
    feedback_fn("* Verifying remaining instances")
1075
    result = self._VerifyOrphanInstances(instancelist, node_instance,
1076
                                         feedback_fn)
1077
    bad = bad or result
1078

    
1079
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1080
      feedback_fn("* Verifying N+1 Memory redundancy")
1081
      result = self._VerifyNPlusOneMemory(node_info, instance_cfg, feedback_fn)
1082
      bad = bad or result
1083

    
1084
    feedback_fn("* Other Notes")
1085
    if i_non_redundant:
1086
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1087
                  % len(i_non_redundant))
1088

    
1089
    if i_non_a_balanced:
1090
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1091
                  % len(i_non_a_balanced))
1092

    
1093
    if n_offline:
1094
      feedback_fn("  - NOTICE: %d offline node(s) found." % len(n_offline))
1095

    
1096
    return not bad
1097

    
1098
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1099
    """Analize the post-hooks' result
1100

1101
    This method analyses the hook result, handles it, and sends some
1102
    nicely-formatted feedback back to the user.
1103

1104
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1105
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1106
    @param hooks_results: the results of the multi-node hooks rpc call
1107
    @param feedback_fn: function used send feedback back to the caller
1108
    @param lu_result: previous Exec result
1109
    @return: the new Exec result, based on the previous result
1110
        and hook results
1111

1112
    """
1113
    # We only really run POST phase hooks, and are only interested in
1114
    # their results
1115
    if phase == constants.HOOKS_PHASE_POST:
1116
      # Used to change hooks' output to proper indentation
1117
      indent_re = re.compile('^', re.M)
1118
      feedback_fn("* Hooks Results")
1119
      if not hooks_results:
1120
        feedback_fn("  - ERROR: general communication failure")
1121
        lu_result = 1
1122
      else:
1123
        for node_name in hooks_results:
1124
          show_node_header = True
1125
          res = hooks_results[node_name]
1126
          if res.failed or res.data is False or not isinstance(res.data, list):
1127
            if res.offline:
1128
              # no need to warn or set fail return value
1129
              continue
1130
            feedback_fn("    Communication failure in hooks execution")
1131
            lu_result = 1
1132
            continue
1133
          for script, hkr, output in res.data:
1134
            if hkr == constants.HKR_FAIL:
1135
              # The node header is only shown once, if there are
1136
              # failing hooks on that node
1137
              if show_node_header:
1138
                feedback_fn("  Node %s:" % node_name)
1139
                show_node_header = False
1140
              feedback_fn("    ERROR: Script %s failed, output:" % script)
1141
              output = indent_re.sub('      ', output)
1142
              feedback_fn("%s" % output)
1143
              lu_result = 1
1144

    
1145
      return lu_result
1146

    
1147

    
1148
class LUVerifyDisks(NoHooksLU):
1149
  """Verifies the cluster disks status.
1150

1151
  """
1152
  _OP_REQP = []
1153
  REQ_BGL = False
1154

    
1155
  def ExpandNames(self):
1156
    self.needed_locks = {
1157
      locking.LEVEL_NODE: locking.ALL_SET,
1158
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1159
    }
1160
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
1161

    
1162
  def CheckPrereq(self):
1163
    """Check prerequisites.
1164

1165
    This has no prerequisites.
1166

1167
    """
1168
    pass
1169

    
1170
  def Exec(self, feedback_fn):
1171
    """Verify integrity of cluster disks.
1172

1173
    """
1174
    result = res_nodes, res_nlvm, res_instances, res_missing = [], {}, [], {}
1175

    
1176
    vg_name = self.cfg.GetVGName()
1177
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1178
    instances = [self.cfg.GetInstanceInfo(name)
1179
                 for name in self.cfg.GetInstanceList()]
1180

    
1181
    nv_dict = {}
1182
    for inst in instances:
1183
      inst_lvs = {}
1184
      if (inst.status != "up" or
1185
          inst.disk_template not in constants.DTS_NET_MIRROR):
1186
        continue
1187
      inst.MapLVsByNode(inst_lvs)
1188
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1189
      for node, vol_list in inst_lvs.iteritems():
1190
        for vol in vol_list:
1191
          nv_dict[(node, vol)] = inst
1192

    
1193
    if not nv_dict:
1194
      return result
1195

    
1196
    node_lvs = self.rpc.call_volume_list(nodes, vg_name)
1197

    
1198
    to_act = set()
1199
    for node in nodes:
1200
      # node_volume
1201
      lvs = node_lvs[node]
1202
      if lvs.failed:
1203
        if not lvs.offline:
1204
          self.LogWarning("Connection to node %s failed: %s" %
1205
                          (node, lvs.data))
1206
        continue
1207
      lvs = lvs.data
1208
      if isinstance(lvs, basestring):
1209
        logging.warning("Error enumerating LVs on node %s: %s", node, lvs)
1210
        res_nlvm[node] = lvs
1211
      elif not isinstance(lvs, dict):
1212
        logging.warning("Connection to node %s failed or invalid data"
1213
                        " returned", node)
1214
        res_nodes.append(node)
1215
        continue
1216

    
1217
      for lv_name, (_, lv_inactive, lv_online) in lvs.iteritems():
1218
        inst = nv_dict.pop((node, lv_name), None)
1219
        if (not lv_online and inst is not None
1220
            and inst.name not in res_instances):
1221
          res_instances.append(inst.name)
1222

    
1223
    # any leftover items in nv_dict are missing LVs, let's arrange the
1224
    # data better
1225
    for key, inst in nv_dict.iteritems():
1226
      if inst.name not in res_missing:
1227
        res_missing[inst.name] = []
1228
      res_missing[inst.name].append(key)
1229

    
1230
    return result
1231

    
1232

    
1233
class LURenameCluster(LogicalUnit):
1234
  """Rename the cluster.
1235

1236
  """
1237
  HPATH = "cluster-rename"
1238
  HTYPE = constants.HTYPE_CLUSTER
1239
  _OP_REQP = ["name"]
1240

    
1241
  def BuildHooksEnv(self):
1242
    """Build hooks env.
1243

1244
    """
1245
    env = {
1246
      "OP_TARGET": self.cfg.GetClusterName(),
1247
      "NEW_NAME": self.op.name,
1248
      }
1249
    mn = self.cfg.GetMasterNode()
1250
    return env, [mn], [mn]
1251

    
1252
  def CheckPrereq(self):
1253
    """Verify that the passed name is a valid one.
1254

1255
    """
1256
    hostname = utils.HostInfo(self.op.name)
1257

    
1258
    new_name = hostname.name
1259
    self.ip = new_ip = hostname.ip
1260
    old_name = self.cfg.GetClusterName()
1261
    old_ip = self.cfg.GetMasterIP()
1262
    if new_name == old_name and new_ip == old_ip:
1263
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1264
                                 " cluster has changed")
1265
    if new_ip != old_ip:
1266
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1267
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1268
                                   " reachable on the network. Aborting." %
1269
                                   new_ip)
1270

    
1271
    self.op.name = new_name
1272

    
1273
  def Exec(self, feedback_fn):
1274
    """Rename the cluster.
1275

1276
    """
1277
    clustername = self.op.name
1278
    ip = self.ip
1279

    
1280
    # shutdown the master IP
1281
    master = self.cfg.GetMasterNode()
1282
    result = self.rpc.call_node_stop_master(master, False)
1283
    if result.failed or not result.data:
1284
      raise errors.OpExecError("Could not disable the master role")
1285

    
1286
    try:
1287
      cluster = self.cfg.GetClusterInfo()
1288
      cluster.cluster_name = clustername
1289
      cluster.master_ip = ip
1290
      self.cfg.Update(cluster)
1291

    
1292
      # update the known hosts file
1293
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
1294
      node_list = self.cfg.GetNodeList()
1295
      try:
1296
        node_list.remove(master)
1297
      except ValueError:
1298
        pass
1299
      result = self.rpc.call_upload_file(node_list,
1300
                                         constants.SSH_KNOWN_HOSTS_FILE)
1301
      for to_node, to_result in result.iteritems():
1302
        if to_result.failed or not to_result.data:
1303
          logging.error("Copy of file %s to node %s failed",
1304
                        constants.SSH_KNOWN_HOSTS_FILE, to_node)
1305

    
1306
    finally:
1307
      result = self.rpc.call_node_start_master(master, False)
1308
      if result.failed or not result.data:
1309
        self.LogWarning("Could not re-enable the master role on"
1310
                        " the master, please restart manually.")
1311

    
1312

    
1313
def _RecursiveCheckIfLVMBased(disk):
1314
  """Check if the given disk or its children are lvm-based.
1315

1316
  @type disk: L{objects.Disk}
1317
  @param disk: the disk to check
1318
  @rtype: booleean
1319
  @return: boolean indicating whether a LD_LV dev_type was found or not
1320

1321
  """
1322
  if disk.children:
1323
    for chdisk in disk.children:
1324
      if _RecursiveCheckIfLVMBased(chdisk):
1325
        return True
1326
  return disk.dev_type == constants.LD_LV
1327

    
1328

    
1329
class LUSetClusterParams(LogicalUnit):
1330
  """Change the parameters of the cluster.
1331

1332
  """
1333
  HPATH = "cluster-modify"
1334
  HTYPE = constants.HTYPE_CLUSTER
1335
  _OP_REQP = []
1336
  REQ_BGL = False
1337

    
1338
  def CheckParameters(self):
1339
    """Check parameters
1340

1341
    """
1342
    if not hasattr(self.op, "candidate_pool_size"):
1343
      self.op.candidate_pool_size = None
1344
    if self.op.candidate_pool_size is not None:
1345
      try:
1346
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
1347
      except ValueError, err:
1348
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
1349
                                   str(err))
1350
      if self.op.candidate_pool_size < 1:
1351
        raise errors.OpPrereqError("At least one master candidate needed")
1352

    
1353
  def ExpandNames(self):
1354
    # FIXME: in the future maybe other cluster params won't require checking on
1355
    # all nodes to be modified.
1356
    self.needed_locks = {
1357
      locking.LEVEL_NODE: locking.ALL_SET,
1358
    }
1359
    self.share_locks[locking.LEVEL_NODE] = 1
1360

    
1361
  def BuildHooksEnv(self):
1362
    """Build hooks env.
1363

1364
    """
1365
    env = {
1366
      "OP_TARGET": self.cfg.GetClusterName(),
1367
      "NEW_VG_NAME": self.op.vg_name,
1368
      }
1369
    mn = self.cfg.GetMasterNode()
1370
    return env, [mn], [mn]
1371

    
1372
  def CheckPrereq(self):
1373
    """Check prerequisites.
1374

1375
    This checks whether the given params don't conflict and
1376
    if the given volume group is valid.
1377

1378
    """
1379
    # FIXME: This only works because there is only one parameter that can be
1380
    # changed or removed.
1381
    if self.op.vg_name is not None and not self.op.vg_name:
1382
      instances = self.cfg.GetAllInstancesInfo().values()
1383
      for inst in instances:
1384
        for disk in inst.disks:
1385
          if _RecursiveCheckIfLVMBased(disk):
1386
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1387
                                       " lvm-based instances exist")
1388

    
1389
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1390

    
1391
    # if vg_name not None, checks given volume group on all nodes
1392
    if self.op.vg_name:
1393
      vglist = self.rpc.call_vg_list(node_list)
1394
      for node in node_list:
1395
        if vglist[node].failed:
1396
          # ignoring down node
1397
          self.LogWarning("Node %s unreachable/error, ignoring" % node)
1398
          continue
1399
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].data,
1400
                                              self.op.vg_name,
1401
                                              constants.MIN_VG_SIZE)
1402
        if vgstatus:
1403
          raise errors.OpPrereqError("Error on node '%s': %s" %
1404
                                     (node, vgstatus))
1405

    
1406
    self.cluster = cluster = self.cfg.GetClusterInfo()
1407
    # validate beparams changes
1408
    if self.op.beparams:
1409
      utils.CheckBEParams(self.op.beparams)
1410
      self.new_beparams = cluster.FillDict(
1411
        cluster.beparams[constants.BEGR_DEFAULT], self.op.beparams)
1412

    
1413
    # hypervisor list/parameters
1414
    self.new_hvparams = cluster.FillDict(cluster.hvparams, {})
1415
    if self.op.hvparams:
1416
      if not isinstance(self.op.hvparams, dict):
1417
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input")
1418
      for hv_name, hv_dict in self.op.hvparams.items():
1419
        if hv_name not in self.new_hvparams:
1420
          self.new_hvparams[hv_name] = hv_dict
1421
        else:
1422
          self.new_hvparams[hv_name].update(hv_dict)
1423

    
1424
    if self.op.enabled_hypervisors is not None:
1425
      self.hv_list = self.op.enabled_hypervisors
1426
    else:
1427
      self.hv_list = cluster.enabled_hypervisors
1428

    
1429
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
1430
      # either the enabled list has changed, or the parameters have, validate
1431
      for hv_name, hv_params in self.new_hvparams.items():
1432
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
1433
            (self.op.enabled_hypervisors and
1434
             hv_name in self.op.enabled_hypervisors)):
1435
          # either this is a new hypervisor, or its parameters have changed
1436
          hv_class = hypervisor.GetHypervisor(hv_name)
1437
          hv_class.CheckParameterSyntax(hv_params)
1438
          _CheckHVParams(self, node_list, hv_name, hv_params)
1439

    
1440
  def Exec(self, feedback_fn):
1441
    """Change the parameters of the cluster.
1442

1443
    """
1444
    if self.op.vg_name is not None:
1445
      if self.op.vg_name != self.cfg.GetVGName():
1446
        self.cfg.SetVGName(self.op.vg_name)
1447
      else:
1448
        feedback_fn("Cluster LVM configuration already in desired"
1449
                    " state, not changing")
1450
    if self.op.hvparams:
1451
      self.cluster.hvparams = self.new_hvparams
1452
    if self.op.enabled_hypervisors is not None:
1453
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
1454
    if self.op.beparams:
1455
      self.cluster.beparams[constants.BEGR_DEFAULT] = self.new_beparams
1456
    if self.op.candidate_pool_size is not None:
1457
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
1458

    
1459
    self.cfg.Update(self.cluster)
1460

    
1461
    # we want to update nodes after the cluster so that if any errors
1462
    # happen, we have recorded and saved the cluster info
1463
    if self.op.candidate_pool_size is not None:
1464
      _AdjustCandidatePool(self)
1465

    
1466

    
1467
class LURedistributeConfig(NoHooksLU):
1468
  """Force the redistribution of cluster configuration.
1469

1470
  This is a very simple LU.
1471

1472
  """
1473
  _OP_REQP = []
1474
  REQ_BGL = False
1475

    
1476
  def ExpandNames(self):
1477
    self.needed_locks = {
1478
      locking.LEVEL_NODE: locking.ALL_SET,
1479
    }
1480
    self.share_locks[locking.LEVEL_NODE] = 1
1481

    
1482
  def CheckPrereq(self):
1483
    """Check prerequisites.
1484

1485
    """
1486

    
1487
  def Exec(self, feedback_fn):
1488
    """Redistribute the configuration.
1489

1490
    """
1491
    self.cfg.Update(self.cfg.GetClusterInfo())
1492

    
1493

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

1497
  """
1498
  if not instance.disks:
1499
    return True
1500

    
1501
  if not oneshot:
1502
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
1503

    
1504
  node = instance.primary_node
1505

    
1506
  for dev in instance.disks:
1507
    lu.cfg.SetDiskID(dev, node)
1508

    
1509
  retries = 0
1510
  while True:
1511
    max_time = 0
1512
    done = True
1513
    cumul_degraded = False
1514
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
1515
    if rstats.failed or not rstats.data:
1516
      lu.LogWarning("Can't get any data from node %s", node)
1517
      retries += 1
1518
      if retries >= 10:
1519
        raise errors.RemoteError("Can't contact node %s for mirror data,"
1520
                                 " aborting." % node)
1521
      time.sleep(6)
1522
      continue
1523
    rstats = rstats.data
1524
    retries = 0
1525
    for i, mstat in enumerate(rstats):
1526
      if mstat is None:
1527
        lu.LogWarning("Can't compute data for node %s/%s",
1528
                           node, instance.disks[i].iv_name)
1529
        continue
1530
      # we ignore the ldisk parameter
1531
      perc_done, est_time, is_degraded, _ = mstat
1532
      cumul_degraded = cumul_degraded or (is_degraded and perc_done is None)
1533
      if perc_done is not None:
1534
        done = False
1535
        if est_time is not None:
1536
          rem_time = "%d estimated seconds remaining" % est_time
1537
          max_time = est_time
1538
        else:
1539
          rem_time = "no time estimate"
1540
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
1541
                        (instance.disks[i].iv_name, perc_done, rem_time))
1542
    if done or oneshot:
1543
      break
1544

    
1545
    time.sleep(min(60, max_time))
1546

    
1547
  if done:
1548
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
1549
  return not cumul_degraded
1550

    
1551

    
1552
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
1553
  """Check that mirrors are not degraded.
1554

1555
  The ldisk parameter, if True, will change the test from the
1556
  is_degraded attribute (which represents overall non-ok status for
1557
  the device(s)) to the ldisk (representing the local storage status).
1558

1559
  """
1560
  lu.cfg.SetDiskID(dev, node)
1561
  if ldisk:
1562
    idx = 6
1563
  else:
1564
    idx = 5
1565

    
1566
  result = True
1567
  if on_primary or dev.AssembleOnSecondary():
1568
    rstats = lu.rpc.call_blockdev_find(node, dev)
1569
    if rstats.failed or not rstats.data:
1570
      logging.warning("Node %s: disk degraded, not found or node down", node)
1571
      result = False
1572
    else:
1573
      result = result and (not rstats.data[idx])
1574
  if dev.children:
1575
    for child in dev.children:
1576
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
1577

    
1578
  return result
1579

    
1580

    
1581
class LUDiagnoseOS(NoHooksLU):
1582
  """Logical unit for OS diagnose/query.
1583

1584
  """
1585
  _OP_REQP = ["output_fields", "names"]
1586
  REQ_BGL = False
1587
  _FIELDS_STATIC = utils.FieldSet()
1588
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status")
1589

    
1590
  def ExpandNames(self):
1591
    if self.op.names:
1592
      raise errors.OpPrereqError("Selective OS query not supported")
1593

    
1594
    _CheckOutputFields(static=self._FIELDS_STATIC,
1595
                       dynamic=self._FIELDS_DYNAMIC,
1596
                       selected=self.op.output_fields)
1597

    
1598
    # Lock all nodes, in shared mode
1599
    self.needed_locks = {}
1600
    self.share_locks[locking.LEVEL_NODE] = 1
1601
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1602

    
1603
  def CheckPrereq(self):
1604
    """Check prerequisites.
1605

1606
    """
1607

    
1608
  @staticmethod
1609
  def _DiagnoseByOS(node_list, rlist):
1610
    """Remaps a per-node return list into an a per-os per-node dictionary
1611

1612
    @param node_list: a list with the names of all nodes
1613
    @param rlist: a map with node names as keys and OS objects as values
1614

1615
    @rtype: dict
1616
    @returns: a dictionary with osnames as keys and as value another map, with
1617
        nodes as keys and list of OS objects as values, eg::
1618

1619
          {"debian-etch": {"node1": [<object>,...],
1620
                           "node2": [<object>,]}
1621
          }
1622

1623
    """
1624
    all_os = {}
1625
    for node_name, nr in rlist.iteritems():
1626
      if nr.failed or not nr.data:
1627
        continue
1628
      for os_obj in nr.data:
1629
        if os_obj.name not in all_os:
1630
          # build a list of nodes for this os containing empty lists
1631
          # for each node in node_list
1632
          all_os[os_obj.name] = {}
1633
          for nname in node_list:
1634
            all_os[os_obj.name][nname] = []
1635
        all_os[os_obj.name][node_name].append(os_obj)
1636
    return all_os
1637

    
1638
  def Exec(self, feedback_fn):
1639
    """Compute the list of OSes.
1640

1641
    """
1642
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1643
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()
1644
                   if node in node_list]
1645
    node_data = self.rpc.call_os_diagnose(valid_nodes)
1646
    if node_data == False:
1647
      raise errors.OpExecError("Can't gather the list of OSes")
1648
    pol = self._DiagnoseByOS(valid_nodes, node_data)
1649
    output = []
1650
    for os_name, os_data in pol.iteritems():
1651
      row = []
1652
      for field in self.op.output_fields:
1653
        if field == "name":
1654
          val = os_name
1655
        elif field == "valid":
1656
          val = utils.all([osl and osl[0] for osl in os_data.values()])
1657
        elif field == "node_status":
1658
          val = {}
1659
          for node_name, nos_list in os_data.iteritems():
1660
            val[node_name] = [(v.status, v.path) for v in nos_list]
1661
        else:
1662
          raise errors.ParameterError(field)
1663
        row.append(val)
1664
      output.append(row)
1665

    
1666
    return output
1667

    
1668

    
1669
class LURemoveNode(LogicalUnit):
1670
  """Logical unit for removing a node.
1671

1672
  """
1673
  HPATH = "node-remove"
1674
  HTYPE = constants.HTYPE_NODE
1675
  _OP_REQP = ["node_name"]
1676

    
1677
  def BuildHooksEnv(self):
1678
    """Build hooks env.
1679

1680
    This doesn't run on the target node in the pre phase as a failed
1681
    node would then be impossible to remove.
1682

1683
    """
1684
    env = {
1685
      "OP_TARGET": self.op.node_name,
1686
      "NODE_NAME": self.op.node_name,
1687
      }
1688
    all_nodes = self.cfg.GetNodeList()
1689
    all_nodes.remove(self.op.node_name)
1690
    return env, all_nodes, all_nodes
1691

    
1692
  def CheckPrereq(self):
1693
    """Check prerequisites.
1694

1695
    This checks:
1696
     - the node exists in the configuration
1697
     - it does not have primary or secondary instances
1698
     - it's not the master
1699

1700
    Any errors are signalled by raising errors.OpPrereqError.
1701

1702
    """
1703
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
1704
    if node is None:
1705
      raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name)
1706

    
1707
    instance_list = self.cfg.GetInstanceList()
1708

    
1709
    masternode = self.cfg.GetMasterNode()
1710
    if node.name == masternode:
1711
      raise errors.OpPrereqError("Node is the master node,"
1712
                                 " you need to failover first.")
1713

    
1714
    for instance_name in instance_list:
1715
      instance = self.cfg.GetInstanceInfo(instance_name)
1716
      if node.name in instance.all_nodes:
1717
        raise errors.OpPrereqError("Instance %s is still running on the node,"
1718
                                   " please remove first." % instance_name)
1719
    self.op.node_name = node.name
1720
    self.node = node
1721

    
1722
  def Exec(self, feedback_fn):
1723
    """Removes the node from the cluster.
1724

1725
    """
1726
    node = self.node
1727
    logging.info("Stopping the node daemon and removing configs from node %s",
1728
                 node.name)
1729

    
1730
    self.context.RemoveNode(node.name)
1731

    
1732
    self.rpc.call_node_leave_cluster(node.name)
1733

    
1734
    # Promote nodes to master candidate as needed
1735
    _AdjustCandidatePool(self)
1736

    
1737

    
1738
class LUQueryNodes(NoHooksLU):
1739
  """Logical unit for querying nodes.
1740

1741
  """
1742
  _OP_REQP = ["output_fields", "names"]
1743
  REQ_BGL = False
1744
  _FIELDS_DYNAMIC = utils.FieldSet(
1745
    "dtotal", "dfree",
1746
    "mtotal", "mnode", "mfree",
1747
    "bootid",
1748
    "ctotal",
1749
    )
1750

    
1751
  _FIELDS_STATIC = utils.FieldSet(
1752
    "name", "pinst_cnt", "sinst_cnt",
1753
    "pinst_list", "sinst_list",
1754
    "pip", "sip", "tags",
1755
    "serial_no",
1756
    "master_candidate",
1757
    "master",
1758
    "offline",
1759
    )
1760

    
1761
  def ExpandNames(self):
1762
    _CheckOutputFields(static=self._FIELDS_STATIC,
1763
                       dynamic=self._FIELDS_DYNAMIC,
1764
                       selected=self.op.output_fields)
1765

    
1766
    self.needed_locks = {}
1767
    self.share_locks[locking.LEVEL_NODE] = 1
1768

    
1769
    if self.op.names:
1770
      self.wanted = _GetWantedNodes(self, self.op.names)
1771
    else:
1772
      self.wanted = locking.ALL_SET
1773

    
1774
    self.do_locking = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
1775
    if self.do_locking:
1776
      # if we don't request only static fields, we need to lock the nodes
1777
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
1778

    
1779

    
1780
  def CheckPrereq(self):
1781
    """Check prerequisites.
1782

1783
    """
1784
    # The validation of the node list is done in the _GetWantedNodes,
1785
    # if non empty, and if empty, there's no validation to do
1786
    pass
1787

    
1788
  def Exec(self, feedback_fn):
1789
    """Computes the list of nodes and their attributes.
1790

1791
    """
1792
    all_info = self.cfg.GetAllNodesInfo()
1793
    if self.do_locking:
1794
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
1795
    elif self.wanted != locking.ALL_SET:
1796
      nodenames = self.wanted
1797
      missing = set(nodenames).difference(all_info.keys())
1798
      if missing:
1799
        raise errors.OpExecError(
1800
          "Some nodes were removed before retrieving their data: %s" % missing)
1801
    else:
1802
      nodenames = all_info.keys()
1803

    
1804
    nodenames = utils.NiceSort(nodenames)
1805
    nodelist = [all_info[name] for name in nodenames]
1806

    
1807
    # begin data gathering
1808

    
1809
    if self.do_locking:
1810
      live_data = {}
1811
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
1812
                                          self.cfg.GetHypervisorType())
1813
      for name in nodenames:
1814
        nodeinfo = node_data[name]
1815
        if not nodeinfo.failed and nodeinfo.data:
1816
          nodeinfo = nodeinfo.data
1817
          fn = utils.TryConvert
1818
          live_data[name] = {
1819
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
1820
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
1821
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
1822
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
1823
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
1824
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
1825
            "bootid": nodeinfo.get('bootid', None),
1826
            }
1827
        else:
1828
          live_data[name] = {}
1829
    else:
1830
      live_data = dict.fromkeys(nodenames, {})
1831

    
1832
    node_to_primary = dict([(name, set()) for name in nodenames])
1833
    node_to_secondary = dict([(name, set()) for name in nodenames])
1834

    
1835
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
1836
                             "sinst_cnt", "sinst_list"))
1837
    if inst_fields & frozenset(self.op.output_fields):
1838
      instancelist = self.cfg.GetInstanceList()
1839

    
1840
      for instance_name in instancelist:
1841
        inst = self.cfg.GetInstanceInfo(instance_name)
1842
        if inst.primary_node in node_to_primary:
1843
          node_to_primary[inst.primary_node].add(inst.name)
1844
        for secnode in inst.secondary_nodes:
1845
          if secnode in node_to_secondary:
1846
            node_to_secondary[secnode].add(inst.name)
1847

    
1848
    master_node = self.cfg.GetMasterNode()
1849

    
1850
    # end data gathering
1851

    
1852
    output = []
1853
    for node in nodelist:
1854
      node_output = []
1855
      for field in self.op.output_fields:
1856
        if field == "name":
1857
          val = node.name
1858
        elif field == "pinst_list":
1859
          val = list(node_to_primary[node.name])
1860
        elif field == "sinst_list":
1861
          val = list(node_to_secondary[node.name])
1862
        elif field == "pinst_cnt":
1863
          val = len(node_to_primary[node.name])
1864
        elif field == "sinst_cnt":
1865
          val = len(node_to_secondary[node.name])
1866
        elif field == "pip":
1867
          val = node.primary_ip
1868
        elif field == "sip":
1869
          val = node.secondary_ip
1870
        elif field == "tags":
1871
          val = list(node.GetTags())
1872
        elif field == "serial_no":
1873
          val = node.serial_no
1874
        elif field == "master_candidate":
1875
          val = node.master_candidate
1876
        elif field == "master":
1877
          val = node.name == master_node
1878
        elif field == "offline":
1879
          val = node.offline
1880
        elif self._FIELDS_DYNAMIC.Matches(field):
1881
          val = live_data[node.name].get(field, None)
1882
        else:
1883
          raise errors.ParameterError(field)
1884
        node_output.append(val)
1885
      output.append(node_output)
1886

    
1887
    return output
1888

    
1889

    
1890
class LUQueryNodeVolumes(NoHooksLU):
1891
  """Logical unit for getting volumes on node(s).
1892

1893
  """
1894
  _OP_REQP = ["nodes", "output_fields"]
1895
  REQ_BGL = False
1896
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
1897
  _FIELDS_STATIC = utils.FieldSet("node")
1898

    
1899
  def ExpandNames(self):
1900
    _CheckOutputFields(static=self._FIELDS_STATIC,
1901
                       dynamic=self._FIELDS_DYNAMIC,
1902
                       selected=self.op.output_fields)
1903

    
1904
    self.needed_locks = {}
1905
    self.share_locks[locking.LEVEL_NODE] = 1
1906
    if not self.op.nodes:
1907
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1908
    else:
1909
      self.needed_locks[locking.LEVEL_NODE] = \
1910
        _GetWantedNodes(self, self.op.nodes)
1911

    
1912
  def CheckPrereq(self):
1913
    """Check prerequisites.
1914

1915
    This checks that the fields required are valid output fields.
1916

1917
    """
1918
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
1919

    
1920
  def Exec(self, feedback_fn):
1921
    """Computes the list of nodes and their attributes.
1922

1923
    """
1924
    nodenames = self.nodes
1925
    volumes = self.rpc.call_node_volumes(nodenames)
1926

    
1927
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
1928
             in self.cfg.GetInstanceList()]
1929

    
1930
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
1931

    
1932
    output = []
1933
    for node in nodenames:
1934
      if node not in volumes or volumes[node].failed or not volumes[node].data:
1935
        continue
1936

    
1937
      node_vols = volumes[node].data[:]
1938
      node_vols.sort(key=lambda vol: vol['dev'])
1939

    
1940
      for vol in node_vols:
1941
        node_output = []
1942
        for field in self.op.output_fields:
1943
          if field == "node":
1944
            val = node
1945
          elif field == "phys":
1946
            val = vol['dev']
1947
          elif field == "vg":
1948
            val = vol['vg']
1949
          elif field == "name":
1950
            val = vol['name']
1951
          elif field == "size":
1952
            val = int(float(vol['size']))
1953
          elif field == "instance":
1954
            for inst in ilist:
1955
              if node not in lv_by_node[inst]:
1956
                continue
1957
              if vol['name'] in lv_by_node[inst][node]:
1958
                val = inst.name
1959
                break
1960
            else:
1961
              val = '-'
1962
          else:
1963
            raise errors.ParameterError(field)
1964
          node_output.append(str(val))
1965

    
1966
        output.append(node_output)
1967

    
1968
    return output
1969

    
1970

    
1971
class LUAddNode(LogicalUnit):
1972
  """Logical unit for adding node to the cluster.
1973

1974
  """
1975
  HPATH = "node-add"
1976
  HTYPE = constants.HTYPE_NODE
1977
  _OP_REQP = ["node_name"]
1978

    
1979
  def BuildHooksEnv(self):
1980
    """Build hooks env.
1981

1982
    This will run on all nodes before, and on all nodes + the new node after.
1983

1984
    """
1985
    env = {
1986
      "OP_TARGET": self.op.node_name,
1987
      "NODE_NAME": self.op.node_name,
1988
      "NODE_PIP": self.op.primary_ip,
1989
      "NODE_SIP": self.op.secondary_ip,
1990
      }
1991
    nodes_0 = self.cfg.GetNodeList()
1992
    nodes_1 = nodes_0 + [self.op.node_name, ]
1993
    return env, nodes_0, nodes_1
1994

    
1995
  def CheckPrereq(self):
1996
    """Check prerequisites.
1997

1998
    This checks:
1999
     - the new node is not already in the config
2000
     - it is resolvable
2001
     - its parameters (single/dual homed) matches the cluster
2002

2003
    Any errors are signalled by raising errors.OpPrereqError.
2004

2005
    """
2006
    node_name = self.op.node_name
2007
    cfg = self.cfg
2008

    
2009
    dns_data = utils.HostInfo(node_name)
2010

    
2011
    node = dns_data.name
2012
    primary_ip = self.op.primary_ip = dns_data.ip
2013
    secondary_ip = getattr(self.op, "secondary_ip", None)
2014
    if secondary_ip is None:
2015
      secondary_ip = primary_ip
2016
    if not utils.IsValidIP(secondary_ip):
2017
      raise errors.OpPrereqError("Invalid secondary IP given")
2018
    self.op.secondary_ip = secondary_ip
2019

    
2020
    node_list = cfg.GetNodeList()
2021
    if not self.op.readd and node in node_list:
2022
      raise errors.OpPrereqError("Node %s is already in the configuration" %
2023
                                 node)
2024
    elif self.op.readd and node not in node_list:
2025
      raise errors.OpPrereqError("Node %s is not in the configuration" % node)
2026

    
2027
    for existing_node_name in node_list:
2028
      existing_node = cfg.GetNodeInfo(existing_node_name)
2029

    
2030
      if self.op.readd and node == existing_node_name:
2031
        if (existing_node.primary_ip != primary_ip or
2032
            existing_node.secondary_ip != secondary_ip):
2033
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
2034
                                     " address configuration as before")
2035
        continue
2036

    
2037
      if (existing_node.primary_ip == primary_ip or
2038
          existing_node.secondary_ip == primary_ip or
2039
          existing_node.primary_ip == secondary_ip or
2040
          existing_node.secondary_ip == secondary_ip):
2041
        raise errors.OpPrereqError("New node ip address(es) conflict with"
2042
                                   " existing node %s" % existing_node.name)
2043

    
2044
    # check that the type of the node (single versus dual homed) is the
2045
    # same as for the master
2046
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
2047
    master_singlehomed = myself.secondary_ip == myself.primary_ip
2048
    newbie_singlehomed = secondary_ip == primary_ip
2049
    if master_singlehomed != newbie_singlehomed:
2050
      if master_singlehomed:
2051
        raise errors.OpPrereqError("The master has no private ip but the"
2052
                                   " new node has one")
2053
      else:
2054
        raise errors.OpPrereqError("The master has a private ip but the"
2055
                                   " new node doesn't have one")
2056

    
2057
    # checks reachablity
2058
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
2059
      raise errors.OpPrereqError("Node not reachable by ping")
2060

    
2061
    if not newbie_singlehomed:
2062
      # check reachability from my secondary ip to newbie's secondary ip
2063
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
2064
                           source=myself.secondary_ip):
2065
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
2066
                                   " based ping to noded port")
2067

    
2068
    cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2069
    mc_now, _ = self.cfg.GetMasterCandidateStats()
2070
    master_candidate = mc_now < cp_size
2071

    
2072
    self.new_node = objects.Node(name=node,
2073
                                 primary_ip=primary_ip,
2074
                                 secondary_ip=secondary_ip,
2075
                                 master_candidate=master_candidate,
2076
                                 offline=False)
2077

    
2078
  def Exec(self, feedback_fn):
2079
    """Adds the new node to the cluster.
2080

2081
    """
2082
    new_node = self.new_node
2083
    node = new_node.name
2084

    
2085
    # check connectivity
2086
    result = self.rpc.call_version([node])[node]
2087
    result.Raise()
2088
    if result.data:
2089
      if constants.PROTOCOL_VERSION == result.data:
2090
        logging.info("Communication to node %s fine, sw version %s match",
2091
                     node, result.data)
2092
      else:
2093
        raise errors.OpExecError("Version mismatch master version %s,"
2094
                                 " node version %s" %
2095
                                 (constants.PROTOCOL_VERSION, result.data))
2096
    else:
2097
      raise errors.OpExecError("Cannot get version from the new node")
2098

    
2099
    # setup ssh on node
2100
    logging.info("Copy ssh key to node %s", node)
2101
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
2102
    keyarray = []
2103
    keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
2104
                constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
2105
                priv_key, pub_key]
2106

    
2107
    for i in keyfiles:
2108
      f = open(i, 'r')
2109
      try:
2110
        keyarray.append(f.read())
2111
      finally:
2112
        f.close()
2113

    
2114
    result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
2115
                                    keyarray[2],
2116
                                    keyarray[3], keyarray[4], keyarray[5])
2117

    
2118
    if result.failed or not result.data:
2119
      raise errors.OpExecError("Cannot transfer ssh keys to the new node")
2120

    
2121
    # Add node to our /etc/hosts, and add key to known_hosts
2122
    utils.AddHostToEtcHosts(new_node.name)
2123

    
2124
    if new_node.secondary_ip != new_node.primary_ip:
2125
      result = self.rpc.call_node_has_ip_address(new_node.name,
2126
                                                 new_node.secondary_ip)
2127
      if result.failed or not result.data:
2128
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
2129
                                 " you gave (%s). Please fix and re-run this"
2130
                                 " command." % new_node.secondary_ip)
2131

    
2132
    node_verify_list = [self.cfg.GetMasterNode()]
2133
    node_verify_param = {
2134
      'nodelist': [node],
2135
      # TODO: do a node-net-test as well?
2136
    }
2137

    
2138
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
2139
                                       self.cfg.GetClusterName())
2140
    for verifier in node_verify_list:
2141
      if result[verifier].failed or not result[verifier].data:
2142
        raise errors.OpExecError("Cannot communicate with %s's node daemon"
2143
                                 " for remote verification" % verifier)
2144
      if result[verifier].data['nodelist']:
2145
        for failed in result[verifier].data['nodelist']:
2146
          feedback_fn("ssh/hostname verification failed %s -> %s" %
2147
                      (verifier, result[verifier]['nodelist'][failed]))
2148
        raise errors.OpExecError("ssh/hostname verification failed.")
2149

    
2150
    # Distribute updated /etc/hosts and known_hosts to all nodes,
2151
    # including the node just added
2152
    myself = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
2153
    dist_nodes = self.cfg.GetNodeList()
2154
    if not self.op.readd:
2155
      dist_nodes.append(node)
2156
    if myself.name in dist_nodes:
2157
      dist_nodes.remove(myself.name)
2158

    
2159
    logging.debug("Copying hosts and known_hosts to all nodes")
2160
    for fname in (constants.ETC_HOSTS, constants.SSH_KNOWN_HOSTS_FILE):
2161
      result = self.rpc.call_upload_file(dist_nodes, fname)
2162
      for to_node, to_result in result.iteritems():
2163
        if to_result.failed or not to_result.data:
2164
          logging.error("Copy of file %s to node %s failed", fname, to_node)
2165

    
2166
    to_copy = []
2167
    if constants.HT_XEN_HVM in self.cfg.GetClusterInfo().enabled_hypervisors:
2168
      to_copy.append(constants.VNC_PASSWORD_FILE)
2169
    for fname in to_copy:
2170
      result = self.rpc.call_upload_file([node], fname)
2171
      if result[node].failed or not result[node]:
2172
        logging.error("Could not copy file %s to node %s", fname, node)
2173

    
2174
    if self.op.readd:
2175
      self.context.ReaddNode(new_node)
2176
    else:
2177
      self.context.AddNode(new_node)
2178

    
2179

    
2180
class LUSetNodeParams(LogicalUnit):
2181
  """Modifies the parameters of a node.
2182

2183
  """
2184
  HPATH = "node-modify"
2185
  HTYPE = constants.HTYPE_NODE
2186
  _OP_REQP = ["node_name"]
2187
  REQ_BGL = False
2188

    
2189
  def CheckArguments(self):
2190
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2191
    if node_name is None:
2192
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
2193
    self.op.node_name = node_name
2194
    _CheckBooleanOpField(self.op, 'master_candidate')
2195
    _CheckBooleanOpField(self.op, 'offline')
2196
    if self.op.master_candidate is None and self.op.offline is None:
2197
      raise errors.OpPrereqError("Please pass at least one modification")
2198
    if self.op.offline == True and self.op.master_candidate == True:
2199
      raise errors.OpPrereqError("Can't set the node into offline and"
2200
                                 " master_candidate at the same time")
2201

    
2202
  def ExpandNames(self):
2203
    self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
2204

    
2205
  def BuildHooksEnv(self):
2206
    """Build hooks env.
2207

2208
    This runs on the master node.
2209

2210
    """
2211
    env = {
2212
      "OP_TARGET": self.op.node_name,
2213
      "MASTER_CANDIDATE": str(self.op.master_candidate),
2214
      "OFFLINE": str(self.op.offline),
2215
      }
2216
    nl = [self.cfg.GetMasterNode(),
2217
          self.op.node_name]
2218
    return env, nl, nl
2219

    
2220
  def CheckPrereq(self):
2221
    """Check prerequisites.
2222

2223
    This only checks the instance list against the existing names.
2224

2225
    """
2226
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
2227

    
2228
    if ((self.op.master_candidate == False or self.op.offline == True)
2229
        and node.master_candidate):
2230
      # we will demote the node from master_candidate
2231
      if self.op.node_name == self.cfg.GetMasterNode():
2232
        raise errors.OpPrereqError("The master node has to be a"
2233
                                   " master candidate and online")
2234
      cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2235
      num_candidates, _ = self.cfg.GetMasterCandidateStats()
2236
      if num_candidates <= cp_size:
2237
        msg = ("Not enough master candidates (desired"
2238
               " %d, new value will be %d)" % (cp_size, num_candidates-1))
2239
        if self.op.force:
2240
          self.LogWarning(msg)
2241
        else:
2242
          raise errors.OpPrereqError(msg)
2243

    
2244
    if (self.op.master_candidate == True and node.offline and
2245
        not self.op.offline == False):
2246
      raise errors.OpPrereqError("Can't set an offline node to"
2247
                                 " master_candidate")
2248

    
2249
    return
2250

    
2251
  def Exec(self, feedback_fn):
2252
    """Modifies a node.
2253

2254
    """
2255
    node = self.node
2256

    
2257
    result = []
2258

    
2259
    if self.op.offline is not None:
2260
      node.offline = self.op.offline
2261
      result.append(("offline", str(self.op.offline)))
2262
      if self.op.offline == True and node.master_candidate:
2263
        node.master_candidate = False
2264
        result.append(("master_candidate", "auto-demotion due to offline"))
2265

    
2266
    if self.op.master_candidate is not None:
2267
      node.master_candidate = self.op.master_candidate
2268
      result.append(("master_candidate", str(self.op.master_candidate)))
2269
      if self.op.master_candidate == False:
2270
        rrc = self.rpc.call_node_demote_from_mc(node.name)
2271
        if (rrc.failed or not isinstance(rrc.data, (tuple, list))
2272
            or len(rrc.data) != 2):
2273
          self.LogWarning("Node rpc error: %s" % rrc.error)
2274
        elif not rrc.data[0]:
2275
          self.LogWarning("Node failed to demote itself: %s" % rrc.data[1])
2276

    
2277
    # this will trigger configuration file update, if needed
2278
    self.cfg.Update(node)
2279
    # this will trigger job queue propagation or cleanup
2280
    if self.op.node_name != self.cfg.GetMasterNode():
2281
      self.context.ReaddNode(node)
2282

    
2283
    return result
2284

    
2285

    
2286
class LUQueryClusterInfo(NoHooksLU):
2287
  """Query cluster configuration.
2288

2289
  """
2290
  _OP_REQP = []
2291
  REQ_BGL = False
2292

    
2293
  def ExpandNames(self):
2294
    self.needed_locks = {}
2295

    
2296
  def CheckPrereq(self):
2297
    """No prerequsites needed for this LU.
2298

2299
    """
2300
    pass
2301

    
2302
  def Exec(self, feedback_fn):
2303
    """Return cluster config.
2304

2305
    """
2306
    cluster = self.cfg.GetClusterInfo()
2307
    result = {
2308
      "software_version": constants.RELEASE_VERSION,
2309
      "protocol_version": constants.PROTOCOL_VERSION,
2310
      "config_version": constants.CONFIG_VERSION,
2311
      "os_api_version": constants.OS_API_VERSION,
2312
      "export_version": constants.EXPORT_VERSION,
2313
      "architecture": (platform.architecture()[0], platform.machine()),
2314
      "name": cluster.cluster_name,
2315
      "master": cluster.master_node,
2316
      "default_hypervisor": cluster.default_hypervisor,
2317
      "enabled_hypervisors": cluster.enabled_hypervisors,
2318
      "hvparams": cluster.hvparams,
2319
      "beparams": cluster.beparams,
2320
      "candidate_pool_size": cluster.candidate_pool_size,
2321
      }
2322

    
2323
    return result
2324

    
2325

    
2326
class LUQueryConfigValues(NoHooksLU):
2327
  """Return configuration values.
2328

2329
  """
2330
  _OP_REQP = []
2331
  REQ_BGL = False
2332
  _FIELDS_DYNAMIC = utils.FieldSet()
2333
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag")
2334

    
2335
  def ExpandNames(self):
2336
    self.needed_locks = {}
2337

    
2338
    _CheckOutputFields(static=self._FIELDS_STATIC,
2339
                       dynamic=self._FIELDS_DYNAMIC,
2340
                       selected=self.op.output_fields)
2341

    
2342
  def CheckPrereq(self):
2343
    """No prerequisites.
2344

2345
    """
2346
    pass
2347

    
2348
  def Exec(self, feedback_fn):
2349
    """Dump a representation of the cluster config to the standard output.
2350

2351
    """
2352
    values = []
2353
    for field in self.op.output_fields:
2354
      if field == "cluster_name":
2355
        entry = self.cfg.GetClusterName()
2356
      elif field == "master_node":
2357
        entry = self.cfg.GetMasterNode()
2358
      elif field == "drain_flag":
2359
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
2360
      else:
2361
        raise errors.ParameterError(field)
2362
      values.append(entry)
2363
    return values
2364

    
2365

    
2366
class LUActivateInstanceDisks(NoHooksLU):
2367
  """Bring up an instance's disks.
2368

2369
  """
2370
  _OP_REQP = ["instance_name"]
2371
  REQ_BGL = False
2372

    
2373
  def ExpandNames(self):
2374
    self._ExpandAndLockInstance()
2375
    self.needed_locks[locking.LEVEL_NODE] = []
2376
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2377

    
2378
  def DeclareLocks(self, level):
2379
    if level == locking.LEVEL_NODE:
2380
      self._LockInstancesNodes()
2381

    
2382
  def CheckPrereq(self):
2383
    """Check prerequisites.
2384

2385
    This checks that the instance is in the cluster.
2386

2387
    """
2388
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2389
    assert self.instance is not None, \
2390
      "Cannot retrieve locked instance %s" % self.op.instance_name
2391
    _CheckNodeOnline(self, self.instance.primary_node)
2392

    
2393
  def Exec(self, feedback_fn):
2394
    """Activate the disks.
2395

2396
    """
2397
    disks_ok, disks_info = _AssembleInstanceDisks(self, self.instance)
2398
    if not disks_ok:
2399
      raise errors.OpExecError("Cannot activate block devices")
2400

    
2401
    return disks_info
2402

    
2403

    
2404
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False):
2405
  """Prepare the block devices for an instance.
2406

2407
  This sets up the block devices on all nodes.
2408

2409
  @type lu: L{LogicalUnit}
2410
  @param lu: the logical unit on whose behalf we execute
2411
  @type instance: L{objects.Instance}
2412
  @param instance: the instance for whose disks we assemble
2413
  @type ignore_secondaries: boolean
2414
  @param ignore_secondaries: if true, errors on secondary nodes
2415
      won't result in an error return from the function
2416
  @return: False if the operation failed, otherwise a list of
2417
      (host, instance_visible_name, node_visible_name)
2418
      with the mapping from node devices to instance devices
2419

2420
  """
2421
  device_info = []
2422
  disks_ok = True
2423
  iname = instance.name
2424
  # With the two passes mechanism we try to reduce the window of
2425
  # opportunity for the race condition of switching DRBD to primary
2426
  # before handshaking occured, but we do not eliminate it
2427

    
2428
  # The proper fix would be to wait (with some limits) until the
2429
  # connection has been made and drbd transitions from WFConnection
2430
  # into any other network-connected state (Connected, SyncTarget,
2431
  # SyncSource, etc.)
2432

    
2433
  # 1st pass, assemble on all nodes in secondary mode
2434
  for inst_disk in instance.disks:
2435
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2436
      lu.cfg.SetDiskID(node_disk, node)
2437
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
2438
      if result.failed or not result:
2439
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2440
                           " (is_primary=False, pass=1)",
2441
                           inst_disk.iv_name, node)
2442
        if not ignore_secondaries:
2443
          disks_ok = False
2444

    
2445
  # FIXME: race condition on drbd migration to primary
2446

    
2447
  # 2nd pass, do only the primary node
2448
  for inst_disk in instance.disks:
2449
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2450
      if node != instance.primary_node:
2451
        continue
2452
      lu.cfg.SetDiskID(node_disk, node)
2453
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
2454
      if result.failed or not result:
2455
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2456
                           " (is_primary=True, pass=2)",
2457
                           inst_disk.iv_name, node)
2458
        disks_ok = False
2459
    device_info.append((instance.primary_node, inst_disk.iv_name, result.data))
2460

    
2461
  # leave the disks configured for the primary node
2462
  # this is a workaround that would be fixed better by
2463
  # improving the logical/physical id handling
2464
  for disk in instance.disks:
2465
    lu.cfg.SetDiskID(disk, instance.primary_node)
2466

    
2467
  return disks_ok, device_info
2468

    
2469

    
2470
def _StartInstanceDisks(lu, instance, force):
2471
  """Start the disks of an instance.
2472

2473
  """
2474
  disks_ok, dummy = _AssembleInstanceDisks(lu, instance,
2475
                                           ignore_secondaries=force)
2476
  if not disks_ok:
2477
    _ShutdownInstanceDisks(lu, instance)
2478
    if force is not None and not force:
2479
      lu.proc.LogWarning("", hint="If the message above refers to a"
2480
                         " secondary node,"
2481
                         " you can retry the operation using '--force'.")
2482
    raise errors.OpExecError("Disk consistency error")
2483

    
2484

    
2485
class LUDeactivateInstanceDisks(NoHooksLU):
2486
  """Shutdown an instance's disks.
2487

2488
  """
2489
  _OP_REQP = ["instance_name"]
2490
  REQ_BGL = False
2491

    
2492
  def ExpandNames(self):
2493
    self._ExpandAndLockInstance()
2494
    self.needed_locks[locking.LEVEL_NODE] = []
2495
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2496

    
2497
  def DeclareLocks(self, level):
2498
    if level == locking.LEVEL_NODE:
2499
      self._LockInstancesNodes()
2500

    
2501
  def CheckPrereq(self):
2502
    """Check prerequisites.
2503

2504
    This checks that the instance is in the cluster.
2505

2506
    """
2507
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2508
    assert self.instance is not None, \
2509
      "Cannot retrieve locked instance %s" % self.op.instance_name
2510

    
2511
  def Exec(self, feedback_fn):
2512
    """Deactivate the disks
2513

2514
    """
2515
    instance = self.instance
2516
    _SafeShutdownInstanceDisks(self, instance)
2517

    
2518

    
2519
def _SafeShutdownInstanceDisks(lu, instance):
2520
  """Shutdown block devices of an instance.
2521

2522
  This function checks if an instance is running, before calling
2523
  _ShutdownInstanceDisks.
2524

2525
  """
2526
  ins_l = lu.rpc.call_instance_list([instance.primary_node],
2527
                                      [instance.hypervisor])
2528
  ins_l = ins_l[instance.primary_node]
2529
  if ins_l.failed or not isinstance(ins_l.data, list):
2530
    raise errors.OpExecError("Can't contact node '%s'" %
2531
                             instance.primary_node)
2532

    
2533
  if instance.name in ins_l.data:
2534
    raise errors.OpExecError("Instance is running, can't shutdown"
2535
                             " block devices.")
2536

    
2537
  _ShutdownInstanceDisks(lu, instance)
2538

    
2539

    
2540
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
2541
  """Shutdown block devices of an instance.
2542

2543
  This does the shutdown on all nodes of the instance.
2544

2545
  If the ignore_primary is false, errors on the primary node are
2546
  ignored.
2547

2548
  """
2549
  result = True
2550
  for disk in instance.disks:
2551
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
2552
      lu.cfg.SetDiskID(top_disk, node)
2553
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
2554
      if result.failed or not result.data:
2555
        logging.error("Could not shutdown block device %s on node %s",
2556
                      disk.iv_name, node)
2557
        if not ignore_primary or node != instance.primary_node:
2558
          result = False
2559
  return result
2560

    
2561

    
2562
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
2563
  """Checks if a node has enough free memory.
2564

2565
  This function check if a given node has the needed amount of free
2566
  memory. In case the node has less memory or we cannot get the
2567
  information from the node, this function raise an OpPrereqError
2568
  exception.
2569

2570
  @type lu: C{LogicalUnit}
2571
  @param lu: a logical unit from which we get configuration data
2572
  @type node: C{str}
2573
  @param node: the node to check
2574
  @type reason: C{str}
2575
  @param reason: string to use in the error message
2576
  @type requested: C{int}
2577
  @param requested: the amount of memory in MiB to check for
2578
  @type hypervisor_name: C{str}
2579
  @param hypervisor_name: the hypervisor to ask for memory stats
2580
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
2581
      we cannot check the node
2582

2583
  """
2584
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
2585
  nodeinfo[node].Raise()
2586
  free_mem = nodeinfo[node].data.get('memory_free')
2587
  if not isinstance(free_mem, int):
2588
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
2589
                             " was '%s'" % (node, free_mem))
2590
  if requested > free_mem:
2591
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
2592
                             " needed %s MiB, available %s MiB" %
2593
                             (node, reason, requested, free_mem))
2594

    
2595

    
2596
class LUStartupInstance(LogicalUnit):
2597
  """Starts an instance.
2598

2599
  """
2600
  HPATH = "instance-start"
2601
  HTYPE = constants.HTYPE_INSTANCE
2602
  _OP_REQP = ["instance_name", "force"]
2603
  REQ_BGL = False
2604

    
2605
  def ExpandNames(self):
2606
    self._ExpandAndLockInstance()
2607

    
2608
  def BuildHooksEnv(self):
2609
    """Build hooks env.
2610

2611
    This runs on master, primary and secondary nodes of the instance.
2612

2613
    """
2614
    env = {
2615
      "FORCE": self.op.force,
2616
      }
2617
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2618
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2619
    return env, nl, nl
2620

    
2621
  def CheckPrereq(self):
2622
    """Check prerequisites.
2623

2624
    This checks that the instance is in the cluster.
2625

2626
    """
2627
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2628
    assert self.instance is not None, \
2629
      "Cannot retrieve locked instance %s" % self.op.instance_name
2630

    
2631
    _CheckNodeOnline(self, instance.primary_node)
2632

    
2633
    bep = self.cfg.GetClusterInfo().FillBE(instance)
2634
    # check bridges existance
2635
    _CheckInstanceBridgesExist(self, instance)
2636

    
2637
    _CheckNodeFreeMemory(self, instance.primary_node,
2638
                         "starting instance %s" % instance.name,
2639
                         bep[constants.BE_MEMORY], instance.hypervisor)
2640

    
2641
  def Exec(self, feedback_fn):
2642
    """Start the instance.
2643

2644
    """
2645
    instance = self.instance
2646
    force = self.op.force
2647
    extra_args = getattr(self.op, "extra_args", "")
2648

    
2649
    self.cfg.MarkInstanceUp(instance.name)
2650

    
2651
    node_current = instance.primary_node
2652

    
2653
    _StartInstanceDisks(self, instance, force)
2654

    
2655
    result = self.rpc.call_instance_start(node_current, instance, extra_args)
2656
    msg = result.RemoteFailMsg()
2657
    if msg:
2658
      _ShutdownInstanceDisks(self, instance)
2659
      raise errors.OpExecError("Could not start instance: %s" % msg)
2660

    
2661

    
2662
class LURebootInstance(LogicalUnit):
2663
  """Reboot an instance.
2664

2665
  """
2666
  HPATH = "instance-reboot"
2667
  HTYPE = constants.HTYPE_INSTANCE
2668
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
2669
  REQ_BGL = False
2670

    
2671
  def ExpandNames(self):
2672
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
2673
                                   constants.INSTANCE_REBOOT_HARD,
2674
                                   constants.INSTANCE_REBOOT_FULL]:
2675
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
2676
                                  (constants.INSTANCE_REBOOT_SOFT,
2677
                                   constants.INSTANCE_REBOOT_HARD,
2678
                                   constants.INSTANCE_REBOOT_FULL))
2679
    self._ExpandAndLockInstance()
2680

    
2681
  def BuildHooksEnv(self):
2682
    """Build hooks env.
2683

2684
    This runs on master, primary and secondary nodes of the instance.
2685

2686
    """
2687
    env = {
2688
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
2689
      }
2690
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2691
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2692
    return env, nl, nl
2693

    
2694
  def CheckPrereq(self):
2695
    """Check prerequisites.
2696

2697
    This checks that the instance is in the cluster.
2698

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

    
2704
    _CheckNodeOnline(self, instance.primary_node)
2705

    
2706
    # check bridges existance
2707
    _CheckInstanceBridgesExist(self, instance)
2708

    
2709
  def Exec(self, feedback_fn):
2710
    """Reboot the instance.
2711

2712
    """
2713
    instance = self.instance
2714
    ignore_secondaries = self.op.ignore_secondaries
2715
    reboot_type = self.op.reboot_type
2716
    extra_args = getattr(self.op, "extra_args", "")
2717

    
2718
    node_current = instance.primary_node
2719

    
2720
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
2721
                       constants.INSTANCE_REBOOT_HARD]:
2722
      result = self.rpc.call_instance_reboot(node_current, instance,
2723
                                             reboot_type, extra_args)
2724
      if result.failed or not result.data:
2725
        raise errors.OpExecError("Could not reboot instance")
2726
    else:
2727
      if not self.rpc.call_instance_shutdown(node_current, instance):
2728
        raise errors.OpExecError("could not shutdown instance for full reboot")
2729
      _ShutdownInstanceDisks(self, instance)
2730
      _StartInstanceDisks(self, instance, ignore_secondaries)
2731
      result = self.rpc.call_instance_start(node_current, instance, extra_args)
2732
      msg = result.RemoteFailMsg()
2733
      if msg:
2734
        _ShutdownInstanceDisks(self, instance)
2735
        raise errors.OpExecError("Could not start instance for"
2736
                                 " full reboot: %s" % msg)
2737

    
2738
    self.cfg.MarkInstanceUp(instance.name)
2739

    
2740

    
2741
class LUShutdownInstance(LogicalUnit):
2742
  """Shutdown an instance.
2743

2744
  """
2745
  HPATH = "instance-stop"
2746
  HTYPE = constants.HTYPE_INSTANCE
2747
  _OP_REQP = ["instance_name"]
2748
  REQ_BGL = False
2749

    
2750
  def ExpandNames(self):
2751
    self._ExpandAndLockInstance()
2752

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

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

2758
    """
2759
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2760
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2761
    return env, nl, nl
2762

    
2763
  def CheckPrereq(self):
2764
    """Check prerequisites.
2765

2766
    This checks that the instance is in the cluster.
2767

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

    
2774
  def Exec(self, feedback_fn):
2775
    """Shutdown the instance.
2776

2777
    """
2778
    instance = self.instance
2779
    node_current = instance.primary_node
2780
    self.cfg.MarkInstanceDown(instance.name)
2781
    result = self.rpc.call_instance_shutdown(node_current, instance)
2782
    if result.failed or not result.data:
2783
      self.proc.LogWarning("Could not shutdown instance")
2784

    
2785
    _ShutdownInstanceDisks(self, instance)
2786

    
2787

    
2788
class LUReinstallInstance(LogicalUnit):
2789
  """Reinstall an instance.
2790

2791
  """
2792
  HPATH = "instance-reinstall"
2793
  HTYPE = constants.HTYPE_INSTANCE
2794
  _OP_REQP = ["instance_name"]
2795
  REQ_BGL = False
2796

    
2797
  def ExpandNames(self):
2798
    self._ExpandAndLockInstance()
2799

    
2800
  def BuildHooksEnv(self):
2801
    """Build hooks env.
2802

2803
    This runs on master, primary and secondary nodes of the instance.
2804

2805
    """
2806
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2807
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2808
    return env, nl, nl
2809

    
2810
  def CheckPrereq(self):
2811
    """Check prerequisites.
2812

2813
    This checks that the instance is in the cluster and is not running.
2814

2815
    """
2816
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2817
    assert instance is not None, \
2818
      "Cannot retrieve locked instance %s" % self.op.instance_name
2819
    _CheckNodeOnline(self, instance.primary_node)
2820

    
2821
    if instance.disk_template == constants.DT_DISKLESS:
2822
      raise errors.OpPrereqError("Instance '%s' has no disks" %
2823
                                 self.op.instance_name)
2824
    if instance.status != "down":
2825
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2826
                                 self.op.instance_name)
2827
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2828
                                              instance.name,
2829
                                              instance.hypervisor)
2830
    if remote_info.failed or remote_info.data:
2831
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2832
                                 (self.op.instance_name,
2833
                                  instance.primary_node))
2834

    
2835
    self.op.os_type = getattr(self.op, "os_type", None)
2836
    if self.op.os_type is not None:
2837
      # OS verification
2838
      pnode = self.cfg.GetNodeInfo(
2839
        self.cfg.ExpandNodeName(instance.primary_node))
2840
      if pnode is None:
2841
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
2842
                                   self.op.pnode)
2843
      result = self.rpc.call_os_get(pnode.name, self.op.os_type)
2844
      result.Raise()
2845
      if not isinstance(result.data, objects.OS):
2846
        raise errors.OpPrereqError("OS '%s' not in supported OS list for"
2847
                                   " primary node"  % self.op.os_type)
2848

    
2849
    self.instance = instance
2850

    
2851
  def Exec(self, feedback_fn):
2852
    """Reinstall the instance.
2853

2854
    """
2855
    inst = self.instance
2856

    
2857
    if self.op.os_type is not None:
2858
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
2859
      inst.os = self.op.os_type
2860
      self.cfg.Update(inst)
2861

    
2862
    _StartInstanceDisks(self, inst, None)
2863
    try:
2864
      feedback_fn("Running the instance OS create scripts...")
2865
      result = self.rpc.call_instance_os_add(inst.primary_node, inst)
2866
      msg = result.RemoteFailMsg()
2867
      if msg:
2868
        raise errors.OpExecError("Could not install OS for instance %s"
2869
                                 " on node %s: %s" %
2870
                                 (inst.name, inst.primary_node, msg))
2871
    finally:
2872
      _ShutdownInstanceDisks(self, inst)
2873

    
2874

    
2875
class LURenameInstance(LogicalUnit):
2876
  """Rename an instance.
2877

2878
  """
2879
  HPATH = "instance-rename"
2880
  HTYPE = constants.HTYPE_INSTANCE
2881
  _OP_REQP = ["instance_name", "new_name"]
2882

    
2883
  def BuildHooksEnv(self):
2884
    """Build hooks env.
2885

2886
    This runs on master, primary and secondary nodes of the instance.
2887

2888
    """
2889
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2890
    env["INSTANCE_NEW_NAME"] = self.op.new_name
2891
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2892
    return env, nl, nl
2893

    
2894
  def CheckPrereq(self):
2895
    """Check prerequisites.
2896

2897
    This checks that the instance is in the cluster and is not running.
2898

2899
    """
2900
    instance = self.cfg.GetInstanceInfo(
2901
      self.cfg.ExpandInstanceName(self.op.instance_name))
2902
    if instance is None:
2903
      raise errors.OpPrereqError("Instance '%s' not known" %
2904
                                 self.op.instance_name)
2905
    _CheckNodeOnline(self, instance.primary_node)
2906

    
2907
    if instance.status != "down":
2908
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2909
                                 self.op.instance_name)
2910
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2911
                                              instance.name,
2912
                                              instance.hypervisor)
2913
    remote_info.Raise()
2914
    if remote_info.data:
2915
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2916
                                 (self.op.instance_name,
2917
                                  instance.primary_node))
2918
    self.instance = instance
2919

    
2920
    # new name verification
2921
    name_info = utils.HostInfo(self.op.new_name)
2922

    
2923
    self.op.new_name = new_name = name_info.name
2924
    instance_list = self.cfg.GetInstanceList()
2925
    if new_name in instance_list:
2926
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
2927
                                 new_name)
2928

    
2929
    if not getattr(self.op, "ignore_ip", False):
2930
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
2931
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
2932
                                   (name_info.ip, new_name))
2933

    
2934

    
2935
  def Exec(self, feedback_fn):
2936
    """Reinstall the instance.
2937

2938
    """
2939
    inst = self.instance
2940
    old_name = inst.name
2941

    
2942
    if inst.disk_template == constants.DT_FILE:
2943
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2944

    
2945
    self.cfg.RenameInstance(inst.name, self.op.new_name)
2946
    # Change the instance lock. This is definitely safe while we hold the BGL
2947
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
2948
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
2949

    
2950
    # re-read the instance from the configuration after rename
2951
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
2952

    
2953
    if inst.disk_template == constants.DT_FILE:
2954
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2955
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
2956
                                                     old_file_storage_dir,
2957
                                                     new_file_storage_dir)
2958
      result.Raise()
2959
      if not result.data:
2960
        raise errors.OpExecError("Could not connect to node '%s' to rename"
2961
                                 " directory '%s' to '%s' (but the instance"
2962
                                 " has been renamed in Ganeti)" % (
2963
                                 inst.primary_node, old_file_storage_dir,
2964
                                 new_file_storage_dir))
2965

    
2966
      if not result.data[0]:
2967
        raise errors.OpExecError("Could not rename directory '%s' to '%s'"
2968
                                 " (but the instance has been renamed in"
2969
                                 " Ganeti)" % (old_file_storage_dir,
2970
                                               new_file_storage_dir))
2971

    
2972
    _StartInstanceDisks(self, inst, None)
2973
    try:
2974
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
2975
                                                 old_name)
2976
      if result.failed or not result.data:
2977
        msg = ("Could not run OS rename script for instance %s on node %s"
2978
               " (but the instance has been renamed in Ganeti)" %
2979
               (inst.name, inst.primary_node))
2980
        self.proc.LogWarning(msg)
2981
    finally:
2982
      _ShutdownInstanceDisks(self, inst)
2983

    
2984

    
2985
class LURemoveInstance(LogicalUnit):
2986
  """Remove an instance.
2987

2988
  """
2989
  HPATH = "instance-remove"
2990
  HTYPE = constants.HTYPE_INSTANCE
2991
  _OP_REQP = ["instance_name", "ignore_failures"]
2992
  REQ_BGL = False
2993

    
2994
  def ExpandNames(self):
2995
    self._ExpandAndLockInstance()
2996
    self.needed_locks[locking.LEVEL_NODE] = []
2997
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2998

    
2999
  def DeclareLocks(self, level):
3000
    if level == locking.LEVEL_NODE:
3001
      self._LockInstancesNodes()
3002

    
3003
  def BuildHooksEnv(self):
3004
    """Build hooks env.
3005

3006
    This runs on master, primary and secondary nodes of the instance.
3007

3008
    """
3009
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3010
    nl = [self.cfg.GetMasterNode()]
3011
    return env, nl, nl
3012

    
3013
  def CheckPrereq(self):
3014
    """Check prerequisites.
3015

3016
    This checks that the instance is in the cluster.
3017

3018
    """
3019
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3020
    assert self.instance is not None, \
3021
      "Cannot retrieve locked instance %s" % self.op.instance_name
3022

    
3023
  def Exec(self, feedback_fn):
3024
    """Remove the instance.
3025

3026
    """
3027
    instance = self.instance
3028
    logging.info("Shutting down instance %s on node %s",
3029
                 instance.name, instance.primary_node)
3030

    
3031
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance)
3032
    if result.failed or not result.data:
3033
      if self.op.ignore_failures:
3034
        feedback_fn("Warning: can't shutdown instance")
3035
      else:
3036
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
3037
                                 (instance.name, instance.primary_node))
3038

    
3039
    logging.info("Removing block devices for instance %s", instance.name)
3040

    
3041
    if not _RemoveDisks(self, instance):
3042
      if self.op.ignore_failures:
3043
        feedback_fn("Warning: can't remove instance's disks")
3044
      else:
3045
        raise errors.OpExecError("Can't remove instance's disks")
3046

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

    
3049
    self.cfg.RemoveInstance(instance.name)
3050
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
3051

    
3052

    
3053
class LUQueryInstances(NoHooksLU):
3054
  """Logical unit for querying instances.
3055

3056
  """
3057
  _OP_REQP = ["output_fields", "names"]
3058
  REQ_BGL = False
3059
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
3060
                                    "admin_state", "admin_ram",
3061
                                    "disk_template", "ip", "mac", "bridge",
3062
                                    "sda_size", "sdb_size", "vcpus", "tags",
3063
                                    "network_port", "beparams",
3064
                                    "(disk).(size)/([0-9]+)",
3065
                                    "(disk).(sizes)",
3066
                                    "(nic).(mac|ip|bridge)/([0-9]+)",
3067
                                    "(nic).(macs|ips|bridges)",
3068
                                    "(disk|nic).(count)",
3069
                                    "serial_no", "hypervisor", "hvparams",] +
3070
                                  ["hv/%s" % name
3071
                                   for name in constants.HVS_PARAMETERS] +
3072
                                  ["be/%s" % name
3073
                                   for name in constants.BES_PARAMETERS])
3074
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
3075

    
3076

    
3077
  def ExpandNames(self):
3078
    _CheckOutputFields(static=self._FIELDS_STATIC,
3079
                       dynamic=self._FIELDS_DYNAMIC,
3080
                       selected=self.op.output_fields)
3081

    
3082
    self.needed_locks = {}
3083
    self.share_locks[locking.LEVEL_INSTANCE] = 1
3084
    self.share_locks[locking.LEVEL_NODE] = 1
3085

    
3086
    if self.op.names:
3087
      self.wanted = _GetWantedInstances(self, self.op.names)
3088
    else:
3089
      self.wanted = locking.ALL_SET
3090

    
3091
    self.do_locking = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3092
    if self.do_locking:
3093
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
3094
      self.needed_locks[locking.LEVEL_NODE] = []
3095
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3096

    
3097
  def DeclareLocks(self, level):
3098
    if level == locking.LEVEL_NODE and self.do_locking:
3099
      self._LockInstancesNodes()
3100

    
3101
  def CheckPrereq(self):
3102
    """Check prerequisites.
3103

3104
    """
3105
    pass
3106

    
3107
  def Exec(self, feedback_fn):
3108
    """Computes the list of nodes and their attributes.
3109

3110
    """
3111
    all_info = self.cfg.GetAllInstancesInfo()
3112
    if self.do_locking:
3113
      instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
3114
    elif self.wanted != locking.ALL_SET:
3115
      instance_names = self.wanted
3116
      missing = set(instance_names).difference(all_info.keys())
3117
      if missing:
3118
        raise errors.OpExecError(
3119
          "Some instances were removed before retrieving their data: %s"
3120
          % missing)
3121
    else:
3122
      instance_names = all_info.keys()
3123

    
3124
    instance_names = utils.NiceSort(instance_names)
3125
    instance_list = [all_info[iname] for iname in instance_names]
3126

    
3127
    # begin data gathering
3128

    
3129
    nodes = frozenset([inst.primary_node for inst in instance_list])
3130
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
3131

    
3132
    bad_nodes = []
3133
    off_nodes = []
3134
    if self.do_locking:
3135
      live_data = {}
3136
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
3137
      for name in nodes:
3138
        result = node_data[name]
3139
        if result.offline:
3140
          # offline nodes will be in both lists
3141
          off_nodes.append(name)
3142
        if result.failed:
3143
          bad_nodes.append(name)
3144
        else:
3145
          if result.data:
3146
            live_data.update(result.data)
3147
            # else no instance is alive
3148
    else:
3149
      live_data = dict([(name, {}) for name in instance_names])
3150

    
3151
    # end data gathering
3152

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

    
3278
    return output
3279

    
3280

    
3281
class LUFailoverInstance(LogicalUnit):
3282
  """Failover an instance.
3283

3284
  """
3285
  HPATH = "instance-failover"
3286
  HTYPE = constants.HTYPE_INSTANCE
3287
  _OP_REQP = ["instance_name", "ignore_consistency"]
3288
  REQ_BGL = False
3289

    
3290
  def ExpandNames(self):
3291
    self._ExpandAndLockInstance()
3292
    self.needed_locks[locking.LEVEL_NODE] = []
3293
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3294

    
3295
  def DeclareLocks(self, level):
3296
    if level == locking.LEVEL_NODE:
3297
      self._LockInstancesNodes()
3298

    
3299
  def BuildHooksEnv(self):
3300
    """Build hooks env.
3301

3302
    This runs on master, primary and secondary nodes of the instance.
3303

3304
    """
3305
    env = {
3306
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
3307
      }
3308
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3309
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
3310
    return env, nl, nl
3311

    
3312
  def CheckPrereq(self):
3313
    """Check prerequisites.
3314

3315
    This checks that the instance is in the cluster.
3316

3317
    """
3318
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3319
    assert self.instance is not None, \
3320
      "Cannot retrieve locked instance %s" % self.op.instance_name
3321

    
3322
    bep = self.cfg.GetClusterInfo().FillBE(instance)
3323
    if instance.disk_template not in constants.DTS_NET_MIRROR:
3324
      raise errors.OpPrereqError("Instance's disk layout is not"
3325
                                 " network mirrored, cannot failover.")
3326

    
3327
    secondary_nodes = instance.secondary_nodes
3328
    if not secondary_nodes:
3329
      raise errors.ProgrammerError("no secondary node but using "
3330
                                   "a mirrored disk template")
3331

    
3332
    target_node = secondary_nodes[0]
3333
    _CheckNodeOnline(self, target_node)
3334
    # check memory requirements on the secondary node
3335
    _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
3336
                         instance.name, bep[constants.BE_MEMORY],
3337
                         instance.hypervisor)
3338

    
3339
    # check bridge existance
3340
    brlist = [nic.bridge for nic in instance.nics]
3341
    result = self.rpc.call_bridges_exist(target_node, brlist)
3342
    result.Raise()
3343
    if not result.data:
3344
      raise errors.OpPrereqError("One or more target bridges %s does not"
3345
                                 " exist on destination node '%s'" %
3346
                                 (brlist, target_node))
3347

    
3348
  def Exec(self, feedback_fn):
3349
    """Failover an instance.
3350

3351
    The failover is done by shutting it down on its present node and
3352
    starting it on the secondary.
3353

3354
    """
3355
    instance = self.instance
3356

    
3357
    source_node = instance.primary_node
3358
    target_node = instance.secondary_nodes[0]
3359

    
3360
    feedback_fn("* checking disk consistency between source and target")
3361
    for dev in instance.disks:
3362
      # for drbd, these are drbd over lvm
3363
      if not _CheckDiskConsistency(self, dev, target_node, False):
3364
        if instance.status == "up" and not self.op.ignore_consistency:
3365
          raise errors.OpExecError("Disk %s is degraded on target node,"
3366
                                   " aborting failover." % dev.iv_name)
3367

    
3368
    feedback_fn("* shutting down instance on source node")
3369
    logging.info("Shutting down instance %s on node %s",
3370
                 instance.name, source_node)
3371

    
3372
    result = self.rpc.call_instance_shutdown(source_node, instance)
3373
    if result.failed or not result.data:
3374
      if self.op.ignore_consistency:
3375
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
3376
                             " Proceeding"
3377
                             " anyway. Please make sure node %s is down",
3378
                             instance.name, source_node, source_node)
3379
      else:
3380
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
3381
                                 (instance.name, source_node))
3382

    
3383
    feedback_fn("* deactivating the instance's disks on source node")
3384
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
3385
      raise errors.OpExecError("Can't shut down the instance's disks.")
3386

    
3387
    instance.primary_node = target_node
3388
    # distribute new instance config to the other nodes
3389
    self.cfg.Update(instance)
3390

    
3391
    # Only start the instance if it's marked as up
3392
    if instance.status == "up":
3393
      feedback_fn("* activating the instance's disks on target node")
3394
      logging.info("Starting instance %s on node %s",
3395
                   instance.name, target_node)
3396

    
3397
      disks_ok, dummy = _AssembleInstanceDisks(self, instance,
3398
                                               ignore_secondaries=True)
3399
      if not disks_ok:
3400
        _ShutdownInstanceDisks(self, instance)
3401
        raise errors.OpExecError("Can't activate the instance's disks")
3402

    
3403
      feedback_fn("* starting the instance on the target node")
3404
      result = self.rpc.call_instance_start(target_node, instance, None)
3405
      msg = result.RemoteFailMsg()
3406
      if msg:
3407
        _ShutdownInstanceDisks(self, instance)
3408
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
3409
                                 (instance.name, target_node, msg))
3410

    
3411

    
3412
class LUMigrateInstance(LogicalUnit):
3413
  """Migrate an instance.
3414

3415
  This is migration without shutting down, compared to the failover,
3416
  which is done with shutdown.
3417

3418
  """
3419
  HPATH = "instance-migrate"
3420
  HTYPE = constants.HTYPE_INSTANCE
3421
  _OP_REQP = ["instance_name", "live", "cleanup"]
3422

    
3423
  REQ_BGL = False
3424

    
3425
  def ExpandNames(self):
3426
    self._ExpandAndLockInstance()
3427
    self.needed_locks[locking.LEVEL_NODE] = []
3428
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3429

    
3430
  def DeclareLocks(self, level):
3431
    if level == locking.LEVEL_NODE:
3432
      self._LockInstancesNodes()
3433

    
3434
  def BuildHooksEnv(self):
3435
    """Build hooks env.
3436

3437
    This runs on master, primary and secondary nodes of the instance.
3438

3439
    """
3440
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3441
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
3442
    return env, nl, nl
3443

    
3444
  def CheckPrereq(self):
3445
    """Check prerequisites.
3446

3447
    This checks that the instance is in the cluster.
3448

3449
    """
3450
    instance = self.cfg.GetInstanceInfo(
3451
      self.cfg.ExpandInstanceName(self.op.instance_name))
3452
    if instance is None:
3453
      raise errors.OpPrereqError("Instance '%s' not known" %
3454
                                 self.op.instance_name)
3455

    
3456
    if instance.disk_template != constants.DT_DRBD8:
3457
      raise errors.OpPrereqError("Instance's disk layout is not"
3458
                                 " drbd8, cannot migrate.")
3459

    
3460
    secondary_nodes = instance.secondary_nodes
3461
    if not secondary_nodes:
3462
      raise errors.ProgrammerError("no secondary node but using "
3463
                                   "drbd8 disk template")
3464

    
3465
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
3466

    
3467
    target_node = secondary_nodes[0]
3468
    # check memory requirements on the secondary node
3469
    _CheckNodeFreeMemory(self, target_node, "migrating instance %s" %
3470
                         instance.name, i_be[constants.BE_MEMORY],
3471
                         instance.hypervisor)
3472

    
3473
    # check bridge existance
3474
    brlist = [nic.bridge for nic in instance.nics]
3475
    result = self.rpc.call_bridges_exist(target_node, brlist)
3476
    if result.failed or not result.data:
3477
      raise errors.OpPrereqError("One or more target bridges %s does not"
3478
                                 " exist on destination node '%s'" %
3479
                                 (brlist, target_node))
3480

    
3481
    if not self.op.cleanup:
3482
      result = self.rpc.call_instance_migratable(instance.primary_node,
3483
                                                 instance)
3484
      msg = result.RemoteFailMsg()
3485
      if msg:
3486
        raise errors.OpPrereqError("Can't migrate: %s - please use failover" %
3487
                                   msg)
3488

    
3489
    self.instance = instance
3490

    
3491
  def _WaitUntilSync(self):
3492
    """Poll with custom rpc for disk sync.
3493

3494
    This uses our own step-based rpc call.
3495

3496
    """
3497
    self.feedback_fn("* wait until resync is done")
3498
    all_done = False
3499
    while not all_done:
3500
      all_done = True
3501
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
3502
                                            self.nodes_ip,
3503
                                            self.instance.disks)
3504
      min_percent = 100
3505
      for node, nres in result.items():
3506
        msg = nres.RemoteFailMsg()
3507
        if msg:
3508
          raise errors.OpExecError("Cannot resync disks on node %s: %s" %
3509
                                   (node, msg))
3510
        node_done, node_percent = nres.data[1]
3511
        all_done = all_done and node_done
3512
        if node_percent is not None:
3513
          min_percent = min(min_percent, node_percent)
3514
      if not all_done:
3515
        if min_percent < 100:
3516
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
3517
        time.sleep(2)
3518

    
3519
  def _EnsureSecondary(self, node):
3520
    """Demote a node to secondary.
3521

3522
    """
3523
    self.feedback_fn("* switching node %s to secondary mode" % node)
3524

    
3525
    for dev in self.instance.disks:
3526
      self.cfg.SetDiskID(dev, node)
3527

    
3528
    result = self.rpc.call_blockdev_close(node, self.instance.name,
3529
                                          self.instance.disks)
3530
    msg = result.RemoteFailMsg()
3531
    if msg:
3532
      raise errors.OpExecError("Cannot change disk to secondary on node %s,"
3533
                               " error %s" % (node, msg))
3534

    
3535
  def _GoStandalone(self):
3536
    """Disconnect from the network.
3537

3538
    """
3539
    self.feedback_fn("* changing into standalone mode")
3540
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
3541
                                               self.instance.disks)
3542
    for node, nres in result.items():
3543
      msg = nres.RemoteFailMsg()
3544
      if msg:
3545
        raise errors.OpExecError("Cannot disconnect disks node %s,"
3546
                                 " error %s" % (node, msg))
3547

    
3548
  def _GoReconnect(self, multimaster):
3549
    """Reconnect to the network.
3550

3551
    """
3552
    if multimaster:
3553
      msg = "dual-master"
3554
    else:
3555
      msg = "single-master"
3556
    self.feedback_fn("* changing disks into %s mode" % msg)
3557
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
3558
                                           self.instance.disks,
3559
                                           self.instance.name, multimaster)
3560
    for node, nres in result.items():
3561
      msg = nres.RemoteFailMsg()
3562
      if msg:
3563
        raise errors.OpExecError("Cannot change disks config on node %s,"
3564
                                 " error: %s" % (node, msg))
3565

    
3566
  def _ExecCleanup(self):
3567
    """Try to cleanup after a failed migration.
3568

3569
    The cleanup is done by:
3570
      - check that the instance is running only on one node
3571
        (and update the config if needed)
3572
      - change disks on its secondary node to secondary
3573
      - wait until disks are fully synchronized
3574
      - disconnect from the network
3575
      - change disks into single-master mode
3576
      - wait again until disks are fully synchronized
3577

3578
    """
3579
    instance = self.instance
3580
    target_node = self.target_node
3581
    source_node = self.source_node
3582

    
3583
    # check running on only one node
3584
    self.feedback_fn("* checking where the instance actually runs"
3585
                     " (if this hangs, the hypervisor might be in"
3586
                     " a bad state)")
3587
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
3588
    for node, result in ins_l.items():
3589
      result.Raise()
3590
      if not isinstance(result.data, list):
3591
        raise errors.OpExecError("Can't contact node '%s'" % node)
3592

    
3593
    runningon_source = instance.name in ins_l[source_node].data
3594
    runningon_target = instance.name in ins_l[target_node].data
3595

    
3596
    if runningon_source and runningon_target:
3597
      raise errors.OpExecError("Instance seems to be running on two nodes,"
3598
                               " or the hypervisor is confused. You will have"
3599
                               " to ensure manually that it runs only on one"
3600
                               " and restart this operation.")
3601

    
3602
    if not (runningon_source or runningon_target):
3603
      raise errors.OpExecError("Instance does not seem to be running at all."
3604
                               " In this case, it's safer to repair by"
3605
                               " running 'gnt-instance stop' to ensure disk"
3606
                               " shutdown, and then restarting it.")
3607

    
3608
    if runningon_target:
3609
      # the migration has actually succeeded, we need to update the config
3610
      self.feedback_fn("* instance running on secondary node (%s),"
3611
                       " updating config" % target_node)
3612
      instance.primary_node = target_node
3613
      self.cfg.Update(instance)
3614
      demoted_node = source_node
3615
    else:
3616
      self.feedback_fn("* instance confirmed to be running on its"
3617
                       " primary node (%s)" % source_node)
3618
      demoted_node = target_node
3619

    
3620
    self._EnsureSecondary(demoted_node)
3621
    try:
3622
      self._WaitUntilSync()
3623
    except errors.OpExecError:
3624
      # we ignore here errors, since if the device is standalone, it
3625
      # won't be able to sync
3626
      pass
3627
    self._GoStandalone()
3628
    self._GoReconnect(False)
3629
    self._WaitUntilSync()
3630

    
3631
    self.feedback_fn("* done")
3632

    
3633
  def _ExecMigration(self):
3634
    """Migrate an instance.
3635

3636
    The migrate is done by:
3637
      - change the disks into dual-master mode
3638
      - wait until disks are fully synchronized again
3639
      - migrate the instance
3640
      - change disks on the new secondary node (the old primary) to secondary
3641
      - wait until disks are fully synchronized
3642
      - change disks into single-master mode
3643

3644
    """
3645
    instance = self.instance
3646
    target_node = self.target_node
3647
    source_node = self.source_node
3648

    
3649
    self.feedback_fn("* checking disk consistency between source and target")
3650
    for dev in instance.disks:
3651
      if not _CheckDiskConsistency(self, dev, target_node, False):
3652
        raise errors.OpExecError("Disk %s is degraded or not fully"
3653
                                 " synchronized on target node,"
3654
                                 " aborting migrate." % dev.iv_name)
3655

    
3656
    self._EnsureSecondary(target_node)
3657
    self._GoStandalone()
3658
    self._GoReconnect(True)
3659
    self._WaitUntilSync()
3660

    
3661
    self.feedback_fn("* migrating instance to %s" % target_node)
3662
    time.sleep(10)
3663
    result = self.rpc.call_instance_migrate(source_node, instance,
3664
                                            self.nodes_ip[target_node],
3665
                                            self.op.live)
3666
    msg = result.RemoteFailMsg()
3667
    if msg:
3668
      logging.error("Instance migration failed, trying to revert"
3669
                    " disk status: %s", msg)
3670
      try:
3671
        self._EnsureSecondary(target_node)
3672
        self._GoStandalone()
3673
        self._GoReconnect(False)
3674
        self._WaitUntilSync()
3675
      except errors.OpExecError, err:
3676
        self.LogWarning("Migration failed and I can't reconnect the"
3677
                        " drives: error '%s'\n"
3678
                        "Please look and recover the instance status" %
3679
                        str(err))
3680

    
3681
      raise errors.OpExecError("Could not migrate instance %s: %s" %
3682
                               (instance.name, msg))
3683
    time.sleep(10)
3684

    
3685
    instance.primary_node = target_node
3686
    # distribute new instance config to the other nodes
3687
    self.cfg.Update(instance)
3688

    
3689
    self._EnsureSecondary(source_node)
3690
    self._WaitUntilSync()
3691
    self._GoStandalone()
3692
    self._GoReconnect(False)
3693
    self._WaitUntilSync()
3694

    
3695
    self.feedback_fn("* done")
3696

    
3697
  def Exec(self, feedback_fn):
3698
    """Perform the migration.
3699

3700
    """
3701
    self.feedback_fn = feedback_fn
3702

    
3703
    self.source_node = self.instance.primary_node
3704
    self.target_node = self.instance.secondary_nodes[0]
3705
    self.all_nodes = [self.source_node, self.target_node]
3706
    self.nodes_ip = {
3707
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
3708
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
3709
      }
3710
    if self.op.cleanup:
3711
      return self._ExecCleanup()
3712
    else:
3713
      return self._ExecMigration()
3714

    
3715

    
3716
def _CreateBlockDev(lu, node, instance, device, force_create,
3717
                    info, force_open):
3718
  """Create a tree of block devices on a given node.
3719

3720
  If this device type has to be created on secondaries, create it and
3721
  all its children.
3722

3723
  If not, just recurse to children keeping the same 'force' value.
3724

3725
  @param lu: the lu on whose behalf we execute
3726
  @param node: the node on which to create the device
3727
  @type instance: L{objects.Instance}
3728
  @param instance: the instance which owns the device
3729
  @type device: L{objects.Disk}
3730
  @param device: the device to create
3731
  @type force_create: boolean
3732
  @param force_create: whether to force creation of this device; this
3733
      will be change to True whenever we find a device which has
3734
      CreateOnSecondary() attribute
3735
  @param info: the extra 'metadata' we should attach to the device
3736
      (this will be represented as a LVM tag)
3737
  @type force_open: boolean
3738
  @param force_open: this parameter will be passes to the
3739
      L{backend.CreateBlockDevice} function where it specifies
3740
      whether we run on primary or not, and it affects both
3741
      the child assembly and the device own Open() execution
3742

3743
  """
3744
  if device.CreateOnSecondary():
3745
    force_create = True
3746

    
3747
  if device.children:
3748
    for child in device.children:
3749
      _CreateBlockDev(lu, node, instance, child, force_create,
3750
                      info, force_open)
3751

    
3752
  if not force_create:
3753
    return
3754

    
3755
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
3756

    
3757

    
3758
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
3759
  """Create a single block device on a given node.
3760

3761
  This will not recurse over children of the device, so they must be
3762
  created in advance.
3763

3764
  @param lu: the lu on whose behalf we execute
3765
  @param node: the node on which to create the device
3766
  @type instance: L{objects.Instance}
3767
  @param instance: the instance which owns the device
3768
  @type device: L{objects.Disk}
3769
  @param device: the device to create
3770
  @param info: the extra 'metadata' we should attach to the device
3771
      (this will be represented as a LVM tag)
3772
  @type force_open: boolean
3773
  @param force_open: this parameter will be passes to the
3774
      L{backend.CreateBlockDevice} function where it specifies
3775
      whether we run on primary or not, and it affects both
3776
      the child assembly and the device own Open() execution
3777

3778
  """
3779
  lu.cfg.SetDiskID(device, node)
3780
  result = lu.rpc.call_blockdev_create(node, device, device.size,
3781
                                       instance.name, force_open, info)
3782
  msg = result.RemoteFailMsg()
3783
  if msg:
3784
    raise errors.OpExecError("Can't create block device %s on"
3785
                             " node %s for instance %s: %s" %
3786
                             (device, node, instance.name, msg))
3787
  if device.physical_id is None:
3788
    device.physical_id = result.data[1]
3789

    
3790

    
3791
def _GenerateUniqueNames(lu, exts):
3792
  """Generate a suitable LV name.
3793

3794
  This will generate a logical volume name for the given instance.
3795

3796
  """
3797
  results = []
3798
  for val in exts:
3799
    new_id = lu.cfg.GenerateUniqueID()
3800
    results.append("%s%s" % (new_id, val))
3801
  return results
3802

    
3803

    
3804
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
3805
                         p_minor, s_minor):
3806
  """Generate a drbd8 device complete with its children.
3807

3808
  """
3809
  port = lu.cfg.AllocatePort()
3810
  vgname = lu.cfg.GetVGName()
3811
  shared_secret = lu.cfg.GenerateDRBDSecret()
3812
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
3813
                          logical_id=(vgname, names[0]))
3814
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
3815
                          logical_id=(vgname, names[1]))
3816
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
3817
                          logical_id=(primary, secondary, port,
3818
                                      p_minor, s_minor,
3819
                                      shared_secret),
3820
                          children=[dev_data, dev_meta],
3821
                          iv_name=iv_name)
3822
  return drbd_dev
3823

    
3824

    
3825
def _GenerateDiskTemplate(lu, template_name,
3826
                          instance_name, primary_node,
3827
                          secondary_nodes, disk_info,
3828
                          file_storage_dir, file_driver,
3829
                          base_index):
3830
  """Generate the entire disk layout for a given template type.
3831

3832
  """
3833
  #TODO: compute space requirements
3834

    
3835
  vgname = lu.cfg.GetVGName()
3836
  disk_count = len(disk_info)
3837
  disks = []
3838
  if template_name == constants.DT_DISKLESS:
3839
    pass
3840
  elif template_name == constants.DT_PLAIN:
3841
    if len(secondary_nodes) != 0:
3842
      raise errors.ProgrammerError("Wrong template configuration")
3843

    
3844
    names = _GenerateUniqueNames(lu, [".disk%d" % i
3845
                                      for i in range(disk_count)])
3846
    for idx, disk in enumerate(disk_info):
3847
      disk_index = idx + base_index
3848
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
3849
                              logical_id=(vgname, names[idx]),
3850
                              iv_name="disk/%d" % disk_index)
3851
      disks.append(disk_dev)
3852
  elif template_name == constants.DT_DRBD8:
3853
    if len(secondary_nodes) != 1:
3854
      raise errors.ProgrammerError("Wrong template configuration")
3855
    remote_node = secondary_nodes[0]
3856
    minors = lu.cfg.AllocateDRBDMinor(
3857
      [primary_node, remote_node] * len(disk_info), instance_name)
3858

    
3859
    names = []
3860
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % i
3861
                                               for i in range(disk_count)]):
3862
      names.append(lv_prefix + "_data")
3863
      names.append(lv_prefix + "_meta")
3864
    for idx, disk in enumerate(disk_info):
3865
      disk_index = idx + base_index
3866
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
3867
                                      disk["size"], names[idx*2:idx*2+2],
3868
                                      "disk/%d" % disk_index,
3869
                                      minors[idx*2], minors[idx*2+1])
3870
      disks.append(disk_dev)
3871
  elif template_name == constants.DT_FILE:
3872
    if len(secondary_nodes) != 0:
3873
      raise errors.ProgrammerError("Wrong template configuration")
3874

    
3875
    for idx, disk in enumerate(disk_info):
3876
      disk_index = idx + base_index
3877
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
3878
                              iv_name="disk/%d" % disk_index,
3879
                              logical_id=(file_driver,
3880
                                          "%s/disk%d" % (file_storage_dir,
3881
                                                         idx)))
3882
      disks.append(disk_dev)
3883
  else:
3884
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
3885
  return disks
3886

    
3887

    
3888
def _GetInstanceInfoText(instance):
3889
  """Compute that text that should be added to the disk's metadata.
3890

3891
  """
3892
  return "originstname+%s" % instance.name
3893

    
3894

    
3895
def _CreateDisks(lu, instance):
3896
  """Create all disks for an instance.
3897

3898
  This abstracts away some work from AddInstance.
3899

3900
  @type lu: L{LogicalUnit}
3901
  @param lu: the logical unit on whose behalf we execute
3902
  @type instance: L{objects.Instance}
3903
  @param instance: the instance whose disks we should create
3904
  @rtype: boolean
3905
  @return: the success of the creation
3906

3907
  """
3908
  info = _GetInstanceInfoText(instance)
3909
  pnode = instance.primary_node
3910

    
3911
  if instance.disk_template == constants.DT_FILE:
3912
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
3913
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
3914

    
3915
    if result.failed or not result.data:
3916
      raise errors.OpExecError("Could not connect to node '%s'" % pnode)
3917

    
3918
    if not result.data[0]:
3919
      raise errors.OpExecError("Failed to create directory '%s'" %
3920
                               file_storage_dir)
3921

    
3922
  # Note: this needs to be kept in sync with adding of disks in
3923
  # LUSetInstanceParams
3924
  for device in instance.disks:
3925
    logging.info("Creating volume %s for instance %s",
3926
                 device.iv_name, instance.name)
3927
    #HARDCODE
3928
    for node in instance.all_nodes:
3929
      f_create = node == pnode
3930
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
3931

    
3932

    
3933
def _RemoveDisks(lu, instance):
3934
  """Remove all disks for an instance.
3935

3936
  This abstracts away some work from `AddInstance()` and
3937
  `RemoveInstance()`. Note that in case some of the devices couldn't
3938
  be removed, the removal will continue with the other ones (compare
3939
  with `_CreateDisks()`).
3940

3941
  @type lu: L{LogicalUnit}
3942
  @param lu: the logical unit on whose behalf we execute
3943
  @type instance: L{objects.Instance}
3944
  @param instance: the instance whose disks we should remove
3945
  @rtype: boolean
3946
  @return: the success of the removal
3947

3948
  """
3949
  logging.info("Removing block devices for instance %s", instance.name)
3950

    
3951
  result = True
3952
  for device in instance.disks:
3953
    for node, disk in device.ComputeNodeTree(instance.primary_node):
3954
      lu.cfg.SetDiskID(disk, node)
3955
      result = lu.rpc.call_blockdev_remove(node, disk)
3956
      if result.failed or not result.data:
3957
        lu.proc.LogWarning("Could not remove block device %s on node %s,"
3958
                           " continuing anyway", device.iv_name, node)
3959
        result = False
3960

    
3961
  if instance.disk_template == constants.DT_FILE:
3962
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
3963
    result = lu.rpc.call_file_storage_dir_remove(instance.primary_node,
3964
                                                 file_storage_dir)
3965
    if result.failed or not result.data:
3966
      logging.error("Could not remove directory '%s'", file_storage_dir)
3967
      result = False
3968

    
3969
  return result
3970

    
3971

    
3972
def _ComputeDiskSize(disk_template, disks):
3973
  """Compute disk size requirements in the volume group
3974

3975
  """
3976
  # Required free disk space as a function of disk and swap space
3977
  req_size_dict = {
3978
    constants.DT_DISKLESS: None,
3979
    constants.DT_PLAIN: sum(d["size"] for d in disks),
3980
    # 128 MB are added for drbd metadata for each disk
3981
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
3982
    constants.DT_FILE: None,
3983
  }
3984

    
3985
  if disk_template not in req_size_dict:
3986
    raise errors.ProgrammerError("Disk template '%s' size requirement"
3987
                                 " is unknown" %  disk_template)
3988

    
3989
  return req_size_dict[disk_template]
3990

    
3991

    
3992
def _CheckHVParams(lu, nodenames, hvname, hvparams):
3993
  """Hypervisor parameter validation.
3994

3995
  This function abstract the hypervisor parameter validation to be
3996
  used in both instance create and instance modify.
3997

3998
  @type lu: L{LogicalUnit}
3999
  @param lu: the logical unit for which we check
4000
  @type nodenames: list
4001
  @param nodenames: the list of nodes on which we should check
4002
  @type hvname: string
4003
  @param hvname: the name of the hypervisor we should use
4004
  @type hvparams: dict
4005
  @param hvparams: the parameters which we need to check
4006
  @raise errors.OpPrereqError: if the parameters are not valid
4007

4008
  """
4009
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
4010
                                                  hvname,
4011
                                                  hvparams)
4012
  for node in nodenames:
4013
    info = hvinfo[node]
4014
    info.Raise()
4015
    if not info.data or not isinstance(info.data, (tuple, list)):
4016
      raise errors.OpPrereqError("Cannot get current information"
4017
                                 " from node '%s' (%s)" % (node, info.data))
4018
    if not info.data[0]:
4019
      raise errors.OpPrereqError("Hypervisor parameter validation failed:"
4020
                                 " %s" % info.data[1])
4021

    
4022

    
4023
class LUCreateInstance(LogicalUnit):
4024
  """Create an instance.
4025

4026
  """
4027
  HPATH = "instance-add"
4028
  HTYPE = constants.HTYPE_INSTANCE
4029
  _OP_REQP = ["instance_name", "disks", "disk_template",
4030
              "mode", "start",
4031
              "wait_for_sync", "ip_check", "nics",
4032
              "hvparams", "beparams"]
4033
  REQ_BGL = False
4034

    
4035
  def _ExpandNode(self, node):
4036
    """Expands and checks one node name.
4037

4038
    """
4039
    node_full = self.cfg.ExpandNodeName(node)
4040
    if node_full is None:
4041
      raise errors.OpPrereqError("Unknown node %s" % node)
4042
    return node_full
4043

    
4044
  def ExpandNames(self):
4045
    """ExpandNames for CreateInstance.
4046

4047
    Figure out the right locks for instance creation.
4048

4049
    """
4050
    self.needed_locks = {}
4051

    
4052
    # set optional parameters to none if they don't exist
4053
    for attr in ["pnode", "snode", "iallocator", "hypervisor"]:
4054
      if not hasattr(self.op, attr):
4055
        setattr(self.op, attr, None)
4056

    
4057
    # cheap checks, mostly valid constants given
4058

    
4059
    # verify creation mode
4060
    if self.op.mode not in (constants.INSTANCE_CREATE,
4061
                            constants.INSTANCE_IMPORT):
4062
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
4063
                                 self.op.mode)
4064

    
4065
    # disk template and mirror node verification
4066
    if self.op.disk_template not in constants.DISK_TEMPLATES:
4067
      raise errors.OpPrereqError("Invalid disk template name")
4068

    
4069
    if self.op.hypervisor is None:
4070
      self.op.hypervisor = self.cfg.GetHypervisorType()
4071

    
4072
    cluster = self.cfg.GetClusterInfo()
4073
    enabled_hvs = cluster.enabled_hypervisors
4074
    if self.op.hypervisor not in enabled_hvs:
4075
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
4076
                                 " cluster (%s)" % (self.op.hypervisor,
4077
                                  ",".join(enabled_hvs)))
4078

    
4079
    # check hypervisor parameter syntax (locally)
4080

    
4081
    filled_hvp = cluster.FillDict(cluster.hvparams[self.op.hypervisor],
4082
                                  self.op.hvparams)
4083
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
4084
    hv_type.CheckParameterSyntax(filled_hvp)
4085

    
4086
    # fill and remember the beparams dict
4087
    utils.CheckBEParams(self.op.beparams)
4088
    self.be_full = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
4089
                                    self.op.beparams)
4090

    
4091
    #### instance parameters check
4092

    
4093
    # instance name verification
4094
    hostname1 = utils.HostInfo(self.op.instance_name)
4095
    self.op.instance_name = instance_name = hostname1.name
4096

    
4097
    # this is just a preventive check, but someone might still add this
4098
    # instance in the meantime, and creation will fail at lock-add time
4099
    if instance_name in self.cfg.GetInstanceList():
4100
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4101
                                 instance_name)
4102

    
4103
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
4104

    
4105
    # NIC buildup
4106
    self.nics = []
4107
    for nic in self.op.nics:
4108
      # ip validity checks
4109
      ip = nic.get("ip", None)
4110
      if ip is None or ip.lower() == "none":
4111
        nic_ip = None
4112
      elif ip.lower() == constants.VALUE_AUTO:
4113
        nic_ip = hostname1.ip
4114
      else:
4115
        if not utils.IsValidIP(ip):
4116
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
4117
                                     " like a valid IP" % ip)
4118
        nic_ip = ip
4119

    
4120
      # MAC address verification
4121
      mac = nic.get("mac", constants.VALUE_AUTO)
4122
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
4123
        if not utils.IsValidMac(mac.lower()):
4124
          raise errors.OpPrereqError("Invalid MAC address specified: %s" %
4125
                                     mac)
4126
      # bridge verification
4127
      bridge = nic.get("bridge", self.cfg.GetDefBridge())
4128
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, bridge=bridge))
4129

    
4130
    # disk checks/pre-build
4131
    self.disks = []
4132
    for disk in self.op.disks:
4133
      mode = disk.get("mode", constants.DISK_RDWR)
4134
      if mode not in constants.DISK_ACCESS_SET:
4135
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
4136
                                   mode)
4137
      size = disk.get("size", None)
4138
      if size is None:
4139
        raise errors.OpPrereqError("Missing disk size")
4140
      try:
4141
        size = int(size)
4142
      except ValueError:
4143
        raise errors.OpPrereqError("Invalid disk size '%s'" % size)
4144
      self.disks.append({"size": size, "mode": mode})
4145

    
4146
    # used in CheckPrereq for ip ping check
4147
    self.check_ip = hostname1.ip
4148

    
4149
    # file storage checks
4150
    if (self.op.file_driver and
4151
        not self.op.file_driver in constants.FILE_DRIVER):
4152
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
4153
                                 self.op.file_driver)
4154

    
4155
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
4156
      raise errors.OpPrereqError("File storage directory path not absolute")
4157

    
4158
    ### Node/iallocator related checks
4159
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
4160
      raise errors.OpPrereqError("One and only one of iallocator and primary"
4161
                                 " node must be given")
4162

    
4163
    if self.op.iallocator:
4164
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4165
    else:
4166
      self.op.pnode = self._ExpandNode(self.op.pnode)
4167
      nodelist = [self.op.pnode]
4168
      if self.op.snode is not None:
4169
        self.op.snode = self._ExpandNode(self.op.snode)
4170
        nodelist.append(self.op.snode)
4171
      self.needed_locks[locking.LEVEL_NODE] = nodelist
4172

    
4173
    # in case of import lock the source node too
4174
    if self.op.mode == constants.INSTANCE_IMPORT:
4175
      src_node = getattr(self.op, "src_node", None)
4176
      src_path = getattr(self.op, "src_path", None)
4177

    
4178
      if src_path is None:
4179
        self.op.src_path = src_path = self.op.instance_name
4180

    
4181
      if src_node is None:
4182
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4183
        self.op.src_node = None
4184
        if os.path.isabs(src_path):
4185
          raise errors.OpPrereqError("Importing an instance from an absolute"
4186
                                     " path requires a source node option.")
4187
      else:
4188
        self.op.src_node = src_node = self._ExpandNode(src_node)
4189
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4190
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
4191
        if not os.path.isabs(src_path):
4192
          self.op.src_path = src_path = \
4193
            os.path.join(constants.EXPORT_DIR, src_path)
4194

    
4195
    else: # INSTANCE_CREATE
4196
      if getattr(self.op, "os_type", None) is None:
4197
        raise errors.OpPrereqError("No guest OS specified")
4198

    
4199
  def _RunAllocator(self):
4200
    """Run the allocator based on input opcode.
4201

4202
    """
4203
    nics = [n.ToDict() for n in self.nics]
4204
    ial = IAllocator(self,
4205
                     mode=constants.IALLOCATOR_MODE_ALLOC,
4206
                     name=self.op.instance_name,
4207
                     disk_template=self.op.disk_template,
4208
                     tags=[],
4209
                     os=self.op.os_type,
4210
                     vcpus=self.be_full[constants.BE_VCPUS],
4211
                     mem_size=self.be_full[constants.BE_MEMORY],
4212
                     disks=self.disks,
4213
                     nics=nics,
4214
                     hypervisor=self.op.hypervisor,
4215
                     )
4216

    
4217
    ial.Run(self.op.iallocator)
4218

    
4219
    if not ial.success:
4220
      raise errors.OpPrereqError("Can't compute nodes using"
4221
                                 " iallocator '%s': %s" % (self.op.iallocator,
4222
                                                           ial.info))
4223
    if len(ial.nodes) != ial.required_nodes:
4224
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
4225
                                 " of nodes (%s), required %s" %
4226
                                 (self.op.iallocator, len(ial.nodes),
4227
                                  ial.required_nodes))
4228
    self.op.pnode = ial.nodes[0]
4229
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
4230
                 self.op.instance_name, self.op.iallocator,
4231
                 ", ".join(ial.nodes))
4232
    if ial.required_nodes == 2:
4233
      self.op.snode = ial.nodes[1]
4234

    
4235
  def BuildHooksEnv(self):
4236
    """Build hooks env.
4237

4238
    This runs on master, primary and secondary nodes of the instance.
4239

4240
    """
4241
    env = {
4242
      "INSTANCE_DISK_TEMPLATE": self.op.disk_template,
4243
      "INSTANCE_DISK_SIZE": ",".join(str(d["size"]) for d in self.disks),
4244
      "INSTANCE_ADD_MODE": self.op.mode,
4245
      }
4246
    if self.op.mode == constants.INSTANCE_IMPORT:
4247
      env["INSTANCE_SRC_NODE"] = self.op.src_node
4248
      env["INSTANCE_SRC_PATH"] = self.op.src_path
4249
      env["INSTANCE_SRC_IMAGES"] = self.src_images
4250

    
4251
    env.update(_BuildInstanceHookEnv(name=self.op.instance_name,
4252
      primary_node=self.op.pnode,
4253
      secondary_nodes=self.secondaries,
4254
      status=self.instance_status,
4255
      os_type=self.op.os_type,
4256
      memory=self.be_full[constants.BE_MEMORY],
4257
      vcpus=self.be_full[constants.BE_VCPUS],
4258
      nics=[(n.ip, n.bridge, n.mac) for n in self.nics],
4259
    ))
4260

    
4261
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
4262
          self.secondaries)
4263
    return env, nl, nl
4264

    
4265

    
4266
  def CheckPrereq(self):
4267
    """Check prerequisites.
4268

4269
    """
4270
    if (not self.cfg.GetVGName() and
4271
        self.op.disk_template not in constants.DTS_NOT_LVM):
4272
      raise errors.OpPrereqError("Cluster does not support lvm-based"
4273
                                 " instances")
4274

    
4275

    
4276
    if self.op.mode == constants.INSTANCE_IMPORT:
4277
      src_node = self.op.src_node
4278
      src_path = self.op.src_path
4279

    
4280
      if src_node is None:
4281
        exp_list = self.rpc.call_export_list(
4282
          self.acquired_locks[locking.LEVEL_NODE])
4283
        found = False
4284
        for node in exp_list:
4285
          if not exp_list[node].failed and src_path in exp_list[node].data:
4286
            found = True
4287
            self.op.src_node = src_node = node
4288
            self.op.src_path = src_path = os.path.join(constants.EXPORT_DIR,
4289
                                                       src_path)
4290
            break
4291
        if not found:
4292
          raise errors.OpPrereqError("No export found for relative path %s" %
4293
                                      src_path)
4294

    
4295
      _CheckNodeOnline(self, src_node)
4296
      result = self.rpc.call_export_info(src_node, src_path)
4297
      result.Raise()
4298
      if not result.data:
4299
        raise errors.OpPrereqError("No export found in dir %s" % src_path)
4300

    
4301
      export_info = result.data
4302
      if not export_info.has_section(constants.INISECT_EXP):
4303
        raise errors.ProgrammerError("Corrupted export config")
4304

    
4305
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
4306
      if (int(ei_version) != constants.EXPORT_VERSION):
4307
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
4308
                                   (ei_version, constants.EXPORT_VERSION))
4309

    
4310
      # Check that the new instance doesn't have less disks than the export
4311
      instance_disks = len(self.disks)
4312
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
4313
      if instance_disks < export_disks:
4314
        raise errors.OpPrereqError("Not enough disks to import."
4315
                                   " (instance: %d, export: %d)" %
4316
                                   (instance_disks, export_disks))
4317

    
4318
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
4319
      disk_images = []
4320
      for idx in range(export_disks):
4321
        option = 'disk%d_dump' % idx
4322
        if export_info.has_option(constants.INISECT_INS, option):
4323
          # FIXME: are the old os-es, disk sizes, etc. useful?
4324
          export_name = export_info.get(constants.INISECT_INS, option)
4325
          image = os.path.join(src_path, export_name)
4326
          disk_images.append(image)
4327
        else:
4328
          disk_images.append(False)
4329

    
4330
      self.src_images = disk_images
4331

    
4332
      old_name = export_info.get(constants.INISECT_INS, 'name')
4333
      # FIXME: int() here could throw a ValueError on broken exports
4334
      exp_nic_count = int(export_info.get(constants.INISECT_INS, 'nic_count'))
4335
      if self.op.instance_name == old_name:
4336
        for idx, nic in enumerate(self.nics):
4337
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
4338
            nic_mac_ini = 'nic%d_mac' % idx
4339
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
4340

    
4341
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
4342
    if self.op.start and not self.op.ip_check:
4343
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
4344
                                 " adding an instance in start mode")
4345

    
4346
    if self.op.ip_check:
4347
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
4348
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4349
                                   (self.check_ip, self.op.instance_name))
4350

    
4351
    #### allocator run
4352

    
4353
    if self.op.iallocator is not None:
4354
      self._RunAllocator()
4355

    
4356
    #### node related checks
4357

    
4358
    # check primary node
4359
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
4360
    assert self.pnode is not None, \
4361
      "Cannot retrieve locked node %s" % self.op.pnode
4362
    if pnode.offline:
4363
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
4364
                                 pnode.name)
4365

    
4366
    self.secondaries = []
4367

    
4368
    # mirror node verification
4369
    if self.op.disk_template in constants.DTS_NET_MIRROR:
4370
      if self.op.snode is None:
4371
        raise errors.OpPrereqError("The networked disk templates need"
4372
                                   " a mirror node")
4373
      if self.op.snode == pnode.name:
4374
        raise errors.OpPrereqError("The secondary node cannot be"
4375
                                   " the primary node.")
4376
      self.secondaries.append(self.op.snode)
4377
      _CheckNodeOnline(self, self.op.snode)
4378

    
4379
    nodenames = [pnode.name] + self.secondaries
4380

    
4381
    req_size = _ComputeDiskSize(self.op.disk_template,
4382
                                self.disks)
4383

    
4384
    # Check lv size requirements
4385
    if req_size is not None:
4386
      nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
4387
                                         self.op.hypervisor)
4388
      for node in nodenames:
4389
        info = nodeinfo[node]
4390
        info.Raise()
4391
        info = info.data
4392
        if not info:
4393
          raise errors.OpPrereqError("Cannot get current information"
4394
                                     " from node '%s'" % node)
4395
        vg_free = info.get('vg_free', None)
4396
        if not isinstance(vg_free, int):
4397
          raise errors.OpPrereqError("Can't compute free disk space on"
4398
                                     " node %s" % node)
4399
        if req_size > info['vg_free']:
4400
          raise errors.OpPrereqError("Not enough disk space on target node %s."
4401
                                     " %d MB available, %d MB required" %
4402
                                     (node, info['vg_free'], req_size))
4403

    
4404
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
4405

    
4406
    # os verification
4407
    result = self.rpc.call_os_get(pnode.name, self.op.os_type)
4408
    result.Raise()
4409
    if not isinstance(result.data, objects.OS):
4410
      raise errors.OpPrereqError("OS '%s' not in supported os list for"
4411
                                 " primary node"  % self.op.os_type)
4412

    
4413
    # bridge check on primary node
4414
    bridges = [n.bridge for n in self.nics]
4415
    result = self.rpc.call_bridges_exist(self.pnode.name, bridges)
4416
    result.Raise()
4417
    if not result.data:
4418
      raise errors.OpPrereqError("One of the target bridges '%s' does not"
4419
                                 " exist on destination node '%s'" %
4420
                                 (",".join(bridges), pnode.name))
4421

    
4422
    # memory check on primary node
4423
    if self.op.start:
4424
      _CheckNodeFreeMemory(self, self.pnode.name,
4425
                           "creating instance %s" % self.op.instance_name,
4426
                           self.be_full[constants.BE_MEMORY],
4427
                           self.op.hypervisor)
4428

    
4429
    if self.op.start:
4430
      self.instance_status = 'up'
4431
    else:
4432
      self.instance_status = 'down'
4433

    
4434
  def Exec(self, feedback_fn):
4435
    """Create and add the instance to the cluster.
4436

4437
    """
4438
    instance = self.op.instance_name
4439
    pnode_name = self.pnode.name
4440

    
4441
    for nic in self.nics:
4442
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
4443
        nic.mac = self.cfg.GenerateMAC()
4444

    
4445
    ht_kind = self.op.hypervisor
4446
    if ht_kind in constants.HTS_REQ_PORT:
4447
      network_port = self.cfg.AllocatePort()
4448
    else:
4449
      network_port = None
4450

    
4451
    ##if self.op.vnc_bind_address is None:
4452
    ##  self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
4453

    
4454
    # this is needed because os.path.join does not accept None arguments
4455
    if self.op.file_storage_dir is None:
4456
      string_file_storage_dir = ""
4457
    else:
4458
      string_file_storage_dir = self.op.file_storage_dir
4459

    
4460
    # build the full file storage dir path
4461
    file_storage_dir = os.path.normpath(os.path.join(
4462
                                        self.cfg.GetFileStorageDir(),
4463
                                        string_file_storage_dir, instance))
4464

    
4465

    
4466
    disks = _GenerateDiskTemplate(self,
4467
                                  self.op.disk_template,
4468
                                  instance, pnode_name,
4469
                                  self.secondaries,
4470
                                  self.disks,
4471
                                  file_storage_dir,
4472
                                  self.op.file_driver,
4473
                                  0)
4474

    
4475
    iobj = objects.Instance(name=instance, os=self.op.os_type,
4476
                            primary_node=pnode_name,
4477
                            nics=self.nics, disks=disks,
4478
                            disk_template=self.op.disk_template,
4479
                            status=self.instance_status,
4480
                            network_port=network_port,
4481
                            beparams=self.op.beparams,
4482
                            hvparams=self.op.hvparams,
4483
                            hypervisor=self.op.hypervisor,
4484
                            )
4485

    
4486
    feedback_fn("* creating instance disks...")
4487
    try:
4488
      _CreateDisks(self, iobj)
4489
    except errors.OpExecError:
4490
      self.LogWarning("Device creation failed, reverting...")
4491
      try:
4492
        _RemoveDisks(self, iobj)
4493
      finally:
4494
        self.cfg.ReleaseDRBDMinors(instance)
4495
        raise
4496

    
4497
    feedback_fn("adding instance %s to cluster config" % instance)
4498

    
4499
    self.cfg.AddInstance(iobj)
4500
    # Declare that we don't want to remove the instance lock anymore, as we've
4501
    # added the instance to the config
4502
    del self.remove_locks[locking.LEVEL_INSTANCE]
4503
    # Remove the temp. assignements for the instance's drbds
4504
    self.cfg.ReleaseDRBDMinors(instance)
4505
    # Unlock all the nodes
4506
    if self.op.mode == constants.INSTANCE_IMPORT:
4507
      nodes_keep = [self.op.src_node]
4508
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
4509
                       if node != self.op.src_node]
4510
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
4511
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
4512
    else:
4513
      self.context.glm.release(locking.LEVEL_NODE)
4514
      del self.acquired_locks[locking.LEVEL_NODE]
4515

    
4516
    if self.op.wait_for_sync:
4517
      disk_abort = not _WaitForSync(self, iobj)
4518
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
4519
      # make sure the disks are not degraded (still sync-ing is ok)
4520
      time.sleep(15)
4521
      feedback_fn("* checking mirrors status")
4522
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
4523
    else:
4524
      disk_abort = False
4525

    
4526
    if disk_abort:
4527
      _RemoveDisks(self, iobj)
4528
      self.cfg.RemoveInstance(iobj.name)
4529
      # Make sure the instance lock gets removed
4530
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
4531
      raise errors.OpExecError("There are some degraded disks for"
4532
                               " this instance")
4533

    
4534
    feedback_fn("creating os for instance %s on node %s" %
4535
                (instance, pnode_name))
4536

    
4537
    if iobj.disk_template != constants.DT_DISKLESS:
4538
      if self.op.mode == constants.INSTANCE_CREATE:
4539
        feedback_fn("* running the instance OS create scripts...")
4540
        result = self.rpc.call_instance_os_add(pnode_name, iobj)
4541
        msg = result.RemoteFailMsg()
4542
        if msg:
4543
          raise errors.OpExecError("Could not add os for instance %s"
4544
                                   " on node %s: %s" %
4545
                                   (instance, pnode_name, msg))
4546

    
4547
      elif self.op.mode == constants.INSTANCE_IMPORT:
4548
        feedback_fn("* running the instance OS import scripts...")
4549
        src_node = self.op.src_node
4550
        src_images = self.src_images
4551
        cluster_name = self.cfg.GetClusterName()
4552
        import_result = self.rpc.call_instance_os_import(pnode_name, iobj,
4553
                                                         src_node, src_images,
4554
                                                         cluster_name)
4555
        import_result.Raise()
4556
        for idx, result in enumerate(import_result.data):
4557
          if not result:
4558
            self.LogWarning("Could not import the image %s for instance"
4559
                            " %s, disk %d, on node %s" %
4560
                            (src_images[idx], instance, idx, pnode_name))
4561
      else:
4562
        # also checked in the prereq part
4563
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
4564
                                     % self.op.mode)
4565

    
4566
    if self.op.start:
4567
      logging.info("Starting instance %s on node %s", instance, pnode_name)
4568
      feedback_fn("* starting instance...")
4569
      result = self.rpc.call_instance_start(pnode_name, iobj, None)
4570
      msg = result.RemoteFailMsg()
4571
      if msg:
4572
        raise errors.OpExecError("Could not start instance: %s" % msg)
4573

    
4574

    
4575
class LUConnectConsole(NoHooksLU):
4576
  """Connect to an instance's console.
4577

4578
  This is somewhat special in that it returns the command line that
4579
  you need to run on the master node in order to connect to the
4580
  console.
4581

4582
  """
4583
  _OP_REQP = ["instance_name"]
4584
  REQ_BGL = False
4585

    
4586
  def ExpandNames(self):
4587
    self._ExpandAndLockInstance()
4588

    
4589
  def CheckPrereq(self):
4590
    """Check prerequisites.
4591

4592
    This checks that the instance is in the cluster.
4593

4594
    """
4595
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4596
    assert self.instance is not None, \
4597
      "Cannot retrieve locked instance %s" % self.op.instance_name
4598
    _CheckNodeOnline(self, self.instance.primary_node)
4599

    
4600
  def Exec(self, feedback_fn):
4601
    """Connect to the console of an instance
4602

4603
    """
4604
    instance = self.instance
4605
    node = instance.primary_node
4606

    
4607
    node_insts = self.rpc.call_instance_list([node],
4608
                                             [instance.hypervisor])[node]
4609
    node_insts.Raise()
4610

    
4611
    if instance.name not in node_insts.data:
4612
      raise errors.OpExecError("Instance %s is not running." % instance.name)
4613

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

    
4616
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
4617
    console_cmd = hyper.GetShellCommandForConsole(instance)
4618

    
4619
    # build ssh cmdline
4620
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
4621

    
4622

    
4623
class LUReplaceDisks(LogicalUnit):
4624
  """Replace the disks of an instance.
4625

4626
  """
4627
  HPATH = "mirrors-replace"
4628
  HTYPE = constants.HTYPE_INSTANCE
4629
  _OP_REQP = ["instance_name", "mode", "disks"]
4630
  REQ_BGL = False
4631

    
4632
  def CheckArguments(self):
4633
    if not hasattr(self.op, "remote_node"):
4634
      self.op.remote_node = None
4635
    if not hasattr(self.op, "iallocator"):
4636
      self.op.iallocator = None
4637

    
4638
    # check for valid parameter combination
4639
    cnt = [self.op.remote_node, self.op.iallocator].count(None)
4640
    if self.op.mode == constants.REPLACE_DISK_CHG:
4641
      if cnt == 2:
4642
        raise errors.OpPrereqError("When changing the secondary either an"
4643
                                   " iallocator script must be used or the"
4644
                                   " new node given")
4645
      elif cnt == 0:
4646
        raise errors.OpPrereqError("Give either the iallocator or the new"
4647
                                   " secondary, not both")
4648
    else: # not replacing the secondary
4649
      if cnt != 2:
4650
        raise errors.OpPrereqError("The iallocator and new node options can"
4651
                                   " be used only when changing the"
4652
                                   " secondary node")
4653

    
4654
  def ExpandNames(self):
4655
    self._ExpandAndLockInstance()
4656

    
4657
    if self.op.iallocator is not None:
4658
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4659
    elif self.op.remote_node is not None:
4660
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
4661
      if remote_node is None:
4662
        raise errors.OpPrereqError("Node '%s' not known" %
4663
                                   self.op.remote_node)
4664
      self.op.remote_node = remote_node
4665
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
4666
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4667
    else:
4668
      self.needed_locks[locking.LEVEL_NODE] = []
4669
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4670

    
4671
  def DeclareLocks(self, level):
4672
    # If we're not already locking all nodes in the set we have to declare the
4673
    # instance's primary/secondary nodes.
4674
    if (level == locking.LEVEL_NODE and
4675
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
4676
      self._LockInstancesNodes()
4677

    
4678
  def _RunAllocator(self):
4679
    """Compute a new secondary node using an IAllocator.
4680

4681
    """
4682
    ial = IAllocator(self,
4683
                     mode=constants.IALLOCATOR_MODE_RELOC,
4684
                     name=self.op.instance_name,
4685
                     relocate_from=[self.sec_node])
4686

    
4687
    ial.Run(self.op.iallocator)
4688

    
4689
    if not ial.success:
4690
      raise errors.OpPrereqError("Can't compute nodes using"
4691
                                 " iallocator '%s': %s" % (self.op.iallocator,
4692
                                                           ial.info))
4693
    if len(ial.nodes) != ial.required_nodes:
4694
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
4695
                                 " of nodes (%s), required %s" %
4696
                                 (len(ial.nodes), ial.required_nodes))
4697
    self.op.remote_node = ial.nodes[0]
4698
    self.LogInfo("Selected new secondary for the instance: %s",
4699
                 self.op.remote_node)
4700

    
4701
  def BuildHooksEnv(self):
4702
    """Build hooks env.
4703

4704
    This runs on the master, the primary and all the secondaries.
4705

4706
    """
4707
    env = {
4708
      "MODE": self.op.mode,
4709
      "NEW_SECONDARY": self.op.remote_node,
4710
      "OLD_SECONDARY": self.instance.secondary_nodes[0],
4711
      }
4712
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4713
    nl = [
4714
      self.cfg.GetMasterNode(),
4715
      self.instance.primary_node,
4716
      ]
4717
    if self.op.remote_node is not None:
4718
      nl.append(self.op.remote_node)
4719
    return env, nl, nl
4720

    
4721
  def CheckPrereq(self):
4722
    """Check prerequisites.
4723

4724
    This checks that the instance is in the cluster.
4725

4726
    """
4727
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4728
    assert instance is not None, \
4729
      "Cannot retrieve locked instance %s" % self.op.instance_name
4730
    self.instance = instance
4731

    
4732
    if instance.disk_template != constants.DT_DRBD8:
4733
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
4734
                                 " instances")
4735

    
4736
    if len(instance.secondary_nodes) != 1:
4737
      raise errors.OpPrereqError("The instance has a strange layout,"
4738
                                 " expected one secondary but found %d" %
4739
                                 len(instance.secondary_nodes))
4740

    
4741
    self.sec_node = instance.secondary_nodes[0]
4742

    
4743
    if self.op.iallocator is not None:
4744
      self._RunAllocator()
4745

    
4746
    remote_node = self.op.remote_node
4747
    if remote_node is not None:
4748
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
4749
      assert self.remote_node_info is not None, \
4750
        "Cannot retrieve locked node %s" % remote_node
4751
    else:
4752
      self.remote_node_info = None
4753
    if remote_node == instance.primary_node:
4754
      raise errors.OpPrereqError("The specified node is the primary node of"
4755
                                 " the instance.")
4756
    elif remote_node == self.sec_node:
4757
      raise errors.OpPrereqError("The specified node is already the"
4758
                                 " secondary node of the instance.")
4759

    
4760
    if self.op.mode == constants.REPLACE_DISK_PRI:
4761
      n1 = self.tgt_node = instance.primary_node
4762
      n2 = self.oth_node = self.sec_node
4763
    elif self.op.mode == constants.REPLACE_DISK_SEC:
4764
      n1 = self.tgt_node = self.sec_node
4765
      n2 = self.oth_node = instance.primary_node
4766
    elif self.op.mode == constants.REPLACE_DISK_CHG:
4767
      n1 = self.new_node = remote_node
4768
      n2 = self.oth_node = instance.primary_node
4769
      self.tgt_node = self.sec_node
4770
    else:
4771
      raise errors.ProgrammerError("Unhandled disk replace mode")
4772

    
4773
    _CheckNodeOnline(self, n1)
4774
    _CheckNodeOnline(self, n2)
4775

    
4776
    if not self.op.disks:
4777
      self.op.disks = range(len(instance.disks))
4778

    
4779
    for disk_idx in self.op.disks:
4780
      instance.FindDisk(disk_idx)
4781

    
4782
  def _ExecD8DiskOnly(self, feedback_fn):
4783
    """Replace a disk on the primary or secondary for dbrd8.
4784

4785
    The algorithm for replace is quite complicated:
4786

4787
      1. for each disk to be replaced:
4788

4789
        1. create new LVs on the target node with unique names
4790
        1. detach old LVs from the drbd device
4791
        1. rename old LVs to name_replaced.<time_t>
4792
        1. rename new LVs to old LVs
4793
        1. attach the new LVs (with the old names now) to the drbd device
4794

4795
      1. wait for sync across all devices
4796

4797
      1. for each modified disk:
4798

4799
        1. remove old LVs (which have the name name_replaces.<time_t>)
4800

4801
    Failures are not very well handled.
4802

4803
    """
4804
    steps_total = 6
4805
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
4806
    instance = self.instance
4807
    iv_names = {}
4808
    vgname = self.cfg.GetVGName()
4809
    # start of work
4810
    cfg = self.cfg
4811
    tgt_node = self.tgt_node
4812
    oth_node = self.oth_node
4813

    
4814
    # Step: check device activation
4815
    self.proc.LogStep(1, steps_total, "check device existence")
4816
    info("checking volume groups")
4817
    my_vg = cfg.GetVGName()
4818
    results = self.rpc.call_vg_list([oth_node, tgt_node])
4819
    if not results:
4820
      raise errors.OpExecError("Can't list volume groups on the nodes")
4821
    for node in oth_node, tgt_node:
4822
      res = results[node]
4823
      if res.failed or not res.data or my_vg not in res.data:
4824
        raise errors.OpExecError("Volume group '%s' not found on %s" %
4825
                                 (my_vg, node))
4826
    for idx, dev in enumerate(instance.disks):
4827
      if idx not in self.op.disks:
4828
        continue
4829
      for node in tgt_node, oth_node:
4830
        info("checking disk/%d on %s" % (idx, node))
4831
        cfg.SetDiskID(dev, node)
4832
        if not self.rpc.call_blockdev_find(node, dev):
4833
          raise errors.OpExecError("Can't find disk/%d on node %s" %
4834
                                   (idx, node))
4835

    
4836
    # Step: check other node consistency
4837
    self.proc.LogStep(2, steps_total, "check peer consistency")
4838
    for idx, dev in enumerate(instance.disks):
4839
      if idx not in self.op.disks:
4840
        continue
4841
      info("checking disk/%d consistency on %s" % (idx, oth_node))
4842
      if not _CheckDiskConsistency(self, dev, oth_node,
4843
                                   oth_node==instance.primary_node):
4844
        raise errors.OpExecError("Peer node (%s) has degraded storage, unsafe"
4845
                                 " to replace disks on this node (%s)" %
4846
                                 (oth_node, tgt_node))
4847

    
4848
    # Step: create new storage
4849
    self.proc.LogStep(3, steps_total, "allocate new storage")
4850
    for idx, dev in enumerate(instance.disks):
4851
      if idx not in self.op.disks:
4852
        continue
4853
      size = dev.size
4854
      cfg.SetDiskID(dev, tgt_node)
4855
      lv_names = [".disk%d_%s" % (idx, suf)
4856
                  for suf in ["data", "meta"]]
4857
      names = _GenerateUniqueNames(self, lv_names)
4858
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=size,
4859
                             logical_id=(vgname, names[0]))
4860
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
4861
                             logical_id=(vgname, names[1]))
4862
      new_lvs = [lv_data, lv_meta]
4863
      old_lvs = dev.children
4864
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
4865
      info("creating new local storage on %s for %s" %
4866
           (tgt_node, dev.iv_name))
4867
      # we pass force_create=True to force the LVM creation
4868
      for new_lv in new_lvs:
4869
        _CreateBlockDev(self, tgt_node, instance, new_lv, True,
4870
                        _GetInstanceInfoText(instance), False)
4871

    
4872
    # Step: for each lv, detach+rename*2+attach
4873
    self.proc.LogStep(4, steps_total, "change drbd configuration")
4874
    for dev, old_lvs, new_lvs in iv_names.itervalues():
4875
      info("detaching %s drbd from local storage" % dev.iv_name)
4876
      result = self.rpc.call_blockdev_removechildren(tgt_node, dev, old_lvs)
4877
      result.Raise()
4878
      if not result.data:
4879
        raise errors.OpExecError("Can't detach drbd from local storage on node"
4880
                                 " %s for device %s" % (tgt_node, dev.iv_name))
4881
      #dev.children = []
4882
      #cfg.Update(instance)
4883

    
4884
      # ok, we created the new LVs, so now we know we have the needed
4885
      # storage; as such, we proceed on the target node to rename
4886
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
4887
      # using the assumption that logical_id == physical_id (which in
4888
      # turn is the unique_id on that node)
4889

    
4890
      # FIXME(iustin): use a better name for the replaced LVs
4891
      temp_suffix = int(time.time())
4892
      ren_fn = lambda d, suff: (d.physical_id[0],
4893
                                d.physical_id[1] + "_replaced-%s" % suff)
4894
      # build the rename list based on what LVs exist on the node
4895
      rlist = []
4896
      for to_ren in old_lvs:
4897
        find_res = self.rpc.call_blockdev_find(tgt_node, to_ren)
4898
        if not find_res.failed and find_res.data is not None: # device exists
4899
          rlist.append((to_ren, ren_fn(to_ren, temp_suffix)))
4900

    
4901
      info("renaming the old LVs on the target node")
4902
      result = self.rpc.call_blockdev_rename(tgt_node, rlist)
4903
      result.Raise()
4904
      if not result.data:
4905
        raise errors.OpExecError("Can't rename old LVs on node %s" % tgt_node)
4906
      # now we rename the new LVs to the old LVs
4907
      info("renaming the new LVs on the target node")
4908
      rlist = [(new, old.physical_id) for old, new in zip(old_lvs, new_lvs)]
4909
      result = self.rpc.call_blockdev_rename(tgt_node, rlist)
4910
      result.Raise()
4911
      if not result.data:
4912
        raise errors.OpExecError("Can't rename new LVs on node %s" % tgt_node)
4913

    
4914
      for old, new in zip(old_lvs, new_lvs):
4915
        new.logical_id = old.logical_id
4916
        cfg.SetDiskID(new, tgt_node)
4917

    
4918
      for disk in old_lvs:
4919
        disk.logical_id = ren_fn(disk, temp_suffix)
4920
        cfg.SetDiskID(disk, tgt_node)
4921

    
4922
      # now that the new lvs have the old name, we can add them to the device
4923
      info("adding new mirror component on %s" % tgt_node)
4924
      result = self.rpc.call_blockdev_addchildren(tgt_node, dev, new_lvs)
4925
      if result.failed or not result.data:
4926
        for new_lv in new_lvs:
4927
          result = self.rpc.call_blockdev_remove(tgt_node, new_lv)
4928
          if result.failed or not result.data:
4929
            warning("Can't rollback device %s", hint="manually cleanup unused"
4930
                    " logical volumes")
4931
        raise errors.OpExecError("Can't add local storage to drbd")
4932

    
4933
      dev.children = new_lvs
4934
      cfg.Update(instance)
4935

    
4936
    # Step: wait for sync
4937

    
4938
    # this can fail as the old devices are degraded and _WaitForSync
4939
    # does a combined result over all disks, so we don't check its
4940
    # return value
4941
    self.proc.LogStep(5, steps_total, "sync devices")
4942
    _WaitForSync(self, instance, unlock=True)
4943

    
4944
    # so check manually all the devices
4945
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
4946
      cfg.SetDiskID(dev, instance.primary_node)
4947
      result = self.rpc.call_blockdev_find(instance.primary_node, dev)
4948
      if result.failed or result.data[5]:
4949
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
4950

    
4951
    # Step: remove old storage
4952
    self.proc.LogStep(6, steps_total, "removing old storage")
4953
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
4954
      info("remove logical volumes for %s" % name)
4955
      for lv in old_lvs:
4956
        cfg.SetDiskID(lv, tgt_node)
4957
        result = self.rpc.call_blockdev_remove(tgt_node, lv)
4958
        if result.failed or not result.data:
4959
          warning("Can't remove old LV", hint="manually remove unused LVs")
4960
          continue
4961

    
4962
  def _ExecD8Secondary(self, feedback_fn):
4963
    """Replace the secondary node for drbd8.
4964

4965
    The algorithm for replace is quite complicated:
4966
      - for all disks of the instance:
4967
        - create new LVs on the new node with same names
4968
        - shutdown the drbd device on the old secondary
4969
        - disconnect the drbd network on the primary
4970
        - create the drbd device on the new secondary
4971
        - network attach the drbd on the primary, using an artifice:
4972
          the drbd code for Attach() will connect to the network if it
4973
          finds a device which is connected to the good local disks but
4974
          not network enabled
4975
      - wait for sync across all devices
4976
      - remove all disks from the old secondary
4977

4978
    Failures are not very well handled.
4979

4980
    """
4981
    steps_total = 6
4982
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
4983
    instance = self.instance
4984
    iv_names = {}
4985
    # start of work
4986
    cfg = self.cfg
4987
    old_node = self.tgt_node
4988
    new_node = self.new_node
4989
    pri_node = instance.primary_node
4990
    nodes_ip = {
4991
      old_node: self.cfg.GetNodeInfo(old_node).secondary_ip,
4992
      new_node: self.cfg.GetNodeInfo(new_node).secondary_ip,
4993
      pri_node: self.cfg.GetNodeInfo(pri_node).secondary_ip,
4994
      }
4995

    
4996
    # Step: check device activation
4997
    self.proc.LogStep(1, steps_total, "check device existence")
4998
    info("checking volume groups")
4999
    my_vg = cfg.GetVGName()
5000
    results = self.rpc.call_vg_list([pri_node, new_node])
5001
    for node in pri_node, new_node:
5002
      res = results[node]
5003
      if res.failed or not res.data or my_vg not in res.data:
5004
        raise errors.OpExecError("Volume group '%s' not found on %s" %
5005
                                 (my_vg, node))
5006
    for idx, dev in enumerate(instance.disks):
5007
      if idx not in self.op.disks:
5008
        continue
5009
      info("checking disk/%d on %s" % (idx, pri_node))
5010
      cfg.SetDiskID(dev, pri_node)
5011
      result = self.rpc.call_blockdev_find(pri_node, dev)
5012
      result.Raise()
5013
      if not result.data:
5014
        raise errors.OpExecError("Can't find disk/%d on node %s" %
5015
                                 (idx, pri_node))
5016

    
5017
    # Step: check other node consistency
5018
    self.proc.LogStep(2, steps_total, "check peer consistency")
5019
    for idx, dev in enumerate(instance.disks):
5020
      if idx not in self.op.disks:
5021
        continue
5022
      info("checking disk/%d consistency on %s" % (idx, pri_node))
5023
      if not _CheckDiskConsistency(self, dev, pri_node, True, ldisk=True):
5024
        raise errors.OpExecError("Primary node (%s) has degraded storage,"
5025
                                 " unsafe to replace the secondary" %
5026
                                 pri_node)
5027

    
5028
    # Step: create new storage
5029
    self.proc.LogStep(3, steps_total, "allocate new storage")
5030
    for idx, dev in enumerate(instance.disks):
5031
      info("adding new local storage on %s for disk/%d" %
5032
           (new_node, idx))
5033
      # we pass force_create=True to force LVM creation
5034
      for new_lv in dev.children:
5035
        _CreateBlockDev(self, new_node, instance, new_lv, True,
5036
                        _GetInstanceInfoText(instance), False)
5037

    
5038
    # Step 4: dbrd minors and drbd setups changes
5039
    # after this, we must manually remove the drbd minors on both the
5040
    # error and the success paths
5041
    minors = cfg.AllocateDRBDMinor([new_node for dev in instance.disks],
5042
                                   instance.name)
5043
    logging.debug("Allocated minors %s" % (minors,))
5044
    self.proc.LogStep(4, steps_total, "changing drbd configuration")
5045
    for idx, (dev, new_minor) in enumerate(zip(instance.disks, minors)):
5046
      size = dev.size
5047
      info("activating a new drbd on %s for disk/%d" % (new_node, idx))
5048
      # create new devices on new_node; note that we create two IDs:
5049
      # one without port, so the drbd will be activated without
5050
      # networking information on the new node at this stage, and one
5051
      # with network, for the latter activation in step 4
5052
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
5053
      if pri_node == o_node1:
5054
        p_minor = o_minor1
5055
      else:
5056
        p_minor = o_minor2
5057

    
5058
      new_alone_id = (pri_node, new_node, None, p_minor, new_minor, o_secret)
5059
      new_net_id = (pri_node, new_node, o_port, p_minor, new_minor, o_secret)
5060

    
5061
      iv_names[idx] = (dev, dev.children, new_net_id)
5062
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
5063
                    new_net_id)
5064
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
5065
                              logical_id=new_alone_id,
5066
                              children=dev.children)
5067
      try:
5068
        _CreateSingleBlockDev(self, new_node, instance, new_drbd,
5069
                              _GetInstanceInfoText(instance), False)
5070
      except errors.BlockDeviceError:
5071
        self.cfg.ReleaseDRBDMinors(instance.name)
5072
        raise
5073

    
5074
    for idx, dev in enumerate(instance.disks):
5075
      # we have new devices, shutdown the drbd on the old secondary
5076
      info("shutting down drbd for disk/%d on old node" % idx)
5077
      cfg.SetDiskID(dev, old_node)
5078
      result = self.rpc.call_blockdev_shutdown(old_node, dev)
5079
      if result.failed or not result.data:
5080
        warning("Failed to shutdown drbd for disk/%d on old node" % idx,
5081
                hint="Please cleanup this device manually as soon as possible")
5082

    
5083
    info("detaching primary drbds from the network (=> standalone)")
5084
    result = self.rpc.call_drbd_disconnect_net([pri_node], nodes_ip,
5085
                                               instance.disks)[pri_node]
5086

    
5087
    msg = result.RemoteFailMsg()
5088
    if msg:
5089
      # detaches didn't succeed (unlikely)
5090
      self.cfg.ReleaseDRBDMinors(instance.name)
5091
      raise errors.OpExecError("Can't detach the disks from the network on"
5092
                               " old node: %s" % (msg,))
5093

    
5094
    # if we managed to detach at least one, we update all the disks of
5095
    # the instance to point to the new secondary
5096
    info("updating instance configuration")
5097
    for dev, _, new_logical_id in iv_names.itervalues():
5098
      dev.logical_id = new_logical_id
5099
      cfg.SetDiskID(dev, pri_node)
5100
    cfg.Update(instance)
5101
    # we can remove now the temp minors as now the new values are
5102
    # written to the config file (and therefore stable)
5103
    self.cfg.ReleaseDRBDMinors(instance.name)
5104

    
5105
    # and now perform the drbd attach
5106
    info("attaching primary drbds to new secondary (standalone => connected)")
5107
    result = self.rpc.call_drbd_attach_net([pri_node, new_node], nodes_ip,
5108
                                           instance.disks, instance.name,
5109
                                           False)
5110
    for to_node, to_result in result.items():
5111
      msg = to_result.RemoteFailMsg()
5112
      if msg:
5113
        warning("can't attach drbd disks on node %s: %s", to_node, msg,
5114
                hint="please do a gnt-instance info to see the"
5115
                " status of disks")
5116

    
5117
    # this can fail as the old devices are degraded and _WaitForSync
5118
    # does a combined result over all disks, so we don't check its
5119
    # return value
5120
    self.proc.LogStep(5, steps_total, "sync devices")
5121
    _WaitForSync(self, instance, unlock=True)
5122

    
5123
    # so check manually all the devices
5124
    for idx, (dev, old_lvs, _) in iv_names.iteritems():
5125
      cfg.SetDiskID(dev, pri_node)
5126
      result = self.rpc.call_blockdev_find(pri_node, dev)
5127
      result.Raise()
5128
      if result.data[5]:
5129
        raise errors.OpExecError("DRBD device disk/%d is degraded!" % idx)
5130

    
5131
    self.proc.LogStep(6, steps_total, "removing old storage")
5132
    for idx, (dev, old_lvs, _) in iv_names.iteritems():
5133
      info("remove logical volumes for disk/%d" % idx)
5134
      for lv in old_lvs:
5135
        cfg.SetDiskID(lv, old_node)
5136
        result = self.rpc.call_blockdev_remove(old_node, lv)
5137
        if result.failed or not result.data:
5138
          warning("Can't remove LV on old secondary",
5139
                  hint="Cleanup stale volumes by hand")
5140

    
5141
  def Exec(self, feedback_fn):
5142
    """Execute disk replacement.
5143

5144
    This dispatches the disk replacement to the appropriate handler.
5145

5146
    """
5147
    instance = self.instance
5148

    
5149
    # Activate the instance disks if we're replacing them on a down instance
5150
    if instance.status == "down":
5151
      _StartInstanceDisks(self, instance, True)
5152

    
5153
    if self.op.mode == constants.REPLACE_DISK_CHG:
5154
      fn = self._ExecD8Secondary
5155
    else:
5156
      fn = self._ExecD8DiskOnly
5157

    
5158
    ret = fn(feedback_fn)
5159

    
5160
    # Deactivate the instance disks if we're replacing them on a down instance
5161
    if instance.status == "down":
5162
      _SafeShutdownInstanceDisks(self, instance)
5163

    
5164
    return ret
5165

    
5166

    
5167
class LUGrowDisk(LogicalUnit):
5168
  """Grow a disk of an instance.
5169

5170
  """
5171
  HPATH = "disk-grow"
5172
  HTYPE = constants.HTYPE_INSTANCE
5173
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
5174
  REQ_BGL = False
5175

    
5176
  def ExpandNames(self):
5177
    self._ExpandAndLockInstance()
5178
    self.needed_locks[locking.LEVEL_NODE] = []
5179
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5180

    
5181
  def DeclareLocks(self, level):
5182
    if level == locking.LEVEL_NODE:
5183
      self._LockInstancesNodes()
5184

    
5185
  def BuildHooksEnv(self):
5186
    """Build hooks env.
5187

5188
    This runs on the master, the primary and all the secondaries.
5189

5190
    """
5191
    env = {
5192
      "DISK": self.op.disk,
5193
      "AMOUNT": self.op.amount,
5194
      }
5195
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5196
    nl = [
5197
      self.cfg.GetMasterNode(),
5198
      self.instance.primary_node,
5199
      ]
5200
    return env, nl, nl
5201

    
5202
  def CheckPrereq(self):
5203
    """Check prerequisites.
5204

5205
    This checks that the instance is in the cluster.
5206

5207
    """
5208
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5209
    assert instance is not None, \
5210
      "Cannot retrieve locked instance %s" % self.op.instance_name
5211
    nodenames = list(instance.all_nodes)
5212
    for node in nodenames:
5213
      _CheckNodeOnline(self, node)
5214

    
5215

    
5216
    self.instance = instance
5217

    
5218
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
5219
      raise errors.OpPrereqError("Instance's disk layout does not support"
5220
                                 " growing.")
5221

    
5222
    self.disk = instance.FindDisk(self.op.disk)
5223

    
5224
    nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
5225
                                       instance.hypervisor)
5226
    for node in nodenames:
5227
      info = nodeinfo[node]
5228
      if info.failed or not info.data:
5229
        raise errors.OpPrereqError("Cannot get current information"
5230
                                   " from node '%s'" % node)
5231
      vg_free = info.data.get('vg_free', None)
5232
      if not isinstance(vg_free, int):
5233
        raise errors.OpPrereqError("Can't compute free disk space on"
5234
                                   " node %s" % node)
5235
      if self.op.amount > vg_free:
5236
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
5237
                                   " %d MiB available, %d MiB required" %
5238
                                   (node, vg_free, self.op.amount))
5239

    
5240
  def Exec(self, feedback_fn):
5241
    """Execute disk grow.
5242

5243
    """
5244
    instance = self.instance
5245
    disk = self.disk
5246
    for node in instance.all_nodes:
5247
      self.cfg.SetDiskID(disk, node)
5248
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
5249
      result.Raise()
5250
      if (not result.data or not isinstance(result.data, (list, tuple)) or
5251
          len(result.data) != 2):
5252
        raise errors.OpExecError("Grow request failed to node %s" % node)
5253
      elif not result.data[0]:
5254
        raise errors.OpExecError("Grow request failed to node %s: %s" %
5255
                                 (node, result.data[1]))
5256
    disk.RecordGrow(self.op.amount)
5257
    self.cfg.Update(instance)
5258
    if self.op.wait_for_sync:
5259
      disk_abort = not _WaitForSync(self, instance)
5260
      if disk_abort:
5261
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
5262
                             " status.\nPlease check the instance.")
5263

    
5264

    
5265
class LUQueryInstanceData(NoHooksLU):
5266
  """Query runtime instance data.
5267

5268
  """
5269
  _OP_REQP = ["instances", "static"]
5270
  REQ_BGL = False
5271

    
5272
  def ExpandNames(self):
5273
    self.needed_locks = {}
5274
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
5275

    
5276
    if not isinstance(self.op.instances, list):
5277
      raise errors.OpPrereqError("Invalid argument type 'instances'")
5278

    
5279
    if self.op.instances:
5280
      self.wanted_names = []
5281
      for name in self.op.instances:
5282
        full_name = self.cfg.ExpandInstanceName(name)
5283
        if full_name is None:
5284
          raise errors.OpPrereqError("Instance '%s' not known" % name)
5285
        self.wanted_names.append(full_name)
5286
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
5287
    else:
5288
      self.wanted_names = None
5289
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
5290

    
5291
    self.needed_locks[locking.LEVEL_NODE] = []
5292
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5293

    
5294
  def DeclareLocks(self, level):
5295
    if level == locking.LEVEL_NODE:
5296
      self._LockInstancesNodes()
5297

    
5298
  def CheckPrereq(self):
5299
    """Check prerequisites.
5300

5301
    This only checks the optional instance list against the existing names.
5302

5303
    """
5304
    if self.wanted_names is None:
5305
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5306

    
5307
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
5308
                             in self.wanted_names]
5309
    return
5310

    
5311
  def _ComputeDiskStatus(self, instance, snode, dev):
5312
    """Compute block device status.
5313

5314
    """
5315
    static = self.op.static
5316
    if not static:
5317
      self.cfg.SetDiskID(dev, instance.primary_node)
5318
      dev_pstatus = self.rpc.call_blockdev_find(instance.primary_node, dev)
5319
      dev_pstatus.Raise()
5320
      dev_pstatus = dev_pstatus.data
5321
    else:
5322
      dev_pstatus = None
5323

    
5324
    if dev.dev_type in constants.LDS_DRBD:
5325
      # we change the snode then (otherwise we use the one passed in)
5326
      if dev.logical_id[0] == instance.primary_node:
5327
        snode = dev.logical_id[1]
5328
      else:
5329
        snode = dev.logical_id[0]
5330

    
5331
    if snode and not static:
5332
      self.cfg.SetDiskID(dev, snode)
5333
      dev_sstatus = self.rpc.call_blockdev_find(snode, dev)
5334
      dev_sstatus.Raise()
5335
      dev_sstatus = dev_sstatus.data
5336
    else:
5337
      dev_sstatus = None
5338

    
5339
    if dev.children:
5340
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
5341
                      for child in dev.children]
5342
    else:
5343
      dev_children = []
5344

    
5345
    data = {
5346
      "iv_name": dev.iv_name,
5347
      "dev_type": dev.dev_type,
5348
      "logical_id": dev.logical_id,
5349
      "physical_id": dev.physical_id,
5350
      "pstatus": dev_pstatus,
5351
      "sstatus": dev_sstatus,
5352
      "children": dev_children,
5353
      "mode": dev.mode,
5354
      }
5355

    
5356
    return data
5357

    
5358
  def Exec(self, feedback_fn):
5359
    """Gather and return data"""
5360
    result = {}
5361

    
5362
    cluster = self.cfg.GetClusterInfo()
5363

    
5364
    for instance in self.wanted_instances:
5365
      if not self.op.static:
5366
        remote_info = self.rpc.call_instance_info(instance.primary_node,
5367
                                                  instance.name,
5368
                                                  instance.hypervisor)
5369
        remote_info.Raise()
5370
        remote_info = remote_info.data
5371
        if remote_info and "state" in remote_info:
5372
          remote_state = "up"
5373
        else:
5374
          remote_state = "down"
5375
      else:
5376
        remote_state = None
5377
      if instance.status == "down":
5378
        config_state = "down"
5379
      else:
5380
        config_state = "up"
5381

    
5382
      disks = [self._ComputeDiskStatus(instance, None, device)
5383
               for device in instance.disks]
5384

    
5385
      idict = {
5386
        "name": instance.name,
5387
        "config_state": config_state,
5388
        "run_state": remote_state,
5389
        "pnode": instance.primary_node,
5390
        "snodes": instance.secondary_nodes,
5391
        "os": instance.os,
5392
        "nics": [(nic.mac, nic.ip, nic.bridge) for nic in instance.nics],
5393
        "disks": disks,
5394
        "hypervisor": instance.hypervisor,
5395
        "network_port": instance.network_port,
5396
        "hv_instance": instance.hvparams,
5397
        "hv_actual": cluster.FillHV(instance),
5398
        "be_instance": instance.beparams,
5399
        "be_actual": cluster.FillBE(instance),
5400
        }
5401

    
5402
      result[instance.name] = idict
5403

    
5404
    return result
5405

    
5406

    
5407
class LUSetInstanceParams(LogicalUnit):
5408
  """Modifies an instances's parameters.
5409

5410
  """
5411
  HPATH = "instance-modify"
5412
  HTYPE = constants.HTYPE_INSTANCE
5413
  _OP_REQP = ["instance_name"]
5414
  REQ_BGL = False
5415

    
5416
  def CheckArguments(self):
5417
    if not hasattr(self.op, 'nics'):
5418
      self.op.nics = []
5419
    if not hasattr(self.op, 'disks'):
5420
      self.op.disks = []
5421
    if not hasattr(self.op, 'beparams'):
5422
      self.op.beparams = {}
5423
    if not hasattr(self.op, 'hvparams'):
5424
      self.op.hvparams = {}
5425
    self.op.force = getattr(self.op, "force", False)
5426
    if not (self.op.nics or self.op.disks or
5427
            self.op.hvparams or self.op.beparams):
5428
      raise errors.OpPrereqError("No changes submitted")
5429

    
5430
    utils.CheckBEParams(self.op.beparams)
5431

    
5432
    # Disk validation
5433
    disk_addremove = 0
5434
    for disk_op, disk_dict in self.op.disks:
5435
      if disk_op == constants.DDM_REMOVE:
5436
        disk_addremove += 1
5437
        continue
5438
      elif disk_op == constants.DDM_ADD:
5439
        disk_addremove += 1
5440
      else:
5441
        if not isinstance(disk_op, int):
5442
          raise errors.OpPrereqError("Invalid disk index")
5443
      if disk_op == constants.DDM_ADD:
5444
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
5445
        if mode not in (constants.DISK_RDONLY, constants.DISK_RDWR):
5446
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode)
5447
        size = disk_dict.get('size', None)
5448
        if size is None:
5449
          raise errors.OpPrereqError("Required disk parameter size missing")
5450
        try:
5451
          size = int(size)
5452
        except ValueError, err:
5453
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
5454
                                     str(err))
5455
        disk_dict['size'] = size
5456
      else:
5457
        # modification of disk
5458
        if 'size' in disk_dict:
5459
          raise errors.OpPrereqError("Disk size change not possible, use"
5460
                                     " grow-disk")
5461

    
5462
    if disk_addremove > 1:
5463
      raise errors.OpPrereqError("Only one disk add or remove operation"
5464
                                 " supported at a time")
5465

    
5466
    # NIC validation
5467
    nic_addremove = 0
5468
    for nic_op, nic_dict in self.op.nics:
5469
      if nic_op == constants.DDM_REMOVE:
5470
        nic_addremove += 1
5471
        continue
5472
      elif nic_op == constants.DDM_ADD:
5473
        nic_addremove += 1
5474
      else:
5475
        if not isinstance(nic_op, int):
5476
          raise errors.OpPrereqError("Invalid nic index")
5477

    
5478
      # nic_dict should be a dict
5479
      nic_ip = nic_dict.get('ip', None)
5480
      if nic_ip is not None:
5481
        if nic_ip.lower() == "none":
5482
          nic_dict['ip'] = None
5483
        else:
5484
          if not utils.IsValidIP(nic_ip):
5485
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip)
5486
      # we can only check None bridges and assign the default one
5487
      nic_bridge = nic_dict.get('bridge', None)
5488
      if nic_bridge is None:
5489
        nic_dict['bridge'] = self.cfg.GetDefBridge()
5490
      # but we can validate MACs
5491
      nic_mac = nic_dict.get('mac', None)
5492
      if nic_mac is not None:
5493
        if self.cfg.IsMacInUse(nic_mac):
5494
          raise errors.OpPrereqError("MAC address %s already in use"
5495
                                     " in cluster" % nic_mac)
5496
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5497
          if not utils.IsValidMac(nic_mac):
5498
            raise errors.OpPrereqError("Invalid MAC address %s" % nic_mac)
5499
    if nic_addremove > 1:
5500
      raise errors.OpPrereqError("Only one NIC add or remove operation"
5501
                                 " supported at a time")
5502

    
5503
  def ExpandNames(self):
5504
    self._ExpandAndLockInstance()
5505
    self.needed_locks[locking.LEVEL_NODE] = []
5506
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5507

    
5508
  def DeclareLocks(self, level):
5509
    if level == locking.LEVEL_NODE:
5510
      self._LockInstancesNodes()
5511

    
5512
  def BuildHooksEnv(self):
5513
    """Build hooks env.
5514

5515
    This runs on the master, primary and secondaries.
5516

5517
    """
5518
    args = dict()
5519
    if constants.BE_MEMORY in self.be_new:
5520
      args['memory'] = self.be_new[constants.BE_MEMORY]
5521
    if constants.BE_VCPUS in self.be_new:
5522
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
5523
    # FIXME: readd disk/nic changes
5524
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
5525
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5526
    return env, nl, nl
5527

    
5528
  def CheckPrereq(self):
5529
    """Check prerequisites.
5530

5531
    This only checks the instance list against the existing names.
5532

5533
    """
5534
    force = self.force = self.op.force
5535

    
5536
    # checking the new params on the primary/secondary nodes
5537

    
5538
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5539
    assert self.instance is not None, \
5540
      "Cannot retrieve locked instance %s" % self.op.instance_name
5541
    pnode = instance.primary_node
5542
    nodelist = list(instance.all_nodes)
5543

    
5544
    # hvparams processing
5545
    if self.op.hvparams:
5546
      i_hvdict = copy.deepcopy(instance.hvparams)
5547
      for key, val in self.op.hvparams.iteritems():
5548
        if val == constants.VALUE_DEFAULT:
5549
          try:
5550
            del i_hvdict[key]
5551
          except KeyError:
5552
            pass
5553
        elif val == constants.VALUE_NONE:
5554
          i_hvdict[key] = None
5555
        else:
5556
          i_hvdict[key] = val
5557
      cluster = self.cfg.GetClusterInfo()
5558
      hv_new = cluster.FillDict(cluster.hvparams[instance.hypervisor],
5559
                                i_hvdict)
5560
      # local check
5561
      hypervisor.GetHypervisor(
5562
        instance.hypervisor).CheckParameterSyntax(hv_new)
5563
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
5564
      self.hv_new = hv_new # the new actual values
5565
      self.hv_inst = i_hvdict # the new dict (without defaults)
5566
    else:
5567
      self.hv_new = self.hv_inst = {}
5568

    
5569
    # beparams processing
5570
    if self.op.beparams:
5571
      i_bedict = copy.deepcopy(instance.beparams)
5572
      for key, val in self.op.beparams.iteritems():
5573
        if val == constants.VALUE_DEFAULT:
5574
          try:
5575
            del i_bedict[key]
5576
          except KeyError:
5577
            pass
5578
        else:
5579
          i_bedict[key] = val
5580
      cluster = self.cfg.GetClusterInfo()
5581
      be_new = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
5582
                                i_bedict)
5583
      self.be_new = be_new # the new actual values
5584
      self.be_inst = i_bedict # the new dict (without defaults)
5585
    else:
5586
      self.be_new = self.be_inst = {}
5587

    
5588
    self.warn = []
5589

    
5590
    if constants.BE_MEMORY in self.op.beparams and not self.force:
5591
      mem_check_list = [pnode]
5592
      if be_new[constants.BE_AUTO_BALANCE]:
5593
        # either we changed auto_balance to yes or it was from before
5594
        mem_check_list.extend(instance.secondary_nodes)
5595
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
5596
                                                  instance.hypervisor)
5597
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
5598
                                         instance.hypervisor)
5599
      if nodeinfo[pnode].failed or not isinstance(nodeinfo[pnode].data, dict):
5600
        # Assume the primary node is unreachable and go ahead
5601
        self.warn.append("Can't get info from primary node %s" % pnode)
5602
      else:
5603
        if not instance_info.failed and instance_info.data:
5604
          current_mem = instance_info.data['memory']
5605
        else:
5606
          # Assume instance not running
5607
          # (there is a slight race condition here, but it's not very probable,
5608
          # and we have no other way to check)
5609
          current_mem = 0
5610
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
5611
                    nodeinfo[pnode].data['memory_free'])
5612
        if miss_mem > 0:
5613
          raise errors.OpPrereqError("This change will prevent the instance"
5614
                                     " from starting, due to %d MB of memory"
5615
                                     " missing on its primary node" % miss_mem)
5616

    
5617
      if be_new[constants.BE_AUTO_BALANCE]:
5618
        for node, nres in nodeinfo.iteritems():
5619
          if node not in instance.secondary_nodes:
5620
            continue
5621
          if nres.failed or not isinstance(nres.data, dict):
5622
            self.warn.append("Can't get info from secondary node %s" % node)
5623
          elif be_new[constants.BE_MEMORY] > nres.data['memory_free']:
5624
            self.warn.append("Not enough memory to failover instance to"
5625
                             " secondary node %s" % node)
5626

    
5627
    # NIC processing
5628
    for nic_op, nic_dict in self.op.nics:
5629
      if nic_op == constants.DDM_REMOVE:
5630
        if not instance.nics:
5631
          raise errors.OpPrereqError("Instance has no NICs, cannot remove")
5632
        continue
5633
      if nic_op != constants.DDM_ADD:
5634
        # an existing nic
5635
        if nic_op < 0 or nic_op >= len(instance.nics):
5636
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
5637
                                     " are 0 to %d" %
5638
                                     (nic_op, len(instance.nics)))
5639
      nic_bridge = nic_dict.get('bridge', None)
5640
      if nic_bridge is not None:
5641
        if not self.rpc.call_bridges_exist(pnode, [nic_bridge]):
5642
          msg = ("Bridge '%s' doesn't exist on one of"
5643
                 " the instance nodes" % nic_bridge)
5644
          if self.force:
5645
            self.warn.append(msg)
5646
          else:
5647
            raise errors.OpPrereqError(msg)
5648

    
5649
    # DISK processing
5650
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
5651
      raise errors.OpPrereqError("Disk operations not supported for"
5652
                                 " diskless instances")
5653
    for disk_op, disk_dict in self.op.disks:
5654
      if disk_op == constants.DDM_REMOVE:
5655
        if len(instance.disks) == 1:
5656
          raise errors.OpPrereqError("Cannot remove the last disk of"
5657
                                     " an instance")
5658
        ins_l = self.rpc.call_instance_list([pnode], [instance.hypervisor])
5659
        ins_l = ins_l[pnode]
5660
        if ins_l.failed or not isinstance(ins_l.data, list):
5661
          raise errors.OpPrereqError("Can't contact node '%s'" % pnode)
5662
        if instance.name in ins_l.data:
5663
          raise errors.OpPrereqError("Instance is running, can't remove"
5664
                                     " disks.")
5665

    
5666
      if (disk_op == constants.DDM_ADD and
5667
          len(instance.nics) >= constants.MAX_DISKS):
5668
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
5669
                                   " add more" % constants.MAX_DISKS)
5670
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
5671
        # an existing disk
5672
        if disk_op < 0 or disk_op >= len(instance.disks):
5673
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
5674
                                     " are 0 to %d" %
5675
                                     (disk_op, len(instance.disks)))
5676

    
5677
    return
5678

    
5679
  def Exec(self, feedback_fn):
5680
    """Modifies an instance.
5681

5682
    All parameters take effect only at the next restart of the instance.
5683

5684
    """
5685
    # Process here the warnings from CheckPrereq, as we don't have a
5686
    # feedback_fn there.
5687
    for warn in self.warn:
5688
      feedback_fn("WARNING: %s" % warn)
5689

    
5690
    result = []
5691
    instance = self.instance
5692
    # disk changes
5693
    for disk_op, disk_dict in self.op.disks:
5694
      if disk_op == constants.DDM_REMOVE:
5695
        # remove the last disk
5696
        device = instance.disks.pop()
5697
        device_idx = len(instance.disks)
5698
        for node, disk in device.ComputeNodeTree(instance.primary_node):
5699
          self.cfg.SetDiskID(disk, node)
5700
          rpc_result = self.rpc.call_blockdev_remove(node, disk)
5701
          if rpc_result.failed or not rpc_result.data:
5702
            self.proc.LogWarning("Could not remove disk/%d on node %s,"
5703
                                 " continuing anyway", device_idx, node)
5704
        result.append(("disk/%d" % device_idx, "remove"))
5705
      elif disk_op == constants.DDM_ADD:
5706
        # add a new disk
5707
        if instance.disk_template == constants.DT_FILE:
5708
          file_driver, file_path = instance.disks[0].logical_id
5709
          file_path = os.path.dirname(file_path)
5710
        else:
5711
          file_driver = file_path = None
5712
        disk_idx_base = len(instance.disks)
5713
        new_disk = _GenerateDiskTemplate(self,
5714
                                         instance.disk_template,
5715
                                         instance.name, instance.primary_node,
5716
                                         instance.secondary_nodes,
5717
                                         [disk_dict],
5718
                                         file_path,
5719
                                         file_driver,
5720
                                         disk_idx_base)[0]
5721
        new_disk.mode = disk_dict['mode']
5722
        instance.disks.append(new_disk)
5723
        info = _GetInstanceInfoText(instance)
5724

    
5725
        logging.info("Creating volume %s for instance %s",
5726
                     new_disk.iv_name, instance.name)
5727
        # Note: this needs to be kept in sync with _CreateDisks
5728
        #HARDCODE
5729
        for node in instance.all_nodes:
5730
          f_create = node == instance.primary_node
5731
          try:
5732
            _CreateBlockDev(self, node, instance, new_disk,
5733
                            f_create, info, f_create)
5734
          except errors.OpExecError, err:
5735
            self.LogWarning("Failed to create volume %s (%s) on"
5736
                            " node %s: %s",
5737
                            new_disk.iv_name, new_disk, node, err)
5738
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
5739
                       (new_disk.size, new_disk.mode)))
5740
      else:
5741
        # change a given disk
5742
        instance.disks[disk_op].mode = disk_dict['mode']
5743
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
5744
    # NIC changes
5745
    for nic_op, nic_dict in self.op.nics:
5746
      if nic_op == constants.DDM_REMOVE:
5747
        # remove the last nic
5748
        del instance.nics[-1]
5749
        result.append(("nic.%d" % len(instance.nics), "remove"))
5750
      elif nic_op == constants.DDM_ADD:
5751
        # add a new nic
5752
        if 'mac' not in nic_dict:
5753
          mac = constants.VALUE_GENERATE
5754
        else:
5755
          mac = nic_dict['mac']
5756
        if mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5757
          mac = self.cfg.GenerateMAC()
5758
        new_nic = objects.NIC(mac=mac, ip=nic_dict.get('ip', None),
5759
                              bridge=nic_dict.get('bridge', None))
5760
        instance.nics.append(new_nic)
5761
        result.append(("nic.%d" % (len(instance.nics) - 1),
5762
                       "add:mac=%s,ip=%s,bridge=%s" %
5763
                       (new_nic.mac, new_nic.ip, new_nic.bridge)))
5764
      else:
5765
        # change a given nic
5766
        for key in 'mac', 'ip', 'bridge':
5767
          if key in nic_dict:
5768
            setattr(instance.nics[nic_op], key, nic_dict[key])
5769
            result.append(("nic.%s/%d" % (key, nic_op), nic_dict[key]))
5770

    
5771
    # hvparams changes
5772
    if self.op.hvparams:
5773
      instance.hvparams = self.hv_new
5774
      for key, val in self.op.hvparams.iteritems():
5775
        result.append(("hv/%s" % key, val))
5776

    
5777
    # beparams changes
5778
    if self.op.beparams:
5779
      instance.beparams = self.be_inst
5780
      for key, val in self.op.beparams.iteritems():
5781
        result.append(("be/%s" % key, val))
5782

    
5783
    self.cfg.Update(instance)
5784

    
5785
    return result
5786

    
5787

    
5788
class LUQueryExports(NoHooksLU):
5789
  """Query the exports list
5790

5791
  """
5792
  _OP_REQP = ['nodes']
5793
  REQ_BGL = False
5794

    
5795
  def ExpandNames(self):
5796
    self.needed_locks = {}
5797
    self.share_locks[locking.LEVEL_NODE] = 1
5798
    if not self.op.nodes:
5799
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5800
    else:
5801
      self.needed_locks[locking.LEVEL_NODE] = \
5802
        _GetWantedNodes(self, self.op.nodes)
5803

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

5807
    """
5808
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
5809

    
5810
  def Exec(self, feedback_fn):
5811
    """Compute the list of all the exported system images.
5812

5813
    @rtype: dict
5814
    @return: a dictionary with the structure node->(export-list)
5815
        where export-list is a list of the instances exported on
5816
        that node.
5817

5818
    """
5819
    rpcresult = self.rpc.call_export_list(self.nodes)
5820
    result = {}
5821
    for node in rpcresult:
5822
      if rpcresult[node].failed:
5823
        result[node] = False
5824
      else:
5825
        result[node] = rpcresult[node].data
5826

    
5827
    return result
5828

    
5829

    
5830
class LUExportInstance(LogicalUnit):
5831
  """Export an instance to an image in the cluster.
5832

5833
  """
5834
  HPATH = "instance-export"
5835
  HTYPE = constants.HTYPE_INSTANCE
5836
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
5837
  REQ_BGL = False
5838

    
5839
  def ExpandNames(self):
5840
    self._ExpandAndLockInstance()
5841
    # FIXME: lock only instance primary and destination node
5842
    #
5843
    # Sad but true, for now we have do lock all nodes, as we don't know where
5844
    # the previous export might be, and and in this LU we search for it and
5845
    # remove it from its current node. In the future we could fix this by:
5846
    #  - making a tasklet to search (share-lock all), then create the new one,
5847
    #    then one to remove, after
5848
    #  - removing the removal operation altoghether
5849
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5850

    
5851
  def DeclareLocks(self, level):
5852
    """Last minute lock declaration."""
5853
    # All nodes are locked anyway, so nothing to do here.
5854

    
5855
  def BuildHooksEnv(self):
5856
    """Build hooks env.
5857

5858
    This will run on the master, primary node and target node.
5859

5860
    """
5861
    env = {
5862
      "EXPORT_NODE": self.op.target_node,
5863
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
5864
      }
5865
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5866
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node,
5867
          self.op.target_node]
5868
    return env, nl, nl
5869

    
5870
  def CheckPrereq(self):
5871
    """Check prerequisites.
5872

5873
    This checks that the instance and node names are valid.
5874

5875
    """
5876
    instance_name = self.op.instance_name
5877
    self.instance = self.cfg.GetInstanceInfo(instance_name)
5878
    assert self.instance is not None, \
5879
          "Cannot retrieve locked instance %s" % self.op.instance_name
5880
    _CheckNodeOnline(self, self.instance.primary_node)
5881

    
5882
    self.dst_node = self.cfg.GetNodeInfo(
5883
      self.cfg.ExpandNodeName(self.op.target_node))
5884

    
5885
    if self.dst_node is None:
5886
      # This is wrong node name, not a non-locked node
5887
      raise errors.OpPrereqError("Wrong node name %s" % self.op.target_node)
5888
    _CheckNodeOnline(self, self.dst_node.name)
5889

    
5890
    # instance disk type verification
5891
    for disk in self.instance.disks:
5892
      if disk.dev_type == constants.LD_FILE:
5893
        raise errors.OpPrereqError("Export not supported for instances with"
5894
                                   " file-based disks")
5895

    
5896
  def Exec(self, feedback_fn):
5897
    """Export an instance to an image in the cluster.
5898

5899
    """
5900
    instance = self.instance
5901
    dst_node = self.dst_node
5902
    src_node = instance.primary_node
5903
    if self.op.shutdown:
5904
      # shutdown the instance, but not the disks
5905
      result = self.rpc.call_instance_shutdown(src_node, instance)
5906
      result.Raise()
5907
      if not result.data:
5908
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
5909
                                 (instance.name, src_node))
5910

    
5911
    vgname = self.cfg.GetVGName()
5912

    
5913
    snap_disks = []
5914

    
5915
    # set the disks ID correctly since call_instance_start needs the
5916
    # correct drbd minor to create the symlinks
5917
    for disk in instance.disks:
5918
      self.cfg.SetDiskID(disk, src_node)
5919

    
5920
    try:
5921
      for disk in instance.disks:
5922
        # new_dev_name will be a snapshot of an lvm leaf of the one we passed
5923
        new_dev_name = self.rpc.call_blockdev_snapshot(src_node, disk)
5924
        if new_dev_name.failed or not new_dev_name.data:
5925
          self.LogWarning("Could not snapshot block device %s on node %s",
5926
                          disk.logical_id[1], src_node)
5927
          snap_disks.append(False)
5928
        else:
5929
          new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
5930
                                 logical_id=(vgname, new_dev_name.data),
5931
                                 physical_id=(vgname, new_dev_name.data),
5932
                                 iv_name=disk.iv_name)
5933
          snap_disks.append(new_dev)
5934

    
5935
    finally:
5936
      if self.op.shutdown and instance.status == "up":
5937
        result = self.rpc.call_instance_start(src_node, instance, None)
5938
        msg = result.RemoteFailMsg()
5939
        if msg:
5940
          _ShutdownInstanceDisks(self, instance)
5941
          raise errors.OpExecError("Could not start instance: %s" % msg)
5942

    
5943
    # TODO: check for size
5944

    
5945
    cluster_name = self.cfg.GetClusterName()
5946
    for idx, dev in enumerate(snap_disks):
5947
      if dev:
5948
        result = self.rpc.call_snapshot_export(src_node, dev, dst_node.name,
5949
                                               instance, cluster_name, idx)
5950
        if result.failed or not result.data:
5951
          self.LogWarning("Could not export block device %s from node %s to"
5952
                          " node %s", dev.logical_id[1], src_node,
5953
                          dst_node.name)
5954
        result = self.rpc.call_blockdev_remove(src_node, dev)
5955
        if result.failed or not result.data:
5956
          self.LogWarning("Could not remove snapshot block device %s from node"
5957
                          " %s", dev.logical_id[1], src_node)
5958

    
5959
    result = self.rpc.call_finalize_export(dst_node.name, instance, snap_disks)
5960
    if result.failed or not result.data:
5961
      self.LogWarning("Could not finalize export for instance %s on node %s",
5962
                      instance.name, dst_node.name)
5963

    
5964
    nodelist = self.cfg.GetNodeList()
5965
    nodelist.remove(dst_node.name)
5966

    
5967
    # on one-node clusters nodelist will be empty after the removal
5968
    # if we proceed the backup would be removed because OpQueryExports
5969
    # substitutes an empty list with the full cluster node list.
5970
    if nodelist:
5971
      exportlist = self.rpc.call_export_list(nodelist)
5972
      for node in exportlist:
5973
        if exportlist[node].failed:
5974
          continue
5975
        if instance.name in exportlist[node].data:
5976
          if not self.rpc.call_export_remove(node, instance.name):
5977
            self.LogWarning("Could not remove older export for instance %s"
5978
                            " on node %s", instance.name, node)
5979

    
5980

    
5981
class LURemoveExport(NoHooksLU):
5982
  """Remove exports related to the named instance.
5983

5984
  """
5985
  _OP_REQP = ["instance_name"]
5986
  REQ_BGL = False
5987

    
5988
  def ExpandNames(self):
5989
    self.needed_locks = {}
5990
    # We need all nodes to be locked in order for RemoveExport to work, but we
5991
    # don't need to lock the instance itself, as nothing will happen to it (and
5992
    # we can remove exports also for a removed instance)
5993
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5994

    
5995
  def CheckPrereq(self):
5996
    """Check prerequisites.
5997
    """
5998
    pass
5999

    
6000
  def Exec(self, feedback_fn):
6001
    """Remove any export.
6002

6003
    """
6004
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
6005
    # If the instance was not found we'll try with the name that was passed in.
6006
    # This will only work if it was an FQDN, though.
6007
    fqdn_warn = False
6008
    if not instance_name:
6009
      fqdn_warn = True
6010
      instance_name = self.op.instance_name
6011

    
6012
    exportlist = self.rpc.call_export_list(self.acquired_locks[
6013
      locking.LEVEL_NODE])
6014
    found = False
6015
    for node in exportlist:
6016
      if exportlist[node].failed:
6017
        self.LogWarning("Failed to query node %s, continuing" % node)
6018
        continue
6019
      if instance_name in exportlist[node].data:
6020
        found = True
6021
        result = self.rpc.call_export_remove(node, instance_name)
6022
        if result.failed or not result.data:
6023
          logging.error("Could not remove export for instance %s"
6024
                        " on node %s", instance_name, node)
6025

    
6026
    if fqdn_warn and not found:
6027
      feedback_fn("Export not found. If trying to remove an export belonging"
6028
                  " to a deleted instance please use its Fully Qualified"
6029
                  " Domain Name.")
6030

    
6031

    
6032
class TagsLU(NoHooksLU):
6033
  """Generic tags LU.
6034

6035
  This is an abstract class which is the parent of all the other tags LUs.
6036

6037
  """
6038

    
6039
  def ExpandNames(self):
6040
    self.needed_locks = {}
6041
    if self.op.kind == constants.TAG_NODE:
6042
      name = self.cfg.ExpandNodeName(self.op.name)
6043
      if name is None:
6044
        raise errors.OpPrereqError("Invalid node name (%s)" %
6045
                                   (self.op.name,))
6046
      self.op.name = name
6047
      self.needed_locks[locking.LEVEL_NODE] = name
6048
    elif self.op.kind == constants.TAG_INSTANCE:
6049
      name = self.cfg.ExpandInstanceName(self.op.name)
6050
      if name is None:
6051
        raise errors.OpPrereqError("Invalid instance name (%s)" %
6052
                                   (self.op.name,))
6053
      self.op.name = name
6054
      self.needed_locks[locking.LEVEL_INSTANCE] = name
6055

    
6056
  def CheckPrereq(self):
6057
    """Check prerequisites.
6058

6059
    """
6060
    if self.op.kind == constants.TAG_CLUSTER:
6061
      self.target = self.cfg.GetClusterInfo()
6062
    elif self.op.kind == constants.TAG_NODE:
6063
      self.target = self.cfg.GetNodeInfo(self.op.name)
6064
    elif self.op.kind == constants.TAG_INSTANCE:
6065
      self.target = self.cfg.GetInstanceInfo(self.op.name)
6066
    else:
6067
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
6068
                                 str(self.op.kind))
6069

    
6070

    
6071
class LUGetTags(TagsLU):
6072
  """Returns the tags of a given object.
6073

6074
  """
6075
  _OP_REQP = ["kind", "name"]
6076
  REQ_BGL = False
6077

    
6078
  def Exec(self, feedback_fn):
6079
    """Returns the tag list.
6080

6081
    """
6082
    return list(self.target.GetTags())
6083

    
6084

    
6085
class LUSearchTags(NoHooksLU):
6086
  """Searches the tags for a given pattern.
6087

6088
  """
6089
  _OP_REQP = ["pattern"]
6090
  REQ_BGL = False
6091

    
6092
  def ExpandNames(self):
6093
    self.needed_locks = {}
6094

    
6095
  def CheckPrereq(self):
6096
    """Check prerequisites.
6097

6098
    This checks the pattern passed for validity by compiling it.
6099

6100
    """
6101
    try:
6102
      self.re = re.compile(self.op.pattern)
6103
    except re.error, err:
6104
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
6105
                                 (self.op.pattern, err))
6106

    
6107
  def Exec(self, feedback_fn):
6108
    """Returns the tag list.
6109

6110
    """
6111
    cfg = self.cfg
6112
    tgts = [("/cluster", cfg.GetClusterInfo())]
6113
    ilist = cfg.GetAllInstancesInfo().values()
6114
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
6115
    nlist = cfg.GetAllNodesInfo().values()
6116
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
6117
    results = []
6118
    for path, target in tgts:
6119
      for tag in target.GetTags():
6120
        if self.re.search(tag):
6121
          results.append((path, tag))
6122
    return results
6123

    
6124

    
6125
class LUAddTags(TagsLU):
6126
  """Sets a tag on a given object.
6127

6128
  """
6129
  _OP_REQP = ["kind", "name", "tags"]
6130
  REQ_BGL = False
6131

    
6132
  def CheckPrereq(self):
6133
    """Check prerequisites.
6134

6135
    This checks the type and length of the tag name and value.
6136

6137
    """
6138
    TagsLU.CheckPrereq(self)
6139
    for tag in self.op.tags:
6140
      objects.TaggableObject.ValidateTag(tag)
6141

    
6142
  def Exec(self, feedback_fn):
6143
    """Sets the tag.
6144

6145
    """
6146
    try:
6147
      for tag in self.op.tags:
6148
        self.target.AddTag(tag)
6149
    except errors.TagError, err:
6150
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
6151
    try:
6152
      self.cfg.Update(self.target)
6153
    except errors.ConfigurationError:
6154
      raise errors.OpRetryError("There has been a modification to the"
6155
                                " config file and the operation has been"
6156
                                " aborted. Please retry.")
6157

    
6158

    
6159
class LUDelTags(TagsLU):
6160
  """Delete a list of tags from a given object.
6161

6162
  """
6163
  _OP_REQP = ["kind", "name", "tags"]
6164
  REQ_BGL = False
6165

    
6166
  def CheckPrereq(self):
6167
    """Check prerequisites.
6168

6169
    This checks that we have the given tag.
6170

6171
    """
6172
    TagsLU.CheckPrereq(self)
6173
    for tag in self.op.tags:
6174
      objects.TaggableObject.ValidateTag(tag)
6175
    del_tags = frozenset(self.op.tags)
6176
    cur_tags = self.target.GetTags()
6177
    if not del_tags <= cur_tags:
6178
      diff_tags = del_tags - cur_tags
6179
      diff_names = ["'%s'" % tag for tag in diff_tags]
6180
      diff_names.sort()
6181
      raise errors.OpPrereqError("Tag(s) %s not found" %
6182
                                 (",".join(diff_names)))
6183

    
6184
  def Exec(self, feedback_fn):
6185
    """Remove the tag from the object.
6186

6187
    """
6188
    for tag in self.op.tags:
6189
      self.target.RemoveTag(tag)
6190
    try:
6191
      self.cfg.Update(self.target)
6192
    except errors.ConfigurationError:
6193
      raise errors.OpRetryError("There has been a modification to the"
6194
                                " config file and the operation has been"
6195
                                " aborted. Please retry.")
6196

    
6197

    
6198
class LUTestDelay(NoHooksLU):
6199
  """Sleep for a specified amount of time.
6200

6201
  This LU sleeps on the master and/or nodes for a specified amount of
6202
  time.
6203

6204
  """
6205
  _OP_REQP = ["duration", "on_master", "on_nodes"]
6206
  REQ_BGL = False
6207

    
6208
  def ExpandNames(self):
6209
    """Expand names and set required locks.
6210

6211
    This expands the node list, if any.
6212

6213
    """
6214
    self.needed_locks = {}
6215
    if self.op.on_nodes:
6216
      # _GetWantedNodes can be used here, but is not always appropriate to use
6217
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
6218
      # more information.
6219
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
6220
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
6221

    
6222
  def CheckPrereq(self):
6223
    """Check prerequisites.
6224

6225
    """
6226

    
6227
  def Exec(self, feedback_fn):
6228
    """Do the actual sleep.
6229

6230
    """
6231
    if self.op.on_master:
6232
      if not utils.TestDelay(self.op.duration):
6233
        raise errors.OpExecError("Error during master delay test")
6234
    if self.op.on_nodes:
6235
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
6236
      if not result:
6237
        raise errors.OpExecError("Complete failure from rpc call")
6238
      for node, node_result in result.items():
6239
        node_result.Raise()
6240
        if not node_result.data:
6241
          raise errors.OpExecError("Failure during rpc call to node %s,"
6242
                                   " result: %s" % (node, node_result.data))
6243

    
6244

    
6245
class IAllocator(object):
6246
  """IAllocator framework.
6247

6248
  An IAllocator instance has three sets of attributes:
6249
    - cfg that is needed to query the cluster
6250
    - input data (all members of the _KEYS class attribute are required)
6251
    - four buffer attributes (in|out_data|text), that represent the
6252
      input (to the external script) in text and data structure format,
6253
      and the output from it, again in two formats
6254
    - the result variables from the script (success, info, nodes) for
6255
      easy usage
6256

6257
  """
6258
  _ALLO_KEYS = [
6259
    "mem_size", "disks", "disk_template",
6260
    "os", "tags", "nics", "vcpus", "hypervisor",
6261
    ]
6262
  _RELO_KEYS = [
6263
    "relocate_from",
6264
    ]
6265

    
6266
  def __init__(self, lu, mode, name, **kwargs):
6267
    self.lu = lu
6268
    # init buffer variables
6269
    self.in_text = self.out_text = self.in_data = self.out_data = None
6270
    # init all input fields so that pylint is happy
6271
    self.mode = mode
6272
    self.name = name
6273
    self.mem_size = self.disks = self.disk_template = None
6274
    self.os = self.tags = self.nics = self.vcpus = None
6275
    self.hypervisor = None
6276
    self.relocate_from = None
6277
    # computed fields
6278
    self.required_nodes = None
6279
    # init result fields
6280
    self.success = self.info = self.nodes = None
6281
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6282
      keyset = self._ALLO_KEYS
6283
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
6284
      keyset = self._RELO_KEYS
6285
    else:
6286
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
6287
                                   " IAllocator" % self.mode)
6288
    for key in kwargs:
6289
      if key not in keyset:
6290
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
6291
                                     " IAllocator" % key)
6292
      setattr(self, key, kwargs[key])
6293
    for key in keyset:
6294
      if key not in kwargs:
6295
        raise errors.ProgrammerError("Missing input parameter '%s' to"
6296
                                     " IAllocator" % key)
6297
    self._BuildInputData()
6298

    
6299
  def _ComputeClusterData(self):
6300
    """Compute the generic allocator input data.
6301

6302
    This is the data that is independent of the actual operation.
6303

6304
    """
6305
    cfg = self.lu.cfg
6306
    cluster_info = cfg.GetClusterInfo()
6307
    # cluster data
6308
    data = {
6309
      "version": 1,
6310
      "cluster_name": cfg.GetClusterName(),
6311
      "cluster_tags": list(cluster_info.GetTags()),
6312
      "enable_hypervisors": list(cluster_info.enabled_hypervisors),
6313
      # we don't have job IDs
6314
      }
6315
    iinfo = cfg.GetAllInstancesInfo().values()
6316
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
6317

    
6318
    # node data
6319
    node_results = {}
6320
    node_list = cfg.GetNodeList()
6321

    
6322
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6323
      hypervisor_name = self.hypervisor
6324
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
6325
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
6326

    
6327
    node_data = self.lu.rpc.call_node_info(node_list, cfg.GetVGName(),
6328
                                           hypervisor_name)
6329
    node_iinfo = self.lu.rpc.call_all_instances_info(node_list,
6330
                       cluster_info.enabled_hypervisors)
6331
    for nname in node_list:
6332
      ninfo = cfg.GetNodeInfo(nname)
6333
      node_data[nname].Raise()
6334
      if not isinstance(node_data[nname].data, dict):
6335
        raise errors.OpExecError("Can't get data for node %s" % nname)
6336
      remote_info = node_data[nname].data
6337
      for attr in ['memory_total', 'memory_free', 'memory_dom0',
6338
                   'vg_size', 'vg_free', 'cpu_total']:
6339
        if attr not in remote_info:
6340
          raise errors.OpExecError("Node '%s' didn't return attribute '%s'" %
6341
                                   (nname, attr))
6342
        try:
6343
          remote_info[attr] = int(remote_info[attr])
6344
        except ValueError, err:
6345
          raise errors.OpExecError("Node '%s' returned invalid value for '%s':"
6346
                                   " %s" % (nname, attr, str(err)))
6347
      # compute memory used by primary instances
6348
      i_p_mem = i_p_up_mem = 0
6349
      for iinfo, beinfo in i_list:
6350
        if iinfo.primary_node == nname:
6351
          i_p_mem += beinfo[constants.BE_MEMORY]
6352
          if iinfo.name not in node_iinfo[nname]:
6353
            i_used_mem = 0
6354
          else:
6355
            i_used_mem = int(node_iinfo[nname][iinfo.name]['memory'])
6356
          i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
6357
          remote_info['memory_free'] -= max(0, i_mem_diff)
6358

    
6359
          if iinfo.status == "up":
6360
            i_p_up_mem += beinfo[constants.BE_MEMORY]
6361

    
6362
      # compute memory used by instances
6363
      pnr = {
6364
        "tags": list(ninfo.GetTags()),
6365
        "total_memory": remote_info['memory_total'],
6366
        "reserved_memory": remote_info['memory_dom0'],
6367
        "free_memory": remote_info['memory_free'],
6368
        "i_pri_memory": i_p_mem,
6369
        "i_pri_up_memory": i_p_up_mem,
6370
        "total_disk": remote_info['vg_size'],
6371
        "free_disk": remote_info['vg_free'],
6372
        "primary_ip": ninfo.primary_ip,
6373
        "secondary_ip": ninfo.secondary_ip,
6374
        "total_cpus": remote_info['cpu_total'],
6375
        "offline": ninfo.offline,
6376
        }
6377
      node_results[nname] = pnr
6378
    data["nodes"] = node_results
6379

    
6380
    # instance data
6381
    instance_data = {}
6382
    for iinfo, beinfo in i_list:
6383
      nic_data = [{"mac": n.mac, "ip": n.ip, "bridge": n.bridge}
6384
                  for n in iinfo.nics]
6385
      pir = {
6386
        "tags": list(iinfo.GetTags()),
6387
        "should_run": iinfo.status == "up",
6388
        "vcpus": beinfo[constants.BE_VCPUS],
6389
        "memory": beinfo[constants.BE_MEMORY],
6390
        "os": iinfo.os,
6391
        "nodes": list(iinfo.all_nodes),
6392
        "nics": nic_data,
6393
        "disks": [{"size": dsk.size, "mode": "w"} for dsk in iinfo.disks],
6394
        "disk_template": iinfo.disk_template,
6395
        "hypervisor": iinfo.hypervisor,
6396
        }
6397
      instance_data[iinfo.name] = pir
6398

    
6399
    data["instances"] = instance_data
6400

    
6401
    self.in_data = data
6402

    
6403
  def _AddNewInstance(self):
6404
    """Add new instance data to allocator structure.
6405

6406
    This in combination with _AllocatorGetClusterData will create the
6407
    correct structure needed as input for the allocator.
6408

6409
    The checks for the completeness of the opcode must have already been
6410
    done.
6411

6412
    """
6413
    data = self.in_data
6414
    if len(self.disks) != 2:
6415
      raise errors.OpExecError("Only two-disk configurations supported")
6416

    
6417
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
6418

    
6419
    if self.disk_template in constants.DTS_NET_MIRROR:
6420
      self.required_nodes = 2
6421
    else:
6422
      self.required_nodes = 1
6423
    request = {
6424
      "type": "allocate",
6425
      "name": self.name,
6426
      "disk_template": self.disk_template,
6427
      "tags": self.tags,
6428
      "os": self.os,
6429
      "vcpus": self.vcpus,
6430
      "memory": self.mem_size,
6431
      "disks": self.disks,
6432
      "disk_space_total": disk_space,
6433
      "nics": self.nics,
6434
      "required_nodes": self.required_nodes,
6435
      }
6436
    data["request"] = request
6437

    
6438
  def _AddRelocateInstance(self):
6439
    """Add relocate instance data to allocator structure.
6440

6441
    This in combination with _IAllocatorGetClusterData will create the
6442
    correct structure needed as input for the allocator.
6443

6444
    The checks for the completeness of the opcode must have already been
6445
    done.
6446

6447
    """
6448
    instance = self.lu.cfg.GetInstanceInfo(self.name)
6449
    if instance is None:
6450
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
6451
                                   " IAllocator" % self.name)
6452

    
6453
    if instance.disk_template not in constants.DTS_NET_MIRROR:
6454
      raise errors.OpPrereqError("Can't relocate non-mirrored instances")
6455

    
6456
    if len(instance.secondary_nodes) != 1:
6457
      raise errors.OpPrereqError("Instance has not exactly one secondary node")
6458

    
6459
    self.required_nodes = 1
6460
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
6461
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
6462

    
6463
    request = {
6464
      "type": "relocate",
6465
      "name": self.name,
6466
      "disk_space_total": disk_space,
6467
      "required_nodes": self.required_nodes,
6468
      "relocate_from": self.relocate_from,
6469
      }
6470
    self.in_data["request"] = request
6471

    
6472
  def _BuildInputData(self):
6473
    """Build input data structures.
6474

6475
    """
6476
    self._ComputeClusterData()
6477

    
6478
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6479
      self._AddNewInstance()
6480
    else:
6481
      self._AddRelocateInstance()
6482

    
6483
    self.in_text = serializer.Dump(self.in_data)
6484

    
6485
  def Run(self, name, validate=True, call_fn=None):
6486
    """Run an instance allocator and return the results.
6487

6488
    """
6489
    if call_fn is None:
6490
      call_fn = self.lu.rpc.call_iallocator_runner
6491
    data = self.in_text
6492

    
6493
    result = call_fn(self.lu.cfg.GetMasterNode(), name, self.in_text)
6494
    result.Raise()
6495

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

    
6499
    rcode, stdout, stderr, fail = result.data
6500

    
6501
    if rcode == constants.IARUN_NOTFOUND:
6502
      raise errors.OpExecError("Can't find allocator '%s'" % name)
6503
    elif rcode == constants.IARUN_FAILURE:
6504
      raise errors.OpExecError("Instance allocator call failed: %s,"
6505
                               " output: %s" % (fail, stdout+stderr))
6506
    self.out_text = stdout
6507
    if validate:
6508
      self._ValidateResult()
6509

    
6510
  def _ValidateResult(self):
6511
    """Process the allocator results.
6512

6513
    This will process and if successful save the result in
6514
    self.out_data and the other parameters.
6515

6516
    """
6517
    try:
6518
      rdict = serializer.Load(self.out_text)
6519
    except Exception, err:
6520
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
6521

    
6522
    if not isinstance(rdict, dict):
6523
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
6524

    
6525
    for key in "success", "info", "nodes":
6526
      if key not in rdict:
6527
        raise errors.OpExecError("Can't parse iallocator results:"
6528
                                 " missing key '%s'" % key)
6529
      setattr(self, key, rdict[key])
6530

    
6531
    if not isinstance(rdict["nodes"], list):
6532
      raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
6533
                               " is not a list")
6534
    self.out_data = rdict
6535

    
6536

    
6537
class LUTestAllocator(NoHooksLU):
6538
  """Run allocator tests.
6539

6540
  This LU runs the allocator tests
6541

6542
  """
6543
  _OP_REQP = ["direction", "mode", "name"]
6544

    
6545
  def CheckPrereq(self):
6546
    """Check prerequisites.
6547

6548
    This checks the opcode parameters depending on the director and mode test.
6549

6550
    """
6551
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
6552
      for attr in ["name", "mem_size", "disks", "disk_template",
6553
                   "os", "tags", "nics", "vcpus"]:
6554
        if not hasattr(self.op, attr):
6555
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
6556
                                     attr)
6557
      iname = self.cfg.ExpandInstanceName(self.op.name)
6558
      if iname is not None:
6559
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
6560
                                   iname)
6561
      if not isinstance(self.op.nics, list):
6562
        raise errors.OpPrereqError("Invalid parameter 'nics'")
6563
      for row in self.op.nics:
6564
        if (not isinstance(row, dict) or
6565
            "mac" not in row or
6566
            "ip" not in row or
6567
            "bridge" not in row):
6568
          raise errors.OpPrereqError("Invalid contents of the"
6569
                                     " 'nics' parameter")
6570
      if not isinstance(self.op.disks, list):
6571
        raise errors.OpPrereqError("Invalid parameter 'disks'")
6572
      if len(self.op.disks) != 2:
6573
        raise errors.OpPrereqError("Only two-disk configurations supported")
6574
      for row in self.op.disks:
6575
        if (not isinstance(row, dict) or
6576
            "size" not in row or
6577
            not isinstance(row["size"], int) or
6578
            "mode" not in row or
6579
            row["mode"] not in ['r', 'w']):
6580
          raise errors.OpPrereqError("Invalid contents of the"
6581
                                     " 'disks' parameter")
6582
      if self.op.hypervisor is None:
6583
        self.op.hypervisor = self.cfg.GetHypervisorType()
6584
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
6585
      if not hasattr(self.op, "name"):
6586
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input")
6587
      fname = self.cfg.ExpandInstanceName(self.op.name)
6588
      if fname is None:
6589
        raise errors.OpPrereqError("Instance '%s' not found for relocation" %
6590
                                   self.op.name)
6591
      self.op.name = fname
6592
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
6593
    else:
6594
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
6595
                                 self.op.mode)
6596

    
6597
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
6598
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
6599
        raise errors.OpPrereqError("Missing allocator name")
6600
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
6601
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
6602
                                 self.op.direction)
6603

    
6604
  def Exec(self, feedback_fn):
6605
    """Run the allocator test.
6606

6607
    """
6608
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
6609
      ial = IAllocator(self,
6610
                       mode=self.op.mode,
6611
                       name=self.op.name,
6612
                       mem_size=self.op.mem_size,
6613
                       disks=self.op.disks,
6614
                       disk_template=self.op.disk_template,
6615
                       os=self.op.os,
6616
                       tags=self.op.tags,
6617
                       nics=self.op.nics,
6618
                       vcpus=self.op.vcpus,
6619
                       hypervisor=self.op.hypervisor,
6620
                       )
6621
    else:
6622
      ial = IAllocator(self,
6623
                       mode=self.op.mode,
6624
                       name=self.op.name,
6625
                       relocate_from=list(self.relocate_from),
6626
                       )
6627

    
6628
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
6629
      result = ial.in_text
6630
    else:
6631
      ial.Run(self.op.allocator, validate=False)
6632
      result = ial.out_text
6633
    return result