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