Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ c4a2fee1

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

    
2195
  def BuildHooksEnv(self):
2196
    """Build hooks env.
2197

2198
    This runs on master, primary and secondary nodes of the instance.
2199

2200
    """
2201
    env = _BuildInstanceHookEnvByObject(self.instance)
2202
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2203
          list(self.instance.secondary_nodes))
2204
    return env, nl, nl
2205

    
2206
  def CheckPrereq(self):
2207
    """Check prerequisites.
2208

2209
    This checks that the instance is in the cluster and is not running.
2210

2211
    """
2212
    instance = self.cfg.GetInstanceInfo(
2213
      self.cfg.ExpandInstanceName(self.op.instance_name))
2214
    if instance is None:
2215
      raise errors.OpPrereqError("Instance '%s' not known" %
2216
                                 self.op.instance_name)
2217
    if instance.disk_template == constants.DT_DISKLESS:
2218
      raise errors.OpPrereqError("Instance '%s' has no disks" %
2219
                                 self.op.instance_name)
2220
    if instance.status != "down":
2221
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2222
                                 self.op.instance_name)
2223
    remote_info = rpc.call_instance_info(instance.primary_node, instance.name)
2224
    if remote_info:
2225
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2226
                                 (self.op.instance_name,
2227
                                  instance.primary_node))
2228

    
2229
    self.op.os_type = getattr(self.op, "os_type", None)
2230
    if self.op.os_type is not None:
2231
      # OS verification
2232
      pnode = self.cfg.GetNodeInfo(
2233
        self.cfg.ExpandNodeName(instance.primary_node))
2234
      if pnode is None:
2235
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
2236
                                   self.op.pnode)
2237
      os_obj = rpc.call_os_get(pnode.name, self.op.os_type)
2238
      if not os_obj:
2239
        raise errors.OpPrereqError("OS '%s' not in supported OS list for"
2240
                                   " primary node"  % self.op.os_type)
2241

    
2242
    self.instance = instance
2243

    
2244
  def Exec(self, feedback_fn):
2245
    """Reinstall the instance.
2246

2247
    """
2248
    inst = self.instance
2249

    
2250
    if self.op.os_type is not None:
2251
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
2252
      inst.os = self.op.os_type
2253
      self.cfg.AddInstance(inst)
2254

    
2255
    _StartInstanceDisks(self.cfg, inst, None)
2256
    try:
2257
      feedback_fn("Running the instance OS create scripts...")
2258
      if not rpc.call_instance_os_add(inst.primary_node, inst, "sda", "sdb"):
2259
        raise errors.OpExecError("Could not install OS for instance %s"
2260
                                 " on node %s" %
2261
                                 (inst.name, inst.primary_node))
2262
    finally:
2263
      _ShutdownInstanceDisks(inst, self.cfg)
2264

    
2265

    
2266
class LURenameInstance(LogicalUnit):
2267
  """Rename an instance.
2268

2269
  """
2270
  HPATH = "instance-rename"
2271
  HTYPE = constants.HTYPE_INSTANCE
2272
  _OP_REQP = ["instance_name", "new_name"]
2273

    
2274
  def BuildHooksEnv(self):
2275
    """Build hooks env.
2276

2277
    This runs on master, primary and secondary nodes of the instance.
2278

2279
    """
2280
    env = _BuildInstanceHookEnvByObject(self.instance)
2281
    env["INSTANCE_NEW_NAME"] = self.op.new_name
2282
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2283
          list(self.instance.secondary_nodes))
2284
    return env, nl, nl
2285

    
2286
  def CheckPrereq(self):
2287
    """Check prerequisites.
2288

2289
    This checks that the instance is in the cluster and is not running.
2290

2291
    """
2292
    instance = self.cfg.GetInstanceInfo(
2293
      self.cfg.ExpandInstanceName(self.op.instance_name))
2294
    if instance is None:
2295
      raise errors.OpPrereqError("Instance '%s' not known" %
2296
                                 self.op.instance_name)
2297
    if instance.status != "down":
2298
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2299
                                 self.op.instance_name)
2300
    remote_info = rpc.call_instance_info(instance.primary_node, instance.name)
2301
    if remote_info:
2302
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2303
                                 (self.op.instance_name,
2304
                                  instance.primary_node))
2305
    self.instance = instance
2306

    
2307
    # new name verification
2308
    name_info = utils.HostInfo(self.op.new_name)
2309

    
2310
    self.op.new_name = new_name = name_info.name
2311
    instance_list = self.cfg.GetInstanceList()
2312
    if new_name in instance_list:
2313
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
2314
                                 new_name)
2315

    
2316
    if not getattr(self.op, "ignore_ip", False):
2317
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
2318
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
2319
                                   (name_info.ip, new_name))
2320

    
2321

    
2322
  def Exec(self, feedback_fn):
2323
    """Reinstall the instance.
2324

2325
    """
2326
    inst = self.instance
2327
    old_name = inst.name
2328

    
2329
    if inst.disk_template == constants.DT_FILE:
2330
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2331

    
2332
    self.cfg.RenameInstance(inst.name, self.op.new_name)
2333
    # Change the instance lock. This is definitely safe while we hold the BGL
2334
    self.context.glm.remove(locking.LEVEL_INSTANCE, inst.name)
2335
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
2336

    
2337
    # re-read the instance from the configuration after rename
2338
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
2339

    
2340
    if inst.disk_template == constants.DT_FILE:
2341
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2342
      result = rpc.call_file_storage_dir_rename(inst.primary_node,
2343
                                                old_file_storage_dir,
2344
                                                new_file_storage_dir)
2345

    
2346
      if not result:
2347
        raise errors.OpExecError("Could not connect to node '%s' to rename"
2348
                                 " directory '%s' to '%s' (but the instance"
2349
                                 " has been renamed in Ganeti)" % (
2350
                                 inst.primary_node, old_file_storage_dir,
2351
                                 new_file_storage_dir))
2352

    
2353
      if not result[0]:
2354
        raise errors.OpExecError("Could not rename directory '%s' to '%s'"
2355
                                 " (but the instance has been renamed in"
2356
                                 " Ganeti)" % (old_file_storage_dir,
2357
                                               new_file_storage_dir))
2358

    
2359
    _StartInstanceDisks(self.cfg, inst, None)
2360
    try:
2361
      if not rpc.call_instance_run_rename(inst.primary_node, inst, old_name,
2362
                                          "sda", "sdb"):
2363
        msg = ("Could run OS rename script for instance %s on node %s (but the"
2364
               " instance has been renamed in Ganeti)" %
2365
               (inst.name, inst.primary_node))
2366
        logger.Error(msg)
2367
    finally:
2368
      _ShutdownInstanceDisks(inst, self.cfg)
2369

    
2370

    
2371
class LURemoveInstance(LogicalUnit):
2372
  """Remove an instance.
2373

2374
  """
2375
  HPATH = "instance-remove"
2376
  HTYPE = constants.HTYPE_INSTANCE
2377
  _OP_REQP = ["instance_name", "ignore_failures"]
2378

    
2379
  def BuildHooksEnv(self):
2380
    """Build hooks env.
2381

2382
    This runs on master, primary and secondary nodes of the instance.
2383

2384
    """
2385
    env = _BuildInstanceHookEnvByObject(self.instance)
2386
    nl = [self.sstore.GetMasterNode()]
2387
    return env, nl, nl
2388

    
2389
  def CheckPrereq(self):
2390
    """Check prerequisites.
2391

2392
    This checks that the instance is in the cluster.
2393

2394
    """
2395
    instance = self.cfg.GetInstanceInfo(
2396
      self.cfg.ExpandInstanceName(self.op.instance_name))
2397
    if instance is None:
2398
      raise errors.OpPrereqError("Instance '%s' not known" %
2399
                                 self.op.instance_name)
2400
    self.instance = instance
2401

    
2402
  def Exec(self, feedback_fn):
2403
    """Remove the instance.
2404

2405
    """
2406
    instance = self.instance
2407
    logger.Info("shutting down instance %s on node %s" %
2408
                (instance.name, instance.primary_node))
2409

    
2410
    if not rpc.call_instance_shutdown(instance.primary_node, instance):
2411
      if self.op.ignore_failures:
2412
        feedback_fn("Warning: can't shutdown instance")
2413
      else:
2414
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
2415
                                 (instance.name, instance.primary_node))
2416

    
2417
    logger.Info("removing block devices for instance %s" % instance.name)
2418

    
2419
    if not _RemoveDisks(instance, self.cfg):
2420
      if self.op.ignore_failures:
2421
        feedback_fn("Warning: can't remove instance's disks")
2422
      else:
2423
        raise errors.OpExecError("Can't remove instance's disks")
2424

    
2425
    logger.Info("removing instance %s out of cluster config" % instance.name)
2426

    
2427
    self.cfg.RemoveInstance(instance.name)
2428
    # Remove the new instance from the Ganeti Lock Manager
2429
    self.context.glm.remove(locking.LEVEL_INSTANCE, instance.name)
2430

    
2431

    
2432
class LUQueryInstances(NoHooksLU):
2433
  """Logical unit for querying instances.
2434

2435
  """
2436
  _OP_REQP = ["output_fields", "names"]
2437

    
2438
  def CheckPrereq(self):
2439
    """Check prerequisites.
2440

2441
    This checks that the fields required are valid output fields.
2442

2443
    """
2444
    self.dynamic_fields = frozenset(["oper_state", "oper_ram", "status"])
2445
    _CheckOutputFields(static=["name", "os", "pnode", "snodes",
2446
                               "admin_state", "admin_ram",
2447
                               "disk_template", "ip", "mac", "bridge",
2448
                               "sda_size", "sdb_size", "vcpus", "tags"],
2449
                       dynamic=self.dynamic_fields,
2450
                       selected=self.op.output_fields)
2451

    
2452
    self.wanted = _GetWantedInstances(self, self.op.names)
2453

    
2454
  def Exec(self, feedback_fn):
2455
    """Computes the list of nodes and their attributes.
2456

2457
    """
2458
    instance_names = self.wanted
2459
    instance_list = [self.cfg.GetInstanceInfo(iname) for iname
2460
                     in instance_names]
2461

    
2462
    # begin data gathering
2463

    
2464
    nodes = frozenset([inst.primary_node for inst in instance_list])
2465

    
2466
    bad_nodes = []
2467
    if self.dynamic_fields.intersection(self.op.output_fields):
2468
      live_data = {}
2469
      node_data = rpc.call_all_instances_info(nodes)
2470
      for name in nodes:
2471
        result = node_data[name]
2472
        if result:
2473
          live_data.update(result)
2474
        elif result == False:
2475
          bad_nodes.append(name)
2476
        # else no instance is alive
2477
    else:
2478
      live_data = dict([(name, {}) for name in instance_names])
2479

    
2480
    # end data gathering
2481

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

    
2548
    return output
2549

    
2550

    
2551
class LUFailoverInstance(LogicalUnit):
2552
  """Failover an instance.
2553

2554
  """
2555
  HPATH = "instance-failover"
2556
  HTYPE = constants.HTYPE_INSTANCE
2557
  _OP_REQP = ["instance_name", "ignore_consistency"]
2558

    
2559
  def BuildHooksEnv(self):
2560
    """Build hooks env.
2561

2562
    This runs on master, primary and secondary nodes of the instance.
2563

2564
    """
2565
    env = {
2566
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
2567
      }
2568
    env.update(_BuildInstanceHookEnvByObject(self.instance))
2569
    nl = [self.sstore.GetMasterNode()] + list(self.instance.secondary_nodes)
2570
    return env, nl, nl
2571

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

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

2577
    """
2578
    instance = self.cfg.GetInstanceInfo(
2579
      self.cfg.ExpandInstanceName(self.op.instance_name))
2580
    if instance is None:
2581
      raise errors.OpPrereqError("Instance '%s' not known" %
2582
                                 self.op.instance_name)
2583

    
2584
    if instance.disk_template not in constants.DTS_NET_MIRROR:
2585
      raise errors.OpPrereqError("Instance's disk layout is not"
2586
                                 " network mirrored, cannot failover.")
2587

    
2588
    secondary_nodes = instance.secondary_nodes
2589
    if not secondary_nodes:
2590
      raise errors.ProgrammerError("no secondary node but using "
2591
                                   "a mirrored disk template")
2592

    
2593
    target_node = secondary_nodes[0]
2594
    # check memory requirements on the secondary node
2595
    _CheckNodeFreeMemory(self.cfg, target_node, "failing over instance %s" %
2596
                         instance.name, instance.memory)
2597

    
2598
    # check bridge existance
2599
    brlist = [nic.bridge for nic in instance.nics]
2600
    if not rpc.call_bridges_exist(target_node, brlist):
2601
      raise errors.OpPrereqError("One or more target bridges %s does not"
2602
                                 " exist on destination node '%s'" %
2603
                                 (brlist, target_node))
2604

    
2605
    self.instance = instance
2606

    
2607
  def Exec(self, feedback_fn):
2608
    """Failover an instance.
2609

2610
    The failover is done by shutting it down on its present node and
2611
    starting it on the secondary.
2612

2613
    """
2614
    instance = self.instance
2615

    
2616
    source_node = instance.primary_node
2617
    target_node = instance.secondary_nodes[0]
2618

    
2619
    feedback_fn("* checking disk consistency between source and target")
2620
    for dev in instance.disks:
2621
      # for drbd, these are drbd over lvm
2622
      if not _CheckDiskConsistency(self.cfg, dev, target_node, False):
2623
        if instance.status == "up" and not self.op.ignore_consistency:
2624
          raise errors.OpExecError("Disk %s is degraded on target node,"
2625
                                   " aborting failover." % dev.iv_name)
2626

    
2627
    feedback_fn("* shutting down instance on source node")
2628
    logger.Info("Shutting down instance %s on node %s" %
2629
                (instance.name, source_node))
2630

    
2631
    if not rpc.call_instance_shutdown(source_node, instance):
2632
      if self.op.ignore_consistency:
2633
        logger.Error("Could not shutdown instance %s on node %s. Proceeding"
2634
                     " anyway. Please make sure node %s is down"  %
2635
                     (instance.name, source_node, source_node))
2636
      else:
2637
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
2638
                                 (instance.name, source_node))
2639

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

    
2644
    instance.primary_node = target_node
2645
    # distribute new instance config to the other nodes
2646
    self.cfg.Update(instance)
2647

    
2648
    # Only start the instance if it's marked as up
2649
    if instance.status == "up":
2650
      feedback_fn("* activating the instance's disks on target node")
2651
      logger.Info("Starting instance %s on node %s" %
2652
                  (instance.name, target_node))
2653

    
2654
      disks_ok, dummy = _AssembleInstanceDisks(instance, self.cfg,
2655
                                               ignore_secondaries=True)
2656
      if not disks_ok:
2657
        _ShutdownInstanceDisks(instance, self.cfg)
2658
        raise errors.OpExecError("Can't activate the instance's disks")
2659

    
2660
      feedback_fn("* starting the instance on the target node")
2661
      if not rpc.call_instance_start(target_node, instance, None):
2662
        _ShutdownInstanceDisks(instance, self.cfg)
2663
        raise errors.OpExecError("Could not start instance %s on node %s." %
2664
                                 (instance.name, target_node))
2665

    
2666

    
2667
def _CreateBlockDevOnPrimary(cfg, node, instance, device, info):
2668
  """Create a tree of block devices on the primary node.
2669

2670
  This always creates all devices.
2671

2672
  """
2673
  if device.children:
2674
    for child in device.children:
2675
      if not _CreateBlockDevOnPrimary(cfg, node, instance, child, info):
2676
        return False
2677

    
2678
  cfg.SetDiskID(device, node)
2679
  new_id = rpc.call_blockdev_create(node, device, device.size,
2680
                                    instance.name, True, info)
2681
  if not new_id:
2682
    return False
2683
  if device.physical_id is None:
2684
    device.physical_id = new_id
2685
  return True
2686

    
2687

    
2688
def _CreateBlockDevOnSecondary(cfg, node, instance, device, force, info):
2689
  """Create a tree of block devices on a secondary node.
2690

2691
  If this device type has to be created on secondaries, create it and
2692
  all its children.
2693

2694
  If not, just recurse to children keeping the same 'force' value.
2695

2696
  """
2697
  if device.CreateOnSecondary():
2698
    force = True
2699
  if device.children:
2700
    for child in device.children:
2701
      if not _CreateBlockDevOnSecondary(cfg, node, instance,
2702
                                        child, force, info):
2703
        return False
2704

    
2705
  if not force:
2706
    return True
2707
  cfg.SetDiskID(device, node)
2708
  new_id = rpc.call_blockdev_create(node, device, device.size,
2709
                                    instance.name, False, info)
2710
  if not new_id:
2711
    return False
2712
  if device.physical_id is None:
2713
    device.physical_id = new_id
2714
  return True
2715

    
2716

    
2717
def _GenerateUniqueNames(cfg, exts):
2718
  """Generate a suitable LV name.
2719

2720
  This will generate a logical volume name for the given instance.
2721

2722
  """
2723
  results = []
2724
  for val in exts:
2725
    new_id = cfg.GenerateUniqueID()
2726
    results.append("%s%s" % (new_id, val))
2727
  return results
2728

    
2729

    
2730
def _GenerateDRBD8Branch(cfg, primary, secondary, size, names, iv_name):
2731
  """Generate a drbd8 device complete with its children.
2732

2733
  """
2734
  port = cfg.AllocatePort()
2735
  vgname = cfg.GetVGName()
2736
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
2737
                          logical_id=(vgname, names[0]))
2738
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
2739
                          logical_id=(vgname, names[1]))
2740
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
2741
                          logical_id = (primary, secondary, port),
2742
                          children = [dev_data, dev_meta],
2743
                          iv_name=iv_name)
2744
  return drbd_dev
2745

    
2746

    
2747
def _GenerateDiskTemplate(cfg, template_name,
2748
                          instance_name, primary_node,
2749
                          secondary_nodes, disk_sz, swap_sz,
2750
                          file_storage_dir, file_driver):
2751
  """Generate the entire disk layout for a given template type.
2752

2753
  """
2754
  #TODO: compute space requirements
2755

    
2756
  vgname = cfg.GetVGName()
2757
  if template_name == constants.DT_DISKLESS:
2758
    disks = []
2759
  elif template_name == constants.DT_PLAIN:
2760
    if len(secondary_nodes) != 0:
2761
      raise errors.ProgrammerError("Wrong template configuration")
2762

    
2763
    names = _GenerateUniqueNames(cfg, [".sda", ".sdb"])
2764
    sda_dev = objects.Disk(dev_type=constants.LD_LV, size=disk_sz,
2765
                           logical_id=(vgname, names[0]),
2766
                           iv_name = "sda")
2767
    sdb_dev = objects.Disk(dev_type=constants.LD_LV, size=swap_sz,
2768
                           logical_id=(vgname, names[1]),
2769
                           iv_name = "sdb")
2770
    disks = [sda_dev, sdb_dev]
2771
  elif template_name == constants.DT_DRBD8:
2772
    if len(secondary_nodes) != 1:
2773
      raise errors.ProgrammerError("Wrong template configuration")
2774
    remote_node = secondary_nodes[0]
2775
    names = _GenerateUniqueNames(cfg, [".sda_data", ".sda_meta",
2776
                                       ".sdb_data", ".sdb_meta"])
2777
    drbd_sda_dev = _GenerateDRBD8Branch(cfg, primary_node, remote_node,
2778
                                         disk_sz, names[0:2], "sda")
2779
    drbd_sdb_dev = _GenerateDRBD8Branch(cfg, primary_node, remote_node,
2780
                                         swap_sz, names[2:4], "sdb")
2781
    disks = [drbd_sda_dev, drbd_sdb_dev]
2782
  elif template_name == constants.DT_FILE:
2783
    if len(secondary_nodes) != 0:
2784
      raise errors.ProgrammerError("Wrong template configuration")
2785

    
2786
    file_sda_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk_sz,
2787
                                iv_name="sda", logical_id=(file_driver,
2788
                                "%s/sda" % file_storage_dir))
2789
    file_sdb_dev = objects.Disk(dev_type=constants.LD_FILE, size=swap_sz,
2790
                                iv_name="sdb", logical_id=(file_driver,
2791
                                "%s/sdb" % file_storage_dir))
2792
    disks = [file_sda_dev, file_sdb_dev]
2793
  else:
2794
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
2795
  return disks
2796

    
2797

    
2798
def _GetInstanceInfoText(instance):
2799
  """Compute that text that should be added to the disk's metadata.
2800

2801
  """
2802
  return "originstname+%s" % instance.name
2803

    
2804

    
2805
def _CreateDisks(cfg, instance):
2806
  """Create all disks for an instance.
2807

2808
  This abstracts away some work from AddInstance.
2809

2810
  Args:
2811
    instance: the instance object
2812

2813
  Returns:
2814
    True or False showing the success of the creation process
2815

2816
  """
2817
  info = _GetInstanceInfoText(instance)
2818

    
2819
  if instance.disk_template == constants.DT_FILE:
2820
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
2821
    result = rpc.call_file_storage_dir_create(instance.primary_node,
2822
                                              file_storage_dir)
2823

    
2824
    if not result:
2825
      logger.Error("Could not connect to node '%s'" % instance.primary_node)
2826
      return False
2827

    
2828
    if not result[0]:
2829
      logger.Error("failed to create directory '%s'" % file_storage_dir)
2830
      return False
2831

    
2832
  for device in instance.disks:
2833
    logger.Info("creating volume %s for instance %s" %
2834
                (device.iv_name, instance.name))
2835
    #HARDCODE
2836
    for secondary_node in instance.secondary_nodes:
2837
      if not _CreateBlockDevOnSecondary(cfg, secondary_node, instance,
2838
                                        device, False, info):
2839
        logger.Error("failed to create volume %s (%s) on secondary node %s!" %
2840
                     (device.iv_name, device, secondary_node))
2841
        return False
2842
    #HARDCODE
2843
    if not _CreateBlockDevOnPrimary(cfg, instance.primary_node,
2844
                                    instance, device, info):
2845
      logger.Error("failed to create volume %s on primary!" %
2846
                   device.iv_name)
2847
      return False
2848

    
2849
  return True
2850

    
2851

    
2852
def _RemoveDisks(instance, cfg):
2853
  """Remove all disks for an instance.
2854

2855
  This abstracts away some work from `AddInstance()` and
2856
  `RemoveInstance()`. Note that in case some of the devices couldn't
2857
  be removed, the removal will continue with the other ones (compare
2858
  with `_CreateDisks()`).
2859

2860
  Args:
2861
    instance: the instance object
2862

2863
  Returns:
2864
    True or False showing the success of the removal proces
2865

2866
  """
2867
  logger.Info("removing block devices for instance %s" % instance.name)
2868

    
2869
  result = True
2870
  for device in instance.disks:
2871
    for node, disk in device.ComputeNodeTree(instance.primary_node):
2872
      cfg.SetDiskID(disk, node)
2873
      if not rpc.call_blockdev_remove(node, disk):
2874
        logger.Error("could not remove block device %s on node %s,"
2875
                     " continuing anyway" %
2876
                     (device.iv_name, node))
2877
        result = False
2878

    
2879
  if instance.disk_template == constants.DT_FILE:
2880
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
2881
    if not rpc.call_file_storage_dir_remove(instance.primary_node,
2882
                                            file_storage_dir):
2883
      logger.Error("could not remove directory '%s'" % file_storage_dir)
2884
      result = False
2885

    
2886
  return result
2887

    
2888

    
2889
def _ComputeDiskSize(disk_template, disk_size, swap_size):
2890
  """Compute disk size requirements in the volume group
2891

2892
  This is currently hard-coded for the two-drive layout.
2893

2894
  """
2895
  # Required free disk space as a function of disk and swap space
2896
  req_size_dict = {
2897
    constants.DT_DISKLESS: None,
2898
    constants.DT_PLAIN: disk_size + swap_size,
2899
    # 256 MB are added for drbd metadata, 128MB for each drbd device
2900
    constants.DT_DRBD8: disk_size + swap_size + 256,
2901
    constants.DT_FILE: None,
2902
  }
2903

    
2904
  if disk_template not in req_size_dict:
2905
    raise errors.ProgrammerError("Disk template '%s' size requirement"
2906
                                 " is unknown" %  disk_template)
2907

    
2908
  return req_size_dict[disk_template]
2909

    
2910

    
2911
class LUCreateInstance(LogicalUnit):
2912
  """Create an instance.
2913

2914
  """
2915
  HPATH = "instance-add"
2916
  HTYPE = constants.HTYPE_INSTANCE
2917
  _OP_REQP = ["instance_name", "mem_size", "disk_size",
2918
              "disk_template", "swap_size", "mode", "start", "vcpus",
2919
              "wait_for_sync", "ip_check", "mac"]
2920

    
2921
  def _RunAllocator(self):
2922
    """Run the allocator based on input opcode.
2923

2924
    """
2925
    disks = [{"size": self.op.disk_size, "mode": "w"},
2926
             {"size": self.op.swap_size, "mode": "w"}]
2927
    nics = [{"mac": self.op.mac, "ip": getattr(self.op, "ip", None),
2928
             "bridge": self.op.bridge}]
2929
    ial = IAllocator(self.cfg, self.sstore,
2930
                     mode=constants.IALLOCATOR_MODE_ALLOC,
2931
                     name=self.op.instance_name,
2932
                     disk_template=self.op.disk_template,
2933
                     tags=[],
2934
                     os=self.op.os_type,
2935
                     vcpus=self.op.vcpus,
2936
                     mem_size=self.op.mem_size,
2937
                     disks=disks,
2938
                     nics=nics,
2939
                     )
2940

    
2941
    ial.Run(self.op.iallocator)
2942

    
2943
    if not ial.success:
2944
      raise errors.OpPrereqError("Can't compute nodes using"
2945
                                 " iallocator '%s': %s" % (self.op.iallocator,
2946
                                                           ial.info))
2947
    if len(ial.nodes) != ial.required_nodes:
2948
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
2949
                                 " of nodes (%s), required %s" %
2950
                                 (len(ial.nodes), ial.required_nodes))
2951
    self.op.pnode = ial.nodes[0]
2952
    logger.ToStdout("Selected nodes for the instance: %s" %
2953
                    (", ".join(ial.nodes),))
2954
    logger.Info("Selected nodes for instance %s via iallocator %s: %s" %
2955
                (self.op.instance_name, self.op.iallocator, ial.nodes))
2956
    if ial.required_nodes == 2:
2957
      self.op.snode = ial.nodes[1]
2958

    
2959
  def BuildHooksEnv(self):
2960
    """Build hooks env.
2961

2962
    This runs on master, primary and secondary nodes of the instance.
2963

2964
    """
2965
    env = {
2966
      "INSTANCE_DISK_TEMPLATE": self.op.disk_template,
2967
      "INSTANCE_DISK_SIZE": self.op.disk_size,
2968
      "INSTANCE_SWAP_SIZE": self.op.swap_size,
2969
      "INSTANCE_ADD_MODE": self.op.mode,
2970
      }
2971
    if self.op.mode == constants.INSTANCE_IMPORT:
2972
      env["INSTANCE_SRC_NODE"] = self.op.src_node
2973
      env["INSTANCE_SRC_PATH"] = self.op.src_path
2974
      env["INSTANCE_SRC_IMAGE"] = self.src_image
2975

    
2976
    env.update(_BuildInstanceHookEnv(name=self.op.instance_name,
2977
      primary_node=self.op.pnode,
2978
      secondary_nodes=self.secondaries,
2979
      status=self.instance_status,
2980
      os_type=self.op.os_type,
2981
      memory=self.op.mem_size,
2982
      vcpus=self.op.vcpus,
2983
      nics=[(self.inst_ip, self.op.bridge, self.op.mac)],
2984
    ))
2985

    
2986
    nl = ([self.sstore.GetMasterNode(), self.op.pnode] +
2987
          self.secondaries)
2988
    return env, nl, nl
2989

    
2990

    
2991
  def CheckPrereq(self):
2992
    """Check prerequisites.
2993

2994
    """
2995
    # set optional parameters to none if they don't exist
2996
    for attr in ["kernel_path", "initrd_path", "hvm_boot_order", "pnode",
2997
                 "iallocator", "hvm_acpi", "hvm_pae", "hvm_cdrom_image_path",
2998
                 "vnc_bind_address"]:
2999
      if not hasattr(self.op, attr):
3000
        setattr(self.op, attr, None)
3001

    
3002
    if self.op.mode not in (constants.INSTANCE_CREATE,
3003
                            constants.INSTANCE_IMPORT):
3004
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
3005
                                 self.op.mode)
3006

    
3007
    if (not self.cfg.GetVGName() and
3008
        self.op.disk_template not in constants.DTS_NOT_LVM):
3009
      raise errors.OpPrereqError("Cluster does not support lvm-based"
3010
                                 " instances")
3011

    
3012
    if self.op.mode == constants.INSTANCE_IMPORT:
3013
      src_node = getattr(self.op, "src_node", None)
3014
      src_path = getattr(self.op, "src_path", None)
3015
      if src_node is None or src_path is None:
3016
        raise errors.OpPrereqError("Importing an instance requires source"
3017
                                   " node and path options")
3018
      src_node_full = self.cfg.ExpandNodeName(src_node)
3019
      if src_node_full is None:
3020
        raise errors.OpPrereqError("Unknown source node '%s'" % src_node)
3021
      self.op.src_node = src_node = src_node_full
3022

    
3023
      if not os.path.isabs(src_path):
3024
        raise errors.OpPrereqError("The source path must be absolute")
3025

    
3026
      export_info = rpc.call_export_info(src_node, src_path)
3027

    
3028
      if not export_info:
3029
        raise errors.OpPrereqError("No export found in dir %s" % src_path)
3030

    
3031
      if not export_info.has_section(constants.INISECT_EXP):
3032
        raise errors.ProgrammerError("Corrupted export config")
3033

    
3034
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
3035
      if (int(ei_version) != constants.EXPORT_VERSION):
3036
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
3037
                                   (ei_version, constants.EXPORT_VERSION))
3038

    
3039
      if int(export_info.get(constants.INISECT_INS, 'disk_count')) > 1:
3040
        raise errors.OpPrereqError("Can't import instance with more than"
3041
                                   " one data disk")
3042

    
3043
      # FIXME: are the old os-es, disk sizes, etc. useful?
3044
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
3045
      diskimage = os.path.join(src_path, export_info.get(constants.INISECT_INS,
3046
                                                         'disk0_dump'))
3047
      self.src_image = diskimage
3048
    else: # INSTANCE_CREATE
3049
      if getattr(self.op, "os_type", None) is None:
3050
        raise errors.OpPrereqError("No guest OS specified")
3051

    
3052
    #### instance parameters check
3053

    
3054
    # disk template and mirror node verification
3055
    if self.op.disk_template not in constants.DISK_TEMPLATES:
3056
      raise errors.OpPrereqError("Invalid disk template name")
3057

    
3058
    # instance name verification
3059
    hostname1 = utils.HostInfo(self.op.instance_name)
3060

    
3061
    self.op.instance_name = instance_name = hostname1.name
3062
    instance_list = self.cfg.GetInstanceList()
3063
    if instance_name in instance_list:
3064
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
3065
                                 instance_name)
3066

    
3067
    # ip validity checks
3068
    ip = getattr(self.op, "ip", None)
3069
    if ip is None or ip.lower() == "none":
3070
      inst_ip = None
3071
    elif ip.lower() == "auto":
3072
      inst_ip = hostname1.ip
3073
    else:
3074
      if not utils.IsValidIP(ip):
3075
        raise errors.OpPrereqError("given IP address '%s' doesn't look"
3076
                                   " like a valid IP" % ip)
3077
      inst_ip = ip
3078
    self.inst_ip = self.op.ip = inst_ip
3079

    
3080
    if self.op.start and not self.op.ip_check:
3081
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
3082
                                 " adding an instance in start mode")
3083

    
3084
    if self.op.ip_check:
3085
      if utils.TcpPing(hostname1.ip, constants.DEFAULT_NODED_PORT):
3086
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
3087
                                   (hostname1.ip, instance_name))
3088

    
3089
    # MAC address verification
3090
    if self.op.mac != "auto":
3091
      if not utils.IsValidMac(self.op.mac.lower()):
3092
        raise errors.OpPrereqError("invalid MAC address specified: %s" %
3093
                                   self.op.mac)
3094

    
3095
    # bridge verification
3096
    bridge = getattr(self.op, "bridge", None)
3097
    if bridge is None:
3098
      self.op.bridge = self.cfg.GetDefBridge()
3099
    else:
3100
      self.op.bridge = bridge
3101

    
3102
    # boot order verification
3103
    if self.op.hvm_boot_order is not None:
3104
      if len(self.op.hvm_boot_order.strip("acdn")) != 0:
3105
        raise errors.OpPrereqError("invalid boot order specified,"
3106
                                   " must be one or more of [acdn]")
3107
    # file storage checks
3108
    if (self.op.file_driver and
3109
        not self.op.file_driver in constants.FILE_DRIVER):
3110
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
3111
                                 self.op.file_driver)
3112

    
3113
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
3114
      raise errors.OpPrereqError("File storage directory not a relative"
3115
                                 " path")
3116
    #### allocator run
3117

    
3118
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
3119
      raise errors.OpPrereqError("One and only one of iallocator and primary"
3120
                                 " node must be given")
3121

    
3122
    if self.op.iallocator is not None:
3123
      self._RunAllocator()
3124

    
3125
    #### node related checks
3126

    
3127
    # check primary node
3128
    pnode = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.pnode))
3129
    if pnode is None:
3130
      raise errors.OpPrereqError("Primary node '%s' is unknown" %
3131
                                 self.op.pnode)
3132
    self.op.pnode = pnode.name
3133
    self.pnode = pnode
3134
    self.secondaries = []
3135

    
3136
    # mirror node verification
3137
    if self.op.disk_template in constants.DTS_NET_MIRROR:
3138
      if getattr(self.op, "snode", None) is None:
3139
        raise errors.OpPrereqError("The networked disk templates need"
3140
                                   " a mirror node")
3141

    
3142
      snode_name = self.cfg.ExpandNodeName(self.op.snode)
3143
      if snode_name is None:
3144
        raise errors.OpPrereqError("Unknown secondary node '%s'" %
3145
                                   self.op.snode)
3146
      elif snode_name == pnode.name:
3147
        raise errors.OpPrereqError("The secondary node cannot be"
3148
                                   " the primary node.")
3149
      self.secondaries.append(snode_name)
3150

    
3151
    req_size = _ComputeDiskSize(self.op.disk_template,
3152
                                self.op.disk_size, self.op.swap_size)
3153

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

    
3172
    # os verification
3173
    os_obj = rpc.call_os_get(pnode.name, self.op.os_type)
3174
    if not os_obj:
3175
      raise errors.OpPrereqError("OS '%s' not in supported os list for"
3176
                                 " primary node"  % self.op.os_type)
3177

    
3178
    if self.op.kernel_path == constants.VALUE_NONE:
3179
      raise errors.OpPrereqError("Can't set instance kernel to none")
3180

    
3181

    
3182
    # bridge check on primary node
3183
    if not rpc.call_bridges_exist(self.pnode.name, [self.op.bridge]):
3184
      raise errors.OpPrereqError("target bridge '%s' does not exist on"
3185
                                 " destination node '%s'" %
3186
                                 (self.op.bridge, pnode.name))
3187

    
3188
    # memory check on primary node
3189
    if self.op.start:
3190
      _CheckNodeFreeMemory(self.cfg, self.pnode.name,
3191
                           "creating instance %s" % self.op.instance_name,
3192
                           self.op.mem_size)
3193

    
3194
    # hvm_cdrom_image_path verification
3195
    if self.op.hvm_cdrom_image_path is not None:
3196
      if not os.path.isabs(self.op.hvm_cdrom_image_path):
3197
        raise errors.OpPrereqError("The path to the HVM CDROM image must"
3198
                                   " be an absolute path or None, not %s" %
3199
                                   self.op.hvm_cdrom_image_path)
3200
      if not os.path.isfile(self.op.hvm_cdrom_image_path):
3201
        raise errors.OpPrereqError("The HVM CDROM image must either be a"
3202
                                   " regular file or a symlink pointing to"
3203
                                   " an existing regular file, not %s" %
3204
                                   self.op.hvm_cdrom_image_path)
3205

    
3206
    # vnc_bind_address verification
3207
    if self.op.vnc_bind_address is not None:
3208
      if not utils.IsValidIP(self.op.vnc_bind_address):
3209
        raise errors.OpPrereqError("given VNC bind address '%s' doesn't look"
3210
                                   " like a valid IP address" %
3211
                                   self.op.vnc_bind_address)
3212

    
3213
    if self.op.start:
3214
      self.instance_status = 'up'
3215
    else:
3216
      self.instance_status = 'down'
3217

    
3218
  def Exec(self, feedback_fn):
3219
    """Create and add the instance to the cluster.
3220

3221
    """
3222
    instance = self.op.instance_name
3223
    pnode_name = self.pnode.name
3224

    
3225
    if self.op.mac == "auto":
3226
      mac_address = self.cfg.GenerateMAC()
3227
    else:
3228
      mac_address = self.op.mac
3229

    
3230
    nic = objects.NIC(bridge=self.op.bridge, mac=mac_address)
3231
    if self.inst_ip is not None:
3232
      nic.ip = self.inst_ip
3233

    
3234
    ht_kind = self.sstore.GetHypervisorType()
3235
    if ht_kind in constants.HTS_REQ_PORT:
3236
      network_port = self.cfg.AllocatePort()
3237
    else:
3238
      network_port = None
3239

    
3240
    if self.op.vnc_bind_address is None:
3241
      self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
3242

    
3243
    # this is needed because os.path.join does not accept None arguments
3244
    if self.op.file_storage_dir is None:
3245
      string_file_storage_dir = ""
3246
    else:
3247
      string_file_storage_dir = self.op.file_storage_dir
3248

    
3249
    # build the full file storage dir path
3250
    file_storage_dir = os.path.normpath(os.path.join(
3251
                                        self.sstore.GetFileStorageDir(),
3252
                                        string_file_storage_dir, instance))
3253

    
3254

    
3255
    disks = _GenerateDiskTemplate(self.cfg,
3256
                                  self.op.disk_template,
3257
                                  instance, pnode_name,
3258
                                  self.secondaries, self.op.disk_size,
3259
                                  self.op.swap_size,
3260
                                  file_storage_dir,
3261
                                  self.op.file_driver)
3262

    
3263
    iobj = objects.Instance(name=instance, os=self.op.os_type,
3264
                            primary_node=pnode_name,
3265
                            memory=self.op.mem_size,
3266
                            vcpus=self.op.vcpus,
3267
                            nics=[nic], disks=disks,
3268
                            disk_template=self.op.disk_template,
3269
                            status=self.instance_status,
3270
                            network_port=network_port,
3271
                            kernel_path=self.op.kernel_path,
3272
                            initrd_path=self.op.initrd_path,
3273
                            hvm_boot_order=self.op.hvm_boot_order,
3274
                            hvm_acpi=self.op.hvm_acpi,
3275
                            hvm_pae=self.op.hvm_pae,
3276
                            hvm_cdrom_image_path=self.op.hvm_cdrom_image_path,
3277
                            vnc_bind_address=self.op.vnc_bind_address,
3278
                            )
3279

    
3280
    feedback_fn("* creating instance disks...")
3281
    if not _CreateDisks(self.cfg, iobj):
3282
      _RemoveDisks(iobj, self.cfg)
3283
      raise errors.OpExecError("Device creation failed, reverting...")
3284

    
3285
    feedback_fn("adding instance %s to cluster config" % instance)
3286

    
3287
    self.cfg.AddInstance(iobj)
3288
    # Add the new instance to the Ganeti Lock Manager
3289
    self.context.glm.add(locking.LEVEL_INSTANCE, instance)
3290

    
3291
    if self.op.wait_for_sync:
3292
      disk_abort = not _WaitForSync(self.cfg, iobj, self.proc)
3293
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
3294
      # make sure the disks are not degraded (still sync-ing is ok)
3295
      time.sleep(15)
3296
      feedback_fn("* checking mirrors status")
3297
      disk_abort = not _WaitForSync(self.cfg, iobj, self.proc, oneshot=True)
3298
    else:
3299
      disk_abort = False
3300

    
3301
    if disk_abort:
3302
      _RemoveDisks(iobj, self.cfg)
3303
      self.cfg.RemoveInstance(iobj.name)
3304
      # Remove the new instance from the Ganeti Lock Manager
3305
      self.context.glm.remove(locking.LEVEL_INSTANCE, iobj.name)
3306
      raise errors.OpExecError("There are some degraded disks for"
3307
                               " this instance")
3308

    
3309
    feedback_fn("creating os for instance %s on node %s" %
3310
                (instance, pnode_name))
3311

    
3312
    if iobj.disk_template != constants.DT_DISKLESS:
3313
      if self.op.mode == constants.INSTANCE_CREATE:
3314
        feedback_fn("* running the instance OS create scripts...")
3315
        if not rpc.call_instance_os_add(pnode_name, iobj, "sda", "sdb"):
3316
          raise errors.OpExecError("could not add os for instance %s"
3317
                                   " on node %s" %
3318
                                   (instance, pnode_name))
3319

    
3320
      elif self.op.mode == constants.INSTANCE_IMPORT:
3321
        feedback_fn("* running the instance OS import scripts...")
3322
        src_node = self.op.src_node
3323
        src_image = self.src_image
3324
        if not rpc.call_instance_os_import(pnode_name, iobj, "sda", "sdb",
3325
                                                src_node, src_image):
3326
          raise errors.OpExecError("Could not import os for instance"
3327
                                   " %s on node %s" %
3328
                                   (instance, pnode_name))
3329
      else:
3330
        # also checked in the prereq part
3331
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
3332
                                     % self.op.mode)
3333

    
3334
    if self.op.start:
3335
      logger.Info("starting instance %s on node %s" % (instance, pnode_name))
3336
      feedback_fn("* starting instance...")
3337
      if not rpc.call_instance_start(pnode_name, iobj, None):
3338
        raise errors.OpExecError("Could not start instance")
3339

    
3340

    
3341
class LUConnectConsole(NoHooksLU):
3342
  """Connect to an instance's console.
3343

3344
  This is somewhat special in that it returns the command line that
3345
  you need to run on the master node in order to connect to the
3346
  console.
3347

3348
  """
3349
  _OP_REQP = ["instance_name"]
3350
  REQ_BGL = False
3351

    
3352
  def ExpandNames(self):
3353
    self._ExpandAndLockInstance()
3354

    
3355
  def CheckPrereq(self):
3356
    """Check prerequisites.
3357

3358
    This checks that the instance is in the cluster.
3359

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

    
3365
  def Exec(self, feedback_fn):
3366
    """Connect to the console of an instance
3367

3368
    """
3369
    instance = self.instance
3370
    node = instance.primary_node
3371

    
3372
    node_insts = rpc.call_instance_list([node])[node]
3373
    if node_insts is False:
3374
      raise errors.OpExecError("Can't connect to node %s." % node)
3375

    
3376
    if instance.name not in node_insts:
3377
      raise errors.OpExecError("Instance %s is not running." % instance.name)
3378

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

    
3381
    hyper = hypervisor.GetHypervisor()
3382
    console_cmd = hyper.GetShellCommandForConsole(instance)
3383

    
3384
    # build ssh cmdline
3385
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
3386

    
3387

    
3388
class LUReplaceDisks(LogicalUnit):
3389
  """Replace the disks of an instance.
3390

3391
  """
3392
  HPATH = "mirrors-replace"
3393
  HTYPE = constants.HTYPE_INSTANCE
3394
  _OP_REQP = ["instance_name", "mode", "disks"]
3395

    
3396
  def _RunAllocator(self):
3397
    """Compute a new secondary node using an IAllocator.
3398

3399
    """
3400
    ial = IAllocator(self.cfg, self.sstore,
3401
                     mode=constants.IALLOCATOR_MODE_RELOC,
3402
                     name=self.op.instance_name,
3403
                     relocate_from=[self.sec_node])
3404

    
3405
    ial.Run(self.op.iallocator)
3406

    
3407
    if not ial.success:
3408
      raise errors.OpPrereqError("Can't compute nodes using"
3409
                                 " iallocator '%s': %s" % (self.op.iallocator,
3410
                                                           ial.info))
3411
    if len(ial.nodes) != ial.required_nodes:
3412
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
3413
                                 " of nodes (%s), required %s" %
3414
                                 (len(ial.nodes), ial.required_nodes))
3415
    self.op.remote_node = ial.nodes[0]
3416
    logger.ToStdout("Selected new secondary for the instance: %s" %
3417
                    self.op.remote_node)
3418

    
3419
  def BuildHooksEnv(self):
3420
    """Build hooks env.
3421

3422
    This runs on the master, the primary and all the secondaries.
3423

3424
    """
3425
    env = {
3426
      "MODE": self.op.mode,
3427
      "NEW_SECONDARY": self.op.remote_node,
3428
      "OLD_SECONDARY": self.instance.secondary_nodes[0],
3429
      }
3430
    env.update(_BuildInstanceHookEnvByObject(self.instance))
3431
    nl = [
3432
      self.sstore.GetMasterNode(),
3433
      self.instance.primary_node,
3434
      ]
3435
    if self.op.remote_node is not None:
3436
      nl.append(self.op.remote_node)
3437
    return env, nl, nl
3438

    
3439
  def CheckPrereq(self):
3440
    """Check prerequisites.
3441

3442
    This checks that the instance is in the cluster.
3443

3444
    """
3445
    if not hasattr(self.op, "remote_node"):
3446
      self.op.remote_node = None
3447

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

    
3456
    if instance.disk_template not in constants.DTS_NET_MIRROR:
3457
      raise errors.OpPrereqError("Instance's disk layout is not"
3458
                                 " network mirrored.")
3459

    
3460
    if len(instance.secondary_nodes) != 1:
3461
      raise errors.OpPrereqError("The instance has a strange layout,"
3462
                                 " expected one secondary but found %d" %
3463
                                 len(instance.secondary_nodes))
3464

    
3465
    self.sec_node = instance.secondary_nodes[0]
3466

    
3467
    ia_name = getattr(self.op, "iallocator", None)
3468
    if ia_name is not None:
3469
      if self.op.remote_node is not None:
3470
        raise errors.OpPrereqError("Give either the iallocator or the new"
3471
                                   " secondary, not both")
3472
      self.op.remote_node = self._RunAllocator()
3473

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

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

    
3517
    for name in self.op.disks:
3518
      if instance.FindDisk(name) is None:
3519
        raise errors.OpPrereqError("Disk '%s' not found for instance '%s'" %
3520
                                   (name, instance.name))
3521
    self.op.remote_node = remote_node
3522

    
3523
  def _ExecD8DiskOnly(self, feedback_fn):
3524
    """Replace a disk on the primary or secondary for dbrd8.
3525

3526
    The algorithm for replace is quite complicated:
3527
      - for each disk to be replaced:
3528
        - create new LVs on the target node with unique names
3529
        - detach old LVs from the drbd device
3530
        - rename old LVs to name_replaced.<time_t>
3531
        - rename new LVs to old LVs
3532
        - attach the new LVs (with the old names now) to the drbd device
3533
      - wait for sync across all devices
3534
      - for each modified disk:
3535
        - remove old LVs (which have the name name_replaces.<time_t>)
3536

3537
    Failures are not very well handled.
3538

3539
    """
3540
    steps_total = 6
3541
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
3542
    instance = self.instance
3543
    iv_names = {}
3544
    vgname = self.cfg.GetVGName()
3545
    # start of work
3546
    cfg = self.cfg
3547
    tgt_node = self.tgt_node
3548
    oth_node = self.oth_node
3549

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

    
3572
    # Step: check other node consistency
3573
    self.proc.LogStep(2, steps_total, "check peer consistency")
3574
    for dev in instance.disks:
3575
      if not dev.iv_name in self.op.disks:
3576
        continue
3577
      info("checking %s consistency on %s" % (dev.iv_name, oth_node))
3578
      if not _CheckDiskConsistency(self.cfg, dev, oth_node,
3579
                                   oth_node==instance.primary_node):
3580
        raise errors.OpExecError("Peer node (%s) has degraded storage, unsafe"
3581
                                 " to replace disks on this node (%s)" %
3582
                                 (oth_node, tgt_node))
3583

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

    
3612
    # Step: for each lv, detach+rename*2+attach
3613
    self.proc.LogStep(4, steps_total, "change drbd configuration")
3614
    for dev, old_lvs, new_lvs in iv_names.itervalues():
3615
      info("detaching %s drbd from local storage" % dev.iv_name)
3616
      if not rpc.call_blockdev_removechildren(tgt_node, dev, old_lvs):
3617
        raise errors.OpExecError("Can't detach drbd from local storage on node"
3618
                                 " %s for device %s" % (tgt_node, dev.iv_name))
3619
      #dev.children = []
3620
      #cfg.Update(instance)
3621

    
3622
      # ok, we created the new LVs, so now we know we have the needed
3623
      # storage; as such, we proceed on the target node to rename
3624
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
3625
      # using the assumption that logical_id == physical_id (which in
3626
      # turn is the unique_id on that node)
3627

    
3628
      # FIXME(iustin): use a better name for the replaced LVs
3629
      temp_suffix = int(time.time())
3630
      ren_fn = lambda d, suff: (d.physical_id[0],
3631
                                d.physical_id[1] + "_replaced-%s" % suff)
3632
      # build the rename list based on what LVs exist on the node
3633
      rlist = []
3634
      for to_ren in old_lvs:
3635
        find_res = rpc.call_blockdev_find(tgt_node, to_ren)
3636
        if find_res is not None: # device exists
3637
          rlist.append((to_ren, ren_fn(to_ren, temp_suffix)))
3638

    
3639
      info("renaming the old LVs on the target node")
3640
      if not rpc.call_blockdev_rename(tgt_node, rlist):
3641
        raise errors.OpExecError("Can't rename old LVs on node %s" % tgt_node)
3642
      # now we rename the new LVs to the old LVs
3643
      info("renaming the new LVs on the target node")
3644
      rlist = [(new, old.physical_id) for old, new in zip(old_lvs, new_lvs)]
3645
      if not rpc.call_blockdev_rename(tgt_node, rlist):
3646
        raise errors.OpExecError("Can't rename new LVs on node %s" % tgt_node)
3647

    
3648
      for old, new in zip(old_lvs, new_lvs):
3649
        new.logical_id = old.logical_id
3650
        cfg.SetDiskID(new, tgt_node)
3651

    
3652
      for disk in old_lvs:
3653
        disk.logical_id = ren_fn(disk, temp_suffix)
3654
        cfg.SetDiskID(disk, tgt_node)
3655

    
3656
      # now that the new lvs have the old name, we can add them to the device
3657
      info("adding new mirror component on %s" % tgt_node)
3658
      if not rpc.call_blockdev_addchildren(tgt_node, dev, new_lvs):
3659
        for new_lv in new_lvs:
3660
          if not rpc.call_blockdev_remove(tgt_node, new_lv):
3661
            warning("Can't rollback device %s", hint="manually cleanup unused"
3662
                    " logical volumes")
3663
        raise errors.OpExecError("Can't add local storage to drbd")
3664

    
3665
      dev.children = new_lvs
3666
      cfg.Update(instance)
3667

    
3668
    # Step: wait for sync
3669

    
3670
    # this can fail as the old devices are degraded and _WaitForSync
3671
    # does a combined result over all disks, so we don't check its
3672
    # return value
3673
    self.proc.LogStep(5, steps_total, "sync devices")
3674
    _WaitForSync(cfg, instance, self.proc, unlock=True)
3675

    
3676
    # so check manually all the devices
3677
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
3678
      cfg.SetDiskID(dev, instance.primary_node)
3679
      is_degr = rpc.call_blockdev_find(instance.primary_node, dev)[5]
3680
      if is_degr:
3681
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
3682

    
3683
    # Step: remove old storage
3684
    self.proc.LogStep(6, steps_total, "removing old storage")
3685
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
3686
      info("remove logical volumes for %s" % name)
3687
      for lv in old_lvs:
3688
        cfg.SetDiskID(lv, tgt_node)
3689
        if not rpc.call_blockdev_remove(tgt_node, lv):
3690
          warning("Can't remove old LV", hint="manually remove unused LVs")
3691
          continue
3692

    
3693
  def _ExecD8Secondary(self, feedback_fn):
3694
    """Replace the secondary node for drbd8.
3695

3696
    The algorithm for replace is quite complicated:
3697
      - for all disks of the instance:
3698
        - create new LVs on the new node with same names
3699
        - shutdown the drbd device on the old secondary
3700
        - disconnect the drbd network on the primary
3701
        - create the drbd device on the new secondary
3702
        - network attach the drbd on the primary, using an artifice:
3703
          the drbd code for Attach() will connect to the network if it
3704
          finds a device which is connected to the good local disks but
3705
          not network enabled
3706
      - wait for sync across all devices
3707
      - remove all disks from the old secondary
3708

3709
    Failures are not very well handled.
3710

3711
    """
3712
    steps_total = 6
3713
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
3714
    instance = self.instance
3715
    iv_names = {}
3716
    vgname = self.cfg.GetVGName()
3717
    # start of work
3718
    cfg = self.cfg
3719
    old_node = self.tgt_node
3720
    new_node = self.new_node
3721
    pri_node = instance.primary_node
3722

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

    
3744
    # Step: check other node consistency
3745
    self.proc.LogStep(2, steps_total, "check peer consistency")
3746
    for dev in instance.disks:
3747
      if not dev.iv_name in self.op.disks:
3748
        continue
3749
      info("checking %s consistency on %s" % (dev.iv_name, pri_node))
3750
      if not _CheckDiskConsistency(self.cfg, dev, pri_node, True, ldisk=True):
3751
        raise errors.OpExecError("Primary node (%s) has degraded storage,"
3752
                                 " unsafe to replace the secondary" %
3753
                                 pri_node)
3754

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

    
3770
      iv_names[dev.iv_name] = (dev, dev.children)
3771

    
3772
    self.proc.LogStep(4, steps_total, "changing drbd configuration")
3773
    for dev in instance.disks:
3774
      size = dev.size
3775
      info("activating a new drbd on %s for %s" % (new_node, dev.iv_name))
3776
      # create new devices on new_node
3777
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
3778
                              logical_id=(pri_node, new_node,
3779
                                          dev.logical_id[2]),
3780
                              children=dev.children)
3781
      if not _CreateBlockDevOnSecondary(cfg, new_node, instance,
3782
                                        new_drbd, False,
3783
                                      _GetInstanceInfoText(instance)):
3784
        raise errors.OpExecError("Failed to create new DRBD on"
3785
                                 " node '%s'" % new_node)
3786

    
3787
    for dev in instance.disks:
3788
      # we have new devices, shutdown the drbd on the old secondary
3789
      info("shutting down drbd for %s on old node" % dev.iv_name)
3790
      cfg.SetDiskID(dev, old_node)
3791
      if not rpc.call_blockdev_shutdown(old_node, dev):
3792
        warning("Failed to shutdown drbd for %s on old node" % dev.iv_name,
3793
                hint="Please cleanup this device manually as soon as possible")
3794

    
3795
    info("detaching primary drbds from the network (=> standalone)")
3796
    done = 0
3797
    for dev in instance.disks:
3798
      cfg.SetDiskID(dev, pri_node)
3799
      # set the physical (unique in bdev terms) id to None, meaning
3800
      # detach from network
3801
      dev.physical_id = (None,) * len(dev.physical_id)
3802
      # and 'find' the device, which will 'fix' it to match the
3803
      # standalone state
3804
      if rpc.call_blockdev_find(pri_node, dev):
3805
        done += 1
3806
      else:
3807
        warning("Failed to detach drbd %s from network, unusual case" %
3808
                dev.iv_name)
3809

    
3810
    if not done:
3811
      # no detaches succeeded (very unlikely)
3812
      raise errors.OpExecError("Can't detach at least one DRBD from old node")
3813

    
3814
    # if we managed to detach at least one, we update all the disks of
3815
    # the instance to point to the new secondary
3816
    info("updating instance configuration")
3817
    for dev in instance.disks:
3818
      dev.logical_id = (pri_node, new_node) + dev.logical_id[2:]
3819
      cfg.SetDiskID(dev, pri_node)
3820
    cfg.Update(instance)
3821

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

    
3835
    # this can fail as the old devices are degraded and _WaitForSync
3836
    # does a combined result over all disks, so we don't check its
3837
    # return value
3838
    self.proc.LogStep(5, steps_total, "sync devices")
3839
    _WaitForSync(cfg, instance, self.proc, unlock=True)
3840

    
3841
    # so check manually all the devices
3842
    for name, (dev, old_lvs) in iv_names.iteritems():
3843
      cfg.SetDiskID(dev, pri_node)
3844
      is_degr = rpc.call_blockdev_find(pri_node, dev)[5]
3845
      if is_degr:
3846
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
3847

    
3848
    self.proc.LogStep(6, steps_total, "removing old storage")
3849
    for name, (dev, old_lvs) in iv_names.iteritems():
3850
      info("remove logical volumes for %s" % name)
3851
      for lv in old_lvs:
3852
        cfg.SetDiskID(lv, old_node)
3853
        if not rpc.call_blockdev_remove(old_node, lv):
3854
          warning("Can't remove LV on old secondary",
3855
                  hint="Cleanup stale volumes by hand")
3856

    
3857
  def Exec(self, feedback_fn):
3858
    """Execute disk replacement.
3859

3860
    This dispatches the disk replacement to the appropriate handler.
3861

3862
    """
3863
    instance = self.instance
3864

    
3865
    # Activate the instance disks if we're replacing them on a down instance
3866
    if instance.status == "down":
3867
      op = opcodes.OpActivateInstanceDisks(instance_name=instance.name)
3868
      self.proc.ChainOpCode(op)
3869

    
3870
    if instance.disk_template == constants.DT_DRBD8:
3871
      if self.op.remote_node is None:
3872
        fn = self._ExecD8DiskOnly
3873
      else:
3874
        fn = self._ExecD8Secondary
3875
    else:
3876
      raise errors.ProgrammerError("Unhandled disk replacement case")
3877

    
3878
    ret = fn(feedback_fn)
3879

    
3880
    # Deactivate the instance disks if we're replacing them on a down instance
3881
    if instance.status == "down":
3882
      op = opcodes.OpDeactivateInstanceDisks(instance_name=instance.name)
3883
      self.proc.ChainOpCode(op)
3884

    
3885
    return ret
3886

    
3887

    
3888
class LUGrowDisk(LogicalUnit):
3889
  """Grow a disk of an instance.
3890

3891
  """
3892
  HPATH = "disk-grow"
3893
  HTYPE = constants.HTYPE_INSTANCE
3894
  _OP_REQP = ["instance_name", "disk", "amount"]
3895

    
3896
  def BuildHooksEnv(self):
3897
    """Build hooks env.
3898

3899
    This runs on the master, the primary and all the secondaries.
3900

3901
    """
3902
    env = {
3903
      "DISK": self.op.disk,
3904
      "AMOUNT": self.op.amount,
3905
      }
3906
    env.update(_BuildInstanceHookEnvByObject(self.instance))
3907
    nl = [
3908
      self.sstore.GetMasterNode(),
3909
      self.instance.primary_node,
3910
      ]
3911
    return env, nl, nl
3912

    
3913
  def CheckPrereq(self):
3914
    """Check prerequisites.
3915

3916
    This checks that the instance is in the cluster.
3917

3918
    """
3919
    instance = self.cfg.GetInstanceInfo(
3920
      self.cfg.ExpandInstanceName(self.op.instance_name))
3921
    if instance is None:
3922
      raise errors.OpPrereqError("Instance '%s' not known" %
3923
                                 self.op.instance_name)
3924
    self.instance = instance
3925
    self.op.instance_name = instance.name
3926

    
3927
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
3928
      raise errors.OpPrereqError("Instance's disk layout does not support"
3929
                                 " growing.")
3930

    
3931
    if instance.FindDisk(self.op.disk) is None:
3932
      raise errors.OpPrereqError("Disk '%s' not found for instance '%s'" %
3933
                                 (self.op.disk, instance.name))
3934

    
3935
    nodenames = [instance.primary_node] + list(instance.secondary_nodes)
3936
    nodeinfo = rpc.call_node_info(nodenames, self.cfg.GetVGName())
3937
    for node in nodenames:
3938
      info = nodeinfo.get(node, None)
3939
      if not info:
3940
        raise errors.OpPrereqError("Cannot get current information"
3941
                                   " from node '%s'" % node)
3942
      vg_free = info.get('vg_free', None)
3943
      if not isinstance(vg_free, int):
3944
        raise errors.OpPrereqError("Can't compute free disk space on"
3945
                                   " node %s" % node)
3946
      if self.op.amount > info['vg_free']:
3947
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
3948
                                   " %d MiB available, %d MiB required" %
3949
                                   (node, info['vg_free'], self.op.amount))
3950

    
3951
  def Exec(self, feedback_fn):
3952
    """Execute disk grow.
3953

3954
    """
3955
    instance = self.instance
3956
    disk = instance.FindDisk(self.op.disk)
3957
    for node in (instance.secondary_nodes + (instance.primary_node,)):
3958
      self.cfg.SetDiskID(disk, node)
3959
      result = rpc.call_blockdev_grow(node, disk, self.op.amount)
3960
      if not result or not isinstance(result, tuple) or len(result) != 2:
3961
        raise errors.OpExecError("grow request failed to node %s" % node)
3962
      elif not result[0]:
3963
        raise errors.OpExecError("grow request failed to node %s: %s" %
3964
                                 (node, result[1]))
3965
    disk.RecordGrow(self.op.amount)
3966
    self.cfg.Update(instance)
3967
    return
3968

    
3969

    
3970
class LUQueryInstanceData(NoHooksLU):
3971
  """Query runtime instance data.
3972

3973
  """
3974
  _OP_REQP = ["instances"]
3975

    
3976
  def CheckPrereq(self):
3977
    """Check prerequisites.
3978

3979
    This only checks the optional instance list against the existing names.
3980

3981
    """
3982
    if not isinstance(self.op.instances, list):
3983
      raise errors.OpPrereqError("Invalid argument type 'instances'")
3984
    if self.op.instances:
3985
      self.wanted_instances = []
3986
      names = self.op.instances
3987
      for name in names:
3988
        instance = self.cfg.GetInstanceInfo(self.cfg.ExpandInstanceName(name))
3989
        if instance is None:
3990
          raise errors.OpPrereqError("No such instance name '%s'" % name)
3991
        self.wanted_instances.append(instance)
3992
    else:
3993
      self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
3994
                               in self.cfg.GetInstanceList()]
3995
    return
3996

    
3997

    
3998
  def _ComputeDiskStatus(self, instance, snode, dev):
3999
    """Compute block device status.
4000

4001
    """
4002
    self.cfg.SetDiskID(dev, instance.primary_node)
4003
    dev_pstatus = rpc.call_blockdev_find(instance.primary_node, dev)
4004
    if dev.dev_type in constants.LDS_DRBD:
4005
      # we change the snode then (otherwise we use the one passed in)
4006
      if dev.logical_id[0] == instance.primary_node:
4007
        snode = dev.logical_id[1]
4008
      else:
4009
        snode = dev.logical_id[0]
4010

    
4011
    if snode:
4012
      self.cfg.SetDiskID(dev, snode)
4013
      dev_sstatus = rpc.call_blockdev_find(snode, dev)
4014
    else:
4015
      dev_sstatus = None
4016

    
4017
    if dev.children:
4018
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
4019
                      for child in dev.children]
4020
    else:
4021
      dev_children = []
4022

    
4023
    data = {
4024
      "iv_name": dev.iv_name,
4025
      "dev_type": dev.dev_type,
4026
      "logical_id": dev.logical_id,
4027
      "physical_id": dev.physical_id,
4028
      "pstatus": dev_pstatus,
4029
      "sstatus": dev_sstatus,
4030
      "children": dev_children,
4031
      }
4032

    
4033
    return data
4034

    
4035
  def Exec(self, feedback_fn):
4036
    """Gather and return data"""
4037
    result = {}
4038
    for instance in self.wanted_instances:
4039
      remote_info = rpc.call_instance_info(instance.primary_node,
4040
                                                instance.name)
4041
      if remote_info and "state" in remote_info:
4042
        remote_state = "up"
4043
      else:
4044
        remote_state = "down"
4045
      if instance.status == "down":
4046
        config_state = "down"
4047
      else:
4048
        config_state = "up"
4049

    
4050
      disks = [self._ComputeDiskStatus(instance, None, device)
4051
               for device in instance.disks]
4052

    
4053
      idict = {
4054
        "name": instance.name,
4055
        "config_state": config_state,
4056
        "run_state": remote_state,
4057
        "pnode": instance.primary_node,
4058
        "snodes": instance.secondary_nodes,
4059
        "os": instance.os,
4060
        "memory": instance.memory,
4061
        "nics": [(nic.mac, nic.ip, nic.bridge) for nic in instance.nics],
4062
        "disks": disks,
4063
        "vcpus": instance.vcpus,
4064
        }
4065

    
4066
      htkind = self.sstore.GetHypervisorType()
4067
      if htkind == constants.HT_XEN_PVM30:
4068
        idict["kernel_path"] = instance.kernel_path
4069
        idict["initrd_path"] = instance.initrd_path
4070

    
4071
      if htkind == constants.HT_XEN_HVM31:
4072
        idict["hvm_boot_order"] = instance.hvm_boot_order
4073
        idict["hvm_acpi"] = instance.hvm_acpi
4074
        idict["hvm_pae"] = instance.hvm_pae
4075
        idict["hvm_cdrom_image_path"] = instance.hvm_cdrom_image_path
4076

    
4077
      if htkind in constants.HTS_REQ_PORT:
4078
        idict["vnc_bind_address"] = instance.vnc_bind_address
4079
        idict["network_port"] = instance.network_port
4080

    
4081
      result[instance.name] = idict
4082

    
4083
    return result
4084

    
4085

    
4086
class LUSetInstanceParams(LogicalUnit):
4087
  """Modifies an instances's parameters.
4088

4089
  """
4090
  HPATH = "instance-modify"
4091
  HTYPE = constants.HTYPE_INSTANCE
4092
  _OP_REQP = ["instance_name"]
4093
  REQ_BGL = False
4094

    
4095
  def ExpandNames(self):
4096
    self._ExpandAndLockInstance()
4097

    
4098
  def BuildHooksEnv(self):
4099
    """Build hooks env.
4100

4101
    This runs on the master, primary and secondaries.
4102

4103
    """
4104
    args = dict()
4105
    if self.mem:
4106
      args['memory'] = self.mem
4107
    if self.vcpus:
4108
      args['vcpus'] = self.vcpus
4109
    if self.do_ip or self.do_bridge or self.mac:
4110
      if self.do_ip:
4111
        ip = self.ip
4112
      else:
4113
        ip = self.instance.nics[0].ip
4114
      if self.bridge:
4115
        bridge = self.bridge
4116
      else:
4117
        bridge = self.instance.nics[0].bridge
4118
      if self.mac:
4119
        mac = self.mac
4120
      else:
4121
        mac = self.instance.nics[0].mac
4122
      args['nics'] = [(ip, bridge, mac)]
4123
    env = _BuildInstanceHookEnvByObject(self.instance, override=args)
4124
    nl = [self.sstore.GetMasterNode(),
4125
          self.instance.primary_node] + list(self.instance.secondary_nodes)
4126
    return env, nl, nl
4127

    
4128
  def CheckPrereq(self):
4129
    """Check prerequisites.
4130

4131
    This only checks the instance list against the existing names.
4132

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

    
4182
    if self.kernel_path is not None:
4183
      self.do_kernel_path = True
4184
      if self.kernel_path == constants.VALUE_NONE:
4185
        raise errors.OpPrereqError("Can't set instance to no kernel")
4186

    
4187
      if self.kernel_path != constants.VALUE_DEFAULT:
4188
        if not os.path.isabs(self.kernel_path):
4189
          raise errors.OpPrereqError("The kernel path must be an absolute"
4190
                                    " filename")
4191
    else:
4192
      self.do_kernel_path = False
4193

    
4194
    if self.initrd_path is not None:
4195
      self.do_initrd_path = True
4196
      if self.initrd_path not in (constants.VALUE_NONE,
4197
                                  constants.VALUE_DEFAULT):
4198
        if not os.path.isabs(self.initrd_path):
4199
          raise errors.OpPrereqError("The initrd path must be an absolute"
4200
                                    " filename")
4201
    else:
4202
      self.do_initrd_path = False
4203

    
4204
    # boot order verification
4205
    if self.hvm_boot_order is not None:
4206
      if self.hvm_boot_order != constants.VALUE_DEFAULT:
4207
        if len(self.hvm_boot_order.strip("acdn")) != 0:
4208
          raise errors.OpPrereqError("invalid boot order specified,"
4209
                                     " must be one or more of [acdn]"
4210
                                     " or 'default'")
4211

    
4212
    # hvm_cdrom_image_path verification
4213
    if self.op.hvm_cdrom_image_path is not None:
4214
      if not os.path.isabs(self.op.hvm_cdrom_image_path):
4215
        raise errors.OpPrereqError("The path to the HVM CDROM image must"
4216
                                   " be an absolute path or None, not %s" %
4217
                                   self.op.hvm_cdrom_image_path)
4218
      if not os.path.isfile(self.op.hvm_cdrom_image_path):
4219
        raise errors.OpPrereqError("The HVM CDROM image must either be a"
4220
                                   " regular file or a symlink pointing to"
4221
                                   " an existing regular file, not %s" %
4222
                                   self.op.hvm_cdrom_image_path)
4223

    
4224
    # vnc_bind_address verification
4225
    if self.op.vnc_bind_address is not None:
4226
      if not utils.IsValidIP(self.op.vnc_bind_address):
4227
        raise errors.OpPrereqError("given VNC bind address '%s' doesn't look"
4228
                                   " like a valid IP address" %
4229
                                   self.op.vnc_bind_address)
4230

    
4231
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4232
    assert self.instance is not None, \
4233
      "Cannot retrieve locked instance %s" % self.op.instance_name
4234
    return
4235

    
4236
  def Exec(self, feedback_fn):
4237
    """Modifies an instance.
4238

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

    
4283
    self.cfg.Update(instance)
4284

    
4285
    return result
4286

    
4287

    
4288
class LUQueryExports(NoHooksLU):
4289
  """Query the exports list
4290

4291
  """
4292
  _OP_REQP = []
4293

    
4294
  def CheckPrereq(self):
4295
    """Check that the nodelist contains only existing nodes.
4296

4297
    """
4298
    self.nodes = _GetWantedNodes(self, getattr(self.op, "nodes", None))
4299

    
4300
  def Exec(self, feedback_fn):
4301
    """Compute the list of all the exported system images.
4302

4303
    Returns:
4304
      a dictionary with the structure node->(export-list)
4305
      where export-list is a list of the instances exported on
4306
      that node.
4307

4308
    """
4309
    return rpc.call_export_list(self.nodes)
4310

    
4311

    
4312
class LUExportInstance(LogicalUnit):
4313
  """Export an instance to an image in the cluster.
4314

4315
  """
4316
  HPATH = "instance-export"
4317
  HTYPE = constants.HTYPE_INSTANCE
4318
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
4319

    
4320
  def BuildHooksEnv(self):
4321
    """Build hooks env.
4322

4323
    This will run on the master, primary node and target node.
4324

4325
    """
4326
    env = {
4327
      "EXPORT_NODE": self.op.target_node,
4328
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
4329
      }
4330
    env.update(_BuildInstanceHookEnvByObject(self.instance))
4331
    nl = [self.sstore.GetMasterNode(), self.instance.primary_node,
4332
          self.op.target_node]
4333
    return env, nl, nl
4334

    
4335
  def CheckPrereq(self):
4336
    """Check prerequisites.
4337

4338
    This checks that the instance and node names are valid.
4339

4340
    """
4341
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
4342
    self.instance = self.cfg.GetInstanceInfo(instance_name)
4343
    if self.instance is None:
4344
      raise errors.OpPrereqError("Instance '%s' not found" %
4345
                                 self.op.instance_name)
4346

    
4347
    # node verification
4348
    dst_node_short = self.cfg.ExpandNodeName(self.op.target_node)
4349
    self.dst_node = self.cfg.GetNodeInfo(dst_node_short)
4350

    
4351
    if self.dst_node is None:
4352
      raise errors.OpPrereqError("Destination node '%s' is unknown." %
4353
                                 self.op.target_node)
4354
    self.op.target_node = self.dst_node.name
4355

    
4356
    # instance disk type verification
4357
    for disk in self.instance.disks:
4358
      if disk.dev_type == constants.LD_FILE:
4359
        raise errors.OpPrereqError("Export not supported for instances with"
4360
                                   " file-based disks")
4361

    
4362
  def Exec(self, feedback_fn):
4363
    """Export an instance to an image in the cluster.
4364

4365
    """
4366
    instance = self.instance
4367
    dst_node = self.dst_node
4368
    src_node = instance.primary_node
4369
    if self.op.shutdown:
4370
      # shutdown the instance, but not the disks
4371
      if not rpc.call_instance_shutdown(src_node, instance):
4372
         raise errors.OpExecError("Could not shutdown instance %s on node %s" %
4373
                                  (instance.name, src_node))
4374

    
4375
    vgname = self.cfg.GetVGName()
4376

    
4377
    snap_disks = []
4378

    
4379
    try:
4380
      for disk in instance.disks:
4381
        if disk.iv_name == "sda":
4382
          # new_dev_name will be a snapshot of an lvm leaf of the one we passed
4383
          new_dev_name = rpc.call_blockdev_snapshot(src_node, disk)
4384

    
4385
          if not new_dev_name:
4386
            logger.Error("could not snapshot block device %s on node %s" %
4387
                         (disk.logical_id[1], src_node))
4388
          else:
4389
            new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
4390
                                      logical_id=(vgname, new_dev_name),
4391
                                      physical_id=(vgname, new_dev_name),
4392
                                      iv_name=disk.iv_name)
4393
            snap_disks.append(new_dev)
4394

    
4395
    finally:
4396
      if self.op.shutdown and instance.status == "up":
4397
        if not rpc.call_instance_start(src_node, instance, None):
4398
          _ShutdownInstanceDisks(instance, self.cfg)
4399
          raise errors.OpExecError("Could not start instance")
4400

    
4401
    # TODO: check for size
4402

    
4403
    for dev in snap_disks:
4404
      if not rpc.call_snapshot_export(src_node, dev, dst_node.name, instance):
4405
        logger.Error("could not export block device %s from node %s to node %s"
4406
                     % (dev.logical_id[1], src_node, dst_node.name))
4407
      if not rpc.call_blockdev_remove(src_node, dev):
4408
        logger.Error("could not remove snapshot block device %s from node %s" %
4409
                     (dev.logical_id[1], src_node))
4410

    
4411
    if not rpc.call_finalize_export(dst_node.name, instance, snap_disks):
4412
      logger.Error("could not finalize export for instance %s on node %s" %
4413
                   (instance.name, dst_node.name))
4414

    
4415
    nodelist = self.cfg.GetNodeList()
4416
    nodelist.remove(dst_node.name)
4417

    
4418
    # on one-node clusters nodelist will be empty after the removal
4419
    # if we proceed the backup would be removed because OpQueryExports
4420
    # substitutes an empty list with the full cluster node list.
4421
    if nodelist:
4422
      op = opcodes.OpQueryExports(nodes=nodelist)
4423
      exportlist = self.proc.ChainOpCode(op)
4424
      for node in exportlist:
4425
        if instance.name in exportlist[node]:
4426
          if not rpc.call_export_remove(node, instance.name):
4427
            logger.Error("could not remove older export for instance %s"
4428
                         " on node %s" % (instance.name, node))
4429

    
4430

    
4431
class LURemoveExport(NoHooksLU):
4432
  """Remove exports related to the named instance.
4433

4434
  """
4435
  _OP_REQP = ["instance_name"]
4436

    
4437
  def CheckPrereq(self):
4438
    """Check prerequisites.
4439
    """
4440
    pass
4441

    
4442
  def Exec(self, feedback_fn):
4443
    """Remove any export.
4444

4445
    """
4446
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
4447
    # If the instance was not found we'll try with the name that was passed in.
4448
    # This will only work if it was an FQDN, though.
4449
    fqdn_warn = False
4450
    if not instance_name:
4451
      fqdn_warn = True
4452
      instance_name = self.op.instance_name
4453

    
4454
    op = opcodes.OpQueryExports(nodes=[])
4455
    exportlist = self.proc.ChainOpCode(op)
4456
    found = False
4457
    for node in exportlist:
4458
      if instance_name in exportlist[node]:
4459
        found = True
4460
        if not rpc.call_export_remove(node, instance_name):
4461
          logger.Error("could not remove export for instance %s"
4462
                       " on node %s" % (instance_name, node))
4463

    
4464
    if fqdn_warn and not found:
4465
      feedback_fn("Export not found. If trying to remove an export belonging"
4466
                  " to a deleted instance please use its Fully Qualified"
4467
                  " Domain Name.")
4468

    
4469

    
4470
class TagsLU(NoHooksLU):
4471
  """Generic tags LU.
4472

4473
  This is an abstract class which is the parent of all the other tags LUs.
4474

4475
  """
4476
  def CheckPrereq(self):
4477
    """Check prerequisites.
4478

4479
    """
4480
    if self.op.kind == constants.TAG_CLUSTER:
4481
      self.target = self.cfg.GetClusterInfo()
4482
    elif self.op.kind == constants.TAG_NODE:
4483
      name = self.cfg.ExpandNodeName(self.op.name)
4484
      if name is None:
4485
        raise errors.OpPrereqError("Invalid node name (%s)" %
4486
                                   (self.op.name,))
4487
      self.op.name = name
4488
      self.target = self.cfg.GetNodeInfo(name)
4489
    elif self.op.kind == constants.TAG_INSTANCE:
4490
      name = self.cfg.ExpandInstanceName(self.op.name)
4491
      if name is None:
4492
        raise errors.OpPrereqError("Invalid instance name (%s)" %
4493
                                   (self.op.name,))
4494
      self.op.name = name
4495
      self.target = self.cfg.GetInstanceInfo(name)
4496
    else:
4497
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
4498
                                 str(self.op.kind))
4499

    
4500

    
4501
class LUGetTags(TagsLU):
4502
  """Returns the tags of a given object.
4503

4504
  """
4505
  _OP_REQP = ["kind", "name"]
4506

    
4507
  def Exec(self, feedback_fn):
4508
    """Returns the tag list.
4509

4510
    """
4511
    return list(self.target.GetTags())
4512

    
4513

    
4514
class LUSearchTags(NoHooksLU):
4515
  """Searches the tags for a given pattern.
4516

4517
  """
4518
  _OP_REQP = ["pattern"]
4519

    
4520
  def CheckPrereq(self):
4521
    """Check prerequisites.
4522

4523
    This checks the pattern passed for validity by compiling it.
4524

4525
    """
4526
    try:
4527
      self.re = re.compile(self.op.pattern)
4528
    except re.error, err:
4529
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
4530
                                 (self.op.pattern, err))
4531

    
4532
  def Exec(self, feedback_fn):
4533
    """Returns the tag list.
4534

4535
    """
4536
    cfg = self.cfg
4537
    tgts = [("/cluster", cfg.GetClusterInfo())]
4538
    ilist = [cfg.GetInstanceInfo(name) for name in cfg.GetInstanceList()]
4539
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
4540
    nlist = [cfg.GetNodeInfo(name) for name in cfg.GetNodeList()]
4541
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
4542
    results = []
4543
    for path, target in tgts:
4544
      for tag in target.GetTags():
4545
        if self.re.search(tag):
4546
          results.append((path, tag))
4547
    return results
4548

    
4549

    
4550
class LUAddTags(TagsLU):
4551
  """Sets a tag on a given object.
4552

4553
  """
4554
  _OP_REQP = ["kind", "name", "tags"]
4555

    
4556
  def CheckPrereq(self):
4557
    """Check prerequisites.
4558

4559
    This checks the type and length of the tag name and value.
4560

4561
    """
4562
    TagsLU.CheckPrereq(self)
4563
    for tag in self.op.tags:
4564
      objects.TaggableObject.ValidateTag(tag)
4565

    
4566
  def Exec(self, feedback_fn):
4567
    """Sets the tag.
4568

4569
    """
4570
    try:
4571
      for tag in self.op.tags:
4572
        self.target.AddTag(tag)
4573
    except errors.TagError, err:
4574
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
4575
    try:
4576
      self.cfg.Update(self.target)
4577
    except errors.ConfigurationError:
4578
      raise errors.OpRetryError("There has been a modification to the"
4579
                                " config file and the operation has been"
4580
                                " aborted. Please retry.")
4581

    
4582

    
4583
class LUDelTags(TagsLU):
4584
  """Delete a list of tags from a given object.
4585

4586
  """
4587
  _OP_REQP = ["kind", "name", "tags"]
4588

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

4592
    This checks that we have the given tag.
4593

4594
    """
4595
    TagsLU.CheckPrereq(self)
4596
    for tag in self.op.tags:
4597
      objects.TaggableObject.ValidateTag(tag)
4598
    del_tags = frozenset(self.op.tags)
4599
    cur_tags = self.target.GetTags()
4600
    if not del_tags <= cur_tags:
4601
      diff_tags = del_tags - cur_tags
4602
      diff_names = ["'%s'" % tag for tag in diff_tags]
4603
      diff_names.sort()
4604
      raise errors.OpPrereqError("Tag(s) %s not found" %
4605
                                 (",".join(diff_names)))
4606

    
4607
  def Exec(self, feedback_fn):
4608
    """Remove the tag from the object.
4609

4610
    """
4611
    for tag in self.op.tags:
4612
      self.target.RemoveTag(tag)
4613
    try:
4614
      self.cfg.Update(self.target)
4615
    except errors.ConfigurationError:
4616
      raise errors.OpRetryError("There has been a modification to the"
4617
                                " config file and the operation has been"
4618
                                " aborted. Please retry.")
4619

    
4620

    
4621
class LUTestDelay(NoHooksLU):
4622
  """Sleep for a specified amount of time.
4623

4624
  This LU sleeps on the master and/or nodes for a specified amount of
4625
  time.
4626

4627
  """
4628
  _OP_REQP = ["duration", "on_master", "on_nodes"]
4629
  REQ_BGL = False
4630

    
4631
  def ExpandNames(self):
4632
    """Expand names and set required locks.
4633

4634
    This expands the node list, if any.
4635

4636
    """
4637
    self.needed_locks = {}
4638
    if self.op.on_nodes:
4639
      # _GetWantedNodes can be used here, but is not always appropriate to use
4640
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
4641
      # more information.
4642
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
4643
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
4644

    
4645
  def CheckPrereq(self):
4646
    """Check prerequisites.
4647

4648
    """
4649

    
4650
  def Exec(self, feedback_fn):
4651
    """Do the actual sleep.
4652

4653
    """
4654
    if self.op.on_master:
4655
      if not utils.TestDelay(self.op.duration):
4656
        raise errors.OpExecError("Error during master delay test")
4657
    if self.op.on_nodes:
4658
      result = rpc.call_test_delay(self.op.on_nodes, self.op.duration)
4659
      if not result:
4660
        raise errors.OpExecError("Complete failure from rpc call")
4661
      for node, node_result in result.items():
4662
        if not node_result:
4663
          raise errors.OpExecError("Failure during rpc call to node %s,"
4664
                                   " result: %s" % (node, node_result))
4665

    
4666

    
4667
class IAllocator(object):
4668
  """IAllocator framework.
4669

4670
  An IAllocator instance has three sets of attributes:
4671
    - cfg/sstore that are needed to query the cluster
4672
    - input data (all members of the _KEYS class attribute are required)
4673
    - four buffer attributes (in|out_data|text), that represent the
4674
      input (to the external script) in text and data structure format,
4675
      and the output from it, again in two formats
4676
    - the result variables from the script (success, info, nodes) for
4677
      easy usage
4678

4679
  """
4680
  _ALLO_KEYS = [
4681
    "mem_size", "disks", "disk_template",
4682
    "os", "tags", "nics", "vcpus",
4683
    ]
4684
  _RELO_KEYS = [
4685
    "relocate_from",
4686
    ]
4687

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

    
4721
  def _ComputeClusterData(self):
4722
    """Compute the generic allocator input data.
4723

4724
    This is the data that is independent of the actual operation.
4725

4726
    """
4727
    cfg = self.cfg
4728
    # cluster data
4729
    data = {
4730
      "version": 1,
4731
      "cluster_name": self.sstore.GetClusterName(),
4732
      "cluster_tags": list(cfg.GetClusterInfo().GetTags()),
4733
      "hypervisor_type": self.sstore.GetHypervisorType(),
4734
      # we don't have job IDs
4735
      }
4736

    
4737
    i_list = [cfg.GetInstanceInfo(iname) for iname in cfg.GetInstanceList()]
4738

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

    
4766
      # compute memory used by instances
4767
      pnr = {
4768
        "tags": list(ninfo.GetTags()),
4769
        "total_memory": remote_info['memory_total'],
4770
        "reserved_memory": remote_info['memory_dom0'],
4771
        "free_memory": remote_info['memory_free'],
4772
        "i_pri_memory": i_p_mem,
4773
        "i_pri_up_memory": i_p_up_mem,
4774
        "total_disk": remote_info['vg_size'],
4775
        "free_disk": remote_info['vg_free'],
4776
        "primary_ip": ninfo.primary_ip,
4777
        "secondary_ip": ninfo.secondary_ip,
4778
        "total_cpus": remote_info['cpu_total'],
4779
        }
4780
      node_results[nname] = pnr
4781
    data["nodes"] = node_results
4782

    
4783
    # instance data
4784
    instance_data = {}
4785
    for iinfo in i_list:
4786
      nic_data = [{"mac": n.mac, "ip": n.ip, "bridge": n.bridge}
4787
                  for n in iinfo.nics]
4788
      pir = {
4789
        "tags": list(iinfo.GetTags()),
4790
        "should_run": iinfo.status == "up",
4791
        "vcpus": iinfo.vcpus,
4792
        "memory": iinfo.memory,
4793
        "os": iinfo.os,
4794
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
4795
        "nics": nic_data,
4796
        "disks": [{"size": dsk.size, "mode": "w"} for dsk in iinfo.disks],
4797
        "disk_template": iinfo.disk_template,
4798
        }
4799
      instance_data[iinfo.name] = pir
4800

    
4801
    data["instances"] = instance_data
4802

    
4803
    self.in_data = data
4804

    
4805
  def _AddNewInstance(self):
4806
    """Add new instance data to allocator structure.
4807

4808
    This in combination with _AllocatorGetClusterData will create the
4809
    correct structure needed as input for the allocator.
4810

4811
    The checks for the completeness of the opcode must have already been
4812
    done.
4813

4814
    """
4815
    data = self.in_data
4816
    if len(self.disks) != 2:
4817
      raise errors.OpExecError("Only two-disk configurations supported")
4818

    
4819
    disk_space = _ComputeDiskSize(self.disk_template,
4820
                                  self.disks[0]["size"], self.disks[1]["size"])
4821

    
4822
    if self.disk_template in constants.DTS_NET_MIRROR:
4823
      self.required_nodes = 2
4824
    else:
4825
      self.required_nodes = 1
4826
    request = {
4827
      "type": "allocate",
4828
      "name": self.name,
4829
      "disk_template": self.disk_template,
4830
      "tags": self.tags,
4831
      "os": self.os,
4832
      "vcpus": self.vcpus,
4833
      "memory": self.mem_size,
4834
      "disks": self.disks,
4835
      "disk_space_total": disk_space,
4836
      "nics": self.nics,
4837
      "required_nodes": self.required_nodes,
4838
      }
4839
    data["request"] = request
4840

    
4841
  def _AddRelocateInstance(self):
4842
    """Add relocate instance data to allocator structure.
4843

4844
    This in combination with _IAllocatorGetClusterData will create the
4845
    correct structure needed as input for the allocator.
4846

4847
    The checks for the completeness of the opcode must have already been
4848
    done.
4849

4850
    """
4851
    instance = self.cfg.GetInstanceInfo(self.name)
4852
    if instance is None:
4853
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
4854
                                   " IAllocator" % self.name)
4855

    
4856
    if instance.disk_template not in constants.DTS_NET_MIRROR:
4857
      raise errors.OpPrereqError("Can't relocate non-mirrored instances")
4858

    
4859
    if len(instance.secondary_nodes) != 1:
4860
      raise errors.OpPrereqError("Instance has not exactly one secondary node")
4861

    
4862
    self.required_nodes = 1
4863

    
4864
    disk_space = _ComputeDiskSize(instance.disk_template,
4865
                                  instance.disks[0].size,
4866
                                  instance.disks[1].size)
4867

    
4868
    request = {
4869
      "type": "relocate",
4870
      "name": self.name,
4871
      "disk_space_total": disk_space,
4872
      "required_nodes": self.required_nodes,
4873
      "relocate_from": self.relocate_from,
4874
      }
4875
    self.in_data["request"] = request
4876

    
4877
  def _BuildInputData(self):
4878
    """Build input data structures.
4879

4880
    """
4881
    self._ComputeClusterData()
4882

    
4883
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
4884
      self._AddNewInstance()
4885
    else:
4886
      self._AddRelocateInstance()
4887

    
4888
    self.in_text = serializer.Dump(self.in_data)
4889

    
4890
  def Run(self, name, validate=True, call_fn=rpc.call_iallocator_runner):
4891
    """Run an instance allocator and return the results.
4892

4893
    """
4894
    data = self.in_text
4895

    
4896
    result = call_fn(self.sstore.GetMasterNode(), name, self.in_text)
4897

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

    
4901
    rcode, stdout, stderr, fail = result
4902

    
4903
    if rcode == constants.IARUN_NOTFOUND:
4904
      raise errors.OpExecError("Can't find allocator '%s'" % name)
4905
    elif rcode == constants.IARUN_FAILURE:
4906
        raise errors.OpExecError("Instance allocator call failed: %s,"
4907
                                 " output: %s" %
4908
                                 (fail, stdout+stderr))
4909
    self.out_text = stdout
4910
    if validate:
4911
      self._ValidateResult()
4912

    
4913
  def _ValidateResult(self):
4914
    """Process the allocator results.
4915

4916
    This will process and if successful save the result in
4917
    self.out_data and the other parameters.
4918

4919
    """
4920
    try:
4921
      rdict = serializer.Load(self.out_text)
4922
    except Exception, err:
4923
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
4924

    
4925
    if not isinstance(rdict, dict):
4926
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
4927

    
4928
    for key in "success", "info", "nodes":
4929
      if key not in rdict:
4930
        raise errors.OpExecError("Can't parse iallocator results:"
4931
                                 " missing key '%s'" % key)
4932
      setattr(self, key, rdict[key])
4933

    
4934
    if not isinstance(rdict["nodes"], list):
4935
      raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
4936
                               " is not a list")
4937
    self.out_data = rdict
4938

    
4939

    
4940
class LUTestAllocator(NoHooksLU):
4941
  """Run allocator tests.
4942

4943
  This LU runs the allocator tests
4944

4945
  """
4946
  _OP_REQP = ["direction", "mode", "name"]
4947

    
4948
  def CheckPrereq(self):
4949
    """Check prerequisites.
4950

4951
    This checks the opcode parameters depending on the director and mode test.
4952

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

    
4998
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
4999
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
5000
        raise errors.OpPrereqError("Missing allocator name")
5001
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
5002
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
5003
                                 self.op.direction)
5004

    
5005
  def Exec(self, feedback_fn):
5006
    """Run the allocator test.
5007

5008
    """
5009
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
5010
      ial = IAllocator(self.cfg, self.sstore,
5011
                       mode=self.op.mode,
5012
                       name=self.op.name,
5013
                       mem_size=self.op.mem_size,
5014
                       disks=self.op.disks,
5015
                       disk_template=self.op.disk_template,
5016
                       os=self.op.os,
5017
                       tags=self.op.tags,
5018
                       nics=self.op.nics,
5019
                       vcpus=self.op.vcpus,
5020
                       )
5021
    else:
5022
      ial = IAllocator(self.cfg, self.sstore,
5023
                       mode=self.op.mode,
5024
                       name=self.op.name,
5025
                       relocate_from=list(self.relocate_from),
5026
                       )
5027

    
5028
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
5029
      result = ial.in_text
5030
    else:
5031
      ial.Run(self.op.allocator, validate=False)
5032
      result = ial.out_text
5033
    return result