Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 3e0cea06

History | View | Annotate | Download (194.3 kB)

1
#
2
#
3

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

    
21

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

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

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

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

    
47

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

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

61
  Note that all commands require root permissions.
62

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

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

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

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

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

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

    
110
  def __GetSSH(self):
111
    """Returns the SshRunner object
112

113
    """
114
    if not self.__ssh:
115
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
116
    return self.__ssh
117

    
118
  ssh = property(fget=__GetSSH)
119

    
120
  def ExpandNames(self):
121
    """Expand names for this LU.
122

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

128
    LUs which implement this method must also populate the self.needed_locks
129
    member, as a dict with lock levels as keys, and a list of needed lock names
130
    as values. Rules:
131
      - Use an empty dict if you don't need any lock
132
      - If you don't need any lock at a particular level omit that level
133
      - Don't put anything for the BGL level
134
      - If you want all locks at a level use locking.ALL_SET as a value
135

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

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

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

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

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

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

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

178
    """
179

    
180
  def CheckPrereq(self):
181
    """Check prerequisites for this LU.
182

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

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

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

194
    """
195
    raise NotImplementedError
196

    
197
  def Exec(self, feedback_fn):
198
    """Execute the LU.
199

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

204
    """
205
    raise NotImplementedError
206

    
207
  def BuildHooksEnv(self):
208
    """Build hooks environment for this LU.
209

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

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

221
    No nodes should be returned as an empty list (and not None).
222

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

226
    """
227
    raise NotImplementedError
228

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

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

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

244
    """
245
    return lu_result
246

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

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

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

    
269
  def _LockInstancesNodes(self, primary_only=False):
270
    """Helper function to declare instances' nodes for locking.
271

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

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

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

283
    If should be called in DeclareLocks in a way similar to:
284

285
    if level == locking.LEVEL_NODE:
286
      self._LockInstancesNodes()
287

288
    @type primary_only: boolean
289
    @param primary_only: only lock primary nodes of locked instances
290

291
    """
292
    assert locking.LEVEL_NODE in self.recalculate_locks, \
293
      "_LockInstancesNodes helper function called with no nodes to recalculate"
294

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

    
297
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
298
    # future we might want to have different behaviors depending on the value
299
    # of self.recalculate_locks[locking.LEVEL_NODE]
300
    wanted_nodes = []
301
    for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
302
      instance = self.context.cfg.GetInstanceInfo(instance_name)
303
      wanted_nodes.append(instance.primary_node)
304
      if not primary_only:
305
        wanted_nodes.extend(instance.secondary_nodes)
306

    
307
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
308
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
309
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
310
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
311

    
312
    del self.recalculate_locks[locking.LEVEL_NODE]
313

    
314

    
315
class NoHooksLU(LogicalUnit):
316
  """Simple LU which runs no hooks.
317

318
  This LU is intended as a parent for other LogicalUnits which will
319
  run no hooks, in order to reduce duplicate code.
320

321
  """
322
  HPATH = None
323
  HTYPE = None
324

    
325

    
326
class _FieldSet(object):
327
  """A simple field set.
328

329
  Among the features are:
330
    - checking if a string is among a list of static string or regex objects
331
    - checking if a whole list of string matches
332
    - returning the matching groups from a regex match
333

334
  Internally, all fields are held as regular expression objects.
335

336
  """
337
  def __init__(self, *items):
338
    self.items = [re.compile("^%s$" % value) for value in items]
339

    
340
  def Extend(self, other_set):
341
    """Extend the field set with the items from another one"""
342
    self.items.extend(other_set.items)
343

    
344
  def Matches(self, field):
345
    """Checks if a field matches the current set
346

347
    @type field: str
348
    @param field: the string to match
349
    @return: either False or a regular expression match object
350

351
    """
352
    for m in itertools.ifilter(None, (val.match(field) for val in self.items)):
353
      return m
354
    return False
355

    
356
  def NonMatching(self, items):
357
    """Returns the list of fields not matching the current set
358

359
    @type items: list
360
    @param items: the list of fields to check
361
    @rtype: list
362
    @return: list of non-matching fields
363

364
    """
365
    return [val for val in items if not self.Matches(val)]
366

    
367

    
368
def _GetWantedNodes(lu, nodes):
369
  """Returns list of checked and expanded node names.
370

371
  Args:
372
    nodes: List of nodes (strings) or None for all
373

374
  """
375
  if not isinstance(nodes, list):
376
    raise errors.OpPrereqError("Invalid argument type 'nodes'")
377

    
378
  if not nodes:
379
    raise errors.ProgrammerError("_GetWantedNodes should only be called with a"
380
      " non-empty list of nodes whose name is to be expanded.")
381

    
382
  wanted = []
383
  for name in nodes:
384
    node = lu.cfg.ExpandNodeName(name)
385
    if node is None:
386
      raise errors.OpPrereqError("No such node name '%s'" % name)
387
    wanted.append(node)
388

    
389
  return utils.NiceSort(wanted)
390

    
391

    
392
def _GetWantedInstances(lu, instances):
393
  """Returns list of checked and expanded instance names.
394

395
  Args:
396
    instances: List of instances (strings) or None for all
397

398
  """
399
  if not isinstance(instances, list):
400
    raise errors.OpPrereqError("Invalid argument type 'instances'")
401

    
402
  if instances:
403
    wanted = []
404

    
405
    for name in instances:
406
      instance = lu.cfg.ExpandInstanceName(name)
407
      if instance is None:
408
        raise errors.OpPrereqError("No such instance name '%s'" % name)
409
      wanted.append(instance)
410

    
411
  else:
412
    wanted = lu.cfg.GetInstanceList()
413
  return utils.NiceSort(wanted)
414

    
415

    
416
def _CheckOutputFields(static, dynamic, selected):
417
  """Checks whether all selected fields are valid.
418

419
  @type static: L{_FieldSet}
420
  @param static: static fields set
421
  @type dynamic: L{_FieldSet}
422
  @param dynamic: dynamic fields set
423

424
  """
425
  f = _FieldSet()
426
  f.Extend(static)
427
  f.Extend(dynamic)
428

    
429
  delta = f.NonMatching(selected)
430
  if delta:
431
    raise errors.OpPrereqError("Unknown output fields selected: %s"
432
                               % ",".join(delta))
433

    
434

    
435
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
436
                          memory, vcpus, nics):
437
  """Builds instance related env variables for hooks from single variables.
438

439
  Args:
440
    secondary_nodes: List of secondary nodes as strings
441
  """
442
  env = {
443
    "OP_TARGET": name,
444
    "INSTANCE_NAME": name,
445
    "INSTANCE_PRIMARY": primary_node,
446
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
447
    "INSTANCE_OS_TYPE": os_type,
448
    "INSTANCE_STATUS": status,
449
    "INSTANCE_MEMORY": memory,
450
    "INSTANCE_VCPUS": vcpus,
451
  }
452

    
453
  if nics:
454
    nic_count = len(nics)
455
    for idx, (ip, bridge, mac) in enumerate(nics):
456
      if ip is None:
457
        ip = ""
458
      env["INSTANCE_NIC%d_IP" % idx] = ip
459
      env["INSTANCE_NIC%d_BRIDGE" % idx] = bridge
460
      env["INSTANCE_NIC%d_HWADDR" % idx] = mac
461
  else:
462
    nic_count = 0
463

    
464
  env["INSTANCE_NIC_COUNT"] = nic_count
465

    
466
  return env
467

    
468

    
469
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
470
  """Builds instance related env variables for hooks from an object.
471

472
  Args:
473
    instance: objects.Instance object of instance
474
    override: dict of values to override
475
  """
476
  bep = lu.cfg.GetClusterInfo().FillBE(instance)
477
  args = {
478
    'name': instance.name,
479
    'primary_node': instance.primary_node,
480
    'secondary_nodes': instance.secondary_nodes,
481
    'os_type': instance.os,
482
    'status': instance.os,
483
    'memory': bep[constants.BE_MEMORY],
484
    'vcpus': bep[constants.BE_VCPUS],
485
    'nics': [(nic.ip, nic.bridge, nic.mac) for nic in instance.nics],
486
  }
487
  if override:
488
    args.update(override)
489
  return _BuildInstanceHookEnv(**args)
490

    
491

    
492
def _CheckInstanceBridgesExist(lu, instance):
493
  """Check that the brigdes needed by an instance exist.
494

495
  """
496
  # check bridges existance
497
  brlist = [nic.bridge for nic in instance.nics]
498
  if not lu.rpc.call_bridges_exist(instance.primary_node, brlist):
499
    raise errors.OpPrereqError("one or more target bridges %s does not"
500
                               " exist on destination node '%s'" %
501
                               (brlist, instance.primary_node))
502

    
503

    
504
class LUDestroyCluster(NoHooksLU):
505
  """Logical unit for destroying the cluster.
506

507
  """
508
  _OP_REQP = []
509

    
510
  def CheckPrereq(self):
511
    """Check prerequisites.
512

513
    This checks whether the cluster is empty.
514

515
    Any errors are signalled by raising errors.OpPrereqError.
516

517
    """
518
    master = self.cfg.GetMasterNode()
519

    
520
    nodelist = self.cfg.GetNodeList()
521
    if len(nodelist) != 1 or nodelist[0] != master:
522
      raise errors.OpPrereqError("There are still %d node(s) in"
523
                                 " this cluster." % (len(nodelist) - 1))
524
    instancelist = self.cfg.GetInstanceList()
525
    if instancelist:
526
      raise errors.OpPrereqError("There are still %d instance(s) in"
527
                                 " this cluster." % len(instancelist))
528

    
529
  def Exec(self, feedback_fn):
530
    """Destroys the cluster.
531

532
    """
533
    master = self.cfg.GetMasterNode()
534
    if not self.rpc.call_node_stop_master(master, False):
535
      raise errors.OpExecError("Could not disable the master role")
536
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
537
    utils.CreateBackup(priv_key)
538
    utils.CreateBackup(pub_key)
539
    return master
540

    
541

    
542
class LUVerifyCluster(LogicalUnit):
543
  """Verifies the cluster status.
544

545
  """
546
  HPATH = "cluster-verify"
547
  HTYPE = constants.HTYPE_CLUSTER
548
  _OP_REQP = ["skip_checks"]
549
  REQ_BGL = False
550

    
551
  def ExpandNames(self):
552
    self.needed_locks = {
553
      locking.LEVEL_NODE: locking.ALL_SET,
554
      locking.LEVEL_INSTANCE: locking.ALL_SET,
555
    }
556
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
557

    
558
  def _VerifyNode(self, node, file_list, local_cksum, vglist, node_result,
559
                  remote_version, feedback_fn):
560
    """Run multiple tests against a node.
561

562
    Test list:
563
      - compares ganeti version
564
      - checks vg existance and size > 20G
565
      - checks config file checksum
566
      - checks ssh to other nodes
567

568
    Args:
569
      node: name of the node to check
570
      file_list: required list of files
571
      local_cksum: dictionary of local files and their checksums
572

573
    """
574
    # compares ganeti version
575
    local_version = constants.PROTOCOL_VERSION
576
    if not remote_version:
577
      feedback_fn("  - ERROR: connection to %s failed" % (node))
578
      return True
579

    
580
    if local_version != remote_version:
581
      feedback_fn("  - ERROR: sw version mismatch: master %s, node(%s) %s" %
582
                      (local_version, node, remote_version))
583
      return True
584

    
585
    # checks vg existance and size > 20G
586

    
587
    bad = False
588
    if not vglist:
589
      feedback_fn("  - ERROR: unable to check volume groups on node %s." %
590
                      (node,))
591
      bad = True
592
    else:
593
      vgstatus = utils.CheckVolumeGroupSize(vglist, self.cfg.GetVGName(),
594
                                            constants.MIN_VG_SIZE)
595
      if vgstatus:
596
        feedback_fn("  - ERROR: %s on node %s" % (vgstatus, node))
597
        bad = True
598

    
599
    if not node_result:
600
      feedback_fn("  - ERROR: unable to verify node %s." % (node,))
601
      return True
602

    
603
    # checks config file checksum
604
    # checks ssh to any
605

    
606
    if 'filelist' not in node_result:
607
      bad = True
608
      feedback_fn("  - ERROR: node hasn't returned file checksum data")
609
    else:
610
      remote_cksum = node_result['filelist']
611
      for file_name in file_list:
612
        if file_name not in remote_cksum:
613
          bad = True
614
          feedback_fn("  - ERROR: file '%s' missing" % file_name)
615
        elif remote_cksum[file_name] != local_cksum[file_name]:
616
          bad = True
617
          feedback_fn("  - ERROR: file '%s' has wrong checksum" % file_name)
618

    
619
    if 'nodelist' not in node_result:
620
      bad = True
621
      feedback_fn("  - ERROR: node hasn't returned node ssh connectivity data")
622
    else:
623
      if node_result['nodelist']:
624
        bad = True
625
        for node in node_result['nodelist']:
626
          feedback_fn("  - ERROR: ssh communication with node '%s': %s" %
627
                          (node, node_result['nodelist'][node]))
628
    if 'node-net-test' not in node_result:
629
      bad = True
630
      feedback_fn("  - ERROR: node hasn't returned node tcp connectivity data")
631
    else:
632
      if node_result['node-net-test']:
633
        bad = True
634
        nlist = utils.NiceSort(node_result['node-net-test'].keys())
635
        for node in nlist:
636
          feedback_fn("  - ERROR: tcp communication with node '%s': %s" %
637
                          (node, node_result['node-net-test'][node]))
638

    
639
    hyp_result = node_result.get('hypervisor', None)
640
    if isinstance(hyp_result, dict):
641
      for hv_name, hv_result in hyp_result.iteritems():
642
        if hv_result is not None:
643
          feedback_fn("  - ERROR: hypervisor %s verify failure: '%s'" %
644
                      (hv_name, hv_result))
645
    return bad
646

    
647
  def _VerifyInstance(self, instance, instanceconfig, node_vol_is,
648
                      node_instance, feedback_fn):
649
    """Verify an instance.
650

651
    This function checks to see if the required block devices are
652
    available on the instance's node.
653

654
    """
655
    bad = False
656

    
657
    node_current = instanceconfig.primary_node
658

    
659
    node_vol_should = {}
660
    instanceconfig.MapLVsByNode(node_vol_should)
661

    
662
    for node in node_vol_should:
663
      for volume in node_vol_should[node]:
664
        if node not in node_vol_is or volume not in node_vol_is[node]:
665
          feedback_fn("  - ERROR: volume %s missing on node %s" %
666
                          (volume, node))
667
          bad = True
668

    
669
    if not instanceconfig.status == 'down':
670
      if (node_current not in node_instance or
671
          not instance in node_instance[node_current]):
672
        feedback_fn("  - ERROR: instance %s not running on node %s" %
673
                        (instance, node_current))
674
        bad = True
675

    
676
    for node in node_instance:
677
      if (not node == node_current):
678
        if instance in node_instance[node]:
679
          feedback_fn("  - ERROR: instance %s should not run on node %s" %
680
                          (instance, node))
681
          bad = True
682

    
683
    return bad
684

    
685
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is, feedback_fn):
686
    """Verify if there are any unknown volumes in the cluster.
687

688
    The .os, .swap and backup volumes are ignored. All other volumes are
689
    reported as unknown.
690

691
    """
692
    bad = False
693

    
694
    for node in node_vol_is:
695
      for volume in node_vol_is[node]:
696
        if node not in node_vol_should or volume not in node_vol_should[node]:
697
          feedback_fn("  - ERROR: volume %s on node %s should not exist" %
698
                      (volume, node))
699
          bad = True
700
    return bad
701

    
702
  def _VerifyOrphanInstances(self, instancelist, node_instance, feedback_fn):
703
    """Verify the list of running instances.
704

705
    This checks what instances are running but unknown to the cluster.
706

707
    """
708
    bad = False
709
    for node in node_instance:
710
      for runninginstance in node_instance[node]:
711
        if runninginstance not in instancelist:
712
          feedback_fn("  - ERROR: instance %s on node %s should not exist" %
713
                          (runninginstance, node))
714
          bad = True
715
    return bad
716

    
717
  def _VerifyNPlusOneMemory(self, node_info, instance_cfg, feedback_fn):
718
    """Verify N+1 Memory Resilience.
719

720
    Check that if one single node dies we can still start all the instances it
721
    was primary for.
722

723
    """
724
    bad = False
725

    
726
    for node, nodeinfo in node_info.iteritems():
727
      # This code checks that every node which is now listed as secondary has
728
      # enough memory to host all instances it is supposed to should a single
729
      # other node in the cluster fail.
730
      # FIXME: not ready for failover to an arbitrary node
731
      # FIXME: does not support file-backed instances
732
      # WARNING: we currently take into account down instances as well as up
733
      # ones, considering that even if they're down someone might want to start
734
      # them even in the event of a node failure.
735
      for prinode, instances in nodeinfo['sinst-by-pnode'].iteritems():
736
        needed_mem = 0
737
        for instance in instances:
738
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
739
          if bep[constants.BE_AUTO_BALANCE]:
740
            needed_mem += bep[constants.BE_MEMORY]
741
        if nodeinfo['mfree'] < needed_mem:
742
          feedback_fn("  - ERROR: not enough memory on node %s to accomodate"
743
                      " failovers should node %s fail" % (node, prinode))
744
          bad = True
745
    return bad
746

    
747
  def CheckPrereq(self):
748
    """Check prerequisites.
749

750
    Transform the list of checks we're going to skip into a set and check that
751
    all its members are valid.
752

753
    """
754
    self.skip_set = frozenset(self.op.skip_checks)
755
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
756
      raise errors.OpPrereqError("Invalid checks to be skipped specified")
757

    
758
  def BuildHooksEnv(self):
759
    """Build hooks env.
760

761
    Cluster-Verify hooks just rone in the post phase and their failure makes
762
    the output be logged in the verify output and the verification to fail.
763

764
    """
765
    all_nodes = self.cfg.GetNodeList()
766
    # TODO: populate the environment with useful information for verify hooks
767
    env = {}
768
    return env, [], all_nodes
769

    
770
  def Exec(self, feedback_fn):
771
    """Verify integrity of cluster, performing various test on nodes.
772

773
    """
774
    bad = False
775
    feedback_fn("* Verifying global settings")
776
    for msg in self.cfg.VerifyConfig():
777
      feedback_fn("  - ERROR: %s" % msg)
778

    
779
    vg_name = self.cfg.GetVGName()
780
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
781
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
782
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
783
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
784
    i_non_redundant = [] # Non redundant instances
785
    i_non_a_balanced = [] # Non auto-balanced instances
786
    node_volume = {}
787
    node_instance = {}
788
    node_info = {}
789
    instance_cfg = {}
790

    
791
    # FIXME: verify OS list
792
    # do local checksums
793
    file_names = []
794
    file_names.append(constants.SSL_CERT_FILE)
795
    file_names.append(constants.CLUSTER_CONF_FILE)
796
    local_checksums = utils.FingerprintFiles(file_names)
797

    
798
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
799
    all_volumeinfo = self.rpc.call_volume_list(nodelist, vg_name)
800
    all_instanceinfo = self.rpc.call_instance_list(nodelist, hypervisors)
801
    all_vglist = self.rpc.call_vg_list(nodelist)
802
    node_verify_param = {
803
      'filelist': file_names,
804
      'nodelist': nodelist,
805
      'hypervisor': hypervisors,
806
      'node-net-test': [(node.name, node.primary_ip, node.secondary_ip)
807
                        for node in nodeinfo]
808
      }
809
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
810
                                           self.cfg.GetClusterName())
811
    all_rversion = self.rpc.call_version(nodelist)
812
    all_ninfo = self.rpc.call_node_info(nodelist, self.cfg.GetVGName(),
813
                                        self.cfg.GetHypervisorType())
814

    
815
    cluster = self.cfg.GetClusterInfo()
816
    for node in nodelist:
817
      feedback_fn("* Verifying node %s" % node)
818
      result = self._VerifyNode(node, file_names, local_checksums,
819
                                all_vglist[node], all_nvinfo[node],
820
                                all_rversion[node], feedback_fn)
821
      bad = bad or result
822

    
823
      # node_volume
824
      volumeinfo = all_volumeinfo[node]
825

    
826
      if isinstance(volumeinfo, basestring):
827
        feedback_fn("  - ERROR: LVM problem on node %s: %s" %
828
                    (node, volumeinfo[-400:].encode('string_escape')))
829
        bad = True
830
        node_volume[node] = {}
831
      elif not isinstance(volumeinfo, dict):
832
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
833
        bad = True
834
        continue
835
      else:
836
        node_volume[node] = volumeinfo
837

    
838
      # node_instance
839
      nodeinstance = all_instanceinfo[node]
840
      if type(nodeinstance) != list:
841
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
842
        bad = True
843
        continue
844

    
845
      node_instance[node] = nodeinstance
846

    
847
      # node_info
848
      nodeinfo = all_ninfo[node]
849
      if not isinstance(nodeinfo, dict):
850
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
851
        bad = True
852
        continue
853

    
854
      try:
855
        node_info[node] = {
856
          "mfree": int(nodeinfo['memory_free']),
857
          "dfree": int(nodeinfo['vg_free']),
858
          "pinst": [],
859
          "sinst": [],
860
          # dictionary holding all instances this node is secondary for,
861
          # grouped by their primary node. Each key is a cluster node, and each
862
          # value is a list of instances which have the key as primary and the
863
          # current node as secondary.  this is handy to calculate N+1 memory
864
          # availability if you can only failover from a primary to its
865
          # secondary.
866
          "sinst-by-pnode": {},
867
        }
868
      except ValueError:
869
        feedback_fn("  - ERROR: invalid value returned from node %s" % (node,))
870
        bad = True
871
        continue
872

    
873
    node_vol_should = {}
874

    
875
    for instance in instancelist:
876
      feedback_fn("* Verifying instance %s" % instance)
877
      inst_config = self.cfg.GetInstanceInfo(instance)
878
      result =  self._VerifyInstance(instance, inst_config, node_volume,
879
                                     node_instance, feedback_fn)
880
      bad = bad or result
881

    
882
      inst_config.MapLVsByNode(node_vol_should)
883

    
884
      instance_cfg[instance] = inst_config
885

    
886
      pnode = inst_config.primary_node
887
      if pnode in node_info:
888
        node_info[pnode]['pinst'].append(instance)
889
      else:
890
        feedback_fn("  - ERROR: instance %s, connection to primary node"
891
                    " %s failed" % (instance, pnode))
892
        bad = True
893

    
894
      # If the instance is non-redundant we cannot survive losing its primary
895
      # node, so we are not N+1 compliant. On the other hand we have no disk
896
      # templates with more than one secondary so that situation is not well
897
      # supported either.
898
      # FIXME: does not support file-backed instances
899
      if len(inst_config.secondary_nodes) == 0:
900
        i_non_redundant.append(instance)
901
      elif len(inst_config.secondary_nodes) > 1:
902
        feedback_fn("  - WARNING: multiple secondaries for instance %s"
903
                    % instance)
904

    
905
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
906
        i_non_a_balanced.append(instance)
907

    
908
      for snode in inst_config.secondary_nodes:
909
        if snode in node_info:
910
          node_info[snode]['sinst'].append(instance)
911
          if pnode not in node_info[snode]['sinst-by-pnode']:
912
            node_info[snode]['sinst-by-pnode'][pnode] = []
913
          node_info[snode]['sinst-by-pnode'][pnode].append(instance)
914
        else:
915
          feedback_fn("  - ERROR: instance %s, connection to secondary node"
916
                      " %s failed" % (instance, snode))
917

    
918
    feedback_fn("* Verifying orphan volumes")
919
    result = self._VerifyOrphanVolumes(node_vol_should, node_volume,
920
                                       feedback_fn)
921
    bad = bad or result
922

    
923
    feedback_fn("* Verifying remaining instances")
924
    result = self._VerifyOrphanInstances(instancelist, node_instance,
925
                                         feedback_fn)
926
    bad = bad or result
927

    
928
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
929
      feedback_fn("* Verifying N+1 Memory redundancy")
930
      result = self._VerifyNPlusOneMemory(node_info, instance_cfg, feedback_fn)
931
      bad = bad or result
932

    
933
    feedback_fn("* Other Notes")
934
    if i_non_redundant:
935
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
936
                  % len(i_non_redundant))
937

    
938
    if i_non_a_balanced:
939
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
940
                  % len(i_non_a_balanced))
941

    
942
    return not bad
943

    
944
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
945
    """Analize the post-hooks' result, handle it, and send some
946
    nicely-formatted feedback back to the user.
947

948
    Args:
949
      phase: the hooks phase that has just been run
950
      hooks_results: the results of the multi-node hooks rpc call
951
      feedback_fn: function to send feedback back to the caller
952
      lu_result: previous Exec result
953

954
    """
955
    # We only really run POST phase hooks, and are only interested in
956
    # their results
957
    if phase == constants.HOOKS_PHASE_POST:
958
      # Used to change hooks' output to proper indentation
959
      indent_re = re.compile('^', re.M)
960
      feedback_fn("* Hooks Results")
961
      if not hooks_results:
962
        feedback_fn("  - ERROR: general communication failure")
963
        lu_result = 1
964
      else:
965
        for node_name in hooks_results:
966
          show_node_header = True
967
          res = hooks_results[node_name]
968
          if res is False or not isinstance(res, list):
969
            feedback_fn("    Communication failure")
970
            lu_result = 1
971
            continue
972
          for script, hkr, output in res:
973
            if hkr == constants.HKR_FAIL:
974
              # The node header is only shown once, if there are
975
              # failing hooks on that node
976
              if show_node_header:
977
                feedback_fn("  Node %s:" % node_name)
978
                show_node_header = False
979
              feedback_fn("    ERROR: Script %s failed, output:" % script)
980
              output = indent_re.sub('      ', output)
981
              feedback_fn("%s" % output)
982
              lu_result = 1
983

    
984
      return lu_result
985

    
986

    
987
class LUVerifyDisks(NoHooksLU):
988
  """Verifies the cluster disks status.
989

990
  """
991
  _OP_REQP = []
992
  REQ_BGL = False
993

    
994
  def ExpandNames(self):
995
    self.needed_locks = {
996
      locking.LEVEL_NODE: locking.ALL_SET,
997
      locking.LEVEL_INSTANCE: locking.ALL_SET,
998
    }
999
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
1000

    
1001
  def CheckPrereq(self):
1002
    """Check prerequisites.
1003

1004
    This has no prerequisites.
1005

1006
    """
1007
    pass
1008

    
1009
  def Exec(self, feedback_fn):
1010
    """Verify integrity of cluster disks.
1011

1012
    """
1013
    result = res_nodes, res_nlvm, res_instances, res_missing = [], {}, [], {}
1014

    
1015
    vg_name = self.cfg.GetVGName()
1016
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1017
    instances = [self.cfg.GetInstanceInfo(name)
1018
                 for name in self.cfg.GetInstanceList()]
1019

    
1020
    nv_dict = {}
1021
    for inst in instances:
1022
      inst_lvs = {}
1023
      if (inst.status != "up" or
1024
          inst.disk_template not in constants.DTS_NET_MIRROR):
1025
        continue
1026
      inst.MapLVsByNode(inst_lvs)
1027
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1028
      for node, vol_list in inst_lvs.iteritems():
1029
        for vol in vol_list:
1030
          nv_dict[(node, vol)] = inst
1031

    
1032
    if not nv_dict:
1033
      return result
1034

    
1035
    node_lvs = self.rpc.call_volume_list(nodes, vg_name)
1036

    
1037
    to_act = set()
1038
    for node in nodes:
1039
      # node_volume
1040
      lvs = node_lvs[node]
1041

    
1042
      if isinstance(lvs, basestring):
1043
        logging.warning("Error enumerating LVs on node %s: %s", node, lvs)
1044
        res_nlvm[node] = lvs
1045
      elif not isinstance(lvs, dict):
1046
        logging.warning("Connection to node %s failed or invalid data"
1047
                        " returned", node)
1048
        res_nodes.append(node)
1049
        continue
1050

    
1051
      for lv_name, (_, lv_inactive, lv_online) in lvs.iteritems():
1052
        inst = nv_dict.pop((node, lv_name), None)
1053
        if (not lv_online and inst is not None
1054
            and inst.name not in res_instances):
1055
          res_instances.append(inst.name)
1056

    
1057
    # any leftover items in nv_dict are missing LVs, let's arrange the
1058
    # data better
1059
    for key, inst in nv_dict.iteritems():
1060
      if inst.name not in res_missing:
1061
        res_missing[inst.name] = []
1062
      res_missing[inst.name].append(key)
1063

    
1064
    return result
1065

    
1066

    
1067
class LURenameCluster(LogicalUnit):
1068
  """Rename the cluster.
1069

1070
  """
1071
  HPATH = "cluster-rename"
1072
  HTYPE = constants.HTYPE_CLUSTER
1073
  _OP_REQP = ["name"]
1074

    
1075
  def BuildHooksEnv(self):
1076
    """Build hooks env.
1077

1078
    """
1079
    env = {
1080
      "OP_TARGET": self.cfg.GetClusterName(),
1081
      "NEW_NAME": self.op.name,
1082
      }
1083
    mn = self.cfg.GetMasterNode()
1084
    return env, [mn], [mn]
1085

    
1086
  def CheckPrereq(self):
1087
    """Verify that the passed name is a valid one.
1088

1089
    """
1090
    hostname = utils.HostInfo(self.op.name)
1091

    
1092
    new_name = hostname.name
1093
    self.ip = new_ip = hostname.ip
1094
    old_name = self.cfg.GetClusterName()
1095
    old_ip = self.cfg.GetMasterIP()
1096
    if new_name == old_name and new_ip == old_ip:
1097
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1098
                                 " cluster has changed")
1099
    if new_ip != old_ip:
1100
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1101
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1102
                                   " reachable on the network. Aborting." %
1103
                                   new_ip)
1104

    
1105
    self.op.name = new_name
1106

    
1107
  def Exec(self, feedback_fn):
1108
    """Rename the cluster.
1109

1110
    """
1111
    clustername = self.op.name
1112
    ip = self.ip
1113

    
1114
    # shutdown the master IP
1115
    master = self.cfg.GetMasterNode()
1116
    if not self.rpc.call_node_stop_master(master, False):
1117
      raise errors.OpExecError("Could not disable the master role")
1118

    
1119
    try:
1120
      # modify the sstore
1121
      # TODO: sstore
1122
      ss.SetKey(ss.SS_MASTER_IP, ip)
1123
      ss.SetKey(ss.SS_CLUSTER_NAME, clustername)
1124

    
1125
      # Distribute updated ss config to all nodes
1126
      myself = self.cfg.GetNodeInfo(master)
1127
      dist_nodes = self.cfg.GetNodeList()
1128
      if myself.name in dist_nodes:
1129
        dist_nodes.remove(myself.name)
1130

    
1131
      logging.debug("Copying updated ssconf data to all nodes")
1132
      for keyname in [ss.SS_CLUSTER_NAME, ss.SS_MASTER_IP]:
1133
        fname = ss.KeyToFilename(keyname)
1134
        result = self.rpc.call_upload_file(dist_nodes, fname)
1135
        for to_node in dist_nodes:
1136
          if not result[to_node]:
1137
            self.LogWarning("Copy of file %s to node %s failed",
1138
                            fname, to_node)
1139
    finally:
1140
      if not self.rpc.call_node_start_master(master, False):
1141
        self.LogWarning("Could not re-enable the master role on"
1142
                        " the master, please restart manually.")
1143

    
1144

    
1145
def _RecursiveCheckIfLVMBased(disk):
1146
  """Check if the given disk or its children are lvm-based.
1147

1148
  Args:
1149
    disk: ganeti.objects.Disk object
1150

1151
  Returns:
1152
    boolean indicating whether a LD_LV dev_type was found or not
1153

1154
  """
1155
  if disk.children:
1156
    for chdisk in disk.children:
1157
      if _RecursiveCheckIfLVMBased(chdisk):
1158
        return True
1159
  return disk.dev_type == constants.LD_LV
1160

    
1161

    
1162
class LUSetClusterParams(LogicalUnit):
1163
  """Change the parameters of the cluster.
1164

1165
  """
1166
  HPATH = "cluster-modify"
1167
  HTYPE = constants.HTYPE_CLUSTER
1168
  _OP_REQP = []
1169
  REQ_BGL = False
1170

    
1171
  def ExpandNames(self):
1172
    # FIXME: in the future maybe other cluster params won't require checking on
1173
    # all nodes to be modified.
1174
    self.needed_locks = {
1175
      locking.LEVEL_NODE: locking.ALL_SET,
1176
    }
1177
    self.share_locks[locking.LEVEL_NODE] = 1
1178

    
1179
  def BuildHooksEnv(self):
1180
    """Build hooks env.
1181

1182
    """
1183
    env = {
1184
      "OP_TARGET": self.cfg.GetClusterName(),
1185
      "NEW_VG_NAME": self.op.vg_name,
1186
      }
1187
    mn = self.cfg.GetMasterNode()
1188
    return env, [mn], [mn]
1189

    
1190
  def CheckPrereq(self):
1191
    """Check prerequisites.
1192

1193
    This checks whether the given params don't conflict and
1194
    if the given volume group is valid.
1195

1196
    """
1197
    # FIXME: This only works because there is only one parameter that can be
1198
    # changed or removed.
1199
    if self.op.vg_name is not None and not self.op.vg_name:
1200
      instances = self.cfg.GetAllInstancesInfo().values()
1201
      for inst in instances:
1202
        for disk in inst.disks:
1203
          if _RecursiveCheckIfLVMBased(disk):
1204
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1205
                                       " lvm-based instances exist")
1206

    
1207
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1208

    
1209
    # if vg_name not None, checks given volume group on all nodes
1210
    if self.op.vg_name:
1211
      vglist = self.rpc.call_vg_list(node_list)
1212
      for node in node_list:
1213
        vgstatus = utils.CheckVolumeGroupSize(vglist[node], self.op.vg_name,
1214
                                              constants.MIN_VG_SIZE)
1215
        if vgstatus:
1216
          raise errors.OpPrereqError("Error on node '%s': %s" %
1217
                                     (node, vgstatus))
1218

    
1219
    self.cluster = cluster = self.cfg.GetClusterInfo()
1220
    # beparams changes do not need validation (we can't validate?),
1221
    # but we still process here
1222
    if self.op.beparams:
1223
      self.new_beparams = cluster.FillDict(
1224
        cluster.beparams[constants.BEGR_DEFAULT], self.op.beparams)
1225

    
1226
    # hypervisor list/parameters
1227
    self.new_hvparams = cluster.FillDict(cluster.hvparams, {})
1228
    if self.op.hvparams:
1229
      if not isinstance(self.op.hvparams, dict):
1230
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input")
1231
      for hv_name, hv_dict in self.op.hvparams.items():
1232
        if hv_name not in self.new_hvparams:
1233
          self.new_hvparams[hv_name] = hv_dict
1234
        else:
1235
          self.new_hvparams[hv_name].update(hv_dict)
1236

    
1237
    if self.op.enabled_hypervisors is not None:
1238
      self.hv_list = self.op.enabled_hypervisors
1239
    else:
1240
      self.hv_list = cluster.enabled_hypervisors
1241

    
1242
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
1243
      # either the enabled list has changed, or the parameters have, validate
1244
      for hv_name, hv_params in self.new_hvparams.items():
1245
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
1246
            (self.op.enabled_hypervisors and
1247
             hv_name in self.op.enabled_hypervisors)):
1248
          # either this is a new hypervisor, or its parameters have changed
1249
          hv_class = hypervisor.GetHypervisor(hv_name)
1250
          hv_class.CheckParameterSyntax(hv_params)
1251
          _CheckHVParams(self, node_list, hv_name, hv_params)
1252

    
1253
  def Exec(self, feedback_fn):
1254
    """Change the parameters of the cluster.
1255

1256
    """
1257
    if self.op.vg_name is not None:
1258
      if self.op.vg_name != self.cfg.GetVGName():
1259
        self.cfg.SetVGName(self.op.vg_name)
1260
      else:
1261
        feedback_fn("Cluster LVM configuration already in desired"
1262
                    " state, not changing")
1263
    if self.op.hvparams:
1264
      self.cluster.hvparams = self.new_hvparams
1265
    if self.op.enabled_hypervisors is not None:
1266
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
1267
    if self.op.beparams:
1268
      self.cluster.beparams[constants.BEGR_DEFAULT] = self.new_beparams
1269
    self.cfg.Update(self.cluster)
1270

    
1271

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

1275
  """
1276
  if not instance.disks:
1277
    return True
1278

    
1279
  if not oneshot:
1280
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
1281

    
1282
  node = instance.primary_node
1283

    
1284
  for dev in instance.disks:
1285
    lu.cfg.SetDiskID(dev, node)
1286

    
1287
  retries = 0
1288
  while True:
1289
    max_time = 0
1290
    done = True
1291
    cumul_degraded = False
1292
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
1293
    if not rstats:
1294
      lu.LogWarning("Can't get any data from node %s", node)
1295
      retries += 1
1296
      if retries >= 10:
1297
        raise errors.RemoteError("Can't contact node %s for mirror data,"
1298
                                 " aborting." % node)
1299
      time.sleep(6)
1300
      continue
1301
    retries = 0
1302
    for i in range(len(rstats)):
1303
      mstat = rstats[i]
1304
      if mstat is None:
1305
        lu.LogWarning("Can't compute data for node %s/%s",
1306
                           node, instance.disks[i].iv_name)
1307
        continue
1308
      # we ignore the ldisk parameter
1309
      perc_done, est_time, is_degraded, _ = mstat
1310
      cumul_degraded = cumul_degraded or (is_degraded and perc_done is None)
1311
      if perc_done is not None:
1312
        done = False
1313
        if est_time is not None:
1314
          rem_time = "%d estimated seconds remaining" % est_time
1315
          max_time = est_time
1316
        else:
1317
          rem_time = "no time estimate"
1318
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
1319
                        (instance.disks[i].iv_name, perc_done, rem_time))
1320
    if done or oneshot:
1321
      break
1322

    
1323
    time.sleep(min(60, max_time))
1324

    
1325
  if done:
1326
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
1327
  return not cumul_degraded
1328

    
1329

    
1330
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
1331
  """Check that mirrors are not degraded.
1332

1333
  The ldisk parameter, if True, will change the test from the
1334
  is_degraded attribute (which represents overall non-ok status for
1335
  the device(s)) to the ldisk (representing the local storage status).
1336

1337
  """
1338
  lu.cfg.SetDiskID(dev, node)
1339
  if ldisk:
1340
    idx = 6
1341
  else:
1342
    idx = 5
1343

    
1344
  result = True
1345
  if on_primary or dev.AssembleOnSecondary():
1346
    rstats = lu.rpc.call_blockdev_find(node, dev)
1347
    if not rstats:
1348
      logging.warning("Node %s: disk degraded, not found or node down", node)
1349
      result = False
1350
    else:
1351
      result = result and (not rstats[idx])
1352
  if dev.children:
1353
    for child in dev.children:
1354
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
1355

    
1356
  return result
1357

    
1358

    
1359
class LUDiagnoseOS(NoHooksLU):
1360
  """Logical unit for OS diagnose/query.
1361

1362
  """
1363
  _OP_REQP = ["output_fields", "names"]
1364
  REQ_BGL = False
1365
  _FIELDS_STATIC = _FieldSet()
1366
  _FIELDS_DYNAMIC = _FieldSet("name", "valid", "node_status")
1367

    
1368
  def ExpandNames(self):
1369
    if self.op.names:
1370
      raise errors.OpPrereqError("Selective OS query not supported")
1371

    
1372
    _CheckOutputFields(static=self._FIELDS_STATIC,
1373
                       dynamic=self._FIELDS_DYNAMIC,
1374
                       selected=self.op.output_fields)
1375

    
1376
    # Lock all nodes, in shared mode
1377
    self.needed_locks = {}
1378
    self.share_locks[locking.LEVEL_NODE] = 1
1379
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1380

    
1381
  def CheckPrereq(self):
1382
    """Check prerequisites.
1383

1384
    """
1385

    
1386
  @staticmethod
1387
  def _DiagnoseByOS(node_list, rlist):
1388
    """Remaps a per-node return list into an a per-os per-node dictionary
1389

1390
      Args:
1391
        node_list: a list with the names of all nodes
1392
        rlist: a map with node names as keys and OS objects as values
1393

1394
      Returns:
1395
        map: a map with osnames as keys and as value another map, with
1396
             nodes as
1397
             keys and list of OS objects as values
1398
             e.g. {"debian-etch": {"node1": [<object>,...],
1399
                                   "node2": [<object>,]}
1400
                  }
1401

1402
    """
1403
    all_os = {}
1404
    for node_name, nr in rlist.iteritems():
1405
      if not nr:
1406
        continue
1407
      for os_obj in nr:
1408
        if os_obj.name not in all_os:
1409
          # build a list of nodes for this os containing empty lists
1410
          # for each node in node_list
1411
          all_os[os_obj.name] = {}
1412
          for nname in node_list:
1413
            all_os[os_obj.name][nname] = []
1414
        all_os[os_obj.name][node_name].append(os_obj)
1415
    return all_os
1416

    
1417
  def Exec(self, feedback_fn):
1418
    """Compute the list of OSes.
1419

1420
    """
1421
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1422
    node_data = self.rpc.call_os_diagnose(node_list)
1423
    if node_data == False:
1424
      raise errors.OpExecError("Can't gather the list of OSes")
1425
    pol = self._DiagnoseByOS(node_list, node_data)
1426
    output = []
1427
    for os_name, os_data in pol.iteritems():
1428
      row = []
1429
      for field in self.op.output_fields:
1430
        if field == "name":
1431
          val = os_name
1432
        elif field == "valid":
1433
          val = utils.all([osl and osl[0] for osl in os_data.values()])
1434
        elif field == "node_status":
1435
          val = {}
1436
          for node_name, nos_list in os_data.iteritems():
1437
            val[node_name] = [(v.status, v.path) for v in nos_list]
1438
        else:
1439
          raise errors.ParameterError(field)
1440
        row.append(val)
1441
      output.append(row)
1442

    
1443
    return output
1444

    
1445

    
1446
class LURemoveNode(LogicalUnit):
1447
  """Logical unit for removing a node.
1448

1449
  """
1450
  HPATH = "node-remove"
1451
  HTYPE = constants.HTYPE_NODE
1452
  _OP_REQP = ["node_name"]
1453

    
1454
  def BuildHooksEnv(self):
1455
    """Build hooks env.
1456

1457
    This doesn't run on the target node in the pre phase as a failed
1458
    node would then be impossible to remove.
1459

1460
    """
1461
    env = {
1462
      "OP_TARGET": self.op.node_name,
1463
      "NODE_NAME": self.op.node_name,
1464
      }
1465
    all_nodes = self.cfg.GetNodeList()
1466
    all_nodes.remove(self.op.node_name)
1467
    return env, all_nodes, all_nodes
1468

    
1469
  def CheckPrereq(self):
1470
    """Check prerequisites.
1471

1472
    This checks:
1473
     - the node exists in the configuration
1474
     - it does not have primary or secondary instances
1475
     - it's not the master
1476

1477
    Any errors are signalled by raising errors.OpPrereqError.
1478

1479
    """
1480
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
1481
    if node is None:
1482
      raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name)
1483

    
1484
    instance_list = self.cfg.GetInstanceList()
1485

    
1486
    masternode = self.cfg.GetMasterNode()
1487
    if node.name == masternode:
1488
      raise errors.OpPrereqError("Node is the master node,"
1489
                                 " you need to failover first.")
1490

    
1491
    for instance_name in instance_list:
1492
      instance = self.cfg.GetInstanceInfo(instance_name)
1493
      if node.name == instance.primary_node:
1494
        raise errors.OpPrereqError("Instance %s still running on the node,"
1495
                                   " please remove first." % instance_name)
1496
      if node.name in instance.secondary_nodes:
1497
        raise errors.OpPrereqError("Instance %s has node as a secondary,"
1498
                                   " please remove first." % instance_name)
1499
    self.op.node_name = node.name
1500
    self.node = node
1501

    
1502
  def Exec(self, feedback_fn):
1503
    """Removes the node from the cluster.
1504

1505
    """
1506
    node = self.node
1507
    logging.info("Stopping the node daemon and removing configs from node %s",
1508
                 node.name)
1509

    
1510
    self.context.RemoveNode(node.name)
1511

    
1512
    self.rpc.call_node_leave_cluster(node.name)
1513

    
1514

    
1515
class LUQueryNodes(NoHooksLU):
1516
  """Logical unit for querying nodes.
1517

1518
  """
1519
  _OP_REQP = ["output_fields", "names"]
1520
  REQ_BGL = False
1521
  _FIELDS_DYNAMIC = _FieldSet(
1522
    "dtotal", "dfree",
1523
    "mtotal", "mnode", "mfree",
1524
    "bootid",
1525
    "ctotal",
1526
    )
1527

    
1528
  _FIELDS_STATIC = _FieldSet(
1529
    "name", "pinst_cnt", "sinst_cnt",
1530
    "pinst_list", "sinst_list",
1531
    "pip", "sip", "tags",
1532
    "serial_no",
1533
    )
1534

    
1535
  def ExpandNames(self):
1536
    _CheckOutputFields(static=self._FIELDS_STATIC,
1537
                       dynamic=self._FIELDS_DYNAMIC,
1538
                       selected=self.op.output_fields)
1539

    
1540
    self.needed_locks = {}
1541
    self.share_locks[locking.LEVEL_NODE] = 1
1542

    
1543
    if self.op.names:
1544
      self.wanted = _GetWantedNodes(self, self.op.names)
1545
    else:
1546
      self.wanted = locking.ALL_SET
1547

    
1548
    self.do_locking = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
1549
    if self.do_locking:
1550
      # if we don't request only static fields, we need to lock the nodes
1551
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
1552

    
1553

    
1554
  def CheckPrereq(self):
1555
    """Check prerequisites.
1556

1557
    """
1558
    # The validation of the node list is done in the _GetWantedNodes,
1559
    # if non empty, and if empty, there's no validation to do
1560
    pass
1561

    
1562
  def Exec(self, feedback_fn):
1563
    """Computes the list of nodes and their attributes.
1564

1565
    """
1566
    all_info = self.cfg.GetAllNodesInfo()
1567
    if self.do_locking:
1568
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
1569
    elif self.wanted != locking.ALL_SET:
1570
      nodenames = self.wanted
1571
      missing = set(nodenames).difference(all_info.keys())
1572
      if missing:
1573
        raise errors.OpExecError(
1574
          "Some nodes were removed before retrieving their data: %s" % missing)
1575
    else:
1576
      nodenames = all_info.keys()
1577

    
1578
    nodenames = utils.NiceSort(nodenames)
1579
    nodelist = [all_info[name] for name in nodenames]
1580

    
1581
    # begin data gathering
1582

    
1583
    if self.do_locking:
1584
      live_data = {}
1585
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
1586
                                          self.cfg.GetHypervisorType())
1587
      for name in nodenames:
1588
        nodeinfo = node_data.get(name, None)
1589
        if nodeinfo:
1590
          live_data[name] = {
1591
            "mtotal": utils.TryConvert(int, nodeinfo['memory_total']),
1592
            "mnode": utils.TryConvert(int, nodeinfo['memory_dom0']),
1593
            "mfree": utils.TryConvert(int, nodeinfo['memory_free']),
1594
            "dtotal": utils.TryConvert(int, nodeinfo['vg_size']),
1595
            "dfree": utils.TryConvert(int, nodeinfo['vg_free']),
1596
            "ctotal": utils.TryConvert(int, nodeinfo['cpu_total']),
1597
            "bootid": nodeinfo['bootid'],
1598
            }
1599
        else:
1600
          live_data[name] = {}
1601
    else:
1602
      live_data = dict.fromkeys(nodenames, {})
1603

    
1604
    node_to_primary = dict([(name, set()) for name in nodenames])
1605
    node_to_secondary = dict([(name, set()) for name in nodenames])
1606

    
1607
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
1608
                             "sinst_cnt", "sinst_list"))
1609
    if inst_fields & frozenset(self.op.output_fields):
1610
      instancelist = self.cfg.GetInstanceList()
1611

    
1612
      for instance_name in instancelist:
1613
        inst = self.cfg.GetInstanceInfo(instance_name)
1614
        if inst.primary_node in node_to_primary:
1615
          node_to_primary[inst.primary_node].add(inst.name)
1616
        for secnode in inst.secondary_nodes:
1617
          if secnode in node_to_secondary:
1618
            node_to_secondary[secnode].add(inst.name)
1619

    
1620
    # end data gathering
1621

    
1622
    output = []
1623
    for node in nodelist:
1624
      node_output = []
1625
      for field in self.op.output_fields:
1626
        if field == "name":
1627
          val = node.name
1628
        elif field == "pinst_list":
1629
          val = list(node_to_primary[node.name])
1630
        elif field == "sinst_list":
1631
          val = list(node_to_secondary[node.name])
1632
        elif field == "pinst_cnt":
1633
          val = len(node_to_primary[node.name])
1634
        elif field == "sinst_cnt":
1635
          val = len(node_to_secondary[node.name])
1636
        elif field == "pip":
1637
          val = node.primary_ip
1638
        elif field == "sip":
1639
          val = node.secondary_ip
1640
        elif field == "tags":
1641
          val = list(node.GetTags())
1642
        elif field == "serial_no":
1643
          val = node.serial_no
1644
        elif self._FIELDS_DYNAMIC.Matches(field):
1645
          val = live_data[node.name].get(field, None)
1646
        else:
1647
          raise errors.ParameterError(field)
1648
        node_output.append(val)
1649
      output.append(node_output)
1650

    
1651
    return output
1652

    
1653

    
1654
class LUQueryNodeVolumes(NoHooksLU):
1655
  """Logical unit for getting volumes on node(s).
1656

1657
  """
1658
  _OP_REQP = ["nodes", "output_fields"]
1659
  REQ_BGL = False
1660
  _FIELDS_DYNAMIC = _FieldSet("phys", "vg", "name", "size", "instance")
1661
  _FIELDS_STATIC = _FieldSet("node")
1662

    
1663
  def ExpandNames(self):
1664
    _CheckOutputFields(static=self._FIELDS_STATIC,
1665
                       dynamic=self._FIELDS_DYNAMIC,
1666
                       selected=self.op.output_fields)
1667

    
1668
    self.needed_locks = {}
1669
    self.share_locks[locking.LEVEL_NODE] = 1
1670
    if not self.op.nodes:
1671
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1672
    else:
1673
      self.needed_locks[locking.LEVEL_NODE] = \
1674
        _GetWantedNodes(self, self.op.nodes)
1675

    
1676
  def CheckPrereq(self):
1677
    """Check prerequisites.
1678

1679
    This checks that the fields required are valid output fields.
1680

1681
    """
1682
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
1683

    
1684
  def Exec(self, feedback_fn):
1685
    """Computes the list of nodes and their attributes.
1686

1687
    """
1688
    nodenames = self.nodes
1689
    volumes = self.rpc.call_node_volumes(nodenames)
1690

    
1691
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
1692
             in self.cfg.GetInstanceList()]
1693

    
1694
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
1695

    
1696
    output = []
1697
    for node in nodenames:
1698
      if node not in volumes or not volumes[node]:
1699
        continue
1700

    
1701
      node_vols = volumes[node][:]
1702
      node_vols.sort(key=lambda vol: vol['dev'])
1703

    
1704
      for vol in node_vols:
1705
        node_output = []
1706
        for field in self.op.output_fields:
1707
          if field == "node":
1708
            val = node
1709
          elif field == "phys":
1710
            val = vol['dev']
1711
          elif field == "vg":
1712
            val = vol['vg']
1713
          elif field == "name":
1714
            val = vol['name']
1715
          elif field == "size":
1716
            val = int(float(vol['size']))
1717
          elif field == "instance":
1718
            for inst in ilist:
1719
              if node not in lv_by_node[inst]:
1720
                continue
1721
              if vol['name'] in lv_by_node[inst][node]:
1722
                val = inst.name
1723
                break
1724
            else:
1725
              val = '-'
1726
          else:
1727
            raise errors.ParameterError(field)
1728
          node_output.append(str(val))
1729

    
1730
        output.append(node_output)
1731

    
1732
    return output
1733

    
1734

    
1735
class LUAddNode(LogicalUnit):
1736
  """Logical unit for adding node to the cluster.
1737

1738
  """
1739
  HPATH = "node-add"
1740
  HTYPE = constants.HTYPE_NODE
1741
  _OP_REQP = ["node_name"]
1742

    
1743
  def BuildHooksEnv(self):
1744
    """Build hooks env.
1745

1746
    This will run on all nodes before, and on all nodes + the new node after.
1747

1748
    """
1749
    env = {
1750
      "OP_TARGET": self.op.node_name,
1751
      "NODE_NAME": self.op.node_name,
1752
      "NODE_PIP": self.op.primary_ip,
1753
      "NODE_SIP": self.op.secondary_ip,
1754
      }
1755
    nodes_0 = self.cfg.GetNodeList()
1756
    nodes_1 = nodes_0 + [self.op.node_name, ]
1757
    return env, nodes_0, nodes_1
1758

    
1759
  def CheckPrereq(self):
1760
    """Check prerequisites.
1761

1762
    This checks:
1763
     - the new node is not already in the config
1764
     - it is resolvable
1765
     - its parameters (single/dual homed) matches the cluster
1766

1767
    Any errors are signalled by raising errors.OpPrereqError.
1768

1769
    """
1770
    node_name = self.op.node_name
1771
    cfg = self.cfg
1772

    
1773
    dns_data = utils.HostInfo(node_name)
1774

    
1775
    node = dns_data.name
1776
    primary_ip = self.op.primary_ip = dns_data.ip
1777
    secondary_ip = getattr(self.op, "secondary_ip", None)
1778
    if secondary_ip is None:
1779
      secondary_ip = primary_ip
1780
    if not utils.IsValidIP(secondary_ip):
1781
      raise errors.OpPrereqError("Invalid secondary IP given")
1782
    self.op.secondary_ip = secondary_ip
1783

    
1784
    node_list = cfg.GetNodeList()
1785
    if not self.op.readd and node in node_list:
1786
      raise errors.OpPrereqError("Node %s is already in the configuration" %
1787
                                 node)
1788
    elif self.op.readd and node not in node_list:
1789
      raise errors.OpPrereqError("Node %s is not in the configuration" % node)
1790

    
1791
    for existing_node_name in node_list:
1792
      existing_node = cfg.GetNodeInfo(existing_node_name)
1793

    
1794
      if self.op.readd and node == existing_node_name:
1795
        if (existing_node.primary_ip != primary_ip or
1796
            existing_node.secondary_ip != secondary_ip):
1797
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
1798
                                     " address configuration as before")
1799
        continue
1800

    
1801
      if (existing_node.primary_ip == primary_ip or
1802
          existing_node.secondary_ip == primary_ip or
1803
          existing_node.primary_ip == secondary_ip or
1804
          existing_node.secondary_ip == secondary_ip):
1805
        raise errors.OpPrereqError("New node ip address(es) conflict with"
1806
                                   " existing node %s" % existing_node.name)
1807

    
1808
    # check that the type of the node (single versus dual homed) is the
1809
    # same as for the master
1810
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
1811
    master_singlehomed = myself.secondary_ip == myself.primary_ip
1812
    newbie_singlehomed = secondary_ip == primary_ip
1813
    if master_singlehomed != newbie_singlehomed:
1814
      if master_singlehomed:
1815
        raise errors.OpPrereqError("The master has no private ip but the"
1816
                                   " new node has one")
1817
      else:
1818
        raise errors.OpPrereqError("The master has a private ip but the"
1819
                                   " new node doesn't have one")
1820

    
1821
    # checks reachablity
1822
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
1823
      raise errors.OpPrereqError("Node not reachable by ping")
1824

    
1825
    if not newbie_singlehomed:
1826
      # check reachability from my secondary ip to newbie's secondary ip
1827
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
1828
                           source=myself.secondary_ip):
1829
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
1830
                                   " based ping to noded port")
1831

    
1832
    self.new_node = objects.Node(name=node,
1833
                                 primary_ip=primary_ip,
1834
                                 secondary_ip=secondary_ip)
1835

    
1836
  def Exec(self, feedback_fn):
1837
    """Adds the new node to the cluster.
1838

1839
    """
1840
    new_node = self.new_node
1841
    node = new_node.name
1842

    
1843
    # check connectivity
1844
    result = self.rpc.call_version([node])[node]
1845
    if result:
1846
      if constants.PROTOCOL_VERSION == result:
1847
        logging.info("Communication to node %s fine, sw version %s match",
1848
                     node, result)
1849
      else:
1850
        raise errors.OpExecError("Version mismatch master version %s,"
1851
                                 " node version %s" %
1852
                                 (constants.PROTOCOL_VERSION, result))
1853
    else:
1854
      raise errors.OpExecError("Cannot get version from the new node")
1855

    
1856
    # setup ssh on node
1857
    logging.info("Copy ssh key to node %s", node)
1858
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
1859
    keyarray = []
1860
    keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
1861
                constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
1862
                priv_key, pub_key]
1863

    
1864
    for i in keyfiles:
1865
      f = open(i, 'r')
1866
      try:
1867
        keyarray.append(f.read())
1868
      finally:
1869
        f.close()
1870

    
1871
    result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
1872
                                    keyarray[2],
1873
                                    keyarray[3], keyarray[4], keyarray[5])
1874

    
1875
    if not result:
1876
      raise errors.OpExecError("Cannot transfer ssh keys to the new node")
1877

    
1878
    # Add node to our /etc/hosts, and add key to known_hosts
1879
    utils.AddHostToEtcHosts(new_node.name)
1880

    
1881
    if new_node.secondary_ip != new_node.primary_ip:
1882
      if not self.rpc.call_node_has_ip_address(new_node.name,
1883
                                               new_node.secondary_ip):
1884
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
1885
                                 " you gave (%s). Please fix and re-run this"
1886
                                 " command." % new_node.secondary_ip)
1887

    
1888
    node_verify_list = [self.cfg.GetMasterNode()]
1889
    node_verify_param = {
1890
      'nodelist': [node],
1891
      # TODO: do a node-net-test as well?
1892
    }
1893

    
1894
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
1895
                                       self.cfg.GetClusterName())
1896
    for verifier in node_verify_list:
1897
      if not result[verifier]:
1898
        raise errors.OpExecError("Cannot communicate with %s's node daemon"
1899
                                 " for remote verification" % verifier)
1900
      if result[verifier]['nodelist']:
1901
        for failed in result[verifier]['nodelist']:
1902
          feedback_fn("ssh/hostname verification failed %s -> %s" %
1903
                      (verifier, result[verifier]['nodelist'][failed]))
1904
        raise errors.OpExecError("ssh/hostname verification failed.")
1905

    
1906
    # Distribute updated /etc/hosts and known_hosts to all nodes,
1907
    # including the node just added
1908
    myself = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
1909
    dist_nodes = self.cfg.GetNodeList()
1910
    if not self.op.readd:
1911
      dist_nodes.append(node)
1912
    if myself.name in dist_nodes:
1913
      dist_nodes.remove(myself.name)
1914

    
1915
    logging.debug("Copying hosts and known_hosts to all nodes")
1916
    for fname in (constants.ETC_HOSTS, constants.SSH_KNOWN_HOSTS_FILE):
1917
      result = self.rpc.call_upload_file(dist_nodes, fname)
1918
      for to_node in dist_nodes:
1919
        if not result[to_node]:
1920
          logging.error("Copy of file %s to node %s failed", fname, to_node)
1921

    
1922
    to_copy = []
1923
    if constants.HT_XEN_HVM in self.cfg.GetClusterInfo().enabled_hypervisors:
1924
      to_copy.append(constants.VNC_PASSWORD_FILE)
1925
    for fname in to_copy:
1926
      result = self.rpc.call_upload_file([node], fname)
1927
      if not result[node]:
1928
        logging.error("Could not copy file %s to node %s", fname, node)
1929

    
1930
    if self.op.readd:
1931
      self.context.ReaddNode(new_node)
1932
    else:
1933
      self.context.AddNode(new_node)
1934

    
1935

    
1936
class LUQueryClusterInfo(NoHooksLU):
1937
  """Query cluster configuration.
1938

1939
  """
1940
  _OP_REQP = []
1941
  REQ_MASTER = False
1942
  REQ_BGL = False
1943

    
1944
  def ExpandNames(self):
1945
    self.needed_locks = {}
1946

    
1947
  def CheckPrereq(self):
1948
    """No prerequsites needed for this LU.
1949

1950
    """
1951
    pass
1952

    
1953
  def Exec(self, feedback_fn):
1954
    """Return cluster config.
1955

1956
    """
1957
    cluster = self.cfg.GetClusterInfo()
1958
    result = {
1959
      "software_version": constants.RELEASE_VERSION,
1960
      "protocol_version": constants.PROTOCOL_VERSION,
1961
      "config_version": constants.CONFIG_VERSION,
1962
      "os_api_version": constants.OS_API_VERSION,
1963
      "export_version": constants.EXPORT_VERSION,
1964
      "architecture": (platform.architecture()[0], platform.machine()),
1965
      "name": cluster.cluster_name,
1966
      "master": cluster.master_node,
1967
      "default_hypervisor": cluster.default_hypervisor,
1968
      "enabled_hypervisors": cluster.enabled_hypervisors,
1969
      "hvparams": cluster.hvparams,
1970
      "beparams": cluster.beparams,
1971
      }
1972

    
1973
    return result
1974

    
1975

    
1976
class LUQueryConfigValues(NoHooksLU):
1977
  """Return configuration values.
1978

1979
  """
1980
  _OP_REQP = []
1981
  REQ_BGL = False
1982
  _FIELDS_DYNAMIC = _FieldSet()
1983
  _FIELDS_STATIC = _FieldSet("cluster_name", "master_node", "drain_flag")
1984

    
1985
  def ExpandNames(self):
1986
    self.needed_locks = {}
1987

    
1988
    _CheckOutputFields(static=self._FIELDS_STATIC,
1989
                       dynamic=self._FIELDS_DYNAMIC,
1990
                       selected=self.op.output_fields)
1991

    
1992
  def CheckPrereq(self):
1993
    """No prerequisites.
1994

1995
    """
1996
    pass
1997

    
1998
  def Exec(self, feedback_fn):
1999
    """Dump a representation of the cluster config to the standard output.
2000

2001
    """
2002
    values = []
2003
    for field in self.op.output_fields:
2004
      if field == "cluster_name":
2005
        entry = self.cfg.GetClusterName()
2006
      elif field == "master_node":
2007
        entry = self.cfg.GetMasterNode()
2008
      elif field == "drain_flag":
2009
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
2010
      else:
2011
        raise errors.ParameterError(field)
2012
      values.append(entry)
2013
    return values
2014

    
2015

    
2016
class LUActivateInstanceDisks(NoHooksLU):
2017
  """Bring up an instance's disks.
2018

2019
  """
2020
  _OP_REQP = ["instance_name"]
2021
  REQ_BGL = False
2022

    
2023
  def ExpandNames(self):
2024
    self._ExpandAndLockInstance()
2025
    self.needed_locks[locking.LEVEL_NODE] = []
2026
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2027

    
2028
  def DeclareLocks(self, level):
2029
    if level == locking.LEVEL_NODE:
2030
      self._LockInstancesNodes()
2031

    
2032
  def CheckPrereq(self):
2033
    """Check prerequisites.
2034

2035
    This checks that the instance is in the cluster.
2036

2037
    """
2038
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2039
    assert self.instance is not None, \
2040
      "Cannot retrieve locked instance %s" % self.op.instance_name
2041

    
2042
  def Exec(self, feedback_fn):
2043
    """Activate the disks.
2044

2045
    """
2046
    disks_ok, disks_info = _AssembleInstanceDisks(self, self.instance)
2047
    if not disks_ok:
2048
      raise errors.OpExecError("Cannot activate block devices")
2049

    
2050
    return disks_info
2051

    
2052

    
2053
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False):
2054
  """Prepare the block devices for an instance.
2055

2056
  This sets up the block devices on all nodes.
2057

2058
  Args:
2059
    instance: a ganeti.objects.Instance object
2060
    ignore_secondaries: if true, errors on secondary nodes won't result
2061
                        in an error return from the function
2062

2063
  Returns:
2064
    false if the operation failed
2065
    list of (host, instance_visible_name, node_visible_name) if the operation
2066
         suceeded with the mapping from node devices to instance devices
2067
  """
2068
  device_info = []
2069
  disks_ok = True
2070
  iname = instance.name
2071
  # With the two passes mechanism we try to reduce the window of
2072
  # opportunity for the race condition of switching DRBD to primary
2073
  # before handshaking occured, but we do not eliminate it
2074

    
2075
  # The proper fix would be to wait (with some limits) until the
2076
  # connection has been made and drbd transitions from WFConnection
2077
  # into any other network-connected state (Connected, SyncTarget,
2078
  # SyncSource, etc.)
2079

    
2080
  # 1st pass, assemble on all nodes in secondary mode
2081
  for inst_disk in instance.disks:
2082
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2083
      lu.cfg.SetDiskID(node_disk, node)
2084
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
2085
      if not result:
2086
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2087
                           " (is_primary=False, pass=1)",
2088
                           inst_disk.iv_name, node)
2089
        if not ignore_secondaries:
2090
          disks_ok = False
2091

    
2092
  # FIXME: race condition on drbd migration to primary
2093

    
2094
  # 2nd pass, do only the primary node
2095
  for inst_disk in instance.disks:
2096
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2097
      if node != instance.primary_node:
2098
        continue
2099
      lu.cfg.SetDiskID(node_disk, node)
2100
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
2101
      if not result:
2102
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2103
                           " (is_primary=True, pass=2)",
2104
                           inst_disk.iv_name, node)
2105
        disks_ok = False
2106
    device_info.append((instance.primary_node, inst_disk.iv_name, result))
2107

    
2108
  # leave the disks configured for the primary node
2109
  # this is a workaround that would be fixed better by
2110
  # improving the logical/physical id handling
2111
  for disk in instance.disks:
2112
    lu.cfg.SetDiskID(disk, instance.primary_node)
2113

    
2114
  return disks_ok, device_info
2115

    
2116

    
2117
def _StartInstanceDisks(lu, instance, force):
2118
  """Start the disks of an instance.
2119

2120
  """
2121
  disks_ok, dummy = _AssembleInstanceDisks(lu, instance,
2122
                                           ignore_secondaries=force)
2123
  if not disks_ok:
2124
    _ShutdownInstanceDisks(lu, instance)
2125
    if force is not None and not force:
2126
      lu.proc.LogWarning("", hint="If the message above refers to a"
2127
                         " secondary node,"
2128
                         " you can retry the operation using '--force'.")
2129
    raise errors.OpExecError("Disk consistency error")
2130

    
2131

    
2132
class LUDeactivateInstanceDisks(NoHooksLU):
2133
  """Shutdown an instance's disks.
2134

2135
  """
2136
  _OP_REQP = ["instance_name"]
2137
  REQ_BGL = False
2138

    
2139
  def ExpandNames(self):
2140
    self._ExpandAndLockInstance()
2141
    self.needed_locks[locking.LEVEL_NODE] = []
2142
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2143

    
2144
  def DeclareLocks(self, level):
2145
    if level == locking.LEVEL_NODE:
2146
      self._LockInstancesNodes()
2147

    
2148
  def CheckPrereq(self):
2149
    """Check prerequisites.
2150

2151
    This checks that the instance is in the cluster.
2152

2153
    """
2154
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2155
    assert self.instance is not None, \
2156
      "Cannot retrieve locked instance %s" % self.op.instance_name
2157

    
2158
  def Exec(self, feedback_fn):
2159
    """Deactivate the disks
2160

2161
    """
2162
    instance = self.instance
2163
    _SafeShutdownInstanceDisks(self, instance)
2164

    
2165

    
2166
def _SafeShutdownInstanceDisks(lu, instance):
2167
  """Shutdown block devices of an instance.
2168

2169
  This function checks if an instance is running, before calling
2170
  _ShutdownInstanceDisks.
2171

2172
  """
2173
  ins_l = lu.rpc.call_instance_list([instance.primary_node],
2174
                                      [instance.hypervisor])
2175
  ins_l = ins_l[instance.primary_node]
2176
  if not type(ins_l) is list:
2177
    raise errors.OpExecError("Can't contact node '%s'" %
2178
                             instance.primary_node)
2179

    
2180
  if instance.name in ins_l:
2181
    raise errors.OpExecError("Instance is running, can't shutdown"
2182
                             " block devices.")
2183

    
2184
  _ShutdownInstanceDisks(lu, instance)
2185

    
2186

    
2187
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
2188
  """Shutdown block devices of an instance.
2189

2190
  This does the shutdown on all nodes of the instance.
2191

2192
  If the ignore_primary is false, errors on the primary node are
2193
  ignored.
2194

2195
  """
2196
  result = True
2197
  for disk in instance.disks:
2198
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
2199
      lu.cfg.SetDiskID(top_disk, node)
2200
      if not lu.rpc.call_blockdev_shutdown(node, top_disk):
2201
        logging.error("Could not shutdown block device %s on node %s",
2202
                      disk.iv_name, node)
2203
        if not ignore_primary or node != instance.primary_node:
2204
          result = False
2205
  return result
2206

    
2207

    
2208
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor):
2209
  """Checks if a node has enough free memory.
2210

2211
  This function check if a given node has the needed amount of free
2212
  memory. In case the node has less memory or we cannot get the
2213
  information from the node, this function raise an OpPrereqError
2214
  exception.
2215

2216
  @type lu: C{LogicalUnit}
2217
  @param lu: a logical unit from which we get configuration data
2218
  @type node: C{str}
2219
  @param node: the node to check
2220
  @type reason: C{str}
2221
  @param reason: string to use in the error message
2222
  @type requested: C{int}
2223
  @param requested: the amount of memory in MiB to check for
2224
  @type hypervisor: C{str}
2225
  @param hypervisor: the hypervisor to ask for memory stats
2226
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
2227
      we cannot check the node
2228

2229
  """
2230
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor)
2231
  if not nodeinfo or not isinstance(nodeinfo, dict):
2232
    raise errors.OpPrereqError("Could not contact node %s for resource"
2233
                             " information" % (node,))
2234

    
2235
  free_mem = nodeinfo[node].get('memory_free')
2236
  if not isinstance(free_mem, int):
2237
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
2238
                             " was '%s'" % (node, free_mem))
2239
  if requested > free_mem:
2240
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
2241
                             " needed %s MiB, available %s MiB" %
2242
                             (node, reason, requested, free_mem))
2243

    
2244

    
2245
class LUStartupInstance(LogicalUnit):
2246
  """Starts an instance.
2247

2248
  """
2249
  HPATH = "instance-start"
2250
  HTYPE = constants.HTYPE_INSTANCE
2251
  _OP_REQP = ["instance_name", "force"]
2252
  REQ_BGL = False
2253

    
2254
  def ExpandNames(self):
2255
    self._ExpandAndLockInstance()
2256
    self.needed_locks[locking.LEVEL_NODE] = []
2257
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2258

    
2259
  def DeclareLocks(self, level):
2260
    if level == locking.LEVEL_NODE:
2261
      self._LockInstancesNodes()
2262

    
2263
  def BuildHooksEnv(self):
2264
    """Build hooks env.
2265

2266
    This runs on master, primary and secondary nodes of the instance.
2267

2268
    """
2269
    env = {
2270
      "FORCE": self.op.force,
2271
      }
2272
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2273
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2274
          list(self.instance.secondary_nodes))
2275
    return env, nl, nl
2276

    
2277
  def CheckPrereq(self):
2278
    """Check prerequisites.
2279

2280
    This checks that the instance is in the cluster.
2281

2282
    """
2283
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2284
    assert self.instance is not None, \
2285
      "Cannot retrieve locked instance %s" % self.op.instance_name
2286

    
2287
    bep = self.cfg.GetClusterInfo().FillBE(instance)
2288
    # check bridges existance
2289
    _CheckInstanceBridgesExist(self, instance)
2290

    
2291
    _CheckNodeFreeMemory(self, instance.primary_node,
2292
                         "starting instance %s" % instance.name,
2293
                         bep[constants.BE_MEMORY], instance.hypervisor)
2294

    
2295
  def Exec(self, feedback_fn):
2296
    """Start the instance.
2297

2298
    """
2299
    instance = self.instance
2300
    force = self.op.force
2301
    extra_args = getattr(self.op, "extra_args", "")
2302

    
2303
    self.cfg.MarkInstanceUp(instance.name)
2304

    
2305
    node_current = instance.primary_node
2306

    
2307
    _StartInstanceDisks(self, instance, force)
2308

    
2309
    if not self.rpc.call_instance_start(node_current, instance, extra_args):
2310
      _ShutdownInstanceDisks(self, instance)
2311
      raise errors.OpExecError("Could not start instance")
2312

    
2313

    
2314
class LURebootInstance(LogicalUnit):
2315
  """Reboot an instance.
2316

2317
  """
2318
  HPATH = "instance-reboot"
2319
  HTYPE = constants.HTYPE_INSTANCE
2320
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
2321
  REQ_BGL = False
2322

    
2323
  def ExpandNames(self):
2324
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
2325
                                   constants.INSTANCE_REBOOT_HARD,
2326
                                   constants.INSTANCE_REBOOT_FULL]:
2327
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
2328
                                  (constants.INSTANCE_REBOOT_SOFT,
2329
                                   constants.INSTANCE_REBOOT_HARD,
2330
                                   constants.INSTANCE_REBOOT_FULL))
2331
    self._ExpandAndLockInstance()
2332
    self.needed_locks[locking.LEVEL_NODE] = []
2333
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2334

    
2335
  def DeclareLocks(self, level):
2336
    if level == locking.LEVEL_NODE:
2337
      primary_only = not constants.INSTANCE_REBOOT_FULL
2338
      self._LockInstancesNodes(primary_only=primary_only)
2339

    
2340
  def BuildHooksEnv(self):
2341
    """Build hooks env.
2342

2343
    This runs on master, primary and secondary nodes of the instance.
2344

2345
    """
2346
    env = {
2347
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
2348
      }
2349
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2350
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2351
          list(self.instance.secondary_nodes))
2352
    return env, nl, nl
2353

    
2354
  def CheckPrereq(self):
2355
    """Check prerequisites.
2356

2357
    This checks that the instance is in the cluster.
2358

2359
    """
2360
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2361
    assert self.instance is not None, \
2362
      "Cannot retrieve locked instance %s" % self.op.instance_name
2363

    
2364
    # check bridges existance
2365
    _CheckInstanceBridgesExist(self, instance)
2366

    
2367
  def Exec(self, feedback_fn):
2368
    """Reboot the instance.
2369

2370
    """
2371
    instance = self.instance
2372
    ignore_secondaries = self.op.ignore_secondaries
2373
    reboot_type = self.op.reboot_type
2374
    extra_args = getattr(self.op, "extra_args", "")
2375

    
2376
    node_current = instance.primary_node
2377

    
2378
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
2379
                       constants.INSTANCE_REBOOT_HARD]:
2380
      if not self.rpc.call_instance_reboot(node_current, instance,
2381
                                           reboot_type, extra_args):
2382
        raise errors.OpExecError("Could not reboot instance")
2383
    else:
2384
      if not self.rpc.call_instance_shutdown(node_current, instance):
2385
        raise errors.OpExecError("could not shutdown instance for full reboot")
2386
      _ShutdownInstanceDisks(self, instance)
2387
      _StartInstanceDisks(self, instance, ignore_secondaries)
2388
      if not self.rpc.call_instance_start(node_current, instance, extra_args):
2389
        _ShutdownInstanceDisks(self, instance)
2390
        raise errors.OpExecError("Could not start instance for full reboot")
2391

    
2392
    self.cfg.MarkInstanceUp(instance.name)
2393

    
2394

    
2395
class LUShutdownInstance(LogicalUnit):
2396
  """Shutdown an instance.
2397

2398
  """
2399
  HPATH = "instance-stop"
2400
  HTYPE = constants.HTYPE_INSTANCE
2401
  _OP_REQP = ["instance_name"]
2402
  REQ_BGL = False
2403

    
2404
  def ExpandNames(self):
2405
    self._ExpandAndLockInstance()
2406
    self.needed_locks[locking.LEVEL_NODE] = []
2407
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2408

    
2409
  def DeclareLocks(self, level):
2410
    if level == locking.LEVEL_NODE:
2411
      self._LockInstancesNodes()
2412

    
2413
  def BuildHooksEnv(self):
2414
    """Build hooks env.
2415

2416
    This runs on master, primary and secondary nodes of the instance.
2417

2418
    """
2419
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2420
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2421
          list(self.instance.secondary_nodes))
2422
    return env, nl, nl
2423

    
2424
  def CheckPrereq(self):
2425
    """Check prerequisites.
2426

2427
    This checks that the instance is in the cluster.
2428

2429
    """
2430
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2431
    assert self.instance is not None, \
2432
      "Cannot retrieve locked instance %s" % self.op.instance_name
2433

    
2434
  def Exec(self, feedback_fn):
2435
    """Shutdown the instance.
2436

2437
    """
2438
    instance = self.instance
2439
    node_current = instance.primary_node
2440
    self.cfg.MarkInstanceDown(instance.name)
2441
    if not self.rpc.call_instance_shutdown(node_current, instance):
2442
      self.proc.LogWarning("Could not shutdown instance")
2443

    
2444
    _ShutdownInstanceDisks(self, instance)
2445

    
2446

    
2447
class LUReinstallInstance(LogicalUnit):
2448
  """Reinstall an instance.
2449

2450
  """
2451
  HPATH = "instance-reinstall"
2452
  HTYPE = constants.HTYPE_INSTANCE
2453
  _OP_REQP = ["instance_name"]
2454
  REQ_BGL = False
2455

    
2456
  def ExpandNames(self):
2457
    self._ExpandAndLockInstance()
2458
    self.needed_locks[locking.LEVEL_NODE] = []
2459
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2460

    
2461
  def DeclareLocks(self, level):
2462
    if level == locking.LEVEL_NODE:
2463
      self._LockInstancesNodes()
2464

    
2465
  def BuildHooksEnv(self):
2466
    """Build hooks env.
2467

2468
    This runs on master, primary and secondary nodes of the instance.
2469

2470
    """
2471
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2472
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2473
          list(self.instance.secondary_nodes))
2474
    return env, nl, nl
2475

    
2476
  def CheckPrereq(self):
2477
    """Check prerequisites.
2478

2479
    This checks that the instance is in the cluster and is not running.
2480

2481
    """
2482
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2483
    assert instance is not None, \
2484
      "Cannot retrieve locked instance %s" % self.op.instance_name
2485

    
2486
    if instance.disk_template == constants.DT_DISKLESS:
2487
      raise errors.OpPrereqError("Instance '%s' has no disks" %
2488
                                 self.op.instance_name)
2489
    if instance.status != "down":
2490
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2491
                                 self.op.instance_name)
2492
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2493
                                              instance.name,
2494
                                              instance.hypervisor)
2495
    if remote_info:
2496
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2497
                                 (self.op.instance_name,
2498
                                  instance.primary_node))
2499

    
2500
    self.op.os_type = getattr(self.op, "os_type", None)
2501
    if self.op.os_type is not None:
2502
      # OS verification
2503
      pnode = self.cfg.GetNodeInfo(
2504
        self.cfg.ExpandNodeName(instance.primary_node))
2505
      if pnode is None:
2506
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
2507
                                   self.op.pnode)
2508
      os_obj = self.rpc.call_os_get(pnode.name, self.op.os_type)
2509
      if not os_obj:
2510
        raise errors.OpPrereqError("OS '%s' not in supported OS list for"
2511
                                   " primary node"  % self.op.os_type)
2512

    
2513
    self.instance = instance
2514

    
2515
  def Exec(self, feedback_fn):
2516
    """Reinstall the instance.
2517

2518
    """
2519
    inst = self.instance
2520

    
2521
    if self.op.os_type is not None:
2522
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
2523
      inst.os = self.op.os_type
2524
      self.cfg.Update(inst)
2525

    
2526
    _StartInstanceDisks(self, inst, None)
2527
    try:
2528
      feedback_fn("Running the instance OS create scripts...")
2529
      if not self.rpc.call_instance_os_add(inst.primary_node, inst):
2530
        raise errors.OpExecError("Could not install OS for instance %s"
2531
                                 " on node %s" %
2532
                                 (inst.name, inst.primary_node))
2533
    finally:
2534
      _ShutdownInstanceDisks(self, inst)
2535

    
2536

    
2537
class LURenameInstance(LogicalUnit):
2538
  """Rename an instance.
2539

2540
  """
2541
  HPATH = "instance-rename"
2542
  HTYPE = constants.HTYPE_INSTANCE
2543
  _OP_REQP = ["instance_name", "new_name"]
2544

    
2545
  def BuildHooksEnv(self):
2546
    """Build hooks env.
2547

2548
    This runs on master, primary and secondary nodes of the instance.
2549

2550
    """
2551
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2552
    env["INSTANCE_NEW_NAME"] = self.op.new_name
2553
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2554
          list(self.instance.secondary_nodes))
2555
    return env, nl, nl
2556

    
2557
  def CheckPrereq(self):
2558
    """Check prerequisites.
2559

2560
    This checks that the instance is in the cluster and is not running.
2561

2562
    """
2563
    instance = self.cfg.GetInstanceInfo(
2564
      self.cfg.ExpandInstanceName(self.op.instance_name))
2565
    if instance is None:
2566
      raise errors.OpPrereqError("Instance '%s' not known" %
2567
                                 self.op.instance_name)
2568
    if instance.status != "down":
2569
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2570
                                 self.op.instance_name)
2571
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2572
                                              instance.name,
2573
                                              instance.hypervisor)
2574
    if remote_info:
2575
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2576
                                 (self.op.instance_name,
2577
                                  instance.primary_node))
2578
    self.instance = instance
2579

    
2580
    # new name verification
2581
    name_info = utils.HostInfo(self.op.new_name)
2582

    
2583
    self.op.new_name = new_name = name_info.name
2584
    instance_list = self.cfg.GetInstanceList()
2585
    if new_name in instance_list:
2586
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
2587
                                 new_name)
2588

    
2589
    if not getattr(self.op, "ignore_ip", False):
2590
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
2591
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
2592
                                   (name_info.ip, new_name))
2593

    
2594

    
2595
  def Exec(self, feedback_fn):
2596
    """Reinstall the instance.
2597

2598
    """
2599
    inst = self.instance
2600
    old_name = inst.name
2601

    
2602
    if inst.disk_template == constants.DT_FILE:
2603
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2604

    
2605
    self.cfg.RenameInstance(inst.name, self.op.new_name)
2606
    # Change the instance lock. This is definitely safe while we hold the BGL
2607
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
2608
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
2609

    
2610
    # re-read the instance from the configuration after rename
2611
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
2612

    
2613
    if inst.disk_template == constants.DT_FILE:
2614
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2615
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
2616
                                                     old_file_storage_dir,
2617
                                                     new_file_storage_dir)
2618

    
2619
      if not result:
2620
        raise errors.OpExecError("Could not connect to node '%s' to rename"
2621
                                 " directory '%s' to '%s' (but the instance"
2622
                                 " has been renamed in Ganeti)" % (
2623
                                 inst.primary_node, old_file_storage_dir,
2624
                                 new_file_storage_dir))
2625

    
2626
      if not result[0]:
2627
        raise errors.OpExecError("Could not rename directory '%s' to '%s'"
2628
                                 " (but the instance has been renamed in"
2629
                                 " Ganeti)" % (old_file_storage_dir,
2630
                                               new_file_storage_dir))
2631

    
2632
    _StartInstanceDisks(self, inst, None)
2633
    try:
2634
      if not self.rpc.call_instance_run_rename(inst.primary_node, inst,
2635
                                               old_name):
2636
        msg = ("Could not run OS rename script for instance %s on node %s"
2637
               " (but the instance has been renamed in Ganeti)" %
2638
               (inst.name, inst.primary_node))
2639
        self.proc.LogWarning(msg)
2640
    finally:
2641
      _ShutdownInstanceDisks(self, inst)
2642

    
2643

    
2644
class LURemoveInstance(LogicalUnit):
2645
  """Remove an instance.
2646

2647
  """
2648
  HPATH = "instance-remove"
2649
  HTYPE = constants.HTYPE_INSTANCE
2650
  _OP_REQP = ["instance_name", "ignore_failures"]
2651
  REQ_BGL = False
2652

    
2653
  def ExpandNames(self):
2654
    self._ExpandAndLockInstance()
2655
    self.needed_locks[locking.LEVEL_NODE] = []
2656
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2657

    
2658
  def DeclareLocks(self, level):
2659
    if level == locking.LEVEL_NODE:
2660
      self._LockInstancesNodes()
2661

    
2662
  def BuildHooksEnv(self):
2663
    """Build hooks env.
2664

2665
    This runs on master, primary and secondary nodes of the instance.
2666

2667
    """
2668
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2669
    nl = [self.cfg.GetMasterNode()]
2670
    return env, nl, nl
2671

    
2672
  def CheckPrereq(self):
2673
    """Check prerequisites.
2674

2675
    This checks that the instance is in the cluster.
2676

2677
    """
2678
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2679
    assert self.instance is not None, \
2680
      "Cannot retrieve locked instance %s" % self.op.instance_name
2681

    
2682
  def Exec(self, feedback_fn):
2683
    """Remove the instance.
2684

2685
    """
2686
    instance = self.instance
2687
    logging.info("Shutting down instance %s on node %s",
2688
                 instance.name, instance.primary_node)
2689

    
2690
    if not self.rpc.call_instance_shutdown(instance.primary_node, instance):
2691
      if self.op.ignore_failures:
2692
        feedback_fn("Warning: can't shutdown instance")
2693
      else:
2694
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
2695
                                 (instance.name, instance.primary_node))
2696

    
2697
    logging.info("Removing block devices for instance %s", instance.name)
2698

    
2699
    if not _RemoveDisks(self, instance):
2700
      if self.op.ignore_failures:
2701
        feedback_fn("Warning: can't remove instance's disks")
2702
      else:
2703
        raise errors.OpExecError("Can't remove instance's disks")
2704

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

    
2707
    self.cfg.RemoveInstance(instance.name)
2708
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
2709

    
2710

    
2711
class LUQueryInstances(NoHooksLU):
2712
  """Logical unit for querying instances.
2713

2714
  """
2715
  _OP_REQP = ["output_fields", "names"]
2716
  REQ_BGL = False
2717
  _FIELDS_STATIC = _FieldSet(*["name", "os", "pnode", "snodes",
2718
                               "admin_state", "admin_ram",
2719
                               "disk_template", "ip", "mac", "bridge",
2720
                               "sda_size", "sdb_size", "vcpus", "tags",
2721
                               "network_port", "beparams",
2722
                               "(disk).(size)/([0-9]+)",
2723
                               "(disk).(sizes)",
2724
                               "(nic).(mac|ip|bridge)/([0-9]+)",
2725
                               "(nic).(macs|ips|bridges)",
2726
                               "(disk|nic).(count)",
2727
                               "serial_no", "hypervisor", "hvparams",] +
2728
                             ["hv/%s" % name
2729
                              for name in constants.HVS_PARAMETERS] +
2730
                             ["be/%s" % name
2731
                              for name in constants.BES_PARAMETERS])
2732
  _FIELDS_DYNAMIC = _FieldSet("oper_state", "oper_ram", "status")
2733

    
2734

    
2735
  def ExpandNames(self):
2736
    _CheckOutputFields(static=self._FIELDS_STATIC,
2737
                       dynamic=self._FIELDS_DYNAMIC,
2738
                       selected=self.op.output_fields)
2739

    
2740
    self.needed_locks = {}
2741
    self.share_locks[locking.LEVEL_INSTANCE] = 1
2742
    self.share_locks[locking.LEVEL_NODE] = 1
2743

    
2744
    if self.op.names:
2745
      self.wanted = _GetWantedInstances(self, self.op.names)
2746
    else:
2747
      self.wanted = locking.ALL_SET
2748

    
2749
    self.do_locking = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
2750
    if self.do_locking:
2751
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
2752
      self.needed_locks[locking.LEVEL_NODE] = []
2753
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2754

    
2755
  def DeclareLocks(self, level):
2756
    if level == locking.LEVEL_NODE and self.do_locking:
2757
      self._LockInstancesNodes()
2758

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

2762
    """
2763
    pass
2764

    
2765
  def Exec(self, feedback_fn):
2766
    """Computes the list of nodes and their attributes.
2767

2768
    """
2769
    all_info = self.cfg.GetAllInstancesInfo()
2770
    if self.do_locking:
2771
      instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2772
    elif self.wanted != locking.ALL_SET:
2773
      instance_names = self.wanted
2774
      missing = set(instance_names).difference(all_info.keys())
2775
      if missing:
2776
        raise errors.OpExecError(
2777
          "Some instances were removed before retrieving their data: %s"
2778
          % missing)
2779
    else:
2780
      instance_names = all_info.keys()
2781

    
2782
    instance_names = utils.NiceSort(instance_names)
2783
    instance_list = [all_info[iname] for iname in instance_names]
2784

    
2785
    # begin data gathering
2786

    
2787
    nodes = frozenset([inst.primary_node for inst in instance_list])
2788
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
2789

    
2790
    bad_nodes = []
2791
    if self.do_locking:
2792
      live_data = {}
2793
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
2794
      for name in nodes:
2795
        result = node_data[name]
2796
        if result:
2797
          live_data.update(result)
2798
        elif result == False:
2799
          bad_nodes.append(name)
2800
        # else no instance is alive
2801
    else:
2802
      live_data = dict([(name, {}) for name in instance_names])
2803

    
2804
    # end data gathering
2805

    
2806
    HVPREFIX = "hv/"
2807
    BEPREFIX = "be/"
2808
    output = []
2809
    for instance in instance_list:
2810
      iout = []
2811
      i_hv = self.cfg.GetClusterInfo().FillHV(instance)
2812
      i_be = self.cfg.GetClusterInfo().FillBE(instance)
2813
      for field in self.op.output_fields:
2814
        st_match = self._FIELDS_STATIC.Matches(field)
2815
        if field == "name":
2816
          val = instance.name
2817
        elif field == "os":
2818
          val = instance.os
2819
        elif field == "pnode":
2820
          val = instance.primary_node
2821
        elif field == "snodes":
2822
          val = list(instance.secondary_nodes)
2823
        elif field == "admin_state":
2824
          val = (instance.status != "down")
2825
        elif field == "oper_state":
2826
          if instance.primary_node in bad_nodes:
2827
            val = None
2828
          else:
2829
            val = bool(live_data.get(instance.name))
2830
        elif field == "status":
2831
          if instance.primary_node in bad_nodes:
2832
            val = "ERROR_nodedown"
2833
          else:
2834
            running = bool(live_data.get(instance.name))
2835
            if running:
2836
              if instance.status != "down":
2837
                val = "running"
2838
              else:
2839
                val = "ERROR_up"
2840
            else:
2841
              if instance.status != "down":
2842
                val = "ERROR_down"
2843
              else:
2844
                val = "ADMIN_down"
2845
        elif field == "oper_ram":
2846
          if instance.primary_node in bad_nodes:
2847
            val = None
2848
          elif instance.name in live_data:
2849
            val = live_data[instance.name].get("memory", "?")
2850
          else:
2851
            val = "-"
2852
        elif field == "disk_template":
2853
          val = instance.disk_template
2854
        elif field == "ip":
2855
          val = instance.nics[0].ip
2856
        elif field == "bridge":
2857
          val = instance.nics[0].bridge
2858
        elif field == "mac":
2859
          val = instance.nics[0].mac
2860
        elif field == "sda_size" or field == "sdb_size":
2861
          idx = ord(field[2]) - ord('a')
2862
          try:
2863
            val = instance.FindDisk(idx).size
2864
          except errors.OpPrereqError:
2865
            val = None
2866
        elif field == "tags":
2867
          val = list(instance.GetTags())
2868
        elif field == "serial_no":
2869
          val = instance.serial_no
2870
        elif field == "network_port":
2871
          val = instance.network_port
2872
        elif field == "hypervisor":
2873
          val = instance.hypervisor
2874
        elif field == "hvparams":
2875
          val = i_hv
2876
        elif (field.startswith(HVPREFIX) and
2877
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS):
2878
          val = i_hv.get(field[len(HVPREFIX):], None)
2879
        elif field == "beparams":
2880
          val = i_be
2881
        elif (field.startswith(BEPREFIX) and
2882
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
2883
          val = i_be.get(field[len(BEPREFIX):], None)
2884
        elif st_match and st_match.groups():
2885
          # matches a variable list
2886
          st_groups = st_match.groups()
2887
          if st_groups and st_groups[0] == "disk":
2888
            if st_groups[1] == "count":
2889
              val = len(instance.disks)
2890
            elif st_groups[1] == "sizes":
2891
              val = [disk.size for disk in instance.disks]
2892
            elif st_groups[1] == "size":
2893
              try:
2894
                val = instance.FindDisk(st_groups[2]).size
2895
              except errors.OpPrereqError:
2896
                val = None
2897
            else:
2898
              assert False, "Unhandled disk parameter"
2899
          elif st_groups[0] == "nic":
2900
            if st_groups[1] == "count":
2901
              val = len(instance.nics)
2902
            elif st_groups[1] == "macs":
2903
              val = [nic.mac for nic in instance.nics]
2904
            elif st_groups[1] == "ips":
2905
              val = [nic.ip for nic in instance.nics]
2906
            elif st_groups[1] == "bridges":
2907
              val = [nic.bridge for nic in instance.nics]
2908
            else:
2909
              # index-based item
2910
              nic_idx = int(st_groups[2])
2911
              if nic_idx >= len(instance.nics):
2912
                val = None
2913
              else:
2914
                if st_groups[1] == "mac":
2915
                  val = instance.nics[nic_idx].mac
2916
                elif st_groups[1] == "ip":
2917
                  val = instance.nics[nic_idx].ip
2918
                elif st_groups[1] == "bridge":
2919
                  val = instance.nics[nic_idx].bridge
2920
                else:
2921
                  assert False, "Unhandled NIC parameter"
2922
          else:
2923
            assert False, "Unhandled variable parameter"
2924
        else:
2925
          raise errors.ParameterError(field)
2926
        iout.append(val)
2927
      output.append(iout)
2928

    
2929
    return output
2930

    
2931

    
2932
class LUFailoverInstance(LogicalUnit):
2933
  """Failover an instance.
2934

2935
  """
2936
  HPATH = "instance-failover"
2937
  HTYPE = constants.HTYPE_INSTANCE
2938
  _OP_REQP = ["instance_name", "ignore_consistency"]
2939
  REQ_BGL = False
2940

    
2941
  def ExpandNames(self):
2942
    self._ExpandAndLockInstance()
2943
    self.needed_locks[locking.LEVEL_NODE] = []
2944
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2945

    
2946
  def DeclareLocks(self, level):
2947
    if level == locking.LEVEL_NODE:
2948
      self._LockInstancesNodes()
2949

    
2950
  def BuildHooksEnv(self):
2951
    """Build hooks env.
2952

2953
    This runs on master, primary and secondary nodes of the instance.
2954

2955
    """
2956
    env = {
2957
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
2958
      }
2959
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2960
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
2961
    return env, nl, nl
2962

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

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

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

    
2973
    bep = self.cfg.GetClusterInfo().FillBE(instance)
2974
    if instance.disk_template not in constants.DTS_NET_MIRROR:
2975
      raise errors.OpPrereqError("Instance's disk layout is not"
2976
                                 " network mirrored, cannot failover.")
2977

    
2978
    secondary_nodes = instance.secondary_nodes
2979
    if not secondary_nodes:
2980
      raise errors.ProgrammerError("no secondary node but using "
2981
                                   "a mirrored disk template")
2982

    
2983
    target_node = secondary_nodes[0]
2984
    # check memory requirements on the secondary node
2985
    _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
2986
                         instance.name, bep[constants.BE_MEMORY],
2987
                         instance.hypervisor)
2988

    
2989
    # check bridge existance
2990
    brlist = [nic.bridge for nic in instance.nics]
2991
    if not self.rpc.call_bridges_exist(target_node, brlist):
2992
      raise errors.OpPrereqError("One or more target bridges %s does not"
2993
                                 " exist on destination node '%s'" %
2994
                                 (brlist, target_node))
2995

    
2996
  def Exec(self, feedback_fn):
2997
    """Failover an instance.
2998

2999
    The failover is done by shutting it down on its present node and
3000
    starting it on the secondary.
3001

3002
    """
3003
    instance = self.instance
3004

    
3005
    source_node = instance.primary_node
3006
    target_node = instance.secondary_nodes[0]
3007

    
3008
    feedback_fn("* checking disk consistency between source and target")
3009
    for dev in instance.disks:
3010
      # for drbd, these are drbd over lvm
3011
      if not _CheckDiskConsistency(self, dev, target_node, False):
3012
        if instance.status == "up" and not self.op.ignore_consistency:
3013
          raise errors.OpExecError("Disk %s is degraded on target node,"
3014
                                   " aborting failover." % dev.iv_name)
3015

    
3016
    feedback_fn("* shutting down instance on source node")
3017
    logging.info("Shutting down instance %s on node %s",
3018
                 instance.name, source_node)
3019

    
3020
    if not self.rpc.call_instance_shutdown(source_node, instance):
3021
      if self.op.ignore_consistency:
3022
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
3023
                             " Proceeding"
3024
                             " anyway. Please make sure node %s is down",
3025
                             instance.name, source_node, source_node)
3026
      else:
3027
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
3028
                                 (instance.name, source_node))
3029

    
3030
    feedback_fn("* deactivating the instance's disks on source node")
3031
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
3032
      raise errors.OpExecError("Can't shut down the instance's disks.")
3033

    
3034
    instance.primary_node = target_node
3035
    # distribute new instance config to the other nodes
3036
    self.cfg.Update(instance)
3037

    
3038
    # Only start the instance if it's marked as up
3039
    if instance.status == "up":
3040
      feedback_fn("* activating the instance's disks on target node")
3041
      logging.info("Starting instance %s on node %s",
3042
                   instance.name, target_node)
3043

    
3044
      disks_ok, dummy = _AssembleInstanceDisks(self, instance,
3045
                                               ignore_secondaries=True)
3046
      if not disks_ok:
3047
        _ShutdownInstanceDisks(self, instance)
3048
        raise errors.OpExecError("Can't activate the instance's disks")
3049

    
3050
      feedback_fn("* starting the instance on the target node")
3051
      if not self.rpc.call_instance_start(target_node, instance, None):
3052
        _ShutdownInstanceDisks(self, instance)
3053
        raise errors.OpExecError("Could not start instance %s on node %s." %
3054
                                 (instance.name, target_node))
3055

    
3056

    
3057
def _CreateBlockDevOnPrimary(lu, node, instance, device, info):
3058
  """Create a tree of block devices on the primary node.
3059

3060
  This always creates all devices.
3061

3062
  """
3063
  if device.children:
3064
    for child in device.children:
3065
      if not _CreateBlockDevOnPrimary(lu, node, instance, child, info):
3066
        return False
3067

    
3068
  lu.cfg.SetDiskID(device, node)
3069
  new_id = lu.rpc.call_blockdev_create(node, device, device.size,
3070
                                       instance.name, True, info)
3071
  if not new_id:
3072
    return False
3073
  if device.physical_id is None:
3074
    device.physical_id = new_id
3075
  return True
3076

    
3077

    
3078
def _CreateBlockDevOnSecondary(lu, node, instance, device, force, info):
3079
  """Create a tree of block devices on a secondary node.
3080

3081
  If this device type has to be created on secondaries, create it and
3082
  all its children.
3083

3084
  If not, just recurse to children keeping the same 'force' value.
3085

3086
  """
3087
  if device.CreateOnSecondary():
3088
    force = True
3089
  if device.children:
3090
    for child in device.children:
3091
      if not _CreateBlockDevOnSecondary(lu, node, instance,
3092
                                        child, force, info):
3093
        return False
3094

    
3095
  if not force:
3096
    return True
3097
  lu.cfg.SetDiskID(device, node)
3098
  new_id = lu.rpc.call_blockdev_create(node, device, device.size,
3099
                                       instance.name, False, info)
3100
  if not new_id:
3101
    return False
3102
  if device.physical_id is None:
3103
    device.physical_id = new_id
3104
  return True
3105

    
3106

    
3107
def _GenerateUniqueNames(lu, exts):
3108
  """Generate a suitable LV name.
3109

3110
  This will generate a logical volume name for the given instance.
3111

3112
  """
3113
  results = []
3114
  for val in exts:
3115
    new_id = lu.cfg.GenerateUniqueID()
3116
    results.append("%s%s" % (new_id, val))
3117
  return results
3118

    
3119

    
3120
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
3121
                         p_minor, s_minor):
3122
  """Generate a drbd8 device complete with its children.
3123

3124
  """
3125
  port = lu.cfg.AllocatePort()
3126
  vgname = lu.cfg.GetVGName()
3127
  shared_secret = lu.cfg.GenerateDRBDSecret()
3128
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
3129
                          logical_id=(vgname, names[0]))
3130
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
3131
                          logical_id=(vgname, names[1]))
3132
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
3133
                          logical_id=(primary, secondary, port,
3134
                                      p_minor, s_minor,
3135
                                      shared_secret),
3136
                          children=[dev_data, dev_meta],
3137
                          iv_name=iv_name)
3138
  return drbd_dev
3139

    
3140

    
3141
def _GenerateDiskTemplate(lu, template_name,
3142
                          instance_name, primary_node,
3143
                          secondary_nodes, disk_info,
3144
                          file_storage_dir, file_driver):
3145
  """Generate the entire disk layout for a given template type.
3146

3147
  """
3148
  #TODO: compute space requirements
3149

    
3150
  vgname = lu.cfg.GetVGName()
3151
  disk_count = len(disk_info)
3152
  disks = []
3153
  if template_name == constants.DT_DISKLESS:
3154
    pass
3155
  elif template_name == constants.DT_PLAIN:
3156
    if len(secondary_nodes) != 0:
3157
      raise errors.ProgrammerError("Wrong template configuration")
3158

    
3159
    names = _GenerateUniqueNames(lu, [".disk%d" % i
3160
                                      for i in range(disk_count)])
3161
    for idx, disk in enumerate(disk_info):
3162
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
3163
                              logical_id=(vgname, names[idx]),
3164
                              iv_name = "disk/%d" % idx)
3165
      disks.append(disk_dev)
3166
  elif template_name == constants.DT_DRBD8:
3167
    if len(secondary_nodes) != 1:
3168
      raise errors.ProgrammerError("Wrong template configuration")
3169
    remote_node = secondary_nodes[0]
3170
    minors = lu.cfg.AllocateDRBDMinor(
3171
      [primary_node, remote_node] * len(disk_info), instance_name)
3172

    
3173
    names = _GenerateUniqueNames(lu,
3174
                                 [".disk%d_%s" % (i, s)
3175
                                  for i in range(disk_count)
3176
                                  for s in ("data", "meta")
3177
                                  ])
3178
    for idx, disk in enumerate(disk_info):
3179
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
3180
                                      disk["size"], names[idx*2:idx*2+2],
3181
                                      "disk/%d" % idx,
3182
                                      minors[idx*2], minors[idx*2+1])
3183
      disks.append(disk_dev)
3184
  elif template_name == constants.DT_FILE:
3185
    if len(secondary_nodes) != 0:
3186
      raise errors.ProgrammerError("Wrong template configuration")
3187

    
3188
    for idx, disk in enumerate(disk_info):
3189

    
3190
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
3191
                              iv_name="disk/%d" % idx,
3192
                              logical_id=(file_driver,
3193
                                          "%s/disk%d" % (file_storage_dir,
3194
                                                         idx)))
3195
      disks.append(disk_dev)
3196
  else:
3197
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
3198
  return disks
3199

    
3200

    
3201
def _GetInstanceInfoText(instance):
3202
  """Compute that text that should be added to the disk's metadata.
3203

3204
  """
3205
  return "originstname+%s" % instance.name
3206

    
3207

    
3208
def _CreateDisks(lu, instance):
3209
  """Create all disks for an instance.
3210

3211
  This abstracts away some work from AddInstance.
3212

3213
  Args:
3214
    instance: the instance object
3215

3216
  Returns:
3217
    True or False showing the success of the creation process
3218

3219
  """
3220
  info = _GetInstanceInfoText(instance)
3221

    
3222
  if instance.disk_template == constants.DT_FILE:
3223
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
3224
    result = lu.rpc.call_file_storage_dir_create(instance.primary_node,
3225
                                                 file_storage_dir)
3226

    
3227
    if not result:
3228
      logging.error("Could not connect to node '%s'", instance.primary_node)
3229
      return False
3230

    
3231
    if not result[0]:
3232
      logging.error("Failed to create directory '%s'", file_storage_dir)
3233
      return False
3234

    
3235
  for device in instance.disks:
3236
    logging.info("Creating volume %s for instance %s",
3237
                 device.iv_name, instance.name)
3238
    #HARDCODE
3239
    for secondary_node in instance.secondary_nodes:
3240
      if not _CreateBlockDevOnSecondary(lu, secondary_node, instance,
3241
                                        device, False, info):
3242
        logging.error("Failed to create volume %s (%s) on secondary node %s!",
3243
                      device.iv_name, device, secondary_node)
3244
        return False
3245
    #HARDCODE
3246
    if not _CreateBlockDevOnPrimary(lu, instance.primary_node,
3247
                                    instance, device, info):
3248
      logging.error("Failed to create volume %s on primary!", device.iv_name)
3249
      return False
3250

    
3251
  return True
3252

    
3253

    
3254
def _RemoveDisks(lu, instance):
3255
  """Remove all disks for an instance.
3256

3257
  This abstracts away some work from `AddInstance()` and
3258
  `RemoveInstance()`. Note that in case some of the devices couldn't
3259
  be removed, the removal will continue with the other ones (compare
3260
  with `_CreateDisks()`).
3261

3262
  Args:
3263
    instance: the instance object
3264

3265
  Returns:
3266
    True or False showing the success of the removal proces
3267

3268
  """
3269
  logging.info("Removing block devices for instance %s", instance.name)
3270

    
3271
  result = True
3272
  for device in instance.disks:
3273
    for node, disk in device.ComputeNodeTree(instance.primary_node):
3274
      lu.cfg.SetDiskID(disk, node)
3275
      if not lu.rpc.call_blockdev_remove(node, disk):
3276
        lu.proc.LogWarning("Could not remove block device %s on node %s,"
3277
                           " continuing anyway", device.iv_name, node)
3278
        result = False
3279

    
3280
  if instance.disk_template == constants.DT_FILE:
3281
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
3282
    if not lu.rpc.call_file_storage_dir_remove(instance.primary_node,
3283
                                               file_storage_dir):
3284
      logging.error("Could not remove directory '%s'", file_storage_dir)
3285
      result = False
3286

    
3287
  return result
3288

    
3289

    
3290
def _ComputeDiskSize(disk_template, disks):
3291
  """Compute disk size requirements in the volume group
3292

3293
  This is currently hard-coded for the two-drive layout.
3294

3295
  """
3296
  # Required free disk space as a function of disk and swap space
3297
  req_size_dict = {
3298
    constants.DT_DISKLESS: None,
3299
    constants.DT_PLAIN: sum(d["size"] for d in disks),
3300
    # 128 MB are added for drbd metadata for each disk
3301
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
3302
    constants.DT_FILE: None,
3303
  }
3304

    
3305
  if disk_template not in req_size_dict:
3306
    raise errors.ProgrammerError("Disk template '%s' size requirement"
3307
                                 " is unknown" %  disk_template)
3308

    
3309
  return req_size_dict[disk_template]
3310

    
3311

    
3312
def _CheckHVParams(lu, nodenames, hvname, hvparams):
3313
  """Hypervisor parameter validation.
3314

3315
  This function abstract the hypervisor parameter validation to be
3316
  used in both instance create and instance modify.
3317

3318
  @type lu: L{LogicalUnit}
3319
  @param lu: the logical unit for which we check
3320
  @type nodenames: list
3321
  @param nodenames: the list of nodes on which we should check
3322
  @type hvname: string
3323
  @param hvname: the name of the hypervisor we should use
3324
  @type hvparams: dict
3325
  @param hvparams: the parameters which we need to check
3326
  @raise errors.OpPrereqError: if the parameters are not valid
3327

3328
  """
3329
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
3330
                                                  hvname,
3331
                                                  hvparams)
3332
  for node in nodenames:
3333
    info = hvinfo.get(node, None)
3334
    if not info or not isinstance(info, (tuple, list)):
3335
      raise errors.OpPrereqError("Cannot get current information"
3336
                                 " from node '%s' (%s)" % (node, info))
3337
    if not info[0]:
3338
      raise errors.OpPrereqError("Hypervisor parameter validation failed:"
3339
                                 " %s" % info[1])
3340

    
3341

    
3342
class LUCreateInstance(LogicalUnit):
3343
  """Create an instance.
3344

3345
  """
3346
  HPATH = "instance-add"
3347
  HTYPE = constants.HTYPE_INSTANCE
3348
  _OP_REQP = ["instance_name", "disks", "disk_template",
3349
              "mode", "start",
3350
              "wait_for_sync", "ip_check", "nics",
3351
              "hvparams", "beparams"]
3352
  REQ_BGL = False
3353

    
3354
  def _ExpandNode(self, node):
3355
    """Expands and checks one node name.
3356

3357
    """
3358
    node_full = self.cfg.ExpandNodeName(node)
3359
    if node_full is None:
3360
      raise errors.OpPrereqError("Unknown node %s" % node)
3361
    return node_full
3362

    
3363
  def ExpandNames(self):
3364
    """ExpandNames for CreateInstance.
3365

3366
    Figure out the right locks for instance creation.
3367

3368
    """
3369
    self.needed_locks = {}
3370

    
3371
    # set optional parameters to none if they don't exist
3372
    for attr in ["pnode", "snode", "iallocator", "hypervisor"]:
3373
      if not hasattr(self.op, attr):
3374
        setattr(self.op, attr, None)
3375

    
3376
    # cheap checks, mostly valid constants given
3377

    
3378
    # verify creation mode
3379
    if self.op.mode not in (constants.INSTANCE_CREATE,
3380
                            constants.INSTANCE_IMPORT):
3381
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
3382
                                 self.op.mode)
3383

    
3384
    # disk template and mirror node verification
3385
    if self.op.disk_template not in constants.DISK_TEMPLATES:
3386
      raise errors.OpPrereqError("Invalid disk template name")
3387

    
3388
    if self.op.hypervisor is None:
3389
      self.op.hypervisor = self.cfg.GetHypervisorType()
3390

    
3391
    cluster = self.cfg.GetClusterInfo()
3392
    enabled_hvs = cluster.enabled_hypervisors
3393
    if self.op.hypervisor not in enabled_hvs:
3394
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
3395
                                 " cluster (%s)" % (self.op.hypervisor,
3396
                                  ",".join(enabled_hvs)))
3397

    
3398
    # check hypervisor parameter syntax (locally)
3399

    
3400
    filled_hvp = cluster.FillDict(cluster.hvparams[self.op.hypervisor],
3401
                                  self.op.hvparams)
3402
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
3403
    hv_type.CheckParameterSyntax(filled_hvp)
3404

    
3405
    # fill and remember the beparams dict
3406
    self.be_full = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
3407
                                    self.op.beparams)
3408

    
3409
    #### instance parameters check
3410

    
3411
    # instance name verification
3412
    hostname1 = utils.HostInfo(self.op.instance_name)
3413
    self.op.instance_name = instance_name = hostname1.name
3414

    
3415
    # this is just a preventive check, but someone might still add this
3416
    # instance in the meantime, and creation will fail at lock-add time
3417
    if instance_name in self.cfg.GetInstanceList():
3418
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
3419
                                 instance_name)
3420

    
3421
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
3422

    
3423
    # NIC buildup
3424
    self.nics = []
3425
    for nic in self.op.nics:
3426
      # ip validity checks
3427
      ip = nic.get("ip", None)
3428
      if ip is None or ip.lower() == "none":
3429
        nic_ip = None
3430
      elif ip.lower() == constants.VALUE_AUTO:
3431
        nic_ip = hostname1.ip
3432
      else:
3433
        if not utils.IsValidIP(ip):
3434
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
3435
                                     " like a valid IP" % ip)
3436
        nic_ip = ip
3437

    
3438
      # MAC address verification
3439
      mac = nic.get("mac", constants.VALUE_AUTO)
3440
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
3441
        if not utils.IsValidMac(mac.lower()):
3442
          raise errors.OpPrereqError("Invalid MAC address specified: %s" %
3443
                                     mac)
3444
      # bridge verification
3445
      bridge = nic.get("bridge", self.cfg.GetDefBridge())
3446
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, bridge=bridge))
3447

    
3448
    # disk checks/pre-build
3449
    self.disks = []
3450
    for disk in self.op.disks:
3451
      mode = disk.get("mode", constants.DISK_RDWR)
3452
      if mode not in constants.DISK_ACCESS_SET:
3453
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
3454
                                   mode)
3455
      size = disk.get("size", None)
3456
      if size is None:
3457
        raise errors.OpPrereqError("Missing disk size")
3458
      try:
3459
        size = int(size)
3460
      except ValueError:
3461
        raise errors.OpPrereqError("Invalid disk size '%s'" % size)
3462
      self.disks.append({"size": size, "mode": mode})
3463

    
3464
    # used in CheckPrereq for ip ping check
3465
    self.check_ip = hostname1.ip
3466

    
3467
    # file storage checks
3468
    if (self.op.file_driver and
3469
        not self.op.file_driver in constants.FILE_DRIVER):
3470
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
3471
                                 self.op.file_driver)
3472

    
3473
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
3474
      raise errors.OpPrereqError("File storage directory path not absolute")
3475

    
3476
    ### Node/iallocator related checks
3477
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
3478
      raise errors.OpPrereqError("One and only one of iallocator and primary"
3479
                                 " node must be given")
3480

    
3481
    if self.op.iallocator:
3482
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3483
    else:
3484
      self.op.pnode = self._ExpandNode(self.op.pnode)
3485
      nodelist = [self.op.pnode]
3486
      if self.op.snode is not None:
3487
        self.op.snode = self._ExpandNode(self.op.snode)
3488
        nodelist.append(self.op.snode)
3489
      self.needed_locks[locking.LEVEL_NODE] = nodelist
3490

    
3491
    # in case of import lock the source node too
3492
    if self.op.mode == constants.INSTANCE_IMPORT:
3493
      src_node = getattr(self.op, "src_node", None)
3494
      src_path = getattr(self.op, "src_path", None)
3495

    
3496
      if src_node is None or src_path is None:
3497
        raise errors.OpPrereqError("Importing an instance requires source"
3498
                                   " node and path options")
3499

    
3500
      if not os.path.isabs(src_path):
3501
        raise errors.OpPrereqError("The source path must be absolute")
3502

    
3503
      self.op.src_node = src_node = self._ExpandNode(src_node)
3504
      if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
3505
        self.needed_locks[locking.LEVEL_NODE].append(src_node)
3506

    
3507
    else: # INSTANCE_CREATE
3508
      if getattr(self.op, "os_type", None) is None:
3509
        raise errors.OpPrereqError("No guest OS specified")
3510

    
3511
  def _RunAllocator(self):
3512
    """Run the allocator based on input opcode.
3513

3514
    """
3515
    nics = [n.ToDict() for n in self.nics]
3516
    ial = IAllocator(self,
3517
                     mode=constants.IALLOCATOR_MODE_ALLOC,
3518
                     name=self.op.instance_name,
3519
                     disk_template=self.op.disk_template,
3520
                     tags=[],
3521
                     os=self.op.os_type,
3522
                     vcpus=self.be_full[constants.BE_VCPUS],
3523
                     mem_size=self.be_full[constants.BE_MEMORY],
3524
                     disks=self.disks,
3525
                     nics=nics,
3526
                     )
3527

    
3528
    ial.Run(self.op.iallocator)
3529

    
3530
    if not ial.success:
3531
      raise errors.OpPrereqError("Can't compute nodes using"
3532
                                 " iallocator '%s': %s" % (self.op.iallocator,
3533
                                                           ial.info))
3534
    if len(ial.nodes) != ial.required_nodes:
3535
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
3536
                                 " of nodes (%s), required %s" %
3537
                                 (self.op.iallocator, len(ial.nodes),
3538
                                  ial.required_nodes))
3539
    self.op.pnode = ial.nodes[0]
3540
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
3541
                 self.op.instance_name, self.op.iallocator,
3542
                 ", ".join(ial.nodes))
3543
    if ial.required_nodes == 2:
3544
      self.op.snode = ial.nodes[1]
3545

    
3546
  def BuildHooksEnv(self):
3547
    """Build hooks env.
3548

3549
    This runs on master, primary and secondary nodes of the instance.
3550

3551
    """
3552
    env = {
3553
      "INSTANCE_DISK_TEMPLATE": self.op.disk_template,
3554
      "INSTANCE_DISK_SIZE": ",".join(str(d["size"]) for d in self.disks),
3555
      "INSTANCE_ADD_MODE": self.op.mode,
3556
      }
3557
    if self.op.mode == constants.INSTANCE_IMPORT:
3558
      env["INSTANCE_SRC_NODE"] = self.op.src_node
3559
      env["INSTANCE_SRC_PATH"] = self.op.src_path
3560
      env["INSTANCE_SRC_IMAGES"] = self.src_images
3561

    
3562
    env.update(_BuildInstanceHookEnv(name=self.op.instance_name,
3563
      primary_node=self.op.pnode,
3564
      secondary_nodes=self.secondaries,
3565
      status=self.instance_status,
3566
      os_type=self.op.os_type,
3567
      memory=self.be_full[constants.BE_MEMORY],
3568
      vcpus=self.be_full[constants.BE_VCPUS],
3569
      nics=[(n.ip, n.bridge, n.mac) for n in self.nics],
3570
    ))
3571

    
3572
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
3573
          self.secondaries)
3574
    return env, nl, nl
3575

    
3576

    
3577
  def CheckPrereq(self):
3578
    """Check prerequisites.
3579

3580
    """
3581
    if (not self.cfg.GetVGName() and
3582
        self.op.disk_template not in constants.DTS_NOT_LVM):
3583
      raise errors.OpPrereqError("Cluster does not support lvm-based"
3584
                                 " instances")
3585

    
3586

    
3587
    if self.op.mode == constants.INSTANCE_IMPORT:
3588
      src_node = self.op.src_node
3589
      src_path = self.op.src_path
3590

    
3591
      export_info = self.rpc.call_export_info(src_node, src_path)
3592

    
3593
      if not export_info:
3594
        raise errors.OpPrereqError("No export found in dir %s" % src_path)
3595

    
3596
      if not export_info.has_section(constants.INISECT_EXP):
3597
        raise errors.ProgrammerError("Corrupted export config")
3598

    
3599
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
3600
      if (int(ei_version) != constants.EXPORT_VERSION):
3601
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
3602
                                   (ei_version, constants.EXPORT_VERSION))
3603

    
3604
      # Check that the new instance doesn't have less disks than the export
3605
      instance_disks = len(self.disks)
3606
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
3607
      if instance_disks < export_disks:
3608
        raise errors.OpPrereqError("Not enough disks to import."
3609
                                   " (instance: %d, export: %d)" %
3610
                                   (2, export_disks))
3611

    
3612
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
3613
      disk_images = []
3614
      for idx in range(export_disks):
3615
        option = 'disk%d_dump' % idx
3616
        if export_info.has_option(constants.INISECT_INS, option):
3617
          # FIXME: are the old os-es, disk sizes, etc. useful?
3618
          export_name = export_info.get(constants.INISECT_INS, option)
3619
          image = os.path.join(src_path, export_name)
3620
          disk_images.append(image)
3621
        else:
3622
          disk_images.append(False)
3623

    
3624
      self.src_images = disk_images
3625

    
3626
      if self.op.mac == constants.VALUE_AUTO:
3627
        old_name = export_info.get(constants.INISECT_INS, 'name')
3628
        if self.op.instance_name == old_name:
3629
          # FIXME: adjust every nic, when we'll be able to create instances
3630
          # with more than one
3631
          if int(export_info.get(constants.INISECT_INS, 'nic_count')) >= 1:
3632
            self.op.mac = export_info.get(constants.INISECT_INS, 'nic_0_mac')
3633

    
3634
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
3635

    
3636
    if self.op.start and not self.op.ip_check:
3637
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
3638
                                 " adding an instance in start mode")
3639

    
3640
    if self.op.ip_check:
3641
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
3642
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
3643
                                   (self.check_ip, self.op.instance_name))
3644

    
3645
    #### allocator run
3646

    
3647
    if self.op.iallocator is not None:
3648
      self._RunAllocator()
3649

    
3650
    #### node related checks
3651

    
3652
    # check primary node
3653
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
3654
    assert self.pnode is not None, \
3655
      "Cannot retrieve locked node %s" % self.op.pnode
3656
    self.secondaries = []
3657

    
3658
    # mirror node verification
3659
    if self.op.disk_template in constants.DTS_NET_MIRROR:
3660
      if self.op.snode is None:
3661
        raise errors.OpPrereqError("The networked disk templates need"
3662
                                   " a mirror node")
3663
      if self.op.snode == pnode.name:
3664
        raise errors.OpPrereqError("The secondary node cannot be"
3665
                                   " the primary node.")
3666
      self.secondaries.append(self.op.snode)
3667

    
3668
    nodenames = [pnode.name] + self.secondaries
3669

    
3670
    req_size = _ComputeDiskSize(self.op.disk_template,
3671
                                self.disks)
3672

    
3673
    # Check lv size requirements
3674
    if req_size is not None:
3675
      nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
3676
                                         self.op.hypervisor)
3677
      for node in nodenames:
3678
        info = nodeinfo.get(node, None)
3679
        if not info:
3680
          raise errors.OpPrereqError("Cannot get current information"
3681
                                     " from node '%s'" % node)
3682
        vg_free = info.get('vg_free', None)
3683
        if not isinstance(vg_free, int):
3684
          raise errors.OpPrereqError("Can't compute free disk space on"
3685
                                     " node %s" % node)
3686
        if req_size > info['vg_free']:
3687
          raise errors.OpPrereqError("Not enough disk space on target node %s."
3688
                                     " %d MB available, %d MB required" %
3689
                                     (node, info['vg_free'], req_size))
3690

    
3691
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
3692

    
3693
    # os verification
3694
    os_obj = self.rpc.call_os_get(pnode.name, self.op.os_type)
3695
    if not os_obj:
3696
      raise errors.OpPrereqError("OS '%s' not in supported os list for"
3697
                                 " primary node"  % self.op.os_type)
3698

    
3699
    # bridge check on primary node
3700
    bridges = [n.bridge for n in self.nics]
3701
    if not self.rpc.call_bridges_exist(self.pnode.name, bridges):
3702
      raise errors.OpPrereqError("one of the target bridges '%s' does not"
3703
                                 " exist on"
3704
                                 " destination node '%s'" %
3705
                                 (",".join(bridges), pnode.name))
3706

    
3707
    # memory check on primary node
3708
    if self.op.start:
3709
      _CheckNodeFreeMemory(self, self.pnode.name,
3710
                           "creating instance %s" % self.op.instance_name,
3711
                           self.be_full[constants.BE_MEMORY],
3712
                           self.op.hypervisor)
3713

    
3714
    if self.op.start:
3715
      self.instance_status = 'up'
3716
    else:
3717
      self.instance_status = 'down'
3718

    
3719
  def Exec(self, feedback_fn):
3720
    """Create and add the instance to the cluster.
3721

3722
    """
3723
    instance = self.op.instance_name
3724
    pnode_name = self.pnode.name
3725

    
3726
    for nic in self.nics:
3727
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
3728
        nic.mac = self.cfg.GenerateMAC()
3729

    
3730
    ht_kind = self.op.hypervisor
3731
    if ht_kind in constants.HTS_REQ_PORT:
3732
      network_port = self.cfg.AllocatePort()
3733
    else:
3734
      network_port = None
3735

    
3736
    ##if self.op.vnc_bind_address is None:
3737
    ##  self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
3738

    
3739
    # this is needed because os.path.join does not accept None arguments
3740
    if self.op.file_storage_dir is None:
3741
      string_file_storage_dir = ""
3742
    else:
3743
      string_file_storage_dir = self.op.file_storage_dir
3744

    
3745
    # build the full file storage dir path
3746
    file_storage_dir = os.path.normpath(os.path.join(
3747
                                        self.cfg.GetFileStorageDir(),
3748
                                        string_file_storage_dir, instance))
3749

    
3750

    
3751
    disks = _GenerateDiskTemplate(self,
3752
                                  self.op.disk_template,
3753
                                  instance, pnode_name,
3754
                                  self.secondaries,
3755
                                  self.disks,
3756
                                  file_storage_dir,
3757
                                  self.op.file_driver)
3758

    
3759
    iobj = objects.Instance(name=instance, os=self.op.os_type,
3760
                            primary_node=pnode_name,
3761
                            nics=self.nics, disks=disks,
3762
                            disk_template=self.op.disk_template,
3763
                            status=self.instance_status,
3764
                            network_port=network_port,
3765
                            beparams=self.op.beparams,
3766
                            hvparams=self.op.hvparams,
3767
                            hypervisor=self.op.hypervisor,
3768
                            )
3769

    
3770
    feedback_fn("* creating instance disks...")
3771
    if not _CreateDisks(self, iobj):
3772
      _RemoveDisks(self, iobj)
3773
      self.cfg.ReleaseDRBDMinors(instance)
3774
      raise errors.OpExecError("Device creation failed, reverting...")
3775

    
3776
    feedback_fn("adding instance %s to cluster config" % instance)
3777

    
3778
    self.cfg.AddInstance(iobj)
3779
    # Declare that we don't want to remove the instance lock anymore, as we've
3780
    # added the instance to the config
3781
    del self.remove_locks[locking.LEVEL_INSTANCE]
3782
    # Remove the temp. assignements for the instance's drbds
3783
    self.cfg.ReleaseDRBDMinors(instance)
3784

    
3785
    if self.op.wait_for_sync:
3786
      disk_abort = not _WaitForSync(self, iobj)
3787
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
3788
      # make sure the disks are not degraded (still sync-ing is ok)
3789
      time.sleep(15)
3790
      feedback_fn("* checking mirrors status")
3791
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
3792
    else:
3793
      disk_abort = False
3794

    
3795
    if disk_abort:
3796
      _RemoveDisks(self, iobj)
3797
      self.cfg.RemoveInstance(iobj.name)
3798
      # Make sure the instance lock gets removed
3799
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
3800
      raise errors.OpExecError("There are some degraded disks for"
3801
                               " this instance")
3802

    
3803
    feedback_fn("creating os for instance %s on node %s" %
3804
                (instance, pnode_name))
3805

    
3806
    if iobj.disk_template != constants.DT_DISKLESS:
3807
      if self.op.mode == constants.INSTANCE_CREATE:
3808
        feedback_fn("* running the instance OS create scripts...")
3809
        if not self.rpc.call_instance_os_add(pnode_name, iobj):
3810
          raise errors.OpExecError("could not add os for instance %s"
3811
                                   " on node %s" %
3812
                                   (instance, pnode_name))
3813

    
3814
      elif self.op.mode == constants.INSTANCE_IMPORT:
3815
        feedback_fn("* running the instance OS import scripts...")
3816
        src_node = self.op.src_node
3817
        src_images = self.src_images
3818
        cluster_name = self.cfg.GetClusterName()
3819
        import_result = self.rpc.call_instance_os_import(pnode_name, iobj,
3820
                                                         src_node, src_images,
3821
                                                         cluster_name)
3822
        for idx, result in enumerate(import_result):
3823
          if not result:
3824
            self.LogWarning("Could not image %s for on instance %s, disk %d,"
3825
                            " on node %s" % (src_images[idx], instance, idx,
3826
                                             pnode_name))
3827
      else:
3828
        # also checked in the prereq part
3829
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
3830
                                     % self.op.mode)
3831

    
3832
    if self.op.start:
3833
      logging.info("Starting instance %s on node %s", instance, pnode_name)
3834
      feedback_fn("* starting instance...")
3835
      if not self.rpc.call_instance_start(pnode_name, iobj, None):
3836
        raise errors.OpExecError("Could not start instance")
3837

    
3838

    
3839
class LUConnectConsole(NoHooksLU):
3840
  """Connect to an instance's console.
3841

3842
  This is somewhat special in that it returns the command line that
3843
  you need to run on the master node in order to connect to the
3844
  console.
3845

3846
  """
3847
  _OP_REQP = ["instance_name"]
3848
  REQ_BGL = False
3849

    
3850
  def ExpandNames(self):
3851
    self._ExpandAndLockInstance()
3852

    
3853
  def CheckPrereq(self):
3854
    """Check prerequisites.
3855

3856
    This checks that the instance is in the cluster.
3857

3858
    """
3859
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3860
    assert self.instance is not None, \
3861
      "Cannot retrieve locked instance %s" % self.op.instance_name
3862

    
3863
  def Exec(self, feedback_fn):
3864
    """Connect to the console of an instance
3865

3866
    """
3867
    instance = self.instance
3868
    node = instance.primary_node
3869

    
3870
    node_insts = self.rpc.call_instance_list([node],
3871
                                             [instance.hypervisor])[node]
3872
    if node_insts is False:
3873
      raise errors.OpExecError("Can't connect to node %s." % node)
3874

    
3875
    if instance.name not in node_insts:
3876
      raise errors.OpExecError("Instance %s is not running." % instance.name)
3877

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

    
3880
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
3881
    console_cmd = hyper.GetShellCommandForConsole(instance)
3882

    
3883
    # build ssh cmdline
3884
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
3885

    
3886

    
3887
class LUReplaceDisks(LogicalUnit):
3888
  """Replace the disks of an instance.
3889

3890
  """
3891
  HPATH = "mirrors-replace"
3892
  HTYPE = constants.HTYPE_INSTANCE
3893
  _OP_REQP = ["instance_name", "mode", "disks"]
3894
  REQ_BGL = False
3895

    
3896
  def ExpandNames(self):
3897
    self._ExpandAndLockInstance()
3898

    
3899
    if not hasattr(self.op, "remote_node"):
3900
      self.op.remote_node = None
3901

    
3902
    ia_name = getattr(self.op, "iallocator", None)
3903
    if ia_name is not None:
3904
      if self.op.remote_node is not None:
3905
        raise errors.OpPrereqError("Give either the iallocator or the new"
3906
                                   " secondary, not both")
3907
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3908
    elif self.op.remote_node is not None:
3909
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
3910
      if remote_node is None:
3911
        raise errors.OpPrereqError("Node '%s' not known" %
3912
                                   self.op.remote_node)
3913
      self.op.remote_node = remote_node
3914
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
3915
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
3916
    else:
3917
      self.needed_locks[locking.LEVEL_NODE] = []
3918
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3919

    
3920
  def DeclareLocks(self, level):
3921
    # If we're not already locking all nodes in the set we have to declare the
3922
    # instance's primary/secondary nodes.
3923
    if (level == locking.LEVEL_NODE and
3924
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
3925
      self._LockInstancesNodes()
3926

    
3927
  def _RunAllocator(self):
3928
    """Compute a new secondary node using an IAllocator.
3929

3930
    """
3931
    ial = IAllocator(self,
3932
                     mode=constants.IALLOCATOR_MODE_RELOC,
3933
                     name=self.op.instance_name,
3934
                     relocate_from=[self.sec_node])
3935

    
3936
    ial.Run(self.op.iallocator)
3937

    
3938
    if not ial.success:
3939
      raise errors.OpPrereqError("Can't compute nodes using"
3940
                                 " iallocator '%s': %s" % (self.op.iallocator,
3941
                                                           ial.info))
3942
    if len(ial.nodes) != ial.required_nodes:
3943
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
3944
                                 " of nodes (%s), required %s" %
3945
                                 (len(ial.nodes), ial.required_nodes))
3946
    self.op.remote_node = ial.nodes[0]
3947
    self.LogInfo("Selected new secondary for the instance: %s",
3948
                 self.op.remote_node)
3949

    
3950
  def BuildHooksEnv(self):
3951
    """Build hooks env.
3952

3953
    This runs on the master, the primary and all the secondaries.
3954

3955
    """
3956
    env = {
3957
      "MODE": self.op.mode,
3958
      "NEW_SECONDARY": self.op.remote_node,
3959
      "OLD_SECONDARY": self.instance.secondary_nodes[0],
3960
      }
3961
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3962
    nl = [
3963
      self.cfg.GetMasterNode(),
3964
      self.instance.primary_node,
3965
      ]
3966
    if self.op.remote_node is not None:
3967
      nl.append(self.op.remote_node)
3968
    return env, nl, nl
3969

    
3970
  def CheckPrereq(self):
3971
    """Check prerequisites.
3972

3973
    This checks that the instance is in the cluster.
3974

3975
    """
3976
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3977
    assert instance is not None, \
3978
      "Cannot retrieve locked instance %s" % self.op.instance_name
3979
    self.instance = instance
3980

    
3981
    if instance.disk_template not in constants.DTS_NET_MIRROR:
3982
      raise errors.OpPrereqError("Instance's disk layout is not"
3983
                                 " network mirrored.")
3984

    
3985
    if len(instance.secondary_nodes) != 1:
3986
      raise errors.OpPrereqError("The instance has a strange layout,"
3987
                                 " expected one secondary but found %d" %
3988
                                 len(instance.secondary_nodes))
3989

    
3990
    self.sec_node = instance.secondary_nodes[0]
3991

    
3992
    ia_name = getattr(self.op, "iallocator", None)
3993
    if ia_name is not None:
3994
      self._RunAllocator()
3995

    
3996
    remote_node = self.op.remote_node
3997
    if remote_node is not None:
3998
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
3999
      assert self.remote_node_info is not None, \
4000
        "Cannot retrieve locked node %s" % remote_node
4001
    else:
4002
      self.remote_node_info = None
4003
    if remote_node == instance.primary_node:
4004
      raise errors.OpPrereqError("The specified node is the primary node of"
4005
                                 " the instance.")
4006
    elif remote_node == self.sec_node:
4007
      if self.op.mode == constants.REPLACE_DISK_SEC:
4008
        # this is for DRBD8, where we can't execute the same mode of
4009
        # replacement as for drbd7 (no different port allocated)
4010
        raise errors.OpPrereqError("Same secondary given, cannot execute"
4011
                                   " replacement")
4012
    if instance.disk_template == constants.DT_DRBD8:
4013
      if (self.op.mode == constants.REPLACE_DISK_ALL and
4014
          remote_node is not None):
4015
        # switch to replace secondary mode
4016
        self.op.mode = constants.REPLACE_DISK_SEC
4017

    
4018
      if self.op.mode == constants.REPLACE_DISK_ALL:
4019
        raise errors.OpPrereqError("Template 'drbd' only allows primary or"
4020
                                   " secondary disk replacement, not"
4021
                                   " both at once")
4022
      elif self.op.mode == constants.REPLACE_DISK_PRI:
4023
        if remote_node is not None:
4024
          raise errors.OpPrereqError("Template 'drbd' does not allow changing"
4025
                                     " the secondary while doing a primary"
4026
                                     " node disk replacement")
4027
        self.tgt_node = instance.primary_node
4028
        self.oth_node = instance.secondary_nodes[0]
4029
      elif self.op.mode == constants.REPLACE_DISK_SEC:
4030
        self.new_node = remote_node # this can be None, in which case
4031
                                    # we don't change the secondary
4032
        self.tgt_node = instance.secondary_nodes[0]
4033
        self.oth_node = instance.primary_node
4034
      else:
4035
        raise errors.ProgrammerError("Unhandled disk replace mode")
4036

    
4037
    if not self.op.disks:
4038
      self.op.disks = range(len(instance.disks))
4039

    
4040
    for disk_idx in self.op.disks:
4041
      instance.FindDisk(disk_idx)
4042

    
4043
  def _ExecD8DiskOnly(self, feedback_fn):
4044
    """Replace a disk on the primary or secondary for dbrd8.
4045

4046
    The algorithm for replace is quite complicated:
4047
      - for each disk to be replaced:
4048
        - create new LVs on the target node with unique names
4049
        - detach old LVs from the drbd device
4050
        - rename old LVs to name_replaced.<time_t>
4051
        - rename new LVs to old LVs
4052
        - attach the new LVs (with the old names now) to the drbd device
4053
      - wait for sync across all devices
4054
      - for each modified disk:
4055
        - remove old LVs (which have the name name_replaces.<time_t>)
4056

4057
    Failures are not very well handled.
4058

4059
    """
4060
    steps_total = 6
4061
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
4062
    instance = self.instance
4063
    iv_names = {}
4064
    vgname = self.cfg.GetVGName()
4065
    # start of work
4066
    cfg = self.cfg
4067
    tgt_node = self.tgt_node
4068
    oth_node = self.oth_node
4069

    
4070
    # Step: check device activation
4071
    self.proc.LogStep(1, steps_total, "check device existence")
4072
    info("checking volume groups")
4073
    my_vg = cfg.GetVGName()
4074
    results = self.rpc.call_vg_list([oth_node, tgt_node])
4075
    if not results:
4076
      raise errors.OpExecError("Can't list volume groups on the nodes")
4077
    for node in oth_node, tgt_node:
4078
      res = results.get(node, False)
4079
      if not res or my_vg not in res:
4080
        raise errors.OpExecError("Volume group '%s' not found on %s" %
4081
                                 (my_vg, node))
4082
    for idx, dev in enumerate(instance.disks):
4083
      if idx not in self.op.disks:
4084
        continue
4085
      for node in tgt_node, oth_node:
4086
        info("checking disk/%d on %s" % (idx, node))
4087
        cfg.SetDiskID(dev, node)
4088
        if not self.rpc.call_blockdev_find(node, dev):
4089
          raise errors.OpExecError("Can't find disk/%d on node %s" %
4090
                                   (idx, node))
4091

    
4092
    # Step: check other node consistency
4093
    self.proc.LogStep(2, steps_total, "check peer consistency")
4094
    for idx, dev in enumerate(instance.disks):
4095
      if idx not in self.op.disks:
4096
        continue
4097
      info("checking disk/%d consistency on %s" % (idx, oth_node))
4098
      if not _CheckDiskConsistency(self, dev, oth_node,
4099
                                   oth_node==instance.primary_node):
4100
        raise errors.OpExecError("Peer node (%s) has degraded storage, unsafe"
4101
                                 " to replace disks on this node (%s)" %
4102
                                 (oth_node, tgt_node))
4103

    
4104
    # Step: create new storage
4105
    self.proc.LogStep(3, steps_total, "allocate new storage")
4106
    for idx, dev in enumerate(instance.disks):
4107
      if idx not in self.op.disks:
4108
        continue
4109
      size = dev.size
4110
      cfg.SetDiskID(dev, tgt_node)
4111
      lv_names = [".disk%d_%s" % (idx, suf)
4112
                  for suf in ["data", "meta"]]
4113
      names = _GenerateUniqueNames(self, lv_names)
4114
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=size,
4115
                             logical_id=(vgname, names[0]))
4116
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
4117
                             logical_id=(vgname, names[1]))
4118
      new_lvs = [lv_data, lv_meta]
4119
      old_lvs = dev.children
4120
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
4121
      info("creating new local storage on %s for %s" %
4122
           (tgt_node, dev.iv_name))
4123
      # since we *always* want to create this LV, we use the
4124
      # _Create...OnPrimary (which forces the creation), even if we
4125
      # are talking about the secondary node
4126
      for new_lv in new_lvs:
4127
        if not _CreateBlockDevOnPrimary(self, tgt_node, instance, new_lv,
4128
                                        _GetInstanceInfoText(instance)):
4129
          raise errors.OpExecError("Failed to create new LV named '%s' on"
4130
                                   " node '%s'" %
4131
                                   (new_lv.logical_id[1], tgt_node))
4132

    
4133
    # Step: for each lv, detach+rename*2+attach
4134
    self.proc.LogStep(4, steps_total, "change drbd configuration")
4135
    for dev, old_lvs, new_lvs in iv_names.itervalues():
4136
      info("detaching %s drbd from local storage" % dev.iv_name)
4137
      if not self.rpc.call_blockdev_removechildren(tgt_node, dev, old_lvs):
4138
        raise errors.OpExecError("Can't detach drbd from local storage on node"
4139
                                 " %s for device %s" % (tgt_node, dev.iv_name))
4140
      #dev.children = []
4141
      #cfg.Update(instance)
4142

    
4143
      # ok, we created the new LVs, so now we know we have the needed
4144
      # storage; as such, we proceed on the target node to rename
4145
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
4146
      # using the assumption that logical_id == physical_id (which in
4147
      # turn is the unique_id on that node)
4148

    
4149
      # FIXME(iustin): use a better name for the replaced LVs
4150
      temp_suffix = int(time.time())
4151
      ren_fn = lambda d, suff: (d.physical_id[0],
4152
                                d.physical_id[1] + "_replaced-%s" % suff)
4153
      # build the rename list based on what LVs exist on the node
4154
      rlist = []
4155
      for to_ren in old_lvs:
4156
        find_res = self.rpc.call_blockdev_find(tgt_node, to_ren)
4157
        if find_res is not None: # device exists
4158
          rlist.append((to_ren, ren_fn(to_ren, temp_suffix)))
4159

    
4160
      info("renaming the old LVs on the target node")
4161
      if not self.rpc.call_blockdev_rename(tgt_node, rlist):
4162
        raise errors.OpExecError("Can't rename old LVs on node %s" % tgt_node)
4163
      # now we rename the new LVs to the old LVs
4164
      info("renaming the new LVs on the target node")
4165
      rlist = [(new, old.physical_id) for old, new in zip(old_lvs, new_lvs)]
4166
      if not self.rpc.call_blockdev_rename(tgt_node, rlist):
4167
        raise errors.OpExecError("Can't rename new LVs on node %s" % tgt_node)
4168

    
4169
      for old, new in zip(old_lvs, new_lvs):
4170
        new.logical_id = old.logical_id
4171
        cfg.SetDiskID(new, tgt_node)
4172

    
4173
      for disk in old_lvs:
4174
        disk.logical_id = ren_fn(disk, temp_suffix)
4175
        cfg.SetDiskID(disk, tgt_node)
4176

    
4177
      # now that the new lvs have the old name, we can add them to the device
4178
      info("adding new mirror component on %s" % tgt_node)
4179
      if not self.rpc.call_blockdev_addchildren(tgt_node, dev, new_lvs):
4180
        for new_lv in new_lvs:
4181
          if not self.rpc.call_blockdev_remove(tgt_node, new_lv):
4182
            warning("Can't rollback device %s", hint="manually cleanup unused"
4183
                    " logical volumes")
4184
        raise errors.OpExecError("Can't add local storage to drbd")
4185

    
4186
      dev.children = new_lvs
4187
      cfg.Update(instance)
4188

    
4189
    # Step: wait for sync
4190

    
4191
    # this can fail as the old devices are degraded and _WaitForSync
4192
    # does a combined result over all disks, so we don't check its
4193
    # return value
4194
    self.proc.LogStep(5, steps_total, "sync devices")
4195
    _WaitForSync(self, instance, unlock=True)
4196

    
4197
    # so check manually all the devices
4198
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
4199
      cfg.SetDiskID(dev, instance.primary_node)
4200
      is_degr = self.rpc.call_blockdev_find(instance.primary_node, dev)[5]
4201
      if is_degr:
4202
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
4203

    
4204
    # Step: remove old storage
4205
    self.proc.LogStep(6, steps_total, "removing old storage")
4206
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
4207
      info("remove logical volumes for %s" % name)
4208
      for lv in old_lvs:
4209
        cfg.SetDiskID(lv, tgt_node)
4210
        if not self.rpc.call_blockdev_remove(tgt_node, lv):
4211
          warning("Can't remove old LV", hint="manually remove unused LVs")
4212
          continue
4213

    
4214
  def _ExecD8Secondary(self, feedback_fn):
4215
    """Replace the secondary node for drbd8.
4216

4217
    The algorithm for replace is quite complicated:
4218
      - for all disks of the instance:
4219
        - create new LVs on the new node with same names
4220
        - shutdown the drbd device on the old secondary
4221
        - disconnect the drbd network on the primary
4222
        - create the drbd device on the new secondary
4223
        - network attach the drbd on the primary, using an artifice:
4224
          the drbd code for Attach() will connect to the network if it
4225
          finds a device which is connected to the good local disks but
4226
          not network enabled
4227
      - wait for sync across all devices
4228
      - remove all disks from the old secondary
4229

4230
    Failures are not very well handled.
4231

4232
    """
4233
    steps_total = 6
4234
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
4235
    instance = self.instance
4236
    iv_names = {}
4237
    vgname = self.cfg.GetVGName()
4238
    # start of work
4239
    cfg = self.cfg
4240
    old_node = self.tgt_node
4241
    new_node = self.new_node
4242
    pri_node = instance.primary_node
4243

    
4244
    # Step: check device activation
4245
    self.proc.LogStep(1, steps_total, "check device existence")
4246
    info("checking volume groups")
4247
    my_vg = cfg.GetVGName()
4248
    results = self.rpc.call_vg_list([pri_node, new_node])
4249
    if not results:
4250
      raise errors.OpExecError("Can't list volume groups on the nodes")
4251
    for node in pri_node, new_node:
4252
      res = results.get(node, False)
4253
      if not res or my_vg not in res:
4254
        raise errors.OpExecError("Volume group '%s' not found on %s" %
4255
                                 (my_vg, node))
4256
    for idx, dev in enumerate(instance.disks):
4257
      if idx not in self.op.disks:
4258
        continue
4259
      info("checking disk/%d on %s" % (idx, pri_node))
4260
      cfg.SetDiskID(dev, pri_node)
4261
      if not self.rpc.call_blockdev_find(pri_node, dev):
4262
        raise errors.OpExecError("Can't find disk/%d on node %s" %
4263
                                 (idx, pri_node))
4264

    
4265
    # Step: check other node consistency
4266
    self.proc.LogStep(2, steps_total, "check peer consistency")
4267
    for idx, dev in enumerate(instance.disks):
4268
      if idx not in self.op.disks:
4269
        continue
4270
      info("checking disk/%d consistency on %s" % (idx, pri_node))
4271
      if not _CheckDiskConsistency(self, dev, pri_node, True, ldisk=True):
4272
        raise errors.OpExecError("Primary node (%s) has degraded storage,"
4273
                                 " unsafe to replace the secondary" %
4274
                                 pri_node)
4275

    
4276
    # Step: create new storage
4277
    self.proc.LogStep(3, steps_total, "allocate new storage")
4278
    for idx, dev in enumerate(instance.disks):
4279
      size = dev.size
4280
      info("adding new local storage on %s for disk/%d" %
4281
           (new_node, idx))
4282
      # since we *always* want to create this LV, we use the
4283
      # _Create...OnPrimary (which forces the creation), even if we
4284
      # are talking about the secondary node
4285
      for new_lv in dev.children:
4286
        if not _CreateBlockDevOnPrimary(self, new_node, instance, new_lv,
4287
                                        _GetInstanceInfoText(instance)):
4288
          raise errors.OpExecError("Failed to create new LV named '%s' on"
4289
                                   " node '%s'" %
4290
                                   (new_lv.logical_id[1], new_node))
4291

    
4292
    # Step 4: dbrd minors and drbd setups changes
4293
    # after this, we must manually remove the drbd minors on both the
4294
    # error and the success paths
4295
    minors = cfg.AllocateDRBDMinor([new_node for dev in instance.disks],
4296
                                   instance.name)
4297
    logging.debug("Allocated minors %s" % (minors,))
4298
    self.proc.LogStep(4, steps_total, "changing drbd configuration")
4299
    for idx, (dev, new_minor) in enumerate(zip(instance.disks, minors)):
4300
      size = dev.size
4301
      info("activating a new drbd on %s for disk/%d" % (new_node, idx))
4302
      # create new devices on new_node
4303
      if pri_node == dev.logical_id[0]:
4304
        new_logical_id = (pri_node, new_node,
4305
                          dev.logical_id[2], dev.logical_id[3], new_minor,
4306
                          dev.logical_id[5])
4307
      else:
4308
        new_logical_id = (new_node, pri_node,
4309
                          dev.logical_id[2], new_minor, dev.logical_id[4],
4310
                          dev.logical_id[5])
4311
      iv_names[idx] = (dev, dev.children, new_logical_id)
4312
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
4313
                    new_logical_id)
4314
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
4315
                              logical_id=new_logical_id,
4316
                              children=dev.children)
4317
      if not _CreateBlockDevOnSecondary(self, new_node, instance,
4318
                                        new_drbd, False,
4319
                                        _GetInstanceInfoText(instance)):
4320
        self.cfg.ReleaseDRBDMinors(instance.name)
4321
        raise errors.OpExecError("Failed to create new DRBD on"
4322
                                 " node '%s'" % new_node)
4323

    
4324
    for idx, dev in enumerate(instance.disks):
4325
      # we have new devices, shutdown the drbd on the old secondary
4326
      info("shutting down drbd for disk/%d on old node" % idx)
4327
      cfg.SetDiskID(dev, old_node)
4328
      if not self.rpc.call_blockdev_shutdown(old_node, dev):
4329
        warning("Failed to shutdown drbd for disk/%d on old node" % idx,
4330
                hint="Please cleanup this device manually as soon as possible")
4331

    
4332
    info("detaching primary drbds from the network (=> standalone)")
4333
    done = 0
4334
    for idx, dev in enumerate(instance.disks):
4335
      cfg.SetDiskID(dev, pri_node)
4336
      # set the network part of the physical (unique in bdev terms) id
4337
      # to None, meaning detach from network
4338
      dev.physical_id = (None, None, None, None) + dev.physical_id[4:]
4339
      # and 'find' the device, which will 'fix' it to match the
4340
      # standalone state
4341
      if self.rpc.call_blockdev_find(pri_node, dev):
4342
        done += 1
4343
      else:
4344
        warning("Failed to detach drbd disk/%d from network, unusual case" %
4345
                idx)
4346

    
4347
    if not done:
4348
      # no detaches succeeded (very unlikely)
4349
      self.cfg.ReleaseDRBDMinors(instance.name)
4350
      raise errors.OpExecError("Can't detach at least one DRBD from old node")
4351

    
4352
    # if we managed to detach at least one, we update all the disks of
4353
    # the instance to point to the new secondary
4354
    info("updating instance configuration")
4355
    for dev, _, new_logical_id in iv_names.itervalues():
4356
      dev.logical_id = new_logical_id
4357
      cfg.SetDiskID(dev, pri_node)
4358
    cfg.Update(instance)
4359
    # we can remove now the temp minors as now the new values are
4360
    # written to the config file (and therefore stable)
4361
    self.cfg.ReleaseDRBDMinors(instance.name)
4362

    
4363
    # and now perform the drbd attach
4364
    info("attaching primary drbds to new secondary (standalone => connected)")
4365
    failures = []
4366
    for idx, dev in enumerate(instance.disks):
4367
      info("attaching primary drbd for disk/%d to new secondary node" % idx)
4368
      # since the attach is smart, it's enough to 'find' the device,
4369
      # it will automatically activate the network, if the physical_id
4370
      # is correct
4371
      cfg.SetDiskID(dev, pri_node)
4372
      logging.debug("Disk to attach: %s", dev)
4373
      if not self.rpc.call_blockdev_find(pri_node, dev):
4374
        warning("can't attach drbd disk/%d to new secondary!" % idx,
4375
                "please do a gnt-instance info to see the status of disks")
4376

    
4377
    # this can fail as the old devices are degraded and _WaitForSync
4378
    # does a combined result over all disks, so we don't check its
4379
    # return value
4380
    self.proc.LogStep(5, steps_total, "sync devices")
4381
    _WaitForSync(self, instance, unlock=True)
4382

    
4383
    # so check manually all the devices
4384
    for idx, (dev, old_lvs, _) in iv_names.iteritems():
4385
      cfg.SetDiskID(dev, pri_node)
4386
      is_degr = self.rpc.call_blockdev_find(pri_node, dev)[5]
4387
      if is_degr:
4388
        raise errors.OpExecError("DRBD device disk/%d is degraded!" % idx)
4389

    
4390
    self.proc.LogStep(6, steps_total, "removing old storage")
4391
    for idx, (dev, old_lvs, _) in iv_names.iteritems():
4392
      info("remove logical volumes for disk/%d" % idx)
4393
      for lv in old_lvs:
4394
        cfg.SetDiskID(lv, old_node)
4395
        if not self.rpc.call_blockdev_remove(old_node, lv):
4396
          warning("Can't remove LV on old secondary",
4397
                  hint="Cleanup stale volumes by hand")
4398

    
4399
  def Exec(self, feedback_fn):
4400
    """Execute disk replacement.
4401

4402
    This dispatches the disk replacement to the appropriate handler.
4403

4404
    """
4405
    instance = self.instance
4406

    
4407
    # Activate the instance disks if we're replacing them on a down instance
4408
    if instance.status == "down":
4409
      _StartInstanceDisks(self, instance, True)
4410

    
4411
    if instance.disk_template == constants.DT_DRBD8:
4412
      if self.op.remote_node is None:
4413
        fn = self._ExecD8DiskOnly
4414
      else:
4415
        fn = self._ExecD8Secondary
4416
    else:
4417
      raise errors.ProgrammerError("Unhandled disk replacement case")
4418

    
4419
    ret = fn(feedback_fn)
4420

    
4421
    # Deactivate the instance disks if we're replacing them on a down instance
4422
    if instance.status == "down":
4423
      _SafeShutdownInstanceDisks(self, instance)
4424

    
4425
    return ret
4426

    
4427

    
4428
class LUGrowDisk(LogicalUnit):
4429
  """Grow a disk of an instance.
4430

4431
  """
4432
  HPATH = "disk-grow"
4433
  HTYPE = constants.HTYPE_INSTANCE
4434
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
4435
  REQ_BGL = False
4436

    
4437
  def ExpandNames(self):
4438
    self._ExpandAndLockInstance()
4439
    self.needed_locks[locking.LEVEL_NODE] = []
4440
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4441

    
4442
  def DeclareLocks(self, level):
4443
    if level == locking.LEVEL_NODE:
4444
      self._LockInstancesNodes()
4445

    
4446
  def BuildHooksEnv(self):
4447
    """Build hooks env.
4448

4449
    This runs on the master, the primary and all the secondaries.
4450

4451
    """
4452
    env = {
4453
      "DISK": self.op.disk,
4454
      "AMOUNT": self.op.amount,
4455
      }
4456
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4457
    nl = [
4458
      self.cfg.GetMasterNode(),
4459
      self.instance.primary_node,
4460
      ]
4461
    return env, nl, nl
4462

    
4463
  def CheckPrereq(self):
4464
    """Check prerequisites.
4465

4466
    This checks that the instance is in the cluster.
4467

4468
    """
4469
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4470
    assert instance is not None, \
4471
      "Cannot retrieve locked instance %s" % self.op.instance_name
4472

    
4473
    self.instance = instance
4474

    
4475
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
4476
      raise errors.OpPrereqError("Instance's disk layout does not support"
4477
                                 " growing.")
4478

    
4479
    self.disk = instance.FindDisk(self.op.disk)
4480

    
4481
    nodenames = [instance.primary_node] + list(instance.secondary_nodes)
4482
    nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
4483
                                       instance.hypervisor)
4484
    for node in nodenames:
4485
      info = nodeinfo.get(node, None)
4486
      if not info:
4487
        raise errors.OpPrereqError("Cannot get current information"
4488
                                   " from node '%s'" % node)
4489
      vg_free = info.get('vg_free', None)
4490
      if not isinstance(vg_free, int):
4491
        raise errors.OpPrereqError("Can't compute free disk space on"
4492
                                   " node %s" % node)
4493
      if self.op.amount > info['vg_free']:
4494
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
4495
                                   " %d MiB available, %d MiB required" %
4496
                                   (node, info['vg_free'], self.op.amount))
4497

    
4498
  def Exec(self, feedback_fn):
4499
    """Execute disk grow.
4500

4501
    """
4502
    instance = self.instance
4503
    disk = self.disk
4504
    for node in (instance.secondary_nodes + (instance.primary_node,)):
4505
      self.cfg.SetDiskID(disk, node)
4506
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
4507
      if (not result or not isinstance(result, (list, tuple)) or
4508
          len(result) != 2):
4509
        raise errors.OpExecError("grow request failed to node %s" % node)
4510
      elif not result[0]:
4511
        raise errors.OpExecError("grow request failed to node %s: %s" %
4512
                                 (node, result[1]))
4513
    disk.RecordGrow(self.op.amount)
4514
    self.cfg.Update(instance)
4515
    if self.op.wait_for_sync:
4516
      disk_abort = not _WaitForSync(self, instance)
4517
      if disk_abort:
4518
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
4519
                             " status.\nPlease check the instance.")
4520

    
4521

    
4522
class LUQueryInstanceData(NoHooksLU):
4523
  """Query runtime instance data.
4524

4525
  """
4526
  _OP_REQP = ["instances", "static"]
4527
  REQ_BGL = False
4528

    
4529
  def ExpandNames(self):
4530
    self.needed_locks = {}
4531
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
4532

    
4533
    if not isinstance(self.op.instances, list):
4534
      raise errors.OpPrereqError("Invalid argument type 'instances'")
4535

    
4536
    if self.op.instances:
4537
      self.wanted_names = []
4538
      for name in self.op.instances:
4539
        full_name = self.cfg.ExpandInstanceName(name)
4540
        if full_name is None:
4541
          raise errors.OpPrereqError("Instance '%s' not known" %
4542
                                     self.op.instance_name)
4543
        self.wanted_names.append(full_name)
4544
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
4545
    else:
4546
      self.wanted_names = None
4547
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4548

    
4549
    self.needed_locks[locking.LEVEL_NODE] = []
4550
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4551

    
4552
  def DeclareLocks(self, level):
4553
    if level == locking.LEVEL_NODE:
4554
      self._LockInstancesNodes()
4555

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

4559
    This only checks the optional instance list against the existing names.
4560

4561
    """
4562
    if self.wanted_names is None:
4563
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
4564

    
4565
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
4566
                             in self.wanted_names]
4567
    return
4568

    
4569
  def _ComputeDiskStatus(self, instance, snode, dev):
4570
    """Compute block device status.
4571

4572
    """
4573
    static = self.op.static
4574
    if not static:
4575
      self.cfg.SetDiskID(dev, instance.primary_node)
4576
      dev_pstatus = self.rpc.call_blockdev_find(instance.primary_node, dev)
4577
    else:
4578
      dev_pstatus = None
4579

    
4580
    if dev.dev_type in constants.LDS_DRBD:
4581
      # we change the snode then (otherwise we use the one passed in)
4582
      if dev.logical_id[0] == instance.primary_node:
4583
        snode = dev.logical_id[1]
4584
      else:
4585
        snode = dev.logical_id[0]
4586

    
4587
    if snode and not static:
4588
      self.cfg.SetDiskID(dev, snode)
4589
      dev_sstatus = self.rpc.call_blockdev_find(snode, dev)
4590
    else:
4591
      dev_sstatus = None
4592

    
4593
    if dev.children:
4594
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
4595
                      for child in dev.children]
4596
    else:
4597
      dev_children = []
4598

    
4599
    data = {
4600
      "iv_name": dev.iv_name,
4601
      "dev_type": dev.dev_type,
4602
      "logical_id": dev.logical_id,
4603
      "physical_id": dev.physical_id,
4604
      "pstatus": dev_pstatus,
4605
      "sstatus": dev_sstatus,
4606
      "children": dev_children,
4607
      }
4608

    
4609
    return data
4610

    
4611
  def Exec(self, feedback_fn):
4612
    """Gather and return data"""
4613
    result = {}
4614

    
4615
    cluster = self.cfg.GetClusterInfo()
4616

    
4617
    for instance in self.wanted_instances:
4618
      if not self.op.static:
4619
        remote_info = self.rpc.call_instance_info(instance.primary_node,
4620
                                                  instance.name,
4621
                                                  instance.hypervisor)
4622
        if remote_info and "state" in remote_info:
4623
          remote_state = "up"
4624
        else:
4625
          remote_state = "down"
4626
      else:
4627
        remote_state = None
4628
      if instance.status == "down":
4629
        config_state = "down"
4630
      else:
4631
        config_state = "up"
4632

    
4633
      disks = [self._ComputeDiskStatus(instance, None, device)
4634
               for device in instance.disks]
4635

    
4636
      idict = {
4637
        "name": instance.name,
4638
        "config_state": config_state,
4639
        "run_state": remote_state,
4640
        "pnode": instance.primary_node,
4641
        "snodes": instance.secondary_nodes,
4642
        "os": instance.os,
4643
        "nics": [(nic.mac, nic.ip, nic.bridge) for nic in instance.nics],
4644
        "disks": disks,
4645
        "hypervisor": instance.hypervisor,
4646
        "network_port": instance.network_port,
4647
        "hv_instance": instance.hvparams,
4648
        "hv_actual": cluster.FillHV(instance),
4649
        "be_instance": instance.beparams,
4650
        "be_actual": cluster.FillBE(instance),
4651
        }
4652

    
4653
      result[instance.name] = idict
4654

    
4655
    return result
4656

    
4657

    
4658
class LUSetInstanceParams(LogicalUnit):
4659
  """Modifies an instances's parameters.
4660

4661
  """
4662
  HPATH = "instance-modify"
4663
  HTYPE = constants.HTYPE_INSTANCE
4664
  _OP_REQP = ["instance_name", "hvparams"]
4665
  REQ_BGL = False
4666

    
4667
  def ExpandNames(self):
4668
    self._ExpandAndLockInstance()
4669
    self.needed_locks[locking.LEVEL_NODE] = []
4670
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4671

    
4672

    
4673
  def DeclareLocks(self, level):
4674
    if level == locking.LEVEL_NODE:
4675
      self._LockInstancesNodes()
4676

    
4677
  def BuildHooksEnv(self):
4678
    """Build hooks env.
4679

4680
    This runs on the master, primary and secondaries.
4681

4682
    """
4683
    args = dict()
4684
    if constants.BE_MEMORY in self.be_new:
4685
      args['memory'] = self.be_new[constants.BE_MEMORY]
4686
    if constants.BE_VCPUS in self.be_new:
4687
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
4688
    if self.do_ip or self.do_bridge or self.mac:
4689
      if self.do_ip:
4690
        ip = self.ip
4691
      else:
4692
        ip = self.instance.nics[0].ip
4693
      if self.bridge:
4694
        bridge = self.bridge
4695
      else:
4696
        bridge = self.instance.nics[0].bridge
4697
      if self.mac:
4698
        mac = self.mac
4699
      else:
4700
        mac = self.instance.nics[0].mac
4701
      args['nics'] = [(ip, bridge, mac)]
4702
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
4703
    nl = [self.cfg.GetMasterNode(),
4704
          self.instance.primary_node] + list(self.instance.secondary_nodes)
4705
    return env, nl, nl
4706

    
4707
  def CheckPrereq(self):
4708
    """Check prerequisites.
4709

4710
    This only checks the instance list against the existing names.
4711

4712
    """
4713
    # FIXME: all the parameters could be checked before, in ExpandNames, or in
4714
    # a separate CheckArguments function, if we implement one, so the operation
4715
    # can be aborted without waiting for any lock, should it have an error...
4716
    self.ip = getattr(self.op, "ip", None)
4717
    self.mac = getattr(self.op, "mac", None)
4718
    self.bridge = getattr(self.op, "bridge", None)
4719
    self.kernel_path = getattr(self.op, "kernel_path", None)
4720
    self.initrd_path = getattr(self.op, "initrd_path", None)
4721
    self.force = getattr(self.op, "force", None)
4722
    all_parms = [self.ip, self.bridge, self.mac]
4723
    if (all_parms.count(None) == len(all_parms) and
4724
        not self.op.hvparams and
4725
        not self.op.beparams):
4726
      raise errors.OpPrereqError("No changes submitted")
4727
    for item in (constants.BE_MEMORY, constants.BE_VCPUS):
4728
      val = self.op.beparams.get(item, None)
4729
      if val is not None:
4730
        try:
4731
          val = int(val)
4732
        except ValueError, err:
4733
          raise errors.OpPrereqError("Invalid %s size: %s" % (item, str(err)))
4734
        self.op.beparams[item] = val
4735
    if self.ip is not None:
4736
      self.do_ip = True
4737
      if self.ip.lower() == "none":
4738
        self.ip = None
4739
      else:
4740
        if not utils.IsValidIP(self.ip):
4741
          raise errors.OpPrereqError("Invalid IP address '%s'." % self.ip)
4742
    else:
4743
      self.do_ip = False
4744
    self.do_bridge = (self.bridge is not None)
4745
    if self.mac is not None:
4746
      if self.cfg.IsMacInUse(self.mac):
4747
        raise errors.OpPrereqError('MAC address %s already in use in cluster' %
4748
                                   self.mac)
4749
      if not utils.IsValidMac(self.mac):
4750
        raise errors.OpPrereqError('Invalid MAC address %s' % self.mac)
4751

    
4752
    # checking the new params on the primary/secondary nodes
4753

    
4754
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4755
    assert self.instance is not None, \
4756
      "Cannot retrieve locked instance %s" % self.op.instance_name
4757
    pnode = self.instance.primary_node
4758
    nodelist = [pnode]
4759
    nodelist.extend(instance.secondary_nodes)
4760

    
4761
    # hvparams processing
4762
    if self.op.hvparams:
4763
      i_hvdict = copy.deepcopy(instance.hvparams)
4764
      for key, val in self.op.hvparams.iteritems():
4765
        if val is None:
4766
          try:
4767
            del i_hvdict[key]
4768
          except KeyError:
4769
            pass
4770
        else:
4771
          i_hvdict[key] = val
4772
      cluster = self.cfg.GetClusterInfo()
4773
      hv_new = cluster.FillDict(cluster.hvparams[instance.hypervisor],
4774
                                i_hvdict)
4775
      # local check
4776
      hypervisor.GetHypervisor(
4777
        instance.hypervisor).CheckParameterSyntax(hv_new)
4778
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
4779
      self.hv_new = hv_new # the new actual values
4780
      self.hv_inst = i_hvdict # the new dict (without defaults)
4781
    else:
4782
      self.hv_new = self.hv_inst = {}
4783

    
4784
    # beparams processing
4785
    if self.op.beparams:
4786
      i_bedict = copy.deepcopy(instance.beparams)
4787
      for key, val in self.op.beparams.iteritems():
4788
        if val is None:
4789
          try:
4790
            del i_bedict[key]
4791
          except KeyError:
4792
            pass
4793
        else:
4794
          i_bedict[key] = val
4795
      cluster = self.cfg.GetClusterInfo()
4796
      be_new = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
4797
                                i_bedict)
4798
      self.be_new = be_new # the new actual values
4799
      self.be_inst = i_bedict # the new dict (without defaults)
4800
    else:
4801
      self.hv_new = self.hv_inst = {}
4802

    
4803
    self.warn = []
4804

    
4805
    if constants.BE_MEMORY in self.op.beparams and not self.force:
4806
      mem_check_list = [pnode]
4807
      if be_new[constants.BE_AUTO_BALANCE]:
4808
        # either we changed auto_balance to yes or it was from before
4809
        mem_check_list.extend(instance.secondary_nodes)
4810
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
4811
                                                  instance.hypervisor)
4812
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
4813
                                         instance.hypervisor)
4814

    
4815
      if pnode not in nodeinfo or not isinstance(nodeinfo[pnode], dict):
4816
        # Assume the primary node is unreachable and go ahead
4817
        self.warn.append("Can't get info from primary node %s" % pnode)
4818
      else:
4819
        if instance_info:
4820
          current_mem = instance_info['memory']
4821
        else:
4822
          # Assume instance not running
4823
          # (there is a slight race condition here, but it's not very probable,
4824
          # and we have no other way to check)
4825
          current_mem = 0
4826
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
4827
                    nodeinfo[pnode]['memory_free'])
4828
        if miss_mem > 0:
4829
          raise errors.OpPrereqError("This change will prevent the instance"
4830
                                     " from starting, due to %d MB of memory"
4831
                                     " missing on its primary node" % miss_mem)
4832

    
4833
      if be_new[constants.BE_AUTO_BALANCE]:
4834
        for node in instance.secondary_nodes:
4835
          if node not in nodeinfo or not isinstance(nodeinfo[node], dict):
4836
            self.warn.append("Can't get info from secondary node %s" % node)
4837
          elif be_new[constants.BE_MEMORY] > nodeinfo[node]['memory_free']:
4838
            self.warn.append("Not enough memory to failover instance to"
4839
                             " secondary node %s" % node)
4840

    
4841
    return
4842

    
4843
  def Exec(self, feedback_fn):
4844
    """Modifies an instance.
4845

4846
    All parameters take effect only at the next restart of the instance.
4847
    """
4848
    # Process here the warnings from CheckPrereq, as we don't have a
4849
    # feedback_fn there.
4850
    for warn in self.warn:
4851
      feedback_fn("WARNING: %s" % warn)
4852

    
4853
    result = []
4854
    instance = self.instance
4855
    if self.do_ip:
4856
      instance.nics[0].ip = self.ip
4857
      result.append(("ip", self.ip))
4858
    if self.bridge:
4859
      instance.nics[0].bridge = self.bridge
4860
      result.append(("bridge", self.bridge))
4861
    if self.mac:
4862
      instance.nics[0].mac = self.mac
4863
      result.append(("mac", self.mac))
4864
    if self.op.hvparams:
4865
      instance.hvparams = self.hv_new
4866
      for key, val in self.op.hvparams.iteritems():
4867
        result.append(("hv/%s" % key, val))
4868
    if self.op.beparams:
4869
      instance.beparams = self.be_inst
4870
      for key, val in self.op.beparams.iteritems():
4871
        result.append(("be/%s" % key, val))
4872

    
4873
    self.cfg.Update(instance)
4874

    
4875
    return result
4876

    
4877

    
4878
class LUQueryExports(NoHooksLU):
4879
  """Query the exports list
4880

4881
  """
4882
  _OP_REQP = ['nodes']
4883
  REQ_BGL = False
4884

    
4885
  def ExpandNames(self):
4886
    self.needed_locks = {}
4887
    self.share_locks[locking.LEVEL_NODE] = 1
4888
    if not self.op.nodes:
4889
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4890
    else:
4891
      self.needed_locks[locking.LEVEL_NODE] = \
4892
        _GetWantedNodes(self, self.op.nodes)
4893

    
4894
  def CheckPrereq(self):
4895
    """Check prerequisites.
4896

4897
    """
4898
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
4899

    
4900
  def Exec(self, feedback_fn):
4901
    """Compute the list of all the exported system images.
4902

4903
    Returns:
4904
      a dictionary with the structure node->(export-list)
4905
      where export-list is a list of the instances exported on
4906
      that node.
4907

4908
    """
4909
    return self.rpc.call_export_list(self.nodes)
4910

    
4911

    
4912
class LUExportInstance(LogicalUnit):
4913
  """Export an instance to an image in the cluster.
4914

4915
  """
4916
  HPATH = "instance-export"
4917
  HTYPE = constants.HTYPE_INSTANCE
4918
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
4919
  REQ_BGL = False
4920

    
4921
  def ExpandNames(self):
4922
    self._ExpandAndLockInstance()
4923
    # FIXME: lock only instance primary and destination node
4924
    #
4925
    # Sad but true, for now we have do lock all nodes, as we don't know where
4926
    # the previous export might be, and and in this LU we search for it and
4927
    # remove it from its current node. In the future we could fix this by:
4928
    #  - making a tasklet to search (share-lock all), then create the new one,
4929
    #    then one to remove, after
4930
    #  - removing the removal operation altoghether
4931
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4932

    
4933
  def DeclareLocks(self, level):
4934
    """Last minute lock declaration."""
4935
    # All nodes are locked anyway, so nothing to do here.
4936

    
4937
  def BuildHooksEnv(self):
4938
    """Build hooks env.
4939

4940
    This will run on the master, primary node and target node.
4941

4942
    """
4943
    env = {
4944
      "EXPORT_NODE": self.op.target_node,
4945
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
4946
      }
4947
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4948
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node,
4949
          self.op.target_node]
4950
    return env, nl, nl
4951

    
4952
  def CheckPrereq(self):
4953
    """Check prerequisites.
4954

4955
    This checks that the instance and node names are valid.
4956

4957
    """
4958
    instance_name = self.op.instance_name
4959
    self.instance = self.cfg.GetInstanceInfo(instance_name)
4960
    assert self.instance is not None, \
4961
          "Cannot retrieve locked instance %s" % self.op.instance_name
4962

    
4963
    self.dst_node = self.cfg.GetNodeInfo(
4964
      self.cfg.ExpandNodeName(self.op.target_node))
4965

    
4966
    assert self.dst_node is not None, \
4967
          "Cannot retrieve locked node %s" % self.op.target_node
4968

    
4969
    # instance disk type verification
4970
    for disk in self.instance.disks:
4971
      if disk.dev_type == constants.LD_FILE:
4972
        raise errors.OpPrereqError("Export not supported for instances with"
4973
                                   " file-based disks")
4974

    
4975
  def Exec(self, feedback_fn):
4976
    """Export an instance to an image in the cluster.
4977

4978
    """
4979
    instance = self.instance
4980
    dst_node = self.dst_node
4981
    src_node = instance.primary_node
4982
    if self.op.shutdown:
4983
      # shutdown the instance, but not the disks
4984
      if not self.rpc.call_instance_shutdown(src_node, instance):
4985
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
4986
                                 (instance.name, src_node))
4987

    
4988
    vgname = self.cfg.GetVGName()
4989

    
4990
    snap_disks = []
4991

    
4992
    try:
4993
      for disk in instance.disks:
4994
        # new_dev_name will be a snapshot of an lvm leaf of the one we passed
4995
        new_dev_name = self.rpc.call_blockdev_snapshot(src_node, disk)
4996

    
4997
        if not new_dev_name:
4998
          self.LogWarning("Could not snapshot block device %s on node %s",
4999
                          disk.logical_id[1], src_node)
5000
          snap_disks.append(False)
5001
        else:
5002
          new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
5003
                                 logical_id=(vgname, new_dev_name),
5004
                                 physical_id=(vgname, new_dev_name),
5005
                                 iv_name=disk.iv_name)
5006
          snap_disks.append(new_dev)
5007

    
5008
    finally:
5009
      if self.op.shutdown and instance.status == "up":
5010
        if not self.rpc.call_instance_start(src_node, instance, None):
5011
          _ShutdownInstanceDisks(self, instance)
5012
          raise errors.OpExecError("Could not start instance")
5013

    
5014
    # TODO: check for size
5015

    
5016
    cluster_name = self.cfg.GetClusterName()
5017
    for idx, dev in enumerate(snap_disks):
5018
      if dev:
5019
        if not self.rpc.call_snapshot_export(src_node, dev, dst_node.name,
5020
                                             instance, cluster_name, idx):
5021
          self.LogWarning("Could not export block device %s from node %s to"
5022
                          " node %s", dev.logical_id[1], src_node,
5023
                          dst_node.name)
5024
        if not self.rpc.call_blockdev_remove(src_node, dev):
5025
          self.LogWarning("Could not remove snapshot block device %s from node"
5026
                          " %s", dev.logical_id[1], src_node)
5027

    
5028
    if not self.rpc.call_finalize_export(dst_node.name, instance, snap_disks):
5029
      self.LogWarning("Could not finalize export for instance %s on node %s",
5030
                      instance.name, dst_node.name)
5031

    
5032
    nodelist = self.cfg.GetNodeList()
5033
    nodelist.remove(dst_node.name)
5034

    
5035
    # on one-node clusters nodelist will be empty after the removal
5036
    # if we proceed the backup would be removed because OpQueryExports
5037
    # substitutes an empty list with the full cluster node list.
5038
    if nodelist:
5039
      exportlist = self.rpc.call_export_list(nodelist)
5040
      for node in exportlist:
5041
        if instance.name in exportlist[node]:
5042
          if not self.rpc.call_export_remove(node, instance.name):
5043
            self.LogWarning("Could not remove older export for instance %s"
5044
                            " on node %s", instance.name, node)
5045

    
5046

    
5047
class LURemoveExport(NoHooksLU):
5048
  """Remove exports related to the named instance.
5049

5050
  """
5051
  _OP_REQP = ["instance_name"]
5052
  REQ_BGL = False
5053

    
5054
  def ExpandNames(self):
5055
    self.needed_locks = {}
5056
    # We need all nodes to be locked in order for RemoveExport to work, but we
5057
    # don't need to lock the instance itself, as nothing will happen to it (and
5058
    # we can remove exports also for a removed instance)
5059
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5060

    
5061
  def CheckPrereq(self):
5062
    """Check prerequisites.
5063
    """
5064
    pass
5065

    
5066
  def Exec(self, feedback_fn):
5067
    """Remove any export.
5068

5069
    """
5070
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
5071
    # If the instance was not found we'll try with the name that was passed in.
5072
    # This will only work if it was an FQDN, though.
5073
    fqdn_warn = False
5074
    if not instance_name:
5075
      fqdn_warn = True
5076
      instance_name = self.op.instance_name
5077

    
5078
    exportlist = self.rpc.call_export_list(self.acquired_locks[
5079
      locking.LEVEL_NODE])
5080
    found = False
5081
    for node in exportlist:
5082
      if instance_name in exportlist[node]:
5083
        found = True
5084
        if not self.rpc.call_export_remove(node, instance_name):
5085
          logging.error("Could not remove export for instance %s"
5086
                        " on node %s", instance_name, node)
5087

    
5088
    if fqdn_warn and not found:
5089
      feedback_fn("Export not found. If trying to remove an export belonging"
5090
                  " to a deleted instance please use its Fully Qualified"
5091
                  " Domain Name.")
5092

    
5093

    
5094
class TagsLU(NoHooksLU):
5095
  """Generic tags LU.
5096

5097
  This is an abstract class which is the parent of all the other tags LUs.
5098

5099
  """
5100

    
5101
  def ExpandNames(self):
5102
    self.needed_locks = {}
5103
    if self.op.kind == constants.TAG_NODE:
5104
      name = self.cfg.ExpandNodeName(self.op.name)
5105
      if name is None:
5106
        raise errors.OpPrereqError("Invalid node name (%s)" %
5107
                                   (self.op.name,))
5108
      self.op.name = name
5109
      self.needed_locks[locking.LEVEL_NODE] = name
5110
    elif self.op.kind == constants.TAG_INSTANCE:
5111
      name = self.cfg.ExpandInstanceName(self.op.name)
5112
      if name is None:
5113
        raise errors.OpPrereqError("Invalid instance name (%s)" %
5114
                                   (self.op.name,))
5115
      self.op.name = name
5116
      self.needed_locks[locking.LEVEL_INSTANCE] = name
5117

    
5118
  def CheckPrereq(self):
5119
    """Check prerequisites.
5120

5121
    """
5122
    if self.op.kind == constants.TAG_CLUSTER:
5123
      self.target = self.cfg.GetClusterInfo()
5124
    elif self.op.kind == constants.TAG_NODE:
5125
      self.target = self.cfg.GetNodeInfo(self.op.name)
5126
    elif self.op.kind == constants.TAG_INSTANCE:
5127
      self.target = self.cfg.GetInstanceInfo(self.op.name)
5128
    else:
5129
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
5130
                                 str(self.op.kind))
5131

    
5132

    
5133
class LUGetTags(TagsLU):
5134
  """Returns the tags of a given object.
5135

5136
  """
5137
  _OP_REQP = ["kind", "name"]
5138
  REQ_BGL = False
5139

    
5140
  def Exec(self, feedback_fn):
5141
    """Returns the tag list.
5142

5143
    """
5144
    return list(self.target.GetTags())
5145

    
5146

    
5147
class LUSearchTags(NoHooksLU):
5148
  """Searches the tags for a given pattern.
5149

5150
  """
5151
  _OP_REQP = ["pattern"]
5152
  REQ_BGL = False
5153

    
5154
  def ExpandNames(self):
5155
    self.needed_locks = {}
5156

    
5157
  def CheckPrereq(self):
5158
    """Check prerequisites.
5159

5160
    This checks the pattern passed for validity by compiling it.
5161

5162
    """
5163
    try:
5164
      self.re = re.compile(self.op.pattern)
5165
    except re.error, err:
5166
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
5167
                                 (self.op.pattern, err))
5168

    
5169
  def Exec(self, feedback_fn):
5170
    """Returns the tag list.
5171

5172
    """
5173
    cfg = self.cfg
5174
    tgts = [("/cluster", cfg.GetClusterInfo())]
5175
    ilist = cfg.GetAllInstancesInfo().values()
5176
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
5177
    nlist = cfg.GetAllNodesInfo().values()
5178
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
5179
    results = []
5180
    for path, target in tgts:
5181
      for tag in target.GetTags():
5182
        if self.re.search(tag):
5183
          results.append((path, tag))
5184
    return results
5185

    
5186

    
5187
class LUAddTags(TagsLU):
5188
  """Sets a tag on a given object.
5189

5190
  """
5191
  _OP_REQP = ["kind", "name", "tags"]
5192
  REQ_BGL = False
5193

    
5194
  def CheckPrereq(self):
5195
    """Check prerequisites.
5196

5197
    This checks the type and length of the tag name and value.
5198

5199
    """
5200
    TagsLU.CheckPrereq(self)
5201
    for tag in self.op.tags:
5202
      objects.TaggableObject.ValidateTag(tag)
5203

    
5204
  def Exec(self, feedback_fn):
5205
    """Sets the tag.
5206

5207
    """
5208
    try:
5209
      for tag in self.op.tags:
5210
        self.target.AddTag(tag)
5211
    except errors.TagError, err:
5212
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
5213
    try:
5214
      self.cfg.Update(self.target)
5215
    except errors.ConfigurationError:
5216
      raise errors.OpRetryError("There has been a modification to the"
5217
                                " config file and the operation has been"
5218
                                " aborted. Please retry.")
5219

    
5220

    
5221
class LUDelTags(TagsLU):
5222
  """Delete a list of tags from a given object.
5223

5224
  """
5225
  _OP_REQP = ["kind", "name", "tags"]
5226
  REQ_BGL = False
5227

    
5228
  def CheckPrereq(self):
5229
    """Check prerequisites.
5230

5231
    This checks that we have the given tag.
5232

5233
    """
5234
    TagsLU.CheckPrereq(self)
5235
    for tag in self.op.tags:
5236
      objects.TaggableObject.ValidateTag(tag)
5237
    del_tags = frozenset(self.op.tags)
5238
    cur_tags = self.target.GetTags()
5239
    if not del_tags <= cur_tags:
5240
      diff_tags = del_tags - cur_tags
5241
      diff_names = ["'%s'" % tag for tag in diff_tags]
5242
      diff_names.sort()
5243
      raise errors.OpPrereqError("Tag(s) %s not found" %
5244
                                 (",".join(diff_names)))
5245

    
5246
  def Exec(self, feedback_fn):
5247
    """Remove the tag from the object.
5248

5249
    """
5250
    for tag in self.op.tags:
5251
      self.target.RemoveTag(tag)
5252
    try:
5253
      self.cfg.Update(self.target)
5254
    except errors.ConfigurationError:
5255
      raise errors.OpRetryError("There has been a modification to the"
5256
                                " config file and the operation has been"
5257
                                " aborted. Please retry.")
5258

    
5259

    
5260
class LUTestDelay(NoHooksLU):
5261
  """Sleep for a specified amount of time.
5262

5263
  This LU sleeps on the master and/or nodes for a specified amount of
5264
  time.
5265

5266
  """
5267
  _OP_REQP = ["duration", "on_master", "on_nodes"]
5268
  REQ_BGL = False
5269

    
5270
  def ExpandNames(self):
5271
    """Expand names and set required locks.
5272

5273
    This expands the node list, if any.
5274

5275
    """
5276
    self.needed_locks = {}
5277
    if self.op.on_nodes:
5278
      # _GetWantedNodes can be used here, but is not always appropriate to use
5279
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
5280
      # more information.
5281
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
5282
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
5283

    
5284
  def CheckPrereq(self):
5285
    """Check prerequisites.
5286

5287
    """
5288

    
5289
  def Exec(self, feedback_fn):
5290
    """Do the actual sleep.
5291

5292
    """
5293
    if self.op.on_master:
5294
      if not utils.TestDelay(self.op.duration):
5295
        raise errors.OpExecError("Error during master delay test")
5296
    if self.op.on_nodes:
5297
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
5298
      if not result:
5299
        raise errors.OpExecError("Complete failure from rpc call")
5300
      for node, node_result in result.items():
5301
        if not node_result:
5302
          raise errors.OpExecError("Failure during rpc call to node %s,"
5303
                                   " result: %s" % (node, node_result))
5304

    
5305

    
5306
class IAllocator(object):
5307
  """IAllocator framework.
5308

5309
  An IAllocator instance has three sets of attributes:
5310
    - cfg that is needed to query the cluster
5311
    - input data (all members of the _KEYS class attribute are required)
5312
    - four buffer attributes (in|out_data|text), that represent the
5313
      input (to the external script) in text and data structure format,
5314
      and the output from it, again in two formats
5315
    - the result variables from the script (success, info, nodes) for
5316
      easy usage
5317

5318
  """
5319
  _ALLO_KEYS = [
5320
    "mem_size", "disks", "disk_template",
5321
    "os", "tags", "nics", "vcpus",
5322
    ]
5323
  _RELO_KEYS = [
5324
    "relocate_from",
5325
    ]
5326

    
5327
  def __init__(self, lu, mode, name, **kwargs):
5328
    self.lu = lu
5329
    # init buffer variables
5330
    self.in_text = self.out_text = self.in_data = self.out_data = None
5331
    # init all input fields so that pylint is happy
5332
    self.mode = mode
5333
    self.name = name
5334
    self.mem_size = self.disks = self.disk_template = None
5335
    self.os = self.tags = self.nics = self.vcpus = None
5336
    self.relocate_from = None
5337
    # computed fields
5338
    self.required_nodes = None
5339
    # init result fields
5340
    self.success = self.info = self.nodes = None
5341
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
5342
      keyset = self._ALLO_KEYS
5343
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
5344
      keyset = self._RELO_KEYS
5345
    else:
5346
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
5347
                                   " IAllocator" % self.mode)
5348
    for key in kwargs:
5349
      if key not in keyset:
5350
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
5351
                                     " IAllocator" % key)
5352
      setattr(self, key, kwargs[key])
5353
    for key in keyset:
5354
      if key not in kwargs:
5355
        raise errors.ProgrammerError("Missing input parameter '%s' to"
5356
                                     " IAllocator" % key)
5357
    self._BuildInputData()
5358

    
5359
  def _ComputeClusterData(self):
5360
    """Compute the generic allocator input data.
5361

5362
    This is the data that is independent of the actual operation.
5363

5364
    """
5365
    cfg = self.lu.cfg
5366
    cluster_info = cfg.GetClusterInfo()
5367
    # cluster data
5368
    data = {
5369
      "version": 1,
5370
      "cluster_name": cfg.GetClusterName(),
5371
      "cluster_tags": list(cluster_info.GetTags()),
5372
      "enable_hypervisors": list(cluster_info.enabled_hypervisors),
5373
      # we don't have job IDs
5374
      }
5375

    
5376
    i_list = []
5377
    cluster = self.cfg.GetClusterInfo()
5378
    for iname in cfg.GetInstanceList():
5379
      i_obj = cfg.GetInstanceInfo(iname)
5380
      i_list.append((i_obj, cluster.FillBE(i_obj)))
5381

    
5382
    # node data
5383
    node_results = {}
5384
    node_list = cfg.GetNodeList()
5385
    # FIXME: here we have only one hypervisor information, but
5386
    # instance can belong to different hypervisors
5387
    node_data = self.lu.rpc.call_node_info(node_list, cfg.GetVGName(),
5388
                                           cfg.GetHypervisorType())
5389
    for nname in node_list:
5390
      ninfo = cfg.GetNodeInfo(nname)
5391
      if nname not in node_data or not isinstance(node_data[nname], dict):
5392
        raise errors.OpExecError("Can't get data for node %s" % nname)
5393
      remote_info = node_data[nname]
5394
      for attr in ['memory_total', 'memory_free', 'memory_dom0',
5395
                   'vg_size', 'vg_free', 'cpu_total']:
5396
        if attr not in remote_info:
5397
          raise errors.OpExecError("Node '%s' didn't return attribute '%s'" %
5398
                                   (nname, attr))
5399
        try:
5400
          remote_info[attr] = int(remote_info[attr])
5401
        except ValueError, err:
5402
          raise errors.OpExecError("Node '%s' returned invalid value for '%s':"
5403
                                   " %s" % (nname, attr, str(err)))
5404
      # compute memory used by primary instances
5405
      i_p_mem = i_p_up_mem = 0
5406
      for iinfo, beinfo in i_list:
5407
        if iinfo.primary_node == nname:
5408
          i_p_mem += beinfo[constants.BE_MEMORY]
5409
          if iinfo.status == "up":
5410
            i_p_up_mem += beinfo[constants.BE_MEMORY]
5411

    
5412
      # compute memory used by instances
5413
      pnr = {
5414
        "tags": list(ninfo.GetTags()),
5415
        "total_memory": remote_info['memory_total'],
5416
        "reserved_memory": remote_info['memory_dom0'],
5417
        "free_memory": remote_info['memory_free'],
5418
        "i_pri_memory": i_p_mem,
5419
        "i_pri_up_memory": i_p_up_mem,
5420
        "total_disk": remote_info['vg_size'],
5421
        "free_disk": remote_info['vg_free'],
5422
        "primary_ip": ninfo.primary_ip,
5423
        "secondary_ip": ninfo.secondary_ip,
5424
        "total_cpus": remote_info['cpu_total'],
5425
        }
5426
      node_results[nname] = pnr
5427
    data["nodes"] = node_results
5428

    
5429
    # instance data
5430
    instance_data = {}
5431
    for iinfo, beinfo in i_list:
5432
      nic_data = [{"mac": n.mac, "ip": n.ip, "bridge": n.bridge}
5433
                  for n in iinfo.nics]
5434
      pir = {
5435
        "tags": list(iinfo.GetTags()),
5436
        "should_run": iinfo.status == "up",
5437
        "vcpus": beinfo[constants.BE_VCPUS],
5438
        "memory": beinfo[constants.BE_MEMORY],
5439
        "os": iinfo.os,
5440
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
5441
        "nics": nic_data,
5442
        "disks": [{"size": dsk.size, "mode": "w"} for dsk in iinfo.disks],
5443
        "disk_template": iinfo.disk_template,
5444
        "hypervisor": iinfo.hypervisor,
5445
        }
5446
      instance_data[iinfo.name] = pir
5447

    
5448
    data["instances"] = instance_data
5449

    
5450
    self.in_data = data
5451

    
5452
  def _AddNewInstance(self):
5453
    """Add new instance data to allocator structure.
5454

5455
    This in combination with _AllocatorGetClusterData will create the
5456
    correct structure needed as input for the allocator.
5457

5458
    The checks for the completeness of the opcode must have already been
5459
    done.
5460

5461
    """
5462
    data = self.in_data
5463
    if len(self.disks) != 2:
5464
      raise errors.OpExecError("Only two-disk configurations supported")
5465

    
5466
    disk_space = _ComputeDiskSize(self.disk_template,
5467
                                  self.disks[0]["size"], self.disks[1]["size"])
5468

    
5469
    if self.disk_template in constants.DTS_NET_MIRROR:
5470
      self.required_nodes = 2
5471
    else:
5472
      self.required_nodes = 1
5473
    request = {
5474
      "type": "allocate",
5475
      "name": self.name,
5476
      "disk_template": self.disk_template,
5477
      "tags": self.tags,
5478
      "os": self.os,
5479
      "vcpus": self.vcpus,
5480
      "memory": self.mem_size,
5481
      "disks": self.disks,
5482
      "disk_space_total": disk_space,
5483
      "nics": self.nics,
5484
      "required_nodes": self.required_nodes,
5485
      }
5486
    data["request"] = request
5487

    
5488
  def _AddRelocateInstance(self):
5489
    """Add relocate instance data to allocator structure.
5490

5491
    This in combination with _IAllocatorGetClusterData will create the
5492
    correct structure needed as input for the allocator.
5493

5494
    The checks for the completeness of the opcode must have already been
5495
    done.
5496

5497
    """
5498
    instance = self.lu.cfg.GetInstanceInfo(self.name)
5499
    if instance is None:
5500
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
5501
                                   " IAllocator" % self.name)
5502

    
5503
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5504
      raise errors.OpPrereqError("Can't relocate non-mirrored instances")
5505

    
5506
    if len(instance.secondary_nodes) != 1:
5507
      raise errors.OpPrereqError("Instance has not exactly one secondary node")
5508

    
5509
    self.required_nodes = 1
5510

    
5511
    disk_space = _ComputeDiskSize(instance.disk_template,
5512
                                  instance.disks[0].size,
5513
                                  instance.disks[1].size)
5514

    
5515
    request = {
5516
      "type": "relocate",
5517
      "name": self.name,
5518
      "disk_space_total": disk_space,
5519
      "required_nodes": self.required_nodes,
5520
      "relocate_from": self.relocate_from,
5521
      }
5522
    self.in_data["request"] = request
5523

    
5524
  def _BuildInputData(self):
5525
    """Build input data structures.
5526

5527
    """
5528
    self._ComputeClusterData()
5529

    
5530
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
5531
      self._AddNewInstance()
5532
    else:
5533
      self._AddRelocateInstance()
5534

    
5535
    self.in_text = serializer.Dump(self.in_data)
5536

    
5537
  def Run(self, name, validate=True, call_fn=None):
5538
    """Run an instance allocator and return the results.
5539

5540
    """
5541
    if call_fn is None:
5542
      call_fn = self.lu.rpc.call_iallocator_runner
5543
    data = self.in_text
5544

    
5545
    result = call_fn(self.lu.cfg.GetMasterNode(), name, self.in_text)
5546

    
5547
    if not isinstance(result, (list, tuple)) or len(result) != 4:
5548
      raise errors.OpExecError("Invalid result from master iallocator runner")
5549

    
5550
    rcode, stdout, stderr, fail = result
5551

    
5552
    if rcode == constants.IARUN_NOTFOUND:
5553
      raise errors.OpExecError("Can't find allocator '%s'" % name)
5554
    elif rcode == constants.IARUN_FAILURE:
5555
      raise errors.OpExecError("Instance allocator call failed: %s,"
5556
                               " output: %s" % (fail, stdout+stderr))
5557
    self.out_text = stdout
5558
    if validate:
5559
      self._ValidateResult()
5560

    
5561
  def _ValidateResult(self):
5562
    """Process the allocator results.
5563

5564
    This will process and if successful save the result in
5565
    self.out_data and the other parameters.
5566

5567
    """
5568
    try:
5569
      rdict = serializer.Load(self.out_text)
5570
    except Exception, err:
5571
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
5572

    
5573
    if not isinstance(rdict, dict):
5574
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
5575

    
5576
    for key in "success", "info", "nodes":
5577
      if key not in rdict:
5578
        raise errors.OpExecError("Can't parse iallocator results:"
5579
                                 " missing key '%s'" % key)
5580
      setattr(self, key, rdict[key])
5581

    
5582
    if not isinstance(rdict["nodes"], list):
5583
      raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
5584
                               " is not a list")
5585
    self.out_data = rdict
5586

    
5587

    
5588
class LUTestAllocator(NoHooksLU):
5589
  """Run allocator tests.
5590

5591
  This LU runs the allocator tests
5592

5593
  """
5594
  _OP_REQP = ["direction", "mode", "name"]
5595

    
5596
  def CheckPrereq(self):
5597
    """Check prerequisites.
5598

5599
    This checks the opcode parameters depending on the director and mode test.
5600

5601
    """
5602
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
5603
      for attr in ["name", "mem_size", "disks", "disk_template",
5604
                   "os", "tags", "nics", "vcpus"]:
5605
        if not hasattr(self.op, attr):
5606
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
5607
                                     attr)
5608
      iname = self.cfg.ExpandInstanceName(self.op.name)
5609
      if iname is not None:
5610
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
5611
                                   iname)
5612
      if not isinstance(self.op.nics, list):
5613
        raise errors.OpPrereqError("Invalid parameter 'nics'")
5614
      for row in self.op.nics:
5615
        if (not isinstance(row, dict) or
5616
            "mac" not in row or
5617
            "ip" not in row or
5618
            "bridge" not in row):
5619
          raise errors.OpPrereqError("Invalid contents of the"
5620
                                     " 'nics' parameter")
5621
      if not isinstance(self.op.disks, list):
5622
        raise errors.OpPrereqError("Invalid parameter 'disks'")
5623
      if len(self.op.disks) != 2:
5624
        raise errors.OpPrereqError("Only two-disk configurations supported")
5625
      for row in self.op.disks:
5626
        if (not isinstance(row, dict) or
5627
            "size" not in row or
5628
            not isinstance(row["size"], int) or
5629
            "mode" not in row or
5630
            row["mode"] not in ['r', 'w']):
5631
          raise errors.OpPrereqError("Invalid contents of the"
5632
                                     " 'disks' parameter")
5633
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
5634
      if not hasattr(self.op, "name"):
5635
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input")
5636
      fname = self.cfg.ExpandInstanceName(self.op.name)
5637
      if fname is None:
5638
        raise errors.OpPrereqError("Instance '%s' not found for relocation" %
5639
                                   self.op.name)
5640
      self.op.name = fname
5641
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
5642
    else:
5643
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
5644
                                 self.op.mode)
5645

    
5646
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
5647
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
5648
        raise errors.OpPrereqError("Missing allocator name")
5649
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
5650
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
5651
                                 self.op.direction)
5652

    
5653
  def Exec(self, feedback_fn):
5654
    """Run the allocator test.
5655

5656
    """
5657
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
5658
      ial = IAllocator(self,
5659
                       mode=self.op.mode,
5660
                       name=self.op.name,
5661
                       mem_size=self.op.mem_size,
5662
                       disks=self.op.disks,
5663
                       disk_template=self.op.disk_template,
5664
                       os=self.op.os,
5665
                       tags=self.op.tags,
5666
                       nics=self.op.nics,
5667
                       vcpus=self.op.vcpus,
5668
                       )
5669
    else:
5670
      ial = IAllocator(self,
5671
                       mode=self.op.mode,
5672
                       name=self.op.name,
5673
                       relocate_from=list(self.relocate_from),
5674
                       )
5675

    
5676
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
5677
      result = ial.in_text
5678
    else:
5679
      ial.Run(self.op.allocator, validate=False)
5680
      result = ial.out_text
5681
    return result