Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 7e9366f7

History | View | Annotate | Download (217.7 kB)

1
#
2
#
3

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

    
21

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

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

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

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

    
48

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

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

61
  Note that all commands require root permissions.
62

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

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

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

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

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

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

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

    
109
  ssh = property(fget=__GetSSH)
110

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

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

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

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

126
    """
127
    pass
128

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

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

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

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

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

150
    Examples::
151

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

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

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

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

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

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

189
    """
190

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

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

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

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

205
    """
206
    raise NotImplementedError
207

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

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

215
    """
216
    raise NotImplementedError
217

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

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

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

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

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

237
    """
238
    raise NotImplementedError
239

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

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

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

258
    """
259
    return lu_result
260

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
326
    del self.recalculate_locks[locking.LEVEL_NODE]
327

    
328

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

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

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

    
339

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

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

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

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

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

    
366
  return utils.NiceSort(wanted)
367

    
368

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

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

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

    
385
  if instances:
386
    wanted = []
387

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

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

    
398

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

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

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

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

    
417

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

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

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

    
431

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

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

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

    
443

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

448
  This builds the hook environment from individual variables.
449

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

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

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

    
493
  env["INSTANCE_NIC_COUNT"] = nic_count
494

    
495
  return env
496

    
497

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

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

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

    
528

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

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

    
544

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

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

    
558

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

562
  """
563
  _OP_REQP = []
564

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

568
    This checks whether the cluster is empty.
569

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

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

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

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

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

    
598

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

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

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

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

619
    Test list:
620

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

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

634
    """
635
    node = nodeinfo.name
636

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

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

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

    
654
    # checks vg existance and size > 20G
655

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

    
669
    # checks config file checksum
670

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

    
698
    # checks ssh to any
699

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

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

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

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

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

736
    """
737
    bad = False
738

    
739
    node_current = instanceconfig.primary_node
740

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

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

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

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

    
769
    return bad
770

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

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

777
    """
778
    bad = False
779

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

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

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

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

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

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

809
    """
810
    bad = False
811

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

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

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

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

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

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

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

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

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

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

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

    
882
    file_names = ssconf.SimpleStore().GetFileList()
883
    file_names.append(constants.SSL_CERT_FILE)
884
    file_names.append(constants.RAPI_CERT_FILE)
885
    file_names.extend(master_files)
886

    
887
    local_checksums = utils.FingerprintFiles(file_names)
888

    
889
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
890
    node_verify_param = {
891
      constants.NV_FILELIST: file_names,
892
      constants.NV_NODELIST: [node.name for node in nodeinfo
893
                              if not node.offline],
894
      constants.NV_HYPERVISOR: hypervisors,
895
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
896
                                  node.secondary_ip) for node in nodeinfo
897
                                 if not node.offline],
898
      constants.NV_LVLIST: vg_name,
899
      constants.NV_INSTANCELIST: hypervisors,
900
      constants.NV_VGLIST: None,
901
      constants.NV_VERSION: None,
902
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
903
      }
904
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
905
                                           self.cfg.GetClusterName())
906

    
907
    cluster = self.cfg.GetClusterInfo()
908
    master_node = self.cfg.GetMasterNode()
909
    for node_i in nodeinfo:
910
      node = node_i.name
911
      nresult = all_nvinfo[node].data
912

    
913
      if node_i.offline:
914
        feedback_fn("* Skipping offline node %s" % (node,))
915
        n_offline.append(node)
916
        continue
917

    
918
      if node == master_node:
919
        ntype = "master"
920
      elif node_i.master_candidate:
921
        ntype = "master candidate"
922
      else:
923
        ntype = "regular"
924
      feedback_fn("* Verifying node %s (%s)" % (node, ntype))
925

    
926
      if all_nvinfo[node].failed or not isinstance(nresult, dict):
927
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
928
        bad = True
929
        continue
930

    
931
      result = self._VerifyNode(node_i, file_names, local_checksums,
932
                                nresult, feedback_fn, master_files)
933
      bad = bad or result
934

    
935
      lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
936
      if isinstance(lvdata, basestring):
937
        feedback_fn("  - ERROR: LVM problem on node %s: %s" %
938
                    (node, lvdata.encode('string_escape')))
939
        bad = True
940
        node_volume[node] = {}
941
      elif not isinstance(lvdata, dict):
942
        feedback_fn("  - ERROR: connection to %s failed (lvlist)" % (node,))
943
        bad = True
944
        continue
945
      else:
946
        node_volume[node] = lvdata
947

    
948
      # node_instance
949
      idata = nresult.get(constants.NV_INSTANCELIST, None)
950
      if not isinstance(idata, list):
951
        feedback_fn("  - ERROR: connection to %s failed (instancelist)" %
952
                    (node,))
953
        bad = True
954
        continue
955

    
956
      node_instance[node] = idata
957

    
958
      # node_info
959
      nodeinfo = nresult.get(constants.NV_HVINFO, None)
960
      if not isinstance(nodeinfo, dict):
961
        feedback_fn("  - ERROR: connection to %s failed (hvinfo)" % (node,))
962
        bad = True
963
        continue
964

    
965
      try:
966
        node_info[node] = {
967
          "mfree": int(nodeinfo['memory_free']),
968
          "dfree": int(nresult[constants.NV_VGLIST][vg_name]),
969
          "pinst": [],
970
          "sinst": [],
971
          # dictionary holding all instances this node is secondary for,
972
          # grouped by their primary node. Each key is a cluster node, and each
973
          # value is a list of instances which have the key as primary and the
974
          # current node as secondary.  this is handy to calculate N+1 memory
975
          # availability if you can only failover from a primary to its
976
          # secondary.
977
          "sinst-by-pnode": {},
978
        }
979
      except ValueError:
980
        feedback_fn("  - ERROR: invalid value returned from node %s" % (node,))
981
        bad = True
982
        continue
983

    
984
    node_vol_should = {}
985

    
986
    for instance in instancelist:
987
      feedback_fn("* Verifying instance %s" % instance)
988
      inst_config = self.cfg.GetInstanceInfo(instance)
989
      result =  self._VerifyInstance(instance, inst_config, node_volume,
990
                                     node_instance, feedback_fn, n_offline)
991
      bad = bad or result
992
      inst_nodes_offline = []
993

    
994
      inst_config.MapLVsByNode(node_vol_should)
995

    
996
      instance_cfg[instance] = inst_config
997

    
998
      pnode = inst_config.primary_node
999
      if pnode in node_info:
1000
        node_info[pnode]['pinst'].append(instance)
1001
      elif pnode not in n_offline:
1002
        feedback_fn("  - ERROR: instance %s, connection to primary node"
1003
                    " %s failed" % (instance, pnode))
1004
        bad = True
1005

    
1006
      if pnode in n_offline:
1007
        inst_nodes_offline.append(pnode)
1008

    
1009
      # If the instance is non-redundant we cannot survive losing its primary
1010
      # node, so we are not N+1 compliant. On the other hand we have no disk
1011
      # templates with more than one secondary so that situation is not well
1012
      # supported either.
1013
      # FIXME: does not support file-backed instances
1014
      if len(inst_config.secondary_nodes) == 0:
1015
        i_non_redundant.append(instance)
1016
      elif len(inst_config.secondary_nodes) > 1:
1017
        feedback_fn("  - WARNING: multiple secondaries for instance %s"
1018
                    % instance)
1019

    
1020
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1021
        i_non_a_balanced.append(instance)
1022

    
1023
      for snode in inst_config.secondary_nodes:
1024
        if snode in node_info:
1025
          node_info[snode]['sinst'].append(instance)
1026
          if pnode not in node_info[snode]['sinst-by-pnode']:
1027
            node_info[snode]['sinst-by-pnode'][pnode] = []
1028
          node_info[snode]['sinst-by-pnode'][pnode].append(instance)
1029
        elif snode not in n_offline:
1030
          feedback_fn("  - ERROR: instance %s, connection to secondary node"
1031
                      " %s failed" % (instance, snode))
1032
          bad = True
1033
        if snode in n_offline:
1034
          inst_nodes_offline.append(snode)
1035

    
1036
      if inst_nodes_offline:
1037
        # warn that the instance lives on offline nodes, and set bad=True
1038
        feedback_fn("  - ERROR: instance lives on offline node(s) %s" %
1039
                    ", ".join(inst_nodes_offline))
1040
        bad = True
1041

    
1042
    feedback_fn("* Verifying orphan volumes")
1043
    result = self._VerifyOrphanVolumes(node_vol_should, node_volume,
1044
                                       feedback_fn)
1045
    bad = bad or result
1046

    
1047
    feedback_fn("* Verifying remaining instances")
1048
    result = self._VerifyOrphanInstances(instancelist, node_instance,
1049
                                         feedback_fn)
1050
    bad = bad or result
1051

    
1052
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1053
      feedback_fn("* Verifying N+1 Memory redundancy")
1054
      result = self._VerifyNPlusOneMemory(node_info, instance_cfg, feedback_fn)
1055
      bad = bad or result
1056

    
1057
    feedback_fn("* Other Notes")
1058
    if i_non_redundant:
1059
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1060
                  % len(i_non_redundant))
1061

    
1062
    if i_non_a_balanced:
1063
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1064
                  % len(i_non_a_balanced))
1065

    
1066
    if n_offline:
1067
      feedback_fn("  - NOTICE: %d offline node(s) found." % len(n_offline))
1068

    
1069
    return not bad
1070

    
1071
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1072
    """Analize the post-hooks' result
1073

1074
    This method analyses the hook result, handles it, and sends some
1075
    nicely-formatted feedback back to the user.
1076

1077
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1078
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1079
    @param hooks_results: the results of the multi-node hooks rpc call
1080
    @param feedback_fn: function used send feedback back to the caller
1081
    @param lu_result: previous Exec result
1082
    @return: the new Exec result, based on the previous result
1083
        and hook results
1084

1085
    """
1086
    # We only really run POST phase hooks, and are only interested in
1087
    # their results
1088
    if phase == constants.HOOKS_PHASE_POST:
1089
      # Used to change hooks' output to proper indentation
1090
      indent_re = re.compile('^', re.M)
1091
      feedback_fn("* Hooks Results")
1092
      if not hooks_results:
1093
        feedback_fn("  - ERROR: general communication failure")
1094
        lu_result = 1
1095
      else:
1096
        for node_name in hooks_results:
1097
          show_node_header = True
1098
          res = hooks_results[node_name]
1099
          if res.failed or res.data is False or not isinstance(res.data, list):
1100
            if res.offline:
1101
              # no need to warn or set fail return value
1102
              continue
1103
            feedback_fn("    Communication failure in hooks execution")
1104
            lu_result = 1
1105
            continue
1106
          for script, hkr, output in res.data:
1107
            if hkr == constants.HKR_FAIL:
1108
              # The node header is only shown once, if there are
1109
              # failing hooks on that node
1110
              if show_node_header:
1111
                feedback_fn("  Node %s:" % node_name)
1112
                show_node_header = False
1113
              feedback_fn("    ERROR: Script %s failed, output:" % script)
1114
              output = indent_re.sub('      ', output)
1115
              feedback_fn("%s" % output)
1116
              lu_result = 1
1117

    
1118
      return lu_result
1119

    
1120

    
1121
class LUVerifyDisks(NoHooksLU):
1122
  """Verifies the cluster disks status.
1123

1124
  """
1125
  _OP_REQP = []
1126
  REQ_BGL = False
1127

    
1128
  def ExpandNames(self):
1129
    self.needed_locks = {
1130
      locking.LEVEL_NODE: locking.ALL_SET,
1131
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1132
    }
1133
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
1134

    
1135
  def CheckPrereq(self):
1136
    """Check prerequisites.
1137

1138
    This has no prerequisites.
1139

1140
    """
1141
    pass
1142

    
1143
  def Exec(self, feedback_fn):
1144
    """Verify integrity of cluster disks.
1145

1146
    """
1147
    result = res_nodes, res_nlvm, res_instances, res_missing = [], {}, [], {}
1148

    
1149
    vg_name = self.cfg.GetVGName()
1150
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1151
    instances = [self.cfg.GetInstanceInfo(name)
1152
                 for name in self.cfg.GetInstanceList()]
1153

    
1154
    nv_dict = {}
1155
    for inst in instances:
1156
      inst_lvs = {}
1157
      if (inst.status != "up" or
1158
          inst.disk_template not in constants.DTS_NET_MIRROR):
1159
        continue
1160
      inst.MapLVsByNode(inst_lvs)
1161
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1162
      for node, vol_list in inst_lvs.iteritems():
1163
        for vol in vol_list:
1164
          nv_dict[(node, vol)] = inst
1165

    
1166
    if not nv_dict:
1167
      return result
1168

    
1169
    node_lvs = self.rpc.call_volume_list(nodes, vg_name)
1170

    
1171
    to_act = set()
1172
    for node in nodes:
1173
      # node_volume
1174
      lvs = node_lvs[node]
1175
      if lvs.failed:
1176
        if not lvs.offline:
1177
          self.LogWarning("Connection to node %s failed: %s" %
1178
                          (node, lvs.data))
1179
        continue
1180
      lvs = lvs.data
1181
      if isinstance(lvs, basestring):
1182
        logging.warning("Error enumerating LVs on node %s: %s", node, lvs)
1183
        res_nlvm[node] = lvs
1184
      elif not isinstance(lvs, dict):
1185
        logging.warning("Connection to node %s failed or invalid data"
1186
                        " returned", node)
1187
        res_nodes.append(node)
1188
        continue
1189

    
1190
      for lv_name, (_, lv_inactive, lv_online) in lvs.iteritems():
1191
        inst = nv_dict.pop((node, lv_name), None)
1192
        if (not lv_online and inst is not None
1193
            and inst.name not in res_instances):
1194
          res_instances.append(inst.name)
1195

    
1196
    # any leftover items in nv_dict are missing LVs, let's arrange the
1197
    # data better
1198
    for key, inst in nv_dict.iteritems():
1199
      if inst.name not in res_missing:
1200
        res_missing[inst.name] = []
1201
      res_missing[inst.name].append(key)
1202

    
1203
    return result
1204

    
1205

    
1206
class LURenameCluster(LogicalUnit):
1207
  """Rename the cluster.
1208

1209
  """
1210
  HPATH = "cluster-rename"
1211
  HTYPE = constants.HTYPE_CLUSTER
1212
  _OP_REQP = ["name"]
1213

    
1214
  def BuildHooksEnv(self):
1215
    """Build hooks env.
1216

1217
    """
1218
    env = {
1219
      "OP_TARGET": self.cfg.GetClusterName(),
1220
      "NEW_NAME": self.op.name,
1221
      }
1222
    mn = self.cfg.GetMasterNode()
1223
    return env, [mn], [mn]
1224

    
1225
  def CheckPrereq(self):
1226
    """Verify that the passed name is a valid one.
1227

1228
    """
1229
    hostname = utils.HostInfo(self.op.name)
1230

    
1231
    new_name = hostname.name
1232
    self.ip = new_ip = hostname.ip
1233
    old_name = self.cfg.GetClusterName()
1234
    old_ip = self.cfg.GetMasterIP()
1235
    if new_name == old_name and new_ip == old_ip:
1236
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1237
                                 " cluster has changed")
1238
    if new_ip != old_ip:
1239
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1240
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1241
                                   " reachable on the network. Aborting." %
1242
                                   new_ip)
1243

    
1244
    self.op.name = new_name
1245

    
1246
  def Exec(self, feedback_fn):
1247
    """Rename the cluster.
1248

1249
    """
1250
    clustername = self.op.name
1251
    ip = self.ip
1252

    
1253
    # shutdown the master IP
1254
    master = self.cfg.GetMasterNode()
1255
    result = self.rpc.call_node_stop_master(master, False)
1256
    if result.failed or not result.data:
1257
      raise errors.OpExecError("Could not disable the master role")
1258

    
1259
    try:
1260
      cluster = self.cfg.GetClusterInfo()
1261
      cluster.cluster_name = clustername
1262
      cluster.master_ip = ip
1263
      self.cfg.Update(cluster)
1264

    
1265
      # update the known hosts file
1266
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
1267
      node_list = self.cfg.GetNodeList()
1268
      try:
1269
        node_list.remove(master)
1270
      except ValueError:
1271
        pass
1272
      result = self.rpc.call_upload_file(node_list,
1273
                                         constants.SSH_KNOWN_HOSTS_FILE)
1274
      for to_node, to_result in result.iteritems():
1275
        if to_result.failed or not to_result.data:
1276
          logging.error("Copy of file %s to node %s failed",
1277
                        constants.SSH_KNOWN_HOSTS_FILE, to_node)
1278

    
1279
    finally:
1280
      result = self.rpc.call_node_start_master(master, False)
1281
      if result.failed or not result.data:
1282
        self.LogWarning("Could not re-enable the master role on"
1283
                        " the master, please restart manually.")
1284

    
1285

    
1286
def _RecursiveCheckIfLVMBased(disk):
1287
  """Check if the given disk or its children are lvm-based.
1288

1289
  @type disk: L{objects.Disk}
1290
  @param disk: the disk to check
1291
  @rtype: booleean
1292
  @return: boolean indicating whether a LD_LV dev_type was found or not
1293

1294
  """
1295
  if disk.children:
1296
    for chdisk in disk.children:
1297
      if _RecursiveCheckIfLVMBased(chdisk):
1298
        return True
1299
  return disk.dev_type == constants.LD_LV
1300

    
1301

    
1302
class LUSetClusterParams(LogicalUnit):
1303
  """Change the parameters of the cluster.
1304

1305
  """
1306
  HPATH = "cluster-modify"
1307
  HTYPE = constants.HTYPE_CLUSTER
1308
  _OP_REQP = []
1309
  REQ_BGL = False
1310

    
1311
  def CheckParameters(self):
1312
    """Check parameters
1313

1314
    """
1315
    if not hasattr(self.op, "candidate_pool_size"):
1316
      self.op.candidate_pool_size = None
1317
    if self.op.candidate_pool_size is not None:
1318
      try:
1319
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
1320
      except ValueError, err:
1321
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
1322
                                   str(err))
1323
      if self.op.candidate_pool_size < 1:
1324
        raise errors.OpPrereqError("At least one master candidate needed")
1325

    
1326
  def ExpandNames(self):
1327
    # FIXME: in the future maybe other cluster params won't require checking on
1328
    # all nodes to be modified.
1329
    self.needed_locks = {
1330
      locking.LEVEL_NODE: locking.ALL_SET,
1331
    }
1332
    self.share_locks[locking.LEVEL_NODE] = 1
1333

    
1334
  def BuildHooksEnv(self):
1335
    """Build hooks env.
1336

1337
    """
1338
    env = {
1339
      "OP_TARGET": self.cfg.GetClusterName(),
1340
      "NEW_VG_NAME": self.op.vg_name,
1341
      }
1342
    mn = self.cfg.GetMasterNode()
1343
    return env, [mn], [mn]
1344

    
1345
  def CheckPrereq(self):
1346
    """Check prerequisites.
1347

1348
    This checks whether the given params don't conflict and
1349
    if the given volume group is valid.
1350

1351
    """
1352
    # FIXME: This only works because there is only one parameter that can be
1353
    # changed or removed.
1354
    if self.op.vg_name is not None and not self.op.vg_name:
1355
      instances = self.cfg.GetAllInstancesInfo().values()
1356
      for inst in instances:
1357
        for disk in inst.disks:
1358
          if _RecursiveCheckIfLVMBased(disk):
1359
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1360
                                       " lvm-based instances exist")
1361

    
1362
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1363

    
1364
    # if vg_name not None, checks given volume group on all nodes
1365
    if self.op.vg_name:
1366
      vglist = self.rpc.call_vg_list(node_list)
1367
      for node in node_list:
1368
        if vglist[node].failed:
1369
          # ignoring down node
1370
          self.LogWarning("Node %s unreachable/error, ignoring" % node)
1371
          continue
1372
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].data,
1373
                                              self.op.vg_name,
1374
                                              constants.MIN_VG_SIZE)
1375
        if vgstatus:
1376
          raise errors.OpPrereqError("Error on node '%s': %s" %
1377
                                     (node, vgstatus))
1378

    
1379
    self.cluster = cluster = self.cfg.GetClusterInfo()
1380
    # validate beparams changes
1381
    if self.op.beparams:
1382
      utils.CheckBEParams(self.op.beparams)
1383
      self.new_beparams = cluster.FillDict(
1384
        cluster.beparams[constants.BEGR_DEFAULT], self.op.beparams)
1385

    
1386
    # hypervisor list/parameters
1387
    self.new_hvparams = cluster.FillDict(cluster.hvparams, {})
1388
    if self.op.hvparams:
1389
      if not isinstance(self.op.hvparams, dict):
1390
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input")
1391
      for hv_name, hv_dict in self.op.hvparams.items():
1392
        if hv_name not in self.new_hvparams:
1393
          self.new_hvparams[hv_name] = hv_dict
1394
        else:
1395
          self.new_hvparams[hv_name].update(hv_dict)
1396

    
1397
    if self.op.enabled_hypervisors is not None:
1398
      self.hv_list = self.op.enabled_hypervisors
1399
    else:
1400
      self.hv_list = cluster.enabled_hypervisors
1401

    
1402
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
1403
      # either the enabled list has changed, or the parameters have, validate
1404
      for hv_name, hv_params in self.new_hvparams.items():
1405
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
1406
            (self.op.enabled_hypervisors and
1407
             hv_name in self.op.enabled_hypervisors)):
1408
          # either this is a new hypervisor, or its parameters have changed
1409
          hv_class = hypervisor.GetHypervisor(hv_name)
1410
          hv_class.CheckParameterSyntax(hv_params)
1411
          _CheckHVParams(self, node_list, hv_name, hv_params)
1412

    
1413
  def Exec(self, feedback_fn):
1414
    """Change the parameters of the cluster.
1415

1416
    """
1417
    if self.op.vg_name is not None:
1418
      if self.op.vg_name != self.cfg.GetVGName():
1419
        self.cfg.SetVGName(self.op.vg_name)
1420
      else:
1421
        feedback_fn("Cluster LVM configuration already in desired"
1422
                    " state, not changing")
1423
    if self.op.hvparams:
1424
      self.cluster.hvparams = self.new_hvparams
1425
    if self.op.enabled_hypervisors is not None:
1426
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
1427
    if self.op.beparams:
1428
      self.cluster.beparams[constants.BEGR_DEFAULT] = self.new_beparams
1429
    if self.op.candidate_pool_size is not None:
1430
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
1431

    
1432
    self.cfg.Update(self.cluster)
1433

    
1434
    # we want to update nodes after the cluster so that if any errors
1435
    # happen, we have recorded and saved the cluster info
1436
    if self.op.candidate_pool_size is not None:
1437
      _AdjustCandidatePool(self)
1438

    
1439

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

1443
  """
1444
  if not instance.disks:
1445
    return True
1446

    
1447
  if not oneshot:
1448
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
1449

    
1450
  node = instance.primary_node
1451

    
1452
  for dev in instance.disks:
1453
    lu.cfg.SetDiskID(dev, node)
1454

    
1455
  retries = 0
1456
  while True:
1457
    max_time = 0
1458
    done = True
1459
    cumul_degraded = False
1460
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
1461
    if rstats.failed or not rstats.data:
1462
      lu.LogWarning("Can't get any data from node %s", node)
1463
      retries += 1
1464
      if retries >= 10:
1465
        raise errors.RemoteError("Can't contact node %s for mirror data,"
1466
                                 " aborting." % node)
1467
      time.sleep(6)
1468
      continue
1469
    rstats = rstats.data
1470
    retries = 0
1471
    for i in range(len(rstats)):
1472
      mstat = rstats[i]
1473
      if mstat is None:
1474
        lu.LogWarning("Can't compute data for node %s/%s",
1475
                           node, instance.disks[i].iv_name)
1476
        continue
1477
      # we ignore the ldisk parameter
1478
      perc_done, est_time, is_degraded, _ = mstat
1479
      cumul_degraded = cumul_degraded or (is_degraded and perc_done is None)
1480
      if perc_done is not None:
1481
        done = False
1482
        if est_time is not None:
1483
          rem_time = "%d estimated seconds remaining" % est_time
1484
          max_time = est_time
1485
        else:
1486
          rem_time = "no time estimate"
1487
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
1488
                        (instance.disks[i].iv_name, perc_done, rem_time))
1489
    if done or oneshot:
1490
      break
1491

    
1492
    time.sleep(min(60, max_time))
1493

    
1494
  if done:
1495
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
1496
  return not cumul_degraded
1497

    
1498

    
1499
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
1500
  """Check that mirrors are not degraded.
1501

1502
  The ldisk parameter, if True, will change the test from the
1503
  is_degraded attribute (which represents overall non-ok status for
1504
  the device(s)) to the ldisk (representing the local storage status).
1505

1506
  """
1507
  lu.cfg.SetDiskID(dev, node)
1508
  if ldisk:
1509
    idx = 6
1510
  else:
1511
    idx = 5
1512

    
1513
  result = True
1514
  if on_primary or dev.AssembleOnSecondary():
1515
    rstats = lu.rpc.call_blockdev_find(node, dev)
1516
    if rstats.failed or not rstats.data:
1517
      logging.warning("Node %s: disk degraded, not found or node down", node)
1518
      result = False
1519
    else:
1520
      result = result and (not rstats.data[idx])
1521
  if dev.children:
1522
    for child in dev.children:
1523
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
1524

    
1525
  return result
1526

    
1527

    
1528
class LUDiagnoseOS(NoHooksLU):
1529
  """Logical unit for OS diagnose/query.
1530

1531
  """
1532
  _OP_REQP = ["output_fields", "names"]
1533
  REQ_BGL = False
1534
  _FIELDS_STATIC = utils.FieldSet()
1535
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status")
1536

    
1537
  def ExpandNames(self):
1538
    if self.op.names:
1539
      raise errors.OpPrereqError("Selective OS query not supported")
1540

    
1541
    _CheckOutputFields(static=self._FIELDS_STATIC,
1542
                       dynamic=self._FIELDS_DYNAMIC,
1543
                       selected=self.op.output_fields)
1544

    
1545
    # Lock all nodes, in shared mode
1546
    self.needed_locks = {}
1547
    self.share_locks[locking.LEVEL_NODE] = 1
1548
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1549

    
1550
  def CheckPrereq(self):
1551
    """Check prerequisites.
1552

1553
    """
1554

    
1555
  @staticmethod
1556
  def _DiagnoseByOS(node_list, rlist):
1557
    """Remaps a per-node return list into an a per-os per-node dictionary
1558

1559
    @param node_list: a list with the names of all nodes
1560
    @param rlist: a map with node names as keys and OS objects as values
1561

1562
    @rtype: dict
1563
    @returns: a dictionary with osnames as keys and as value another map, with
1564
        nodes as keys and list of OS objects as values, eg::
1565

1566
          {"debian-etch": {"node1": [<object>,...],
1567
                           "node2": [<object>,]}
1568
          }
1569

1570
    """
1571
    all_os = {}
1572
    for node_name, nr in rlist.iteritems():
1573
      if nr.failed or not nr.data:
1574
        continue
1575
      for os_obj in nr.data:
1576
        if os_obj.name not in all_os:
1577
          # build a list of nodes for this os containing empty lists
1578
          # for each node in node_list
1579
          all_os[os_obj.name] = {}
1580
          for nname in node_list:
1581
            all_os[os_obj.name][nname] = []
1582
        all_os[os_obj.name][node_name].append(os_obj)
1583
    return all_os
1584

    
1585
  def Exec(self, feedback_fn):
1586
    """Compute the list of OSes.
1587

1588
    """
1589
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1590
    node_data = self.rpc.call_os_diagnose(node_list)
1591
    if node_data == False:
1592
      raise errors.OpExecError("Can't gather the list of OSes")
1593
    pol = self._DiagnoseByOS(node_list, node_data)
1594
    output = []
1595
    for os_name, os_data in pol.iteritems():
1596
      row = []
1597
      for field in self.op.output_fields:
1598
        if field == "name":
1599
          val = os_name
1600
        elif field == "valid":
1601
          val = utils.all([osl and osl[0] for osl in os_data.values()])
1602
        elif field == "node_status":
1603
          val = {}
1604
          for node_name, nos_list in os_data.iteritems():
1605
            val[node_name] = [(v.status, v.path) for v in nos_list]
1606
        else:
1607
          raise errors.ParameterError(field)
1608
        row.append(val)
1609
      output.append(row)
1610

    
1611
    return output
1612

    
1613

    
1614
class LURemoveNode(LogicalUnit):
1615
  """Logical unit for removing a node.
1616

1617
  """
1618
  HPATH = "node-remove"
1619
  HTYPE = constants.HTYPE_NODE
1620
  _OP_REQP = ["node_name"]
1621

    
1622
  def BuildHooksEnv(self):
1623
    """Build hooks env.
1624

1625
    This doesn't run on the target node in the pre phase as a failed
1626
    node would then be impossible to remove.
1627

1628
    """
1629
    env = {
1630
      "OP_TARGET": self.op.node_name,
1631
      "NODE_NAME": self.op.node_name,
1632
      }
1633
    all_nodes = self.cfg.GetNodeList()
1634
    all_nodes.remove(self.op.node_name)
1635
    return env, all_nodes, all_nodes
1636

    
1637
  def CheckPrereq(self):
1638
    """Check prerequisites.
1639

1640
    This checks:
1641
     - the node exists in the configuration
1642
     - it does not have primary or secondary instances
1643
     - it's not the master
1644

1645
    Any errors are signalled by raising errors.OpPrereqError.
1646

1647
    """
1648
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
1649
    if node is None:
1650
      raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name)
1651

    
1652
    instance_list = self.cfg.GetInstanceList()
1653

    
1654
    masternode = self.cfg.GetMasterNode()
1655
    if node.name == masternode:
1656
      raise errors.OpPrereqError("Node is the master node,"
1657
                                 " you need to failover first.")
1658

    
1659
    for instance_name in instance_list:
1660
      instance = self.cfg.GetInstanceInfo(instance_name)
1661
      if node.name == instance.primary_node:
1662
        raise errors.OpPrereqError("Instance %s still running on the node,"
1663
                                   " please remove first." % instance_name)
1664
      if node.name in instance.secondary_nodes:
1665
        raise errors.OpPrereqError("Instance %s has node as a secondary,"
1666
                                   " please remove first." % instance_name)
1667
    self.op.node_name = node.name
1668
    self.node = node
1669

    
1670
  def Exec(self, feedback_fn):
1671
    """Removes the node from the cluster.
1672

1673
    """
1674
    node = self.node
1675
    logging.info("Stopping the node daemon and removing configs from node %s",
1676
                 node.name)
1677

    
1678
    self.context.RemoveNode(node.name)
1679

    
1680
    self.rpc.call_node_leave_cluster(node.name)
1681

    
1682
    # Promote nodes to master candidate as needed
1683
    _AdjustCandidatePool(self)
1684

    
1685

    
1686
class LUQueryNodes(NoHooksLU):
1687
  """Logical unit for querying nodes.
1688

1689
  """
1690
  _OP_REQP = ["output_fields", "names"]
1691
  REQ_BGL = False
1692
  _FIELDS_DYNAMIC = utils.FieldSet(
1693
    "dtotal", "dfree",
1694
    "mtotal", "mnode", "mfree",
1695
    "bootid",
1696
    "ctotal",
1697
    )
1698

    
1699
  _FIELDS_STATIC = utils.FieldSet(
1700
    "name", "pinst_cnt", "sinst_cnt",
1701
    "pinst_list", "sinst_list",
1702
    "pip", "sip", "tags",
1703
    "serial_no",
1704
    "master_candidate",
1705
    "master",
1706
    "offline",
1707
    )
1708

    
1709
  def ExpandNames(self):
1710
    _CheckOutputFields(static=self._FIELDS_STATIC,
1711
                       dynamic=self._FIELDS_DYNAMIC,
1712
                       selected=self.op.output_fields)
1713

    
1714
    self.needed_locks = {}
1715
    self.share_locks[locking.LEVEL_NODE] = 1
1716

    
1717
    if self.op.names:
1718
      self.wanted = _GetWantedNodes(self, self.op.names)
1719
    else:
1720
      self.wanted = locking.ALL_SET
1721

    
1722
    self.do_locking = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
1723
    if self.do_locking:
1724
      # if we don't request only static fields, we need to lock the nodes
1725
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
1726

    
1727

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

1731
    """
1732
    # The validation of the node list is done in the _GetWantedNodes,
1733
    # if non empty, and if empty, there's no validation to do
1734
    pass
1735

    
1736
  def Exec(self, feedback_fn):
1737
    """Computes the list of nodes and their attributes.
1738

1739
    """
1740
    all_info = self.cfg.GetAllNodesInfo()
1741
    if self.do_locking:
1742
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
1743
    elif self.wanted != locking.ALL_SET:
1744
      nodenames = self.wanted
1745
      missing = set(nodenames).difference(all_info.keys())
1746
      if missing:
1747
        raise errors.OpExecError(
1748
          "Some nodes were removed before retrieving their data: %s" % missing)
1749
    else:
1750
      nodenames = all_info.keys()
1751

    
1752
    nodenames = utils.NiceSort(nodenames)
1753
    nodelist = [all_info[name] for name in nodenames]
1754

    
1755
    # begin data gathering
1756

    
1757
    if self.do_locking:
1758
      live_data = {}
1759
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
1760
                                          self.cfg.GetHypervisorType())
1761
      for name in nodenames:
1762
        nodeinfo = node_data[name]
1763
        if not nodeinfo.failed and nodeinfo.data:
1764
          nodeinfo = nodeinfo.data
1765
          fn = utils.TryConvert
1766
          live_data[name] = {
1767
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
1768
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
1769
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
1770
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
1771
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
1772
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
1773
            "bootid": nodeinfo.get('bootid', None),
1774
            }
1775
        else:
1776
          live_data[name] = {}
1777
    else:
1778
      live_data = dict.fromkeys(nodenames, {})
1779

    
1780
    node_to_primary = dict([(name, set()) for name in nodenames])
1781
    node_to_secondary = dict([(name, set()) for name in nodenames])
1782

    
1783
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
1784
                             "sinst_cnt", "sinst_list"))
1785
    if inst_fields & frozenset(self.op.output_fields):
1786
      instancelist = self.cfg.GetInstanceList()
1787

    
1788
      for instance_name in instancelist:
1789
        inst = self.cfg.GetInstanceInfo(instance_name)
1790
        if inst.primary_node in node_to_primary:
1791
          node_to_primary[inst.primary_node].add(inst.name)
1792
        for secnode in inst.secondary_nodes:
1793
          if secnode in node_to_secondary:
1794
            node_to_secondary[secnode].add(inst.name)
1795

    
1796
    master_node = self.cfg.GetMasterNode()
1797

    
1798
    # end data gathering
1799

    
1800
    output = []
1801
    for node in nodelist:
1802
      node_output = []
1803
      for field in self.op.output_fields:
1804
        if field == "name":
1805
          val = node.name
1806
        elif field == "pinst_list":
1807
          val = list(node_to_primary[node.name])
1808
        elif field == "sinst_list":
1809
          val = list(node_to_secondary[node.name])
1810
        elif field == "pinst_cnt":
1811
          val = len(node_to_primary[node.name])
1812
        elif field == "sinst_cnt":
1813
          val = len(node_to_secondary[node.name])
1814
        elif field == "pip":
1815
          val = node.primary_ip
1816
        elif field == "sip":
1817
          val = node.secondary_ip
1818
        elif field == "tags":
1819
          val = list(node.GetTags())
1820
        elif field == "serial_no":
1821
          val = node.serial_no
1822
        elif field == "master_candidate":
1823
          val = node.master_candidate
1824
        elif field == "master":
1825
          val = node.name == master_node
1826
        elif field == "offline":
1827
          val = node.offline
1828
        elif self._FIELDS_DYNAMIC.Matches(field):
1829
          val = live_data[node.name].get(field, None)
1830
        else:
1831
          raise errors.ParameterError(field)
1832
        node_output.append(val)
1833
      output.append(node_output)
1834

    
1835
    return output
1836

    
1837

    
1838
class LUQueryNodeVolumes(NoHooksLU):
1839
  """Logical unit for getting volumes on node(s).
1840

1841
  """
1842
  _OP_REQP = ["nodes", "output_fields"]
1843
  REQ_BGL = False
1844
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
1845
  _FIELDS_STATIC = utils.FieldSet("node")
1846

    
1847
  def ExpandNames(self):
1848
    _CheckOutputFields(static=self._FIELDS_STATIC,
1849
                       dynamic=self._FIELDS_DYNAMIC,
1850
                       selected=self.op.output_fields)
1851

    
1852
    self.needed_locks = {}
1853
    self.share_locks[locking.LEVEL_NODE] = 1
1854
    if not self.op.nodes:
1855
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1856
    else:
1857
      self.needed_locks[locking.LEVEL_NODE] = \
1858
        _GetWantedNodes(self, self.op.nodes)
1859

    
1860
  def CheckPrereq(self):
1861
    """Check prerequisites.
1862

1863
    This checks that the fields required are valid output fields.
1864

1865
    """
1866
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
1867

    
1868
  def Exec(self, feedback_fn):
1869
    """Computes the list of nodes and their attributes.
1870

1871
    """
1872
    nodenames = self.nodes
1873
    volumes = self.rpc.call_node_volumes(nodenames)
1874

    
1875
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
1876
             in self.cfg.GetInstanceList()]
1877

    
1878
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
1879

    
1880
    output = []
1881
    for node in nodenames:
1882
      if node not in volumes or volumes[node].failed or not volumes[node].data:
1883
        continue
1884

    
1885
      node_vols = volumes[node].data[:]
1886
      node_vols.sort(key=lambda vol: vol['dev'])
1887

    
1888
      for vol in node_vols:
1889
        node_output = []
1890
        for field in self.op.output_fields:
1891
          if field == "node":
1892
            val = node
1893
          elif field == "phys":
1894
            val = vol['dev']
1895
          elif field == "vg":
1896
            val = vol['vg']
1897
          elif field == "name":
1898
            val = vol['name']
1899
          elif field == "size":
1900
            val = int(float(vol['size']))
1901
          elif field == "instance":
1902
            for inst in ilist:
1903
              if node not in lv_by_node[inst]:
1904
                continue
1905
              if vol['name'] in lv_by_node[inst][node]:
1906
                val = inst.name
1907
                break
1908
            else:
1909
              val = '-'
1910
          else:
1911
            raise errors.ParameterError(field)
1912
          node_output.append(str(val))
1913

    
1914
        output.append(node_output)
1915

    
1916
    return output
1917

    
1918

    
1919
class LUAddNode(LogicalUnit):
1920
  """Logical unit for adding node to the cluster.
1921

1922
  """
1923
  HPATH = "node-add"
1924
  HTYPE = constants.HTYPE_NODE
1925
  _OP_REQP = ["node_name"]
1926

    
1927
  def BuildHooksEnv(self):
1928
    """Build hooks env.
1929

1930
    This will run on all nodes before, and on all nodes + the new node after.
1931

1932
    """
1933
    env = {
1934
      "OP_TARGET": self.op.node_name,
1935
      "NODE_NAME": self.op.node_name,
1936
      "NODE_PIP": self.op.primary_ip,
1937
      "NODE_SIP": self.op.secondary_ip,
1938
      }
1939
    nodes_0 = self.cfg.GetNodeList()
1940
    nodes_1 = nodes_0 + [self.op.node_name, ]
1941
    return env, nodes_0, nodes_1
1942

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

1946
    This checks:
1947
     - the new node is not already in the config
1948
     - it is resolvable
1949
     - its parameters (single/dual homed) matches the cluster
1950

1951
    Any errors are signalled by raising errors.OpPrereqError.
1952

1953
    """
1954
    node_name = self.op.node_name
1955
    cfg = self.cfg
1956

    
1957
    dns_data = utils.HostInfo(node_name)
1958

    
1959
    node = dns_data.name
1960
    primary_ip = self.op.primary_ip = dns_data.ip
1961
    secondary_ip = getattr(self.op, "secondary_ip", None)
1962
    if secondary_ip is None:
1963
      secondary_ip = primary_ip
1964
    if not utils.IsValidIP(secondary_ip):
1965
      raise errors.OpPrereqError("Invalid secondary IP given")
1966
    self.op.secondary_ip = secondary_ip
1967

    
1968
    node_list = cfg.GetNodeList()
1969
    if not self.op.readd and node in node_list:
1970
      raise errors.OpPrereqError("Node %s is already in the configuration" %
1971
                                 node)
1972
    elif self.op.readd and node not in node_list:
1973
      raise errors.OpPrereqError("Node %s is not in the configuration" % node)
1974

    
1975
    for existing_node_name in node_list:
1976
      existing_node = cfg.GetNodeInfo(existing_node_name)
1977

    
1978
      if self.op.readd and node == existing_node_name:
1979
        if (existing_node.primary_ip != primary_ip or
1980
            existing_node.secondary_ip != secondary_ip):
1981
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
1982
                                     " address configuration as before")
1983
        continue
1984

    
1985
      if (existing_node.primary_ip == primary_ip or
1986
          existing_node.secondary_ip == primary_ip or
1987
          existing_node.primary_ip == secondary_ip or
1988
          existing_node.secondary_ip == secondary_ip):
1989
        raise errors.OpPrereqError("New node ip address(es) conflict with"
1990
                                   " existing node %s" % existing_node.name)
1991

    
1992
    # check that the type of the node (single versus dual homed) is the
1993
    # same as for the master
1994
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
1995
    master_singlehomed = myself.secondary_ip == myself.primary_ip
1996
    newbie_singlehomed = secondary_ip == primary_ip
1997
    if master_singlehomed != newbie_singlehomed:
1998
      if master_singlehomed:
1999
        raise errors.OpPrereqError("The master has no private ip but the"
2000
                                   " new node has one")
2001
      else:
2002
        raise errors.OpPrereqError("The master has a private ip but the"
2003
                                   " new node doesn't have one")
2004

    
2005
    # checks reachablity
2006
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
2007
      raise errors.OpPrereqError("Node not reachable by ping")
2008

    
2009
    if not newbie_singlehomed:
2010
      # check reachability from my secondary ip to newbie's secondary ip
2011
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
2012
                           source=myself.secondary_ip):
2013
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
2014
                                   " based ping to noded port")
2015

    
2016
    cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2017
    mc_now, _ = self.cfg.GetMasterCandidateStats()
2018
    master_candidate = mc_now < cp_size
2019

    
2020
    self.new_node = objects.Node(name=node,
2021
                                 primary_ip=primary_ip,
2022
                                 secondary_ip=secondary_ip,
2023
                                 master_candidate=master_candidate,
2024
                                 offline=False)
2025

    
2026
  def Exec(self, feedback_fn):
2027
    """Adds the new node to the cluster.
2028

2029
    """
2030
    new_node = self.new_node
2031
    node = new_node.name
2032

    
2033
    # check connectivity
2034
    result = self.rpc.call_version([node])[node]
2035
    result.Raise()
2036
    if result.data:
2037
      if constants.PROTOCOL_VERSION == result.data:
2038
        logging.info("Communication to node %s fine, sw version %s match",
2039
                     node, result.data)
2040
      else:
2041
        raise errors.OpExecError("Version mismatch master version %s,"
2042
                                 " node version %s" %
2043
                                 (constants.PROTOCOL_VERSION, result.data))
2044
    else:
2045
      raise errors.OpExecError("Cannot get version from the new node")
2046

    
2047
    # setup ssh on node
2048
    logging.info("Copy ssh key to node %s", node)
2049
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
2050
    keyarray = []
2051
    keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
2052
                constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
2053
                priv_key, pub_key]
2054

    
2055
    for i in keyfiles:
2056
      f = open(i, 'r')
2057
      try:
2058
        keyarray.append(f.read())
2059
      finally:
2060
        f.close()
2061

    
2062
    result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
2063
                                    keyarray[2],
2064
                                    keyarray[3], keyarray[4], keyarray[5])
2065

    
2066
    if result.failed or not result.data:
2067
      raise errors.OpExecError("Cannot transfer ssh keys to the new node")
2068

    
2069
    # Add node to our /etc/hosts, and add key to known_hosts
2070
    utils.AddHostToEtcHosts(new_node.name)
2071

    
2072
    if new_node.secondary_ip != new_node.primary_ip:
2073
      result = self.rpc.call_node_has_ip_address(new_node.name,
2074
                                                 new_node.secondary_ip)
2075
      if result.failed or not result.data:
2076
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
2077
                                 " you gave (%s). Please fix and re-run this"
2078
                                 " command." % new_node.secondary_ip)
2079

    
2080
    node_verify_list = [self.cfg.GetMasterNode()]
2081
    node_verify_param = {
2082
      'nodelist': [node],
2083
      # TODO: do a node-net-test as well?
2084
    }
2085

    
2086
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
2087
                                       self.cfg.GetClusterName())
2088
    for verifier in node_verify_list:
2089
      if result[verifier].failed or not result[verifier].data:
2090
        raise errors.OpExecError("Cannot communicate with %s's node daemon"
2091
                                 " for remote verification" % verifier)
2092
      if result[verifier].data['nodelist']:
2093
        for failed in result[verifier].data['nodelist']:
2094
          feedback_fn("ssh/hostname verification failed %s -> %s" %
2095
                      (verifier, result[verifier]['nodelist'][failed]))
2096
        raise errors.OpExecError("ssh/hostname verification failed.")
2097

    
2098
    # Distribute updated /etc/hosts and known_hosts to all nodes,
2099
    # including the node just added
2100
    myself = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
2101
    dist_nodes = self.cfg.GetNodeList()
2102
    if not self.op.readd:
2103
      dist_nodes.append(node)
2104
    if myself.name in dist_nodes:
2105
      dist_nodes.remove(myself.name)
2106

    
2107
    logging.debug("Copying hosts and known_hosts to all nodes")
2108
    for fname in (constants.ETC_HOSTS, constants.SSH_KNOWN_HOSTS_FILE):
2109
      result = self.rpc.call_upload_file(dist_nodes, fname)
2110
      for to_node, to_result in result.iteritems():
2111
        if to_result.failed or not to_result.data:
2112
          logging.error("Copy of file %s to node %s failed", fname, to_node)
2113

    
2114
    to_copy = []
2115
    if constants.HT_XEN_HVM in self.cfg.GetClusterInfo().enabled_hypervisors:
2116
      to_copy.append(constants.VNC_PASSWORD_FILE)
2117
    for fname in to_copy:
2118
      result = self.rpc.call_upload_file([node], fname)
2119
      if result[node].failed or not result[node]:
2120
        logging.error("Could not copy file %s to node %s", fname, node)
2121

    
2122
    if self.op.readd:
2123
      self.context.ReaddNode(new_node)
2124
    else:
2125
      self.context.AddNode(new_node)
2126

    
2127

    
2128
class LUSetNodeParams(LogicalUnit):
2129
  """Modifies the parameters of a node.
2130

2131
  """
2132
  HPATH = "node-modify"
2133
  HTYPE = constants.HTYPE_NODE
2134
  _OP_REQP = ["node_name"]
2135
  REQ_BGL = False
2136

    
2137
  def CheckArguments(self):
2138
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2139
    if node_name is None:
2140
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
2141
    self.op.node_name = node_name
2142
    _CheckBooleanOpField(self.op, 'master_candidate')
2143
    _CheckBooleanOpField(self.op, 'offline')
2144
    if self.op.master_candidate is None and self.op.offline is None:
2145
      raise errors.OpPrereqError("Please pass at least one modification")
2146
    if self.op.offline == True and self.op.master_candidate == True:
2147
      raise errors.OpPrereqError("Can't set the node into offline and"
2148
                                 " master_candidate at the same time")
2149

    
2150
  def ExpandNames(self):
2151
    self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
2152

    
2153
  def BuildHooksEnv(self):
2154
    """Build hooks env.
2155

2156
    This runs on the master node.
2157

2158
    """
2159
    env = {
2160
      "OP_TARGET": self.op.node_name,
2161
      "MASTER_CANDIDATE": str(self.op.master_candidate),
2162
      "OFFLINE": str(self.op.offline),
2163
      }
2164
    nl = [self.cfg.GetMasterNode(),
2165
          self.op.node_name]
2166
    return env, nl, nl
2167

    
2168
  def CheckPrereq(self):
2169
    """Check prerequisites.
2170

2171
    This only checks the instance list against the existing names.
2172

2173
    """
2174
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
2175

    
2176
    if ((self.op.master_candidate == False or self.op.offline == True)
2177
        and node.master_candidate):
2178
      # we will demote the node from master_candidate
2179
      if self.op.node_name == self.cfg.GetMasterNode():
2180
        raise errors.OpPrereqError("The master node has to be a"
2181
                                   " master candidate and online")
2182
      cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2183
      num_candidates, _ = self.cfg.GetMasterCandidateStats()
2184
      if num_candidates <= cp_size:
2185
        msg = ("Not enough master candidates (desired"
2186
               " %d, new value will be %d)" % (cp_size, num_candidates-1))
2187
        if self.op.force:
2188
          self.LogWarning(msg)
2189
        else:
2190
          raise errors.OpPrereqError(msg)
2191

    
2192
    if (self.op.master_candidate == True and node.offline and
2193
        not self.op.offline == False):
2194
      raise errors.OpPrereqError("Can't set an offline node to"
2195
                                 " master_candidate")
2196

    
2197
    return
2198

    
2199
  def Exec(self, feedback_fn):
2200
    """Modifies a node.
2201

2202
    """
2203
    node = self.node
2204

    
2205
    result = []
2206

    
2207
    if self.op.offline is not None:
2208
      node.offline = self.op.offline
2209
      result.append(("offline", str(self.op.offline)))
2210
      if self.op.offline == True and node.master_candidate:
2211
        node.master_candidate = False
2212
        result.append(("master_candidate", "auto-demotion due to offline"))
2213

    
2214
    if self.op.master_candidate is not None:
2215
      node.master_candidate = self.op.master_candidate
2216
      result.append(("master_candidate", str(self.op.master_candidate)))
2217
      if self.op.master_candidate == False:
2218
        rrc = self.rpc.call_node_demote_from_mc(node.name)
2219
        if (rrc.failed or not isinstance(rrc.data, (tuple, list))
2220
            or len(rrc.data) != 2):
2221
          self.LogWarning("Node rpc error: %s" % rrc.error)
2222
        elif not rrc.data[0]:
2223
          self.LogWarning("Node failed to demote itself: %s" % rrc.data[1])
2224

    
2225
    # this will trigger configuration file update, if needed
2226
    self.cfg.Update(node)
2227
    # this will trigger job queue propagation or cleanup
2228
    if self.op.node_name != self.cfg.GetMasterNode():
2229
      self.context.ReaddNode(node)
2230

    
2231
    return result
2232

    
2233

    
2234
class LUQueryClusterInfo(NoHooksLU):
2235
  """Query cluster configuration.
2236

2237
  """
2238
  _OP_REQP = []
2239
  REQ_BGL = False
2240

    
2241
  def ExpandNames(self):
2242
    self.needed_locks = {}
2243

    
2244
  def CheckPrereq(self):
2245
    """No prerequsites needed for this LU.
2246

2247
    """
2248
    pass
2249

    
2250
  def Exec(self, feedback_fn):
2251
    """Return cluster config.
2252

2253
    """
2254
    cluster = self.cfg.GetClusterInfo()
2255
    result = {
2256
      "software_version": constants.RELEASE_VERSION,
2257
      "protocol_version": constants.PROTOCOL_VERSION,
2258
      "config_version": constants.CONFIG_VERSION,
2259
      "os_api_version": constants.OS_API_VERSION,
2260
      "export_version": constants.EXPORT_VERSION,
2261
      "architecture": (platform.architecture()[0], platform.machine()),
2262
      "name": cluster.cluster_name,
2263
      "master": cluster.master_node,
2264
      "default_hypervisor": cluster.default_hypervisor,
2265
      "enabled_hypervisors": cluster.enabled_hypervisors,
2266
      "hvparams": cluster.hvparams,
2267
      "beparams": cluster.beparams,
2268
      "candidate_pool_size": cluster.candidate_pool_size,
2269
      }
2270

    
2271
    return result
2272

    
2273

    
2274
class LUQueryConfigValues(NoHooksLU):
2275
  """Return configuration values.
2276

2277
  """
2278
  _OP_REQP = []
2279
  REQ_BGL = False
2280
  _FIELDS_DYNAMIC = utils.FieldSet()
2281
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag")
2282

    
2283
  def ExpandNames(self):
2284
    self.needed_locks = {}
2285

    
2286
    _CheckOutputFields(static=self._FIELDS_STATIC,
2287
                       dynamic=self._FIELDS_DYNAMIC,
2288
                       selected=self.op.output_fields)
2289

    
2290
  def CheckPrereq(self):
2291
    """No prerequisites.
2292

2293
    """
2294
    pass
2295

    
2296
  def Exec(self, feedback_fn):
2297
    """Dump a representation of the cluster config to the standard output.
2298

2299
    """
2300
    values = []
2301
    for field in self.op.output_fields:
2302
      if field == "cluster_name":
2303
        entry = self.cfg.GetClusterName()
2304
      elif field == "master_node":
2305
        entry = self.cfg.GetMasterNode()
2306
      elif field == "drain_flag":
2307
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
2308
      else:
2309
        raise errors.ParameterError(field)
2310
      values.append(entry)
2311
    return values
2312

    
2313

    
2314
class LUActivateInstanceDisks(NoHooksLU):
2315
  """Bring up an instance's disks.
2316

2317
  """
2318
  _OP_REQP = ["instance_name"]
2319
  REQ_BGL = False
2320

    
2321
  def ExpandNames(self):
2322
    self._ExpandAndLockInstance()
2323
    self.needed_locks[locking.LEVEL_NODE] = []
2324
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2325

    
2326
  def DeclareLocks(self, level):
2327
    if level == locking.LEVEL_NODE:
2328
      self._LockInstancesNodes()
2329

    
2330
  def CheckPrereq(self):
2331
    """Check prerequisites.
2332

2333
    This checks that the instance is in the cluster.
2334

2335
    """
2336
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2337
    assert self.instance is not None, \
2338
      "Cannot retrieve locked instance %s" % self.op.instance_name
2339
    _CheckNodeOnline(self, self.instance.primary_node)
2340

    
2341
  def Exec(self, feedback_fn):
2342
    """Activate the disks.
2343

2344
    """
2345
    disks_ok, disks_info = _AssembleInstanceDisks(self, self.instance)
2346
    if not disks_ok:
2347
      raise errors.OpExecError("Cannot activate block devices")
2348

    
2349
    return disks_info
2350

    
2351

    
2352
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False):
2353
  """Prepare the block devices for an instance.
2354

2355
  This sets up the block devices on all nodes.
2356

2357
  @type lu: L{LogicalUnit}
2358
  @param lu: the logical unit on whose behalf we execute
2359
  @type instance: L{objects.Instance}
2360
  @param instance: the instance for whose disks we assemble
2361
  @type ignore_secondaries: boolean
2362
  @param ignore_secondaries: if true, errors on secondary nodes
2363
      won't result in an error return from the function
2364
  @return: False if the operation failed, otherwise a list of
2365
      (host, instance_visible_name, node_visible_name)
2366
      with the mapping from node devices to instance devices
2367

2368
  """
2369
  device_info = []
2370
  disks_ok = True
2371
  iname = instance.name
2372
  # With the two passes mechanism we try to reduce the window of
2373
  # opportunity for the race condition of switching DRBD to primary
2374
  # before handshaking occured, but we do not eliminate it
2375

    
2376
  # The proper fix would be to wait (with some limits) until the
2377
  # connection has been made and drbd transitions from WFConnection
2378
  # into any other network-connected state (Connected, SyncTarget,
2379
  # SyncSource, etc.)
2380

    
2381
  # 1st pass, assemble on all nodes in secondary mode
2382
  for inst_disk in instance.disks:
2383
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2384
      lu.cfg.SetDiskID(node_disk, node)
2385
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
2386
      if result.failed or not result:
2387
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2388
                           " (is_primary=False, pass=1)",
2389
                           inst_disk.iv_name, node)
2390
        if not ignore_secondaries:
2391
          disks_ok = False
2392

    
2393
  # FIXME: race condition on drbd migration to primary
2394

    
2395
  # 2nd pass, do only the primary node
2396
  for inst_disk in instance.disks:
2397
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2398
      if node != instance.primary_node:
2399
        continue
2400
      lu.cfg.SetDiskID(node_disk, node)
2401
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
2402
      if result.failed or not result:
2403
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2404
                           " (is_primary=True, pass=2)",
2405
                           inst_disk.iv_name, node)
2406
        disks_ok = False
2407
    device_info.append((instance.primary_node, inst_disk.iv_name, result.data))
2408

    
2409
  # leave the disks configured for the primary node
2410
  # this is a workaround that would be fixed better by
2411
  # improving the logical/physical id handling
2412
  for disk in instance.disks:
2413
    lu.cfg.SetDiskID(disk, instance.primary_node)
2414

    
2415
  return disks_ok, device_info
2416

    
2417

    
2418
def _StartInstanceDisks(lu, instance, force):
2419
  """Start the disks of an instance.
2420

2421
  """
2422
  disks_ok, dummy = _AssembleInstanceDisks(lu, instance,
2423
                                           ignore_secondaries=force)
2424
  if not disks_ok:
2425
    _ShutdownInstanceDisks(lu, instance)
2426
    if force is not None and not force:
2427
      lu.proc.LogWarning("", hint="If the message above refers to a"
2428
                         " secondary node,"
2429
                         " you can retry the operation using '--force'.")
2430
    raise errors.OpExecError("Disk consistency error")
2431

    
2432

    
2433
class LUDeactivateInstanceDisks(NoHooksLU):
2434
  """Shutdown an instance's disks.
2435

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

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

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

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

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

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

    
2459
  def Exec(self, feedback_fn):
2460
    """Deactivate the disks
2461

2462
    """
2463
    instance = self.instance
2464
    _SafeShutdownInstanceDisks(self, instance)
2465

    
2466

    
2467
def _SafeShutdownInstanceDisks(lu, instance):
2468
  """Shutdown block devices of an instance.
2469

2470
  This function checks if an instance is running, before calling
2471
  _ShutdownInstanceDisks.
2472

2473
  """
2474
  ins_l = lu.rpc.call_instance_list([instance.primary_node],
2475
                                      [instance.hypervisor])
2476
  ins_l = ins_l[instance.primary_node]
2477
  if ins_l.failed or not isinstance(ins_l.data, list):
2478
    raise errors.OpExecError("Can't contact node '%s'" %
2479
                             instance.primary_node)
2480

    
2481
  if instance.name in ins_l.data:
2482
    raise errors.OpExecError("Instance is running, can't shutdown"
2483
                             " block devices.")
2484

    
2485
  _ShutdownInstanceDisks(lu, instance)
2486

    
2487

    
2488
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
2489
  """Shutdown block devices of an instance.
2490

2491
  This does the shutdown on all nodes of the instance.
2492

2493
  If the ignore_primary is false, errors on the primary node are
2494
  ignored.
2495

2496
  """
2497
  result = True
2498
  for disk in instance.disks:
2499
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
2500
      lu.cfg.SetDiskID(top_disk, node)
2501
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
2502
      if result.failed or not result.data:
2503
        logging.error("Could not shutdown block device %s on node %s",
2504
                      disk.iv_name, node)
2505
        if not ignore_primary or node != instance.primary_node:
2506
          result = False
2507
  return result
2508

    
2509

    
2510
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
2511
  """Checks if a node has enough free memory.
2512

2513
  This function check if a given node has the needed amount of free
2514
  memory. In case the node has less memory or we cannot get the
2515
  information from the node, this function raise an OpPrereqError
2516
  exception.
2517

2518
  @type lu: C{LogicalUnit}
2519
  @param lu: a logical unit from which we get configuration data
2520
  @type node: C{str}
2521
  @param node: the node to check
2522
  @type reason: C{str}
2523
  @param reason: string to use in the error message
2524
  @type requested: C{int}
2525
  @param requested: the amount of memory in MiB to check for
2526
  @type hypervisor_name: C{str}
2527
  @param hypervisor_name: the hypervisor to ask for memory stats
2528
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
2529
      we cannot check the node
2530

2531
  """
2532
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
2533
  nodeinfo[node].Raise()
2534
  free_mem = nodeinfo[node].data.get('memory_free')
2535
  if not isinstance(free_mem, int):
2536
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
2537
                             " was '%s'" % (node, free_mem))
2538
  if requested > free_mem:
2539
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
2540
                             " needed %s MiB, available %s MiB" %
2541
                             (node, reason, requested, free_mem))
2542

    
2543

    
2544
class LUStartupInstance(LogicalUnit):
2545
  """Starts an instance.
2546

2547
  """
2548
  HPATH = "instance-start"
2549
  HTYPE = constants.HTYPE_INSTANCE
2550
  _OP_REQP = ["instance_name", "force"]
2551
  REQ_BGL = False
2552

    
2553
  def ExpandNames(self):
2554
    self._ExpandAndLockInstance()
2555

    
2556
  def BuildHooksEnv(self):
2557
    """Build hooks env.
2558

2559
    This runs on master, primary and secondary nodes of the instance.
2560

2561
    """
2562
    env = {
2563
      "FORCE": self.op.force,
2564
      }
2565
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2566
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2567
          list(self.instance.secondary_nodes))
2568
    return env, nl, nl
2569

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

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

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

    
2580
    _CheckNodeOnline(self, instance.primary_node)
2581

    
2582
    bep = self.cfg.GetClusterInfo().FillBE(instance)
2583
    # check bridges existance
2584
    _CheckInstanceBridgesExist(self, instance)
2585

    
2586
    _CheckNodeFreeMemory(self, instance.primary_node,
2587
                         "starting instance %s" % instance.name,
2588
                         bep[constants.BE_MEMORY], instance.hypervisor)
2589

    
2590
  def Exec(self, feedback_fn):
2591
    """Start the instance.
2592

2593
    """
2594
    instance = self.instance
2595
    force = self.op.force
2596
    extra_args = getattr(self.op, "extra_args", "")
2597

    
2598
    self.cfg.MarkInstanceUp(instance.name)
2599

    
2600
    node_current = instance.primary_node
2601

    
2602
    _StartInstanceDisks(self, instance, force)
2603

    
2604
    result = self.rpc.call_instance_start(node_current, instance, extra_args)
2605
    if result.failed or not result.data:
2606
      _ShutdownInstanceDisks(self, instance)
2607
      raise errors.OpExecError("Could not start instance")
2608

    
2609

    
2610
class LURebootInstance(LogicalUnit):
2611
  """Reboot an instance.
2612

2613
  """
2614
  HPATH = "instance-reboot"
2615
  HTYPE = constants.HTYPE_INSTANCE
2616
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
2617
  REQ_BGL = False
2618

    
2619
  def ExpandNames(self):
2620
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
2621
                                   constants.INSTANCE_REBOOT_HARD,
2622
                                   constants.INSTANCE_REBOOT_FULL]:
2623
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
2624
                                  (constants.INSTANCE_REBOOT_SOFT,
2625
                                   constants.INSTANCE_REBOOT_HARD,
2626
                                   constants.INSTANCE_REBOOT_FULL))
2627
    self._ExpandAndLockInstance()
2628

    
2629
  def BuildHooksEnv(self):
2630
    """Build hooks env.
2631

2632
    This runs on master, primary and secondary nodes of the instance.
2633

2634
    """
2635
    env = {
2636
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
2637
      }
2638
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2639
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2640
          list(self.instance.secondary_nodes))
2641
    return env, nl, nl
2642

    
2643
  def CheckPrereq(self):
2644
    """Check prerequisites.
2645

2646
    This checks that the instance is in the cluster.
2647

2648
    """
2649
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2650
    assert self.instance is not None, \
2651
      "Cannot retrieve locked instance %s" % self.op.instance_name
2652

    
2653
    _CheckNodeOnline(self, instance.primary_node)
2654

    
2655
    # check bridges existance
2656
    _CheckInstanceBridgesExist(self, instance)
2657

    
2658
  def Exec(self, feedback_fn):
2659
    """Reboot the instance.
2660

2661
    """
2662
    instance = self.instance
2663
    ignore_secondaries = self.op.ignore_secondaries
2664
    reboot_type = self.op.reboot_type
2665
    extra_args = getattr(self.op, "extra_args", "")
2666

    
2667
    node_current = instance.primary_node
2668

    
2669
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
2670
                       constants.INSTANCE_REBOOT_HARD]:
2671
      result = self.rpc.call_instance_reboot(node_current, instance,
2672
                                             reboot_type, extra_args)
2673
      if result.failed or not result.data:
2674
        raise errors.OpExecError("Could not reboot instance")
2675
    else:
2676
      if not self.rpc.call_instance_shutdown(node_current, instance):
2677
        raise errors.OpExecError("could not shutdown instance for full reboot")
2678
      _ShutdownInstanceDisks(self, instance)
2679
      _StartInstanceDisks(self, instance, ignore_secondaries)
2680
      result = self.rpc.call_instance_start(node_current, instance, extra_args)
2681
      if result.failed or not result.data:
2682
        _ShutdownInstanceDisks(self, instance)
2683
        raise errors.OpExecError("Could not start instance for full reboot")
2684

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

    
2687

    
2688
class LUShutdownInstance(LogicalUnit):
2689
  """Shutdown an instance.
2690

2691
  """
2692
  HPATH = "instance-stop"
2693
  HTYPE = constants.HTYPE_INSTANCE
2694
  _OP_REQP = ["instance_name"]
2695
  REQ_BGL = False
2696

    
2697
  def ExpandNames(self):
2698
    self._ExpandAndLockInstance()
2699

    
2700
  def BuildHooksEnv(self):
2701
    """Build hooks env.
2702

2703
    This runs on master, primary and secondary nodes of the instance.
2704

2705
    """
2706
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2707
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2708
          list(self.instance.secondary_nodes))
2709
    return env, nl, nl
2710

    
2711
  def CheckPrereq(self):
2712
    """Check prerequisites.
2713

2714
    This checks that the instance is in the cluster.
2715

2716
    """
2717
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2718
    assert self.instance is not None, \
2719
      "Cannot retrieve locked instance %s" % self.op.instance_name
2720
    _CheckNodeOnline(self, self.instance.primary_node)
2721

    
2722
  def Exec(self, feedback_fn):
2723
    """Shutdown the instance.
2724

2725
    """
2726
    instance = self.instance
2727
    node_current = instance.primary_node
2728
    self.cfg.MarkInstanceDown(instance.name)
2729
    result = self.rpc.call_instance_shutdown(node_current, instance)
2730
    if result.failed or not result.data:
2731
      self.proc.LogWarning("Could not shutdown instance")
2732

    
2733
    _ShutdownInstanceDisks(self, instance)
2734

    
2735

    
2736
class LUReinstallInstance(LogicalUnit):
2737
  """Reinstall an instance.
2738

2739
  """
2740
  HPATH = "instance-reinstall"
2741
  HTYPE = constants.HTYPE_INSTANCE
2742
  _OP_REQP = ["instance_name"]
2743
  REQ_BGL = False
2744

    
2745
  def ExpandNames(self):
2746
    self._ExpandAndLockInstance()
2747

    
2748
  def BuildHooksEnv(self):
2749
    """Build hooks env.
2750

2751
    This runs on master, primary and secondary nodes of the instance.
2752

2753
    """
2754
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2755
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2756
          list(self.instance.secondary_nodes))
2757
    return env, nl, nl
2758

    
2759
  def CheckPrereq(self):
2760
    """Check prerequisites.
2761

2762
    This checks that the instance is in the cluster and is not running.
2763

2764
    """
2765
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2766
    assert instance is not None, \
2767
      "Cannot retrieve locked instance %s" % self.op.instance_name
2768
    _CheckNodeOnline(self, instance.primary_node)
2769

    
2770
    if instance.disk_template == constants.DT_DISKLESS:
2771
      raise errors.OpPrereqError("Instance '%s' has no disks" %
2772
                                 self.op.instance_name)
2773
    if instance.status != "down":
2774
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2775
                                 self.op.instance_name)
2776
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2777
                                              instance.name,
2778
                                              instance.hypervisor)
2779
    if remote_info.failed or remote_info.data:
2780
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2781
                                 (self.op.instance_name,
2782
                                  instance.primary_node))
2783

    
2784
    self.op.os_type = getattr(self.op, "os_type", None)
2785
    if self.op.os_type is not None:
2786
      # OS verification
2787
      pnode = self.cfg.GetNodeInfo(
2788
        self.cfg.ExpandNodeName(instance.primary_node))
2789
      if pnode is None:
2790
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
2791
                                   self.op.pnode)
2792
      result = self.rpc.call_os_get(pnode.name, self.op.os_type)
2793
      result.Raise()
2794
      if not isinstance(result.data, objects.OS):
2795
        raise errors.OpPrereqError("OS '%s' not in supported OS list for"
2796
                                   " primary node"  % self.op.os_type)
2797

    
2798
    self.instance = instance
2799

    
2800
  def Exec(self, feedback_fn):
2801
    """Reinstall the instance.
2802

2803
    """
2804
    inst = self.instance
2805

    
2806
    if self.op.os_type is not None:
2807
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
2808
      inst.os = self.op.os_type
2809
      self.cfg.Update(inst)
2810

    
2811
    _StartInstanceDisks(self, inst, None)
2812
    try:
2813
      feedback_fn("Running the instance OS create scripts...")
2814
      result = self.rpc.call_instance_os_add(inst.primary_node, inst)
2815
      result.Raise()
2816
      if not result.data:
2817
        raise errors.OpExecError("Could not install OS for instance %s"
2818
                                 " on node %s" %
2819
                                 (inst.name, inst.primary_node))
2820
    finally:
2821
      _ShutdownInstanceDisks(self, inst)
2822

    
2823

    
2824
class LURenameInstance(LogicalUnit):
2825
  """Rename an instance.
2826

2827
  """
2828
  HPATH = "instance-rename"
2829
  HTYPE = constants.HTYPE_INSTANCE
2830
  _OP_REQP = ["instance_name", "new_name"]
2831

    
2832
  def BuildHooksEnv(self):
2833
    """Build hooks env.
2834

2835
    This runs on master, primary and secondary nodes of the instance.
2836

2837
    """
2838
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2839
    env["INSTANCE_NEW_NAME"] = self.op.new_name
2840
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2841
          list(self.instance.secondary_nodes))
2842
    return env, nl, nl
2843

    
2844
  def CheckPrereq(self):
2845
    """Check prerequisites.
2846

2847
    This checks that the instance is in the cluster and is not running.
2848

2849
    """
2850
    instance = self.cfg.GetInstanceInfo(
2851
      self.cfg.ExpandInstanceName(self.op.instance_name))
2852
    if instance is None:
2853
      raise errors.OpPrereqError("Instance '%s' not known" %
2854
                                 self.op.instance_name)
2855
    _CheckNodeOnline(self, instance.primary_node)
2856

    
2857
    if instance.status != "down":
2858
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2859
                                 self.op.instance_name)
2860
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2861
                                              instance.name,
2862
                                              instance.hypervisor)
2863
    remote_info.Raise()
2864
    if remote_info.data:
2865
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2866
                                 (self.op.instance_name,
2867
                                  instance.primary_node))
2868
    self.instance = instance
2869

    
2870
    # new name verification
2871
    name_info = utils.HostInfo(self.op.new_name)
2872

    
2873
    self.op.new_name = new_name = name_info.name
2874
    instance_list = self.cfg.GetInstanceList()
2875
    if new_name in instance_list:
2876
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
2877
                                 new_name)
2878

    
2879
    if not getattr(self.op, "ignore_ip", False):
2880
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
2881
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
2882
                                   (name_info.ip, new_name))
2883

    
2884

    
2885
  def Exec(self, feedback_fn):
2886
    """Reinstall the instance.
2887

2888
    """
2889
    inst = self.instance
2890
    old_name = inst.name
2891

    
2892
    if inst.disk_template == constants.DT_FILE:
2893
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2894

    
2895
    self.cfg.RenameInstance(inst.name, self.op.new_name)
2896
    # Change the instance lock. This is definitely safe while we hold the BGL
2897
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
2898
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
2899

    
2900
    # re-read the instance from the configuration after rename
2901
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
2902

    
2903
    if inst.disk_template == constants.DT_FILE:
2904
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2905
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
2906
                                                     old_file_storage_dir,
2907
                                                     new_file_storage_dir)
2908
      result.Raise()
2909
      if not result.data:
2910
        raise errors.OpExecError("Could not connect to node '%s' to rename"
2911
                                 " directory '%s' to '%s' (but the instance"
2912
                                 " has been renamed in Ganeti)" % (
2913
                                 inst.primary_node, old_file_storage_dir,
2914
                                 new_file_storage_dir))
2915

    
2916
      if not result.data[0]:
2917
        raise errors.OpExecError("Could not rename directory '%s' to '%s'"
2918
                                 " (but the instance has been renamed in"
2919
                                 " Ganeti)" % (old_file_storage_dir,
2920
                                               new_file_storage_dir))
2921

    
2922
    _StartInstanceDisks(self, inst, None)
2923
    try:
2924
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
2925
                                                 old_name)
2926
      if result.failed or not result.data:
2927
        msg = ("Could not run OS rename script for instance %s on node %s"
2928
               " (but the instance has been renamed in Ganeti)" %
2929
               (inst.name, inst.primary_node))
2930
        self.proc.LogWarning(msg)
2931
    finally:
2932
      _ShutdownInstanceDisks(self, inst)
2933

    
2934

    
2935
class LURemoveInstance(LogicalUnit):
2936
  """Remove an instance.
2937

2938
  """
2939
  HPATH = "instance-remove"
2940
  HTYPE = constants.HTYPE_INSTANCE
2941
  _OP_REQP = ["instance_name", "ignore_failures"]
2942
  REQ_BGL = False
2943

    
2944
  def ExpandNames(self):
2945
    self._ExpandAndLockInstance()
2946
    self.needed_locks[locking.LEVEL_NODE] = []
2947
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2948

    
2949
  def DeclareLocks(self, level):
2950
    if level == locking.LEVEL_NODE:
2951
      self._LockInstancesNodes()
2952

    
2953
  def BuildHooksEnv(self):
2954
    """Build hooks env.
2955

2956
    This runs on master, primary and secondary nodes of the instance.
2957

2958
    """
2959
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2960
    nl = [self.cfg.GetMasterNode()]
2961
    return env, nl, nl
2962

    
2963
  def CheckPrereq(self):
2964
    """Check prerequisites.
2965

2966
    This checks that the instance is in the cluster.
2967

2968
    """
2969
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2970
    assert self.instance is not None, \
2971
      "Cannot retrieve locked instance %s" % self.op.instance_name
2972

    
2973
  def Exec(self, feedback_fn):
2974
    """Remove the instance.
2975

2976
    """
2977
    instance = self.instance
2978
    logging.info("Shutting down instance %s on node %s",
2979
                 instance.name, instance.primary_node)
2980

    
2981
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance)
2982
    if result.failed or not result.data:
2983
      if self.op.ignore_failures:
2984
        feedback_fn("Warning: can't shutdown instance")
2985
      else:
2986
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
2987
                                 (instance.name, instance.primary_node))
2988

    
2989
    logging.info("Removing block devices for instance %s", instance.name)
2990

    
2991
    if not _RemoveDisks(self, instance):
2992
      if self.op.ignore_failures:
2993
        feedback_fn("Warning: can't remove instance's disks")
2994
      else:
2995
        raise errors.OpExecError("Can't remove instance's disks")
2996

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

    
2999
    self.cfg.RemoveInstance(instance.name)
3000
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
3001

    
3002

    
3003
class LUQueryInstances(NoHooksLU):
3004
  """Logical unit for querying instances.
3005

3006
  """
3007
  _OP_REQP = ["output_fields", "names"]
3008
  REQ_BGL = False
3009
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
3010
                                    "admin_state", "admin_ram",
3011
                                    "disk_template", "ip", "mac", "bridge",
3012
                                    "sda_size", "sdb_size", "vcpus", "tags",
3013
                                    "network_port", "beparams",
3014
                                    "(disk).(size)/([0-9]+)",
3015
                                    "(disk).(sizes)",
3016
                                    "(nic).(mac|ip|bridge)/([0-9]+)",
3017
                                    "(nic).(macs|ips|bridges)",
3018
                                    "(disk|nic).(count)",
3019
                                    "serial_no", "hypervisor", "hvparams",] +
3020
                                  ["hv/%s" % name
3021
                                   for name in constants.HVS_PARAMETERS] +
3022
                                  ["be/%s" % name
3023
                                   for name in constants.BES_PARAMETERS])
3024
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
3025

    
3026

    
3027
  def ExpandNames(self):
3028
    _CheckOutputFields(static=self._FIELDS_STATIC,
3029
                       dynamic=self._FIELDS_DYNAMIC,
3030
                       selected=self.op.output_fields)
3031

    
3032
    self.needed_locks = {}
3033
    self.share_locks[locking.LEVEL_INSTANCE] = 1
3034
    self.share_locks[locking.LEVEL_NODE] = 1
3035

    
3036
    if self.op.names:
3037
      self.wanted = _GetWantedInstances(self, self.op.names)
3038
    else:
3039
      self.wanted = locking.ALL_SET
3040

    
3041
    self.do_locking = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3042
    if self.do_locking:
3043
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
3044
      self.needed_locks[locking.LEVEL_NODE] = []
3045
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3046

    
3047
  def DeclareLocks(self, level):
3048
    if level == locking.LEVEL_NODE and self.do_locking:
3049
      self._LockInstancesNodes()
3050

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

3054
    """
3055
    pass
3056

    
3057
  def Exec(self, feedback_fn):
3058
    """Computes the list of nodes and their attributes.
3059

3060
    """
3061
    all_info = self.cfg.GetAllInstancesInfo()
3062
    if self.do_locking:
3063
      instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
3064
    elif self.wanted != locking.ALL_SET:
3065
      instance_names = self.wanted
3066
      missing = set(instance_names).difference(all_info.keys())
3067
      if missing:
3068
        raise errors.OpExecError(
3069
          "Some instances were removed before retrieving their data: %s"
3070
          % missing)
3071
    else:
3072
      instance_names = all_info.keys()
3073

    
3074
    instance_names = utils.NiceSort(instance_names)
3075
    instance_list = [all_info[iname] for iname in instance_names]
3076

    
3077
    # begin data gathering
3078

    
3079
    nodes = frozenset([inst.primary_node for inst in instance_list])
3080
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
3081

    
3082
    bad_nodes = []
3083
    off_nodes = []
3084
    if self.do_locking:
3085
      live_data = {}
3086
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
3087
      for name in nodes:
3088
        result = node_data[name]
3089
        if result.offline:
3090
          # offline nodes will be in both lists
3091
          off_nodes.append(name)
3092
        if result.failed:
3093
          bad_nodes.append(name)
3094
        else:
3095
          if result.data:
3096
            live_data.update(result.data)
3097
            # else no instance is alive
3098
    else:
3099
      live_data = dict([(name, {}) for name in instance_names])
3100

    
3101
    # end data gathering
3102

    
3103
    HVPREFIX = "hv/"
3104
    BEPREFIX = "be/"
3105
    output = []
3106
    for instance in instance_list:
3107
      iout = []
3108
      i_hv = self.cfg.GetClusterInfo().FillHV(instance)
3109
      i_be = self.cfg.GetClusterInfo().FillBE(instance)
3110
      for field in self.op.output_fields:
3111
        st_match = self._FIELDS_STATIC.Matches(field)
3112
        if field == "name":
3113
          val = instance.name
3114
        elif field == "os":
3115
          val = instance.os
3116
        elif field == "pnode":
3117
          val = instance.primary_node
3118
        elif field == "snodes":
3119
          val = list(instance.secondary_nodes)
3120
        elif field == "admin_state":
3121
          val = (instance.status != "down")
3122
        elif field == "oper_state":
3123
          if instance.primary_node in bad_nodes:
3124
            val = None
3125
          else:
3126
            val = bool(live_data.get(instance.name))
3127
        elif field == "status":
3128
          if instance.primary_node in off_nodes:
3129
            val = "ERROR_nodeoffline"
3130
          elif instance.primary_node in bad_nodes:
3131
            val = "ERROR_nodedown"
3132
          else:
3133
            running = bool(live_data.get(instance.name))
3134
            if running:
3135
              if instance.status != "down":
3136
                val = "running"
3137
              else:
3138
                val = "ERROR_up"
3139
            else:
3140
              if instance.status != "down":
3141
                val = "ERROR_down"
3142
              else:
3143
                val = "ADMIN_down"
3144
        elif field == "oper_ram":
3145
          if instance.primary_node in bad_nodes:
3146
            val = None
3147
          elif instance.name in live_data:
3148
            val = live_data[instance.name].get("memory", "?")
3149
          else:
3150
            val = "-"
3151
        elif field == "disk_template":
3152
          val = instance.disk_template
3153
        elif field == "ip":
3154
          val = instance.nics[0].ip
3155
        elif field == "bridge":
3156
          val = instance.nics[0].bridge
3157
        elif field == "mac":
3158
          val = instance.nics[0].mac
3159
        elif field == "sda_size" or field == "sdb_size":
3160
          idx = ord(field[2]) - ord('a')
3161
          try:
3162
            val = instance.FindDisk(idx).size
3163
          except errors.OpPrereqError:
3164
            val = None
3165
        elif field == "tags":
3166
          val = list(instance.GetTags())
3167
        elif field == "serial_no":
3168
          val = instance.serial_no
3169
        elif field == "network_port":
3170
          val = instance.network_port
3171
        elif field == "hypervisor":
3172
          val = instance.hypervisor
3173
        elif field == "hvparams":
3174
          val = i_hv
3175
        elif (field.startswith(HVPREFIX) and
3176
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS):
3177
          val = i_hv.get(field[len(HVPREFIX):], None)
3178
        elif field == "beparams":
3179
          val = i_be
3180
        elif (field.startswith(BEPREFIX) and
3181
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
3182
          val = i_be.get(field[len(BEPREFIX):], None)
3183
        elif st_match and st_match.groups():
3184
          # matches a variable list
3185
          st_groups = st_match.groups()
3186
          if st_groups and st_groups[0] == "disk":
3187
            if st_groups[1] == "count":
3188
              val = len(instance.disks)
3189
            elif st_groups[1] == "sizes":
3190
              val = [disk.size for disk in instance.disks]
3191
            elif st_groups[1] == "size":
3192
              try:
3193
                val = instance.FindDisk(st_groups[2]).size
3194
              except errors.OpPrereqError:
3195
                val = None
3196
            else:
3197
              assert False, "Unhandled disk parameter"
3198
          elif st_groups[0] == "nic":
3199
            if st_groups[1] == "count":
3200
              val = len(instance.nics)
3201
            elif st_groups[1] == "macs":
3202
              val = [nic.mac for nic in instance.nics]
3203
            elif st_groups[1] == "ips":
3204
              val = [nic.ip for nic in instance.nics]
3205
            elif st_groups[1] == "bridges":
3206
              val = [nic.bridge for nic in instance.nics]
3207
            else:
3208
              # index-based item
3209
              nic_idx = int(st_groups[2])
3210
              if nic_idx >= len(instance.nics):
3211
                val = None
3212
              else:
3213
                if st_groups[1] == "mac":
3214
                  val = instance.nics[nic_idx].mac
3215
                elif st_groups[1] == "ip":
3216
                  val = instance.nics[nic_idx].ip
3217
                elif st_groups[1] == "bridge":
3218
                  val = instance.nics[nic_idx].bridge
3219
                else:
3220
                  assert False, "Unhandled NIC parameter"
3221
          else:
3222
            assert False, "Unhandled variable parameter"
3223
        else:
3224
          raise errors.ParameterError(field)
3225
        iout.append(val)
3226
      output.append(iout)
3227

    
3228
    return output
3229

    
3230

    
3231
class LUFailoverInstance(LogicalUnit):
3232
  """Failover an instance.
3233

3234
  """
3235
  HPATH = "instance-failover"
3236
  HTYPE = constants.HTYPE_INSTANCE
3237
  _OP_REQP = ["instance_name", "ignore_consistency"]
3238
  REQ_BGL = False
3239

    
3240
  def ExpandNames(self):
3241
    self._ExpandAndLockInstance()
3242
    self.needed_locks[locking.LEVEL_NODE] = []
3243
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3244

    
3245
  def DeclareLocks(self, level):
3246
    if level == locking.LEVEL_NODE:
3247
      self._LockInstancesNodes()
3248

    
3249
  def BuildHooksEnv(self):
3250
    """Build hooks env.
3251

3252
    This runs on master, primary and secondary nodes of the instance.
3253

3254
    """
3255
    env = {
3256
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
3257
      }
3258
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3259
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
3260
    return env, nl, nl
3261

    
3262
  def CheckPrereq(self):
3263
    """Check prerequisites.
3264

3265
    This checks that the instance is in the cluster.
3266

3267
    """
3268
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3269
    assert self.instance is not None, \
3270
      "Cannot retrieve locked instance %s" % self.op.instance_name
3271

    
3272
    bep = self.cfg.GetClusterInfo().FillBE(instance)
3273
    if instance.disk_template not in constants.DTS_NET_MIRROR:
3274
      raise errors.OpPrereqError("Instance's disk layout is not"
3275
                                 " network mirrored, cannot failover.")
3276

    
3277
    secondary_nodes = instance.secondary_nodes
3278
    if not secondary_nodes:
3279
      raise errors.ProgrammerError("no secondary node but using "
3280
                                   "a mirrored disk template")
3281

    
3282
    target_node = secondary_nodes[0]
3283
    _CheckNodeOnline(self, target_node)
3284
    # check memory requirements on the secondary node
3285
    _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
3286
                         instance.name, bep[constants.BE_MEMORY],
3287
                         instance.hypervisor)
3288

    
3289
    # check bridge existance
3290
    brlist = [nic.bridge for nic in instance.nics]
3291
    result = self.rpc.call_bridges_exist(target_node, brlist)
3292
    result.Raise()
3293
    if not result.data:
3294
      raise errors.OpPrereqError("One or more target bridges %s does not"
3295
                                 " exist on destination node '%s'" %
3296
                                 (brlist, target_node))
3297

    
3298
  def Exec(self, feedback_fn):
3299
    """Failover an instance.
3300

3301
    The failover is done by shutting it down on its present node and
3302
    starting it on the secondary.
3303

3304
    """
3305
    instance = self.instance
3306

    
3307
    source_node = instance.primary_node
3308
    target_node = instance.secondary_nodes[0]
3309

    
3310
    feedback_fn("* checking disk consistency between source and target")
3311
    for dev in instance.disks:
3312
      # for drbd, these are drbd over lvm
3313
      if not _CheckDiskConsistency(self, dev, target_node, False):
3314
        if instance.status == "up" and not self.op.ignore_consistency:
3315
          raise errors.OpExecError("Disk %s is degraded on target node,"
3316
                                   " aborting failover." % dev.iv_name)
3317

    
3318
    feedback_fn("* shutting down instance on source node")
3319
    logging.info("Shutting down instance %s on node %s",
3320
                 instance.name, source_node)
3321

    
3322
    result = self.rpc.call_instance_shutdown(source_node, instance)
3323
    if result.failed or not result.data:
3324
      if self.op.ignore_consistency:
3325
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
3326
                             " Proceeding"
3327
                             " anyway. Please make sure node %s is down",
3328
                             instance.name, source_node, source_node)
3329
      else:
3330
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
3331
                                 (instance.name, source_node))
3332

    
3333
    feedback_fn("* deactivating the instance's disks on source node")
3334
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
3335
      raise errors.OpExecError("Can't shut down the instance's disks.")
3336

    
3337
    instance.primary_node = target_node
3338
    # distribute new instance config to the other nodes
3339
    self.cfg.Update(instance)
3340

    
3341
    # Only start the instance if it's marked as up
3342
    if instance.status == "up":
3343
      feedback_fn("* activating the instance's disks on target node")
3344
      logging.info("Starting instance %s on node %s",
3345
                   instance.name, target_node)
3346

    
3347
      disks_ok, dummy = _AssembleInstanceDisks(self, instance,
3348
                                               ignore_secondaries=True)
3349
      if not disks_ok:
3350
        _ShutdownInstanceDisks(self, instance)
3351
        raise errors.OpExecError("Can't activate the instance's disks")
3352

    
3353
      feedback_fn("* starting the instance on the target node")
3354
      result = self.rpc.call_instance_start(target_node, instance, None)
3355
      if result.failed or not result.data:
3356
        _ShutdownInstanceDisks(self, instance)
3357
        raise errors.OpExecError("Could not start instance %s on node %s." %
3358
                                 (instance.name, target_node))
3359

    
3360

    
3361
def _CreateBlockDevOnPrimary(lu, node, instance, device, info):
3362
  """Create a tree of block devices on the primary node.
3363

3364
  This always creates all devices.
3365

3366
  """
3367
  if device.children:
3368
    for child in device.children:
3369
      if not _CreateBlockDevOnPrimary(lu, node, instance, child, info):
3370
        return False
3371

    
3372
  lu.cfg.SetDiskID(device, node)
3373
  new_id = lu.rpc.call_blockdev_create(node, device, device.size,
3374
                                       instance.name, True, info)
3375
  if new_id.failed or not new_id.data:
3376
    return False
3377
  if device.physical_id is None:
3378
    device.physical_id = new_id
3379
  return True
3380

    
3381

    
3382
def _CreateBlockDevOnSecondary(lu, node, instance, device, force, info):
3383
  """Create a tree of block devices on a secondary node.
3384

3385
  If this device type has to be created on secondaries, create it and
3386
  all its children.
3387

3388
  If not, just recurse to children keeping the same 'force' value.
3389

3390
  """
3391
  if device.CreateOnSecondary():
3392
    force = True
3393
  if device.children:
3394
    for child in device.children:
3395
      if not _CreateBlockDevOnSecondary(lu, node, instance,
3396
                                        child, force, info):
3397
        return False
3398

    
3399
  if not force:
3400
    return True
3401
  lu.cfg.SetDiskID(device, node)
3402
  new_id = lu.rpc.call_blockdev_create(node, device, device.size,
3403
                                       instance.name, False, info)
3404
  if new_id.failed or not new_id.data:
3405
    return False
3406
  if device.physical_id is None:
3407
    device.physical_id = new_id
3408
  return True
3409

    
3410

    
3411
def _GenerateUniqueNames(lu, exts):
3412
  """Generate a suitable LV name.
3413

3414
  This will generate a logical volume name for the given instance.
3415

3416
  """
3417
  results = []
3418
  for val in exts:
3419
    new_id = lu.cfg.GenerateUniqueID()
3420
    results.append("%s%s" % (new_id, val))
3421
  return results
3422

    
3423

    
3424
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
3425
                         p_minor, s_minor):
3426
  """Generate a drbd8 device complete with its children.
3427

3428
  """
3429
  port = lu.cfg.AllocatePort()
3430
  vgname = lu.cfg.GetVGName()
3431
  shared_secret = lu.cfg.GenerateDRBDSecret()
3432
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
3433
                          logical_id=(vgname, names[0]))
3434
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
3435
                          logical_id=(vgname, names[1]))
3436
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
3437
                          logical_id=(primary, secondary, port,
3438
                                      p_minor, s_minor,
3439
                                      shared_secret),
3440
                          children=[dev_data, dev_meta],
3441
                          iv_name=iv_name)
3442
  return drbd_dev
3443

    
3444

    
3445
def _GenerateDiskTemplate(lu, template_name,
3446
                          instance_name, primary_node,
3447
                          secondary_nodes, disk_info,
3448
                          file_storage_dir, file_driver,
3449
                          base_index):
3450
  """Generate the entire disk layout for a given template type.
3451

3452
  """
3453
  #TODO: compute space requirements
3454

    
3455
  vgname = lu.cfg.GetVGName()
3456
  disk_count = len(disk_info)
3457
  disks = []
3458
  if template_name == constants.DT_DISKLESS:
3459
    pass
3460
  elif template_name == constants.DT_PLAIN:
3461
    if len(secondary_nodes) != 0:
3462
      raise errors.ProgrammerError("Wrong template configuration")
3463

    
3464
    names = _GenerateUniqueNames(lu, [".disk%d" % i
3465
                                      for i in range(disk_count)])
3466
    for idx, disk in enumerate(disk_info):
3467
      disk_index = idx + base_index
3468
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
3469
                              logical_id=(vgname, names[idx]),
3470
                              iv_name="disk/%d" % disk_index)
3471
      disks.append(disk_dev)
3472
  elif template_name == constants.DT_DRBD8:
3473
    if len(secondary_nodes) != 1:
3474
      raise errors.ProgrammerError("Wrong template configuration")
3475
    remote_node = secondary_nodes[0]
3476
    minors = lu.cfg.AllocateDRBDMinor(
3477
      [primary_node, remote_node] * len(disk_info), instance_name)
3478

    
3479
    names = _GenerateUniqueNames(lu,
3480
                                 [".disk%d_%s" % (i, s)
3481
                                  for i in range(disk_count)
3482
                                  for s in ("data", "meta")
3483
                                  ])
3484
    for idx, disk in enumerate(disk_info):
3485
      disk_index = idx + base_index
3486
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
3487
                                      disk["size"], names[idx*2:idx*2+2],
3488
                                      "disk/%d" % disk_index,
3489
                                      minors[idx*2], minors[idx*2+1])
3490
      disks.append(disk_dev)
3491
  elif template_name == constants.DT_FILE:
3492
    if len(secondary_nodes) != 0:
3493
      raise errors.ProgrammerError("Wrong template configuration")
3494

    
3495
    for idx, disk in enumerate(disk_info):
3496
      disk_index = idx + base_index
3497
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
3498
                              iv_name="disk/%d" % disk_index,
3499
                              logical_id=(file_driver,
3500
                                          "%s/disk%d" % (file_storage_dir,
3501
                                                         idx)))
3502
      disks.append(disk_dev)
3503
  else:
3504
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
3505
  return disks
3506

    
3507

    
3508
def _GetInstanceInfoText(instance):
3509
  """Compute that text that should be added to the disk's metadata.
3510

3511
  """
3512
  return "originstname+%s" % instance.name
3513

    
3514

    
3515
def _CreateDisks(lu, instance):
3516
  """Create all disks for an instance.
3517

3518
  This abstracts away some work from AddInstance.
3519

3520
  @type lu: L{LogicalUnit}
3521
  @param lu: the logical unit on whose behalf we execute
3522
  @type instance: L{objects.Instance}
3523
  @param instance: the instance whose disks we should create
3524
  @rtype: boolean
3525
  @return: the success of the creation
3526

3527
  """
3528
  info = _GetInstanceInfoText(instance)
3529

    
3530
  if instance.disk_template == constants.DT_FILE:
3531
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
3532
    result = lu.rpc.call_file_storage_dir_create(instance.primary_node,
3533
                                                 file_storage_dir)
3534

    
3535
    if result.failed or not result.data:
3536
      logging.error("Could not connect to node '%s'", instance.primary_node)
3537
      return False
3538

    
3539
    if not result.data[0]:
3540
      logging.error("Failed to create directory '%s'", file_storage_dir)
3541
      return False
3542

    
3543
  # Note: this needs to be kept in sync with adding of disks in
3544
  # LUSetInstanceParams
3545
  for device in instance.disks:
3546
    logging.info("Creating volume %s for instance %s",
3547
                 device.iv_name, instance.name)
3548
    #HARDCODE
3549
    for secondary_node in instance.secondary_nodes:
3550
      if not _CreateBlockDevOnSecondary(lu, secondary_node, instance,
3551
                                        device, False, info):
3552
        logging.error("Failed to create volume %s (%s) on secondary node %s!",
3553
                      device.iv_name, device, secondary_node)
3554
        return False
3555
    #HARDCODE
3556
    if not _CreateBlockDevOnPrimary(lu, instance.primary_node,
3557
                                    instance, device, info):
3558
      logging.error("Failed to create volume %s on primary!", device.iv_name)
3559
      return False
3560

    
3561
  return True
3562

    
3563

    
3564
def _RemoveDisks(lu, instance):
3565
  """Remove all disks for an instance.
3566

3567
  This abstracts away some work from `AddInstance()` and
3568
  `RemoveInstance()`. Note that in case some of the devices couldn't
3569
  be removed, the removal will continue with the other ones (compare
3570
  with `_CreateDisks()`).
3571

3572
  @type lu: L{LogicalUnit}
3573
  @param lu: the logical unit on whose behalf we execute
3574
  @type instance: L{objects.Instance}
3575
  @param instance: the instance whose disks we should remove
3576
  @rtype: boolean
3577
  @return: the success of the removal
3578

3579
  """
3580
  logging.info("Removing block devices for instance %s", instance.name)
3581

    
3582
  result = True
3583
  for device in instance.disks:
3584
    for node, disk in device.ComputeNodeTree(instance.primary_node):
3585
      lu.cfg.SetDiskID(disk, node)
3586
      result = lu.rpc.call_blockdev_remove(node, disk)
3587
      if result.failed or not result.data:
3588
        lu.proc.LogWarning("Could not remove block device %s on node %s,"
3589
                           " continuing anyway", device.iv_name, node)
3590
        result = False
3591

    
3592
  if instance.disk_template == constants.DT_FILE:
3593
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
3594
    result = lu.rpc.call_file_storage_dir_remove(instance.primary_node,
3595
                                                 file_storage_dir)
3596
    if result.failed or not result.data:
3597
      logging.error("Could not remove directory '%s'", file_storage_dir)
3598
      result = False
3599

    
3600
  return result
3601

    
3602

    
3603
def _ComputeDiskSize(disk_template, disks):
3604
  """Compute disk size requirements in the volume group
3605

3606
  """
3607
  # Required free disk space as a function of disk and swap space
3608
  req_size_dict = {
3609
    constants.DT_DISKLESS: None,
3610
    constants.DT_PLAIN: sum(d["size"] for d in disks),
3611
    # 128 MB are added for drbd metadata for each disk
3612
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
3613
    constants.DT_FILE: None,
3614
  }
3615

    
3616
  if disk_template not in req_size_dict:
3617
    raise errors.ProgrammerError("Disk template '%s' size requirement"
3618
                                 " is unknown" %  disk_template)
3619

    
3620
  return req_size_dict[disk_template]
3621

    
3622

    
3623
def _CheckHVParams(lu, nodenames, hvname, hvparams):
3624
  """Hypervisor parameter validation.
3625

3626
  This function abstract the hypervisor parameter validation to be
3627
  used in both instance create and instance modify.
3628

3629
  @type lu: L{LogicalUnit}
3630
  @param lu: the logical unit for which we check
3631
  @type nodenames: list
3632
  @param nodenames: the list of nodes on which we should check
3633
  @type hvname: string
3634
  @param hvname: the name of the hypervisor we should use
3635
  @type hvparams: dict
3636
  @param hvparams: the parameters which we need to check
3637
  @raise errors.OpPrereqError: if the parameters are not valid
3638

3639
  """
3640
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
3641
                                                  hvname,
3642
                                                  hvparams)
3643
  for node in nodenames:
3644
    info = hvinfo[node]
3645
    info.Raise()
3646
    if not info.data or not isinstance(info.data, (tuple, list)):
3647
      raise errors.OpPrereqError("Cannot get current information"
3648
                                 " from node '%s' (%s)" % (node, info.data))
3649
    if not info.data[0]:
3650
      raise errors.OpPrereqError("Hypervisor parameter validation failed:"
3651
                                 " %s" % info.data[1])
3652

    
3653

    
3654
class LUCreateInstance(LogicalUnit):
3655
  """Create an instance.
3656

3657
  """
3658
  HPATH = "instance-add"
3659
  HTYPE = constants.HTYPE_INSTANCE
3660
  _OP_REQP = ["instance_name", "disks", "disk_template",
3661
              "mode", "start",
3662
              "wait_for_sync", "ip_check", "nics",
3663
              "hvparams", "beparams"]
3664
  REQ_BGL = False
3665

    
3666
  def _ExpandNode(self, node):
3667
    """Expands and checks one node name.
3668

3669
    """
3670
    node_full = self.cfg.ExpandNodeName(node)
3671
    if node_full is None:
3672
      raise errors.OpPrereqError("Unknown node %s" % node)
3673
    return node_full
3674

    
3675
  def ExpandNames(self):
3676
    """ExpandNames for CreateInstance.
3677

3678
    Figure out the right locks for instance creation.
3679

3680
    """
3681
    self.needed_locks = {}
3682

    
3683
    # set optional parameters to none if they don't exist
3684
    for attr in ["pnode", "snode", "iallocator", "hypervisor"]:
3685
      if not hasattr(self.op, attr):
3686
        setattr(self.op, attr, None)
3687

    
3688
    # cheap checks, mostly valid constants given
3689

    
3690
    # verify creation mode
3691
    if self.op.mode not in (constants.INSTANCE_CREATE,
3692
                            constants.INSTANCE_IMPORT):
3693
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
3694
                                 self.op.mode)
3695

    
3696
    # disk template and mirror node verification
3697
    if self.op.disk_template not in constants.DISK_TEMPLATES:
3698
      raise errors.OpPrereqError("Invalid disk template name")
3699

    
3700
    if self.op.hypervisor is None:
3701
      self.op.hypervisor = self.cfg.GetHypervisorType()
3702

    
3703
    cluster = self.cfg.GetClusterInfo()
3704
    enabled_hvs = cluster.enabled_hypervisors
3705
    if self.op.hypervisor not in enabled_hvs:
3706
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
3707
                                 " cluster (%s)" % (self.op.hypervisor,
3708
                                  ",".join(enabled_hvs)))
3709

    
3710
    # check hypervisor parameter syntax (locally)
3711

    
3712
    filled_hvp = cluster.FillDict(cluster.hvparams[self.op.hypervisor],
3713
                                  self.op.hvparams)
3714
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
3715
    hv_type.CheckParameterSyntax(filled_hvp)
3716

    
3717
    # fill and remember the beparams dict
3718
    utils.CheckBEParams(self.op.beparams)
3719
    self.be_full = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
3720
                                    self.op.beparams)
3721

    
3722
    #### instance parameters check
3723

    
3724
    # instance name verification
3725
    hostname1 = utils.HostInfo(self.op.instance_name)
3726
    self.op.instance_name = instance_name = hostname1.name
3727

    
3728
    # this is just a preventive check, but someone might still add this
3729
    # instance in the meantime, and creation will fail at lock-add time
3730
    if instance_name in self.cfg.GetInstanceList():
3731
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
3732
                                 instance_name)
3733

    
3734
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
3735

    
3736
    # NIC buildup
3737
    self.nics = []
3738
    for nic in self.op.nics:
3739
      # ip validity checks
3740
      ip = nic.get("ip", None)
3741
      if ip is None or ip.lower() == "none":
3742
        nic_ip = None
3743
      elif ip.lower() == constants.VALUE_AUTO:
3744
        nic_ip = hostname1.ip
3745
      else:
3746
        if not utils.IsValidIP(ip):
3747
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
3748
                                     " like a valid IP" % ip)
3749
        nic_ip = ip
3750

    
3751
      # MAC address verification
3752
      mac = nic.get("mac", constants.VALUE_AUTO)
3753
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
3754
        if not utils.IsValidMac(mac.lower()):
3755
          raise errors.OpPrereqError("Invalid MAC address specified: %s" %
3756
                                     mac)
3757
      # bridge verification
3758
      bridge = nic.get("bridge", self.cfg.GetDefBridge())
3759
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, bridge=bridge))
3760

    
3761
    # disk checks/pre-build
3762
    self.disks = []
3763
    for disk in self.op.disks:
3764
      mode = disk.get("mode", constants.DISK_RDWR)
3765
      if mode not in constants.DISK_ACCESS_SET:
3766
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
3767
                                   mode)
3768
      size = disk.get("size", None)
3769
      if size is None:
3770
        raise errors.OpPrereqError("Missing disk size")
3771
      try:
3772
        size = int(size)
3773
      except ValueError:
3774
        raise errors.OpPrereqError("Invalid disk size '%s'" % size)
3775
      self.disks.append({"size": size, "mode": mode})
3776

    
3777
    # used in CheckPrereq for ip ping check
3778
    self.check_ip = hostname1.ip
3779

    
3780
    # file storage checks
3781
    if (self.op.file_driver and
3782
        not self.op.file_driver in constants.FILE_DRIVER):
3783
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
3784
                                 self.op.file_driver)
3785

    
3786
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
3787
      raise errors.OpPrereqError("File storage directory path not absolute")
3788

    
3789
    ### Node/iallocator related checks
3790
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
3791
      raise errors.OpPrereqError("One and only one of iallocator and primary"
3792
                                 " node must be given")
3793

    
3794
    if self.op.iallocator:
3795
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3796
    else:
3797
      self.op.pnode = self._ExpandNode(self.op.pnode)
3798
      nodelist = [self.op.pnode]
3799
      if self.op.snode is not None:
3800
        self.op.snode = self._ExpandNode(self.op.snode)
3801
        nodelist.append(self.op.snode)
3802
      self.needed_locks[locking.LEVEL_NODE] = nodelist
3803

    
3804
    # in case of import lock the source node too
3805
    if self.op.mode == constants.INSTANCE_IMPORT:
3806
      src_node = getattr(self.op, "src_node", None)
3807
      src_path = getattr(self.op, "src_path", None)
3808

    
3809
      if src_path is None:
3810
        self.op.src_path = src_path = self.op.instance_name
3811

    
3812
      if src_node is None:
3813
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3814
        self.op.src_node = None
3815
        if os.path.isabs(src_path):
3816
          raise errors.OpPrereqError("Importing an instance from an absolute"
3817
                                     " path requires a source node option.")
3818
      else:
3819
        self.op.src_node = src_node = self._ExpandNode(src_node)
3820
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
3821
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
3822
        if not os.path.isabs(src_path):
3823
          self.op.src_path = src_path = \
3824
            os.path.join(constants.EXPORT_DIR, src_path)
3825

    
3826
    else: # INSTANCE_CREATE
3827
      if getattr(self.op, "os_type", None) is None:
3828
        raise errors.OpPrereqError("No guest OS specified")
3829

    
3830
  def _RunAllocator(self):
3831
    """Run the allocator based on input opcode.
3832

3833
    """
3834
    nics = [n.ToDict() for n in self.nics]
3835
    ial = IAllocator(self,
3836
                     mode=constants.IALLOCATOR_MODE_ALLOC,
3837
                     name=self.op.instance_name,
3838
                     disk_template=self.op.disk_template,
3839
                     tags=[],
3840
                     os=self.op.os_type,
3841
                     vcpus=self.be_full[constants.BE_VCPUS],
3842
                     mem_size=self.be_full[constants.BE_MEMORY],
3843
                     disks=self.disks,
3844
                     nics=nics,
3845
                     hypervisor=self.op.hypervisor,
3846
                     )
3847

    
3848
    ial.Run(self.op.iallocator)
3849

    
3850
    if not ial.success:
3851
      raise errors.OpPrereqError("Can't compute nodes using"
3852
                                 " iallocator '%s': %s" % (self.op.iallocator,
3853
                                                           ial.info))
3854
    if len(ial.nodes) != ial.required_nodes:
3855
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
3856
                                 " of nodes (%s), required %s" %
3857
                                 (self.op.iallocator, len(ial.nodes),
3858
                                  ial.required_nodes))
3859
    self.op.pnode = ial.nodes[0]
3860
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
3861
                 self.op.instance_name, self.op.iallocator,
3862
                 ", ".join(ial.nodes))
3863
    if ial.required_nodes == 2:
3864
      self.op.snode = ial.nodes[1]
3865

    
3866
  def BuildHooksEnv(self):
3867
    """Build hooks env.
3868

3869
    This runs on master, primary and secondary nodes of the instance.
3870

3871
    """
3872
    env = {
3873
      "INSTANCE_DISK_TEMPLATE": self.op.disk_template,
3874
      "INSTANCE_DISK_SIZE": ",".join(str(d["size"]) for d in self.disks),
3875
      "INSTANCE_ADD_MODE": self.op.mode,
3876
      }
3877
    if self.op.mode == constants.INSTANCE_IMPORT:
3878
      env["INSTANCE_SRC_NODE"] = self.op.src_node
3879
      env["INSTANCE_SRC_PATH"] = self.op.src_path
3880
      env["INSTANCE_SRC_IMAGES"] = self.src_images
3881

    
3882
    env.update(_BuildInstanceHookEnv(name=self.op.instance_name,
3883
      primary_node=self.op.pnode,
3884
      secondary_nodes=self.secondaries,
3885
      status=self.instance_status,
3886
      os_type=self.op.os_type,
3887
      memory=self.be_full[constants.BE_MEMORY],
3888
      vcpus=self.be_full[constants.BE_VCPUS],
3889
      nics=[(n.ip, n.bridge, n.mac) for n in self.nics],
3890
    ))
3891

    
3892
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
3893
          self.secondaries)
3894
    return env, nl, nl
3895

    
3896

    
3897
  def CheckPrereq(self):
3898
    """Check prerequisites.
3899

3900
    """
3901
    if (not self.cfg.GetVGName() and
3902
        self.op.disk_template not in constants.DTS_NOT_LVM):
3903
      raise errors.OpPrereqError("Cluster does not support lvm-based"
3904
                                 " instances")
3905

    
3906

    
3907
    if self.op.mode == constants.INSTANCE_IMPORT:
3908
      src_node = self.op.src_node
3909
      src_path = self.op.src_path
3910

    
3911
      if src_node is None:
3912
        exp_list = self.rpc.call_export_list(
3913
          self.acquired_locks[locking.LEVEL_NODE])
3914
        found = False
3915
        for node in exp_list:
3916
          if not exp_list[node].failed and src_path in exp_list[node].data:
3917
            found = True
3918
            self.op.src_node = src_node = node
3919
            self.op.src_path = src_path = os.path.join(constants.EXPORT_DIR,
3920
                                                       src_path)
3921
            break
3922
        if not found:
3923
          raise errors.OpPrereqError("No export found for relative path %s" %
3924
                                      src_path)
3925

    
3926
      _CheckNodeOnline(self, src_node)
3927
      result = self.rpc.call_export_info(src_node, src_path)
3928
      result.Raise()
3929
      if not result.data:
3930
        raise errors.OpPrereqError("No export found in dir %s" % src_path)
3931

    
3932
      export_info = result.data
3933
      if not export_info.has_section(constants.INISECT_EXP):
3934
        raise errors.ProgrammerError("Corrupted export config")
3935

    
3936
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
3937
      if (int(ei_version) != constants.EXPORT_VERSION):
3938
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
3939
                                   (ei_version, constants.EXPORT_VERSION))
3940

    
3941
      # Check that the new instance doesn't have less disks than the export
3942
      instance_disks = len(self.disks)
3943
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
3944
      if instance_disks < export_disks:
3945
        raise errors.OpPrereqError("Not enough disks to import."
3946
                                   " (instance: %d, export: %d)" %
3947
                                   (instance_disks, export_disks))
3948

    
3949
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
3950
      disk_images = []
3951
      for idx in range(export_disks):
3952
        option = 'disk%d_dump' % idx
3953
        if export_info.has_option(constants.INISECT_INS, option):
3954
          # FIXME: are the old os-es, disk sizes, etc. useful?
3955
          export_name = export_info.get(constants.INISECT_INS, option)
3956
          image = os.path.join(src_path, export_name)
3957
          disk_images.append(image)
3958
        else:
3959
          disk_images.append(False)
3960

    
3961
      self.src_images = disk_images
3962

    
3963
      old_name = export_info.get(constants.INISECT_INS, 'name')
3964
      # FIXME: int() here could throw a ValueError on broken exports
3965
      exp_nic_count = int(export_info.get(constants.INISECT_INS, 'nic_count'))
3966
      if self.op.instance_name == old_name:
3967
        for idx, nic in enumerate(self.nics):
3968
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
3969
            nic_mac_ini = 'nic%d_mac' % idx
3970
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
3971

    
3972
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
3973
    if self.op.start and not self.op.ip_check:
3974
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
3975
                                 " adding an instance in start mode")
3976

    
3977
    if self.op.ip_check:
3978
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
3979
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
3980
                                   (self.check_ip, self.op.instance_name))
3981

    
3982
    #### allocator run
3983

    
3984
    if self.op.iallocator is not None:
3985
      self._RunAllocator()
3986

    
3987
    #### node related checks
3988

    
3989
    # check primary node
3990
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
3991
    assert self.pnode is not None, \
3992
      "Cannot retrieve locked node %s" % self.op.pnode
3993
    if pnode.offline:
3994
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
3995
                                 pnode.name)
3996

    
3997
    self.secondaries = []
3998

    
3999
    # mirror node verification
4000
    if self.op.disk_template in constants.DTS_NET_MIRROR:
4001
      if self.op.snode is None:
4002
        raise errors.OpPrereqError("The networked disk templates need"
4003