Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 4e0b4d2d

History | View | Annotate | Download (172 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

    
34
from ganeti import rpc
35
from ganeti import ssh
36
from ganeti import logger
37
from ganeti import utils
38
from ganeti import errors
39
from ganeti import hypervisor
40
from ganeti import locking
41
from ganeti import config
42
from ganeti import constants
43
from ganeti import objects
44
from ganeti import opcodes
45
from ganeti import ssconf
46
from ganeti import serializer
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_MASTER: the LU needs to run on the master node
60
        REQ_WSSTORE: the LU needs a writable SimpleStore
61
        REQ_BGL: the LU needs to hold the Big Ganeti Lock exclusively
62

63
  Note that all commands require root permissions.
64

65
  """
66
  HPATH = None
67
  HTYPE = None
68
  _OP_REQP = []
69
  REQ_MASTER = True
70
  REQ_WSSTORE = False
71
  REQ_BGL = True
72

    
73
  def __init__(self, processor, op, context, sstore):
74
    """Constructor for LogicalUnit.
75

76
    This needs to be overriden in derived classes in order to check op
77
    validity.
78

79
    """
80
    self.proc = processor
81
    self.op = op
82
    self.cfg = context.cfg
83
    self.sstore = sstore
84
    self.context = context
85
    self.needed_locks = None
86
    self.share_locks = dict(((i, 0) for i in locking.LEVELS))
87
    # Used to force good behavior when calling helper functions
88
    self.recalculate_locks = {}
89
    self.__ssh = None
90

    
91
    for attr_name in self._OP_REQP:
92
      attr_val = getattr(op, attr_name, None)
93
      if attr_val is None:
94
        raise errors.OpPrereqError("Required parameter '%s' missing" %
95
                                   attr_name)
96

    
97
    if not self.cfg.IsCluster():
98
      raise errors.OpPrereqError("Cluster not initialized yet,"
99
                                 " use 'gnt-cluster init' first.")
100
    if self.REQ_MASTER:
101
      master = sstore.GetMasterNode()
102
      if master != utils.HostInfo().name:
103
        raise errors.OpPrereqError("Commands must be run on the master"
104
                                   " node %s" % master)
105

    
106
  def __GetSSH(self):
107
    """Returns the SshRunner object
108

109
    """
110
    if not self.__ssh:
111
      self.__ssh = ssh.SshRunner(self.sstore)
112
    return self.__ssh
113

    
114
  ssh = property(fget=__GetSSH)
115

    
116
  def ExpandNames(self):
117
    """Expand names for this LU.
118

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

124
    LUs which implement this method must also populate the self.needed_locks
125
    member, as a dict with lock levels as keys, and a list of needed lock names
126
    as values. Rules:
127
      - Use an empty dict if you don't need any lock
128
      - If you don't need any lock at a particular level omit that level
129
      - Don't put anything for the BGL level
130
      - If you want all locks at a level use None as a value
131
        (this reflects what LockSet does, and will be replaced before
132
        CheckPrereq with the full list of nodes that have been locked)
133

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

138
    Examples:
139
    # Acquire all nodes and one instance
140
    self.needed_locks = {
141
      locking.LEVEL_NODE: None,
142
      locking.LEVEL_INSTANCES: ['instance1.example.tld'],
143
    }
144
    # Acquire just two nodes
145
    self.needed_locks = {
146
      locking.LEVEL_NODE: ['node1.example.tld', 'node2.example.tld'],
147
    }
148
    # Acquire no locks
149
    self.needed_locks = {} # No, you can't leave it to the default value None
150

151
    """
152
    # The implementation of this method is mandatory only if the new LU is
153
    # concurrent, so that old LUs don't need to be changed all at the same
154
    # time.
155
    if self.REQ_BGL:
156
      self.needed_locks = {} # Exclusive LUs don't need locks.
157
    else:
158
      raise NotImplementedError
159

    
160
  def DeclareLocks(self, level):
161
    """Declare LU locking needs for a level
162

163
    While most LUs can just declare their locking needs at ExpandNames time,
164
    sometimes there's the need to calculate some locks after having acquired
165
    the ones before. This function is called just before acquiring locks at a
166
    particular level, but after acquiring the ones at lower levels, and permits
167
    such calculations. It can be used to modify self.needed_locks, and by
168
    default it does nothing.
169

170
    This function is only called if you have something already set in
171
    self.needed_locks for the level.
172

173
    @param level: Locking level which is going to be locked
174
    @type level: member of ganeti.locking.LEVELS
175

176
    """
177

    
178
  def CheckPrereq(self):
179
    """Check prerequisites for this LU.
180

181
    This method should check that the prerequisites for the execution
182
    of this LU are fulfilled. It can do internode communication, but
183
    it should be idempotent - no cluster or system changes are
184
    allowed.
185

186
    The method should raise errors.OpPrereqError in case something is
187
    not fulfilled. Its return value is ignored.
188

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

192
    """
193
    raise NotImplementedError
194

    
195
  def Exec(self, feedback_fn):
196
    """Execute the LU.
197

198
    This method should implement the actual work. It should raise
199
    errors.OpExecError for failures that are somewhat dealt with in
200
    code, or expected.
201

202
    """
203
    raise NotImplementedError
204

    
205
  def BuildHooksEnv(self):
206
    """Build hooks environment for this LU.
207

208
    This method should return a three-node tuple consisting of: a dict
209
    containing the environment that will be used for running the
210
    specific hook for this LU, a list of node names on which the hook
211
    should run before the execution, and a list of node names on which
212
    the hook should run after the execution.
213

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

219
    No nodes should be returned as an empty list (and not None).
220

221
    Note that if the HPATH for a LU class is None, this function will
222
    not be called.
223

224
    """
225
    raise NotImplementedError
226

    
227
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
228
    """Notify the LU about the results of its hooks.
229

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

236
    Args:
237
      phase: the hooks phase that has just been run
238
      hooks_results: the results of the multi-node hooks rpc call
239
      feedback_fn: function to send feedback back to the caller
240
      lu_result: the previous result this LU had, or None in the PRE phase.
241

242
    """
243
    return lu_result
244

    
245
  def _ExpandAndLockInstance(self):
246
    """Helper function to expand and lock an instance.
247

248
    Many LUs that work on an instance take its name in self.op.instance_name
249
    and need to expand it and then declare the expanded name for locking. This
250
    function does it, and then updates self.op.instance_name to the expanded
251
    name. It also initializes needed_locks as a dict, if this hasn't been done
252
    before.
253

254
    """
255
    if self.needed_locks is None:
256
      self.needed_locks = {}
257
    else:
258
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
259
        "_ExpandAndLockInstance called with instance-level locks set"
260
    expanded_name = self.cfg.ExpandInstanceName(self.op.instance_name)
261
    if expanded_name is None:
262
      raise errors.OpPrereqError("Instance '%s' not known" %
263
                                  self.op.instance_name)
264
    self.needed_locks[locking.LEVEL_INSTANCE] = expanded_name
265
    self.op.instance_name = expanded_name
266

    
267
  def _LockInstancesNodes(self):
268
    """Helper function to declare instances' nodes for locking.
269

270
    This function should be called after locking one or more instances to lock
271
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
272
    with all primary or secondary nodes for instances already locked and
273
    present in self.needed_locks[locking.LEVEL_INSTANCE].
274

275
    It should be called from DeclareLocks, and for safety only works if
276
    self.recalculate_locks[locking.LEVEL_NODE] is set.
277

278
    In the future it may grow parameters to just lock some instance's nodes, or
279
    to just lock primaries or secondary nodes, if needed.
280

281
    If should be called in DeclareLocks in a way similar to:
282

283
    if level == locking.LEVEL_NODE:
284
      self._LockInstancesNodes()
285

286
    """
287
    assert locking.LEVEL_NODE in self.recalculate_locks, \
288
      "_LockInstancesNodes helper function called with no nodes to recalculate"
289

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

    
292
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
293
    # future we might want to have different behaviors depending on the value
294
    # of self.recalculate_locks[locking.LEVEL_NODE]
295
    wanted_nodes = []
296
    for instance_name in self.needed_locks[locking.LEVEL_INSTANCE]:
297
      instance = self.context.cfg.GetInstanceInfo(instance_name)
298
      wanted_nodes.append(instance.primary_node)
299
      wanted_nodes.extend(instance.secondary_nodes)
300
    self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
301

    
302
    del self.recalculate_locks[locking.LEVEL_NODE]
303

    
304

    
305
class NoHooksLU(LogicalUnit):
306
  """Simple LU which runs no hooks.
307

308
  This LU is intended as a parent for other LogicalUnits which will
309
  run no hooks, in order to reduce duplicate code.
310

311
  """
312
  HPATH = None
313
  HTYPE = None
314

    
315

    
316
def _GetWantedNodes(lu, nodes):
317
  """Returns list of checked and expanded node names.
318

319
  Args:
320
    nodes: List of nodes (strings) or None for all
321

322
  """
323
  if not isinstance(nodes, list):
324
    raise errors.OpPrereqError("Invalid argument type 'nodes'")
325

    
326
  if nodes:
327
    wanted = []
328

    
329
    for name in nodes:
330
      node = lu.cfg.ExpandNodeName(name)
331
      if node is None:
332
        raise errors.OpPrereqError("No such node name '%s'" % name)
333
      wanted.append(node)
334

    
335
  else:
336
    wanted = lu.cfg.GetNodeList()
337
  return utils.NiceSort(wanted)
338

    
339

    
340
def _GetWantedInstances(lu, instances):
341
  """Returns list of checked and expanded instance names.
342

343
  Args:
344
    instances: List of instances (strings) or None for all
345

346
  """
347
  if not isinstance(instances, list):
348
    raise errors.OpPrereqError("Invalid argument type 'instances'")
349

    
350
  if instances:
351
    wanted = []
352

    
353
    for name in instances:
354
      instance = lu.cfg.ExpandInstanceName(name)
355
      if instance is None:
356
        raise errors.OpPrereqError("No such instance name '%s'" % name)
357
      wanted.append(instance)
358

    
359
  else:
360
    wanted = lu.cfg.GetInstanceList()
361
  return utils.NiceSort(wanted)
362

    
363

    
364
def _CheckOutputFields(static, dynamic, selected):
365
  """Checks whether all selected fields are valid.
366

367
  Args:
368
    static: Static fields
369
    dynamic: Dynamic fields
370

371
  """
372
  static_fields = frozenset(static)
373
  dynamic_fields = frozenset(dynamic)
374

    
375
  all_fields = static_fields | dynamic_fields
376

    
377
  if not all_fields.issuperset(selected):
378
    raise errors.OpPrereqError("Unknown output fields selected: %s"
379
                               % ",".join(frozenset(selected).
380
                                          difference(all_fields)))
381

    
382

    
383
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
384
                          memory, vcpus, nics):
385
  """Builds instance related env variables for hooks from single variables.
386

387
  Args:
388
    secondary_nodes: List of secondary nodes as strings
389
  """
390
  env = {
391
    "OP_TARGET": name,
392
    "INSTANCE_NAME": name,
393
    "INSTANCE_PRIMARY": primary_node,
394
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
395
    "INSTANCE_OS_TYPE": os_type,
396
    "INSTANCE_STATUS": status,
397
    "INSTANCE_MEMORY": memory,
398
    "INSTANCE_VCPUS": vcpus,
399
  }
400

    
401
  if nics:
402
    nic_count = len(nics)
403
    for idx, (ip, bridge, mac) in enumerate(nics):
404
      if ip is None:
405
        ip = ""
406
      env["INSTANCE_NIC%d_IP" % idx] = ip
407
      env["INSTANCE_NIC%d_BRIDGE" % idx] = bridge
408
      env["INSTANCE_NIC%d_HWADDR" % idx] = mac
409
  else:
410
    nic_count = 0
411

    
412
  env["INSTANCE_NIC_COUNT"] = nic_count
413

    
414
  return env
415

    
416

    
417
def _BuildInstanceHookEnvByObject(instance, override=None):
418
  """Builds instance related env variables for hooks from an object.
419

420
  Args:
421
    instance: objects.Instance object of instance
422
    override: dict of values to override
423
  """
424
  args = {
425
    'name': instance.name,
426
    'primary_node': instance.primary_node,
427
    'secondary_nodes': instance.secondary_nodes,
428
    'os_type': instance.os,
429
    'status': instance.os,
430
    'memory': instance.memory,
431
    'vcpus': instance.vcpus,
432
    'nics': [(nic.ip, nic.bridge, nic.mac) for nic in instance.nics],
433
  }
434
  if override:
435
    args.update(override)
436
  return _BuildInstanceHookEnv(**args)
437

    
438

    
439
def _CheckInstanceBridgesExist(instance):
440
  """Check that the brigdes needed by an instance exist.
441

442
  """
443
  # check bridges existance
444
  brlist = [nic.bridge for nic in instance.nics]
445
  if not rpc.call_bridges_exist(instance.primary_node, brlist):
446
    raise errors.OpPrereqError("one or more target bridges %s does not"
447
                               " exist on destination node '%s'" %
448
                               (brlist, instance.primary_node))
449

    
450

    
451
class LUDestroyCluster(NoHooksLU):
452
  """Logical unit for destroying the cluster.
453

454
  """
455
  _OP_REQP = []
456

    
457
  def CheckPrereq(self):
458
    """Check prerequisites.
459

460
    This checks whether the cluster is empty.
461

462
    Any errors are signalled by raising errors.OpPrereqError.
463

464
    """
465
    master = self.sstore.GetMasterNode()
466

    
467
    nodelist = self.cfg.GetNodeList()
468
    if len(nodelist) != 1 or nodelist[0] != master:
469
      raise errors.OpPrereqError("There are still %d node(s) in"
470
                                 " this cluster." % (len(nodelist) - 1))
471
    instancelist = self.cfg.GetInstanceList()
472
    if instancelist:
473
      raise errors.OpPrereqError("There are still %d instance(s) in"
474
                                 " this cluster." % len(instancelist))
475

    
476
  def Exec(self, feedback_fn):
477
    """Destroys the cluster.
478

479
    """
480
    master = self.sstore.GetMasterNode()
481
    if not rpc.call_node_stop_master(master, False):
482
      raise errors.OpExecError("Could not disable the master role")
483
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
484
    utils.CreateBackup(priv_key)
485
    utils.CreateBackup(pub_key)
486
    rpc.call_node_leave_cluster(master)
487

    
488

    
489
class LUVerifyCluster(LogicalUnit):
490
  """Verifies the cluster status.
491

492
  """
493
  HPATH = "cluster-verify"
494
  HTYPE = constants.HTYPE_CLUSTER
495
  _OP_REQP = ["skip_checks"]
496

    
497
  def _VerifyNode(self, node, file_list, local_cksum, vglist, node_result,
498
                  remote_version, feedback_fn):
499
    """Run multiple tests against a node.
500

501
    Test list:
502
      - compares ganeti version
503
      - checks vg existance and size > 20G
504
      - checks config file checksum
505
      - checks ssh to other nodes
506

507
    Args:
508
      node: name of the node to check
509
      file_list: required list of files
510
      local_cksum: dictionary of local files and their checksums
511

512
    """
513
    # compares ganeti version
514
    local_version = constants.PROTOCOL_VERSION
515
    if not remote_version:
516
      feedback_fn("  - ERROR: connection to %s failed" % (node))
517
      return True
518

    
519
    if local_version != remote_version:
520
      feedback_fn("  - ERROR: sw version mismatch: master %s, node(%s) %s" %
521
                      (local_version, node, remote_version))
522
      return True
523

    
524
    # checks vg existance and size > 20G
525

    
526
    bad = False
527
    if not vglist:
528
      feedback_fn("  - ERROR: unable to check volume groups on node %s." %
529
                      (node,))
530
      bad = True
531
    else:
532
      vgstatus = utils.CheckVolumeGroupSize(vglist, self.cfg.GetVGName(),
533
                                            constants.MIN_VG_SIZE)
534
      if vgstatus:
535
        feedback_fn("  - ERROR: %s on node %s" % (vgstatus, node))
536
        bad = True
537

    
538
    # checks config file checksum
539
    # checks ssh to any
540

    
541
    if 'filelist' not in node_result:
542
      bad = True
543
      feedback_fn("  - ERROR: node hasn't returned file checksum data")
544
    else:
545
      remote_cksum = node_result['filelist']
546
      for file_name in file_list:
547
        if file_name not in remote_cksum:
548
          bad = True
549
          feedback_fn("  - ERROR: file '%s' missing" % file_name)
550
        elif remote_cksum[file_name] != local_cksum[file_name]:
551
          bad = True
552
          feedback_fn("  - ERROR: file '%s' has wrong checksum" % file_name)
553

    
554
    if 'nodelist' not in node_result:
555
      bad = True
556
      feedback_fn("  - ERROR: node hasn't returned node ssh connectivity data")
557
    else:
558
      if node_result['nodelist']:
559
        bad = True
560
        for node in node_result['nodelist']:
561
          feedback_fn("  - ERROR: ssh communication with node '%s': %s" %
562
                          (node, node_result['nodelist'][node]))
563
    if 'node-net-test' not in node_result:
564
      bad = True
565
      feedback_fn("  - ERROR: node hasn't returned node tcp connectivity data")
566
    else:
567
      if node_result['node-net-test']:
568
        bad = True
569
        nlist = utils.NiceSort(node_result['node-net-test'].keys())
570
        for node in nlist:
571
          feedback_fn("  - ERROR: tcp communication with node '%s': %s" %
572
                          (node, node_result['node-net-test'][node]))
573

    
574
    hyp_result = node_result.get('hypervisor', None)
575
    if hyp_result is not None:
576
      feedback_fn("  - ERROR: hypervisor verify failure: '%s'" % hyp_result)
577
    return bad
578

    
579
  def _VerifyInstance(self, instance, instanceconfig, node_vol_is,
580
                      node_instance, feedback_fn):
581
    """Verify an instance.
582

583
    This function checks to see if the required block devices are
584
    available on the instance's node.
585

586
    """
587
    bad = False
588

    
589
    node_current = instanceconfig.primary_node
590

    
591
    node_vol_should = {}
592
    instanceconfig.MapLVsByNode(node_vol_should)
593

    
594
    for node in node_vol_should:
595
      for volume in node_vol_should[node]:
596
        if node not in node_vol_is or volume not in node_vol_is[node]:
597
          feedback_fn("  - ERROR: volume %s missing on node %s" %
598
                          (volume, node))
599
          bad = True
600

    
601
    if not instanceconfig.status == 'down':
602
      if (node_current not in node_instance or
603
          not instance in node_instance[node_current]):
604
        feedback_fn("  - ERROR: instance %s not running on node %s" %
605
                        (instance, node_current))
606
        bad = True
607

    
608
    for node in node_instance:
609
      if (not node == node_current):
610
        if instance in node_instance[node]:
611
          feedback_fn("  - ERROR: instance %s should not run on node %s" %
612
                          (instance, node))
613
          bad = True
614

    
615
    return bad
616

    
617
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is, feedback_fn):
618
    """Verify if there are any unknown volumes in the cluster.
619

620
    The .os, .swap and backup volumes are ignored. All other volumes are
621
    reported as unknown.
622

623
    """
624
    bad = False
625

    
626
    for node in node_vol_is:
627
      for volume in node_vol_is[node]:
628
        if node not in node_vol_should or volume not in node_vol_should[node]:
629
          feedback_fn("  - ERROR: volume %s on node %s should not exist" %
630
                      (volume, node))
631
          bad = True
632
    return bad
633

    
634
  def _VerifyOrphanInstances(self, instancelist, node_instance, feedback_fn):
635
    """Verify the list of running instances.
636

637
    This checks what instances are running but unknown to the cluster.
638

639
    """
640
    bad = False
641
    for node in node_instance:
642
      for runninginstance in node_instance[node]:
643
        if runninginstance not in instancelist:
644
          feedback_fn("  - ERROR: instance %s on node %s should not exist" %
645
                          (runninginstance, node))
646
          bad = True
647
    return bad
648

    
649
  def _VerifyNPlusOneMemory(self, node_info, instance_cfg, feedback_fn):
650
    """Verify N+1 Memory Resilience.
651

652
    Check that if one single node dies we can still start all the instances it
653
    was primary for.
654

655
    """
656
    bad = False
657

    
658
    for node, nodeinfo in node_info.iteritems():
659
      # This code checks that every node which is now listed as secondary has
660
      # enough memory to host all instances it is supposed to should a single
661
      # other node in the cluster fail.
662
      # FIXME: not ready for failover to an arbitrary node
663
      # FIXME: does not support file-backed instances
664
      # WARNING: we currently take into account down instances as well as up
665
      # ones, considering that even if they're down someone might want to start
666
      # them even in the event of a node failure.
667
      for prinode, instances in nodeinfo['sinst-by-pnode'].iteritems():
668
        needed_mem = 0
669
        for instance in instances:
670
          needed_mem += instance_cfg[instance].memory
671
        if nodeinfo['mfree'] < needed_mem:
672
          feedback_fn("  - ERROR: not enough memory on node %s to accomodate"
673
                      " failovers should node %s fail" % (node, prinode))
674
          bad = True
675
    return bad
676

    
677
  def CheckPrereq(self):
678
    """Check prerequisites.
679

680
    Transform the list of checks we're going to skip into a set and check that
681
    all its members are valid.
682

683
    """
684
    self.skip_set = frozenset(self.op.skip_checks)
685
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
686
      raise errors.OpPrereqError("Invalid checks to be skipped specified")
687

    
688
  def BuildHooksEnv(self):
689
    """Build hooks env.
690

691
    Cluster-Verify hooks just rone in the post phase and their failure makes
692
    the output be logged in the verify output and the verification to fail.
693

694
    """
695
    all_nodes = self.cfg.GetNodeList()
696
    # TODO: populate the environment with useful information for verify hooks
697
    env = {}
698
    return env, [], all_nodes
699

    
700
  def Exec(self, feedback_fn):
701
    """Verify integrity of cluster, performing various test on nodes.
702

703
    """
704
    bad = False
705
    feedback_fn("* Verifying global settings")
706
    for msg in self.cfg.VerifyConfig():
707
      feedback_fn("  - ERROR: %s" % msg)
708

    
709
    vg_name = self.cfg.GetVGName()
710
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
711
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
712
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
713
    i_non_redundant = [] # Non redundant instances
714
    node_volume = {}
715
    node_instance = {}
716
    node_info = {}
717
    instance_cfg = {}
718

    
719
    # FIXME: verify OS list
720
    # do local checksums
721
    file_names = list(self.sstore.GetFileList())
722
    file_names.append(constants.SSL_CERT_FILE)
723
    file_names.append(constants.CLUSTER_CONF_FILE)
724
    local_checksums = utils.FingerprintFiles(file_names)
725

    
726
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
727
    all_volumeinfo = rpc.call_volume_list(nodelist, vg_name)
728
    all_instanceinfo = rpc.call_instance_list(nodelist)
729
    all_vglist = rpc.call_vg_list(nodelist)
730
    node_verify_param = {
731
      'filelist': file_names,
732
      'nodelist': nodelist,
733
      'hypervisor': None,
734
      'node-net-test': [(node.name, node.primary_ip, node.secondary_ip)
735
                        for node in nodeinfo]
736
      }
737
    all_nvinfo = rpc.call_node_verify(nodelist, node_verify_param)
738
    all_rversion = rpc.call_version(nodelist)
739
    all_ninfo = rpc.call_node_info(nodelist, self.cfg.GetVGName())
740

    
741
    for node in nodelist:
742
      feedback_fn("* Verifying node %s" % node)
743
      result = self._VerifyNode(node, file_names, local_checksums,
744
                                all_vglist[node], all_nvinfo[node],
745
                                all_rversion[node], feedback_fn)
746
      bad = bad or result
747

    
748
      # node_volume
749
      volumeinfo = all_volumeinfo[node]
750

    
751
      if isinstance(volumeinfo, basestring):
752
        feedback_fn("  - ERROR: LVM problem on node %s: %s" %
753
                    (node, volumeinfo[-400:].encode('string_escape')))
754
        bad = True
755
        node_volume[node] = {}
756
      elif not isinstance(volumeinfo, dict):
757
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
758
        bad = True
759
        continue
760
      else:
761
        node_volume[node] = volumeinfo
762

    
763
      # node_instance
764
      nodeinstance = all_instanceinfo[node]
765
      if type(nodeinstance) != list:
766
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
767
        bad = True
768
        continue
769

    
770
      node_instance[node] = nodeinstance
771

    
772
      # node_info
773
      nodeinfo = all_ninfo[node]
774
      if not isinstance(nodeinfo, dict):
775
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
776
        bad = True
777
        continue
778

    
779
      try:
780
        node_info[node] = {
781
          "mfree": int(nodeinfo['memory_free']),
782
          "dfree": int(nodeinfo['vg_free']),
783
          "pinst": [],
784
          "sinst": [],
785
          # dictionary holding all instances this node is secondary for,
786
          # grouped by their primary node. Each key is a cluster node, and each
787
          # value is a list of instances which have the key as primary and the
788
          # current node as secondary.  this is handy to calculate N+1 memory
789
          # availability if you can only failover from a primary to its
790
          # secondary.
791
          "sinst-by-pnode": {},
792
        }
793
      except ValueError:
794
        feedback_fn("  - ERROR: invalid value returned from node %s" % (node,))
795
        bad = True
796
        continue
797

    
798
    node_vol_should = {}
799

    
800
    for instance in instancelist:
801
      feedback_fn("* Verifying instance %s" % instance)
802
      inst_config = self.cfg.GetInstanceInfo(instance)
803
      result =  self._VerifyInstance(instance, inst_config, node_volume,
804
                                     node_instance, feedback_fn)
805
      bad = bad or result
806

    
807
      inst_config.MapLVsByNode(node_vol_should)
808

    
809
      instance_cfg[instance] = inst_config
810

    
811
      pnode = inst_config.primary_node
812
      if pnode in node_info:
813
        node_info[pnode]['pinst'].append(instance)
814
      else:
815
        feedback_fn("  - ERROR: instance %s, connection to primary node"
816
                    " %s failed" % (instance, pnode))
817
        bad = True
818

    
819
      # If the instance is non-redundant we cannot survive losing its primary
820
      # node, so we are not N+1 compliant. On the other hand we have no disk
821
      # templates with more than one secondary so that situation is not well
822
      # supported either.
823
      # FIXME: does not support file-backed instances
824
      if len(inst_config.secondary_nodes) == 0:
825
        i_non_redundant.append(instance)
826
      elif len(inst_config.secondary_nodes) > 1:
827
        feedback_fn("  - WARNING: multiple secondaries for instance %s"
828
                    % instance)
829

    
830
      for snode in inst_config.secondary_nodes:
831
        if snode in node_info:
832
          node_info[snode]['sinst'].append(instance)
833
          if pnode not in node_info[snode]['sinst-by-pnode']:
834
            node_info[snode]['sinst-by-pnode'][pnode] = []
835
          node_info[snode]['sinst-by-pnode'][pnode].append(instance)
836
        else:
837
          feedback_fn("  - ERROR: instance %s, connection to secondary node"
838
                      " %s failed" % (instance, snode))
839

    
840
    feedback_fn("* Verifying orphan volumes")
841
    result = self._VerifyOrphanVolumes(node_vol_should, node_volume,
842
                                       feedback_fn)
843
    bad = bad or result
844

    
845
    feedback_fn("* Verifying remaining instances")
846
    result = self._VerifyOrphanInstances(instancelist, node_instance,
847
                                         feedback_fn)
848
    bad = bad or result
849

    
850
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
851
      feedback_fn("* Verifying N+1 Memory redundancy")
852
      result = self._VerifyNPlusOneMemory(node_info, instance_cfg, feedback_fn)
853
      bad = bad or result
854

    
855
    feedback_fn("* Other Notes")
856
    if i_non_redundant:
857
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
858
                  % len(i_non_redundant))
859

    
860
    return int(bad)
861

    
862
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
863
    """Analize the post-hooks' result, handle it, and send some
864
    nicely-formatted feedback back to the user.
865

866
    Args:
867
      phase: the hooks phase that has just been run
868
      hooks_results: the results of the multi-node hooks rpc call
869
      feedback_fn: function to send feedback back to the caller
870
      lu_result: previous Exec result
871

872
    """
873
    # We only really run POST phase hooks, and are only interested in their results
874
    if phase == constants.HOOKS_PHASE_POST:
875
      # Used to change hooks' output to proper indentation
876
      indent_re = re.compile('^', re.M)
877
      feedback_fn("* Hooks Results")
878
      if not hooks_results:
879
        feedback_fn("  - ERROR: general communication failure")
880
        lu_result = 1
881
      else:
882
        for node_name in hooks_results:
883
          show_node_header = True
884
          res = hooks_results[node_name]
885
          if res is False or not isinstance(res, list):
886
            feedback_fn("    Communication failure")
887
            lu_result = 1
888
            continue
889
          for script, hkr, output in res:
890
            if hkr == constants.HKR_FAIL:
891
              # The node header is only shown once, if there are
892
              # failing hooks on that node
893
              if show_node_header:
894
                feedback_fn("  Node %s:" % node_name)
895
                show_node_header = False
896
              feedback_fn("    ERROR: Script %s failed, output:" % script)
897
              output = indent_re.sub('      ', output)
898
              feedback_fn("%s" % output)
899
              lu_result = 1
900

    
901
      return lu_result
902

    
903

    
904
class LUVerifyDisks(NoHooksLU):
905
  """Verifies the cluster disks status.
906

907
  """
908
  _OP_REQP = []
909

    
910
  def CheckPrereq(self):
911
    """Check prerequisites.
912

913
    This has no prerequisites.
914

915
    """
916
    pass
917

    
918
  def Exec(self, feedback_fn):
919
    """Verify integrity of cluster disks.
920

921
    """
922
    result = res_nodes, res_nlvm, res_instances, res_missing = [], {}, [], {}
923

    
924
    vg_name = self.cfg.GetVGName()
925
    nodes = utils.NiceSort(self.cfg.GetNodeList())
926
    instances = [self.cfg.GetInstanceInfo(name)
927
                 for name in self.cfg.GetInstanceList()]
928

    
929
    nv_dict = {}
930
    for inst in instances:
931
      inst_lvs = {}
932
      if (inst.status != "up" or
933
          inst.disk_template not in constants.DTS_NET_MIRROR):
934
        continue
935
      inst.MapLVsByNode(inst_lvs)
936
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
937
      for node, vol_list in inst_lvs.iteritems():
938
        for vol in vol_list:
939
          nv_dict[(node, vol)] = inst
940

    
941
    if not nv_dict:
942
      return result
943

    
944
    node_lvs = rpc.call_volume_list(nodes, vg_name)
945

    
946
    to_act = set()
947
    for node in nodes:
948
      # node_volume
949
      lvs = node_lvs[node]
950

    
951
      if isinstance(lvs, basestring):
952
        logger.Info("error enumerating LVs on node %s: %s" % (node, lvs))
953
        res_nlvm[node] = lvs
954
      elif not isinstance(lvs, dict):
955
        logger.Info("connection to node %s failed or invalid data returned" %
956
                    (node,))
957
        res_nodes.append(node)
958
        continue
959

    
960
      for lv_name, (_, lv_inactive, lv_online) in lvs.iteritems():
961
        inst = nv_dict.pop((node, lv_name), None)
962
        if (not lv_online and inst is not None
963
            and inst.name not in res_instances):
964
          res_instances.append(inst.name)
965

    
966
    # any leftover items in nv_dict are missing LVs, let's arrange the
967
    # data better
968
    for key, inst in nv_dict.iteritems():
969
      if inst.name not in res_missing:
970
        res_missing[inst.name] = []
971
      res_missing[inst.name].append(key)
972

    
973
    return result
974

    
975

    
976
class LURenameCluster(LogicalUnit):
977
  """Rename the cluster.
978

979
  """
980
  HPATH = "cluster-rename"
981
  HTYPE = constants.HTYPE_CLUSTER
982
  _OP_REQP = ["name"]
983
  REQ_WSSTORE = True
984

    
985
  def BuildHooksEnv(self):
986
    """Build hooks env.
987

988
    """
989
    env = {
990
      "OP_TARGET": self.sstore.GetClusterName(),
991
      "NEW_NAME": self.op.name,
992
      }
993
    mn = self.sstore.GetMasterNode()
994
    return env, [mn], [mn]
995

    
996
  def CheckPrereq(self):
997
    """Verify that the passed name is a valid one.
998

999
    """
1000
    hostname = utils.HostInfo(self.op.name)
1001

    
1002
    new_name = hostname.name
1003
    self.ip = new_ip = hostname.ip
1004
    old_name = self.sstore.GetClusterName()
1005
    old_ip = self.sstore.GetMasterIP()
1006
    if new_name == old_name and new_ip == old_ip:
1007
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1008
                                 " cluster has changed")
1009
    if new_ip != old_ip:
1010
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1011
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1012
                                   " reachable on the network. Aborting." %
1013
                                   new_ip)
1014

    
1015
    self.op.name = new_name
1016

    
1017
  def Exec(self, feedback_fn):
1018
    """Rename the cluster.
1019

1020
    """
1021
    clustername = self.op.name
1022
    ip = self.ip
1023
    ss = self.sstore
1024

    
1025
    # shutdown the master IP
1026
    master = ss.GetMasterNode()
1027
    if not rpc.call_node_stop_master(master, False):
1028
      raise errors.OpExecError("Could not disable the master role")
1029

    
1030
    try:
1031
      # modify the sstore
1032
      ss.SetKey(ss.SS_MASTER_IP, ip)
1033
      ss.SetKey(ss.SS_CLUSTER_NAME, clustername)
1034

    
1035
      # Distribute updated ss config to all nodes
1036
      myself = self.cfg.GetNodeInfo(master)
1037
      dist_nodes = self.cfg.GetNodeList()
1038
      if myself.name in dist_nodes:
1039
        dist_nodes.remove(myself.name)
1040

    
1041
      logger.Debug("Copying updated ssconf data to all nodes")
1042
      for keyname in [ss.SS_CLUSTER_NAME, ss.SS_MASTER_IP]:
1043
        fname = ss.KeyToFilename(keyname)
1044
        result = rpc.call_upload_file(dist_nodes, fname)
1045
        for to_node in dist_nodes:
1046
          if not result[to_node]:
1047
            logger.Error("copy of file %s to node %s failed" %
1048
                         (fname, to_node))
1049
    finally:
1050
      if not rpc.call_node_start_master(master, False):
1051
        logger.Error("Could not re-enable the master role on the master,"
1052
                     " please restart manually.")
1053

    
1054

    
1055
def _RecursiveCheckIfLVMBased(disk):
1056
  """Check if the given disk or its children are lvm-based.
1057

1058
  Args:
1059
    disk: ganeti.objects.Disk object
1060

1061
  Returns:
1062
    boolean indicating whether a LD_LV dev_type was found or not
1063

1064
  """
1065
  if disk.children:
1066
    for chdisk in disk.children:
1067
      if _RecursiveCheckIfLVMBased(chdisk):
1068
        return True
1069
  return disk.dev_type == constants.LD_LV
1070

    
1071

    
1072
class LUSetClusterParams(LogicalUnit):
1073
  """Change the parameters of the cluster.
1074

1075
  """
1076
  HPATH = "cluster-modify"
1077
  HTYPE = constants.HTYPE_CLUSTER
1078
  _OP_REQP = []
1079

    
1080
  def BuildHooksEnv(self):
1081
    """Build hooks env.
1082

1083
    """
1084
    env = {
1085
      "OP_TARGET": self.sstore.GetClusterName(),
1086
      "NEW_VG_NAME": self.op.vg_name,
1087
      }
1088
    mn = self.sstore.GetMasterNode()
1089
    return env, [mn], [mn]
1090

    
1091
  def CheckPrereq(self):
1092
    """Check prerequisites.
1093

1094
    This checks whether the given params don't conflict and
1095
    if the given volume group is valid.
1096

1097
    """
1098
    if not self.op.vg_name:
1099
      instances = [self.cfg.GetInstanceInfo(name)
1100
                   for name in self.cfg.GetInstanceList()]
1101
      for inst in instances:
1102
        for disk in inst.disks:
1103
          if _RecursiveCheckIfLVMBased(disk):
1104
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1105
                                       " lvm-based instances exist")
1106

    
1107
    # if vg_name not None, checks given volume group on all nodes
1108
    if self.op.vg_name:
1109
      node_list = self.cfg.GetNodeList()
1110
      vglist = rpc.call_vg_list(node_list)
1111
      for node in node_list:
1112
        vgstatus = utils.CheckVolumeGroupSize(vglist[node], self.op.vg_name,
1113
                                              constants.MIN_VG_SIZE)
1114
        if vgstatus:
1115
          raise errors.OpPrereqError("Error on node '%s': %s" %
1116
                                     (node, vgstatus))
1117

    
1118
  def Exec(self, feedback_fn):
1119
    """Change the parameters of the cluster.
1120

1121
    """
1122
    if self.op.vg_name != self.cfg.GetVGName():
1123
      self.cfg.SetVGName(self.op.vg_name)
1124
    else:
1125
      feedback_fn("Cluster LVM configuration already in desired"
1126
                  " state, not changing")
1127

    
1128

    
1129
def _WaitForSync(cfgw, instance, proc, oneshot=False, unlock=False):
1130
  """Sleep and poll for an instance's disk to sync.
1131

1132
  """
1133
  if not instance.disks:
1134
    return True
1135

    
1136
  if not oneshot:
1137
    proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
1138

    
1139
  node = instance.primary_node
1140

    
1141
  for dev in instance.disks:
1142
    cfgw.SetDiskID(dev, node)
1143

    
1144
  retries = 0
1145
  while True:
1146
    max_time = 0
1147
    done = True
1148
    cumul_degraded = False
1149
    rstats = rpc.call_blockdev_getmirrorstatus(node, instance.disks)
1150
    if not rstats:
1151
      proc.LogWarning("Can't get any data from node %s" % node)
1152
      retries += 1
1153
      if retries >= 10:
1154
        raise errors.RemoteError("Can't contact node %s for mirror data,"
1155
                                 " aborting." % node)
1156
      time.sleep(6)
1157
      continue
1158
    retries = 0
1159
    for i in range(len(rstats)):
1160
      mstat = rstats[i]
1161
      if mstat is None:
1162
        proc.LogWarning("Can't compute data for node %s/%s" %
1163
                        (node, instance.disks[i].iv_name))
1164
        continue
1165
      # we ignore the ldisk parameter
1166
      perc_done, est_time, is_degraded, _ = mstat
1167
      cumul_degraded = cumul_degraded or (is_degraded and perc_done is None)
1168
      if perc_done is not None:
1169
        done = False
1170
        if est_time is not None:
1171
          rem_time = "%d estimated seconds remaining" % est_time
1172
          max_time = est_time
1173
        else:
1174
          rem_time = "no time estimate"
1175
        proc.LogInfo("- device %s: %5.2f%% done, %s" %
1176
                     (instance.disks[i].iv_name, perc_done, rem_time))
1177
    if done or oneshot:
1178
      break
1179

    
1180
    time.sleep(min(60, max_time))
1181

    
1182
  if done:
1183
    proc.LogInfo("Instance %s's disks are in sync." % instance.name)
1184
  return not cumul_degraded
1185

    
1186

    
1187
def _CheckDiskConsistency(cfgw, dev, node, on_primary, ldisk=False):
1188
  """Check that mirrors are not degraded.
1189

1190
  The ldisk parameter, if True, will change the test from the
1191
  is_degraded attribute (which represents overall non-ok status for
1192
  the device(s)) to the ldisk (representing the local storage status).
1193

1194
  """
1195
  cfgw.SetDiskID(dev, node)
1196
  if ldisk:
1197
    idx = 6
1198
  else:
1199
    idx = 5
1200

    
1201
  result = True
1202
  if on_primary or dev.AssembleOnSecondary():
1203
    rstats = rpc.call_blockdev_find(node, dev)
1204
    if not rstats:
1205
      logger.ToStderr("Node %s: Disk degraded, not found or node down" % node)
1206
      result = False
1207
    else:
1208
      result = result and (not rstats[idx])
1209
  if dev.children:
1210
    for child in dev.children:
1211
      result = result and _CheckDiskConsistency(cfgw, child, node, on_primary)
1212

    
1213
  return result
1214

    
1215

    
1216
class LUDiagnoseOS(NoHooksLU):
1217
  """Logical unit for OS diagnose/query.
1218

1219
  """
1220
  _OP_REQP = ["output_fields", "names"]
1221

    
1222
  def CheckPrereq(self):
1223
    """Check prerequisites.
1224

1225
    This always succeeds, since this is a pure query LU.
1226

1227
    """
1228
    if self.op.names:
1229
      raise errors.OpPrereqError("Selective OS query not supported")
1230

    
1231
    self.dynamic_fields = frozenset(["name", "valid", "node_status"])
1232
    _CheckOutputFields(static=[],
1233
                       dynamic=self.dynamic_fields,
1234
                       selected=self.op.output_fields)
1235

    
1236
  @staticmethod
1237
  def _DiagnoseByOS(node_list, rlist):
1238
    """Remaps a per-node return list into an a per-os per-node dictionary
1239

1240
      Args:
1241
        node_list: a list with the names of all nodes
1242
        rlist: a map with node names as keys and OS objects as values
1243

1244
      Returns:
1245
        map: a map with osnames as keys and as value another map, with
1246
             nodes as
1247
             keys and list of OS objects as values
1248
             e.g. {"debian-etch": {"node1": [<object>,...],
1249
                                   "node2": [<object>,]}
1250
                  }
1251

1252
    """
1253
    all_os = {}
1254
    for node_name, nr in rlist.iteritems():
1255
      if not nr:
1256
        continue
1257
      for os_obj in nr:
1258
        if os_obj.name not in all_os:
1259
          # build a list of nodes for this os containing empty lists
1260
          # for each node in node_list
1261
          all_os[os_obj.name] = {}
1262
          for nname in node_list:
1263
            all_os[os_obj.name][nname] = []
1264
        all_os[os_obj.name][node_name].append(os_obj)
1265
    return all_os
1266

    
1267
  def Exec(self, feedback_fn):
1268
    """Compute the list of OSes.
1269

1270
    """
1271
    node_list = self.cfg.GetNodeList()
1272
    node_data = rpc.call_os_diagnose(node_list)
1273
    if node_data == False:
1274
      raise errors.OpExecError("Can't gather the list of OSes")
1275
    pol = self._DiagnoseByOS(node_list, node_data)
1276
    output = []
1277
    for os_name, os_data in pol.iteritems():
1278
      row = []
1279
      for field in self.op.output_fields:
1280
        if field == "name":
1281
          val = os_name
1282
        elif field == "valid":
1283
          val = utils.all([osl and osl[0] for osl in os_data.values()])
1284
        elif field == "node_status":
1285
          val = {}
1286
          for node_name, nos_list in os_data.iteritems():
1287
            val[node_name] = [(v.status, v.path) for v in nos_list]
1288
        else:
1289
          raise errors.ParameterError(field)
1290
        row.append(val)
1291
      output.append(row)
1292

    
1293
    return output
1294

    
1295

    
1296
class LURemoveNode(LogicalUnit):
1297
  """Logical unit for removing a node.
1298

1299
  """
1300
  HPATH = "node-remove"
1301
  HTYPE = constants.HTYPE_NODE
1302
  _OP_REQP = ["node_name"]
1303

    
1304
  def BuildHooksEnv(self):
1305
    """Build hooks env.
1306

1307
    This doesn't run on the target node in the pre phase as a failed
1308
    node would then be impossible to remove.
1309

1310
    """
1311
    env = {
1312
      "OP_TARGET": self.op.node_name,
1313
      "NODE_NAME": self.op.node_name,
1314
      }
1315
    all_nodes = self.cfg.GetNodeList()
1316
    all_nodes.remove(self.op.node_name)
1317
    return env, all_nodes, all_nodes
1318

    
1319
  def CheckPrereq(self):
1320
    """Check prerequisites.
1321

1322
    This checks:
1323
     - the node exists in the configuration
1324
     - it does not have primary or secondary instances
1325
     - it's not the master
1326

1327
    Any errors are signalled by raising errors.OpPrereqError.
1328

1329
    """
1330
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
1331
    if node is None:
1332
      raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name)
1333

    
1334
    instance_list = self.cfg.GetInstanceList()
1335

    
1336
    masternode = self.sstore.GetMasterNode()
1337
    if node.name == masternode:
1338
      raise errors.OpPrereqError("Node is the master node,"
1339
                                 " you need to failover first.")
1340

    
1341
    for instance_name in instance_list:
1342
      instance = self.cfg.GetInstanceInfo(instance_name)
1343
      if node.name == instance.primary_node:
1344
        raise errors.OpPrereqError("Instance %s still running on the node,"
1345
                                   " please remove first." % instance_name)
1346
      if node.name in instance.secondary_nodes:
1347
        raise errors.OpPrereqError("Instance %s has node as a secondary,"
1348
                                   " please remove first." % instance_name)
1349
    self.op.node_name = node.name
1350
    self.node = node
1351

    
1352
  def Exec(self, feedback_fn):
1353
    """Removes the node from the cluster.
1354

1355
    """
1356
    node = self.node
1357
    logger.Info("stopping the node daemon and removing configs from node %s" %
1358
                node.name)
1359

    
1360
    rpc.call_node_leave_cluster(node.name)
1361

    
1362
    logger.Info("Removing node %s from config" % node.name)
1363

    
1364
    self.cfg.RemoveNode(node.name)
1365
    # Remove the node from the Ganeti Lock Manager
1366
    self.context.glm.remove(locking.LEVEL_NODE, node.name)
1367

    
1368
    utils.RemoveHostFromEtcHosts(node.name)
1369

    
1370

    
1371
class LUQueryNodes(NoHooksLU):
1372
  """Logical unit for querying nodes.
1373

1374
  """
1375
  _OP_REQP = ["output_fields", "names"]
1376

    
1377
  def CheckPrereq(self):
1378
    """Check prerequisites.
1379

1380
    This checks that the fields required are valid output fields.
1381

1382
    """
1383
    self.dynamic_fields = frozenset([
1384
      "dtotal", "dfree",
1385
      "mtotal", "mnode", "mfree",
1386
      "bootid",
1387
      "ctotal",
1388
      ])
1389

    
1390
    _CheckOutputFields(static=["name", "pinst_cnt", "sinst_cnt",
1391
                               "pinst_list", "sinst_list",
1392
                               "pip", "sip", "tags"],
1393
                       dynamic=self.dynamic_fields,
1394
                       selected=self.op.output_fields)
1395

    
1396
    self.wanted = _GetWantedNodes(self, self.op.names)
1397

    
1398
  def Exec(self, feedback_fn):
1399
    """Computes the list of nodes and their attributes.
1400

1401
    """
1402
    nodenames = self.wanted
1403
    nodelist = [self.cfg.GetNodeInfo(name) for name in nodenames]
1404

    
1405
    # begin data gathering
1406

    
1407
    if self.dynamic_fields.intersection(self.op.output_fields):
1408
      live_data = {}
1409
      node_data = rpc.call_node_info(nodenames, self.cfg.GetVGName())
1410
      for name in nodenames:
1411
        nodeinfo = node_data.get(name, None)
1412
        if nodeinfo:
1413
          live_data[name] = {
1414
            "mtotal": utils.TryConvert(int, nodeinfo['memory_total']),
1415
            "mnode": utils.TryConvert(int, nodeinfo['memory_dom0']),
1416
            "mfree": utils.TryConvert(int, nodeinfo['memory_free']),
1417
            "dtotal": utils.TryConvert(int, nodeinfo['vg_size']),
1418
            "dfree": utils.TryConvert(int, nodeinfo['vg_free']),
1419
            "ctotal": utils.TryConvert(int, nodeinfo['cpu_total']),
1420
            "bootid": nodeinfo['bootid'],
1421
            }
1422
        else:
1423
          live_data[name] = {}
1424
    else:
1425
      live_data = dict.fromkeys(nodenames, {})
1426

    
1427
    node_to_primary = dict([(name, set()) for name in nodenames])
1428
    node_to_secondary = dict([(name, set()) for name in nodenames])
1429

    
1430
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
1431
                             "sinst_cnt", "sinst_list"))
1432
    if inst_fields & frozenset(self.op.output_fields):
1433
      instancelist = self.cfg.GetInstanceList()
1434

    
1435
      for instance_name in instancelist:
1436
        inst = self.cfg.GetInstanceInfo(instance_name)
1437
        if inst.primary_node in node_to_primary:
1438
          node_to_primary[inst.primary_node].add(inst.name)
1439
        for secnode in inst.secondary_nodes:
1440
          if secnode in node_to_secondary:
1441
            node_to_secondary[secnode].add(inst.name)
1442

    
1443
    # end data gathering
1444

    
1445
    output = []
1446
    for node in nodelist:
1447
      node_output = []
1448
      for field in self.op.output_fields:
1449
        if field == "name":
1450
          val = node.name
1451
        elif field == "pinst_list":
1452
          val = list(node_to_primary[node.name])
1453
        elif field == "sinst_list":
1454
          val = list(node_to_secondary[node.name])
1455
        elif field == "pinst_cnt":
1456
          val = len(node_to_primary[node.name])
1457
        elif field == "sinst_cnt":
1458
          val = len(node_to_secondary[node.name])
1459
        elif field == "pip":
1460
          val = node.primary_ip
1461
        elif field == "sip":
1462
          val = node.secondary_ip
1463
        elif field == "tags":
1464
          val = list(node.GetTags())
1465
        elif field in self.dynamic_fields:
1466
          val = live_data[node.name].get(field, None)
1467
        else:
1468
          raise errors.ParameterError(field)
1469
        node_output.append(val)
1470
      output.append(node_output)
1471

    
1472
    return output
1473

    
1474

    
1475
class LUQueryNodeVolumes(NoHooksLU):
1476
  """Logical unit for getting volumes on node(s).
1477

1478
  """
1479
  _OP_REQP = ["nodes", "output_fields"]
1480

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

1484
    This checks that the fields required are valid output fields.
1485

1486
    """
1487
    self.nodes = _GetWantedNodes(self, self.op.nodes)
1488

    
1489
    _CheckOutputFields(static=["node"],
1490
                       dynamic=["phys", "vg", "name", "size", "instance"],
1491
                       selected=self.op.output_fields)
1492

    
1493

    
1494
  def Exec(self, feedback_fn):
1495
    """Computes the list of nodes and their attributes.
1496

1497
    """
1498
    nodenames = self.nodes
1499
    volumes = rpc.call_node_volumes(nodenames)
1500

    
1501
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
1502
             in self.cfg.GetInstanceList()]
1503

    
1504
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
1505

    
1506
    output = []
1507
    for node in nodenames:
1508
      if node not in volumes or not volumes[node]:
1509
        continue
1510

    
1511
      node_vols = volumes[node][:]
1512
      node_vols.sort(key=lambda vol: vol['dev'])
1513

    
1514
      for vol in node_vols:
1515
        node_output = []
1516
        for field in self.op.output_fields:
1517
          if field == "node":
1518
            val = node
1519
          elif field == "phys":
1520
            val = vol['dev']
1521
          elif field == "vg":
1522
            val = vol['vg']
1523
          elif field == "name":
1524
            val = vol['name']
1525
          elif field == "size":
1526
            val = int(float(vol['size']))
1527
          elif field == "instance":
1528
            for inst in ilist:
1529
              if node not in lv_by_node[inst]:
1530
                continue
1531
              if vol['name'] in lv_by_node[inst][node]:
1532
                val = inst.name
1533
                break
1534
            else:
1535
              val = '-'
1536
          else:
1537
            raise errors.ParameterError(field)
1538
          node_output.append(str(val))
1539

    
1540
        output.append(node_output)
1541

    
1542
    return output
1543

    
1544

    
1545
class LUAddNode(LogicalUnit):
1546
  """Logical unit for adding node to the cluster.
1547

1548
  """
1549
  HPATH = "node-add"
1550
  HTYPE = constants.HTYPE_NODE
1551
  _OP_REQP = ["node_name"]
1552

    
1553
  def BuildHooksEnv(self):
1554
    """Build hooks env.
1555

1556
    This will run on all nodes before, and on all nodes + the new node after.
1557

1558
    """
1559
    env = {
1560
      "OP_TARGET": self.op.node_name,
1561
      "NODE_NAME": self.op.node_name,
1562
      "NODE_PIP": self.op.primary_ip,
1563
      "NODE_SIP": self.op.secondary_ip,
1564
      }
1565
    nodes_0 = self.cfg.GetNodeList()
1566
    nodes_1 = nodes_0 + [self.op.node_name, ]
1567
    return env, nodes_0, nodes_1
1568

    
1569
  def CheckPrereq(self):
1570
    """Check prerequisites.
1571

1572
    This checks:
1573
     - the new node is not already in the config
1574
     - it is resolvable
1575
     - its parameters (single/dual homed) matches the cluster
1576

1577
    Any errors are signalled by raising errors.OpPrereqError.
1578

1579
    """
1580
    node_name = self.op.node_name
1581
    cfg = self.cfg
1582

    
1583
    dns_data = utils.HostInfo(node_name)
1584

    
1585
    node = dns_data.name
1586
    primary_ip = self.op.primary_ip = dns_data.ip
1587
    secondary_ip = getattr(self.op, "secondary_ip", None)
1588
    if secondary_ip is None:
1589
      secondary_ip = primary_ip
1590
    if not utils.IsValidIP(secondary_ip):
1591
      raise errors.OpPrereqError("Invalid secondary IP given")
1592
    self.op.secondary_ip = secondary_ip
1593

    
1594
    node_list = cfg.GetNodeList()
1595
    if not self.op.readd and node in node_list:
1596
      raise errors.OpPrereqError("Node %s is already in the configuration" %
1597
                                 node)
1598
    elif self.op.readd and node not in node_list:
1599
      raise errors.OpPrereqError("Node %s is not in the configuration" % node)
1600

    
1601
    for existing_node_name in node_list:
1602
      existing_node = cfg.GetNodeInfo(existing_node_name)
1603

    
1604
      if self.op.readd and node == existing_node_name:
1605
        if (existing_node.primary_ip != primary_ip or
1606
            existing_node.secondary_ip != secondary_ip):
1607
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
1608
                                     " address configuration as before")
1609
        continue
1610

    
1611
      if (existing_node.primary_ip == primary_ip or
1612
          existing_node.secondary_ip == primary_ip or
1613
          existing_node.primary_ip == secondary_ip or
1614
          existing_node.secondary_ip == secondary_ip):
1615
        raise errors.OpPrereqError("New node ip address(es) conflict with"
1616
                                   " existing node %s" % existing_node.name)
1617

    
1618
    # check that the type of the node (single versus dual homed) is the
1619
    # same as for the master
1620
    myself = cfg.GetNodeInfo(self.sstore.GetMasterNode())
1621
    master_singlehomed = myself.secondary_ip == myself.primary_ip
1622
    newbie_singlehomed = secondary_ip == primary_ip
1623
    if master_singlehomed != newbie_singlehomed:
1624
      if master_singlehomed:
1625
        raise errors.OpPrereqError("The master has no private ip but the"
1626
                                   " new node has one")
1627
      else:
1628
        raise errors.OpPrereqError("The master has a private ip but the"
1629
                                   " new node doesn't have one")
1630

    
1631
    # checks reachablity
1632
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
1633
      raise errors.OpPrereqError("Node not reachable by ping")
1634

    
1635
    if not newbie_singlehomed:
1636
      # check reachability from my secondary ip to newbie's secondary ip
1637
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
1638
                           source=myself.secondary_ip):
1639
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
1640
                                   " based ping to noded port")
1641

    
1642
    self.new_node = objects.Node(name=node,
1643
                                 primary_ip=primary_ip,
1644
                                 secondary_ip=secondary_ip)
1645

    
1646
  def Exec(self, feedback_fn):
1647
    """Adds the new node to the cluster.
1648

1649
    """
1650
    new_node = self.new_node
1651
    node = new_node.name
1652

    
1653
    # check connectivity
1654
    result = rpc.call_version([node])[node]
1655
    if result:
1656
      if constants.PROTOCOL_VERSION == result:
1657
        logger.Info("communication to node %s fine, sw version %s match" %
1658
                    (node, result))
1659
      else:
1660
        raise errors.OpExecError("Version mismatch master version %s,"
1661
                                 " node version %s" %
1662
                                 (constants.PROTOCOL_VERSION, result))
1663
    else:
1664
      raise errors.OpExecError("Cannot get version from the new node")
1665

    
1666
    # setup ssh on node
1667
    logger.Info("copy ssh key to node %s" % node)
1668
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
1669
    keyarray = []
1670
    keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
1671
                constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
1672
                priv_key, pub_key]
1673

    
1674
    for i in keyfiles:
1675
      f = open(i, 'r')
1676
      try:
1677
        keyarray.append(f.read())
1678
      finally:
1679
        f.close()
1680

    
1681
    result = rpc.call_node_add(node, keyarray[0], keyarray[1], keyarray[2],
1682
                               keyarray[3], keyarray[4], keyarray[5])
1683

    
1684
    if not result:
1685
      raise errors.OpExecError("Cannot transfer ssh keys to the new node")
1686

    
1687
    # Add node to our /etc/hosts, and add key to known_hosts
1688
    utils.AddHostToEtcHosts(new_node.name)
1689

    
1690
    if new_node.secondary_ip != new_node.primary_ip:
1691
      if not rpc.call_node_tcp_ping(new_node.name,
1692
                                    constants.LOCALHOST_IP_ADDRESS,
1693
                                    new_node.secondary_ip,
1694
                                    constants.DEFAULT_NODED_PORT,
1695
                                    10, False):
1696
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
1697
                                 " you gave (%s). Please fix and re-run this"
1698
                                 " command." % new_node.secondary_ip)
1699

    
1700
    node_verify_list = [self.sstore.GetMasterNode()]
1701
    node_verify_param = {
1702
      'nodelist': [node],
1703
      # TODO: do a node-net-test as well?
1704
    }
1705

    
1706
    result = rpc.call_node_verify(node_verify_list, node_verify_param)
1707
    for verifier in node_verify_list:
1708
      if not result[verifier]:
1709
        raise errors.OpExecError("Cannot communicate with %s's node daemon"
1710
                                 " for remote verification" % verifier)
1711
      if result[verifier]['nodelist']:
1712
        for failed in result[verifier]['nodelist']:
1713
          feedback_fn("ssh/hostname verification failed %s -> %s" %
1714
                      (verifier, result[verifier]['nodelist'][failed]))
1715
        raise errors.OpExecError("ssh/hostname verification failed.")
1716

    
1717
    # Distribute updated /etc/hosts and known_hosts to all nodes,
1718
    # including the node just added
1719
    myself = self.cfg.GetNodeInfo(self.sstore.GetMasterNode())
1720
    dist_nodes = self.cfg.GetNodeList()
1721
    if not self.op.readd:
1722
      dist_nodes.append(node)
1723
    if myself.name in dist_nodes:
1724
      dist_nodes.remove(myself.name)
1725

    
1726
    logger.Debug("Copying hosts and known_hosts to all nodes")
1727
    for fname in (constants.ETC_HOSTS, constants.SSH_KNOWN_HOSTS_FILE):
1728
      result = rpc.call_upload_file(dist_nodes, fname)
1729
      for to_node in dist_nodes:
1730
        if not result[to_node]:
1731
          logger.Error("copy of file %s to node %s failed" %
1732
                       (fname, to_node))
1733

    
1734
    to_copy = self.sstore.GetFileList()
1735
    if self.sstore.GetHypervisorType() == constants.HT_XEN_HVM31:
1736
      to_copy.append(constants.VNC_PASSWORD_FILE)
1737
    for fname in to_copy:
1738
      result = rpc.call_upload_file([node], fname)
1739
      if not result[node]:
1740
        logger.Error("could not copy file %s to node %s" % (fname, node))
1741

    
1742
    if not self.op.readd:
1743
      logger.Info("adding node %s to cluster.conf" % node)
1744
      self.cfg.AddNode(new_node)
1745
      # Add the new node to the Ganeti Lock Manager
1746
      self.context.glm.add(locking.LEVEL_NODE, node)
1747

    
1748

    
1749
class LUQueryClusterInfo(NoHooksLU):
1750
  """Query cluster configuration.
1751

1752
  """
1753
  _OP_REQP = []
1754
  REQ_MASTER = False
1755
  REQ_BGL = False
1756

    
1757
  def ExpandNames(self):
1758
    self.needed_locks = {}
1759

    
1760
  def CheckPrereq(self):
1761
    """No prerequsites needed for this LU.
1762

1763
    """
1764
    pass
1765

    
1766
  def Exec(self, feedback_fn):
1767
    """Return cluster config.
1768

1769
    """
1770
    result = {
1771
      "name": self.sstore.GetClusterName(),
1772
      "software_version": constants.RELEASE_VERSION,
1773
      "protocol_version": constants.PROTOCOL_VERSION,
1774
      "config_version": constants.CONFIG_VERSION,
1775
      "os_api_version": constants.OS_API_VERSION,
1776
      "export_version": constants.EXPORT_VERSION,
1777
      "master": self.sstore.GetMasterNode(),
1778
      "architecture": (platform.architecture()[0], platform.machine()),
1779
      "hypervisor_type": self.sstore.GetHypervisorType(),
1780
      }
1781

    
1782
    return result
1783

    
1784

    
1785
class LUDumpClusterConfig(NoHooksLU):
1786
  """Return a text-representation of the cluster-config.
1787

1788
  """
1789
  _OP_REQP = []
1790
  REQ_BGL = False
1791

    
1792
  def ExpandNames(self):
1793
    self.needed_locks = {}
1794

    
1795
  def CheckPrereq(self):
1796
    """No prerequisites.
1797

1798
    """
1799
    pass
1800

    
1801
  def Exec(self, feedback_fn):
1802
    """Dump a representation of the cluster config to the standard output.
1803

1804
    """
1805
    return self.cfg.DumpConfig()
1806

    
1807

    
1808
class LUActivateInstanceDisks(NoHooksLU):
1809
  """Bring up an instance's disks.
1810

1811
  """
1812
  _OP_REQP = ["instance_name"]
1813

    
1814
  def CheckPrereq(self):
1815
    """Check prerequisites.
1816

1817
    This checks that the instance is in the cluster.
1818

1819
    """
1820
    instance = self.cfg.GetInstanceInfo(
1821
      self.cfg.ExpandInstanceName(self.op.instance_name))
1822
    if instance is None:
1823
      raise errors.OpPrereqError("Instance '%s' not known" %
1824
                                 self.op.instance_name)
1825
    self.instance = instance
1826

    
1827

    
1828
  def Exec(self, feedback_fn):
1829
    """Activate the disks.
1830

1831
    """
1832
    disks_ok, disks_info = _AssembleInstanceDisks(self.instance, self.cfg)
1833
    if not disks_ok:
1834
      raise errors.OpExecError("Cannot activate block devices")
1835

    
1836
    return disks_info
1837

    
1838

    
1839
def _AssembleInstanceDisks(instance, cfg, ignore_secondaries=False):
1840
  """Prepare the block devices for an instance.
1841

1842
  This sets up the block devices on all nodes.
1843

1844
  Args:
1845
    instance: a ganeti.objects.Instance object
1846
    ignore_secondaries: if true, errors on secondary nodes won't result
1847
                        in an error return from the function
1848

1849
  Returns:
1850
    false if the operation failed
1851
    list of (host, instance_visible_name, node_visible_name) if the operation
1852
         suceeded with the mapping from node devices to instance devices
1853
  """
1854
  device_info = []
1855
  disks_ok = True
1856
  iname = instance.name
1857
  # With the two passes mechanism we try to reduce the window of
1858
  # opportunity for the race condition of switching DRBD to primary
1859
  # before handshaking occured, but we do not eliminate it
1860

    
1861
  # The proper fix would be to wait (with some limits) until the
1862
  # connection has been made and drbd transitions from WFConnection
1863
  # into any other network-connected state (Connected, SyncTarget,
1864
  # SyncSource, etc.)
1865

    
1866
  # 1st pass, assemble on all nodes in secondary mode
1867
  for inst_disk in instance.disks:
1868
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
1869
      cfg.SetDiskID(node_disk, node)
1870
      result = rpc.call_blockdev_assemble(node, node_disk, iname, False)
1871
      if not result:
1872
        logger.Error("could not prepare block device %s on node %s"
1873
                     " (is_primary=False, pass=1)" % (inst_disk.iv_name, node))
1874
        if not ignore_secondaries:
1875
          disks_ok = False
1876

    
1877
  # FIXME: race condition on drbd migration to primary
1878

    
1879
  # 2nd pass, do only the primary node
1880
  for inst_disk in instance.disks:
1881
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
1882
      if node != instance.primary_node:
1883
        continue
1884
      cfg.SetDiskID(node_disk, node)
1885
      result = rpc.call_blockdev_assemble(node, node_disk, iname, True)
1886
      if not result:
1887
        logger.Error("could not prepare block device %s on node %s"
1888
                     " (is_primary=True, pass=2)" % (inst_disk.iv_name, node))
1889
        disks_ok = False
1890
    device_info.append((instance.primary_node, inst_disk.iv_name, result))
1891

    
1892
  # leave the disks configured for the primary node
1893
  # this is a workaround that would be fixed better by
1894
  # improving the logical/physical id handling
1895
  for disk in instance.disks:
1896
    cfg.SetDiskID(disk, instance.primary_node)
1897

    
1898
  return disks_ok, device_info
1899

    
1900

    
1901
def _StartInstanceDisks(cfg, instance, force):
1902
  """Start the disks of an instance.
1903

1904
  """
1905
  disks_ok, dummy = _AssembleInstanceDisks(instance, cfg,
1906
                                           ignore_secondaries=force)
1907
  if not disks_ok:
1908
    _ShutdownInstanceDisks(instance, cfg)
1909
    if force is not None and not force:
1910
      logger.Error("If the message above refers to a secondary node,"
1911
                   " you can retry the operation using '--force'.")
1912
    raise errors.OpExecError("Disk consistency error")
1913

    
1914

    
1915
class LUDeactivateInstanceDisks(NoHooksLU):
1916
  """Shutdown an instance's disks.
1917

1918
  """
1919
  _OP_REQP = ["instance_name"]
1920

    
1921
  def CheckPrereq(self):
1922
    """Check prerequisites.
1923

1924
    This checks that the instance is in the cluster.
1925

1926
    """
1927
    instance = self.cfg.GetInstanceInfo(
1928
      self.cfg.ExpandInstanceName(self.op.instance_name))
1929
    if instance is None:
1930
      raise errors.OpPrereqError("Instance '%s' not known" %
1931
                                 self.op.instance_name)
1932
    self.instance = instance
1933

    
1934
  def Exec(self, feedback_fn):
1935
    """Deactivate the disks
1936

1937
    """
1938
    instance = self.instance
1939
    ins_l = rpc.call_instance_list([instance.primary_node])
1940
    ins_l = ins_l[instance.primary_node]
1941
    if not type(ins_l) is list:
1942
      raise errors.OpExecError("Can't contact node '%s'" %
1943
                               instance.primary_node)
1944

    
1945
    if self.instance.name in ins_l:
1946
      raise errors.OpExecError("Instance is running, can't shutdown"
1947
                               " block devices.")
1948

    
1949
    _ShutdownInstanceDisks(instance, self.cfg)
1950

    
1951

    
1952
def _ShutdownInstanceDisks(instance, cfg, ignore_primary=False):
1953
  """Shutdown block devices of an instance.
1954

1955
  This does the shutdown on all nodes of the instance.
1956

1957
  If the ignore_primary is false, errors on the primary node are
1958
  ignored.
1959

1960
  """
1961
  result = True
1962
  for disk in instance.disks:
1963
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
1964
      cfg.SetDiskID(top_disk, node)
1965
      if not rpc.call_blockdev_shutdown(node, top_disk):
1966
        logger.Error("could not shutdown block device %s on node %s" %
1967
                     (disk.iv_name, node))
1968
        if not ignore_primary or node != instance.primary_node:
1969
          result = False
1970
  return result
1971

    
1972

    
1973
def _CheckNodeFreeMemory(cfg, node, reason, requested):
1974
  """Checks if a node has enough free memory.
1975

1976
  This function check if a given node has the needed amount of free
1977
  memory. In case the node has less memory or we cannot get the
1978
  information from the node, this function raise an OpPrereqError
1979
  exception.
1980

1981
  Args:
1982
    - cfg: a ConfigWriter instance
1983
    - node: the node name
1984
    - reason: string to use in the error message
1985
    - requested: the amount of memory in MiB
1986

1987
  """
1988
  nodeinfo = rpc.call_node_info([node], cfg.GetVGName())
1989
  if not nodeinfo or not isinstance(nodeinfo, dict):
1990
    raise errors.OpPrereqError("Could not contact node %s for resource"
1991
                             " information" % (node,))
1992

    
1993
  free_mem = nodeinfo[node].get('memory_free')
1994
  if not isinstance(free_mem, int):
1995
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
1996
                             " was '%s'" % (node, free_mem))
1997
  if requested > free_mem:
1998
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
1999
                             " needed %s MiB, available %s MiB" %
2000
                             (node, reason, requested, free_mem))
2001

    
2002

    
2003
class LUStartupInstance(LogicalUnit):
2004
  """Starts an instance.
2005

2006
  """
2007
  HPATH = "instance-start"
2008
  HTYPE = constants.HTYPE_INSTANCE
2009
  _OP_REQP = ["instance_name", "force"]
2010

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

2014
    This runs on master, primary and secondary nodes of the instance.
2015

2016
    """
2017
    env = {
2018
      "FORCE": self.op.force,
2019
      }
2020
    env.update(_BuildInstanceHookEnvByObject(self.instance))
2021
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2022
          list(self.instance.secondary_nodes))
2023
    return env, nl, nl
2024

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

2028
    This checks that the instance is in the cluster.
2029

2030
    """
2031
    instance = self.cfg.GetInstanceInfo(
2032
      self.cfg.ExpandInstanceName(self.op.instance_name))
2033
    if instance is None:
2034
      raise errors.OpPrereqError("Instance '%s' not known" %
2035
                                 self.op.instance_name)
2036

    
2037
    # check bridges existance
2038
    _CheckInstanceBridgesExist(instance)
2039

    
2040
    _CheckNodeFreeMemory(self.cfg, instance.primary_node,
2041
                         "starting instance %s" % instance.name,
2042
                         instance.memory)
2043

    
2044
    self.instance = instance
2045
    self.op.instance_name = instance.name
2046

    
2047
  def Exec(self, feedback_fn):
2048
    """Start the instance.
2049

2050
    """
2051
    instance = self.instance
2052
    force = self.op.force
2053
    extra_args = getattr(self.op, "extra_args", "")
2054

    
2055
    self.cfg.MarkInstanceUp(instance.name)
2056

    
2057
    node_current = instance.primary_node
2058

    
2059
    _StartInstanceDisks(self.cfg, instance, force)
2060

    
2061
    if not rpc.call_instance_start(node_current, instance, extra_args):
2062
      _ShutdownInstanceDisks(instance, self.cfg)
2063
      raise errors.OpExecError("Could not start instance")
2064

    
2065

    
2066
class LURebootInstance(LogicalUnit):
2067
  """Reboot an instance.
2068

2069
  """
2070
  HPATH = "instance-reboot"
2071
  HTYPE = constants.HTYPE_INSTANCE
2072
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
2073

    
2074
  def BuildHooksEnv(self):
2075
    """Build hooks env.
2076

2077
    This runs on master, primary and secondary nodes of the instance.
2078

2079
    """
2080
    env = {
2081
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
2082
      }
2083
    env.update(_BuildInstanceHookEnvByObject(self.instance))
2084
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2085
          list(self.instance.secondary_nodes))
2086
    return env, nl, nl
2087

    
2088
  def CheckPrereq(self):
2089
    """Check prerequisites.
2090

2091
    This checks that the instance is in the cluster.
2092

2093
    """
2094
    instance = self.cfg.GetInstanceInfo(
2095
      self.cfg.ExpandInstanceName(self.op.instance_name))
2096
    if instance is None:
2097
      raise errors.OpPrereqError("Instance '%s' not known" %
2098
                                 self.op.instance_name)
2099

    
2100
    # check bridges existance
2101
    _CheckInstanceBridgesExist(instance)
2102

    
2103
    self.instance = instance
2104
    self.op.instance_name = instance.name
2105

    
2106
  def Exec(self, feedback_fn):
2107
    """Reboot the instance.
2108

2109
    """
2110
    instance = self.instance
2111
    ignore_secondaries = self.op.ignore_secondaries
2112
    reboot_type = self.op.reboot_type
2113
    extra_args = getattr(self.op, "extra_args", "")
2114

    
2115
    node_current = instance.primary_node
2116

    
2117
    if reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
2118
                           constants.INSTANCE_REBOOT_HARD,
2119
                           constants.INSTANCE_REBOOT_FULL]:
2120
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
2121
                                  (constants.INSTANCE_REBOOT_SOFT,
2122
                                   constants.INSTANCE_REBOOT_HARD,
2123
                                   constants.INSTANCE_REBOOT_FULL))
2124

    
2125
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
2126
                       constants.INSTANCE_REBOOT_HARD]:
2127
      if not rpc.call_instance_reboot(node_current, instance,
2128
                                      reboot_type, extra_args):
2129
        raise errors.OpExecError("Could not reboot instance")
2130
    else:
2131
      if not rpc.call_instance_shutdown(node_current, instance):
2132
        raise errors.OpExecError("could not shutdown instance for full reboot")
2133
      _ShutdownInstanceDisks(instance, self.cfg)
2134
      _StartInstanceDisks(self.cfg, instance, ignore_secondaries)
2135
      if not rpc.call_instance_start(node_current, instance, extra_args):
2136
        _ShutdownInstanceDisks(instance, self.cfg)
2137
        raise errors.OpExecError("Could not start instance for full reboot")
2138

    
2139
    self.cfg.MarkInstanceUp(instance.name)
2140

    
2141

    
2142
class LUShutdownInstance(LogicalUnit):
2143
  """Shutdown an instance.
2144

2145
  """
2146
  HPATH = "instance-stop"
2147
  HTYPE = constants.HTYPE_INSTANCE
2148
  _OP_REQP = ["instance_name"]
2149

    
2150
  def BuildHooksEnv(self):
2151
    """Build hooks env.
2152

2153
    This runs on master, primary and secondary nodes of the instance.
2154

2155
    """
2156
    env = _BuildInstanceHookEnvByObject(self.instance)
2157
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2158
          list(self.instance.secondary_nodes))
2159
    return env, nl, nl
2160

    
2161
  def CheckPrereq(self):
2162
    """Check prerequisites.
2163

2164
    This checks that the instance is in the cluster.
2165

2166
    """
2167
    instance = self.cfg.GetInstanceInfo(
2168
      self.cfg.ExpandInstanceName(self.op.instance_name))
2169
    if instance is None:
2170
      raise errors.OpPrereqError("Instance '%s' not known" %
2171
                                 self.op.instance_name)
2172
    self.instance = instance
2173

    
2174
  def Exec(self, feedback_fn):
2175
    """Shutdown the instance.
2176

2177
    """
2178
    instance = self.instance
2179
    node_current = instance.primary_node
2180
    self.cfg.MarkInstanceDown(instance.name)
2181
    if not rpc.call_instance_shutdown(node_current, instance):
2182
      logger.Error("could not shutdown instance")
2183

    
2184
    _ShutdownInstanceDisks(instance, self.cfg)
2185

    
2186

    
2187
class LUReinstallInstance(LogicalUnit):
2188
  """Reinstall an instance.
2189

2190
  """
2191
  HPATH = "instance-reinstall"
2192
  HTYPE = constants.HTYPE_INSTANCE
2193
  _OP_REQP = ["instance_name"]
2194
  REQ_BGL = False
2195

    
2196
  def ExpandNames(self):
2197
    self._ExpandAndLockInstance()
2198
    self.needed_locks[locking.LEVEL_NODE] = []
2199
    self.recalculate_locks[locking.LEVEL_NODE] = 'replace'
2200

    
2201
  def DeclareLocks(self, level):
2202
    if level == locking.LEVEL_NODE:
2203
      self._LockInstancesNodes()
2204

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

2208
    This runs on master, primary and secondary nodes of the instance.
2209

2210
    """
2211
    env = _BuildInstanceHookEnvByObject(self.instance)
2212
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2213
          list(self.instance.secondary_nodes))
2214
    return env, nl, nl
2215

    
2216
  def CheckPrereq(self):
2217
    """Check prerequisites.
2218

2219
    This checks that the instance is in the cluster and is not running.
2220

2221
    """
2222
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2223
    assert instance is not None, \
2224
      "Cannot retrieve locked instance %s" % self.op.instance_name
2225

    
2226
    if instance.disk_template == constants.DT_DISKLESS:
2227
      raise errors.OpPrereqError("Instance '%s' has no disks" %
2228
                                 self.op.instance_name)
2229
    if instance.status != "down":
2230
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2231
                                 self.op.instance_name)
2232
    remote_info = rpc.call_instance_info(instance.primary_node, instance.name)
2233
    if remote_info:
2234
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2235
                                 (self.op.instance_name,
2236
                                  instance.primary_node))
2237

    
2238
    self.op.os_type = getattr(self.op, "os_type", None)
2239
    if self.op.os_type is not None:
2240
      # OS verification
2241
      pnode = self.cfg.GetNodeInfo(
2242
        self.cfg.ExpandNodeName(instance.primary_node))
2243
      if pnode is None:
2244
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
2245
                                   self.op.pnode)
2246
      os_obj = rpc.call_os_get(pnode.name, self.op.os_type)
2247
      if not os_obj:
2248
        raise errors.OpPrereqError("OS '%s' not in supported OS list for"
2249
                                   " primary node"  % self.op.os_type)
2250

    
2251
    self.instance = instance
2252

    
2253
  def Exec(self, feedback_fn):
2254
    """Reinstall the instance.
2255

2256
    """
2257
    inst = self.instance
2258

    
2259
    if self.op.os_type is not None:
2260
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
2261
      inst.os = self.op.os_type
2262
      self.cfg.AddInstance(inst)
2263

    
2264
    _StartInstanceDisks(self.cfg, inst, None)
2265
    try:
2266
      feedback_fn("Running the instance OS create scripts...")
2267
      if not rpc.call_instance_os_add(inst.primary_node, inst, "sda", "sdb"):
2268
        raise errors.OpExecError("Could not install OS for instance %s"
2269
                                 " on node %s" %
2270
                                 (inst.name, inst.primary_node))
2271
    finally:
2272
      _ShutdownInstanceDisks(inst, self.cfg)
2273

    
2274

    
2275
class LURenameInstance(LogicalUnit):
2276
  """Rename an instance.
2277

2278
  """
2279
  HPATH = "instance-rename"
2280
  HTYPE = constants.HTYPE_INSTANCE
2281
  _OP_REQP = ["instance_name", "new_name"]
2282

    
2283
  def BuildHooksEnv(self):
2284
    """Build hooks env.
2285

2286
    This runs on master, primary and secondary nodes of the instance.
2287

2288
    """
2289
    env = _BuildInstanceHookEnvByObject(self.instance)
2290
    env["INSTANCE_NEW_NAME"] = self.op.new_name
2291
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2292
          list(self.instance.secondary_nodes))
2293
    return env, nl, nl
2294

    
2295
  def CheckPrereq(self):
2296
    """Check prerequisites.
2297

2298
    This checks that the instance is in the cluster and is not running.
2299

2300
    """
2301
    instance = self.cfg.GetInstanceInfo(
2302
      self.cfg.ExpandInstanceName(self.op.instance_name))
2303
    if instance is None:
2304
      raise errors.OpPrereqError("Instance '%s' not known" %
2305
                                 self.op.instance_name)
2306
    if instance.status != "down":
2307
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2308
                                 self.op.instance_name)
2309
    remote_info = rpc.call_instance_info(instance.primary_node, instance.name)
2310
    if remote_info:
2311
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2312
                                 (self.op.instance_name,
2313
                                  instance.primary_node))
2314
    self.instance = instance
2315

    
2316
    # new name verification
2317
    name_info = utils.HostInfo(self.op.new_name)
2318

    
2319
    self.op.new_name = new_name = name_info.name
2320
    instance_list = self.cfg.GetInstanceList()
2321
    if new_name in instance_list:
2322
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
2323
                                 new_name)
2324

    
2325
    if not getattr(self.op, "ignore_ip", False):
2326
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
2327
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
2328
                                   (name_info.ip, new_name))
2329

    
2330

    
2331
  def Exec(self, feedback_fn):
2332
    """Reinstall the instance.
2333

2334
    """
2335
    inst = self.instance
2336
    old_name = inst.name
2337

    
2338
    if inst.disk_template == constants.DT_FILE:
2339
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2340

    
2341
    self.cfg.RenameInstance(inst.name, self.op.new_name)
2342
    # Change the instance lock. This is definitely safe while we hold the BGL
2343
    self.context.glm.remove(locking.LEVEL_INSTANCE, inst.name)
2344
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
2345

    
2346
    # re-read the instance from the configuration after rename
2347
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
2348

    
2349
    if inst.disk_template == constants.DT_FILE:
2350
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2351
      result = rpc.call_file_storage_dir_rename(inst.primary_node,
2352
                                                old_file_storage_dir,
2353
                                                new_file_storage_dir)
2354

    
2355
      if not result:
2356
        raise errors.OpExecError("Could not connect to node '%s' to rename"
2357
                                 " directory '%s' to '%s' (but the instance"
2358
                                 " has been renamed in Ganeti)" % (
2359
                                 inst.primary_node, old_file_storage_dir,
2360
                                 new_file_storage_dir))
2361

    
2362
      if not result[0]:
2363
        raise errors.OpExecError("Could not rename directory '%s' to '%s'"
2364
                                 " (but the instance has been renamed in"
2365
                                 " Ganeti)" % (old_file_storage_dir,
2366
                                               new_file_storage_dir))
2367

    
2368
    _StartInstanceDisks(self.cfg, inst, None)
2369
    try:
2370
      if not rpc.call_instance_run_rename(inst.primary_node, inst, old_name,
2371
                                          "sda", "sdb"):
2372
        msg = ("Could run OS rename script for instance %s on node %s (but the"
2373
               " instance has been renamed in Ganeti)" %
2374
               (inst.name, inst.primary_node))
2375
        logger.Error(msg)
2376
    finally:
2377
      _ShutdownInstanceDisks(inst, self.cfg)
2378

    
2379

    
2380
class LURemoveInstance(LogicalUnit):
2381
  """Remove an instance.
2382

2383
  """
2384
  HPATH = "instance-remove"
2385
  HTYPE = constants.HTYPE_INSTANCE
2386
  _OP_REQP = ["instance_name", "ignore_failures"]
2387

    
2388
  def BuildHooksEnv(self):
2389
    """Build hooks env.
2390

2391
    This runs on master, primary and secondary nodes of the instance.
2392

2393
    """
2394
    env = _BuildInstanceHookEnvByObject(self.instance)
2395
    nl = [self.sstore.GetMasterNode()]
2396
    return env, nl, nl
2397

    
2398
  def CheckPrereq(self):
2399
    """Check prerequisites.
2400

2401
    This checks that the instance is in the cluster.
2402

2403
    """
2404
    instance = self.cfg.GetInstanceInfo(
2405
      self.cfg.ExpandInstanceName(self.op.instance_name))
2406
    if instance is None:
2407
      raise errors.OpPrereqError("Instance '%s' not known" %
2408
                                 self.op.instance_name)
2409
    self.instance = instance
2410

    
2411
  def Exec(self, feedback_fn):
2412
    """Remove the instance.
2413

2414
    """
2415
    instance = self.instance
2416
    logger.Info("shutting down instance %s on node %s" %
2417
                (instance.name, instance.primary_node))
2418

    
2419
    if not rpc.call_instance_shutdown(instance.primary_node, instance):
2420
      if self.op.ignore_failures:
2421
        feedback_fn("Warning: can't shutdown instance")
2422
      else:
2423
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
2424
                                 (instance.name, instance.primary_node))
2425

    
2426
    logger.Info("removing block devices for instance %s" % instance.name)
2427

    
2428
    if not _RemoveDisks(instance, self.cfg):
2429
      if self.op.ignore_failures:
2430
        feedback_fn("Warning: can't remove instance's disks")
2431
      else:
2432
        raise errors.OpExecError("Can't remove instance's disks")
2433

    
2434
    logger.Info("removing instance %s out of cluster config" % instance.name)
2435

    
2436
    self.cfg.RemoveInstance(instance.name)
2437
    # Remove the new instance from the Ganeti Lock Manager
2438
    self.context.glm.remove(locking.LEVEL_INSTANCE, instance.name)
2439

    
2440

    
2441
class LUQueryInstances(NoHooksLU):
2442
  """Logical unit for querying instances.
2443

2444
  """
2445
  _OP_REQP = ["output_fields", "names"]
2446

    
2447
  def CheckPrereq(self):
2448
    """Check prerequisites.
2449

2450
    This checks that the fields required are valid output fields.
2451

2452
    """
2453
    self.dynamic_fields = frozenset(["oper_state", "oper_ram", "status"])
2454
    _CheckOutputFields(static=["name", "os", "pnode", "snodes",
2455
                               "admin_state", "admin_ram",
2456
                               "disk_template", "ip", "mac", "bridge",
2457
                               "sda_size", "sdb_size", "vcpus", "tags"],
2458
                       dynamic=self.dynamic_fields,
2459
                       selected=self.op.output_fields)
2460

    
2461
    self.wanted = _GetWantedInstances(self, self.op.names)
2462

    
2463
  def Exec(self, feedback_fn):
2464
    """Computes the list of nodes and their attributes.
2465

2466
    """
2467
    instance_names = self.wanted
2468
    instance_list = [self.cfg.GetInstanceInfo(iname) for iname
2469
                     in instance_names]
2470

    
2471
    # begin data gathering
2472

    
2473
    nodes = frozenset([inst.primary_node for inst in instance_list])
2474

    
2475
    bad_nodes = []
2476
    if self.dynamic_fields.intersection(self.op.output_fields):
2477
      live_data = {}
2478
      node_data = rpc.call_all_instances_info(nodes)
2479
      for name in nodes:
2480
        result = node_data[name]
2481
        if result:
2482
          live_data.update(result)
2483
        elif result == False:
2484
          bad_nodes.append(name)
2485
        # else no instance is alive
2486
    else:
2487
      live_data = dict([(name, {}) for name in instance_names])
2488

    
2489
    # end data gathering
2490

    
2491
    output = []
2492
    for instance in instance_list:
2493
      iout = []
2494
      for field in self.op.output_fields:
2495
        if field == "name":
2496
          val = instance.name
2497
        elif field == "os":
2498
          val = instance.os
2499
        elif field == "pnode":
2500
          val = instance.primary_node
2501
        elif field == "snodes":
2502
          val = list(instance.secondary_nodes)
2503
        elif field == "admin_state":
2504
          val = (instance.status != "down")
2505
        elif field == "oper_state":
2506
          if instance.primary_node in bad_nodes:
2507
            val = None
2508
          else:
2509
            val = bool(live_data.get(instance.name))
2510
        elif field == "status":
2511
          if instance.primary_node in bad_nodes:
2512
            val = "ERROR_nodedown"
2513
          else:
2514
            running = bool(live_data.get(instance.name))
2515
            if running:
2516
              if instance.status != "down":
2517
                val = "running"
2518
              else:
2519
                val = "ERROR_up"
2520
            else:
2521
              if instance.status != "down":
2522
                val = "ERROR_down"
2523
              else:
2524
                val = "ADMIN_down"
2525
        elif field == "admin_ram":
2526
          val = instance.memory
2527
        elif field == "oper_ram":
2528
          if instance.primary_node in bad_nodes:
2529
            val = None
2530
          elif instance.name in live_data:
2531
            val = live_data[instance.name].get("memory", "?")
2532
          else:
2533
            val = "-"
2534
        elif field == "disk_template":
2535
          val = instance.disk_template
2536
        elif field == "ip":
2537
          val = instance.nics[0].ip
2538
        elif field == "bridge":
2539
          val = instance.nics[0].bridge
2540
        elif field == "mac":
2541
          val = instance.nics[0].mac
2542
        elif field == "sda_size" or field == "sdb_size":
2543
          disk = instance.FindDisk(field[:3])
2544
          if disk is None:
2545
            val = None
2546
          else:
2547
            val = disk.size
2548
        elif field == "vcpus":
2549
          val = instance.vcpus
2550
        elif field == "tags":
2551
          val = list(instance.GetTags())
2552
        else:
2553
          raise errors.ParameterError(field)
2554
        iout.append(val)
2555
      output.append(iout)
2556

    
2557
    return output
2558

    
2559

    
2560
class LUFailoverInstance(LogicalUnit):
2561
  """Failover an instance.
2562

2563
  """
2564
  HPATH = "instance-failover"
2565
  HTYPE = constants.HTYPE_INSTANCE
2566
  _OP_REQP = ["instance_name", "ignore_consistency"]
2567

    
2568
  def BuildHooksEnv(self):
2569
    """Build hooks env.
2570

2571
    This runs on master, primary and secondary nodes of the instance.
2572

2573
    """
2574
    env = {
2575
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
2576
      }
2577
    env.update(_BuildInstanceHookEnvByObject(self.instance))
2578
    nl = [self.sstore.GetMasterNode()] + list(self.instance.secondary_nodes)
2579
    return env, nl, nl
2580

    
2581
  def CheckPrereq(self):
2582
    """Check prerequisites.
2583

2584
    This checks that the instance is in the cluster.
2585

2586
    """
2587
    instance = self.cfg.GetInstanceInfo(
2588
      self.cfg.ExpandInstanceName(self.op.instance_name))
2589
    if instance is None:
2590
      raise errors.OpPrereqError("Instance '%s' not known" %
2591
                                 self.op.instance_name)
2592

    
2593
    if instance.disk_template not in constants.DTS_NET_MIRROR:
2594
      raise errors.OpPrereqError("Instance's disk layout is not"
2595
                                 " network mirrored, cannot failover.")
2596

    
2597
    secondary_nodes = instance.secondary_nodes
2598
    if not secondary_nodes:
2599
      raise errors.ProgrammerError("no secondary node but using "
2600
                                   "a mirrored disk template")
2601

    
2602
    target_node = secondary_nodes[0]
2603
    # check memory requirements on the secondary node
2604
    _CheckNodeFreeMemory(self.cfg, target_node, "failing over instance %s" %
2605
                         instance.name, instance.memory)
2606

    
2607
    # check bridge existance
2608
    brlist = [nic.bridge for nic in instance.nics]
2609
    if not rpc.call_bridges_exist(target_node, brlist):
2610
      raise errors.OpPrereqError("One or more target bridges %s does not"
2611
                                 " exist on destination node '%s'" %
2612
                                 (brlist, target_node))
2613

    
2614
    self.instance = instance
2615

    
2616
  def Exec(self, feedback_fn):
2617
    """Failover an instance.
2618

2619
    The failover is done by shutting it down on its present node and
2620
    starting it on the secondary.
2621

2622
    """
2623
    instance = self.instance
2624

    
2625
    source_node = instance.primary_node
2626
    target_node = instance.secondary_nodes[0]
2627

    
2628
    feedback_fn("* checking disk consistency between source and target")
2629
    for dev in instance.disks:
2630
      # for drbd, these are drbd over lvm
2631
      if not _CheckDiskConsistency(self.cfg, dev, target_node, False):
2632
        if instance.status == "up" and not self.op.ignore_consistency:
2633
          raise errors.OpExecError("Disk %s is degraded on target node,"
2634
                                   " aborting failover." % dev.iv_name)
2635

    
2636
    feedback_fn("* shutting down instance on source node")
2637
    logger.Info("Shutting down instance %s on node %s" %
2638
                (instance.name, source_node))
2639

    
2640
    if not rpc.call_instance_shutdown(source_node, instance):
2641
      if self.op.ignore_consistency:
2642
        logger.Error("Could not shutdown instance %s on node %s. Proceeding"
2643
                     " anyway. Please make sure node %s is down"  %
2644
                     (instance.name, source_node, source_node))
2645
      else:
2646
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
2647
                                 (instance.name, source_node))
2648

    
2649
    feedback_fn("* deactivating the instance's disks on source node")
2650
    if not _ShutdownInstanceDisks(instance, self.cfg, ignore_primary=True):
2651
      raise errors.OpExecError("Can't shut down the instance's disks.")
2652

    
2653
    instance.primary_node = target_node
2654
    # distribute new instance config to the other nodes
2655
    self.cfg.Update(instance)
2656

    
2657
    # Only start the instance if it's marked as up
2658
    if instance.status == "up":
2659
      feedback_fn("* activating the instance's disks on target node")
2660
      logger.Info("Starting instance %s on node %s" %
2661
                  (instance.name, target_node))
2662

    
2663
      disks_ok, dummy = _AssembleInstanceDisks(instance, self.cfg,
2664
                                               ignore_secondaries=True)
2665
      if not disks_ok:
2666
        _ShutdownInstanceDisks(instance, self.cfg)
2667
        raise errors.OpExecError("Can't activate the instance's disks")
2668

    
2669
      feedback_fn("* starting the instance on the target node")
2670
      if not rpc.call_instance_start(target_node, instance, None):
2671
        _ShutdownInstanceDisks(instance, self.cfg)
2672
        raise errors.OpExecError("Could not start instance %s on node %s." %
2673
                                 (instance.name, target_node))
2674

    
2675

    
2676
def _CreateBlockDevOnPrimary(cfg, node, instance, device, info):
2677
  """Create a tree of block devices on the primary node.
2678

2679
  This always creates all devices.
2680

2681
  """
2682
  if device.children:
2683
    for child in device.children:
2684
      if not _CreateBlockDevOnPrimary(cfg, node, instance, child, info):
2685
        return False
2686

    
2687
  cfg.SetDiskID(device, node)
2688
  new_id = rpc.call_blockdev_create(node, device, device.size,
2689
                                    instance.name, True, info)
2690
  if not new_id:
2691
    return False
2692
  if device.physical_id is None:
2693
    device.physical_id = new_id
2694
  return True
2695

    
2696

    
2697
def _CreateBlockDevOnSecondary(cfg, node, instance, device, force, info):
2698
  """Create a tree of block devices on a secondary node.
2699

2700
  If this device type has to be created on secondaries, create it and
2701
  all its children.
2702

2703
  If not, just recurse to children keeping the same 'force' value.
2704

2705
  """
2706
  if device.CreateOnSecondary():
2707
    force = True
2708
  if device.children:
2709
    for child in device.children:
2710
      if not _CreateBlockDevOnSecondary(cfg, node, instance,
2711
                                        child, force, info):
2712
        return False
2713

    
2714
  if not force:
2715
    return True
2716
  cfg.SetDiskID(device, node)
2717
  new_id = rpc.call_blockdev_create(node, device, device.size,
2718
                                    instance.name, False, info)
2719
  if not new_id:
2720
    return False
2721
  if device.physical_id is None:
2722
    device.physical_id = new_id
2723
  return True
2724

    
2725

    
2726
def _GenerateUniqueNames(cfg, exts):
2727
  """Generate a suitable LV name.
2728

2729
  This will generate a logical volume name for the given instance.
2730

2731
  """
2732
  results = []
2733
  for val in exts:
2734
    new_id = cfg.GenerateUniqueID()
2735
    results.append("%s%s" % (new_id, val))
2736
  return results
2737

    
2738

    
2739
def _GenerateDRBD8Branch(cfg, primary, secondary, size, names, iv_name):
2740
  """Generate a drbd8 device complete with its children.
2741

2742
  """
2743
  port = cfg.AllocatePort()
2744
  vgname = cfg.GetVGName()
2745
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
2746
                          logical_id=(vgname, names[0]))
2747
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
2748
                          logical_id=(vgname, names[1]))
2749
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
2750
                          logical_id = (primary, secondary, port),
2751
                          children = [dev_data, dev_meta],
2752
                          iv_name=iv_name)
2753
  return drbd_dev
2754

    
2755

    
2756
def _GenerateDiskTemplate(cfg, template_name,
2757
                          instance_name, primary_node,
2758
                          secondary_nodes, disk_sz, swap_sz,
2759
                          file_storage_dir, file_driver):
2760
  """Generate the entire disk layout for a given template type.
2761

2762
  """
2763
  #TODO: compute space requirements
2764

    
2765
  vgname = cfg.GetVGName()
2766
  if template_name == constants.DT_DISKLESS:
2767
    disks = []
2768
  elif template_name == constants.DT_PLAIN:
2769
    if len(secondary_nodes) != 0:
2770
      raise errors.ProgrammerError("Wrong template configuration")
2771

    
2772
    names = _GenerateUniqueNames(cfg, [".sda", ".sdb"])
2773
    sda_dev = objects.Disk(dev_type=constants.LD_LV, size=disk_sz,
2774
                           logical_id=(vgname, names[0]),
2775
                           iv_name = "sda")
2776
    sdb_dev = objects.Disk(dev_type=constants.LD_LV, size=swap_sz,
2777
                           logical_id=(vgname, names[1]),
2778
                           iv_name = "sdb")
2779
    disks = [sda_dev, sdb_dev]
2780
  elif template_name == constants.DT_DRBD8:
2781
    if len(secondary_nodes) != 1:
2782
      raise errors.ProgrammerError("Wrong template configuration")
2783
    remote_node = secondary_nodes[0]
2784
    names = _GenerateUniqueNames(cfg, [".sda_data", ".sda_meta",
2785
                                       ".sdb_data", ".sdb_meta"])
2786
    drbd_sda_dev = _GenerateDRBD8Branch(cfg, primary_node, remote_node,
2787
                                         disk_sz, names[0:2], "sda")
2788
    drbd_sdb_dev = _GenerateDRBD8Branch(cfg, primary_node, remote_node,
2789
                                         swap_sz, names[2:4], "sdb")
2790
    disks = [drbd_sda_dev, drbd_sdb_dev]
2791
  elif template_name == constants.DT_FILE:
2792
    if len(secondary_nodes) != 0:
2793
      raise errors.ProgrammerError("Wrong template configuration")
2794

    
2795
    file_sda_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk_sz,
2796
                                iv_name="sda", logical_id=(file_driver,
2797
                                "%s/sda" % file_storage_dir))
2798
    file_sdb_dev = objects.Disk(dev_type=constants.LD_FILE, size=swap_sz,
2799
                                iv_name="sdb", logical_id=(file_driver,
2800
                                "%s/sdb" % file_storage_dir))
2801
    disks = [file_sda_dev, file_sdb_dev]
2802
  else:
2803
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
2804
  return disks
2805

    
2806

    
2807
def _GetInstanceInfoText(instance):
2808
  """Compute that text that should be added to the disk's metadata.
2809

2810
  """
2811
  return "originstname+%s" % instance.name
2812

    
2813

    
2814
def _CreateDisks(cfg, instance):
2815
  """Create all disks for an instance.
2816

2817
  This abstracts away some work from AddInstance.
2818

2819
  Args:
2820
    instance: the instance object
2821

2822
  Returns:
2823
    True or False showing the success of the creation process
2824

2825
  """
2826
  info = _GetInstanceInfoText(instance)
2827

    
2828
  if instance.disk_template == constants.DT_FILE:
2829
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
2830
    result = rpc.call_file_storage_dir_create(instance.primary_node,
2831
                                              file_storage_dir)
2832

    
2833
    if not result:
2834
      logger.Error("Could not connect to node '%s'" % instance.primary_node)
2835
      return False
2836

    
2837
    if not result[0]:
2838
      logger.Error("failed to create directory '%s'" % file_storage_dir)
2839
      return False
2840

    
2841
  for device in instance.disks:
2842
    logger.Info("creating volume %s for instance %s" %
2843
                (device.iv_name, instance.name))
2844
    #HARDCODE
2845
    for secondary_node in instance.secondary_nodes:
2846
      if not _CreateBlockDevOnSecondary(cfg, secondary_node, instance,
2847
                                        device, False, info):
2848
        logger.Error("failed to create volume %s (%s) on secondary node %s!" %
2849
                     (device.iv_name, device, secondary_node))
2850
        return False
2851
    #HARDCODE
2852
    if not _CreateBlockDevOnPrimary(cfg, instance.primary_node,
2853
                                    instance, device, info):
2854
      logger.Error("failed to create volume %s on primary!" %
2855
                   device.iv_name)
2856
      return False
2857

    
2858
  return True
2859

    
2860

    
2861
def _RemoveDisks(instance, cfg):
2862
  """Remove all disks for an instance.
2863

2864
  This abstracts away some work from `AddInstance()` and
2865
  `RemoveInstance()`. Note that in case some of the devices couldn't
2866
  be removed, the removal will continue with the other ones (compare
2867
  with `_CreateDisks()`).
2868

2869
  Args:
2870
    instance: the instance object
2871

2872
  Returns:
2873
    True or False showing the success of the removal proces
2874

2875
  """
2876
  logger.Info("removing block devices for instance %s" % instance.name)
2877

    
2878
  result = True
2879
  for device in instance.disks:
2880
    for node, disk in device.ComputeNodeTree(instance.primary_node):
2881
      cfg.SetDiskID(disk, node)
2882
      if not rpc.call_blockdev_remove(node, disk):
2883
        logger.Error("could not remove block device %s on node %s,"
2884
                     " continuing anyway" %
2885
                     (device.iv_name, node))
2886
        result = False
2887

    
2888
  if instance.disk_template == constants.DT_FILE:
2889
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
2890
    if not rpc.call_file_storage_dir_remove(instance.primary_node,
2891
                                            file_storage_dir):
2892
      logger.Error("could not remove directory '%s'" % file_storage_dir)
2893
      result = False
2894

    
2895
  return result
2896

    
2897

    
2898
def _ComputeDiskSize(disk_template, disk_size, swap_size):
2899
  """Compute disk size requirements in the volume group
2900

2901
  This is currently hard-coded for the two-drive layout.
2902

2903
  """
2904
  # Required free disk space as a function of disk and swap space
2905
  req_size_dict = {
2906
    constants.DT_DISKLESS: None,
2907
    constants.DT_PLAIN: disk_size + swap_size,
2908
    # 256 MB are added for drbd metadata, 128MB for each drbd device
2909
    constants.DT_DRBD8: disk_size + swap_size + 256,
2910
    constants.DT_FILE: None,
2911
  }
2912

    
2913
  if disk_template not in req_size_dict:
2914
    raise errors.ProgrammerError("Disk template '%s' size requirement"
2915
                                 " is unknown" %  disk_template)
2916

    
2917
  return req_size_dict[disk_template]
2918

    
2919

    
2920
class LUCreateInstance(LogicalUnit):
2921
  """Create an instance.
2922

2923
  """
2924
  HPATH = "instance-add"
2925
  HTYPE = constants.HTYPE_INSTANCE
2926
  _OP_REQP = ["instance_name", "mem_size", "disk_size",
2927
              "disk_template", "swap_size", "mode", "start", "vcpus",
2928
              "wait_for_sync", "ip_check", "mac"]
2929

    
2930
  def _RunAllocator(self):
2931
    """Run the allocator based on input opcode.
2932

2933
    """
2934
    disks = [{"size": self.op.disk_size, "mode": "w"},
2935
             {"size": self.op.swap_size, "mode": "w"}]
2936
    nics = [{"mac": self.op.mac, "ip": getattr(self.op, "ip", None),
2937
             "bridge": self.op.bridge}]
2938
    ial = IAllocator(self.cfg, self.sstore,
2939
                     mode=constants.IALLOCATOR_MODE_ALLOC,
2940
                     name=self.op.instance_name,
2941
                     disk_template=self.op.disk_template,
2942
                     tags=[],
2943
                     os=self.op.os_type,
2944
                     vcpus=self.op.vcpus,
2945
                     mem_size=self.op.mem_size,
2946
                     disks=disks,
2947
                     nics=nics,
2948
                     )
2949

    
2950
    ial.Run(self.op.iallocator)
2951

    
2952
    if not ial.success:
2953
      raise errors.OpPrereqError("Can't compute nodes using"
2954
                                 " iallocator '%s': %s" % (self.op.iallocator,
2955
                                                           ial.info))
2956
    if len(ial.nodes) != ial.required_nodes:
2957
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
2958
                                 " of nodes (%s), required %s" %
2959
                                 (len(ial.nodes), ial.required_nodes))
2960
    self.op.pnode = ial.nodes[0]
2961
    logger.ToStdout("Selected nodes for the instance: %s" %
2962
                    (", ".join(ial.nodes),))
2963
    logger.Info("Selected nodes for instance %s via iallocator %s: %s" %
2964
                (self.op.instance_name, self.op.iallocator, ial.nodes))
2965
    if ial.required_nodes == 2:
2966
      self.op.snode = ial.nodes[1]
2967

    
2968
  def BuildHooksEnv(self):
2969
    """Build hooks env.
2970

2971
    This runs on master, primary and secondary nodes of the instance.
2972

2973
    """
2974
    env = {
2975
      "INSTANCE_DISK_TEMPLATE": self.op.disk_template,
2976
      "INSTANCE_DISK_SIZE": self.op.disk_size,
2977
      "INSTANCE_SWAP_SIZE": self.op.swap_size,
2978
      "INSTANCE_ADD_MODE": self.op.mode,
2979
      }
2980
    if self.op.mode == constants.INSTANCE_IMPORT:
2981
      env["INSTANCE_SRC_NODE"] = self.op.src_node
2982
      env["INSTANCE_SRC_PATH"] = self.op.src_path
2983
      env["INSTANCE_SRC_IMAGE"] = self.src_image
2984

    
2985
    env.update(_BuildInstanceHookEnv(name=self.op.instance_name,
2986
      primary_node=self.op.pnode,
2987
      secondary_nodes=self.secondaries,
2988
      status=self.instance_status,
2989
      os_type=self.op.os_type,
2990
      memory=self.op.mem_size,
2991
      vcpus=self.op.vcpus,
2992
      nics=[(self.inst_ip, self.op.bridge, self.op.mac)],
2993
    ))
2994

    
2995
    nl = ([self.sstore.GetMasterNode(), self.op.pnode] +
2996
          self.secondaries)
2997
    return env, nl, nl
2998

    
2999

    
3000
  def CheckPrereq(self):
3001
    """Check prerequisites.
3002

3003
    """
3004
    # set optional parameters to none if they don't exist
3005
    for attr in ["kernel_path", "initrd_path", "hvm_boot_order", "pnode",
3006
                 "iallocator", "hvm_acpi", "hvm_pae", "hvm_cdrom_image_path",
3007
                 "vnc_bind_address"]:
3008
      if not hasattr(self.op, attr):
3009
        setattr(self.op, attr, None)
3010

    
3011
    if self.op.mode not in (constants.INSTANCE_CREATE,
3012
                            constants.INSTANCE_IMPORT):
3013
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
3014
                                 self.op.mode)
3015

    
3016
    if (not self.cfg.GetVGName() and
3017
        self.op.disk_template not in constants.DTS_NOT_LVM):
3018
      raise errors.OpPrereqError("Cluster does not support lvm-based"
3019
                                 " instances")
3020

    
3021
    if self.op.mode == constants.INSTANCE_IMPORT:
3022
      src_node = getattr(self.op, "src_node", None)
3023
      src_path = getattr(self.op, "src_path", None)
3024
      if src_node is None or src_path is None:
3025
        raise errors.OpPrereqError("Importing an instance requires source"
3026
                                   " node and path options")
3027
      src_node_full = self.cfg.ExpandNodeName(src_node)
3028
      if src_node_full is None:
3029
        raise errors.OpPrereqError("Unknown source node '%s'" % src_node)
3030
      self.op.src_node = src_node = src_node_full
3031

    
3032
      if not os.path.isabs(src_path):
3033
        raise errors.OpPrereqError("The source path must be absolute")
3034

    
3035
      export_info = rpc.call_export_info(src_node, src_path)
3036

    
3037
      if not export_info:
3038
        raise errors.OpPrereqError("No export found in dir %s" % src_path)
3039

    
3040
      if not export_info.has_section(constants.INISECT_EXP):
3041
        raise errors.ProgrammerError("Corrupted export config")
3042

    
3043
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
3044
      if (int(ei_version) != constants.EXPORT_VERSION):
3045
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
3046
                                   (ei_version, constants.EXPORT_VERSION))
3047

    
3048
      if int(export_info.get(constants.INISECT_INS, 'disk_count')) > 1:
3049
        raise errors.OpPrereqError("Can't import instance with more than"
3050
                                   " one data disk")
3051

    
3052
      # FIXME: are the old os-es, disk sizes, etc. useful?
3053
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
3054
      diskimage = os.path.join(src_path, export_info.get(constants.INISECT_INS,
3055
                                                         'disk0_dump'))
3056
      self.src_image = diskimage
3057
    else: # INSTANCE_CREATE
3058
      if getattr(self.op, "os_type", None) is None:
3059
        raise errors.OpPrereqError("No guest OS specified")
3060

    
3061
    #### instance parameters check
3062

    
3063
    # disk template and mirror node verification
3064
    if self.op.disk_template not in constants.DISK_TEMPLATES:
3065
      raise errors.OpPrereqError("Invalid disk template name")
3066

    
3067
    # instance name verification
3068
    hostname1 = utils.HostInfo(self.op.instance_name)
3069

    
3070
    self.op.instance_name = instance_name = hostname1.name
3071
    instance_list = self.cfg.GetInstanceList()
3072
    if instance_name in instance_list:
3073
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
3074
                                 instance_name)
3075

    
3076
    # ip validity checks
3077
    ip = getattr(self.op, "ip", None)
3078
    if ip is None or ip.lower() == "none":
3079
      inst_ip = None
3080
    elif ip.lower() == "auto":
3081
      inst_ip = hostname1.ip
3082
    else:
3083
      if not utils.IsValidIP(ip):
3084
        raise errors.OpPrereqError("given IP address '%s' doesn't look"
3085
                                   " like a valid IP" % ip)
3086
      inst_ip = ip
3087
    self.inst_ip = self.op.ip = inst_ip
3088

    
3089
    if self.op.start and not self.op.ip_check:
3090
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
3091
                                 " adding an instance in start mode")
3092

    
3093
    if self.op.ip_check:
3094
      if utils.TcpPing(hostname1.ip, constants.DEFAULT_NODED_PORT):
3095
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
3096
                                   (hostname1.ip, instance_name))
3097

    
3098
    # MAC address verification
3099
    if self.op.mac != "auto":
3100
      if not utils.IsValidMac(self.op.mac.lower()):
3101
        raise errors.OpPrereqError("invalid MAC address specified: %s" %
3102
                                   self.op.mac)
3103

    
3104
    # bridge verification
3105
    bridge = getattr(self.op, "bridge", None)
3106
    if bridge is None:
3107
      self.op.bridge = self.cfg.GetDefBridge()
3108
    else:
3109
      self.op.bridge = bridge
3110

    
3111
    # boot order verification
3112
    if self.op.hvm_boot_order is not None:
3113
      if len(self.op.hvm_boot_order.strip("acdn")) != 0:
3114
        raise errors.OpPrereqError("invalid boot order specified,"
3115
                                   " must be one or more of [acdn]")
3116
    # file storage checks
3117
    if (self.op.file_driver and
3118
        not self.op.file_driver in constants.FILE_DRIVER):
3119
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
3120
                                 self.op.file_driver)
3121

    
3122
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
3123
      raise errors.OpPrereqError("File storage directory not a relative"
3124
                                 " path")
3125
    #### allocator run
3126

    
3127
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
3128
      raise errors.OpPrereqError("One and only one of iallocator and primary"
3129
                                 " node must be given")
3130

    
3131
    if self.op.iallocator is not None:
3132
      self._RunAllocator()
3133

    
3134
    #### node related checks
3135

    
3136
    # check primary node
3137
    pnode = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.pnode))
3138
    if pnode is None:
3139
      raise errors.OpPrereqError("Primary node '%s' is unknown" %
3140
                                 self.op.pnode)
3141
    self.op.pnode = pnode.name
3142
    self.pnode = pnode
3143
    self.secondaries = []
3144

    
3145
    # mirror node verification
3146
    if self.op.disk_template in constants.DTS_NET_MIRROR:
3147
      if getattr(self.op, "snode", None) is None:
3148
        raise errors.OpPrereqError("The networked disk templates need"
3149
                                   " a mirror node")
3150

    
3151
      snode_name = self.cfg.ExpandNodeName(self.op.snode)
3152
      if snode_name is None:
3153
        raise errors.OpPrereqError("Unknown secondary node '%s'" %
3154
                                   self.op.snode)
3155
      elif snode_name == pnode.name:
3156
        raise errors.OpPrereqError("The secondary node cannot be"
3157
                                   " the primary node.")
3158
      self.secondaries.append(snode_name)
3159

    
3160
    req_size = _ComputeDiskSize(self.op.disk_template,
3161
                                self.op.disk_size, self.op.swap_size)
3162

    
3163
    # Check lv size requirements
3164
    if req_size is not None:
3165
      nodenames = [pnode.name] + self.secondaries
3166
      nodeinfo = rpc.call_node_info(nodenames, self.cfg.GetVGName())
3167
      for node in nodenames:
3168
        info = nodeinfo.get(node, None)
3169
        if not info:
3170
          raise errors.OpPrereqError("Cannot get current information"
3171
                                     " from node '%s'" % node)
3172
        vg_free = info.get('vg_free', None)
3173
        if not isinstance(vg_free, int):
3174
          raise errors.OpPrereqError("Can't compute free disk space on"
3175
                                     " node %s" % node)
3176
        if req_size > info['vg_free']:
3177
          raise errors.OpPrereqError("Not enough disk space on target node %s."
3178
                                     " %d MB available, %d MB required" %
3179
                                     (node, info['vg_free'], req_size))
3180

    
3181
    # os verification
3182
    os_obj = rpc.call_os_get(pnode.name, self.op.os_type)
3183
    if not os_obj:
3184
      raise errors.OpPrereqError("OS '%s' not in supported os list for"
3185
                                 " primary node"  % self.op.os_type)
3186

    
3187
    if self.op.kernel_path == constants.VALUE_NONE:
3188
      raise errors.OpPrereqError("Can't set instance kernel to none")
3189

    
3190

    
3191
    # bridge check on primary node
3192
    if not rpc.call_bridges_exist(self.pnode.name, [self.op.bridge]):
3193
      raise errors.OpPrereqError("target bridge '%s' does not exist on"
3194
                                 " destination node '%s'" %
3195
                                 (self.op.bridge, pnode.name))
3196

    
3197
    # memory check on primary node
3198
    if self.op.start:
3199
      _CheckNodeFreeMemory(self.cfg, self.pnode.name,
3200
                           "creating instance %s" % self.op.instance_name,
3201
                           self.op.mem_size)
3202

    
3203
    # hvm_cdrom_image_path verification
3204
    if self.op.hvm_cdrom_image_path is not None:
3205
      if not os.path.isabs(self.op.hvm_cdrom_image_path):
3206
        raise errors.OpPrereqError("The path to the HVM CDROM image must"
3207
                                   " be an absolute path or None, not %s" %
3208
                                   self.op.hvm_cdrom_image_path)
3209
      if not os.path.isfile(self.op.hvm_cdrom_image_path):
3210
        raise errors.OpPrereqError("The HVM CDROM image must either be a"
3211
                                   " regular file or a symlink pointing to"
3212
                                   " an existing regular file, not %s" %
3213
                                   self.op.hvm_cdrom_image_path)
3214

    
3215
    # vnc_bind_address verification
3216
    if self.op.vnc_bind_address is not None:
3217
      if not utils.IsValidIP(self.op.vnc_bind_address):
3218
        raise errors.OpPrereqError("given VNC bind address '%s' doesn't look"
3219
                                   " like a valid IP address" %
3220
                                   self.op.vnc_bind_address)
3221

    
3222
    if self.op.start:
3223
      self.instance_status = 'up'
3224
    else:
3225
      self.instance_status = 'down'
3226

    
3227
  def Exec(self, feedback_fn):
3228
    """Create and add the instance to the cluster.
3229

3230
    """
3231
    instance = self.op.instance_name
3232
    pnode_name = self.pnode.name
3233

    
3234
    if self.op.mac == "auto":
3235
      mac_address = self.cfg.GenerateMAC()
3236
    else:
3237
      mac_address = self.op.mac
3238

    
3239
    nic = objects.NIC(bridge=self.op.bridge, mac=mac_address)
3240
    if self.inst_ip is not None:
3241
      nic.ip = self.inst_ip
3242

    
3243
    ht_kind = self.sstore.GetHypervisorType()
3244
    if ht_kind in constants.HTS_REQ_PORT:
3245
      network_port = self.cfg.AllocatePort()
3246
    else:
3247
      network_port = None
3248

    
3249
    if self.op.vnc_bind_address is None:
3250
      self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
3251

    
3252
    # this is needed because os.path.join does not accept None arguments
3253
    if self.op.file_storage_dir is None:
3254
      string_file_storage_dir = ""
3255
    else:
3256
      string_file_storage_dir = self.op.file_storage_dir
3257

    
3258
    # build the full file storage dir path
3259
    file_storage_dir = os.path.normpath(os.path.join(
3260
                                        self.sstore.GetFileStorageDir(),
3261
                                        string_file_storage_dir, instance))
3262

    
3263

    
3264
    disks = _GenerateDiskTemplate(self.cfg,
3265
                                  self.op.disk_template,
3266
                                  instance, pnode_name,
3267
                                  self.secondaries, self.op.disk_size,
3268
                                  self.op.swap_size,
3269
                                  file_storage_dir,
3270
                                  self.op.file_driver)
3271

    
3272
    iobj = objects.Instance(name=instance, os=self.op.os_type,
3273
                            primary_node=pnode_name,
3274
                            memory=self.op.mem_size,
3275
                            vcpus=self.op.vcpus,
3276
                            nics=[nic], disks=disks,
3277
                            disk_template=self.op.disk_template,
3278
                            status=self.instance_status,
3279
                            network_port=network_port,
3280
                            kernel_path=self.op.kernel_path,
3281
                            initrd_path=self.op.initrd_path,
3282
                            hvm_boot_order=self.op.hvm_boot_order,
3283
                            hvm_acpi=self.op.hvm_acpi,
3284
                            hvm_pae=self.op.hvm_pae,
3285
                            hvm_cdrom_image_path=self.op.hvm_cdrom_image_path,
3286
                            vnc_bind_address=self.op.vnc_bind_address,
3287
                            )
3288

    
3289
    feedback_fn("* creating instance disks...")
3290
    if not _CreateDisks(self.cfg, iobj):
3291
      _RemoveDisks(iobj, self.cfg)
3292
      raise errors.OpExecError("Device creation failed, reverting...")
3293

    
3294
    feedback_fn("adding instance %s to cluster config" % instance)
3295

    
3296
    self.cfg.AddInstance(iobj)
3297
    # Add the new instance to the Ganeti Lock Manager
3298
    self.context.glm.add(locking.LEVEL_INSTANCE, instance)
3299

    
3300
    if self.op.wait_for_sync:
3301
      disk_abort = not _WaitForSync(self.cfg, iobj, self.proc)
3302
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
3303
      # make sure the disks are not degraded (still sync-ing is ok)
3304
      time.sleep(15)
3305
      feedback_fn("* checking mirrors status")
3306
      disk_abort = not _WaitForSync(self.cfg, iobj, self.proc, oneshot=True)
3307
    else:
3308
      disk_abort = False
3309

    
3310
    if disk_abort:
3311
      _RemoveDisks(iobj, self.cfg)
3312
      self.cfg.RemoveInstance(iobj.name)
3313
      # Remove the new instance from the Ganeti Lock Manager
3314
      self.context.glm.remove(locking.LEVEL_INSTANCE, iobj.name)
3315
      raise errors.OpExecError("There are some degraded disks for"
3316
                               " this instance")
3317

    
3318
    feedback_fn("creating os for instance %s on node %s" %
3319
                (instance, pnode_name))
3320

    
3321
    if iobj.disk_template != constants.DT_DISKLESS:
3322
      if self.op.mode == constants.INSTANCE_CREATE:
3323
        feedback_fn("* running the instance OS create scripts...")
3324
        if not rpc.call_instance_os_add(pnode_name, iobj, "sda", "sdb"):
3325
          raise errors.OpExecError("could not add os for instance %s"
3326
                                   " on node %s" %
3327
                                   (instance, pnode_name))
3328

    
3329
      elif self.op.mode == constants.INSTANCE_IMPORT:
3330
        feedback_fn("* running the instance OS import scripts...")
3331
        src_node = self.op.src_node
3332
        src_image = self.src_image
3333
        if not rpc.call_instance_os_import(pnode_name, iobj, "sda", "sdb",
3334
                                                src_node, src_image):
3335
          raise errors.OpExecError("Could not import os for instance"
3336
                                   " %s on node %s" %
3337
                                   (instance, pnode_name))
3338
      else:
3339
        # also checked in the prereq part
3340
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
3341
                                     % self.op.mode)
3342

    
3343
    if self.op.start:
3344
      logger.Info("starting instance %s on node %s" % (instance, pnode_name))
3345
      feedback_fn("* starting instance...")
3346
      if not rpc.call_instance_start(pnode_name, iobj, None):
3347
        raise errors.OpExecError("Could not start instance")
3348

    
3349

    
3350
class LUConnectConsole(NoHooksLU):
3351
  """Connect to an instance's console.
3352

3353
  This is somewhat special in that it returns the command line that
3354
  you need to run on the master node in order to connect to the
3355
  console.
3356

3357
  """
3358
  _OP_REQP = ["instance_name"]
3359
  REQ_BGL = False
3360

    
3361
  def ExpandNames(self):
3362
    self._ExpandAndLockInstance()
3363

    
3364
  def CheckPrereq(self):
3365
    """Check prerequisites.
3366

3367
    This checks that the instance is in the cluster.
3368

3369
    """
3370
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3371
    assert self.instance is not None, \
3372
      "Cannot retrieve locked instance %s" % self.op.instance_name
3373

    
3374
  def Exec(self, feedback_fn):
3375
    """Connect to the console of an instance
3376

3377
    """
3378
    instance = self.instance
3379
    node = instance.primary_node
3380

    
3381
    node_insts = rpc.call_instance_list([node])[node]
3382
    if node_insts is False:
3383
      raise errors.OpExecError("Can't connect to node %s." % node)
3384

    
3385
    if instance.name not in node_insts:
3386
      raise errors.OpExecError("Instance %s is not running." % instance.name)
3387

    
3388
    logger.Debug("connecting to console of %s on %s" % (instance.name, node))
3389

    
3390
    hyper = hypervisor.GetHypervisor()
3391
    console_cmd = hyper.GetShellCommandForConsole(instance)
3392

    
3393
    # build ssh cmdline
3394
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
3395

    
3396

    
3397
class LUReplaceDisks(LogicalUnit):
3398
  """Replace the disks of an instance.
3399

3400
  """
3401
  HPATH = "mirrors-replace"
3402
  HTYPE = constants.HTYPE_INSTANCE
3403
  _OP_REQP = ["instance_name", "mode", "disks"]
3404

    
3405
  def _RunAllocator(self):
3406
    """Compute a new secondary node using an IAllocator.
3407

3408
    """
3409
    ial = IAllocator(self.cfg, self.sstore,
3410
                     mode=constants.IALLOCATOR_MODE_RELOC,
3411
                     name=self.op.instance_name,
3412
                     relocate_from=[self.sec_node])
3413

    
3414
    ial.Run(self.op.iallocator)
3415

    
3416
    if not ial.success:
3417
      raise errors.OpPrereqError("Can't compute nodes using"
3418
                                 " iallocator '%s': %s" % (self.op.iallocator,
3419
                                                           ial.info))
3420
    if len(ial.nodes) != ial.required_nodes:
3421
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
3422
                                 " of nodes (%s), required %s" %
3423
                                 (len(ial.nodes), ial.required_nodes))
3424
    self.op.remote_node = ial.nodes[0]
3425
    logger.ToStdout("Selected new secondary for the instance: %s" %
3426
                    self.op.remote_node)
3427

    
3428
  def BuildHooksEnv(self):
3429
    """Build hooks env.
3430

3431
    This runs on the master, the primary and all the secondaries.
3432

3433
    """
3434
    env = {
3435
      "MODE": self.op.mode,
3436
      "NEW_SECONDARY": self.op.remote_node,
3437
      "OLD_SECONDARY": self.instance.secondary_nodes[0],
3438
      }
3439
    env.update(_BuildInstanceHookEnvByObject(self.instance))
3440
    nl = [
3441
      self.sstore.GetMasterNode(),
3442
      self.instance.primary_node,
3443
      ]
3444
    if self.op.remote_node is not None:
3445
      nl.append(self.op.remote_node)
3446
    return env, nl, nl
3447

    
3448
  def CheckPrereq(self):
3449
    """Check prerequisites.
3450

3451
    This checks that the instance is in the cluster.
3452

3453
    """
3454
    if not hasattr(self.op, "remote_node"):
3455
      self.op.remote_node = None
3456

    
3457
    instance = self.cfg.GetInstanceInfo(
3458
      self.cfg.ExpandInstanceName(self.op.instance_name))
3459
    if instance is None:
3460
      raise errors.OpPrereqError("Instance '%s' not known" %
3461
                                 self.op.instance_name)
3462
    self.instance = instance
3463
    self.op.instance_name = instance.name
3464

    
3465
    if instance.disk_template not in constants.DTS_NET_MIRROR:
3466
      raise errors.OpPrereqError("Instance's disk layout is not"
3467
                                 " network mirrored.")
3468

    
3469
    if len(instance.secondary_nodes) != 1:
3470
      raise errors.OpPrereqError("The instance has a strange layout,"
3471
                                 " expected one secondary but found %d" %
3472
                                 len(instance.secondary_nodes))
3473

    
3474
    self.sec_node = instance.secondary_nodes[0]
3475

    
3476
    ia_name = getattr(self.op, "iallocator", None)
3477
    if ia_name is not None:
3478
      if self.op.remote_node is not None:
3479
        raise errors.OpPrereqError("Give either the iallocator or the new"
3480
                                   " secondary, not both")
3481
      self.op.remote_node = self._RunAllocator()
3482

    
3483
    remote_node = self.op.remote_node
3484
    if remote_node is not None:
3485
      remote_node = self.cfg.ExpandNodeName(remote_node)
3486
      if remote_node is None:
3487
        raise errors.OpPrereqError("Node '%s' not known" %
3488
                                   self.op.remote_node)
3489
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
3490
    else:
3491
      self.remote_node_info = None
3492
    if remote_node == instance.primary_node:
3493
      raise errors.OpPrereqError("The specified node is the primary node of"
3494
                                 " the instance.")
3495
    elif remote_node == self.sec_node:
3496
      if self.op.mode == constants.REPLACE_DISK_SEC:
3497
        # this is for DRBD8, where we can't execute the same mode of
3498
        # replacement as for drbd7 (no different port allocated)
3499
        raise errors.OpPrereqError("Same secondary given, cannot execute"
3500
                                   " replacement")
3501
    if instance.disk_template == constants.DT_DRBD8:
3502
      if (self.op.mode == constants.REPLACE_DISK_ALL and
3503
          remote_node is not None):
3504
        # switch to replace secondary mode
3505
        self.op.mode = constants.REPLACE_DISK_SEC
3506

    
3507
      if self.op.mode == constants.REPLACE_DISK_ALL:
3508
        raise errors.OpPrereqError("Template 'drbd' only allows primary or"
3509
                                   " secondary disk replacement, not"
3510
                                   " both at once")
3511
      elif self.op.mode == constants.REPLACE_DISK_PRI:
3512
        if remote_node is not None:
3513
          raise errors.OpPrereqError("Template 'drbd' does not allow changing"
3514
                                     " the secondary while doing a primary"
3515
                                     " node disk replacement")
3516
        self.tgt_node = instance.primary_node
3517
        self.oth_node = instance.secondary_nodes[0]
3518
      elif self.op.mode == constants.REPLACE_DISK_SEC:
3519
        self.new_node = remote_node # this can be None, in which case
3520
                                    # we don't change the secondary
3521
        self.tgt_node = instance.secondary_nodes[0]
3522
        self.oth_node = instance.primary_node
3523
      else:
3524
        raise errors.ProgrammerError("Unhandled disk replace mode")
3525

    
3526
    for name in self.op.disks:
3527
      if instance.FindDisk(name) is None:
3528
        raise errors.OpPrereqError("Disk '%s' not found for instance '%s'" %
3529
                                   (name, instance.name))
3530
    self.op.remote_node = remote_node
3531

    
3532
  def _ExecD8DiskOnly(self, feedback_fn):
3533
    """Replace a disk on the primary or secondary for dbrd8.
3534

3535
    The algorithm for replace is quite complicated:
3536
      - for each disk to be replaced:
3537
        - create new LVs on the target node with unique names
3538
        - detach old LVs from the drbd device
3539
        - rename old LVs to name_replaced.<time_t>
3540
        - rename new LVs to old LVs
3541
        - attach the new LVs (with the old names now) to the drbd device
3542
      - wait for sync across all devices
3543
      - for each modified disk:
3544
        - remove old LVs (which have the name name_replaces.<time_t>)
3545

3546
    Failures are not very well handled.
3547

3548
    """
3549
    steps_total = 6
3550
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
3551
    instance = self.instance
3552
    iv_names = {}
3553
    vgname = self.cfg.GetVGName()
3554
    # start of work
3555
    cfg = self.cfg
3556
    tgt_node = self.tgt_node
3557
    oth_node = self.oth_node
3558

    
3559
    # Step: check device activation
3560
    self.proc.LogStep(1, steps_total, "check device existence")
3561
    info("checking volume groups")
3562
    my_vg = cfg.GetVGName()
3563
    results = rpc.call_vg_list([oth_node, tgt_node])
3564
    if not results:
3565
      raise errors.OpExecError("Can't list volume groups on the nodes")
3566
    for node in oth_node, tgt_node:
3567
      res = results.get(node, False)
3568
      if not res or my_vg not in res:
3569
        raise errors.OpExecError("Volume group '%s' not found on %s" %
3570
                                 (my_vg, node))
3571
    for dev in instance.disks:
3572
      if not dev.iv_name in self.op.disks:
3573
        continue
3574
      for node in tgt_node, oth_node:
3575
        info("checking %s on %s" % (dev.iv_name, node))
3576
        cfg.SetDiskID(dev, node)
3577
        if not rpc.call_blockdev_find(node, dev):
3578
          raise errors.OpExecError("Can't find device %s on node %s" %
3579
                                   (dev.iv_name, node))
3580

    
3581
    # Step: check other node consistency
3582
    self.proc.LogStep(2, steps_total, "check peer consistency")
3583
    for dev in instance.disks:
3584
      if not dev.iv_name in self.op.disks:
3585
        continue
3586
      info("checking %s consistency on %s" % (dev.iv_name, oth_node))
3587
      if not _CheckDiskConsistency(self.cfg, dev, oth_node,
3588
                                   oth_node==instance.primary_node):
3589
        raise errors.OpExecError("Peer node (%s) has degraded storage, unsafe"
3590
                                 " to replace disks on this node (%s)" %
3591
                                 (oth_node, tgt_node))
3592

    
3593
    # Step: create new storage
3594
    self.proc.LogStep(3, steps_total, "allocate new storage")
3595
    for dev in instance.disks:
3596
      if not dev.iv_name in self.op.disks:
3597
        continue
3598
      size = dev.size
3599
      cfg.SetDiskID(dev, tgt_node)
3600
      lv_names = [".%s_%s" % (dev.iv_name, suf) for suf in ["data", "meta"]]
3601
      names = _GenerateUniqueNames(cfg, lv_names)
3602
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=size,
3603
                             logical_id=(vgname, names[0]))
3604
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
3605
                             logical_id=(vgname, names[1]))
3606
      new_lvs = [lv_data, lv_meta]
3607
      old_lvs = dev.children
3608
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
3609
      info("creating new local storage on %s for %s" %
3610
           (tgt_node, dev.iv_name))
3611
      # since we *always* want to create this LV, we use the
3612
      # _Create...OnPrimary (which forces the creation), even if we
3613
      # are talking about the secondary node
3614
      for new_lv in new_lvs:
3615
        if not _CreateBlockDevOnPrimary(cfg, tgt_node, instance, new_lv,
3616
                                        _GetInstanceInfoText(instance)):
3617
          raise errors.OpExecError("Failed to create new LV named '%s' on"
3618
                                   " node '%s'" %
3619
                                   (new_lv.logical_id[1], tgt_node))
3620

    
3621
    # Step: for each lv, detach+rename*2+attach
3622
    self.proc.LogStep(4, steps_total, "change drbd configuration")
3623
    for dev, old_lvs, new_lvs in iv_names.itervalues():
3624
      info("detaching %s drbd from local storage" % dev.iv_name)
3625
      if not rpc.call_blockdev_removechildren(tgt_node, dev, old_lvs):
3626
        raise errors.OpExecError("Can't detach drbd from local storage on node"
3627
                                 " %s for device %s" % (tgt_node, dev.iv_name))
3628
      #dev.children = []
3629
      #cfg.Update(instance)
3630

    
3631
      # ok, we created the new LVs, so now we know we have the needed
3632
      # storage; as such, we proceed on the target node to rename
3633
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
3634
      # using the assumption that logical_id == physical_id (which in
3635
      # turn is the unique_id on that node)
3636

    
3637
      # FIXME(iustin): use a better name for the replaced LVs
3638
      temp_suffix = int(time.time())
3639
      ren_fn = lambda d, suff: (d.physical_id[0],
3640
                                d.physical_id[1] + "_replaced-%s" % suff)
3641
      # build the rename list based on what LVs exist on the node
3642
      rlist = []
3643
      for to_ren in old_lvs:
3644
        find_res = rpc.call_blockdev_find(tgt_node, to_ren)
3645
        if find_res is not None: # device exists
3646
          rlist.append((to_ren, ren_fn(to_ren, temp_suffix)))
3647

    
3648
      info("renaming the old LVs on the target node")
3649
      if not rpc.call_blockdev_rename(tgt_node, rlist):
3650
        raise errors.OpExecError("Can't rename old LVs on node %s" % tgt_node)
3651
      # now we rename the new LVs to the old LVs
3652
      info("renaming the new LVs on the target node")
3653
      rlist = [(new, old.physical_id) for old, new in zip(old_lvs, new_lvs)]
3654
      if not rpc.call_blockdev_rename(tgt_node, rlist):
3655
        raise errors.OpExecError("Can't rename new LVs on node %s" % tgt_node)
3656

    
3657
      for old, new in zip(old_lvs, new_lvs):
3658
        new.logical_id = old.logical_id
3659
        cfg.SetDiskID(new, tgt_node)
3660

    
3661
      for disk in old_lvs:
3662
        disk.logical_id = ren_fn(disk, temp_suffix)
3663
        cfg.SetDiskID(disk, tgt_node)
3664

    
3665
      # now that the new lvs have the old name, we can add them to the device
3666
      info("adding new mirror component on %s" % tgt_node)
3667
      if not rpc.call_blockdev_addchildren(tgt_node, dev, new_lvs):
3668
        for new_lv in new_lvs:
3669
          if not rpc.call_blockdev_remove(tgt_node, new_lv):
3670
            warning("Can't rollback device %s", hint="manually cleanup unused"
3671
                    " logical volumes")
3672
        raise errors.OpExecError("Can't add local storage to drbd")
3673

    
3674
      dev.children = new_lvs
3675
      cfg.Update(instance)
3676

    
3677
    # Step: wait for sync
3678

    
3679
    # this can fail as the old devices are degraded and _WaitForSync
3680
    # does a combined result over all disks, so we don't check its
3681
    # return value
3682
    self.proc.LogStep(5, steps_total, "sync devices")
3683
    _WaitForSync(cfg, instance, self.proc, unlock=True)
3684

    
3685
    # so check manually all the devices
3686
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
3687
      cfg.SetDiskID(dev, instance.primary_node)
3688
      is_degr = rpc.call_blockdev_find(instance.primary_node, dev)[5]
3689
      if is_degr:
3690
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
3691

    
3692
    # Step: remove old storage
3693
    self.proc.LogStep(6, steps_total, "removing old storage")
3694
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
3695
      info("remove logical volumes for %s" % name)
3696
      for lv in old_lvs:
3697
        cfg.SetDiskID(lv, tgt_node)
3698
        if not rpc.call_blockdev_remove(tgt_node, lv):
3699
          warning("Can't remove old LV", hint="manually remove unused LVs")
3700
          continue
3701

    
3702
  def _ExecD8Secondary(self, feedback_fn):
3703
    """Replace the secondary node for drbd8.
3704

3705
    The algorithm for replace is quite complicated:
3706
      - for all disks of the instance:
3707
        - create new LVs on the new node with same names
3708
        - shutdown the drbd device on the old secondary
3709
        - disconnect the drbd network on the primary
3710
        - create the drbd device on the new secondary
3711
        - network attach the drbd on the primary, using an artifice:
3712
          the drbd code for Attach() will connect to the network if it
3713
          finds a device which is connected to the good local disks but
3714
          not network enabled
3715
      - wait for sync across all devices
3716
      - remove all disks from the old secondary
3717

3718
    Failures are not very well handled.
3719

3720
    """
3721
    steps_total = 6
3722
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
3723
    instance = self.instance
3724
    iv_names = {}
3725
    vgname = self.cfg.GetVGName()
3726
    # start of work
3727
    cfg = self.cfg
3728
    old_node = self.tgt_node
3729
    new_node = self.new_node
3730
    pri_node = instance.primary_node
3731

    
3732
    # Step: check device activation
3733
    self.proc.LogStep(1, steps_total, "check device existence")
3734
    info("checking volume groups")
3735
    my_vg = cfg.GetVGName()
3736
    results = rpc.call_vg_list([pri_node, new_node])
3737
    if not results:
3738
      raise errors.OpExecError("Can't list volume groups on the nodes")
3739
    for node in pri_node, new_node:
3740
      res = results.get(node, False)
3741
      if not res or my_vg not in res:
3742
        raise errors.OpExecError("Volume group '%s' not found on %s" %
3743
                                 (my_vg, node))
3744
    for dev in instance.disks:
3745
      if not dev.iv_name in self.op.disks:
3746
        continue
3747
      info("checking %s on %s" % (dev.iv_name, pri_node))
3748
      cfg.SetDiskID(dev, pri_node)
3749
      if not rpc.call_blockdev_find(pri_node, dev):
3750
        raise errors.OpExecError("Can't find device %s on node %s" %
3751
                                 (dev.iv_name, pri_node))
3752

    
3753
    # Step: check other node consistency
3754
    self.proc.LogStep(2, steps_total, "check peer consistency")
3755
    for dev in instance.disks:
3756
      if not dev.iv_name in self.op.disks:
3757
        continue
3758
      info("checking %s consistency on %s" % (dev.iv_name, pri_node))
3759
      if not _CheckDiskConsistency(self.cfg, dev, pri_node, True, ldisk=True):
3760
        raise errors.OpExecError("Primary node (%s) has degraded storage,"
3761
                                 " unsafe to replace the secondary" %
3762
                                 pri_node)
3763

    
3764
    # Step: create new storage
3765
    self.proc.LogStep(3, steps_total, "allocate new storage")
3766
    for dev in instance.disks:
3767
      size = dev.size
3768
      info("adding new local storage on %s for %s" % (new_node, dev.iv_name))
3769
      # since we *always* want to create this LV, we use the
3770
      # _Create...OnPrimary (which forces the creation), even if we
3771
      # are talking about the secondary node
3772
      for new_lv in dev.children:
3773
        if not _CreateBlockDevOnPrimary(cfg, new_node, instance, new_lv,
3774
                                        _GetInstanceInfoText(instance)):
3775
          raise errors.OpExecError("Failed to create new LV named '%s' on"
3776
                                   " node '%s'" %
3777
                                   (new_lv.logical_id[1], new_node))
3778

    
3779
      iv_names[dev.iv_name] = (dev, dev.children)
3780

    
3781
    self.proc.LogStep(4, steps_total, "changing drbd configuration")
3782
    for dev in instance.disks:
3783
      size = dev.size
3784
      info("activating a new drbd on %s for %s" % (new_node, dev.iv_name))
3785
      # create new devices on new_node
3786
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
3787
                              logical_id=(pri_node, new_node,
3788
                                          dev.logical_id[2]),
3789
                              children=dev.children)
3790
      if not _CreateBlockDevOnSecondary(cfg, new_node, instance,
3791
                                        new_drbd, False,
3792
                                      _GetInstanceInfoText(instance)):
3793
        raise errors.OpExecError("Failed to create new DRBD on"
3794
                                 " node '%s'" % new_node)
3795

    
3796
    for dev in instance.disks:
3797
      # we have new devices, shutdown the drbd on the old secondary
3798
      info("shutting down drbd for %s on old node" % dev.iv_name)
3799
      cfg.SetDiskID(dev, old_node)
3800
      if not rpc.call_blockdev_shutdown(old_node, dev):
3801
        warning("Failed to shutdown drbd for %s on old node" % dev.iv_name,
3802
                hint="Please cleanup this device manually as soon as possible")
3803

    
3804
    info("detaching primary drbds from the network (=> standalone)")
3805
    done = 0
3806
    for dev in instance.disks:
3807
      cfg.SetDiskID(dev, pri_node)
3808
      # set the physical (unique in bdev terms) id to None, meaning
3809
      # detach from network
3810
      dev.physical_id = (None,) * len(dev.physical_id)
3811
      # and 'find' the device, which will 'fix' it to match the
3812
      # standalone state
3813
      if rpc.call_blockdev_find(pri_node, dev):
3814
        done += 1
3815
      else:
3816
        warning("Failed to detach drbd %s from network, unusual case" %
3817
                dev.iv_name)
3818

    
3819
    if not done:
3820
      # no detaches succeeded (very unlikely)
3821
      raise errors.OpExecError("Can't detach at least one DRBD from old node")
3822

    
3823
    # if we managed to detach at least one, we update all the disks of
3824
    # the instance to point to the new secondary
3825
    info("updating instance configuration")
3826
    for dev in instance.disks:
3827
      dev.logical_id = (pri_node, new_node) + dev.logical_id[2:]
3828
      cfg.SetDiskID(dev, pri_node)
3829
    cfg.Update(instance)
3830

    
3831
    # and now perform the drbd attach
3832
    info("attaching primary drbds to new secondary (standalone => connected)")
3833
    failures = []
3834
    for dev in instance.disks:
3835
      info("attaching primary drbd for %s to new secondary node" % dev.iv_name)
3836
      # since the attach is smart, it's enough to 'find' the device,
3837
      # it will automatically activate the network, if the physical_id
3838
      # is correct
3839
      cfg.SetDiskID(dev, pri_node)
3840
      if not rpc.call_blockdev_find(pri_node, dev):
3841
        warning("can't attach drbd %s to new secondary!" % dev.iv_name,
3842
                "please do a gnt-instance info to see the status of disks")
3843

    
3844
    # this can fail as the old devices are degraded and _WaitForSync
3845
    # does a combined result over all disks, so we don't check its
3846
    # return value
3847
    self.proc.LogStep(5, steps_total, "sync devices")
3848
    _WaitForSync(cfg, instance, self.proc, unlock=True)
3849

    
3850
    # so check manually all the devices
3851
    for name, (dev, old_lvs) in iv_names.iteritems():
3852
      cfg.SetDiskID(dev, pri_node)
3853
      is_degr = rpc.call_blockdev_find(pri_node, dev)[5]
3854
      if is_degr:
3855
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
3856

    
3857
    self.proc.LogStep(6, steps_total, "removing old storage")
3858
    for name, (dev, old_lvs) in iv_names.iteritems():
3859
      info("remove logical volumes for %s" % name)
3860
      for lv in old_lvs:
3861
        cfg.SetDiskID(lv, old_node)
3862
        if not rpc.call_blockdev_remove(old_node, lv):
3863
          warning("Can't remove LV on old secondary",
3864
                  hint="Cleanup stale volumes by hand")
3865

    
3866
  def Exec(self, feedback_fn):
3867
    """Execute disk replacement.
3868

3869
    This dispatches the disk replacement to the appropriate handler.
3870

3871
    """
3872
    instance = self.instance
3873

    
3874
    # Activate the instance disks if we're replacing them on a down instance
3875
    if instance.status == "down":
3876
      op = opcodes.OpActivateInstanceDisks(instance_name=instance.name)
3877
      self.proc.ChainOpCode(op)
3878

    
3879
    if instance.disk_template == constants.DT_DRBD8:
3880
      if self.op.remote_node is None:
3881
        fn = self._ExecD8DiskOnly
3882
      else:
3883
        fn = self._ExecD8Secondary
3884
    else:
3885
      raise errors.ProgrammerError("Unhandled disk replacement case")
3886

    
3887
    ret = fn(feedback_fn)
3888

    
3889
    # Deactivate the instance disks if we're replacing them on a down instance
3890
    if instance.status == "down":
3891
      op = opcodes.OpDeactivateInstanceDisks(instance_name=instance.name)
3892
      self.proc.ChainOpCode(op)
3893

    
3894
    return ret
3895

    
3896

    
3897
class LUGrowDisk(LogicalUnit):
3898
  """Grow a disk of an instance.
3899

3900
  """
3901
  HPATH = "disk-grow"
3902
  HTYPE = constants.HTYPE_INSTANCE
3903
  _OP_REQP = ["instance_name", "disk", "amount"]
3904

    
3905
  def BuildHooksEnv(self):
3906
    """Build hooks env.
3907

3908
    This runs on the master, the primary and all the secondaries.
3909

3910
    """
3911
    env = {
3912
      "DISK": self.op.disk,
3913
      "AMOUNT": self.op.amount,
3914
      }
3915
    env.update(_BuildInstanceHookEnvByObject(self.instance))
3916
    nl = [
3917
      self.sstore.GetMasterNode(),
3918
      self.instance.primary_node,
3919
      ]
3920
    return env, nl, nl
3921

    
3922
  def CheckPrereq(self):
3923
    """Check prerequisites.
3924

3925
    This checks that the instance is in the cluster.
3926

3927
    """
3928
    instance = self.cfg.GetInstanceInfo(
3929
      self.cfg.ExpandInstanceName(self.op.instance_name))
3930
    if instance is None:
3931
      raise errors.OpPrereqError("Instance '%s' not known" %
3932
                                 self.op.instance_name)
3933
    self.instance = instance
3934
    self.op.instance_name = instance.name
3935

    
3936
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
3937
      raise errors.OpPrereqError("Instance's disk layout does not support"
3938
                                 " growing.")
3939

    
3940
    if instance.FindDisk(self.op.disk) is None:
3941
      raise errors.OpPrereqError("Disk '%s' not found for instance '%s'" %
3942
                                 (self.op.disk, instance.name))
3943

    
3944
    nodenames = [instance.primary_node] + list(instance.secondary_nodes)
3945
    nodeinfo = rpc.call_node_info(nodenames, self.cfg.GetVGName())
3946
    for node in nodenames:
3947
      info = nodeinfo.get(node, None)
3948
      if not info:
3949
        raise errors.OpPrereqError("Cannot get current information"
3950
                                   " from node '%s'" % node)
3951
      vg_free = info.get('vg_free', None)
3952
      if not isinstance(vg_free, int):
3953
        raise errors.OpPrereqError("Can't compute free disk space on"
3954
                                   " node %s" % node)
3955
      if self.op.amount > info['vg_free']:
3956
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
3957
                                   " %d MiB available, %d MiB required" %
3958
                                   (node, info['vg_free'], self.op.amount))
3959

    
3960
  def Exec(self, feedback_fn):
3961
    """Execute disk grow.
3962

3963
    """
3964
    instance = self.instance
3965
    disk = instance.FindDisk(self.op.disk)
3966
    for node in (instance.secondary_nodes + (instance.primary_node,)):
3967
      self.cfg.SetDiskID(disk, node)
3968
      result = rpc.call_blockdev_grow(node, disk, self.op.amount)
3969
      if not result or not isinstance(result, tuple) or len(result) != 2:
3970
        raise errors.OpExecError("grow request failed to node %s" % node)
3971
      elif not result[0]:
3972
        raise errors.OpExecError("grow request failed to node %s: %s" %
3973
                                 (node, result[1]))
3974
    disk.RecordGrow(self.op.amount)
3975
    self.cfg.Update(instance)
3976
    return
3977

    
3978

    
3979
class LUQueryInstanceData(NoHooksLU):
3980
  """Query runtime instance data.
3981

3982
  """
3983
  _OP_REQP = ["instances"]
3984

    
3985
  def CheckPrereq(self):
3986
    """Check prerequisites.
3987

3988
    This only checks the optional instance list against the existing names.
3989

3990
    """
3991
    if not isinstance(self.op.instances, list):
3992
      raise errors.OpPrereqError("Invalid argument type 'instances'")
3993
    if self.op.instances:
3994
      self.wanted_instances = []
3995
      names = self.op.instances
3996
      for name in names:
3997
        instance = self.cfg.GetInstanceInfo(self.cfg.ExpandInstanceName(name))
3998
        if instance is None:
3999
          raise errors.OpPrereqError("No such instance name '%s'" % name)
4000
        self.wanted_instances.append(instance)
4001
    else:
4002
      self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
4003
                               in self.cfg.GetInstanceList()]
4004
    return
4005

    
4006

    
4007
  def _ComputeDiskStatus(self, instance, snode, dev):
4008
    """Compute block device status.
4009

4010
    """
4011
    self.cfg.SetDiskID(dev, instance.primary_node)
4012
    dev_pstatus = rpc.call_blockdev_find(instance.primary_node, dev)
4013
    if dev.dev_type in constants.LDS_DRBD:
4014
      # we change the snode then (otherwise we use the one passed in)
4015
      if dev.logical_id[0] == instance.primary_node:
4016
        snode = dev.logical_id[1]
4017
      else:
4018
        snode = dev.logical_id[0]
4019

    
4020
    if snode:
4021
      self.cfg.SetDiskID(dev, snode)
4022
      dev_sstatus = rpc.call_blockdev_find(snode, dev)
4023
    else:
4024
      dev_sstatus = None
4025

    
4026
    if dev.children:
4027
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
4028
                      for child in dev.children]
4029
    else:
4030
      dev_children = []
4031

    
4032
    data = {
4033
      "iv_name": dev.iv_name,
4034
      "dev_type": dev.dev_type,
4035
      "logical_id": dev.logical_id,
4036
      "physical_id": dev.physical_id,
4037
      "pstatus": dev_pstatus,
4038
      "sstatus": dev_sstatus,
4039
      "children": dev_children,
4040
      }
4041

    
4042
    return data
4043

    
4044
  def Exec(self, feedback_fn):
4045
    """Gather and return data"""
4046
    result = {}
4047
    for instance in self.wanted_instances:
4048
      remote_info = rpc.call_instance_info(instance.primary_node,
4049
                                                instance.name)
4050
      if remote_info and "state" in remote_info:
4051
        remote_state = "up"
4052
      else:
4053
        remote_state = "down"
4054
      if instance.status == "down":
4055
        config_state = "down"
4056
      else:
4057
        config_state = "up"
4058

    
4059
      disks = [self._ComputeDiskStatus(instance, None, device)
4060
               for device in instance.disks]
4061

    
4062
      idict = {
4063
        "name": instance.name,
4064
        "config_state": config_state,
4065
        "run_state": remote_state,
4066
        "pnode": instance.primary_node,
4067
        "snodes": instance.secondary_nodes,
4068
        "os": instance.os,
4069
        "memory": instance.memory,
4070
        "nics": [(nic.mac, nic.ip, nic.bridge) for nic in instance.nics],
4071
        "disks": disks,
4072
        "vcpus": instance.vcpus,
4073
        }
4074

    
4075
      htkind = self.sstore.GetHypervisorType()
4076
      if htkind == constants.HT_XEN_PVM30:
4077
        idict["kernel_path"] = instance.kernel_path
4078
        idict["initrd_path"] = instance.initrd_path
4079

    
4080
      if htkind == constants.HT_XEN_HVM31:
4081
        idict["hvm_boot_order"] = instance.hvm_boot_order
4082
        idict["hvm_acpi"] = instance.hvm_acpi
4083
        idict["hvm_pae"] = instance.hvm_pae
4084
        idict["hvm_cdrom_image_path"] = instance.hvm_cdrom_image_path
4085

    
4086
      if htkind in constants.HTS_REQ_PORT:
4087
        idict["vnc_bind_address"] = instance.vnc_bind_address
4088
        idict["network_port"] = instance.network_port
4089

    
4090
      result[instance.name] = idict
4091

    
4092
    return result
4093

    
4094

    
4095
class LUSetInstanceParams(LogicalUnit):
4096
  """Modifies an instances's parameters.
4097

4098
  """
4099
  HPATH = "instance-modify"
4100
  HTYPE = constants.HTYPE_INSTANCE
4101
  _OP_REQP = ["instance_name"]
4102
  REQ_BGL = False
4103

    
4104
  def ExpandNames(self):
4105
    self._ExpandAndLockInstance()
4106

    
4107
  def BuildHooksEnv(self):
4108
    """Build hooks env.
4109

4110
    This runs on the master, primary and secondaries.
4111

4112
    """
4113
    args = dict()
4114
    if self.mem:
4115
      args['memory'] = self.mem
4116
    if self.vcpus:
4117
      args['vcpus'] = self.vcpus
4118
    if self.do_ip or self.do_bridge or self.mac:
4119
      if self.do_ip:
4120
        ip = self.ip
4121
      else:
4122
        ip = self.instance.nics[0].ip
4123
      if self.bridge:
4124
        bridge = self.bridge
4125
      else:
4126
        bridge = self.instance.nics[0].bridge
4127
      if self.mac:
4128
        mac = self.mac
4129
      else:
4130
        mac = self.instance.nics[0].mac
4131
      args['nics'] = [(ip, bridge, mac)]
4132
    env = _BuildInstanceHookEnvByObject(self.instance, override=args)
4133
    nl = [self.sstore.GetMasterNode(),
4134
          self.instance.primary_node] + list(self.instance.secondary_nodes)
4135
    return env, nl, nl
4136

    
4137
  def CheckPrereq(self):
4138
    """Check prerequisites.
4139

4140
    This only checks the instance list against the existing names.
4141

4142
    """
4143
    # FIXME: all the parameters could be checked before, in ExpandNames, or in
4144
    # a separate CheckArguments function, if we implement one, so the operation
4145
    # can be aborted without waiting for any lock, should it have an error...
4146
    self.mem = getattr(self.op, "mem", None)
4147
    self.vcpus = getattr(self.op, "vcpus", None)
4148
    self.ip = getattr(self.op, "ip", None)
4149
    self.mac = getattr(self.op, "mac", None)
4150
    self.bridge = getattr(self.op, "bridge", None)
4151
    self.kernel_path = getattr(self.op, "kernel_path", None)
4152
    self.initrd_path = getattr(self.op, "initrd_path", None)
4153
    self.hvm_boot_order = getattr(self.op, "hvm_boot_order", None)
4154
    self.hvm_acpi = getattr(self.op, "hvm_acpi", None)
4155
    self.hvm_pae = getattr(self.op, "hvm_pae", None)
4156
    self.hvm_cdrom_image_path = getattr(self.op, "hvm_cdrom_image_path", None)
4157
    self.vnc_bind_address = getattr(self.op, "vnc_bind_address", None)
4158
    all_parms = [self.mem, self.vcpus, self.ip, self.bridge, self.mac,
4159
                 self.kernel_path, self.initrd_path, self.hvm_boot_order,
4160
                 self.hvm_acpi, self.hvm_pae, self.hvm_cdrom_image_path,
4161
                 self.vnc_bind_address]
4162
    if all_parms.count(None) == len(all_parms):
4163
      raise errors.OpPrereqError("No changes submitted")
4164
    if self.mem is not None:
4165
      try:
4166
        self.mem = int(self.mem)
4167
      except ValueError, err:
4168
        raise errors.OpPrereqError("Invalid memory size: %s" % str(err))
4169
    if self.vcpus is not None:
4170
      try:
4171
        self.vcpus = int(self.vcpus)
4172
      except ValueError, err:
4173
        raise errors.OpPrereqError("Invalid vcpus number: %s" % str(err))
4174
    if self.ip is not None:
4175
      self.do_ip = True
4176
      if self.ip.lower() == "none":
4177
        self.ip = None
4178
      else:
4179
        if not utils.IsValidIP(self.ip):
4180
          raise errors.OpPrereqError("Invalid IP address '%s'." % self.ip)
4181
    else:
4182
      self.do_ip = False
4183
    self.do_bridge = (self.bridge is not None)
4184
    if self.mac is not None:
4185
      if self.cfg.IsMacInUse(self.mac):
4186
        raise errors.OpPrereqError('MAC address %s already in use in cluster' %
4187
                                   self.mac)
4188
      if not utils.IsValidMac(self.mac):
4189
        raise errors.OpPrereqError('Invalid MAC address %s' % self.mac)
4190

    
4191
    if self.kernel_path is not None:
4192
      self.do_kernel_path = True
4193
      if self.kernel_path == constants.VALUE_NONE:
4194
        raise errors.OpPrereqError("Can't set instance to no kernel")
4195

    
4196
      if self.kernel_path != constants.VALUE_DEFAULT:
4197
        if not os.path.isabs(self.kernel_path):
4198
          raise errors.OpPrereqError("The kernel path must be an absolute"
4199
                                    " filename")
4200
    else:
4201
      self.do_kernel_path = False
4202

    
4203
    if self.initrd_path is not None:
4204
      self.do_initrd_path = True
4205
      if self.initrd_path not in (constants.VALUE_NONE,
4206
                                  constants.VALUE_DEFAULT):
4207
        if not os.path.isabs(self.initrd_path):
4208
          raise errors.OpPrereqError("The initrd path must be an absolute"
4209
                                    " filename")
4210
    else:
4211
      self.do_initrd_path = False
4212

    
4213
    # boot order verification
4214
    if self.hvm_boot_order is not None:
4215
      if self.hvm_boot_order != constants.VALUE_DEFAULT:
4216
        if len(self.hvm_boot_order.strip("acdn")) != 0:
4217
          raise errors.OpPrereqError("invalid boot order specified,"
4218
                                     " must be one or more of [acdn]"
4219
                                     " or 'default'")
4220

    
4221
    # hvm_cdrom_image_path verification
4222
    if self.op.hvm_cdrom_image_path is not None:
4223
      if not os.path.isabs(self.op.hvm_cdrom_image_path):
4224
        raise errors.OpPrereqError("The path to the HVM CDROM image must"
4225
                                   " be an absolute path or None, not %s" %
4226
                                   self.op.hvm_cdrom_image_path)
4227
      if not os.path.isfile(self.op.hvm_cdrom_image_path):
4228
        raise errors.OpPrereqError("The HVM CDROM image must either be a"
4229
                                   " regular file or a symlink pointing to"
4230
                                   " an existing regular file, not %s" %
4231
                                   self.op.hvm_cdrom_image_path)
4232

    
4233
    # vnc_bind_address verification
4234
    if self.op.vnc_bind_address is not None:
4235
      if not utils.IsValidIP(self.op.vnc_bind_address):
4236
        raise errors.OpPrereqError("given VNC bind address '%s' doesn't look"
4237
                                   " like a valid IP address" %
4238
                                   self.op.vnc_bind_address)
4239

    
4240
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4241
    assert self.instance is not None, \
4242
      "Cannot retrieve locked instance %s" % self.op.instance_name
4243
    return
4244

    
4245
  def Exec(self, feedback_fn):
4246
    """Modifies an instance.
4247

4248
    All parameters take effect only at the next restart of the instance.
4249
    """
4250
    result = []
4251
    instance = self.instance
4252
    if self.mem:
4253
      instance.memory = self.mem
4254
      result.append(("mem", self.mem))
4255
    if self.vcpus:
4256
      instance.vcpus = self.vcpus
4257
      result.append(("vcpus",  self.vcpus))
4258
    if self.do_ip:
4259
      instance.nics[0].ip = self.ip
4260
      result.append(("ip", self.ip))
4261
    if self.bridge:
4262
      instance.nics[0].bridge = self.bridge
4263
      result.append(("bridge", self.bridge))
4264
    if self.mac:
4265
      instance.nics[0].mac = self.mac
4266
      result.append(("mac", self.mac))
4267
    if self.do_kernel_path:
4268
      instance.kernel_path = self.kernel_path
4269
      result.append(("kernel_path", self.kernel_path))
4270
    if self.do_initrd_path:
4271
      instance.initrd_path = self.initrd_path
4272
      result.append(("initrd_path", self.initrd_path))
4273
    if self.hvm_boot_order:
4274
      if self.hvm_boot_order == constants.VALUE_DEFAULT:
4275
        instance.hvm_boot_order = None
4276
      else:
4277
        instance.hvm_boot_order = self.hvm_boot_order
4278
      result.append(("hvm_boot_order", self.hvm_boot_order))
4279
    if self.hvm_acpi:
4280
      instance.hvm_acpi = self.hvm_acpi
4281
      result.append(("hvm_acpi", self.hvm_acpi))
4282
    if self.hvm_pae:
4283
      instance.hvm_pae = self.hvm_pae
4284
      result.append(("hvm_pae", self.hvm_pae))
4285
    if self.hvm_cdrom_image_path:
4286
      instance.hvm_cdrom_image_path = self.hvm_cdrom_image_path
4287
      result.append(("hvm_cdrom_image_path", self.hvm_cdrom_image_path))
4288
    if self.vnc_bind_address:
4289
      instance.vnc_bind_address = self.vnc_bind_address
4290
      result.append(("vnc_bind_address", self.vnc_bind_address))
4291

    
4292
    self.cfg.Update(instance)
4293

    
4294
    return result
4295

    
4296

    
4297
class LUQueryExports(NoHooksLU):
4298
  """Query the exports list
4299

4300
  """
4301
  _OP_REQP = []
4302

    
4303
  def CheckPrereq(self):
4304
    """Check that the nodelist contains only existing nodes.
4305

4306
    """
4307
    self.nodes = _GetWantedNodes(self, getattr(self.op, "nodes", None))
4308

    
4309
  def Exec(self, feedback_fn):
4310
    """Compute the list of all the exported system images.
4311

4312
    Returns:
4313
      a dictionary with the structure node->(export-list)
4314
      where export-list is a list of the instances exported on
4315
      that node.
4316

4317
    """
4318
    return rpc.call_export_list(self.nodes)
4319

    
4320

    
4321
class LUExportInstance(LogicalUnit):
4322
  """Export an instance to an image in the cluster.
4323

4324
  """
4325
  HPATH = "instance-export"
4326
  HTYPE = constants.HTYPE_INSTANCE
4327
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
4328

    
4329
  def BuildHooksEnv(self):
4330
    """Build hooks env.
4331

4332
    This will run on the master, primary node and target node.
4333

4334
    """
4335
    env = {
4336
      "EXPORT_NODE": self.op.target_node,
4337
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
4338
      }
4339
    env.update(_BuildInstanceHookEnvByObject(self.instance))
4340
    nl = [self.sstore.GetMasterNode(), self.instance.primary_node,
4341
          self.op.target_node]
4342
    return env, nl, nl
4343

    
4344
  def CheckPrereq(self):
4345
    """Check prerequisites.
4346

4347
    This checks that the instance and node names are valid.
4348

4349
    """
4350
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
4351
    self.instance = self.cfg.GetInstanceInfo(instance_name)
4352
    if self.instance is None:
4353
      raise errors.OpPrereqError("Instance '%s' not found" %
4354
                                 self.op.instance_name)
4355

    
4356
    # node verification
4357
    dst_node_short = self.cfg.ExpandNodeName(self.op.target_node)
4358
    self.dst_node = self.cfg.GetNodeInfo(dst_node_short)
4359

    
4360
    if self.dst_node is None:
4361
      raise errors.OpPrereqError("Destination node '%s' is unknown." %
4362
                                 self.op.target_node)
4363
    self.op.target_node = self.dst_node.name
4364

    
4365
    # instance disk type verification
4366
    for disk in self.instance.disks:
4367
      if disk.dev_type == constants.LD_FILE:
4368
        raise errors.OpPrereqError("Export not supported for instances with"
4369
                                   " file-based disks")
4370

    
4371
  def Exec(self, feedback_fn):
4372
    """Export an instance to an image in the cluster.
4373

4374
    """
4375
    instance = self.instance
4376
    dst_node = self.dst_node
4377
    src_node = instance.primary_node
4378
    if self.op.shutdown:
4379
      # shutdown the instance, but not the disks
4380
      if not rpc.call_instance_shutdown(src_node, instance):
4381
         raise errors.OpExecError("Could not shutdown instance %s on node %s" %
4382
                                  (instance.name, src_node))
4383

    
4384
    vgname = self.cfg.GetVGName()
4385

    
4386
    snap_disks = []
4387

    
4388
    try:
4389
      for disk in instance.disks:
4390
        if disk.iv_name == "sda":
4391
          # new_dev_name will be a snapshot of an lvm leaf of the one we passed
4392
          new_dev_name = rpc.call_blockdev_snapshot(src_node, disk)
4393

    
4394
          if not new_dev_name:
4395
            logger.Error("could not snapshot block device %s on node %s" %
4396
                         (disk.logical_id[1], src_node))
4397
          else:
4398
            new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
4399
                                      logical_id=(vgname, new_dev_name),
4400
                                      physical_id=(vgname, new_dev_name),
4401
                                      iv_name=disk.iv_name)
4402
            snap_disks.append(new_dev)
4403

    
4404
    finally:
4405
      if self.op.shutdown and instance.status == "up":
4406
        if not rpc.call_instance_start(src_node, instance, None):
4407
          _ShutdownInstanceDisks(instance, self.cfg)
4408
          raise errors.OpExecError("Could not start instance")
4409

    
4410
    # TODO: check for size
4411

    
4412
    for dev in snap_disks:
4413
      if not rpc.call_snapshot_export(src_node, dev, dst_node.name, instance):
4414
        logger.Error("could not export block device %s from node %s to node %s"
4415
                     % (dev.logical_id[1], src_node, dst_node.name))
4416
      if not rpc.call_blockdev_remove(src_node, dev):
4417
        logger.Error("could not remove snapshot block device %s from node %s" %
4418
                     (dev.logical_id[1], src_node))
4419

    
4420
    if not rpc.call_finalize_export(dst_node.name, instance, snap_disks):
4421
      logger.Error("could not finalize export for instance %s on node %s" %
4422
                   (instance.name, dst_node.name))
4423

    
4424
    nodelist = self.cfg.GetNodeList()
4425
    nodelist.remove(dst_node.name)
4426

    
4427
    # on one-node clusters nodelist will be empty after the removal
4428
    # if we proceed the backup would be removed because OpQueryExports
4429
    # substitutes an empty list with the full cluster node list.
4430
    if nodelist:
4431
      op = opcodes.OpQueryExports(nodes=nodelist)
4432
      exportlist = self.proc.ChainOpCode(op)
4433
      for node in exportlist:
4434
        if instance.name in exportlist[node]:
4435
          if not rpc.call_export_remove(node, instance.name):
4436
            logger.Error("could not remove older export for instance %s"
4437
                         " on node %s" % (instance.name, node))
4438

    
4439

    
4440
class LURemoveExport(NoHooksLU):
4441
  """Remove exports related to the named instance.
4442

4443
  """
4444
  _OP_REQP = ["instance_name"]
4445

    
4446
  def CheckPrereq(self):
4447
    """Check prerequisites.
4448
    """
4449
    pass
4450

    
4451
  def Exec(self, feedback_fn):
4452
    """Remove any export.
4453

4454
    """
4455
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
4456
    # If the instance was not found we'll try with the name that was passed in.
4457
    # This will only work if it was an FQDN, though.
4458
    fqdn_warn = False
4459
    if not instance_name:
4460
      fqdn_warn = True
4461
      instance_name = self.op.instance_name
4462

    
4463
    op = opcodes.OpQueryExports(nodes=[])
4464
    exportlist = self.proc.ChainOpCode(op)
4465
    found = False
4466
    for node in exportlist:
4467
      if instance_name in exportlist[node]:
4468
        found = True
4469
        if not rpc.call_export_remove(node, instance_name):
4470
          logger.Error("could not remove export for instance %s"
4471
                       " on node %s" % (instance_name, node))
4472

    
4473
    if fqdn_warn and not found:
4474
      feedback_fn("Export not found. If trying to remove an export belonging"
4475
                  " to a deleted instance please use its Fully Qualified"
4476
                  " Domain Name.")
4477

    
4478

    
4479
class TagsLU(NoHooksLU):
4480
  """Generic tags LU.
4481

4482
  This is an abstract class which is the parent of all the other tags LUs.
4483

4484
  """
4485
  def CheckPrereq(self):
4486
    """Check prerequisites.
4487

4488
    """
4489
    if self.op.kind == constants.TAG_CLUSTER:
4490
      self.target = self.cfg.GetClusterInfo()
4491
    elif self.op.kind == constants.TAG_NODE:
4492
      name = self.cfg.ExpandNodeName(self.op.name)
4493
      if name is None:
4494
        raise errors.OpPrereqError("Invalid node name (%s)" %
4495
                                   (self.op.name,))
4496
      self.op.name = name
4497
      self.target = self.cfg.GetNodeInfo(name)
4498
    elif self.op.kind == constants.TAG_INSTANCE:
4499
      name = self.cfg.ExpandInstanceName(self.op.name)
4500
      if name is None:
4501
        raise errors.OpPrereqError("Invalid instance name (%s)" %
4502
                                   (self.op.name,))
4503
      self.op.name = name
4504
      self.target = self.cfg.GetInstanceInfo(name)
4505
    else:
4506
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
4507
                                 str(self.op.kind))
4508

    
4509

    
4510
class LUGetTags(TagsLU):
4511
  """Returns the tags of a given object.
4512

4513
  """
4514
  _OP_REQP = ["kind", "name"]
4515

    
4516
  def Exec(self, feedback_fn):
4517
    """Returns the tag list.
4518

4519
    """
4520
    return list(self.target.GetTags())
4521

    
4522

    
4523
class LUSearchTags(NoHooksLU):
4524
  """Searches the tags for a given pattern.
4525

4526
  """
4527
  _OP_REQP = ["pattern"]
4528

    
4529
  def CheckPrereq(self):
4530
    """Check prerequisites.
4531

4532
    This checks the pattern passed for validity by compiling it.
4533

4534
    """
4535
    try:
4536
      self.re = re.compile(self.op.pattern)
4537
    except re.error, err:
4538
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
4539
                                 (self.op.pattern, err))
4540

    
4541
  def Exec(self, feedback_fn):
4542
    """Returns the tag list.
4543

4544
    """
4545
    cfg = self.cfg
4546
    tgts = [("/cluster", cfg.GetClusterInfo())]
4547
    ilist = [cfg.GetInstanceInfo(name) for name in cfg.GetInstanceList()]
4548
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
4549
    nlist = [cfg.GetNodeInfo(name) for name in cfg.GetNodeList()]
4550
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
4551
    results = []
4552
    for path, target in tgts:
4553
      for tag in target.GetTags():
4554
        if self.re.search(tag):
4555
          results.append((path, tag))
4556
    return results
4557

    
4558

    
4559
class LUAddTags(TagsLU):
4560
  """Sets a tag on a given object.
4561

4562
  """
4563
  _OP_REQP = ["kind", "name", "tags"]
4564

    
4565
  def CheckPrereq(self):
4566
    """Check prerequisites.
4567

4568
    This checks the type and length of the tag name and value.
4569

4570
    """
4571
    TagsLU.CheckPrereq(self)
4572
    for tag in self.op.tags:
4573
      objects.TaggableObject.ValidateTag(tag)
4574

    
4575
  def Exec(self, feedback_fn):
4576
    """Sets the tag.
4577

4578
    """
4579
    try:
4580
      for tag in self.op.tags:
4581
        self.target.AddTag(tag)
4582
    except errors.TagError, err:
4583
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
4584
    try:
4585
      self.cfg.Update(self.target)
4586
    except errors.ConfigurationError:
4587
      raise errors.OpRetryError("There has been a modification to the"
4588
                                " config file and the operation has been"
4589
                                " aborted. Please retry.")
4590

    
4591

    
4592
class LUDelTags(TagsLU):
4593
  """Delete a list of tags from a given object.
4594

4595
  """
4596
  _OP_REQP = ["kind", "name", "tags"]
4597

    
4598
  def CheckPrereq(self):
4599
    """Check prerequisites.
4600

4601
    This checks that we have the given tag.
4602

4603
    """
4604
    TagsLU.CheckPrereq(self)
4605
    for tag in self.op.tags:
4606
      objects.TaggableObject.ValidateTag(tag)
4607
    del_tags = frozenset(self.op.tags)
4608
    cur_tags = self.target.GetTags()
4609
    if not del_tags <= cur_tags:
4610
      diff_tags = del_tags - cur_tags
4611
      diff_names = ["'%s'" % tag for tag in diff_tags]
4612
      diff_names.sort()
4613
      raise errors.OpPrereqError("Tag(s) %s not found" %
4614
                                 (",".join(diff_names)))
4615

    
4616
  def Exec(self, feedback_fn):
4617
    """Remove the tag from the object.
4618

4619
    """
4620
    for tag in self.op.tags:
4621
      self.target.RemoveTag(tag)
4622
    try:
4623
      self.cfg.Update(self.target)
4624
    except errors.ConfigurationError:
4625
      raise errors.OpRetryError("There has been a modification to the"
4626
                                " config file and the operation has been"
4627
                                " aborted. Please retry.")
4628

    
4629

    
4630
class LUTestDelay(NoHooksLU):
4631
  """Sleep for a specified amount of time.
4632

4633
  This LU sleeps on the master and/or nodes for a specified amount of
4634
  time.
4635

4636
  """
4637
  _OP_REQP = ["duration", "on_master", "on_nodes"]
4638
  REQ_BGL = False
4639

    
4640
  def ExpandNames(self):
4641
    """Expand names and set required locks.
4642

4643
    This expands the node list, if any.
4644

4645
    """
4646
    self.needed_locks = {}
4647
    if self.op.on_nodes:
4648
      # _GetWantedNodes can be used here, but is not always appropriate to use
4649
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
4650
      # more information.
4651
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
4652
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
4653

    
4654
  def CheckPrereq(self):
4655
    """Check prerequisites.
4656

4657
    """
4658

    
4659
  def Exec(self, feedback_fn):
4660
    """Do the actual sleep.
4661

4662
    """
4663
    if self.op.on_master:
4664
      if not utils.TestDelay(self.op.duration):
4665
        raise errors.OpExecError("Error during master delay test")
4666
    if self.op.on_nodes:
4667
      result = rpc.call_test_delay(self.op.on_nodes, self.op.duration)
4668
      if not result:
4669
        raise errors.OpExecError("Complete failure from rpc call")
4670
      for node, node_result in result.items():
4671
        if not node_result:
4672
          raise errors.OpExecError("Failure during rpc call to node %s,"
4673
                                   " result: %s" % (node, node_result))
4674

    
4675

    
4676
class IAllocator(object):
4677
  """IAllocator framework.
4678

4679
  An IAllocator instance has three sets of attributes:
4680
    - cfg/sstore that are needed to query the cluster
4681
    - input data (all members of the _KEYS class attribute are required)
4682
    - four buffer attributes (in|out_data|text), that represent the
4683
      input (to the external script) in text and data structure format,
4684
      and the output from it, again in two formats
4685
    - the result variables from the script (success, info, nodes) for
4686
      easy usage
4687

4688
  """
4689
  _ALLO_KEYS = [
4690
    "mem_size", "disks", "disk_template",
4691
    "os", "tags", "nics", "vcpus",
4692
    ]
4693
  _RELO_KEYS = [
4694
    "relocate_from",
4695
    ]
4696

    
4697
  def __init__(self, cfg, sstore, mode, name, **kwargs):
4698
    self.cfg = cfg
4699
    self.sstore = sstore
4700
    # init buffer variables
4701
    self.in_text = self.out_text = self.in_data = self.out_data = None
4702
    # init all input fields so that pylint is happy
4703
    self.mode = mode
4704
    self.name = name
4705
    self.mem_size = self.disks = self.disk_template = None
4706
    self.os = self.tags = self.nics = self.vcpus = None
4707
    self.relocate_from = None
4708
    # computed fields
4709
    self.required_nodes = None
4710
    # init result fields
4711
    self.success = self.info = self.nodes = None
4712
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
4713
      keyset = self._ALLO_KEYS
4714
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
4715
      keyset = self._RELO_KEYS
4716
    else:
4717
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
4718
                                   " IAllocator" % self.mode)
4719
    for key in kwargs:
4720
      if key not in keyset:
4721
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
4722
                                     " IAllocator" % key)
4723
      setattr(self, key, kwargs[key])
4724
    for key in keyset:
4725
      if key not in kwargs:
4726
        raise errors.ProgrammerError("Missing input parameter '%s' to"
4727
                                     " IAllocator" % key)
4728
    self._BuildInputData()
4729

    
4730
  def _ComputeClusterData(self):
4731
    """Compute the generic allocator input data.
4732

4733
    This is the data that is independent of the actual operation.
4734

4735
    """
4736
    cfg = self.cfg
4737
    # cluster data
4738
    data = {
4739
      "version": 1,
4740
      "cluster_name": self.sstore.GetClusterName(),
4741
      "cluster_tags": list(cfg.GetClusterInfo().GetTags()),
4742
      "hypervisor_type": self.sstore.GetHypervisorType(),
4743
      # we don't have job IDs
4744
      }
4745

    
4746
    i_list = [cfg.GetInstanceInfo(iname) for iname in cfg.GetInstanceList()]
4747

    
4748
    # node data
4749
    node_results = {}
4750
    node_list = cfg.GetNodeList()
4751
    node_data = rpc.call_node_info(node_list, cfg.GetVGName())
4752
    for nname in node_list:
4753
      ninfo = cfg.GetNodeInfo(nname)
4754
      if nname not in node_data or not isinstance(node_data[nname], dict):
4755
        raise errors.OpExecError("Can't get data for node %s" % nname)
4756
      remote_info = node_data[nname]
4757
      for attr in ['memory_total', 'memory_free', 'memory_dom0',
4758
                   'vg_size', 'vg_free', 'cpu_total']:
4759
        if attr not in remote_info:
4760
          raise errors.OpExecError("Node '%s' didn't return attribute '%s'" %
4761
                                   (nname, attr))
4762
        try:
4763
          remote_info[attr] = int(remote_info[attr])
4764
        except ValueError, err:
4765
          raise errors.OpExecError("Node '%s' returned invalid value for '%s':"
4766
                                   " %s" % (nname, attr, str(err)))
4767
      # compute memory used by primary instances
4768
      i_p_mem = i_p_up_mem = 0
4769
      for iinfo in i_list:
4770
        if iinfo.primary_node == nname:
4771
          i_p_mem += iinfo.memory
4772
          if iinfo.status == "up":
4773
            i_p_up_mem += iinfo.memory
4774

    
4775
      # compute memory used by instances
4776
      pnr = {
4777
        "tags": list(ninfo.GetTags()),
4778
        "total_memory": remote_info['memory_total'],
4779
        "reserved_memory": remote_info['memory_dom0'],
4780
        "free_memory": remote_info['memory_free'],
4781
        "i_pri_memory": i_p_mem,
4782
        "i_pri_up_memory": i_p_up_mem,
4783
        "total_disk": remote_info['vg_size'],
4784
        "free_disk": remote_info['vg_free'],
4785
        "primary_ip": ninfo.primary_ip,
4786
        "secondary_ip": ninfo.secondary_ip,
4787
        "total_cpus": remote_info['cpu_total'],
4788
        }
4789
      node_results[nname] = pnr
4790
    data["nodes"] = node_results
4791

    
4792
    # instance data
4793
    instance_data = {}
4794
    for iinfo in i_list:
4795
      nic_data = [{"mac": n.mac, "ip": n.ip, "bridge": n.bridge}
4796
                  for n in iinfo.nics]
4797
      pir = {
4798
        "tags": list(iinfo.GetTags()),
4799
        "should_run": iinfo.status == "up",
4800
        "vcpus": iinfo.vcpus,
4801
        "memory": iinfo.memory,
4802
        "os": iinfo.os,
4803
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
4804
        "nics": nic_data,
4805
        "disks": [{"size": dsk.size, "mode": "w"} for dsk in iinfo.disks],
4806
        "disk_template": iinfo.disk_template,
4807
        }
4808
      instance_data[iinfo.name] = pir
4809

    
4810
    data["instances"] = instance_data
4811

    
4812
    self.in_data = data
4813

    
4814
  def _AddNewInstance(self):
4815
    """Add new instance data to allocator structure.
4816

4817
    This in combination with _AllocatorGetClusterData will create the
4818
    correct structure needed as input for the allocator.
4819

4820
    The checks for the completeness of the opcode must have already been
4821
    done.
4822

4823
    """
4824
    data = self.in_data
4825
    if len(self.disks) != 2:
4826
      raise errors.OpExecError("Only two-disk configurations supported")
4827

    
4828
    disk_space = _ComputeDiskSize(self.disk_template,
4829
                                  self.disks[0]["size"], self.disks[1]["size"])
4830

    
4831
    if self.disk_template in constants.DTS_NET_MIRROR:
4832
      self.required_nodes = 2
4833
    else:
4834
      self.required_nodes = 1
4835
    request = {
4836
      "type": "allocate",
4837
      "name": self.name,
4838
      "disk_template": self.disk_template,
4839
      "tags": self.tags,
4840
      "os": self.os,
4841
      "vcpus": self.vcpus,
4842
      "memory": self.mem_size,
4843
      "disks": self.disks,
4844
      "disk_space_total": disk_space,
4845
      "nics": self.nics,
4846
      "required_nodes": self.required_nodes,
4847
      }
4848
    data["request"] = request
4849

    
4850
  def _AddRelocateInstance(self):
4851
    """Add relocate instance data to allocator structure.
4852

4853
    This in combination with _IAllocatorGetClusterData will create the
4854
    correct structure needed as input for the allocator.
4855

4856
    The checks for the completeness of the opcode must have already been
4857
    done.
4858

4859
    """
4860
    instance = self.cfg.GetInstanceInfo(self.name)
4861
    if instance is None:
4862
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
4863
                                   " IAllocator" % self.name)
4864

    
4865
    if instance.disk_template not in constants.DTS_NET_MIRROR:
4866
      raise errors.OpPrereqError("Can't relocate non-mirrored instances")
4867

    
4868
    if len(instance.secondary_nodes) != 1:
4869
      raise errors.OpPrereqError("Instance has not exactly one secondary node")
4870

    
4871
    self.required_nodes = 1
4872

    
4873
    disk_space = _ComputeDiskSize(instance.disk_template,
4874
                                  instance.disks[0].size,
4875
                                  instance.disks[1].size)
4876

    
4877
    request = {
4878
      "type": "relocate",
4879
      "name": self.name,
4880
      "disk_space_total": disk_space,
4881
      "required_nodes": self.required_nodes,
4882
      "relocate_from": self.relocate_from,
4883
      }
4884
    self.in_data["request"] = request
4885

    
4886
  def _BuildInputData(self):
4887
    """Build input data structures.
4888

4889
    """
4890
    self._ComputeClusterData()
4891

    
4892
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
4893
      self._AddNewInstance()
4894
    else:
4895
      self._AddRelocateInstance()
4896

    
4897
    self.in_text = serializer.Dump(self.in_data)
4898

    
4899
  def Run(self, name, validate=True, call_fn=rpc.call_iallocator_runner):
4900
    """Run an instance allocator and return the results.
4901

4902
    """
4903
    data = self.in_text
4904

    
4905
    result = call_fn(self.sstore.GetMasterNode(), name, self.in_text)
4906

    
4907
    if not isinstance(result, tuple) or len(result) != 4:
4908
      raise errors.OpExecError("Invalid result from master iallocator runner")
4909

    
4910
    rcode, stdout, stderr, fail = result
4911

    
4912
    if rcode == constants.IARUN_NOTFOUND:
4913
      raise errors.OpExecError("Can't find allocator '%s'" % name)
4914
    elif rcode == constants.IARUN_FAILURE:
4915
        raise errors.OpExecError("Instance allocator call failed: %s,"
4916
                                 " output: %s" %
4917
                                 (fail, stdout+stderr))
4918
    self.out_text = stdout
4919
    if validate:
4920
      self._ValidateResult()
4921

    
4922
  def _ValidateResult(self):
4923
    """Process the allocator results.
4924

4925
    This will process and if successful save the result in
4926
    self.out_data and the other parameters.
4927

4928
    """
4929
    try:
4930
      rdict = serializer.Load(self.out_text)
4931
    except Exception, err:
4932
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
4933

    
4934
    if not isinstance(rdict, dict):
4935
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
4936

    
4937
    for key in "success", "info", "nodes":
4938
      if key not in rdict:
4939
        raise errors.OpExecError("Can't parse iallocator results:"
4940
                                 " missing key '%s'" % key)
4941
      setattr(self, key, rdict[key])
4942

    
4943
    if not isinstance(rdict["nodes"], list):
4944
      raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
4945
                               " is not a list")
4946
    self.out_data = rdict
4947

    
4948

    
4949
class LUTestAllocator(NoHooksLU):
4950
  """Run allocator tests.
4951

4952
  This LU runs the allocator tests
4953

4954
  """
4955
  _OP_REQP = ["direction", "mode", "name"]
4956

    
4957
  def CheckPrereq(self):
4958
    """Check prerequisites.
4959

4960
    This checks the opcode parameters depending on the director and mode test.
4961

4962
    """
4963
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
4964
      for attr in ["name", "mem_size", "disks", "disk_template",
4965
                   "os", "tags", "nics", "vcpus"]:
4966
        if not hasattr(self.op, attr):
4967
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
4968
                                     attr)
4969
      iname = self.cfg.ExpandInstanceName(self.op.name)
4970
      if iname is not None:
4971
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
4972
                                   iname)
4973
      if not isinstance(self.op.nics, list):
4974
        raise errors.OpPrereqError("Invalid parameter 'nics'")
4975
      for row in self.op.nics:
4976
        if (not isinstance(row, dict) or
4977
            "mac" not in row or
4978
            "ip" not in row or
4979
            "bridge" not in row):
4980
          raise errors.OpPrereqError("Invalid contents of the"
4981
                                     " 'nics' parameter")
4982
      if not isinstance(self.op.disks, list):
4983
        raise errors.OpPrereqError("Invalid parameter 'disks'")
4984
      if len(self.op.disks) != 2:
4985
        raise errors.OpPrereqError("Only two-disk configurations supported")
4986
      for row in self.op.disks:
4987
        if (not isinstance(row, dict) or
4988
            "size" not in row or
4989
            not isinstance(row["size"], int) or
4990
            "mode" not in row or
4991
            row["mode"] not in ['r', 'w']):
4992
          raise errors.OpPrereqError("Invalid contents of the"
4993
                                     " 'disks' parameter")
4994
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
4995
      if not hasattr(self.op, "name"):
4996
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input")
4997
      fname = self.cfg.ExpandInstanceName(self.op.name)
4998
      if fname is None:
4999
        raise errors.OpPrereqError("Instance '%s' not found for relocation" %
5000
                                   self.op.name)
5001
      self.op.name = fname
5002
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
5003
    else:
5004
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
5005
                                 self.op.mode)
5006

    
5007
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
5008
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
5009
        raise errors.OpPrereqError("Missing allocator name")
5010
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
5011
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
5012
                                 self.op.direction)
5013

    
5014
  def Exec(self, feedback_fn):
5015
    """Run the allocator test.
5016

5017
    """
5018
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
5019
      ial = IAllocator(self.cfg, self.sstore,
5020
                       mode=self.op.mode,
5021
                       name=self.op.name,
5022
                       mem_size=self.op.mem_size,
5023
                       disks=self.op.disks,
5024
                       disk_template=self.op.disk_template,
5025
                       os=self.op.os,
5026
                       tags=self.op.tags,
5027
                       nics=self.op.nics,
5028
                       vcpus=self.op.vcpus,
5029
                       )
5030
    else:
5031
      ial = IAllocator(self.cfg, self.sstore,
5032
                       mode=self.op.mode,
5033
                       name=self.op.name,
5034
                       relocate_from=list(self.relocate_from),
5035
                       )
5036

    
5037
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
5038
      result = ial.in_text
5039
    else:
5040
      ial.Run(self.op.allocator, validate=False)
5041
      result = ial.out_text
5042
    return result