Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ fc8a6b8f

History | View | Annotate | Download (253.1 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=W0201
25

    
26
# W0201 since most LU attributes are defined in CheckPrereq or similar
27
# functions
28

    
29
import os
30
import os.path
31
import time
32
import re
33
import platform
34
import logging
35
import copy
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 serializer
45
from ganeti import ssconf
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_BGL: the LU needs to hold the Big Ganeti Lock exclusively
59

60
  Note that all commands require root permissions.
61

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

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

71
    This needs to be overridden in derived classes in order to check op
72
    validity.
73

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

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

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

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

    
108
  ssh = property(fget=__GetSSH)
109

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

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

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

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

125
    """
126
    pass
127

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

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

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

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

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

149
    Examples::
150

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

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

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

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

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

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

188
    """
189

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

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

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

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

204
    """
205
    raise NotImplementedError
206

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

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

214
    """
215
    raise NotImplementedError
216

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

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

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

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

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

236
    """
237
    raise NotImplementedError
238

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

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

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

257
    """
258
    return lu_result
259

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
325
    del self.recalculate_locks[locking.LEVEL_NODE]
326

    
327

    
328
class NoHooksLU(LogicalUnit): # pylint: disable-msg=W0223
329
  """Simple LU which runs no hooks.
330

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

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

    
338
  def BuildHooksEnv(self):
339
    """Empty BuildHooksEnv for NoHooksLu.
340

341
    This just raises an error.
342

343
    """
344
    assert False, "BuildHooksEnv called for NoHooksLUs"
345

    
346

    
347
def _GetWantedNodes(lu, nodes):
348
  """Returns list of checked and expanded node names.
349

350
  @type lu: L{LogicalUnit}
351
  @param lu: the logical unit on whose behalf we execute
352
  @type nodes: list
353
  @param nodes: list of node names or None for all nodes
354
  @rtype: list
355
  @return: the list of nodes, sorted
356
  @raise errors.OpProgrammerError: if the nodes parameter is wrong type
357

358
  """
359
  if not isinstance(nodes, list):
360
    raise errors.OpPrereqError("Invalid argument type 'nodes'")
361

    
362
  if not nodes:
363
    raise errors.ProgrammerError("_GetWantedNodes should only be called with a"
364
      " non-empty list of nodes whose name is to be expanded.")
365

    
366
  wanted = []
367
  for name in nodes:
368
    node = lu.cfg.ExpandNodeName(name)
369
    if node is None:
370
      raise errors.OpPrereqError("No such node name '%s'" % name)
371
    wanted.append(node)
372

    
373
  return utils.NiceSort(wanted)
374

    
375

    
376
def _GetWantedInstances(lu, instances):
377
  """Returns list of checked and expanded instance names.
378

379
  @type lu: L{LogicalUnit}
380
  @param lu: the logical unit on whose behalf we execute
381
  @type instances: list
382
  @param instances: list of instance names or None for all instances
383
  @rtype: list
384
  @return: the list of instances, sorted
385
  @raise errors.OpPrereqError: if the instances parameter is wrong type
386
  @raise errors.OpPrereqError: if any of the passed instances is not found
387

388
  """
389
  if not isinstance(instances, list):
390
    raise errors.OpPrereqError("Invalid argument type 'instances'")
391

    
392
  if instances:
393
    wanted = []
394

    
395
    for name in instances:
396
      instance = lu.cfg.ExpandInstanceName(name)
397
      if instance is None:
398
        raise errors.OpPrereqError("No such instance name '%s'" % name)
399
      wanted.append(instance)
400

    
401
  else:
402
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
403
  return wanted
404

    
405

    
406
def _CheckOutputFields(static, dynamic, selected):
407
  """Checks whether all selected fields are valid.
408

409
  @type static: L{utils.FieldSet}
410
  @param static: static fields set
411
  @type dynamic: L{utils.FieldSet}
412
  @param dynamic: dynamic fields set
413

414
  """
415
  f = utils.FieldSet()
416
  f.Extend(static)
417
  f.Extend(dynamic)
418

    
419
  delta = f.NonMatching(selected)
420
  if delta:
421
    raise errors.OpPrereqError("Unknown output fields selected: %s"
422
                               % ",".join(delta))
423

    
424

    
425
def _CheckBooleanOpField(op, name):
426
  """Validates boolean opcode parameters.
427

428
  This will ensure that an opcode parameter is either a boolean value,
429
  or None (but that it always exists).
430

431
  """
432
  val = getattr(op, name, None)
433
  if not (val is None or isinstance(val, bool)):
434
    raise errors.OpPrereqError("Invalid boolean parameter '%s' (%s)" %
435
                               (name, str(val)))
436
  setattr(op, name, val)
437

    
438

    
439
def _CheckNodeOnline(lu, node):
440
  """Ensure that a given node is online.
441

442
  @param lu: the LU on behalf of which we make the check
443
  @param node: the node to check
444
  @raise errors.OpPrereqError: if the node is offline
445

446
  """
447
  if lu.cfg.GetNodeInfo(node).offline:
448
    raise errors.OpPrereqError("Can't use offline node %s" % node)
449

    
450

    
451
def _CheckNodeNotDrained(lu, node):
452
  """Ensure that a given node is not drained.
453

454
  @param lu: the LU on behalf of which we make the check
455
  @param node: the node to check
456
  @raise errors.OpPrereqError: if the node is drained
457

458
  """
459
  if lu.cfg.GetNodeInfo(node).drained:
460
    raise errors.OpPrereqError("Can't use drained node %s" % node)
461

    
462

    
463
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
464
                          memory, vcpus, nics, disk_template, disks,
465
                          bep, hvp, hypervisor_name):
466
  """Builds instance related env variables for hooks
467

468
  This builds the hook environment from individual variables.
469

470
  @type name: string
471
  @param name: the name of the instance
472
  @type primary_node: string
473
  @param primary_node: the name of the instance's primary node
474
  @type secondary_nodes: list
475
  @param secondary_nodes: list of secondary nodes as strings
476
  @type os_type: string
477
  @param os_type: the name of the instance's OS
478
  @type status: boolean
479
  @param status: the should_run status of the instance
480
  @type memory: string
481
  @param memory: the memory size of the instance
482
  @type vcpus: string
483
  @param vcpus: the count of VCPUs the instance has
484
  @type nics: list
485
  @param nics: list of tuples (ip, bridge, mac) representing
486
      the NICs the instance  has
487
  @type disk_template: string
488
  @param disk_template: the disk template of the instance
489
  @type disks: list
490
  @param disks: the list of (size, mode) pairs
491
  @type bep: dict
492
  @param bep: the backend parameters for the instance
493
  @type hvp: dict
494
  @param hvp: the hypervisor parameters for the instance
495
  @type hypervisor_name: string
496
  @param hypervisor_name: the hypervisor for the instance
497
  @rtype: dict
498
  @return: the hook environment for this instance
499

500
  """
501
  if status:
502
    str_status = "up"
503
  else:
504
    str_status = "down"
505
  env = {
506
    "OP_TARGET": name,
507
    "INSTANCE_NAME": name,
508
    "INSTANCE_PRIMARY": primary_node,
509
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
510
    "INSTANCE_OS_TYPE": os_type,
511
    "INSTANCE_STATUS": str_status,
512
    "INSTANCE_MEMORY": memory,
513
    "INSTANCE_VCPUS": vcpus,
514
    "INSTANCE_DISK_TEMPLATE": disk_template,
515
    "INSTANCE_HYPERVISOR": hypervisor_name,
516
  }
517

    
518
  if nics:
519
    nic_count = len(nics)
520
    for idx, (ip, bridge, mac) in enumerate(nics):
521
      if ip is None:
522
        ip = ""
523
      env["INSTANCE_NIC%d_IP" % idx] = ip
524
      env["INSTANCE_NIC%d_BRIDGE" % idx] = bridge
525
      env["INSTANCE_NIC%d_MAC" % idx] = mac
526
  else:
527
    nic_count = 0
528

    
529
  env["INSTANCE_NIC_COUNT"] = nic_count
530

    
531
  if disks:
532
    disk_count = len(disks)
533
    for idx, (size, mode) in enumerate(disks):
534
      env["INSTANCE_DISK%d_SIZE" % idx] = size
535
      env["INSTANCE_DISK%d_MODE" % idx] = mode
536
  else:
537
    disk_count = 0
538

    
539
  env["INSTANCE_DISK_COUNT"] = disk_count
540

    
541
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
542
    for key, value in source.items():
543
      env["INSTANCE_%s_%s" % (kind, key)] = value
544

    
545
  return env
546

    
547

    
548
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
549
  """Builds instance related env variables for hooks from an object.
550

551
  @type lu: L{LogicalUnit}
552
  @param lu: the logical unit on whose behalf we execute
553
  @type instance: L{objects.Instance}
554
  @param instance: the instance for which we should build the
555
      environment
556
  @type override: dict
557
  @param override: dictionary with key/values that will override
558
      our values
559
  @rtype: dict
560
  @return: the hook environment dictionary
561

562
  """
563
  cluster = lu.cfg.GetClusterInfo()
564
  bep = cluster.FillBE(instance)
565
  hvp = cluster.FillHV(instance)
566
  args = {
567
    'name': instance.name,
568
    'primary_node': instance.primary_node,
569
    'secondary_nodes': instance.secondary_nodes,
570
    'os_type': instance.os,
571
    'status': instance.admin_up,
572
    'memory': bep[constants.BE_MEMORY],
573
    'vcpus': bep[constants.BE_VCPUS],
574
    'nics': [(nic.ip, nic.bridge, nic.mac) for nic in instance.nics],
575
    'disk_template': instance.disk_template,
576
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
577
    'bep': bep,
578
    'hvp': hvp,
579
    'hypervisor_name': instance.hypervisor,
580
  }
581
  if override:
582
    args.update(override)
583
  return _BuildInstanceHookEnv(**args)
584

    
585

    
586
def _AdjustCandidatePool(lu):
587
  """Adjust the candidate pool after node operations.
588

589
  """
590
  mod_list = lu.cfg.MaintainCandidatePool()
591
  if mod_list:
592
    lu.LogInfo("Promoted nodes to master candidate role: %s",
593
               ", ".join(node.name for node in mod_list))
594
    for name in mod_list:
595
      lu.context.ReaddNode(name)
596
  mc_now, mc_max = lu.cfg.GetMasterCandidateStats()
597
  if mc_now > mc_max:
598
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
599
               (mc_now, mc_max))
600

    
601

    
602
def _CheckInstanceBridgesExist(lu, instance):
603
  """Check that the bridges needed by an instance exist.
604

605
  """
606
  # check bridges existence
607
  brlist = [nic.bridge for nic in instance.nics]
608
  result = lu.rpc.call_bridges_exist(instance.primary_node, brlist)
609
  result.Raise()
610
  if not result.data:
611
    raise errors.OpPrereqError("One or more target bridges %s does not"
612
                               " exist on destination node '%s'" %
613
                               (brlist, instance.primary_node))
614

    
615

    
616
class LUDestroyCluster(NoHooksLU):
617
  """Logical unit for destroying the cluster.
618

619
  """
620
  _OP_REQP = []
621

    
622
  def CheckPrereq(self):
623
    """Check prerequisites.
624

625
    This checks whether the cluster is empty.
626

627
    Any errors are signaled by raising errors.OpPrereqError.
628

629
    """
630
    master = self.cfg.GetMasterNode()
631

    
632
    nodelist = self.cfg.GetNodeList()
633
    if len(nodelist) != 1 or nodelist[0] != master:
634
      raise errors.OpPrereqError("There are still %d node(s) in"
635
                                 " this cluster." % (len(nodelist) - 1))
636
    instancelist = self.cfg.GetInstanceList()
637
    if instancelist:
638
      raise errors.OpPrereqError("There are still %d instance(s) in"
639
                                 " this cluster." % len(instancelist))
640

    
641
  def Exec(self, feedback_fn):
642
    """Destroys the cluster.
643

644
    """
645
    master = self.cfg.GetMasterNode()
646
    result = self.rpc.call_node_stop_master(master, False)
647
    result.Raise()
648
    if not result.data:
649
      raise errors.OpExecError("Could not disable the master role")
650
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
651
    utils.CreateBackup(priv_key)
652
    utils.CreateBackup(pub_key)
653
    return master
654

    
655

    
656
class LUVerifyCluster(LogicalUnit):
657
  """Verifies the cluster status.
658

659
  """
660
  HPATH = "cluster-verify"
661
  HTYPE = constants.HTYPE_CLUSTER
662
  _OP_REQP = ["skip_checks"]
663
  REQ_BGL = False
664

    
665
  def ExpandNames(self):
666
    self.needed_locks = {
667
      locking.LEVEL_NODE: locking.ALL_SET,
668
      locking.LEVEL_INSTANCE: locking.ALL_SET,
669
    }
670
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
671

    
672
  def _VerifyNode(self, nodeinfo, file_list, local_cksum,
673
                  node_result, feedback_fn, master_files,
674
                  drbd_map, vg_name):
675
    """Run multiple tests against a node.
676

677
    Test list:
678

679
      - compares ganeti version
680
      - checks vg existence and size > 20G
681
      - checks config file checksum
682
      - checks ssh to other nodes
683

684
    @type nodeinfo: L{objects.Node}
685
    @param nodeinfo: the node to check
686
    @param file_list: required list of files
687
    @param local_cksum: dictionary of local files and their checksums
688
    @param node_result: the results from the node
689
    @param feedback_fn: function used to accumulate results
690
    @param master_files: list of files that only masters should have
691
    @param drbd_map: the useddrbd minors for this node, in
692
        form of minor: (instance, must_exist) which correspond to instances
693
        and their running status
694
    @param vg_name: Ganeti Volume Group (result of self.cfg.GetVGName())
695

696
    """
697
    node = nodeinfo.name
698

    
699
    # main result, node_result should be a non-empty dict
700
    if not node_result or not isinstance(node_result, dict):
701
      feedback_fn("  - ERROR: unable to verify node %s." % (node,))
702
      return True
703

    
704
    # compares ganeti version
705
    local_version = constants.PROTOCOL_VERSION
706
    remote_version = node_result.get('version', None)
707
    if not (remote_version and isinstance(remote_version, (list, tuple)) and
708
            len(remote_version) == 2):
709
      feedback_fn("  - ERROR: connection to %s failed" % (node))
710
      return True
711

    
712
    if local_version != remote_version[0]:
713
      feedback_fn("  - ERROR: incompatible protocol versions: master %s,"
714
                  " node %s %s" % (local_version, node, remote_version[0]))
715
      return True
716

    
717
    # node seems compatible, we can actually try to look into its results
718

    
719
    bad = False
720

    
721
    # full package version
722
    if constants.RELEASE_VERSION != remote_version[1]:
723
      feedback_fn("  - WARNING: software version mismatch: master %s,"
724
                  " node %s %s" %
725
                  (constants.RELEASE_VERSION, node, remote_version[1]))
726

    
727
    # checks vg existence and size > 20G
728
    if vg_name is not None:
729
      vglist = node_result.get(constants.NV_VGLIST, None)
730
      if not vglist:
731
        feedback_fn("  - ERROR: unable to check volume groups on node %s." %
732
                        (node,))
733
        bad = True
734
      else:
735
        vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
736
                                              constants.MIN_VG_SIZE)
737
        if vgstatus:
738
          feedback_fn("  - ERROR: %s on node %s" % (vgstatus, node))
739
          bad = True
740

    
741
    # checks config file checksum
742

    
743
    remote_cksum = node_result.get(constants.NV_FILELIST, None)
744
    if not isinstance(remote_cksum, dict):
745
      bad = True
746
      feedback_fn("  - ERROR: node hasn't returned file checksum data")
747
    else:
748
      for file_name in file_list:
749
        node_is_mc = nodeinfo.master_candidate
750
        must_have_file = file_name not in master_files
751
        if file_name not in remote_cksum:
752
          if node_is_mc or must_have_file:
753
            bad = True
754
            feedback_fn("  - ERROR: file '%s' missing" % file_name)
755
        elif remote_cksum[file_name] != local_cksum[file_name]:
756
          if node_is_mc or must_have_file:
757
            bad = True
758
            feedback_fn("  - ERROR: file '%s' has wrong checksum" % file_name)
759
          else:
760
            # not candidate and this is not a must-have file
761
            bad = True
762
            feedback_fn("  - ERROR: file '%s' should not exist on non master"
763
                        " candidates (and the file is outdated)" % file_name)
764
        else:
765
          # all good, except non-master/non-must have combination
766
          if not node_is_mc and not must_have_file:
767
            feedback_fn("  - ERROR: file '%s' should not exist on non master"
768
                        " candidates" % file_name)
769

    
770
    # checks ssh to any
771

    
772
    if constants.NV_NODELIST not in node_result:
773
      bad = True
774
      feedback_fn("  - ERROR: node hasn't returned node ssh connectivity data")
775
    else:
776
      if node_result[constants.NV_NODELIST]:
777
        bad = True
778
        for node in node_result[constants.NV_NODELIST]:
779
          feedback_fn("  - ERROR: ssh communication with node '%s': %s" %
780
                          (node, node_result[constants.NV_NODELIST][node]))
781

    
782
    if constants.NV_NODENETTEST not in node_result:
783
      bad = True
784
      feedback_fn("  - ERROR: node hasn't returned node tcp connectivity data")
785
    else:
786
      if node_result[constants.NV_NODENETTEST]:
787
        bad = True
788
        nlist = utils.NiceSort(node_result[constants.NV_NODENETTEST].keys())
789
        for node in nlist:
790
          feedback_fn("  - ERROR: tcp communication with node '%s': %s" %
791
                          (node, node_result[constants.NV_NODENETTEST][node]))
792

    
793
    hyp_result = node_result.get(constants.NV_HYPERVISOR, None)
794
    if isinstance(hyp_result, dict):
795
      for hv_name, hv_result in hyp_result.iteritems():
796
        if hv_result is not None:
797
          feedback_fn("  - ERROR: hypervisor %s verify failure: '%s'" %
798
                      (hv_name, hv_result))
799

    
800
    # check used drbd list
801
    if vg_name is not None:
802
      used_minors = node_result.get(constants.NV_DRBDLIST, [])
803
      if not isinstance(used_minors, (tuple, list)):
804
        feedback_fn("  - ERROR: cannot parse drbd status file: %s" %
805
                    str(used_minors))
806
      else:
807
        for minor, (iname, must_exist) in drbd_map.items():
808
          if minor not in used_minors and must_exist:
809
            feedback_fn("  - ERROR: drbd minor %d of instance %s is"
810
                        " not active" % (minor, iname))
811
            bad = True
812
        for minor in used_minors:
813
          if minor not in drbd_map:
814
            feedback_fn("  - ERROR: unallocated drbd minor %d is in use" %
815
                        minor)
816
            bad = True
817

    
818
    return bad
819

    
820
  def _VerifyInstance(self, instance, instanceconfig, node_vol_is,
821
                      node_instance, feedback_fn, n_offline):
822
    """Verify an instance.
823

824
    This function checks to see if the required block devices are
825
    available on the instance's node.
826

827
    """
828
    bad = False
829

    
830
    node_current = instanceconfig.primary_node
831

    
832
    node_vol_should = {}
833
    instanceconfig.MapLVsByNode(node_vol_should)
834

    
835
    for node in node_vol_should:
836
      if node in n_offline:
837
        # ignore missing volumes on offline nodes
838
        continue
839
      for volume in node_vol_should[node]:
840
        if node not in node_vol_is or volume not in node_vol_is[node]:
841
          feedback_fn("  - ERROR: volume %s missing on node %s" %
842
                          (volume, node))
843
          bad = True
844

    
845
    if instanceconfig.admin_up:
846
      if ((node_current not in node_instance or
847
          not instance in node_instance[node_current]) and
848
          node_current not in n_offline):
849
        feedback_fn("  - ERROR: instance %s not running on node %s" %
850
                        (instance, node_current))
851
        bad = True
852

    
853
    for node in node_instance:
854
      if (not node == node_current):
855
        if instance in node_instance[node]:
856
          feedback_fn("  - ERROR: instance %s should not run on node %s" %
857
                          (instance, node))
858
          bad = True
859

    
860
    return bad
861

    
862
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is, feedback_fn):
863
    """Verify if there are any unknown volumes in the cluster.
864

865
    The .os, .swap and backup volumes are ignored. All other volumes are
866
    reported as unknown.
867

868
    """
869
    bad = False
870

    
871
    for node in node_vol_is:
872
      for volume in node_vol_is[node]:
873
        if node not in node_vol_should or volume not in node_vol_should[node]:
874
          feedback_fn("  - ERROR: volume %s on node %s should not exist" %
875
                      (volume, node))
876
          bad = True
877
    return bad
878

    
879
  def _VerifyOrphanInstances(self, instancelist, node_instance, feedback_fn):
880
    """Verify the list of running instances.
881

882
    This checks what instances are running but unknown to the cluster.
883

884
    """
885
    bad = False
886
    for node in node_instance:
887
      for runninginstance in node_instance[node]:
888
        if runninginstance not in instancelist:
889
          feedback_fn("  - ERROR: instance %s on node %s should not exist" %
890
                          (runninginstance, node))
891
          bad = True
892
    return bad
893

    
894
  def _VerifyNPlusOneMemory(self, node_info, instance_cfg, feedback_fn):
895
    """Verify N+1 Memory Resilience.
896

897
    Check that if one single node dies we can still start all the instances it
898
    was primary for.
899

900
    """
901
    bad = False
902

    
903
    for node, nodeinfo in node_info.iteritems():
904
      # This code checks that every node which is now listed as secondary has
905
      # enough memory to host all instances it is supposed to should a single
906
      # other node in the cluster fail.
907
      # FIXME: not ready for failover to an arbitrary node
908
      # FIXME: does not support file-backed instances
909
      # WARNING: we currently take into account down instances as well as up
910
      # ones, considering that even if they're down someone might want to start
911
      # them even in the event of a node failure.
912
      for prinode, instances in nodeinfo['sinst-by-pnode'].iteritems():
913
        needed_mem = 0
914
        for instance in instances:
915
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
916
          if bep[constants.BE_AUTO_BALANCE]:
917
            needed_mem += bep[constants.BE_MEMORY]
918
        if nodeinfo['mfree'] < needed_mem:
919
          feedback_fn("  - ERROR: not enough memory on node %s to accommodate"
920
                      " failovers should node %s fail" % (node, prinode))
921
          bad = True
922
    return bad
923

    
924
  def CheckPrereq(self):
925
    """Check prerequisites.
926

927
    Transform the list of checks we're going to skip into a set and check that
928
    all its members are valid.
929

930
    """
931
    self.skip_set = frozenset(self.op.skip_checks)
932
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
933
      raise errors.OpPrereqError("Invalid checks to be skipped specified")
934

    
935
  def BuildHooksEnv(self):
936
    """Build hooks env.
937

938
    Cluster-Verify hooks just ran in the post phase and their failure makes
939
    the output be logged in the verify output and the verification to fail.
940

941
    """
942
    all_nodes = self.cfg.GetNodeList()
943
    env = {
944
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
945
      }
946
    for node in self.cfg.GetAllNodesInfo().values():
947
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
948

    
949
    return env, [], all_nodes
950

    
951
  def Exec(self, feedback_fn):
952
    """Verify integrity of cluster, performing various test on nodes.
953

954
    """
955
    bad = False
956
    feedback_fn("* Verifying global settings")
957
    for msg in self.cfg.VerifyConfig():
958
      feedback_fn("  - ERROR: %s" % msg)
959

    
960
    vg_name = self.cfg.GetVGName()
961
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
962
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
963
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
964
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
965
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
966
                        for iname in instancelist)
967
    i_non_redundant = [] # Non redundant instances
968
    i_non_a_balanced = [] # Non auto-balanced instances
969
    n_offline = [] # List of offline nodes
970
    n_drained = [] # List of nodes being drained
971
    node_volume = {}
972
    node_instance = {}
973
    node_info = {}
974
    instance_cfg = {}
975

    
976
    # FIXME: verify OS list
977
    # do local checksums
978
    master_files = [constants.CLUSTER_CONF_FILE]
979

    
980
    file_names = ssconf.SimpleStore().GetFileList()
981
    file_names.append(constants.SSL_CERT_FILE)
982
    file_names.append(constants.RAPI_CERT_FILE)
983
    file_names.extend(master_files)
984

    
985
    local_checksums = utils.FingerprintFiles(file_names)
986

    
987
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
988
    node_verify_param = {
989
      constants.NV_FILELIST: file_names,
990
      constants.NV_NODELIST: [node.name for node in nodeinfo
991
                              if not node.offline],
992
      constants.NV_HYPERVISOR: hypervisors,
993
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
994
                                  node.secondary_ip) for node in nodeinfo
995
                                 if not node.offline],
996
      constants.NV_INSTANCELIST: hypervisors,
997
      constants.NV_VERSION: None,
998
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
999
      }
1000
    if vg_name is not None:
1001
      node_verify_param[constants.NV_VGLIST] = None
1002
      node_verify_param[constants.NV_LVLIST] = vg_name
1003
      node_verify_param[constants.NV_DRBDLIST] = None
1004
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
1005
                                           self.cfg.GetClusterName())
1006

    
1007
    cluster = self.cfg.GetClusterInfo()
1008
    master_node = self.cfg.GetMasterNode()
1009
    all_drbd_map = self.cfg.ComputeDRBDMap()
1010

    
1011
    for node_i in nodeinfo:
1012
      node = node_i.name
1013
      nresult = all_nvinfo[node].data
1014

    
1015
      if node_i.offline:
1016
        feedback_fn("* Skipping offline node %s" % (node,))
1017
        n_offline.append(node)
1018
        continue
1019

    
1020
      if node == master_node:
1021
        ntype = "master"
1022
      elif node_i.master_candidate:
1023
        ntype = "master candidate"
1024
      elif node_i.drained:
1025
        ntype = "drained"
1026
        n_drained.append(node)
1027
      else:
1028
        ntype = "regular"
1029
      feedback_fn("* Verifying node %s (%s)" % (node, ntype))
1030

    
1031
      if all_nvinfo[node].failed or not isinstance(nresult, dict):
1032
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
1033
        bad = True
1034
        continue
1035

    
1036
      node_drbd = {}
1037
      for minor, instance in all_drbd_map[node].items():
1038
        if instance not in instanceinfo:
1039
          feedback_fn("  - ERROR: ghost instance '%s' in temporary DRBD map" %
1040
                      instance)
1041
          # ghost instance should not be running, but otherwise we
1042
          # don't give double warnings (both ghost instance and
1043
          # unallocated minor in use)
1044
          node_drbd[minor] = (instance, False)
1045
        else:
1046
          instance = instanceinfo[instance]
1047
          node_drbd[minor] = (instance.name, instance.admin_up)
1048
      result = self._VerifyNode(node_i, file_names, local_checksums,
1049
                                nresult, feedback_fn, master_files,
1050
                                node_drbd, vg_name)
1051
      bad = bad or result
1052

    
1053
      lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1054
      if vg_name is None:
1055
        node_volume[node] = {}
1056
      elif isinstance(lvdata, basestring):
1057
        feedback_fn("  - ERROR: LVM problem on node %s: %s" %
1058
                    (node, utils.SafeEncode(lvdata)))
1059
        bad = True
1060
        node_volume[node] = {}
1061
      elif not isinstance(lvdata, dict):
1062
        feedback_fn("  - ERROR: connection to %s failed (lvlist)" % (node,))
1063
        bad = True
1064
        continue
1065
      else:
1066
        node_volume[node] = lvdata
1067

    
1068
      # node_instance
1069
      idata = nresult.get(constants.NV_INSTANCELIST, None)
1070
      if not isinstance(idata, list):
1071
        feedback_fn("  - ERROR: connection to %s failed (instancelist)" %
1072
                    (node,))
1073
        bad = True
1074
        continue
1075

    
1076
      node_instance[node] = idata
1077

    
1078
      # node_info
1079
      nodeinfo = nresult.get(constants.NV_HVINFO, None)
1080
      if not isinstance(nodeinfo, dict):
1081
        feedback_fn("  - ERROR: connection to %s failed (hvinfo)" % (node,))
1082
        bad = True
1083
        continue
1084

    
1085
      try:
1086
        node_info[node] = {
1087
          "mfree": int(nodeinfo['memory_free']),
1088
          "pinst": [],
1089
          "sinst": [],
1090
          # dictionary holding all instances this node is secondary for,
1091
          # grouped by their primary node. Each key is a cluster node, and each
1092
          # value is a list of instances which have the key as primary and the
1093
          # current node as secondary.  this is handy to calculate N+1 memory
1094
          # availability if you can only failover from a primary to its
1095
          # secondary.
1096
          "sinst-by-pnode": {},
1097
        }
1098
        # FIXME: devise a free space model for file based instances as well
1099
        if vg_name is not None:
1100
          if (constants.NV_VGLIST not in nresult or
1101
              vg_name not in nresult[constants.NV_VGLIST]):
1102
            feedback_fn("  - ERROR: node %s didn't return data for the"
1103
                        " volume group '%s' - it is either missing or broken" %
1104
                        (node, vg_name))
1105
            bad = True
1106
            continue
1107
          node_info[node]["dfree"] = int(nresult[constants.NV_VGLIST][vg_name])
1108
      except (ValueError, KeyError):
1109
        feedback_fn("  - ERROR: invalid nodeinfo value returned"
1110
                    " from node %s" % (node,))
1111
        bad = True
1112
        continue
1113

    
1114
    node_vol_should = {}
1115

    
1116
    for instance in instancelist:
1117
      feedback_fn("* Verifying instance %s" % instance)
1118
      inst_config = instanceinfo[instance]
1119
      result =  self._VerifyInstance(instance, inst_config, node_volume,
1120
                                     node_instance, feedback_fn, n_offline)
1121
      bad = bad or result
1122
      inst_nodes_offline = []
1123

    
1124
      inst_config.MapLVsByNode(node_vol_should)
1125

    
1126
      instance_cfg[instance] = inst_config
1127

    
1128
      pnode = inst_config.primary_node
1129
      if pnode in node_info:
1130
        node_info[pnode]['pinst'].append(instance)
1131
      elif pnode not in n_offline:
1132
        feedback_fn("  - ERROR: instance %s, connection to primary node"
1133
                    " %s failed" % (instance, pnode))
1134
        bad = True
1135

    
1136
      if pnode in n_offline:
1137
        inst_nodes_offline.append(pnode)
1138

    
1139
      # If the instance is non-redundant we cannot survive losing its primary
1140
      # node, so we are not N+1 compliant. On the other hand we have no disk
1141
      # templates with more than one secondary so that situation is not well
1142
      # supported either.
1143
      # FIXME: does not support file-backed instances
1144
      if len(inst_config.secondary_nodes) == 0:
1145
        i_non_redundant.append(instance)
1146
      elif len(inst_config.secondary_nodes) > 1:
1147
        feedback_fn("  - WARNING: multiple secondaries for instance %s"
1148
                    % instance)
1149

    
1150
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1151
        i_non_a_balanced.append(instance)
1152

    
1153
      for snode in inst_config.secondary_nodes:
1154
        if snode in node_info:
1155
          node_info[snode]['sinst'].append(instance)
1156
          if pnode not in node_info[snode]['sinst-by-pnode']:
1157
            node_info[snode]['sinst-by-pnode'][pnode] = []
1158
          node_info[snode]['sinst-by-pnode'][pnode].append(instance)
1159
        elif snode not in n_offline:
1160
          feedback_fn("  - ERROR: instance %s, connection to secondary node"
1161
                      " %s failed" % (instance, snode))
1162
          bad = True
1163
        if snode in n_offline:
1164
          inst_nodes_offline.append(snode)
1165

    
1166
      if inst_nodes_offline:
1167
        # warn that the instance lives on offline nodes, and set bad=True
1168
        feedback_fn("  - ERROR: instance lives on offline node(s) %s" %
1169
                    ", ".join(inst_nodes_offline))
1170
        bad = True
1171

    
1172
    feedback_fn("* Verifying orphan volumes")
1173
    result = self._VerifyOrphanVolumes(node_vol_should, node_volume,
1174
                                       feedback_fn)
1175
    bad = bad or result
1176

    
1177
    feedback_fn("* Verifying remaining instances")
1178
    result = self._VerifyOrphanInstances(instancelist, node_instance,
1179
                                         feedback_fn)
1180
    bad = bad or result
1181

    
1182
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1183
      feedback_fn("* Verifying N+1 Memory redundancy")
1184
      result = self._VerifyNPlusOneMemory(node_info, instance_cfg, feedback_fn)
1185
      bad = bad or result
1186

    
1187
    feedback_fn("* Other Notes")
1188
    if i_non_redundant:
1189
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1190
                  % len(i_non_redundant))
1191

    
1192
    if i_non_a_balanced:
1193
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1194
                  % len(i_non_a_balanced))
1195

    
1196
    if n_offline:
1197
      feedback_fn("  - NOTICE: %d offline node(s) found." % len(n_offline))
1198

    
1199
    if n_drained:
1200
      feedback_fn("  - NOTICE: %d drained node(s) found." % len(n_drained))
1201

    
1202
    return not bad
1203

    
1204
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1205
    """Analyze the post-hooks' result
1206

1207
    This method analyses the hook result, handles it, and sends some
1208
    nicely-formatted feedback back to the user.
1209

1210
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1211
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1212
    @param hooks_results: the results of the multi-node hooks rpc call
1213
    @param feedback_fn: function used send feedback back to the caller
1214
    @param lu_result: previous Exec result
1215
    @return: the new Exec result, based on the previous result
1216
        and hook results
1217

1218
    """
1219
    # We only really run POST phase hooks, and are only interested in
1220
    # their results
1221
    if phase == constants.HOOKS_PHASE_POST:
1222
      # Used to change hooks' output to proper indentation
1223
      indent_re = re.compile('^', re.M)
1224
      feedback_fn("* Hooks Results")
1225
      if not hooks_results:
1226
        feedback_fn("  - ERROR: general communication failure")
1227
        lu_result = 1
1228
      else:
1229
        for node_name in hooks_results:
1230
          show_node_header = True
1231
          res = hooks_results[node_name]
1232
          if res.failed or res.data is False or not isinstance(res.data, list):
1233
            if res.offline:
1234
              # no need to warn or set fail return value
1235
              continue
1236
            feedback_fn("    Communication failure in hooks execution")
1237
            lu_result = 1
1238
            continue
1239
          for script, hkr, output in res.data:
1240
            if hkr == constants.HKR_FAIL:
1241
              # The node header is only shown once, if there are
1242
              # failing hooks on that node
1243
              if show_node_header:
1244
                feedback_fn("  Node %s:" % node_name)
1245
                show_node_header = False
1246
              feedback_fn("    ERROR: Script %s failed, output:" % script)
1247
              output = indent_re.sub('      ', output)
1248
              feedback_fn("%s" % output)
1249
              lu_result = 1
1250

    
1251
      return lu_result
1252

    
1253

    
1254
class LUVerifyDisks(NoHooksLU):
1255
  """Verifies the cluster disks status.
1256

1257
  """
1258
  _OP_REQP = []
1259
  REQ_BGL = False
1260

    
1261
  def ExpandNames(self):
1262
    self.needed_locks = {
1263
      locking.LEVEL_NODE: locking.ALL_SET,
1264
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1265
    }
1266
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
1267

    
1268
  def CheckPrereq(self):
1269
    """Check prerequisites.
1270

1271
    This has no prerequisites.
1272

1273
    """
1274
    pass
1275

    
1276
  def Exec(self, feedback_fn):
1277
    """Verify integrity of cluster disks.
1278

1279
    """
1280
    result = res_nodes, res_nlvm, res_instances, res_missing = [], {}, [], {}
1281

    
1282
    vg_name = self.cfg.GetVGName()
1283
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1284
    instances = [self.cfg.GetInstanceInfo(name)
1285
                 for name in self.cfg.GetInstanceList()]
1286

    
1287
    nv_dict = {}
1288
    for inst in instances:
1289
      inst_lvs = {}
1290
      if (not inst.admin_up or
1291
          inst.disk_template not in constants.DTS_NET_MIRROR):
1292
        continue
1293
      inst.MapLVsByNode(inst_lvs)
1294
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1295
      for node, vol_list in inst_lvs.iteritems():
1296
        for vol in vol_list:
1297
          nv_dict[(node, vol)] = inst
1298

    
1299
    if not nv_dict:
1300
      return result
1301

    
1302
    node_lvs = self.rpc.call_volume_list(nodes, vg_name)
1303

    
1304
    for node in nodes:
1305
      # node_volume
1306
      lvs = node_lvs[node]
1307
      if lvs.failed:
1308
        if not lvs.offline:
1309
          self.LogWarning("Connection to node %s failed: %s" %
1310
                          (node, lvs.data))
1311
        continue
1312
      lvs = lvs.data
1313
      if isinstance(lvs, basestring):
1314
        logging.warning("Error enumerating LVs on node %s: %s", node, lvs)
1315
        res_nlvm[node] = lvs
1316
        continue
1317
      elif not isinstance(lvs, dict):
1318
        logging.warning("Connection to node %s failed or invalid data"
1319
                        " returned", node)
1320
        res_nodes.append(node)
1321
        continue
1322

    
1323
      for lv_name, (_, lv_inactive, lv_online) in lvs.iteritems():
1324
        inst = nv_dict.pop((node, lv_name), None)
1325
        if (not lv_online and inst is not None
1326
            and inst.name not in res_instances):
1327
          res_instances.append(inst.name)
1328

    
1329
    # any leftover items in nv_dict are missing LVs, let's arrange the
1330
    # data better
1331
    for key, inst in nv_dict.iteritems():
1332
      if inst.name not in res_missing:
1333
        res_missing[inst.name] = []
1334
      res_missing[inst.name].append(key)
1335

    
1336
    return result
1337

    
1338

    
1339
class LURepairDiskSizes(NoHooksLU):
1340
  """Verifies the cluster disks sizes.
1341

1342
  """
1343
  _OP_REQP = ["instances"]
1344
  REQ_BGL = False
1345

    
1346
  def ExpandNames(self):
1347

    
1348
    if not isinstance(self.op.instances, list):
1349
      raise errors.OpPrereqError("Invalid argument type 'instances'")
1350

    
1351
    if self.op.instances:
1352
      self.wanted_names = []
1353
      for name in self.op.instances:
1354
        full_name = self.cfg.ExpandInstanceName(name)
1355
        if full_name is None:
1356
          raise errors.OpPrereqError("Instance '%s' not known" % name)
1357
        self.wanted_names.append(full_name)
1358
      self.needed_locks = {
1359
        locking.LEVEL_NODE: [],
1360
        locking.LEVEL_INSTANCE: self.wanted_names,
1361
        }
1362
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
1363
    else:
1364
      self.wanted_names = None
1365
      self.needed_locks = {
1366
        locking.LEVEL_NODE: locking.ALL_SET,
1367
        locking.LEVEL_INSTANCE: locking.ALL_SET,
1368
        }
1369
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
1370

    
1371
  def DeclareLocks(self, level):
1372
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
1373
      self._LockInstancesNodes(primary_only=True)
1374

    
1375
  def CheckPrereq(self):
1376
    """Check prerequisites.
1377

1378
    This only checks the optional instance list against the existing names.
1379

1380
    """
1381
    if self.wanted_names is None:
1382
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
1383

    
1384
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
1385
                             in self.wanted_names]
1386

    
1387
  def _EnsureChildSizes(self, disk):
1388
    """Ensure children of the disk have the needed disk size.
1389

1390
    This is valid mainly for DRBD8 and fixes an issue where the
1391
    children have smaller disk size.
1392

1393
    @param disk: an L{ganeti.objects.Disk} object
1394

1395
    """
1396
    if disk.dev_type == constants.LD_DRBD8:
1397
      assert disk.children, "Empty children for DRBD8?"
1398
      fchild = disk.children[0]
1399
      mismatch = fchild.size < disk.size
1400
      if mismatch:
1401
        self.LogInfo("Child disk has size %d, parent %d, fixing",
1402
                     fchild.size, disk.size)
1403
        fchild.size = disk.size
1404

    
1405
      # and we recurse on this child only, not on the metadev
1406
      return self._EnsureChildSizes(fchild) or mismatch
1407
    else:
1408
      return False
1409

    
1410
  def Exec(self, feedback_fn):
1411
    """Verify the size of cluster disks.
1412

1413
    """
1414
    # TODO: check child disks too
1415
    # TODO: check differences in size between primary/secondary nodes
1416
    per_node_disks = {}
1417
    for instance in self.wanted_instances:
1418
      pnode = instance.primary_node
1419
      if pnode not in per_node_disks:
1420
        per_node_disks[pnode] = []
1421
      for idx, disk in enumerate(instance.disks):
1422
        per_node_disks[pnode].append((instance, idx, disk))
1423

    
1424
    changed = []
1425
    for node, dskl in per_node_disks.items():
1426
      newl = [v[2].Copy() for v in dskl]
1427
      for dsk in newl:
1428
        self.cfg.SetDiskID(dsk, node)
1429
      result = self.rpc.call_blockdev_getsizes(node, newl)
1430
      if result.failed:
1431
        self.LogWarning("Failure in blockdev_getsizes call to node"
1432
                        " %s, ignoring", node)
1433
        continue
1434
      if len(result.data) != len(dskl):
1435
        self.LogWarning("Invalid result from node %s, ignoring node results",
1436
                        node)
1437
        continue
1438
      for ((instance, idx, disk), size) in zip(dskl, result.data):
1439
        if size is None:
1440
          self.LogWarning("Disk %d of instance %s did not return size"
1441
                          " information, ignoring", idx, instance.name)
1442
          continue
1443
        if not isinstance(size, (int, long)):
1444
          self.LogWarning("Disk %d of instance %s did not return valid"
1445
                          " size information, ignoring", idx, instance.name)
1446
          continue
1447
        size = size >> 20
1448
        if size != disk.size:
1449
          self.LogInfo("Disk %d of instance %s has mismatched size,"
1450
                       " correcting: recorded %d, actual %d", idx,
1451
                       instance.name, disk.size, size)
1452
          disk.size = size
1453
          self.cfg.Update(instance)
1454
          changed.append((instance.name, idx, size))
1455
        if self._EnsureChildSizes(disk):
1456
          self.cfg.Update(instance)
1457
          changed.append((instance.name, idx, disk.size))
1458
    return changed
1459

    
1460

    
1461
class LURenameCluster(LogicalUnit):
1462
  """Rename the cluster.
1463

1464
  """
1465
  HPATH = "cluster-rename"
1466
  HTYPE = constants.HTYPE_CLUSTER
1467
  _OP_REQP = ["name"]
1468

    
1469
  def BuildHooksEnv(self):
1470
    """Build hooks env.
1471

1472
    """
1473
    env = {
1474
      "OP_TARGET": self.cfg.GetClusterName(),
1475
      "NEW_NAME": self.op.name,
1476
      }
1477
    mn = self.cfg.GetMasterNode()
1478
    return env, [mn], [mn]
1479

    
1480
  def CheckPrereq(self):
1481
    """Verify that the passed name is a valid one.
1482

1483
    """
1484
    hostname = utils.HostInfo(self.op.name)
1485

    
1486
    new_name = hostname.name
1487
    self.ip = new_ip = hostname.ip
1488
    old_name = self.cfg.GetClusterName()
1489
    old_ip = self.cfg.GetMasterIP()
1490
    if new_name == old_name and new_ip == old_ip:
1491
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1492
                                 " cluster has changed")
1493
    if new_ip != old_ip:
1494
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1495
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1496
                                   " reachable on the network. Aborting." %
1497
                                   new_ip)
1498

    
1499
    self.op.name = new_name
1500

    
1501
  def Exec(self, feedback_fn):
1502
    """Rename the cluster.
1503

1504
    """
1505
    clustername = self.op.name
1506
    ip = self.ip
1507

    
1508
    # shutdown the master IP
1509
    master = self.cfg.GetMasterNode()
1510
    result = self.rpc.call_node_stop_master(master, False)
1511
    if result.failed or not result.data:
1512
      raise errors.OpExecError("Could not disable the master role")
1513

    
1514
    try:
1515
      cluster = self.cfg.GetClusterInfo()
1516
      cluster.cluster_name = clustername
1517
      cluster.master_ip = ip
1518
      self.cfg.Update(cluster)
1519

    
1520
      # update the known hosts file
1521
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
1522
      node_list = self.cfg.GetNodeList()
1523
      try:
1524
        node_list.remove(master)
1525
      except ValueError:
1526
        pass
1527
      result = self.rpc.call_upload_file(node_list,
1528
                                         constants.SSH_KNOWN_HOSTS_FILE)
1529
      for to_node, to_result in result.iteritems():
1530
        if to_result.failed or not to_result.data:
1531
          logging.error("Copy of file %s to node %s failed",
1532
                        constants.SSH_KNOWN_HOSTS_FILE, to_node)
1533

    
1534
    finally:
1535
      result = self.rpc.call_node_start_master(master, False, False)
1536
      if result.failed or not result.data:
1537
        self.LogWarning("Could not re-enable the master role on"
1538
                        " the master, please restart manually.")
1539

    
1540

    
1541
def _RecursiveCheckIfLVMBased(disk):
1542
  """Check if the given disk or its children are lvm-based.
1543

1544
  @type disk: L{objects.Disk}
1545
  @param disk: the disk to check
1546
  @rtype: boolean
1547
  @return: boolean indicating whether a LD_LV dev_type was found or not
1548

1549
  """
1550
  if disk.children:
1551
    for chdisk in disk.children:
1552
      if _RecursiveCheckIfLVMBased(chdisk):
1553
        return True
1554
  return disk.dev_type == constants.LD_LV
1555

    
1556

    
1557
class LUSetClusterParams(LogicalUnit):
1558
  """Change the parameters of the cluster.
1559

1560
  """
1561
  HPATH = "cluster-modify"
1562
  HTYPE = constants.HTYPE_CLUSTER
1563
  _OP_REQP = []
1564
  REQ_BGL = False
1565

    
1566
  def CheckArguments(self):
1567
    """Check parameters
1568

1569
    """
1570
    if not hasattr(self.op, "candidate_pool_size"):
1571
      self.op.candidate_pool_size = None
1572
    if self.op.candidate_pool_size is not None:
1573
      try:
1574
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
1575
      except (ValueError, TypeError), err:
1576
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
1577
                                   str(err))
1578
      if self.op.candidate_pool_size < 1:
1579
        raise errors.OpPrereqError("At least one master candidate needed")
1580

    
1581
  def ExpandNames(self):
1582
    # FIXME: in the future maybe other cluster params won't require checking on
1583
    # all nodes to be modified.
1584
    self.needed_locks = {
1585
      locking.LEVEL_NODE: locking.ALL_SET,
1586
    }
1587
    self.share_locks[locking.LEVEL_NODE] = 1
1588

    
1589
  def BuildHooksEnv(self):
1590
    """Build hooks env.
1591

1592
    """
1593
    env = {
1594
      "OP_TARGET": self.cfg.GetClusterName(),
1595
      "NEW_VG_NAME": self.op.vg_name,
1596
      }
1597
    mn = self.cfg.GetMasterNode()
1598
    return env, [mn], [mn]
1599

    
1600
  def CheckPrereq(self):
1601
    """Check prerequisites.
1602

1603
    This checks whether the given params don't conflict and
1604
    if the given volume group is valid.
1605

1606
    """
1607
    if self.op.vg_name is not None and not self.op.vg_name:
1608
      instances = self.cfg.GetAllInstancesInfo().values()
1609
      for inst in instances:
1610
        for disk in inst.disks:
1611
          if _RecursiveCheckIfLVMBased(disk):
1612
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1613
                                       " lvm-based instances exist")
1614

    
1615
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1616

    
1617
    # if vg_name not None, checks given volume group on all nodes
1618
    if self.op.vg_name:
1619
      vglist = self.rpc.call_vg_list(node_list)
1620
      for node in node_list:
1621
        if vglist[node].failed:
1622
          # ignoring down node
1623
          self.LogWarning("Node %s unreachable/error, ignoring" % node)
1624
          continue
1625
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].data,
1626
                                              self.op.vg_name,
1627
                                              constants.MIN_VG_SIZE)
1628
        if vgstatus:
1629
          raise errors.OpPrereqError("Error on node '%s': %s" %
1630
                                     (node, vgstatus))
1631

    
1632
    self.cluster = cluster = self.cfg.GetClusterInfo()
1633
    # validate beparams changes
1634
    if self.op.beparams:
1635
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
1636
      self.new_beparams = cluster.FillDict(
1637
        cluster.beparams[constants.BEGR_DEFAULT], self.op.beparams)
1638

    
1639
    # hypervisor list/parameters
1640
    self.new_hvparams = cluster.FillDict(cluster.hvparams, {})
1641
    if self.op.hvparams:
1642
      if not isinstance(self.op.hvparams, dict):
1643
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input")
1644
      for hv_name, hv_dict in self.op.hvparams.items():
1645
        if hv_name not in self.new_hvparams:
1646
          self.new_hvparams[hv_name] = hv_dict
1647
        else:
1648
          self.new_hvparams[hv_name].update(hv_dict)
1649

    
1650
    if self.op.enabled_hypervisors is not None:
1651
      self.hv_list = self.op.enabled_hypervisors
1652
      if not self.hv_list:
1653
        raise errors.OpPrereqError("Enabled hypervisors list must contain at"
1654
                                   " least one member")
1655
      invalid_hvs = set(self.hv_list) - constants.HYPER_TYPES
1656
      if invalid_hvs:
1657
        raise errors.OpPrereqError("Enabled hypervisors contains invalid"
1658
                                   " entries: %s" % invalid_hvs)
1659
    else:
1660
      self.hv_list = cluster.enabled_hypervisors
1661

    
1662
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
1663
      # either the enabled list has changed, or the parameters have, validate
1664
      for hv_name, hv_params in self.new_hvparams.items():
1665
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
1666
            (self.op.enabled_hypervisors and
1667
             hv_name in self.op.enabled_hypervisors)):
1668
          # either this is a new hypervisor, or its parameters have changed
1669
          hv_class = hypervisor.GetHypervisor(hv_name)
1670
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
1671
          hv_class.CheckParameterSyntax(hv_params)
1672
          _CheckHVParams(self, node_list, hv_name, hv_params)
1673

    
1674
  def Exec(self, feedback_fn):
1675
    """Change the parameters of the cluster.
1676

1677
    """
1678
    if self.op.vg_name is not None:
1679
      new_volume = self.op.vg_name
1680
      if not new_volume:
1681
        new_volume = None
1682
      if new_volume != self.cfg.GetVGName():
1683
        self.cfg.SetVGName(new_volume)
1684
      else:
1685
        feedback_fn("Cluster LVM configuration already in desired"
1686
                    " state, not changing")
1687
    if self.op.hvparams:
1688
      self.cluster.hvparams = self.new_hvparams
1689
    if self.op.enabled_hypervisors is not None:
1690
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
1691
    if self.op.beparams:
1692
      self.cluster.beparams[constants.BEGR_DEFAULT] = self.new_beparams
1693
    if self.op.candidate_pool_size is not None:
1694
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
1695
      # we need to update the pool size here, otherwise the save will fail
1696
      _AdjustCandidatePool(self)
1697

    
1698
    self.cfg.Update(self.cluster)
1699

    
1700

    
1701
class LURedistributeConfig(NoHooksLU):
1702
  """Force the redistribution of cluster configuration.
1703

1704
  This is a very simple LU.
1705

1706
  """
1707
  _OP_REQP = []
1708
  REQ_BGL = False
1709

    
1710
  def ExpandNames(self):
1711
    self.needed_locks = {
1712
      locking.LEVEL_NODE: locking.ALL_SET,
1713
    }
1714
    self.share_locks[locking.LEVEL_NODE] = 1
1715

    
1716
  def CheckPrereq(self):
1717
    """Check prerequisites.
1718

1719
    """
1720

    
1721
  def Exec(self, feedback_fn):
1722
    """Redistribute the configuration.
1723

1724
    """
1725
    self.cfg.Update(self.cfg.GetClusterInfo())
1726

    
1727

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

1731
  """
1732
  if not instance.disks:
1733
    return True
1734

    
1735
  if not oneshot:
1736
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
1737

    
1738
  node = instance.primary_node
1739

    
1740
  for dev in instance.disks:
1741
    lu.cfg.SetDiskID(dev, node)
1742

    
1743
  retries = 0
1744
  degr_retries = 10 # in seconds, as we sleep 1 second each time
1745
  while True:
1746
    max_time = 0
1747
    done = True
1748
    cumul_degraded = False
1749
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
1750
    if rstats.failed or not rstats.data:
1751
      lu.LogWarning("Can't get any data from node %s", node)
1752
      retries += 1
1753
      if retries >= 10:
1754
        raise errors.RemoteError("Can't contact node %s for mirror data,"
1755
                                 " aborting." % node)
1756
      time.sleep(6)
1757
      continue
1758
    rstats = rstats.data
1759
    retries = 0
1760
    for i, mstat in enumerate(rstats):
1761
      if mstat is None:
1762
        lu.LogWarning("Can't compute data for node %s/%s",
1763
                           node, instance.disks[i].iv_name)
1764
        continue
1765
      # we ignore the ldisk parameter
1766
      perc_done, est_time, is_degraded, _ = mstat
1767
      cumul_degraded = cumul_degraded or (is_degraded and perc_done is None)
1768
      if perc_done is not None:
1769
        done = False
1770
        if est_time is not None:
1771
          rem_time = "%d estimated seconds remaining" % est_time
1772
          max_time = est_time
1773
        else:
1774
          rem_time = "no time estimate"
1775
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
1776
                        (instance.disks[i].iv_name, perc_done, rem_time))
1777

    
1778
    # if we're done but degraded, let's do a few small retries, to
1779
    # make sure we see a stable and not transient situation; therefore
1780
    # we force restart of the loop
1781
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
1782
      logging.info("Degraded disks found, %d retries left", degr_retries)
1783
      degr_retries -= 1
1784
      time.sleep(1)
1785
      continue
1786

    
1787
    if done or oneshot:
1788
      break
1789

    
1790
    time.sleep(min(60, max_time))
1791

    
1792
  if done:
1793
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
1794
  return not cumul_degraded
1795

    
1796

    
1797
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
1798
  """Check that mirrors are not degraded.
1799

1800
  The ldisk parameter, if True, will change the test from the
1801
  is_degraded attribute (which represents overall non-ok status for
1802
  the device(s)) to the ldisk (representing the local storage status).
1803

1804
  """
1805
  lu.cfg.SetDiskID(dev, node)
1806
  if ldisk:
1807
    idx = 6
1808
  else:
1809
    idx = 5
1810

    
1811
  result = True
1812
  if on_primary or dev.AssembleOnSecondary():
1813
    rstats = lu.rpc.call_blockdev_find(node, dev)
1814
    msg = rstats.RemoteFailMsg()
1815
    if msg:
1816
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
1817
      result = False
1818
    elif not rstats.payload:
1819
      lu.LogWarning("Can't find disk on node %s", node)
1820
      result = False
1821
    else:
1822
      result = result and (not rstats.payload[idx])
1823
  if dev.children:
1824
    for child in dev.children:
1825
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
1826

    
1827
  return result
1828

    
1829

    
1830
class LUDiagnoseOS(NoHooksLU):
1831
  """Logical unit for OS diagnose/query.
1832

1833
  """
1834
  _OP_REQP = ["output_fields", "names"]
1835
  REQ_BGL = False
1836
  _FIELDS_STATIC = utils.FieldSet()
1837
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status")
1838

    
1839
  def ExpandNames(self):
1840
    if self.op.names:
1841
      raise errors.OpPrereqError("Selective OS query not supported")
1842

    
1843
    _CheckOutputFields(static=self._FIELDS_STATIC,
1844
                       dynamic=self._FIELDS_DYNAMIC,
1845
                       selected=self.op.output_fields)
1846

    
1847
    # Lock all nodes, in shared mode
1848
    # Temporary removal of locks, should be reverted later
1849
    # TODO: reintroduce locks when they are lighter-weight
1850
    self.needed_locks = {}
1851
    #self.share_locks[locking.LEVEL_NODE] = 1
1852
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1853

    
1854
  def CheckPrereq(self):
1855
    """Check prerequisites.
1856

1857
    """
1858

    
1859
  @staticmethod
1860
  def _DiagnoseByOS(node_list, rlist):
1861
    """Remaps a per-node return list into an a per-os per-node dictionary
1862

1863
    @param node_list: a list with the names of all nodes
1864
    @param rlist: a map with node names as keys and OS objects as values
1865

1866
    @rtype: dict
1867
    @return: a dictionary with osnames as keys and as value another map, with
1868
        nodes as keys and list of OS objects as values, eg::
1869

1870
          {"debian-etch": {"node1": [<object>,...],
1871
                           "node2": [<object>,]}
1872
          }
1873

1874
    """
1875
    all_os = {}
1876
    # we build here the list of nodes that didn't fail the RPC (at RPC
1877
    # level), so that nodes with a non-responding node daemon don't
1878
    # make all OSes invalid
1879
    good_nodes = [node_name for node_name in rlist
1880
                  if not rlist[node_name].failed]
1881
    for node_name, nr in rlist.iteritems():
1882
      if nr.failed or not nr.data:
1883
        continue
1884
      for os_obj in nr.data:
1885
        if os_obj.name not in all_os:
1886
          # build a list of nodes for this os containing empty lists
1887
          # for each node in node_list
1888
          all_os[os_obj.name] = {}
1889
          for nname in good_nodes:
1890
            all_os[os_obj.name][nname] = []
1891
        all_os[os_obj.name][node_name].append(os_obj)
1892
    return all_os
1893

    
1894
  def Exec(self, feedback_fn):
1895
    """Compute the list of OSes.
1896

1897
    """
1898
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
1899
    node_data = self.rpc.call_os_diagnose(valid_nodes)
1900
    if node_data == False:
1901
      raise errors.OpExecError("Can't gather the list of OSes")
1902
    pol = self._DiagnoseByOS(valid_nodes, node_data)
1903
    output = []
1904
    for os_name, os_data in pol.iteritems():
1905
      row = []
1906
      for field in self.op.output_fields:
1907
        if field == "name":
1908
          val = os_name
1909
        elif field == "valid":
1910
          val = utils.all([osl and osl[0] for osl in os_data.values()])
1911
        elif field == "node_status":
1912
          val = {}
1913
          for node_name, nos_list in os_data.iteritems():
1914
            val[node_name] = [(v.status, v.path) for v in nos_list]
1915
        else:
1916
          raise errors.ParameterError(field)
1917
        row.append(val)
1918
      output.append(row)
1919

    
1920
    return output
1921

    
1922

    
1923
class LURemoveNode(LogicalUnit):
1924
  """Logical unit for removing a node.
1925

1926
  """
1927
  HPATH = "node-remove"
1928
  HTYPE = constants.HTYPE_NODE
1929
  _OP_REQP = ["node_name"]
1930

    
1931
  def BuildHooksEnv(self):
1932
    """Build hooks env.
1933

1934
    This doesn't run on the target node in the pre phase as a failed
1935
    node would then be impossible to remove.
1936

1937
    """
1938
    env = {
1939
      "OP_TARGET": self.op.node_name,
1940
      "NODE_NAME": self.op.node_name,
1941
      }
1942
    all_nodes = self.cfg.GetNodeList()
1943
    all_nodes.remove(self.op.node_name)
1944
    return env, all_nodes, all_nodes
1945

    
1946
  def CheckPrereq(self):
1947
    """Check prerequisites.
1948

1949
    This checks:
1950
     - the node exists in the configuration
1951
     - it does not have primary or secondary instances
1952
     - it's not the master
1953

1954
    Any errors are signaled by raising errors.OpPrereqError.
1955

1956
    """
1957
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
1958
    if node is None:
1959
      raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name)
1960

    
1961
    instance_list = self.cfg.GetInstanceList()
1962

    
1963
    masternode = self.cfg.GetMasterNode()
1964
    if node.name == masternode:
1965
      raise errors.OpPrereqError("Node is the master node,"
1966
                                 " you need to failover first.")
1967

    
1968
    for instance_name in instance_list:
1969
      instance = self.cfg.GetInstanceInfo(instance_name)
1970
      if node.name in instance.all_nodes:
1971
        raise errors.OpPrereqError("Instance %s is still running on the node,"
1972
                                   " please remove first." % instance_name)
1973
    self.op.node_name = node.name
1974
    self.node = node
1975

    
1976
  def Exec(self, feedback_fn):
1977
    """Removes the node from the cluster.
1978

1979
    """
1980
    node = self.node
1981
    logging.info("Stopping the node daemon and removing configs from node %s",
1982
                 node.name)
1983

    
1984
    self.context.RemoveNode(node.name)
1985

    
1986
    self.rpc.call_node_leave_cluster(node.name)
1987

    
1988
    # Promote nodes to master candidate as needed
1989
    _AdjustCandidatePool(self)
1990

    
1991

    
1992
class LUQueryNodes(NoHooksLU):
1993
  """Logical unit for querying nodes.
1994

1995
  """
1996
  _OP_REQP = ["output_fields", "names", "use_locking"]
1997
  REQ_BGL = False
1998
  _FIELDS_DYNAMIC = utils.FieldSet(
1999
    "dtotal", "dfree",
2000
    "mtotal", "mnode", "mfree",
2001
    "bootid",
2002
    "ctotal", "cnodes", "csockets",
2003
    )
2004

    
2005
  _FIELDS_STATIC = utils.FieldSet(
2006
    "name", "pinst_cnt", "sinst_cnt",
2007
    "pinst_list", "sinst_list",
2008
    "pip", "sip", "tags",
2009
    "serial_no",
2010
    "master_candidate",
2011
    "master",
2012
    "offline",
2013
    "drained",
2014
    "role",
2015
    )
2016

    
2017
  def ExpandNames(self):
2018
    _CheckOutputFields(static=self._FIELDS_STATIC,
2019
                       dynamic=self._FIELDS_DYNAMIC,
2020
                       selected=self.op.output_fields)
2021

    
2022
    self.needed_locks = {}
2023
    self.share_locks[locking.LEVEL_NODE] = 1
2024

    
2025
    if self.op.names:
2026
      self.wanted = _GetWantedNodes(self, self.op.names)
2027
    else:
2028
      self.wanted = locking.ALL_SET
2029

    
2030
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
2031
    self.do_locking = self.do_node_query and self.op.use_locking
2032
    if self.do_locking:
2033
      # if we don't request only static fields, we need to lock the nodes
2034
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
2035

    
2036

    
2037
  def CheckPrereq(self):
2038
    """Check prerequisites.
2039

2040
    """
2041
    # The validation of the node list is done in the _GetWantedNodes,
2042
    # if non empty, and if empty, there's no validation to do
2043
    pass
2044

    
2045
  def Exec(self, feedback_fn):
2046
    """Computes the list of nodes and their attributes.
2047

2048
    """
2049
    all_info = self.cfg.GetAllNodesInfo()
2050
    if self.do_locking:
2051
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
2052
    elif self.wanted != locking.ALL_SET:
2053
      nodenames = self.wanted
2054
      missing = set(nodenames).difference(all_info.keys())
2055
      if missing:
2056
        raise errors.OpExecError(
2057
          "Some nodes were removed before retrieving their data: %s" % missing)
2058
    else:
2059
      nodenames = all_info.keys()
2060

    
2061
    nodenames = utils.NiceSort(nodenames)
2062
    nodelist = [all_info[name] for name in nodenames]
2063

    
2064
    # begin data gathering
2065

    
2066
    if self.do_node_query:
2067
      live_data = {}
2068
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
2069
                                          self.cfg.GetHypervisorType())
2070
      for name in nodenames:
2071
        nodeinfo = node_data[name]
2072
        if not nodeinfo.failed and nodeinfo.data:
2073
          nodeinfo = nodeinfo.data
2074
          fn = utils.TryConvert
2075
          live_data[name] = {
2076
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
2077
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
2078
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
2079
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
2080
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
2081
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
2082
            "bootid": nodeinfo.get('bootid', None),
2083
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
2084
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
2085
            }
2086
        else:
2087
          live_data[name] = {}
2088
    else:
2089
      live_data = dict.fromkeys(nodenames, {})
2090

    
2091
    node_to_primary = dict([(name, set()) for name in nodenames])
2092
    node_to_secondary = dict([(name, set()) for name in nodenames])
2093

    
2094
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
2095
                             "sinst_cnt", "sinst_list"))
2096
    if inst_fields & frozenset(self.op.output_fields):
2097
      inst_data = self.cfg.GetAllInstancesInfo()
2098

    
2099
      for instance_name, inst in inst_data.items():
2100
        if inst.primary_node in node_to_primary:
2101
          node_to_primary[inst.primary_node].add(inst.name)
2102
        for secnode in inst.secondary_nodes:
2103
          if secnode in node_to_secondary:
2104
            node_to_secondary[secnode].add(inst.name)
2105

    
2106
    master_node = self.cfg.GetMasterNode()
2107

    
2108
    # end data gathering
2109

    
2110
    output = []
2111
    for node in nodelist:
2112
      node_output = []
2113
      for field in self.op.output_fields:
2114
        if field == "name":
2115
          val = node.name
2116
        elif field == "pinst_list":
2117
          val = list(node_to_primary[node.name])
2118
        elif field == "sinst_list":
2119
          val = list(node_to_secondary[node.name])
2120
        elif field == "pinst_cnt":
2121
          val = len(node_to_primary[node.name])
2122
        elif field == "sinst_cnt":
2123
          val = len(node_to_secondary[node.name])
2124
        elif field == "pip":
2125
          val = node.primary_ip
2126
        elif field == "sip":
2127
          val = node.secondary_ip
2128
        elif field == "tags":
2129
          val = list(node.GetTags())
2130
        elif field == "serial_no":
2131
          val = node.serial_no
2132
        elif field == "master_candidate":
2133
          val = node.master_candidate
2134
        elif field == "master":
2135
          val = node.name == master_node
2136
        elif field == "offline":
2137
          val = node.offline
2138
        elif field == "drained":
2139
          val = node.drained
2140
        elif self._FIELDS_DYNAMIC.Matches(field):
2141
          val = live_data[node.name].get(field, None)
2142
        elif field == "role":
2143
          if node.name == master_node:
2144
            val = "M"
2145
          elif node.master_candidate:
2146
            val = "C"
2147
          elif node.drained:
2148
            val = "D"
2149
          elif node.offline:
2150
            val = "O"
2151
          else:
2152
            val = "R"
2153
        else:
2154
          raise errors.ParameterError(field)
2155
        node_output.append(val)
2156
      output.append(node_output)
2157

    
2158
    return output
2159

    
2160

    
2161
class LUQueryNodeVolumes(NoHooksLU):
2162
  """Logical unit for getting volumes on node(s).
2163

2164
  """
2165
  _OP_REQP = ["nodes", "output_fields"]
2166
  REQ_BGL = False
2167
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
2168
  _FIELDS_STATIC = utils.FieldSet("node")
2169

    
2170
  def ExpandNames(self):
2171
    _CheckOutputFields(static=self._FIELDS_STATIC,
2172
                       dynamic=self._FIELDS_DYNAMIC,
2173
                       selected=self.op.output_fields)
2174

    
2175
    self.needed_locks = {}
2176
    self.share_locks[locking.LEVEL_NODE] = 1
2177
    if not self.op.nodes:
2178
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2179
    else:
2180
      self.needed_locks[locking.LEVEL_NODE] = \
2181
        _GetWantedNodes(self, self.op.nodes)
2182

    
2183
  def CheckPrereq(self):
2184
    """Check prerequisites.
2185

2186
    This checks that the fields required are valid output fields.
2187

2188
    """
2189
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
2190

    
2191
  def Exec(self, feedback_fn):
2192
    """Computes the list of nodes and their attributes.
2193

2194
    """
2195
    nodenames = self.nodes
2196
    volumes = self.rpc.call_node_volumes(nodenames)
2197

    
2198
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
2199
             in self.cfg.GetInstanceList()]
2200

    
2201
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
2202

    
2203
    output = []
2204
    for node in nodenames:
2205
      if node not in volumes or volumes[node].failed or not volumes[node].data:
2206
        continue
2207

    
2208
      node_vols = volumes[node].data[:]
2209
      node_vols.sort(key=lambda vol: vol['dev'])
2210

    
2211
      for vol in node_vols:
2212
        node_output = []
2213
        for field in self.op.output_fields:
2214
          if field == "node":
2215
            val = node
2216
          elif field == "phys":
2217
            val = vol['dev']
2218
          elif field == "vg":
2219
            val = vol['vg']
2220
          elif field == "name":
2221
            val = vol['name']
2222
          elif field == "size":
2223
            val = int(float(vol['size']))
2224
          elif field == "instance":
2225
            for inst in ilist:
2226
              if node not in lv_by_node[inst]:
2227
                continue
2228
              if vol['name'] in lv_by_node[inst][node]:
2229
                val = inst.name
2230
                break
2231
            else:
2232
              val = '-'
2233
          else:
2234
            raise errors.ParameterError(field)
2235
          node_output.append(str(val))
2236

    
2237
        output.append(node_output)
2238

    
2239
    return output
2240

    
2241

    
2242
class LUAddNode(LogicalUnit):
2243
  """Logical unit for adding node to the cluster.
2244

2245
  """
2246
  HPATH = "node-add"
2247
  HTYPE = constants.HTYPE_NODE
2248
  _OP_REQP = ["node_name"]
2249

    
2250
  def BuildHooksEnv(self):
2251
    """Build hooks env.
2252

2253
    This will run on all nodes before, and on all nodes + the new node after.
2254

2255
    """
2256
    env = {
2257
      "OP_TARGET": self.op.node_name,
2258
      "NODE_NAME": self.op.node_name,
2259
      "NODE_PIP": self.op.primary_ip,
2260
      "NODE_SIP": self.op.secondary_ip,
2261
      }
2262
    nodes_0 = self.cfg.GetNodeList()
2263
    nodes_1 = nodes_0 + [self.op.node_name, ]
2264
    return env, nodes_0, nodes_1
2265

    
2266
  def CheckPrereq(self):
2267
    """Check prerequisites.
2268

2269
    This checks:
2270
     - the new node is not already in the config
2271
     - it is resolvable
2272
     - its parameters (single/dual homed) matches the cluster
2273

2274
    Any errors are signaled by raising errors.OpPrereqError.
2275

2276
    """
2277
    node_name = self.op.node_name
2278
    cfg = self.cfg
2279

    
2280
    dns_data = utils.HostInfo(node_name)
2281

    
2282
    node = dns_data.name
2283
    primary_ip = self.op.primary_ip = dns_data.ip
2284
    secondary_ip = getattr(self.op, "secondary_ip", None)
2285
    if secondary_ip is None:
2286
      secondary_ip = primary_ip
2287
    if not utils.IsValidIP(secondary_ip):
2288
      raise errors.OpPrereqError("Invalid secondary IP given")
2289
    self.op.secondary_ip = secondary_ip
2290

    
2291
    node_list = cfg.GetNodeList()
2292
    if not self.op.readd and node in node_list:
2293
      raise errors.OpPrereqError("Node %s is already in the configuration" %
2294
                                 node)
2295
    elif self.op.readd and node not in node_list:
2296
      raise errors.OpPrereqError("Node %s is not in the configuration" % node)
2297

    
2298
    for existing_node_name in node_list:
2299
      existing_node = cfg.GetNodeInfo(existing_node_name)
2300

    
2301
      if self.op.readd and node == existing_node_name:
2302
        if (existing_node.primary_ip != primary_ip or
2303
            existing_node.secondary_ip != secondary_ip):
2304
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
2305
                                     " address configuration as before")
2306
        continue
2307

    
2308
      if (existing_node.primary_ip == primary_ip or
2309
          existing_node.secondary_ip == primary_ip or
2310
          existing_node.primary_ip == secondary_ip or
2311
          existing_node.secondary_ip == secondary_ip):
2312
        raise errors.OpPrereqError("New node ip address(es) conflict with"
2313
                                   " existing node %s" % existing_node.name)
2314

    
2315
    # check that the type of the node (single versus dual homed) is the
2316
    # same as for the master
2317
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
2318
    master_singlehomed = myself.secondary_ip == myself.primary_ip
2319
    newbie_singlehomed = secondary_ip == primary_ip
2320
    if master_singlehomed != newbie_singlehomed:
2321
      if master_singlehomed:
2322
        raise errors.OpPrereqError("The master has no private ip but the"
2323
                                   " new node has one")
2324
      else:
2325
        raise errors.OpPrereqError("The master has a private ip but the"
2326
                                   " new node doesn't have one")
2327

    
2328
    # checks reachability
2329
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
2330
      raise errors.OpPrereqError("Node not reachable by ping")
2331

    
2332
    if not newbie_singlehomed:
2333
      # check reachability from my secondary ip to newbie's secondary ip
2334
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
2335
                           source=myself.secondary_ip):
2336
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
2337
                                   " based ping to noded port")
2338

    
2339
    cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2340
    if self.op.readd:
2341
      exceptions = [node]
2342
    else:
2343
      exceptions = []
2344
    mc_now, mc_max = self.cfg.GetMasterCandidateStats(exceptions)
2345
    # the new node will increase mc_max with one, so:
2346
    mc_max = min(mc_max + 1, cp_size)
2347
    self.master_candidate = mc_now < mc_max
2348

    
2349
    if self.op.readd:
2350
      self.new_node = self.cfg.GetNodeInfo(node)
2351
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
2352
    else:
2353
      self.new_node = objects.Node(name=node,
2354
                                   primary_ip=primary_ip,
2355
                                   secondary_ip=secondary_ip,
2356
                                   master_candidate=self.master_candidate,
2357
                                   offline=False, drained=False)
2358

    
2359
  def Exec(self, feedback_fn):
2360
    """Adds the new node to the cluster.
2361

2362
    """
2363
    new_node = self.new_node
2364
    node = new_node.name
2365

    
2366
    # for re-adds, reset the offline/drained/master-candidate flags;
2367
    # we need to reset here, otherwise offline would prevent RPC calls
2368
    # later in the procedure; this also means that if the re-add
2369
    # fails, we are left with a non-offlined, broken node
2370
    if self.op.readd:
2371
      new_node.drained = new_node.offline = False
2372
      self.LogInfo("Readding a node, the offline/drained flags were reset")
2373
      # if we demote the node, we do cleanup later in the procedure
2374
      new_node.master_candidate = self.master_candidate
2375

    
2376
    # notify the user about any possible mc promotion
2377
    if new_node.master_candidate:
2378
      self.LogInfo("Node will be a master candidate")
2379

    
2380
    # check connectivity
2381
    result = self.rpc.call_version([node])[node]
2382
    result.Raise()
2383
    if result.data:
2384
      if constants.PROTOCOL_VERSION == result.data:
2385
        logging.info("Communication to node %s fine, sw version %s match",
2386
                     node, result.data)
2387
      else:
2388
        raise errors.OpExecError("Version mismatch master version %s,"
2389
                                 " node version %s" %
2390
                                 (constants.PROTOCOL_VERSION, result.data))
2391
    else:
2392
      raise errors.OpExecError("Cannot get version from the new node")
2393

    
2394
    # setup ssh on node
2395
    logging.info("Copy ssh key to node %s", node)
2396
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
2397
    keyarray = []
2398
    keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
2399
                constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
2400
                priv_key, pub_key]
2401

    
2402
    for i in keyfiles:
2403
      f = open(i, 'r')
2404
      try:
2405
        keyarray.append(f.read())
2406
      finally:
2407
        f.close()
2408

    
2409
    result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
2410
                                    keyarray[2],
2411
                                    keyarray[3], keyarray[4], keyarray[5])
2412

    
2413
    msg = result.RemoteFailMsg()
2414
    if msg:
2415
      raise errors.OpExecError("Cannot transfer ssh keys to the"
2416
                               " new node: %s" % msg)
2417

    
2418
    # Add node to our /etc/hosts, and add key to known_hosts
2419
    if self.cfg.GetClusterInfo().modify_etc_hosts:
2420
      utils.AddHostToEtcHosts(new_node.name)
2421

    
2422
    if new_node.secondary_ip != new_node.primary_ip:
2423
      result = self.rpc.call_node_has_ip_address(new_node.name,
2424
                                                 new_node.secondary_ip)
2425
      if result.failed or not result.data:
2426
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
2427
                                 " you gave (%s). Please fix and re-run this"
2428
                                 " command." % new_node.secondary_ip)
2429

    
2430
    node_verify_list = [self.cfg.GetMasterNode()]
2431
    node_verify_param = {
2432
      'nodelist': [node],
2433
      # TODO: do a node-net-test as well?
2434
    }
2435

    
2436
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
2437
                                       self.cfg.GetClusterName())
2438
    for verifier in node_verify_list:
2439
      if result[verifier].failed or not result[verifier].data:
2440
        raise errors.OpExecError("Cannot communicate with %s's node daemon"
2441
                                 " for remote verification" % verifier)
2442
      if result[verifier].data['nodelist']:
2443
        for failed in result[verifier].data['nodelist']:
2444
          feedback_fn("ssh/hostname verification failed"
2445
                      " (checking from %s): %s" %
2446
                      (verifier, result[verifier].data['nodelist'][failed]))
2447
        raise errors.OpExecError("ssh/hostname verification failed.")
2448

    
2449
    # Distribute updated /etc/hosts and known_hosts to all nodes,
2450
    # including the node just added
2451
    myself = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
2452
    dist_nodes = self.cfg.GetNodeList()
2453
    if not self.op.readd:
2454
      dist_nodes.append(node)
2455
    if myself.name in dist_nodes:
2456
      dist_nodes.remove(myself.name)
2457

    
2458
    logging.debug("Copying hosts and known_hosts to all nodes")
2459
    for fname in (constants.ETC_HOSTS, constants.SSH_KNOWN_HOSTS_FILE):
2460
      result = self.rpc.call_upload_file(dist_nodes, fname)
2461
      for to_node, to_result in result.iteritems():
2462
        if to_result.failed or not to_result.data:
2463
          logging.error("Copy of file %s to node %s failed", fname, to_node)
2464

    
2465
    to_copy = []
2466
    enabled_hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
2467
    if constants.HTS_COPY_VNC_PASSWORD.intersection(enabled_hypervisors):
2468
      to_copy.append(constants.VNC_PASSWORD_FILE)
2469

    
2470
    for fname in to_copy:
2471
      result = self.rpc.call_upload_file([node], fname)
2472
      if result[node].failed or not result[node]:
2473
        logging.error("Could not copy file %s to node %s", fname, node)
2474

    
2475
    if self.op.readd:
2476
      self.context.ReaddNode(new_node)
2477
      # make sure we redistribute the config
2478
      self.cfg.Update(new_node)
2479
      # and make sure the new node will not have old files around
2480
      if not new_node.master_candidate:
2481
        result = self.rpc.call_node_demote_from_mc(new_node.name)
2482
        msg = result.RemoteFailMsg()
2483
        if msg:
2484
          self.LogWarning("Node failed to demote itself from master"
2485
                          " candidate status: %s" % msg)
2486
    else:
2487
      self.context.AddNode(new_node)
2488

    
2489

    
2490
class LUSetNodeParams(LogicalUnit):
2491
  """Modifies the parameters of a node.
2492

2493
  """
2494
  HPATH = "node-modify"
2495
  HTYPE = constants.HTYPE_NODE
2496
  _OP_REQP = ["node_name"]
2497
  REQ_BGL = False
2498

    
2499
  def CheckArguments(self):
2500
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2501
    if node_name is None:
2502
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
2503
    self.op.node_name = node_name
2504
    _CheckBooleanOpField(self.op, 'master_candidate')
2505
    _CheckBooleanOpField(self.op, 'offline')
2506
    _CheckBooleanOpField(self.op, 'drained')
2507
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
2508
    if all_mods.count(None) == 3:
2509
      raise errors.OpPrereqError("Please pass at least one modification")
2510
    if all_mods.count(True) > 1:
2511
      raise errors.OpPrereqError("Can't set the node into more than one"
2512
                                 " state at the same time")
2513

    
2514
  def ExpandNames(self):
2515
    self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
2516

    
2517
  def BuildHooksEnv(self):
2518
    """Build hooks env.
2519

2520
    This runs on the master node.
2521

2522
    """
2523
    env = {
2524
      "OP_TARGET": self.op.node_name,
2525
      "MASTER_CANDIDATE": str(self.op.master_candidate),
2526
      "OFFLINE": str(self.op.offline),
2527
      "DRAINED": str(self.op.drained),
2528
      }
2529
    nl = [self.cfg.GetMasterNode(),
2530
          self.op.node_name]
2531
    return env, nl, nl
2532

    
2533
  def CheckPrereq(self):
2534
    """Check prerequisites.
2535

2536
    This only checks the instance list against the existing names.
2537

2538
    """
2539
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
2540

    
2541
    if (self.op.master_candidate is not None or
2542
        self.op.drained is not None or
2543
        self.op.offline is not None):
2544
      # we can't change the master's node flags
2545
      if self.op.node_name == self.cfg.GetMasterNode():
2546
        raise errors.OpPrereqError("The master role can be changed"
2547
                                   " only via masterfailover")
2548

    
2549
    if ((self.op.master_candidate == False or self.op.offline == True or
2550
         self.op.drained == True) and node.master_candidate):
2551
      cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2552
      num_candidates, _ = self.cfg.GetMasterCandidateStats()
2553
      if num_candidates <= cp_size:
2554
        msg = ("Not enough master candidates (desired"
2555
               " %d, new value will be %d)" % (cp_size, num_candidates-1))
2556
        if self.op.force:
2557
          self.LogWarning(msg)
2558
        else:
2559
          raise errors.OpPrereqError(msg)
2560

    
2561
    if (self.op.master_candidate == True and
2562
        ((node.offline and not self.op.offline == False) or
2563
         (node.drained and not self.op.drained == False))):
2564
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
2565
                                 " to master_candidate" % node.name)
2566

    
2567
    return
2568

    
2569
  def Exec(self, feedback_fn):
2570
    """Modifies a node.
2571

2572
    """
2573
    node = self.node
2574

    
2575
    result = []
2576
    changed_mc = False
2577

    
2578
    if self.op.offline is not None:
2579
      node.offline = self.op.offline
2580
      result.append(("offline", str(self.op.offline)))
2581
      if self.op.offline == True:
2582
        if node.master_candidate:
2583
          node.master_candidate = False
2584
          changed_mc = True
2585
          result.append(("master_candidate", "auto-demotion due to offline"))
2586
        if node.drained:
2587
          node.drained = False
2588
          result.append(("drained", "clear drained status due to offline"))
2589

    
2590
    if self.op.master_candidate is not None:
2591
      node.master_candidate = self.op.master_candidate
2592
      changed_mc = True
2593
      result.append(("master_candidate", str(self.op.master_candidate)))
2594
      if self.op.master_candidate == False:
2595
        rrc = self.rpc.call_node_demote_from_mc(node.name)
2596
        msg = rrc.RemoteFailMsg()
2597
        if msg:
2598
          self.LogWarning("Node failed to demote itself: %s" % msg)
2599

    
2600
    if self.op.drained is not None:
2601
      node.drained = self.op.drained
2602
      result.append(("drained", str(self.op.drained)))
2603
      if self.op.drained == True:
2604
        if node.master_candidate:
2605
          node.master_candidate = False
2606
          changed_mc = True
2607
          result.append(("master_candidate", "auto-demotion due to drain"))
2608
          rrc = self.rpc.call_node_demote_from_mc(node.name)
2609
          msg = rrc.RemoteFailMsg()
2610
          if msg:
2611
            self.LogWarning("Node failed to demote itself: %s" % msg)
2612
        if node.offline:
2613
          node.offline = False
2614
          result.append(("offline", "clear offline status due to drain"))
2615

    
2616
    # this will trigger configuration file update, if needed
2617
    self.cfg.Update(node)
2618
    # this will trigger job queue propagation or cleanup
2619
    if changed_mc:
2620
      self.context.ReaddNode(node)
2621

    
2622
    return result
2623

    
2624

    
2625
class LUQueryClusterInfo(NoHooksLU):
2626
  """Query cluster configuration.
2627

2628
  """
2629
  _OP_REQP = []
2630
  REQ_BGL = False
2631

    
2632
  def ExpandNames(self):
2633
    self.needed_locks = {}
2634

    
2635
  def CheckPrereq(self):
2636
    """No prerequsites needed for this LU.
2637

2638
    """
2639
    pass
2640

    
2641
  def Exec(self, feedback_fn):
2642
    """Return cluster config.
2643

2644
    """
2645
    cluster = self.cfg.GetClusterInfo()
2646
    result = {
2647
      "software_version": constants.RELEASE_VERSION,
2648
      "protocol_version": constants.PROTOCOL_VERSION,
2649
      "config_version": constants.CONFIG_VERSION,
2650
      "os_api_version": constants.OS_API_VERSION,
2651
      "export_version": constants.EXPORT_VERSION,
2652
      "architecture": (platform.architecture()[0], platform.machine()),
2653
      "name": cluster.cluster_name,
2654
      "master": cluster.master_node,
2655
      "default_hypervisor": cluster.default_hypervisor,
2656
      "enabled_hypervisors": cluster.enabled_hypervisors,
2657
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
2658
                        for hypervisor_name in cluster.enabled_hypervisors]),
2659
      "beparams": cluster.beparams,
2660
      "candidate_pool_size": cluster.candidate_pool_size,
2661
      "default_bridge": cluster.default_bridge,
2662
      "master_netdev": cluster.master_netdev,
2663
      "volume_group_name": cluster.volume_group_name,
2664
      "file_storage_dir": cluster.file_storage_dir,
2665
      "tags": list(cluster.GetTags()),
2666
      }
2667

    
2668
    return result
2669

    
2670

    
2671
class LUQueryConfigValues(NoHooksLU):
2672
  """Return configuration values.
2673

2674
  """
2675
  _OP_REQP = []
2676
  REQ_BGL = False
2677
  _FIELDS_DYNAMIC = utils.FieldSet()
2678
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag")
2679

    
2680
  def ExpandNames(self):
2681
    self.needed_locks = {}
2682

    
2683
    _CheckOutputFields(static=self._FIELDS_STATIC,
2684
                       dynamic=self._FIELDS_DYNAMIC,
2685
                       selected=self.op.output_fields)
2686

    
2687
  def CheckPrereq(self):
2688
    """No prerequisites.
2689

2690
    """
2691
    pass
2692

    
2693
  def Exec(self, feedback_fn):
2694
    """Dump a representation of the cluster config to the standard output.
2695

2696
    """
2697
    values = []
2698
    for field in self.op.output_fields:
2699
      if field == "cluster_name":
2700
        entry = self.cfg.GetClusterName()
2701
      elif field == "master_node":
2702
        entry = self.cfg.GetMasterNode()
2703
      elif field == "drain_flag":
2704
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
2705
      else:
2706
        raise errors.ParameterError(field)
2707
      values.append(entry)
2708
    return values
2709

    
2710

    
2711
class LUActivateInstanceDisks(NoHooksLU):
2712
  """Bring up an instance's disks.
2713

2714
  """
2715
  _OP_REQP = ["instance_name"]
2716
  REQ_BGL = False
2717

    
2718
  def ExpandNames(self):
2719
    self._ExpandAndLockInstance()
2720
    self.needed_locks[locking.LEVEL_NODE] = []
2721
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2722

    
2723
  def DeclareLocks(self, level):
2724
    if level == locking.LEVEL_NODE:
2725
      self._LockInstancesNodes()
2726

    
2727
  def CheckPrereq(self):
2728
    """Check prerequisites.
2729

2730
    This checks that the instance is in the cluster.
2731

2732
    """
2733
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2734
    assert self.instance is not None, \
2735
      "Cannot retrieve locked instance %s" % self.op.instance_name
2736
    _CheckNodeOnline(self, self.instance.primary_node)
2737
    if not hasattr(self.op, "ignore_size"):
2738
      self.op.ignore_size = False
2739

    
2740
  def Exec(self, feedback_fn):
2741
    """Activate the disks.
2742

2743
    """
2744
    disks_ok, disks_info = \
2745
              _AssembleInstanceDisks(self, self.instance,
2746
                                     ignore_size=self.op.ignore_size)
2747
    if not disks_ok:
2748
      raise errors.OpExecError("Cannot activate block devices")
2749

    
2750
    return disks_info
2751

    
2752

    
2753
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False,
2754
                           ignore_size=False):
2755
  """Prepare the block devices for an instance.
2756

2757
  This sets up the block devices on all nodes.
2758

2759
  @type lu: L{LogicalUnit}
2760
  @param lu: the logical unit on whose behalf we execute
2761
  @type instance: L{objects.Instance}
2762
  @param instance: the instance for whose disks we assemble
2763
  @type ignore_secondaries: boolean
2764
  @param ignore_secondaries: if true, errors on secondary nodes
2765
      won't result in an error return from the function
2766
  @type ignore_size: boolean
2767
  @param ignore_size: if true, the current known size of the disk
2768
      will not be used during the disk activation, useful for cases
2769
      when the size is wrong
2770
  @return: False if the operation failed, otherwise a list of
2771
      (host, instance_visible_name, node_visible_name)
2772
      with the mapping from node devices to instance devices
2773

2774
  """
2775
  device_info = []
2776
  disks_ok = True
2777
  iname = instance.name
2778
  # With the two passes mechanism we try to reduce the window of
2779
  # opportunity for the race condition of switching DRBD to primary
2780
  # before handshaking occured, but we do not eliminate it
2781

    
2782
  # The proper fix would be to wait (with some limits) until the
2783
  # connection has been made and drbd transitions from WFConnection
2784
  # into any other network-connected state (Connected, SyncTarget,
2785
  # SyncSource, etc.)
2786

    
2787
  # 1st pass, assemble on all nodes in secondary mode
2788
  for inst_disk in instance.disks:
2789
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2790
      if ignore_size:
2791
        node_disk = node_disk.Copy()
2792
        node_disk.UnsetSize()
2793
      lu.cfg.SetDiskID(node_disk, node)
2794
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
2795
      msg = result.RemoteFailMsg()
2796
      if msg:
2797
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2798
                           " (is_primary=False, pass=1): %s",
2799
                           inst_disk.iv_name, node, msg)
2800
        if not ignore_secondaries:
2801
          disks_ok = False
2802

    
2803
  # FIXME: race condition on drbd migration to primary
2804

    
2805
  # 2nd pass, do only the primary node
2806
  for inst_disk in instance.disks:
2807
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2808
      if node != instance.primary_node:
2809
        continue
2810
      if ignore_size:
2811
        node_disk = node_disk.Copy()
2812
        node_disk.UnsetSize()
2813
      lu.cfg.SetDiskID(node_disk, node)
2814
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
2815
      msg = result.RemoteFailMsg()
2816
      if msg:
2817
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2818
                           " (is_primary=True, pass=2): %s",
2819
                           inst_disk.iv_name, node, msg)
2820
        disks_ok = False
2821
    device_info.append((instance.primary_node, inst_disk.iv_name,
2822
                        result.payload))
2823

    
2824
  # leave the disks configured for the primary node
2825
  # this is a workaround that would be fixed better by
2826
  # improving the logical/physical id handling
2827
  for disk in instance.disks:
2828
    lu.cfg.SetDiskID(disk, instance.primary_node)
2829

    
2830
  return disks_ok, device_info
2831

    
2832

    
2833
def _StartInstanceDisks(lu, instance, force):
2834
  """Start the disks of an instance.
2835

2836
  """
2837
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
2838
                                           ignore_secondaries=force)
2839
  if not disks_ok:
2840
    _ShutdownInstanceDisks(lu, instance)
2841
    if force is not None and not force:
2842
      lu.proc.LogWarning("", hint="If the message above refers to a"
2843
                         " secondary node,"
2844
                         " you can retry the operation using '--force'.")
2845
    raise errors.OpExecError("Disk consistency error")
2846

    
2847

    
2848
class LUDeactivateInstanceDisks(NoHooksLU):
2849
  """Shutdown an instance's disks.
2850

2851
  """
2852
  _OP_REQP = ["instance_name"]
2853
  REQ_BGL = False
2854

    
2855
  def ExpandNames(self):
2856
    self._ExpandAndLockInstance()
2857
    self.needed_locks[locking.LEVEL_NODE] = []
2858
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2859

    
2860
  def DeclareLocks(self, level):
2861
    if level == locking.LEVEL_NODE:
2862
      self._LockInstancesNodes()
2863

    
2864
  def CheckPrereq(self):
2865
    """Check prerequisites.
2866

2867
    This checks that the instance is in the cluster.
2868

2869
    """
2870
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2871
    assert self.instance is not None, \
2872
      "Cannot retrieve locked instance %s" % self.op.instance_name
2873

    
2874
  def Exec(self, feedback_fn):
2875
    """Deactivate the disks
2876

2877
    """
2878
    instance = self.instance
2879
    _SafeShutdownInstanceDisks(self, instance)
2880

    
2881

    
2882
def _SafeShutdownInstanceDisks(lu, instance):
2883
  """Shutdown block devices of an instance.
2884

2885
  This function checks if an instance is running, before calling
2886
  _ShutdownInstanceDisks.
2887

2888
  """
2889
  ins_l = lu.rpc.call_instance_list([instance.primary_node],
2890
                                      [instance.hypervisor])
2891
  ins_l = ins_l[instance.primary_node]
2892
  if ins_l.failed or not isinstance(ins_l.data, list):
2893
    raise errors.OpExecError("Can't contact node '%s'" %
2894
                             instance.primary_node)
2895

    
2896
  if instance.name in ins_l.data:
2897
    raise errors.OpExecError("Instance is running, can't shutdown"
2898
                             " block devices.")
2899

    
2900
  _ShutdownInstanceDisks(lu, instance)
2901

    
2902

    
2903
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
2904
  """Shutdown block devices of an instance.
2905

2906
  This does the shutdown on all nodes of the instance.
2907

2908
  If the ignore_primary is false, errors on the primary node are
2909
  ignored.
2910

2911
  """
2912
  all_result = True
2913
  for disk in instance.disks:
2914
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
2915
      lu.cfg.SetDiskID(top_disk, node)
2916
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
2917
      msg = result.RemoteFailMsg()
2918
      if msg:
2919
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
2920
                      disk.iv_name, node, msg)
2921
        if not ignore_primary or node != instance.primary_node:
2922
          all_result = False
2923
  return all_result
2924

    
2925

    
2926
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
2927
  """Checks if a node has enough free memory.
2928

2929
  This function check if a given node has the needed amount of free
2930
  memory. In case the node has less memory or we cannot get the
2931
  information from the node, this function raise an OpPrereqError
2932
  exception.
2933

2934
  @type lu: C{LogicalUnit}
2935
  @param lu: a logical unit from which we get configuration data
2936
  @type node: C{str}
2937
  @param node: the node to check
2938
  @type reason: C{str}
2939
  @param reason: string to use in the error message
2940
  @type requested: C{int}
2941
  @param requested: the amount of memory in MiB to check for
2942
  @type hypervisor_name: C{str}
2943
  @param hypervisor_name: the hypervisor to ask for memory stats
2944
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
2945
      we cannot check the node
2946

2947
  """
2948
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
2949
  nodeinfo[node].Raise()
2950
  free_mem = nodeinfo[node].data.get('memory_free')
2951
  if not isinstance(free_mem, int):
2952
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
2953
                             " was '%s'" % (node, free_mem))
2954
  if requested > free_mem:
2955
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
2956
                             " needed %s MiB, available %s MiB" %
2957
                             (node, reason, requested, free_mem))
2958

    
2959

    
2960
class LUStartupInstance(LogicalUnit):
2961
  """Starts an instance.
2962

2963
  """
2964
  HPATH = "instance-start"
2965
  HTYPE = constants.HTYPE_INSTANCE
2966
  _OP_REQP = ["instance_name", "force"]
2967
  REQ_BGL = False
2968

    
2969
  def ExpandNames(self):
2970
    self._ExpandAndLockInstance()
2971

    
2972
  def BuildHooksEnv(self):
2973
    """Build hooks env.
2974

2975
    This runs on master, primary and secondary nodes of the instance.
2976

2977
    """
2978
    env = {
2979
      "FORCE": self.op.force,
2980
      }
2981
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2982
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2983
    return env, nl, nl
2984

    
2985
  def CheckPrereq(self):
2986
    """Check prerequisites.
2987

2988
    This checks that the instance is in the cluster.
2989

2990
    """
2991
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2992
    assert self.instance is not None, \
2993
      "Cannot retrieve locked instance %s" % self.op.instance_name
2994

    
2995
    # extra beparams
2996
    self.beparams = getattr(self.op, "beparams", {})
2997
    if self.beparams:
2998
      if not isinstance(self.beparams, dict):
2999
        raise errors.OpPrereqError("Invalid beparams passed: %s, expected"
3000
                                   " dict" % (type(self.beparams), ))
3001
      # fill the beparams dict
3002
      utils.ForceDictType(self.beparams, constants.BES_PARAMETER_TYPES)
3003
      self.op.beparams = self.beparams
3004

    
3005
    # extra hvparams
3006
    self.hvparams = getattr(self.op, "hvparams", {})
3007
    if self.hvparams:
3008
      if not isinstance(self.hvparams, dict):
3009
        raise errors.OpPrereqError("Invalid hvparams passed: %s, expected"
3010
                                   " dict" % (type(self.hvparams), ))
3011

    
3012
      # check hypervisor parameter syntax (locally)
3013
      cluster = self.cfg.GetClusterInfo()
3014
      utils.ForceDictType(self.hvparams, constants.HVS_PARAMETER_TYPES)
3015
      filled_hvp = cluster.FillDict(cluster.hvparams[instance.hypervisor],
3016
                                    instance.hvparams)
3017
      filled_hvp.update(self.hvparams)
3018
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
3019
      hv_type.CheckParameterSyntax(filled_hvp)
3020
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
3021
      self.op.hvparams = self.hvparams
3022

    
3023
    _CheckNodeOnline(self, instance.primary_node)
3024

    
3025
    bep = self.cfg.GetClusterInfo().FillBE(instance)
3026
    # check bridges existence
3027
    _CheckInstanceBridgesExist(self, instance)
3028

    
3029
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3030
                                              instance.name,
3031
                                              instance.hypervisor)
3032
    remote_info.Raise()
3033
    if not remote_info.data:
3034
      _CheckNodeFreeMemory(self, instance.primary_node,
3035
                           "starting instance %s" % instance.name,
3036
                           bep[constants.BE_MEMORY], instance.hypervisor)
3037

    
3038
  def Exec(self, feedback_fn):
3039
    """Start the instance.
3040

3041
    """
3042
    instance = self.instance
3043
    force = self.op.force
3044

    
3045
    self.cfg.MarkInstanceUp(instance.name)
3046

    
3047
    node_current = instance.primary_node
3048

    
3049
    _StartInstanceDisks(self, instance, force)
3050

    
3051
    result = self.rpc.call_instance_start(node_current, instance,
3052
                                          self.hvparams, self.beparams)
3053
    msg = result.RemoteFailMsg()
3054
    if msg:
3055
      _ShutdownInstanceDisks(self, instance)
3056
      raise errors.OpExecError("Could not start instance: %s" % msg)
3057

    
3058

    
3059
class LURebootInstance(LogicalUnit):
3060
  """Reboot an instance.
3061

3062
  """
3063
  HPATH = "instance-reboot"
3064
  HTYPE = constants.HTYPE_INSTANCE
3065
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
3066
  REQ_BGL = False
3067

    
3068
  def ExpandNames(self):
3069
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
3070
                                   constants.INSTANCE_REBOOT_HARD,
3071
                                   constants.INSTANCE_REBOOT_FULL]:
3072
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
3073
                                  (constants.INSTANCE_REBOOT_SOFT,
3074
                                   constants.INSTANCE_REBOOT_HARD,
3075
                                   constants.INSTANCE_REBOOT_FULL))
3076
    self._ExpandAndLockInstance()
3077

    
3078
  def BuildHooksEnv(self):
3079
    """Build hooks env.
3080

3081
    This runs on master, primary and secondary nodes of the instance.
3082

3083
    """
3084
    env = {
3085
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
3086
      "REBOOT_TYPE": self.op.reboot_type,
3087
      }
3088
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3089
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3090
    return env, nl, nl
3091

    
3092
  def CheckPrereq(self):
3093
    """Check prerequisites.
3094

3095
    This checks that the instance is in the cluster.
3096

3097
    """
3098
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3099
    assert self.instance is not None, \
3100
      "Cannot retrieve locked instance %s" % self.op.instance_name
3101

    
3102
    _CheckNodeOnline(self, instance.primary_node)
3103

    
3104
    # check bridges existence
3105
    _CheckInstanceBridgesExist(self, instance)
3106

    
3107
  def Exec(self, feedback_fn):
3108
    """Reboot the instance.
3109

3110
    """
3111
    instance = self.instance
3112
    ignore_secondaries = self.op.ignore_secondaries
3113
    reboot_type = self.op.reboot_type
3114

    
3115
    node_current = instance.primary_node
3116

    
3117
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
3118
                       constants.INSTANCE_REBOOT_HARD]:
3119
      for disk in instance.disks:
3120
        self.cfg.SetDiskID(disk, node_current)
3121
      result = self.rpc.call_instance_reboot(node_current, instance,
3122
                                             reboot_type)
3123
      msg = result.RemoteFailMsg()
3124
      if msg:
3125
        raise errors.OpExecError("Could not reboot instance: %s" % msg)
3126
    else:
3127
      result = self.rpc.call_instance_shutdown(node_current, instance)
3128
      msg = result.RemoteFailMsg()
3129
      if msg:
3130
        raise errors.OpExecError("Could not shutdown instance for"
3131
                                 " full reboot: %s" % msg)
3132
      _ShutdownInstanceDisks(self, instance)
3133
      _StartInstanceDisks(self, instance, ignore_secondaries)
3134
      result = self.rpc.call_instance_start(node_current, instance, None, None)
3135
      msg = result.RemoteFailMsg()
3136
      if msg:
3137
        _ShutdownInstanceDisks(self, instance)
3138
        raise errors.OpExecError("Could not start instance for"
3139
                                 " full reboot: %s" % msg)
3140

    
3141
    self.cfg.MarkInstanceUp(instance.name)
3142

    
3143

    
3144
class LUShutdownInstance(LogicalUnit):
3145
  """Shutdown an instance.
3146

3147
  """
3148
  HPATH = "instance-stop"
3149
  HTYPE = constants.HTYPE_INSTANCE
3150
  _OP_REQP = ["instance_name"]
3151
  REQ_BGL = False
3152

    
3153
  def ExpandNames(self):
3154
    self._ExpandAndLockInstance()
3155

    
3156
  def BuildHooksEnv(self):
3157
    """Build hooks env.
3158

3159
    This runs on master, primary and secondary nodes of the instance.
3160

3161
    """
3162
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3163
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3164
    return env, nl, nl
3165

    
3166
  def CheckPrereq(self):
3167
    """Check prerequisites.
3168

3169
    This checks that the instance is in the cluster.
3170

3171
    """
3172
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3173
    assert self.instance is not None, \
3174
      "Cannot retrieve locked instance %s" % self.op.instance_name
3175
    _CheckNodeOnline(self, self.instance.primary_node)
3176

    
3177
  def Exec(self, feedback_fn):
3178
    """Shutdown the instance.
3179

3180
    """
3181
    instance = self.instance
3182
    node_current = instance.primary_node
3183
    self.cfg.MarkInstanceDown(instance.name)
3184
    result = self.rpc.call_instance_shutdown(node_current, instance)
3185
    msg = result.RemoteFailMsg()
3186
    if msg:
3187
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
3188

    
3189
    _ShutdownInstanceDisks(self, instance)
3190

    
3191

    
3192
class LUReinstallInstance(LogicalUnit):
3193
  """Reinstall an instance.
3194

3195
  """
3196
  HPATH = "instance-reinstall"
3197
  HTYPE = constants.HTYPE_INSTANCE
3198
  _OP_REQP = ["instance_name"]
3199
  REQ_BGL = False
3200

    
3201
  def ExpandNames(self):
3202
    self._ExpandAndLockInstance()
3203

    
3204
  def BuildHooksEnv(self):
3205
    """Build hooks env.
3206

3207
    This runs on master, primary and secondary nodes of the instance.
3208

3209
    """
3210
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3211
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3212
    return env, nl, nl
3213

    
3214
  def CheckPrereq(self):
3215
    """Check prerequisites.
3216

3217
    This checks that the instance is in the cluster and is not running.
3218

3219
    """
3220
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3221
    assert instance is not None, \
3222
      "Cannot retrieve locked instance %s" % self.op.instance_name
3223
    _CheckNodeOnline(self, instance.primary_node)
3224

    
3225
    if instance.disk_template == constants.DT_DISKLESS:
3226
      raise errors.OpPrereqError("Instance '%s' has no disks" %
3227
                                 self.op.instance_name)
3228
    if instance.admin_up:
3229
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
3230
                                 self.op.instance_name)
3231
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3232
                                              instance.name,
3233
                                              instance.hypervisor)
3234
    remote_info.Raise()
3235
    if remote_info.data:
3236
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
3237
                                 (self.op.instance_name,
3238
                                  instance.primary_node))
3239

    
3240
    self.op.os_type = getattr(self.op, "os_type", None)
3241
    if self.op.os_type is not None:
3242
      # OS verification
3243
      pnode = self.cfg.GetNodeInfo(
3244
        self.cfg.ExpandNodeName(instance.primary_node))
3245
      if pnode is None:
3246
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
3247
                                   self.op.pnode)
3248
      result = self.rpc.call_os_get(pnode.name, self.op.os_type)
3249
      result.Raise()
3250
      if not isinstance(result.data, objects.OS):
3251
        raise errors.OpPrereqError("OS '%s' not in supported OS list for"
3252
                                   " primary node"  % self.op.os_type)
3253

    
3254
    self.instance = instance
3255

    
3256
  def Exec(self, feedback_fn):
3257
    """Reinstall the instance.
3258

3259
    """
3260
    inst = self.instance
3261

    
3262
    if self.op.os_type is not None:
3263
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
3264
      inst.os = self.op.os_type
3265
      self.cfg.Update(inst)
3266

    
3267
    _StartInstanceDisks(self, inst, None)
3268
    try:
3269
      feedback_fn("Running the instance OS create scripts...")
3270
      result = self.rpc.call_instance_os_add(inst.primary_node, inst)
3271
      msg = result.RemoteFailMsg()
3272
      if msg:
3273
        raise errors.OpExecError("Could not install OS for instance %s"
3274
                                 " on node %s: %s" %
3275
                                 (inst.name, inst.primary_node, msg))
3276
    finally:
3277
      _ShutdownInstanceDisks(self, inst)
3278

    
3279

    
3280
class LURenameInstance(LogicalUnit):
3281
  """Rename an instance.
3282

3283
  """
3284
  HPATH = "instance-rename"
3285
  HTYPE = constants.HTYPE_INSTANCE
3286
  _OP_REQP = ["instance_name", "new_name"]
3287

    
3288
  def BuildHooksEnv(self):
3289
    """Build hooks env.
3290

3291
    This runs on master, primary and secondary nodes of the instance.
3292

3293
    """
3294
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3295
    env["INSTANCE_NEW_NAME"] = self.op.new_name
3296
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3297
    return env, nl, nl
3298

    
3299
  def CheckPrereq(self):
3300
    """Check prerequisites.
3301

3302
    This checks that the instance is in the cluster and is not running.
3303

3304
    """
3305
    instance = self.cfg.GetInstanceInfo(
3306
      self.cfg.ExpandInstanceName(self.op.instance_name))
3307
    if instance is None:
3308
      raise errors.OpPrereqError("Instance '%s' not known" %
3309
                                 self.op.instance_name)
3310
    _CheckNodeOnline(self, instance.primary_node)
3311

    
3312
    if instance.admin_up:
3313
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
3314
                                 self.op.instance_name)
3315
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3316
                                              instance.name,
3317
                                              instance.hypervisor)
3318
    remote_info.Raise()
3319
    if remote_info.data:
3320
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
3321
                                 (self.op.instance_name,
3322
                                  instance.primary_node))
3323
    self.instance = instance
3324

    
3325
    # new name verification
3326
    name_info = utils.HostInfo(self.op.new_name)
3327

    
3328
    self.op.new_name = new_name = name_info.name
3329
    instance_list = self.cfg.GetInstanceList()
3330
    if new_name in instance_list:
3331
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
3332
                                 new_name)
3333

    
3334
    if not getattr(self.op, "ignore_ip", False):
3335
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
3336
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
3337
                                   (name_info.ip, new_name))
3338

    
3339

    
3340
  def Exec(self, feedback_fn):
3341
    """Reinstall the instance.
3342

3343
    """
3344
    inst = self.instance
3345
    old_name = inst.name
3346

    
3347
    if inst.disk_template == constants.DT_FILE:
3348
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
3349

    
3350
    self.cfg.RenameInstance(inst.name, self.op.new_name)
3351
    # Change the instance lock. This is definitely safe while we hold the BGL
3352
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
3353
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
3354

    
3355
    # re-read the instance from the configuration after rename
3356
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
3357

    
3358
    if inst.disk_template == constants.DT_FILE:
3359
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
3360
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
3361
                                                     old_file_storage_dir,
3362
                                                     new_file_storage_dir)
3363
      result.Raise()
3364
      if not result.data:
3365
        raise errors.OpExecError("Could not connect to node '%s' to rename"
3366
                                 " directory '%s' to '%s' (but the instance"
3367
                                 " has been renamed in Ganeti)" % (
3368
                                 inst.primary_node, old_file_storage_dir,
3369
                                 new_file_storage_dir))
3370

    
3371
      if not result.data[0]:
3372
        raise errors.OpExecError("Could not rename directory '%s' to '%s'"
3373
                                 " (but the instance has been renamed in"
3374
                                 " Ganeti)" % (old_file_storage_dir,
3375
                                               new_file_storage_dir))
3376

    
3377
    _StartInstanceDisks(self, inst, None)
3378
    try:
3379
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
3380
                                                 old_name)
3381
      msg = result.RemoteFailMsg()
3382
      if msg:
3383
        msg = ("Could not run OS rename script for instance %s on node %s"
3384
               " (but the instance has been renamed in Ganeti): %s" %
3385
               (inst.name, inst.primary_node, msg))
3386
        self.proc.LogWarning(msg)
3387
    finally:
3388
      _ShutdownInstanceDisks(self, inst)
3389

    
3390

    
3391
class LURemoveInstance(LogicalUnit):
3392
  """Remove an instance.
3393

3394
  """
3395
  HPATH = "instance-remove"
3396
  HTYPE = constants.HTYPE_INSTANCE
3397
  _OP_REQP = ["instance_name", "ignore_failures"]
3398
  REQ_BGL = False
3399

    
3400
  def ExpandNames(self):
3401
    self._ExpandAndLockInstance()
3402
    self.needed_locks[locking.LEVEL_NODE] = []
3403
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3404

    
3405
  def DeclareLocks(self, level):
3406
    if level == locking.LEVEL_NODE:
3407
      self._LockInstancesNodes()
3408

    
3409
  def BuildHooksEnv(self):
3410
    """Build hooks env.
3411

3412
    This runs on master, primary and secondary nodes of the instance.
3413

3414
    """
3415
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3416
    nl = [self.cfg.GetMasterNode()]
3417
    return env, nl, nl
3418

    
3419
  def CheckPrereq(self):
3420
    """Check prerequisites.
3421

3422
    This checks that the instance is in the cluster.
3423

3424
    """
3425
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3426
    assert self.instance is not None, \
3427
      "Cannot retrieve locked instance %s" % self.op.instance_name
3428

    
3429
  def Exec(self, feedback_fn):
3430
    """Remove the instance.
3431

3432
    """
3433
    instance = self.instance
3434
    logging.info("Shutting down instance %s on node %s",
3435
                 instance.name, instance.primary_node)
3436

    
3437
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance)
3438
    msg = result.RemoteFailMsg()
3439
    if msg:
3440
      if self.op.ignore_failures:
3441
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
3442
      else:
3443
        raise errors.OpExecError("Could not shutdown instance %s on"
3444
                                 " node %s: %s" %
3445
                                 (instance.name, instance.primary_node, msg))
3446

    
3447
    logging.info("Removing block devices for instance %s", instance.name)
3448

    
3449
    if not _RemoveDisks(self, instance):
3450
      if self.op.ignore_failures:
3451
        feedback_fn("Warning: can't remove instance's disks")
3452
      else:
3453
        raise errors.OpExecError("Can't remove instance's disks")
3454

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

    
3457
    self.cfg.RemoveInstance(instance.name)
3458
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
3459

    
3460

    
3461
class LUQueryInstances(NoHooksLU):
3462
  """Logical unit for querying instances.
3463

3464
  """
3465
  _OP_REQP = ["output_fields", "names", "use_locking"]
3466
  REQ_BGL = False
3467
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
3468
                                    "admin_state",
3469
                                    "disk_template", "ip", "mac", "bridge",
3470
                                    "sda_size", "sdb_size", "vcpus", "tags",
3471
                                    "network_port", "beparams",
3472
                                    r"(disk)\.(size)/([0-9]+)",
3473
                                    r"(disk)\.(sizes)", "disk_usage",
3474
                                    r"(nic)\.(mac|ip|bridge)/([0-9]+)",
3475
                                    r"(nic)\.(macs|ips|bridges)",
3476
                                    r"(disk|nic)\.(count)",
3477
                                    "serial_no", "hypervisor", "hvparams",] +
3478
                                  ["hv/%s" % name
3479
                                   for name in constants.HVS_PARAMETERS] +
3480
                                  ["be/%s" % name
3481
                                   for name in constants.BES_PARAMETERS])
3482
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
3483

    
3484

    
3485
  def ExpandNames(self):
3486
    _CheckOutputFields(static=self._FIELDS_STATIC,
3487
                       dynamic=self._FIELDS_DYNAMIC,
3488
                       selected=self.op.output_fields)
3489

    
3490
    self.needed_locks = {}
3491
    self.share_locks[locking.LEVEL_INSTANCE] = 1
3492
    self.share_locks[locking.LEVEL_NODE] = 1
3493

    
3494
    if self.op.names:
3495
      self.wanted = _GetWantedInstances(self, self.op.names)
3496
    else:
3497
      self.wanted = locking.ALL_SET
3498

    
3499
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3500
    self.do_locking = self.do_node_query and self.op.use_locking
3501
    if self.do_locking:
3502
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
3503
      self.needed_locks[locking.LEVEL_NODE] = []
3504
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3505

    
3506
  def DeclareLocks(self, level):
3507
    if level == locking.LEVEL_NODE and self.do_locking:
3508
      self._LockInstancesNodes()
3509

    
3510
  def CheckPrereq(self):
3511
    """Check prerequisites.
3512

3513
    """
3514
    pass
3515

    
3516
  def Exec(self, feedback_fn):
3517
    """Computes the list of nodes and their attributes.
3518

3519
    """
3520
    all_info = self.cfg.GetAllInstancesInfo()
3521
    if self.wanted == locking.ALL_SET:
3522
      # caller didn't specify instance names, so ordering is not important
3523
      if self.do_locking:
3524
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
3525
      else:
3526
        instance_names = all_info.keys()
3527
      instance_names = utils.NiceSort(instance_names)
3528
    else:
3529
      # caller did specify names, so we must keep the ordering
3530
      if self.do_locking:
3531
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
3532
      else:
3533
        tgt_set = all_info.keys()
3534
      missing = set(self.wanted).difference(tgt_set)
3535
      if missing:
3536
        raise errors.OpExecError("Some instances were removed before"
3537
                                 " retrieving their data: %s" % missing)
3538
      instance_names = self.wanted
3539

    
3540
    instance_list = [all_info[iname] for iname in instance_names]
3541

    
3542
    # begin data gathering
3543

    
3544
    nodes = frozenset([inst.primary_node for inst in instance_list])
3545
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
3546

    
3547
    bad_nodes = []
3548
    off_nodes = []
3549
    if self.do_node_query:
3550
      live_data = {}
3551
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
3552
      for name in nodes:
3553
        result = node_data[name]
3554
        if result.offline:
3555
          # offline nodes will be in both lists
3556
          off_nodes.append(name)
3557
        if result.failed:
3558
          bad_nodes.append(name)
3559
        else:
3560
          if result.data:
3561
            live_data.update(result.data)
3562
            # else no instance is alive
3563
    else:
3564
      live_data = dict([(name, {}) for name in instance_names])
3565

    
3566
    # end data gathering
3567

    
3568
    HVPREFIX = "hv/"
3569
    BEPREFIX = "be/"
3570
    output = []
3571
    for instance in instance_list:
3572
      iout = []
3573
      i_hv = self.cfg.GetClusterInfo().FillHV(instance)
3574
      i_be = self.cfg.GetClusterInfo().FillBE(instance)
3575
      for field in self.op.output_fields:
3576
        st_match = self._FIELDS_STATIC.Matches(field)
3577
        if field == "name":
3578
          val = instance.name
3579
        elif field == "os":
3580
          val = instance.os
3581
        elif field == "pnode":
3582
          val = instance.primary_node
3583
        elif field == "snodes":
3584
          val = list(instance.secondary_nodes)
3585
        elif field == "admin_state":
3586
          val = instance.admin_up
3587
        elif field == "oper_state":
3588
          if instance.primary_node in bad_nodes:
3589
            val = None
3590
          else:
3591
            val = bool(live_data.get(instance.name))
3592
        elif field == "status":
3593
          if instance.primary_node in off_nodes:
3594
            val = "ERROR_nodeoffline"
3595
          elif instance.primary_node in bad_nodes:
3596
            val = "ERROR_nodedown"
3597
          else:
3598
            running = bool(live_data.get(instance.name))
3599
            if running:
3600
              if instance.admin_up:
3601
                val = "running"
3602
              else:
3603
                val = "ERROR_up"
3604
            else:
3605
              if instance.admin_up:
3606
                val = "ERROR_down"
3607
              else:
3608
                val = "ADMIN_down"
3609
        elif field == "oper_ram":
3610
          if instance.primary_node in bad_nodes:
3611
            val = None
3612
          elif instance.name in live_data:
3613
            val = live_data[instance.name].get("memory", "?")
3614
          else:
3615
            val = "-"
3616
        elif field == "vcpus":
3617
          val = i_be[constants.BE_VCPUS]
3618
        elif field == "disk_template":
3619
          val = instance.disk_template
3620
        elif field == "ip":
3621
          if instance.nics:
3622
            val = instance.nics[0].ip
3623
          else:
3624
            val = None
3625
        elif field == "bridge":
3626
          if instance.nics:
3627
            val = instance.nics[0].bridge
3628
          else:
3629
            val = None
3630
        elif field == "mac":
3631
          if instance.nics:
3632
            val = instance.nics[0].mac
3633
          else:
3634
            val = None
3635
        elif field == "sda_size" or field == "sdb_size":
3636
          idx = ord(field[2]) - ord('a')
3637
          try:
3638
            val = instance.FindDisk(idx).size
3639
          except errors.OpPrereqError:
3640
            val = None
3641
        elif field == "disk_usage": # total disk usage per node
3642
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
3643
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
3644
        elif field == "tags":
3645
          val = list(instance.GetTags())
3646
        elif field == "serial_no":
3647
          val = instance.serial_no
3648
        elif field == "network_port":
3649
          val = instance.network_port
3650
        elif field == "hypervisor":
3651
          val = instance.hypervisor
3652
        elif field == "hvparams":
3653
          val = i_hv
3654
        elif (field.startswith(HVPREFIX) and
3655
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS):
3656
          val = i_hv.get(field[len(HVPREFIX):], None)
3657
        elif field == "beparams":
3658
          val = i_be
3659
        elif (field.startswith(BEPREFIX) and
3660
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
3661
          val = i_be.get(field[len(BEPREFIX):], None)
3662
        elif st_match and st_match.groups():
3663
          # matches a variable list
3664
          st_groups = st_match.groups()
3665
          if st_groups and st_groups[0] == "disk":
3666
            if st_groups[1] == "count":
3667
              val = len(instance.disks)
3668
            elif st_groups[1] == "sizes":
3669
              val = [disk.size for disk in instance.disks]
3670
            elif st_groups[1] == "size":
3671
              try:
3672
                val = instance.FindDisk(st_groups[2]).size
3673
              except errors.OpPrereqError:
3674
                val = None
3675
            else:
3676
              assert False, "Unhandled disk parameter"
3677
          elif st_groups[0] == "nic":
3678
            if st_groups[1] == "count":
3679
              val = len(instance.nics)
3680
            elif st_groups[1] == "macs":
3681
              val = [nic.mac for nic in instance.nics]
3682
            elif st_groups[1] == "ips":
3683
              val = [nic.ip for nic in instance.nics]
3684
            elif st_groups[1] == "bridges":
3685
              val = [nic.bridge for nic in instance.nics]
3686
            else:
3687
              # index-based item
3688
              nic_idx = int(st_groups[2])
3689
              if nic_idx >= len(instance.nics):
3690
                val = None
3691
              else:
3692
                if st_groups[1] == "mac":
3693
                  val = instance.nics[nic_idx].mac
3694
                elif st_groups[1] == "ip":
3695
                  val = instance.nics[nic_idx].ip
3696
                elif st_groups[1] == "bridge":
3697
                  val = instance.nics[nic_idx].bridge
3698
                else:
3699
                  assert False, "Unhandled NIC parameter"
3700
          else:
3701
            assert False, ("Declared but unhandled variable parameter '%s'" %
3702
                           field)
3703
        else:
3704
          assert False, "Declared but unhandled parameter '%s'" % field
3705
        iout.append(val)
3706
      output.append(iout)
3707

    
3708
    return output
3709

    
3710

    
3711
class LUFailoverInstance(LogicalUnit):
3712
  """Failover an instance.
3713

3714
  """
3715
  HPATH = "instance-failover"
3716
  HTYPE = constants.HTYPE_INSTANCE
3717
  _OP_REQP = ["instance_name", "ignore_consistency"]
3718
  REQ_BGL = False
3719

    
3720
  def ExpandNames(self):
3721
    self._ExpandAndLockInstance()
3722
    self.needed_locks[locking.LEVEL_NODE] = []
3723
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3724

    
3725
  def DeclareLocks(self, level):
3726
    if level == locking.LEVEL_NODE:
3727
      self._LockInstancesNodes()
3728

    
3729
  def BuildHooksEnv(self):
3730
    """Build hooks env.
3731

3732
    This runs on master, primary and secondary nodes of the instance.
3733

3734
    """
3735
    env = {
3736
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
3737
      }
3738
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3739
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
3740
    return env, nl, nl
3741

    
3742
  def CheckPrereq(self):
3743
    """Check prerequisites.
3744

3745
    This checks that the instance is in the cluster.
3746

3747
    """
3748
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3749
    assert self.instance is not None, \
3750
      "Cannot retrieve locked instance %s" % self.op.instance_name
3751

    
3752
    bep = self.cfg.GetClusterInfo().FillBE(instance)
3753
    if instance.disk_template not in constants.DTS_NET_MIRROR:
3754
      raise errors.OpPrereqError("Instance's disk layout is not"
3755
                                 " network mirrored, cannot failover.")
3756

    
3757
    secondary_nodes = instance.secondary_nodes
3758
    if not secondary_nodes:
3759
      raise errors.ProgrammerError("no secondary node but using "
3760
                                   "a mirrored disk template")
3761

    
3762
    target_node = secondary_nodes[0]
3763
    _CheckNodeOnline(self, target_node)
3764
    _CheckNodeNotDrained(self, target_node)
3765

    
3766
    if instance.admin_up:
3767
      # check memory requirements on the secondary node
3768
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
3769
                           instance.name, bep[constants.BE_MEMORY],
3770
                           instance.hypervisor)
3771
    else:
3772
      self.LogInfo("Not checking memory on the secondary node as"
3773
                   " instance will not be started")
3774

    
3775
    # check bridge existence
3776
    brlist = [nic.bridge for nic in instance.nics]
3777
    result = self.rpc.call_bridges_exist(target_node, brlist)
3778
    result.Raise()
3779
    if not result.data:
3780
      raise errors.OpPrereqError("One or more target bridges %s does not"
3781
                                 " exist on destination node '%s'" %
3782
                                 (brlist, target_node))
3783

    
3784
  def Exec(self, feedback_fn):
3785
    """Failover an instance.
3786

3787
    The failover is done by shutting it down on its present node and
3788
    starting it on the secondary.
3789

3790
    """
3791
    instance = self.instance
3792

    
3793
    source_node = instance.primary_node
3794
    target_node = instance.secondary_nodes[0]
3795

    
3796
    feedback_fn("* checking disk consistency between source and target")
3797
    for dev in instance.disks:
3798
      # for drbd, these are drbd over lvm
3799
      if not _CheckDiskConsistency(self, dev, target_node, False):
3800
        if instance.admin_up and not self.op.ignore_consistency:
3801
          raise errors.OpExecError("Disk %s is degraded on target node,"
3802
                                   " aborting failover." % dev.iv_name)
3803

    
3804
    feedback_fn("* shutting down instance on source node")
3805
    logging.info("Shutting down instance %s on node %s",
3806
                 instance.name, source_node)
3807

    
3808
    result = self.rpc.call_instance_shutdown(source_node, instance)
3809
    msg = result.RemoteFailMsg()
3810
    if msg:
3811
      if self.op.ignore_consistency:
3812
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
3813
                             " Proceeding anyway. Please make sure node"
3814
                             " %s is down. Error details: %s",
3815
                             instance.name, source_node, source_node, msg)
3816
      else:
3817
        raise errors.OpExecError("Could not shutdown instance %s on"
3818
                                 " node %s: %s" %
3819
                                 (instance.name, source_node, msg))
3820

    
3821
    feedback_fn("* deactivating the instance's disks on source node")
3822
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
3823
      raise errors.OpExecError("Can't shut down the instance's disks.")
3824

    
3825
    instance.primary_node = target_node
3826
    # distribute new instance config to the other nodes
3827
    self.cfg.Update(instance)
3828

    
3829
    # Only start the instance if it's marked as up
3830
    if instance.admin_up:
3831
      feedback_fn("* activating the instance's disks on target node")
3832
      logging.info("Starting instance %s on node %s",
3833
                   instance.name, target_node)
3834

    
3835
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
3836
                                               ignore_secondaries=True)
3837
      if not disks_ok:
3838
        _ShutdownInstanceDisks(self, instance)
3839
        raise errors.OpExecError("Can't activate the instance's disks")
3840

    
3841
      feedback_fn("* starting the instance on the target node")
3842
      result = self.rpc.call_instance_start(target_node, instance, None, None)
3843
      msg = result.RemoteFailMsg()
3844
      if msg:
3845
        _ShutdownInstanceDisks(self, instance)
3846
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
3847
                                 (instance.name, target_node, msg))
3848

    
3849

    
3850
class LUMigrateInstance(LogicalUnit):
3851
  """Migrate an instance.
3852

3853
  This is migration without shutting down, compared to the failover,
3854
  which is done with shutdown.
3855

3856
  """
3857
  HPATH = "instance-migrate"
3858
  HTYPE = constants.HTYPE_INSTANCE
3859
  _OP_REQP = ["instance_name", "live", "cleanup"]
3860

    
3861
  REQ_BGL = False
3862

    
3863
  def ExpandNames(self):
3864
    self._ExpandAndLockInstance()
3865
    self.needed_locks[locking.LEVEL_NODE] = []
3866
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3867

    
3868
  def DeclareLocks(self, level):
3869
    if level == locking.LEVEL_NODE:
3870
      self._LockInstancesNodes()
3871

    
3872
  def BuildHooksEnv(self):
3873
    """Build hooks env.
3874

3875
    This runs on master, primary and secondary nodes of the instance.
3876

3877
    """
3878
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3879
    env["MIGRATE_LIVE"] = self.op.live
3880
    env["MIGRATE_CLEANUP"] = self.op.cleanup
3881
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
3882
    return env, nl, nl
3883

    
3884
  def CheckPrereq(self):
3885
    """Check prerequisites.
3886

3887
    This checks that the instance is in the cluster.
3888

3889
    """
3890
    instance = self.cfg.GetInstanceInfo(
3891
      self.cfg.ExpandInstanceName(self.op.instance_name))
3892
    if instance is None:
3893
      raise errors.OpPrereqError("Instance '%s' not known" %
3894
                                 self.op.instance_name)
3895

    
3896
    if instance.disk_template != constants.DT_DRBD8:
3897
      raise errors.OpPrereqError("Instance's disk layout is not"
3898
                                 " drbd8, cannot migrate.")
3899

    
3900
    secondary_nodes = instance.secondary_nodes
3901
    if not secondary_nodes:
3902
      raise errors.ConfigurationError("No secondary node but using"
3903
                                      " drbd8 disk template")
3904

    
3905
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
3906

    
3907
    target_node = secondary_nodes[0]
3908
    # check memory requirements on the secondary node
3909
    _CheckNodeFreeMemory(self, target_node, "migrating instance %s" %
3910
                         instance.name, i_be[constants.BE_MEMORY],
3911
                         instance.hypervisor)
3912

    
3913
    # check bridge existence
3914
    brlist = [nic.bridge for nic in instance.nics]
3915
    result = self.rpc.call_bridges_exist(target_node, brlist)
3916
    if result.failed or not result.data:
3917
      raise errors.OpPrereqError("One or more target bridges %s does not"
3918
                                 " exist on destination node '%s'" %
3919
                                 (brlist, target_node))
3920

    
3921
    if not self.op.cleanup:
3922
      _CheckNodeNotDrained(self, target_node)
3923
      result = self.rpc.call_instance_migratable(instance.primary_node,
3924
                                                 instance)
3925
      msg = result.RemoteFailMsg()
3926
      if msg:
3927
        raise errors.OpPrereqError("Can't migrate: %s - please use failover" %
3928
                                   msg)
3929

    
3930
    self.instance = instance
3931

    
3932
  def _WaitUntilSync(self):
3933
    """Poll with custom rpc for disk sync.
3934

3935
    This uses our own step-based rpc call.
3936

3937
    """
3938
    self.feedback_fn("* wait until resync is done")
3939
    all_done = False
3940
    while not all_done:
3941
      all_done = True
3942
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
3943
                                            self.nodes_ip,
3944
                                            self.instance.disks)
3945
      min_percent = 100
3946
      for node, nres in result.items():
3947
        msg = nres.RemoteFailMsg()
3948
        if msg:
3949
          raise errors.OpExecError("Cannot resync disks on node %s: %s" %
3950
                                   (node, msg))
3951
        node_done, node_percent = nres.payload
3952
        all_done = all_done and node_done
3953
        if node_percent is not None:
3954
          min_percent = min(min_percent, node_percent)
3955
      if not all_done:
3956
        if min_percent < 100:
3957
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
3958
        time.sleep(2)
3959

    
3960
  def _EnsureSecondary(self, node):
3961
    """Demote a node to secondary.
3962

3963
    """
3964
    self.feedback_fn("* switching node %s to secondary mode" % node)
3965

    
3966
    for dev in self.instance.disks:
3967
      self.cfg.SetDiskID(dev, node)
3968

    
3969
    result = self.rpc.call_blockdev_close(node, self.instance.name,
3970
                                          self.instance.disks)
3971
    msg = result.RemoteFailMsg()
3972
    if msg:
3973
      raise errors.OpExecError("Cannot change disk to secondary on node %s,"
3974
                               " error %s" % (node, msg))
3975

    
3976
  def _GoStandalone(self):
3977
    """Disconnect from the network.
3978

3979
    """
3980
    self.feedback_fn("* changing into standalone mode")
3981
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
3982
                                               self.instance.disks)
3983
    for node, nres in result.items():
3984
      msg = nres.RemoteFailMsg()
3985
      if msg:
3986
        raise errors.OpExecError("Cannot disconnect disks node %s,"
3987
                                 " error %s" % (node, msg))
3988

    
3989
  def _GoReconnect(self, multimaster):
3990
    """Reconnect to the network.
3991

3992
    """
3993
    if multimaster:
3994
      msg = "dual-master"
3995
    else:
3996
      msg = "single-master"
3997
    self.feedback_fn("* changing disks into %s mode" % msg)
3998
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
3999
                                           self.instance.disks,
4000
                                           self.instance.name, multimaster)
4001
    for node, nres in result.items():
4002
      msg = nres.RemoteFailMsg()
4003
      if msg:
4004
        raise errors.OpExecError("Cannot change disks config on node %s,"
4005
                                 " error: %s" % (node, msg))
4006

    
4007
  def _ExecCleanup(self):
4008
    """Try to cleanup after a failed migration.
4009

4010
    The cleanup is done by:
4011
      - check that the instance is running only on one node
4012
        (and update the config if needed)
4013
      - change disks on its secondary node to secondary
4014
      - wait until disks are fully synchronized
4015
      - disconnect from the network
4016
      - change disks into single-master mode
4017
      - wait again until disks are fully synchronized
4018

4019
    """
4020
    instance = self.instance
4021
    target_node = self.target_node
4022
    source_node = self.source_node
4023

    
4024
    # check running on only one node
4025
    self.feedback_fn("* checking where the instance actually runs"
4026
                     " (if this hangs, the hypervisor might be in"
4027
                     " a bad state)")
4028
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
4029
    for node, result in ins_l.items():
4030
      result.Raise()
4031
      if not isinstance(result.data, list):
4032
        raise errors.OpExecError("Can't contact node '%s'" % node)
4033

    
4034
    runningon_source = instance.name in ins_l[source_node].data
4035
    runningon_target = instance.name in ins_l[target_node].data
4036

    
4037
    if runningon_source and runningon_target:
4038
      raise errors.OpExecError("Instance seems to be running on two nodes,"
4039
                               " or the hypervisor is confused. You will have"
4040
                               " to ensure manually that it runs only on one"
4041
                               " and restart this operation.")
4042

    
4043
    if not (runningon_source or runningon_target):
4044
      raise errors.OpExecError("Instance does not seem to be running at all."
4045
                               " In this case, it's safer to repair by"
4046
                               " running 'gnt-instance stop' to ensure disk"
4047
                               " shutdown, and then restarting it.")
4048

    
4049
    if runningon_target:
4050
      # the migration has actually succeeded, we need to update the config
4051
      self.feedback_fn("* instance running on secondary node (%s),"
4052
                       " updating config" % target_node)
4053
      instance.primary_node = target_node
4054
      self.cfg.Update(instance)
4055
      demoted_node = source_node
4056
    else:
4057
      self.feedback_fn("* instance confirmed to be running on its"
4058
                       " primary node (%s)" % source_node)
4059
      demoted_node = target_node
4060

    
4061
    self._EnsureSecondary(demoted_node)
4062
    try:
4063
      self._WaitUntilSync()
4064
    except errors.OpExecError:
4065
      # we ignore here errors, since if the device is standalone, it
4066
      # won't be able to sync
4067
      pass
4068
    self._GoStandalone()
4069
    self._GoReconnect(False)
4070
    self._WaitUntilSync()
4071

    
4072
    self.feedback_fn("* done")
4073

    
4074
  def _RevertDiskStatus(self):
4075
    """Try to revert the disk status after a failed migration.
4076

4077
    """
4078
    target_node = self.target_node
4079
    try:
4080
      self._EnsureSecondary(target_node)
4081
      self._GoStandalone()
4082
      self._GoReconnect(False)
4083
      self._WaitUntilSync()
4084
    except errors.OpExecError, err:
4085
      self.LogWarning("Migration failed and I can't reconnect the"
4086
                      " drives: error '%s'\n"
4087
                      "Please look and recover the instance status" %
4088
                      str(err))
4089

    
4090
  def _AbortMigration(self):
4091
    """Call the hypervisor code to abort a started migration.
4092

4093
    """
4094
    instance = self.instance
4095
    target_node = self.target_node
4096
    migration_info = self.migration_info
4097

    
4098
    abort_result = self.rpc.call_finalize_migration(target_node,
4099
                                                    instance,
4100
                                                    migration_info,
4101
                                                    False)
4102
    abort_msg = abort_result.RemoteFailMsg()
4103
    if abort_msg:
4104
      logging.error("Aborting migration failed on target node %s: %s" %
4105
                    (target_node, abort_msg))
4106
      # Don't raise an exception here, as we stil have to try to revert the
4107
      # disk status, even if this step failed.
4108

    
4109
  def _ExecMigration(self):
4110
    """Migrate an instance.
4111

4112
    The migrate is done by:
4113
      - change the disks into dual-master mode
4114
      - wait until disks are fully synchronized again
4115
      - migrate the instance
4116
      - change disks on the new secondary node (the old primary) to secondary
4117
      - wait until disks are fully synchronized
4118
      - change disks into single-master mode
4119

4120
    """
4121
    instance = self.instance
4122
    target_node = self.target_node
4123
    source_node = self.source_node
4124

    
4125
    self.feedback_fn("* checking disk consistency between source and target")
4126
    for dev in instance.disks:
4127
      if not _CheckDiskConsistency(self, dev, target_node, False):
4128
        raise errors.OpExecError("Disk %s is degraded or not fully"
4129
                                 " synchronized on target node,"
4130
                                 " aborting migrate." % dev.iv_name)
4131

    
4132
    # First get the migration information from the remote node
4133
    result = self.rpc.call_migration_info(source_node, instance)
4134
    msg = result.RemoteFailMsg()
4135
    if msg:
4136
      log_err = ("Failed fetching source migration information from %s: %s" %
4137
                 (source_node, msg))
4138
      logging.error(log_err)
4139
      raise errors.OpExecError(log_err)
4140

    
4141
    self.migration_info = migration_info = result.payload
4142

    
4143
    # Then switch the disks to master/master mode
4144
    self._EnsureSecondary(target_node)
4145
    self._GoStandalone()
4146
    self._GoReconnect(True)
4147
    self._WaitUntilSync()
4148

    
4149
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
4150
    result = self.rpc.call_accept_instance(target_node,
4151
                                           instance,
4152
                                           migration_info,
4153
                                           self.nodes_ip[target_node])
4154

    
4155
    msg = result.RemoteFailMsg()
4156
    if msg:
4157
      logging.error("Instance pre-migration failed, trying to revert"
4158
                    " disk status: %s", msg)
4159
      self._AbortMigration()
4160
      self._RevertDiskStatus()
4161
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
4162
                               (instance.name, msg))
4163

    
4164
    self.feedback_fn("* migrating instance to %s" % target_node)
4165
    time.sleep(10)
4166
    result = self.rpc.call_instance_migrate(source_node, instance,
4167
                                            self.nodes_ip[target_node],
4168
                                            self.op.live)
4169
    msg = result.RemoteFailMsg()
4170
    if msg:
4171
      logging.error("Instance migration failed, trying to revert"
4172
                    " disk status: %s", msg)
4173
      self._AbortMigration()
4174
      self._RevertDiskStatus()
4175
      raise errors.OpExecError("Could not migrate instance %s: %s" %
4176
                               (instance.name, msg))
4177
    time.sleep(10)
4178

    
4179
    instance.primary_node = target_node
4180
    # distribute new instance config to the other nodes
4181
    self.cfg.Update(instance)
4182

    
4183
    result = self.rpc.call_finalize_migration(target_node,
4184
                                              instance,
4185
                                              migration_info,
4186
                                              True)
4187
    msg = result.RemoteFailMsg()
4188
    if msg:
4189
      logging.error("Instance migration succeeded, but finalization failed:"
4190
                    " %s" % msg)
4191
      raise errors.OpExecError("Could not finalize instance migration: %s" %
4192
                               msg)
4193

    
4194
    self._EnsureSecondary(source_node)
4195
    self._WaitUntilSync()
4196
    self._GoStandalone()
4197
    self._GoReconnect(False)
4198
    self._WaitUntilSync()
4199

    
4200
    self.feedback_fn("* done")
4201

    
4202
  def Exec(self, feedback_fn):
4203
    """Perform the migration.
4204

4205
    """
4206
    self.feedback_fn = feedback_fn
4207

    
4208
    self.source_node = self.instance.primary_node
4209
    self.target_node = self.instance.secondary_nodes[0]
4210
    self.all_nodes = [self.source_node, self.target_node]
4211
    self.nodes_ip = {
4212
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
4213
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
4214
      }
4215
    if self.op.cleanup:
4216
      return self._ExecCleanup()
4217
    else:
4218
      return self._ExecMigration()
4219

    
4220

    
4221
def _CreateBlockDev(lu, node, instance, device, force_create,
4222
                    info, force_open):
4223
  """Create a tree of block devices on a given node.
4224

4225
  If this device type has to be created on secondaries, create it and
4226
  all its children.
4227

4228
  If not, just recurse to children keeping the same 'force' value.
4229

4230
  @param lu: the lu on whose behalf we execute
4231
  @param node: the node on which to create the device
4232
  @type instance: L{objects.Instance}
4233
  @param instance: the instance which owns the device
4234
  @type device: L{objects.Disk}
4235
  @param device: the device to create
4236
  @type force_create: boolean
4237
  @param force_create: whether to force creation of this device; this
4238
      will be change to True whenever we find a device which has
4239
      CreateOnSecondary() attribute
4240
  @param info: the extra 'metadata' we should attach to the device
4241
      (this will be represented as a LVM tag)
4242
  @type force_open: boolean
4243
  @param force_open: this parameter will be passes to the
4244
      L{backend.BlockdevCreate} function where it specifies
4245
      whether we run on primary or not, and it affects both
4246
      the child assembly and the device own Open() execution
4247

4248
  """
4249
  if device.CreateOnSecondary():
4250
    force_create = True
4251

    
4252
  if device.children:
4253
    for child in device.children:
4254
      _CreateBlockDev(lu, node, instance, child, force_create,
4255
                      info, force_open)
4256

    
4257
  if not force_create:
4258
    return
4259

    
4260
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
4261

    
4262

    
4263
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
4264
  """Create a single block device on a given node.
4265

4266
  This will not recurse over children of the device, so they must be
4267
  created in advance.
4268

4269
  @param lu: the lu on whose behalf we execute
4270
  @param node: the node on which to create the device
4271
  @type instance: L{objects.Instance}
4272
  @param instance: the instance which owns the device
4273
  @type device: L{objects.Disk}
4274
  @param device: the device to create
4275
  @param info: the extra 'metadata' we should attach to the device
4276
      (this will be represented as a LVM tag)
4277
  @type force_open: boolean
4278
  @param force_open: this parameter will be passes to the
4279
      L{backend.BlockdevCreate} function where it specifies
4280
      whether we run on primary or not, and it affects both
4281
      the child assembly and the device own Open() execution
4282

4283
  """
4284
  lu.cfg.SetDiskID(device, node)
4285
  result = lu.rpc.call_blockdev_create(node, device, device.size,
4286
                                       instance.name, force_open, info)
4287
  msg = result.RemoteFailMsg()
4288
  if msg:
4289
    raise errors.OpExecError("Can't create block device %s on"
4290
                             " node %s for instance %s: %s" %
4291
                             (device, node, instance.name, msg))
4292
  if device.physical_id is None:
4293
    device.physical_id = result.payload
4294

    
4295

    
4296
def _GenerateUniqueNames(lu, exts):
4297
  """Generate a suitable LV name.
4298

4299
  This will generate a logical volume name for the given instance.
4300

4301
  """
4302
  results = []
4303
  for val in exts:
4304
    new_id = lu.cfg.GenerateUniqueID()
4305
    results.append("%s%s" % (new_id, val))
4306
  return results
4307

    
4308

    
4309
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
4310
                         p_minor, s_minor):
4311
  """Generate a drbd8 device complete with its children.
4312

4313
  """
4314
  port = lu.cfg.AllocatePort()
4315
  vgname = lu.cfg.GetVGName()
4316
  shared_secret = lu.cfg.GenerateDRBDSecret()
4317
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
4318
                          logical_id=(vgname, names[0]))
4319
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
4320
                          logical_id=(vgname, names[1]))
4321
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
4322
                          logical_id=(primary, secondary, port,
4323
                                      p_minor, s_minor,
4324
                                      shared_secret),
4325
                          children=[dev_data, dev_meta],
4326
                          iv_name=iv_name)
4327
  return drbd_dev
4328

    
4329

    
4330
def _GenerateDiskTemplate(lu, template_name,
4331
                          instance_name, primary_node,
4332
                          secondary_nodes, disk_info,
4333
                          file_storage_dir, file_driver,
4334
                          base_index):
4335
  """Generate the entire disk layout for a given template type.
4336

4337
  """
4338
  #TODO: compute space requirements
4339

    
4340
  vgname = lu.cfg.GetVGName()
4341
  disk_count = len(disk_info)
4342
  disks = []
4343
  if template_name == constants.DT_DISKLESS:
4344
    pass
4345
  elif template_name == constants.DT_PLAIN:
4346
    if len(secondary_nodes) != 0:
4347
      raise errors.ProgrammerError("Wrong template configuration")
4348

    
4349
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
4350
                                      for i in range(disk_count)])
4351
    for idx, disk in enumerate(disk_info):
4352
      disk_index = idx + base_index
4353
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
4354
                              logical_id=(vgname, names[idx]),
4355
                              iv_name="disk/%d" % disk_index,
4356
                              mode=disk["mode"])
4357
      disks.append(disk_dev)
4358
  elif template_name == constants.DT_DRBD8:
4359
    if len(secondary_nodes) != 1:
4360
      raise errors.ProgrammerError("Wrong template configuration")
4361
    remote_node = secondary_nodes[0]
4362
    minors = lu.cfg.AllocateDRBDMinor(
4363
      [primary_node, remote_node] * len(disk_info), instance_name)
4364

    
4365
    names = []
4366
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
4367
                                               for i in range(disk_count)]):
4368
      names.append(lv_prefix + "_data")
4369
      names.append(lv_prefix + "_meta")
4370
    for idx, disk in enumerate(disk_info):
4371
      disk_index = idx + base_index
4372
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
4373
                                      disk["size"], names[idx*2:idx*2+2],
4374
                                      "disk/%d" % disk_index,
4375
                                      minors[idx*2], minors[idx*2+1])
4376
      disk_dev.mode = disk["mode"]
4377
      disks.append(disk_dev)
4378
  elif template_name == constants.DT_FILE:
4379
    if len(secondary_nodes) != 0:
4380
      raise errors.ProgrammerError("Wrong template configuration")
4381

    
4382
    for idx, disk in enumerate(disk_info):
4383
      disk_index = idx + base_index
4384
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
4385
                              iv_name="disk/%d" % disk_index,
4386
                              logical_id=(file_driver,
4387
                                          "%s/disk%d" % (file_storage_dir,
4388
                                                         disk_index)),
4389
                              mode=disk["mode"])
4390
      disks.append(disk_dev)
4391
  else:
4392
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
4393
  return disks
4394

    
4395

    
4396
def _GetInstanceInfoText(instance):
4397
  """Compute that text that should be added to the disk's metadata.
4398

4399
  """
4400
  return "originstname+%s" % instance.name
4401

    
4402

    
4403
def _CreateDisks(lu, instance):
4404
  """Create all disks for an instance.
4405

4406
  This abstracts away some work from AddInstance.
4407

4408
  @type lu: L{LogicalUnit}
4409
  @param lu: the logical unit on whose behalf we execute
4410
  @type instance: L{objects.Instance}
4411
  @param instance: the instance whose disks we should create
4412
  @rtype: boolean
4413
  @return: the success of the creation
4414

4415
  """
4416
  info = _GetInstanceInfoText(instance)
4417
  pnode = instance.primary_node
4418

    
4419
  if instance.disk_template == constants.DT_FILE:
4420
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
4421
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
4422

    
4423
    if result.failed or not result.data:
4424
      raise errors.OpExecError("Could not connect to node '%s'" % pnode)
4425

    
4426
    if not result.data[0]:
4427
      raise errors.OpExecError("Failed to create directory '%s'" %
4428
                               file_storage_dir)
4429

    
4430
  # Note: this needs to be kept in sync with adding of disks in
4431
  # LUSetInstanceParams
4432
  for device in instance.disks:
4433
    logging.info("Creating volume %s for instance %s",
4434
                 device.iv_name, instance.name)
4435
    #HARDCODE
4436
    for node in instance.all_nodes:
4437
      f_create = node == pnode
4438
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
4439

    
4440

    
4441
def _RemoveDisks(lu, instance):
4442
  """Remove all disks for an instance.
4443

4444
  This abstracts away some work from `AddInstance()` and
4445
  `RemoveInstance()`. Note that in case some of the devices couldn't
4446
  be removed, the removal will continue with the other ones (compare
4447
  with `_CreateDisks()`).
4448

4449
  @type lu: L{LogicalUnit}
4450
  @param lu: the logical unit on whose behalf we execute
4451
  @type instance: L{objects.Instance}
4452
  @param instance: the instance whose disks we should remove
4453
  @rtype: boolean
4454
  @return: the success of the removal
4455

4456
  """
4457
  logging.info("Removing block devices for instance %s", instance.name)
4458

    
4459
  all_result = True
4460
  for device in instance.disks:
4461
    for node, disk in device.ComputeNodeTree(instance.primary_node):
4462
      lu.cfg.SetDiskID(disk, node)
4463
      msg = lu.rpc.call_blockdev_remove(node, disk).RemoteFailMsg()
4464
      if msg:
4465
        lu.LogWarning("Could not remove block device %s on node %s,"
4466
                      " continuing anyway: %s", device.iv_name, node, msg)
4467
        all_result = False
4468

    
4469
  if instance.disk_template == constants.DT_FILE:
4470
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
4471
    result = lu.rpc.call_file_storage_dir_remove(instance.primary_node,
4472
                                                 file_storage_dir)
4473
    if result.failed or not result.data:
4474
      logging.error("Could not remove directory '%s'", file_storage_dir)
4475
      all_result = False
4476

    
4477
  return all_result
4478

    
4479

    
4480
def _ComputeDiskSize(disk_template, disks):
4481
  """Compute disk size requirements in the volume group
4482

4483
  """
4484
  # Required free disk space as a function of disk and swap space
4485
  req_size_dict = {
4486
    constants.DT_DISKLESS: None,
4487
    constants.DT_PLAIN: sum(d["size"] for d in disks),
4488
    # 128 MB are added for drbd metadata for each disk
4489
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
4490
    constants.DT_FILE: None,
4491
  }
4492

    
4493
  if disk_template not in req_size_dict:
4494
    raise errors.ProgrammerError("Disk template '%s' size requirement"
4495
                                 " is unknown" %  disk_template)
4496

    
4497
  return req_size_dict[disk_template]
4498

    
4499

    
4500
def _CheckHVParams(lu, nodenames, hvname, hvparams):
4501
  """Hypervisor parameter validation.
4502

4503
  This function abstract the hypervisor parameter validation to be
4504
  used in both instance create and instance modify.
4505

4506
  @type lu: L{LogicalUnit}
4507
  @param lu: the logical unit for which we check
4508
  @type nodenames: list
4509
  @param nodenames: the list of nodes on which we should check
4510
  @type hvname: string
4511
  @param hvname: the name of the hypervisor we should use
4512
  @type hvparams: dict
4513
  @param hvparams: the parameters which we need to check
4514
  @raise errors.OpPrereqError: if the parameters are not valid
4515

4516
  """
4517
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
4518
                                                  hvname,
4519
                                                  hvparams)
4520
  for node in nodenames:
4521
    info = hvinfo[node]
4522
    if info.offline:
4523
      continue
4524
    msg = info.RemoteFailMsg()
4525
    if msg:
4526
      raise errors.OpPrereqError("Hypervisor parameter validation"
4527
                                 " failed on node %s: %s" % (node, msg))
4528

    
4529

    
4530
class LUCreateInstance(LogicalUnit):
4531
  """Create an instance.
4532

4533
  """
4534
  HPATH = "instance-add"
4535
  HTYPE = constants.HTYPE_INSTANCE
4536
  _OP_REQP = ["instance_name", "disks", "disk_template",
4537
              "mode", "start",
4538
              "wait_for_sync", "ip_check", "nics",
4539
              "hvparams", "beparams"]
4540
  REQ_BGL = False
4541

    
4542
  def _ExpandNode(self, node):
4543
    """Expands and checks one node name.
4544

4545
    """
4546
    node_full = self.cfg.ExpandNodeName(node)
4547
    if node_full is None:
4548
      raise errors.OpPrereqError("Unknown node %s" % node)
4549
    return node_full
4550

    
4551
  def ExpandNames(self):
4552
    """ExpandNames for CreateInstance.
4553

4554
    Figure out the right locks for instance creation.
4555

4556
    """
4557
    self.needed_locks = {}
4558

    
4559
    # set optional parameters to none if they don't exist
4560
    for attr in ["pnode", "snode", "iallocator", "hypervisor"]:
4561
      if not hasattr(self.op, attr):
4562
        setattr(self.op, attr, None)
4563

    
4564
    # cheap checks, mostly valid constants given
4565

    
4566
    # verify creation mode
4567
    if self.op.mode not in (constants.INSTANCE_CREATE,
4568
                            constants.INSTANCE_IMPORT):
4569
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
4570
                                 self.op.mode)
4571

    
4572
    # disk template and mirror node verification
4573
    if self.op.disk_template not in constants.DISK_TEMPLATES:
4574
      raise errors.OpPrereqError("Invalid disk template name")
4575

    
4576
    if self.op.hypervisor is None:
4577
      self.op.hypervisor = self.cfg.GetHypervisorType()
4578

    
4579
    cluster = self.cfg.GetClusterInfo()
4580
    enabled_hvs = cluster.enabled_hypervisors
4581
    if self.op.hypervisor not in enabled_hvs:
4582
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
4583
                                 " cluster (%s)" % (self.op.hypervisor,
4584
                                  ",".join(enabled_hvs)))
4585

    
4586
    # check hypervisor parameter syntax (locally)
4587
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
4588
    filled_hvp = cluster.FillDict(cluster.hvparams[self.op.hypervisor],
4589
                                  self.op.hvparams)
4590
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
4591
    hv_type.CheckParameterSyntax(filled_hvp)
4592
    self.hv_full = filled_hvp
4593

    
4594
    # fill and remember the beparams dict
4595
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
4596
    self.be_full = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
4597
                                    self.op.beparams)
4598

    
4599
    #### instance parameters check
4600

    
4601
    # instance name verification
4602
    hostname1 = utils.HostInfo(self.op.instance_name)
4603
    self.op.instance_name = instance_name = hostname1.name
4604

    
4605
    # this is just a preventive check, but someone might still add this
4606
    # instance in the meantime, and creation will fail at lock-add time
4607
    if instance_name in self.cfg.GetInstanceList():
4608
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4609
                                 instance_name)
4610

    
4611
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
4612

    
4613
    # NIC buildup
4614
    self.nics = []
4615
    for nic in self.op.nics:
4616
      # ip validity checks
4617
      ip = nic.get("ip", None)
4618
      if ip is None or ip.lower() == "none":
4619
        nic_ip = None
4620
      elif ip.lower() == constants.VALUE_AUTO:
4621
        nic_ip = hostname1.ip
4622
      else:
4623
        if not utils.IsValidIP(ip):
4624
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
4625
                                     " like a valid IP" % ip)
4626
        nic_ip = ip
4627

    
4628
      # MAC address verification
4629
      mac = nic.get("mac", constants.VALUE_AUTO)
4630
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
4631
        if not utils.IsValidMac(mac.lower()):
4632
          raise errors.OpPrereqError("Invalid MAC address specified: %s" %
4633
                                     mac)
4634
        else:
4635
          # or validate/reserve the current one
4636
          if self.cfg.IsMacInUse(mac):
4637
            raise errors.OpPrereqError("MAC address %s already in use"
4638
                                       " in cluster" % mac)
4639

    
4640
      # bridge verification
4641
      bridge = nic.get("bridge", None)
4642
      if bridge is None:
4643
        bridge = self.cfg.GetDefBridge()
4644
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, bridge=bridge))
4645

    
4646
    # disk checks/pre-build
4647
    self.disks = []
4648
    for disk in self.op.disks:
4649
      mode = disk.get("mode", constants.DISK_RDWR)
4650
      if mode not in constants.DISK_ACCESS_SET:
4651
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
4652
                                   mode)
4653
      size = disk.get("size", None)
4654
      if size is None:
4655
        raise errors.OpPrereqError("Missing disk size")
4656
      try:
4657
        size = int(size)
4658
      except ValueError:
4659
        raise errors.OpPrereqError("Invalid disk size '%s'" % size)
4660
      self.disks.append({"size": size, "mode": mode})
4661

    
4662
    # used in CheckPrereq for ip ping check
4663
    self.check_ip = hostname1.ip
4664

    
4665
    # file storage checks
4666
    if (self.op.file_driver and
4667
        not self.op.file_driver in constants.FILE_DRIVER):
4668
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
4669
                                 self.op.file_driver)
4670

    
4671
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
4672
      raise errors.OpPrereqError("File storage directory path not absolute")
4673

    
4674
    ### Node/iallocator related checks
4675
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
4676
      raise errors.OpPrereqError("One and only one of iallocator and primary"
4677
                                 " node must be given")
4678

    
4679
    if self.op.iallocator:
4680
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4681
    else:
4682
      self.op.pnode = self._ExpandNode(self.op.pnode)
4683
      nodelist = [self.op.pnode]
4684
      if self.op.snode is not None:
4685
        self.op.snode = self._ExpandNode(self.op.snode)
4686
        nodelist.append(self.op.snode)
4687
      self.needed_locks[locking.LEVEL_NODE] = nodelist
4688

    
4689
    # in case of import lock the source node too
4690
    if self.op.mode == constants.INSTANCE_IMPORT:
4691
      src_node = getattr(self.op, "src_node", None)
4692
      src_path = getattr(self.op, "src_path", None)
4693

    
4694
      if src_path is None:
4695
        self.op.src_path = src_path = self.op.instance_name
4696

    
4697
      if src_node is None:
4698
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4699
        self.op.src_node = None
4700
        if os.path.isabs(src_path):
4701
          raise errors.OpPrereqError("Importing an instance from an absolute"
4702
                                     " path requires a source node option.")
4703
      else:
4704
        self.op.src_node = src_node = self._ExpandNode(src_node)
4705
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4706
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
4707
        if not os.path.isabs(src_path):
4708
          self.op.src_path = src_path = \
4709
            os.path.join(constants.EXPORT_DIR, src_path)
4710

    
4711
    else: # INSTANCE_CREATE
4712
      if getattr(self.op, "os_type", None) is None:
4713
        raise errors.OpPrereqError("No guest OS specified")
4714

    
4715
  def _RunAllocator(self):
4716
    """Run the allocator based on input opcode.
4717

4718
    """
4719
    nics = [n.ToDict() for n in self.nics]
4720
    ial = IAllocator(self,
4721
                     mode=constants.IALLOCATOR_MODE_ALLOC,
4722
                     name=self.op.instance_name,
4723
                     disk_template=self.op.disk_template,
4724
                     tags=[],
4725
                     os=self.op.os_type,
4726
                     vcpus=self.be_full[constants.BE_VCPUS],
4727
                     mem_size=self.be_full[constants.BE_MEMORY],
4728
                     disks=self.disks,
4729
                     nics=nics,
4730
                     hypervisor=self.op.hypervisor,
4731
                     )
4732

    
4733
    ial.Run(self.op.iallocator)
4734

    
4735
    if not ial.success:
4736
      raise errors.OpPrereqError("Can't compute nodes using"
4737
                                 " iallocator '%s': %s" % (self.op.iallocator,
4738
                                                           ial.info))
4739
    if len(ial.nodes) != ial.required_nodes:
4740
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
4741
                                 " of nodes (%s), required %s" %
4742
                                 (self.op.iallocator, len(ial.nodes),
4743
                                  ial.required_nodes))
4744
    self.op.pnode = ial.nodes[0]
4745
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
4746
                 self.op.instance_name, self.op.iallocator,
4747
                 ", ".join(ial.nodes))
4748
    if ial.required_nodes == 2:
4749
      self.op.snode = ial.nodes[1]
4750

    
4751
  def BuildHooksEnv(self):
4752
    """Build hooks env.
4753

4754
    This runs on master, primary and secondary nodes of the instance.
4755

4756
    """
4757
    env = {
4758
      "ADD_MODE": self.op.mode,
4759
      }
4760
    if self.op.mode == constants.INSTANCE_IMPORT:
4761
      env["SRC_NODE"] = self.op.src_node
4762
      env["SRC_PATH"] = self.op.src_path
4763
      env["SRC_IMAGES"] = self.src_images
4764

    
4765
    env.update(_BuildInstanceHookEnv(
4766
      name=self.op.instance_name,
4767
      primary_node=self.op.pnode,
4768
      secondary_nodes=self.secondaries,
4769
      status=self.op.start,
4770
      os_type=self.op.os_type,
4771
      memory=self.be_full[constants.BE_MEMORY],
4772
      vcpus=self.be_full[constants.BE_VCPUS],
4773
      nics=[(n.ip, n.bridge, n.mac) for n in self.nics],
4774
      disk_template=self.op.disk_template,
4775
      disks=[(d["size"], d["mode"]) for d in self.disks],
4776
      bep=self.be_full,
4777
      hvp=self.hv_full,
4778
      hypervisor_name=self.op.hypervisor,
4779
    ))
4780

    
4781
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
4782
          self.secondaries)
4783
    return env, nl, nl
4784

    
4785

    
4786
  def CheckPrereq(self):
4787
    """Check prerequisites.
4788

4789
    """
4790
    if (not self.cfg.GetVGName() and
4791
        self.op.disk_template not in constants.DTS_NOT_LVM):
4792
      raise errors.OpPrereqError("Cluster does not support lvm-based"
4793
                                 " instances")
4794

    
4795
    if self.op.mode == constants.INSTANCE_IMPORT:
4796
      src_node = self.op.src_node
4797
      src_path = self.op.src_path
4798

    
4799
      if src_node is None:
4800
        exp_list = self.rpc.call_export_list(
4801
          self.acquired_locks[locking.LEVEL_NODE])
4802
        found = False
4803
        for node in exp_list:
4804
          if not exp_list[node].failed and src_path in exp_list[node].data:
4805
            found = True
4806
            self.op.src_node = src_node = node
4807
            self.op.src_path = src_path = os.path.join(constants.EXPORT_DIR,
4808
                                                       src_path)
4809
            break
4810
        if not found:
4811
          raise errors.OpPrereqError("No export found for relative path %s" %
4812
                                      src_path)
4813

    
4814
      _CheckNodeOnline(self, src_node)
4815
      result = self.rpc.call_export_info(src_node, src_path)
4816
      result.Raise()
4817
      if not result.data:
4818
        raise errors.OpPrereqError("No export found in dir %s" % src_path)
4819

    
4820
      export_info = result.data
4821
      if not export_info.has_section(constants.INISECT_EXP):
4822
        raise errors.ProgrammerError("Corrupted export config")
4823

    
4824
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
4825
      if (int(ei_version) != constants.EXPORT_VERSION):
4826
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
4827
                                   (ei_version, constants.EXPORT_VERSION))
4828

    
4829
      # Check that the new instance doesn't have less disks than the export
4830
      instance_disks = len(self.disks)
4831
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
4832
      if instance_disks < export_disks:
4833
        raise errors.OpPrereqError("Not enough disks to import."
4834
                                   " (instance: %d, export: %d)" %
4835
                                   (instance_disks, export_disks))
4836

    
4837
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
4838
      disk_images = []
4839
      for idx in range(export_disks):
4840
        option = 'disk%d_dump' % idx
4841
        if export_info.has_option(constants.INISECT_INS, option):
4842
          # FIXME: are the old os-es, disk sizes, etc. useful?
4843
          export_name = export_info.get(constants.INISECT_INS, option)
4844
          image = os.path.join(src_path, export_name)
4845
          disk_images.append(image)
4846
        else:
4847
          disk_images.append(False)
4848

    
4849
      self.src_images = disk_images
4850

    
4851
      old_name = export_info.get(constants.INISECT_INS, 'name')
4852
      # FIXME: int() here could throw a ValueError on broken exports
4853
      exp_nic_count = int(export_info.get(constants.INISECT_INS, 'nic_count'))
4854
      if self.op.instance_name == old_name:
4855
        for idx, nic in enumerate(self.nics):
4856
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
4857
            nic_mac_ini = 'nic%d_mac' % idx
4858
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
4859

    
4860
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
4861
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
4862
    if self.op.start and not self.op.ip_check:
4863
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
4864
                                 " adding an instance in start mode")
4865

    
4866
    if self.op.ip_check:
4867
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
4868
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4869
                                   (self.check_ip, self.op.instance_name))
4870

    
4871
    #### mac address generation
4872
    # By generating here the mac address both the allocator and the hooks get
4873
    # the real final mac address rather than the 'auto' or 'generate' value.
4874
    # There is a race condition between the generation and the instance object
4875
    # creation, which means that we know the mac is valid now, but we're not
4876
    # sure it will be when we actually add the instance. If things go bad
4877
    # adding the instance will abort because of a duplicate mac, and the
4878
    # creation job will fail.
4879
    for nic in self.nics:
4880
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
4881
        nic.mac = self.cfg.GenerateMAC()
4882

    
4883
    #### allocator run
4884

    
4885
    if self.op.iallocator is not None:
4886
      self._RunAllocator()
4887

    
4888
    #### node related checks
4889

    
4890
    # check primary node
4891
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
4892
    assert self.pnode is not None, \
4893
      "Cannot retrieve locked node %s" % self.op.pnode
4894
    if pnode.offline:
4895
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
4896
                                 pnode.name)
4897
    if pnode.drained:
4898
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
4899
                                 pnode.name)
4900

    
4901
    self.secondaries = []
4902

    
4903
    # mirror node verification
4904
    if self.op.disk_template in constants.DTS_NET_MIRROR:
4905
      if self.op.snode is None:
4906
        raise errors.OpPrereqError("The networked disk templates need"
4907
                                   " a mirror node")
4908
      if self.op.snode == pnode.name:
4909
        raise errors.OpPrereqError("The secondary node cannot be"
4910
                                   " the primary node.")
4911
      _CheckNodeOnline(self, self.op.snode)
4912
      _CheckNodeNotDrained(self, self.op.snode)
4913
      self.secondaries.append(self.op.snode)
4914

    
4915
    nodenames = [pnode.name] + self.secondaries
4916

    
4917
    req_size = _ComputeDiskSize(self.op.disk_template,
4918
                                self.disks)
4919

    
4920
    # Check lv size requirements
4921
    if req_size is not None:
4922
      nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
4923
                                         self.op.hypervisor)
4924
      for node in nodenames:
4925
        info = nodeinfo[node]
4926
        info.Raise()
4927
        info = info.data
4928
        if not info:
4929
          raise errors.OpPrereqError("Cannot get current information"
4930
                                     " from node '%s'" % node)
4931
        vg_free = info.get('vg_free', None)
4932
        if not isinstance(vg_free, int):
4933
          raise errors.OpPrereqError("Can't compute free disk space on"
4934
                                     " node %s" % node)
4935
        if req_size > info['vg_free']:
4936
          raise errors.OpPrereqError("Not enough disk space on target node %s."
4937
                                     " %d MB available, %d MB required" %
4938
                                     (node, info['vg_free'], req_size))
4939

    
4940
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
4941

    
4942
    # os verification
4943
    result = self.rpc.call_os_get(pnode.name, self.op.os_type)
4944
    result.Raise()
4945
    if not isinstance(result.data, objects.OS) or not result.data:
4946
      raise errors.OpPrereqError("OS '%s' not in supported os list for"
4947
                                 " primary node"  % self.op.os_type)
4948

    
4949
    # bridge check on primary node
4950
    bridges = [n.bridge for n in self.nics]
4951
    result = self.rpc.call_bridges_exist(self.pnode.name, bridges)
4952
    result.Raise()
4953
    if not result.data:
4954
      raise errors.OpPrereqError("One of the target bridges '%s' does not"
4955
                                 " exist on destination node '%s'" %
4956
                                 (",".join(bridges), pnode.name))
4957

    
4958
    # memory check on primary node
4959
    if self.op.start:
4960
      _CheckNodeFreeMemory(self, self.pnode.name,
4961
                           "creating instance %s" % self.op.instance_name,
4962
                           self.be_full[constants.BE_MEMORY],
4963
                           self.op.hypervisor)
4964

    
4965
  def Exec(self, feedback_fn):
4966
    """Create and add the instance to the cluster.
4967

4968
    """
4969
    instance = self.op.instance_name
4970
    pnode_name = self.pnode.name
4971

    
4972
    ht_kind = self.op.hypervisor
4973
    if ht_kind in constants.HTS_REQ_PORT:
4974
      network_port = self.cfg.AllocatePort()
4975
    else:
4976
      network_port = None
4977

    
4978
    ##if self.op.vnc_bind_address is None:
4979
    ##  self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
4980

    
4981
    # this is needed because os.path.join does not accept None arguments
4982
    if self.op.file_storage_dir is None:
4983
      string_file_storage_dir = ""
4984
    else:
4985
      string_file_storage_dir = self.op.file_storage_dir
4986

    
4987
    # build the full file storage dir path
4988
    file_storage_dir = os.path.normpath(os.path.join(
4989
                                        self.cfg.GetFileStorageDir(),
4990
                                        string_file_storage_dir, instance))
4991

    
4992

    
4993
    disks = _GenerateDiskTemplate(self,
4994
                                  self.op.disk_template,
4995
                                  instance, pnode_name,
4996
                                  self.secondaries,
4997
                                  self.disks,
4998
                                  file_storage_dir,
4999
                                  self.op.file_driver,
5000
                                  0)
5001

    
5002
    iobj = objects.Instance(name=instance, os=self.op.os_type,
5003
                            primary_node=pnode_name,
5004
                            nics=self.nics, disks=disks,
5005
                            disk_template=self.op.disk_template,
5006
                            admin_up=False,
5007
                            network_port=network_port,
5008
                            beparams=self.op.beparams,
5009
                            hvparams=self.op.hvparams,
5010
                            hypervisor=self.op.hypervisor,
5011
                            )
5012

    
5013
    feedback_fn("* creating instance disks...")
5014
    try:
5015
      _CreateDisks(self, iobj)
5016
    except errors.OpExecError:
5017
      self.LogWarning("Device creation failed, reverting...")
5018
      try:
5019
        _RemoveDisks(self, iobj)
5020
      finally:
5021
        self.cfg.ReleaseDRBDMinors(instance)
5022
        raise
5023

    
5024
    feedback_fn("adding instance %s to cluster config" % instance)
5025

    
5026
    self.cfg.AddInstance(iobj)
5027
    # Declare that we don't want to remove the instance lock anymore, as we've
5028
    # added the instance to the config
5029
    del self.remove_locks[locking.LEVEL_INSTANCE]
5030
    # Unlock all the nodes
5031
    if self.op.mode == constants.INSTANCE_IMPORT:
5032
      nodes_keep = [self.op.src_node]
5033
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
5034
                       if node != self.op.src_node]
5035
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
5036
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
5037
    else:
5038
      self.context.glm.release(locking.LEVEL_NODE)
5039
      del self.acquired_locks[locking.LEVEL_NODE]
5040

    
5041
    if self.op.wait_for_sync:
5042
      disk_abort = not _WaitForSync(self, iobj)
5043
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
5044
      # make sure the disks are not degraded (still sync-ing is ok)
5045
      time.sleep(15)
5046
      feedback_fn("* checking mirrors status")
5047
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
5048
    else:
5049
      disk_abort = False
5050

    
5051
    if disk_abort:
5052
      _RemoveDisks(self, iobj)
5053
      self.cfg.RemoveInstance(iobj.name)
5054
      # Make sure the instance lock gets removed
5055
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
5056
      raise errors.OpExecError("There are some degraded disks for"
5057
                               " this instance")
5058

    
5059
    feedback_fn("creating os for instance %s on node %s" %
5060
                (instance, pnode_name))
5061

    
5062
    if iobj.disk_template != constants.DT_DISKLESS:
5063
      if self.op.mode == constants.INSTANCE_CREATE:
5064
        feedback_fn("* running the instance OS create scripts...")
5065
        result = self.rpc.call_instance_os_add(pnode_name, iobj)
5066
        msg = result.RemoteFailMsg()
5067
        if msg:
5068
          raise errors.OpExecError("Could not add os for instance %s"
5069
                                   " on node %s: %s" %
5070
                                   (instance, pnode_name, msg))
5071

    
5072
      elif self.op.mode == constants.INSTANCE_IMPORT:
5073
        feedback_fn("* running the instance OS import scripts...")
5074
        src_node = self.op.src_node
5075
        src_images = self.src_images
5076
        cluster_name = self.cfg.GetClusterName()
5077
        import_result = self.rpc.call_instance_os_import(pnode_name, iobj,
5078
                                                         src_node, src_images,
5079
                                                         cluster_name)
5080
        import_result.Raise()
5081
        for idx, result in enumerate(import_result.data):
5082
          if not result:
5083
            self.LogWarning("Could not import the image %s for instance"
5084
                            " %s, disk %d, on node %s" %
5085
                            (src_images[idx], instance, idx, pnode_name))
5086
      else:
5087
        # also checked in the prereq part
5088
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
5089
                                     % self.op.mode)
5090

    
5091
    if self.op.start:
5092
      iobj.admin_up = True
5093
      self.cfg.Update(iobj)
5094
      logging.info("Starting instance %s on node %s", instance, pnode_name)
5095
      feedback_fn("* starting instance...")
5096
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
5097
      msg = result.RemoteFailMsg()
5098
      if msg:
5099
        raise errors.OpExecError("Could not start instance: %s" % msg)
5100

    
5101

    
5102
class LUConnectConsole(NoHooksLU):
5103
  """Connect to an instance's console.
5104

5105
  This is somewhat special in that it returns the command line that
5106
  you need to run on the master node in order to connect to the
5107
  console.
5108

5109
  """
5110
  _OP_REQP = ["instance_name"]
5111
  REQ_BGL = False
5112

    
5113
  def ExpandNames(self):
5114
    self._ExpandAndLockInstance()
5115

    
5116
  def CheckPrereq(self):
5117
    """Check prerequisites.
5118

5119
    This checks that the instance is in the cluster.
5120

5121
    """
5122
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5123
    assert self.instance is not None, \
5124
      "Cannot retrieve locked instance %s" % self.op.instance_name
5125
    _CheckNodeOnline(self, self.instance.primary_node)
5126

    
5127
  def Exec(self, feedback_fn):
5128
    """Connect to the console of an instance
5129

5130
    """
5131
    instance = self.instance
5132
    node = instance.primary_node
5133

    
5134
    node_insts = self.rpc.call_instance_list([node],
5135
                                             [instance.hypervisor])[node]
5136
    node_insts.Raise()
5137

    
5138
    if instance.name not in node_insts.data:
5139
      raise errors.OpExecError("Instance %s is not running." % instance.name)
5140

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

    
5143
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
5144
    cluster = self.cfg.GetClusterInfo()
5145
    # beparams and hvparams are passed separately, to avoid editing the
5146
    # instance and then saving the defaults in the instance itself.
5147
    hvparams = cluster.FillHV(instance)
5148
    beparams = cluster.FillBE(instance)
5149
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
5150

    
5151
    # build ssh cmdline
5152
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
5153

    
5154

    
5155
class LUReplaceDisks(LogicalUnit):
5156
  """Replace the disks of an instance.
5157

5158
  """
5159
  HPATH = "mirrors-replace"
5160
  HTYPE = constants.HTYPE_INSTANCE
5161
  _OP_REQP = ["instance_name", "mode", "disks"]
5162
  REQ_BGL = False
5163

    
5164
  def CheckArguments(self):
5165
    if not hasattr(self.op, "remote_node"):
5166
      self.op.remote_node = None
5167
    if not hasattr(self.op, "iallocator"):
5168
      self.op.iallocator = None
5169

    
5170
    # check for valid parameter combination
5171
    cnt = [self.op.remote_node, self.op.iallocator].count(None)
5172
    if self.op.mode == constants.REPLACE_DISK_CHG:
5173
      if cnt == 2:
5174
        raise errors.OpPrereqError("When changing the secondary either an"
5175
                                   " iallocator script must be used or the"
5176
                                   " new node given")
5177
      elif cnt == 0:
5178
        raise errors.OpPrereqError("Give either the iallocator or the new"
5179
                                   " secondary, not both")
5180
    else: # not replacing the secondary
5181
      if cnt != 2:
5182
        raise errors.OpPrereqError("The iallocator and new node options can"
5183
                                   " be used only when changing the"
5184
                                   " secondary node")
5185

    
5186
  def ExpandNames(self):
5187
    self._ExpandAndLockInstance()
5188

    
5189
    if self.op.iallocator is not None:
5190
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5191
    elif self.op.remote_node is not None:
5192
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
5193
      if remote_node is None:
5194
        raise errors.OpPrereqError("Node '%s' not known" %
5195
                                   self.op.remote_node)
5196
      self.op.remote_node = remote_node
5197
      # Warning: do not remove the locking of the new secondary here
5198
      # unless DRBD8.AddChildren is changed to work in parallel;
5199
      # currently it doesn't since parallel invocations of
5200
      # FindUnusedMinor will conflict
5201
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
5202
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5203
    else:
5204
      self.needed_locks[locking.LEVEL_NODE] = []
5205
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5206

    
5207
  def DeclareLocks(self, level):
5208
    # If we're not already locking all nodes in the set we have to declare the
5209
    # instance's primary/secondary nodes.
5210
    if (level == locking.LEVEL_NODE and
5211
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
5212
      self._LockInstancesNodes()
5213

    
5214
  def _RunAllocator(self):
5215
    """Compute a new secondary node using an IAllocator.
5216

5217
    """
5218
    ial = IAllocator(self,
5219
                     mode=constants.IALLOCATOR_MODE_RELOC,
5220
                     name=self.op.instance_name,
5221
                     relocate_from=[self.sec_node])
5222

    
5223
    ial.Run(self.op.iallocator)
5224

    
5225
    if not ial.success:
5226
      raise errors.OpPrereqError("Can't compute nodes using"
5227
                                 " iallocator '%s': %s" % (self.op.iallocator,
5228
                                                           ial.info))
5229
    if len(ial.nodes) != ial.required_nodes:
5230
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
5231
                                 " of nodes (%s), required %s" %
5232
                                 (self.op.iallocator,
5233
                                  len(ial.nodes), ial.required_nodes))
5234
    self.op.remote_node = ial.nodes[0]
5235
    self.LogInfo("Selected new secondary for the instance: %s",
5236
                 self.op.remote_node)
5237

    
5238
  def BuildHooksEnv(self):
5239
    """Build hooks env.
5240

5241
    This runs on the master, the primary and all the secondaries.
5242

5243
    """
5244
    env = {
5245
      "MODE": self.op.mode,
5246
      "NEW_SECONDARY": self.op.remote_node,
5247
      "OLD_SECONDARY": self.instance.secondary_nodes[0],
5248
      }
5249
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5250
    nl = [
5251
      self.cfg.GetMasterNode(),
5252
      self.instance.primary_node,
5253
      ]
5254
    if self.op.remote_node is not None:
5255
      nl.append(self.op.remote_node)
5256
    return env, nl, nl
5257

    
5258
  def CheckPrereq(self):
5259
    """Check prerequisites.
5260

5261
    This checks that the instance is in the cluster.
5262

5263
    """
5264
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5265
    assert instance is not None, \
5266
      "Cannot retrieve locked instance %s" % self.op.instance_name
5267
    self.instance = instance
5268

    
5269
    if instance.disk_template != constants.DT_DRBD8:
5270
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
5271
                                 " instances")
5272

    
5273
    if len(instance.secondary_nodes) != 1:
5274
      raise errors.OpPrereqError("The instance has a strange layout,"
5275
                                 " expected one secondary but found %d" %
5276
                                 len(instance.secondary_nodes))
5277

    
5278
    self.sec_node = instance.secondary_nodes[0]
5279

    
5280
    if self.op.iallocator is not None:
5281
      self._RunAllocator()
5282

    
5283
    remote_node = self.op.remote_node
5284
    if remote_node is not None:
5285
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
5286
      assert self.remote_node_info is not None, \
5287
        "Cannot retrieve locked node %s" % remote_node
5288
    else:
5289
      self.remote_node_info = None
5290
    if remote_node == instance.primary_node:
5291
      raise errors.OpPrereqError("The specified node is the primary node of"
5292
                                 " the instance.")
5293
    elif remote_node == self.sec_node:
5294
      raise errors.OpPrereqError("The specified node is already the"
5295
                                 " secondary node of the instance.")
5296

    
5297
    if self.op.mode == constants.REPLACE_DISK_PRI:
5298
      n1 = self.tgt_node = instance.primary_node
5299
      n2 = self.oth_node = self.sec_node
5300
    elif self.op.mode == constants.REPLACE_DISK_SEC:
5301
      n1 = self.tgt_node = self.sec_node
5302
      n2 = self.oth_node = instance.primary_node
5303
    elif self.op.mode == constants.REPLACE_DISK_CHG:
5304
      n1 = self.new_node = remote_node
5305
      n2 = self.oth_node = instance.primary_node
5306
      self.tgt_node = self.sec_node
5307
      _CheckNodeNotDrained(self, remote_node)
5308
    else:
5309
      raise errors.ProgrammerError("Unhandled disk replace mode")
5310

    
5311
    _CheckNodeOnline(self, n1)
5312
    _CheckNodeOnline(self, n2)
5313

    
5314
    if not self.op.disks:
5315
      self.op.disks = range(len(instance.disks))
5316

    
5317
    for disk_idx in self.op.disks:
5318
      instance.FindDisk(disk_idx)
5319

    
5320
  def _ExecD8DiskOnly(self, feedback_fn):
5321
    """Replace a disk on the primary or secondary for dbrd8.
5322

5323
    The algorithm for replace is quite complicated:
5324

5325
      1. for each disk to be replaced:
5326

5327
        1. create new LVs on the target node with unique names
5328
        1. detach old LVs from the drbd device
5329
        1. rename old LVs to name_replaced.<time_t>
5330
        1. rename new LVs to old LVs
5331
        1. attach the new LVs (with the old names now) to the drbd device
5332

5333
      1. wait for sync across all devices
5334

5335
      1. for each modified disk:
5336

5337
        1. remove old LVs (which have the name name_replaces.<time_t>)
5338

5339
    Failures are not very well handled.
5340

5341
    """
5342
    steps_total = 6
5343
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
5344
    instance = self.instance
5345
    iv_names = {}
5346
    vgname = self.cfg.GetVGName()
5347
    # start of work
5348
    cfg = self.cfg
5349
    tgt_node = self.tgt_node
5350
    oth_node = self.oth_node
5351

    
5352
    # Step: check device activation
5353
    self.proc.LogStep(1, steps_total, "check device existence")
5354
    info("checking volume groups")
5355
    my_vg = cfg.GetVGName()
5356
    results = self.rpc.call_vg_list([oth_node, tgt_node])
5357
    if not results:
5358
      raise errors.OpExecError("Can't list volume groups on the nodes")
5359
    for node in oth_node, tgt_node:
5360
      res = results[node]
5361
      if res.failed or not res.data or my_vg not in res.data:
5362
        raise errors.OpExecError("Volume group '%s' not found on %s" %
5363
                                 (my_vg, node))
5364
    for idx, dev in enumerate(instance.disks):
5365
      if idx not in self.op.disks:
5366
        continue
5367
      for node in tgt_node, oth_node:
5368
        info("checking disk/%d on %s" % (idx, node))
5369
        cfg.SetDiskID(dev, node)
5370
        result = self.rpc.call_blockdev_find(node, dev)
5371
        msg = result.RemoteFailMsg()
5372
        if not msg and not result.payload:
5373
          msg = "disk not found"
5374
        if msg:
5375
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
5376
                                   (idx, node, msg))
5377

    
5378
    # Step: check other node consistency
5379
    self.proc.LogStep(2, steps_total, "check peer consistency")
5380
    for idx, dev in enumerate(instance.disks):
5381
      if idx not in self.op.disks:
5382
        continue
5383
      info("checking disk/%d consistency on %s" % (idx, oth_node))
5384
      if not _CheckDiskConsistency(self, dev, oth_node,
5385
                                   oth_node==instance.primary_node):
5386
        raise errors.OpExecError("Peer node (%s) has degraded storage, unsafe"
5387
                                 " to replace disks on this node (%s)" %
5388
                                 (oth_node, tgt_node))
5389

    
5390
    # Step: create new storage
5391
    self.proc.LogStep(3, steps_total, "allocate new storage")
5392
    for idx, dev in enumerate(instance.disks):
5393
      if idx not in self.op.disks:
5394
        continue
5395
      size = dev.size
5396
      cfg.SetDiskID(dev, tgt_node)
5397
      lv_names = [".disk%d_%s" % (idx, suf)
5398
                  for suf in ["data", "meta"]]
5399
      names = _GenerateUniqueNames(self, lv_names)
5400
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=size,
5401
                             logical_id=(vgname, names[0]))
5402
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
5403
                             logical_id=(vgname, names[1]))
5404
      new_lvs = [lv_data, lv_meta]
5405
      old_lvs = dev.children
5406
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
5407
      info("creating new local storage on %s for %s" %
5408
           (tgt_node, dev.iv_name))
5409
      # we pass force_create=True to force the LVM creation
5410
      for new_lv in new_lvs:
5411
        _CreateBlockDev(self, tgt_node, instance, new_lv, True,
5412
                        _GetInstanceInfoText(instance), False)
5413

    
5414
    # Step: for each lv, detach+rename*2+attach
5415
    self.proc.LogStep(4, steps_total, "change drbd configuration")
5416
    for dev, old_lvs, new_lvs in iv_names.itervalues():
5417
      info("detaching %s drbd from local storage" % dev.iv_name)
5418
      result = self.rpc.call_blockdev_removechildren(tgt_node, dev, old_lvs)
5419
      result.Raise()
5420
      if not result.data:
5421
        raise errors.OpExecError("Can't detach drbd from local storage on node"
5422
                                 " %s for device %s" % (tgt_node, dev.iv_name))
5423
      #dev.children = []
5424
      #cfg.Update(instance)
5425

    
5426
      # ok, we created the new LVs, so now we know we have the needed
5427
      # storage; as such, we proceed on the target node to rename
5428
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
5429
      # using the assumption that logical_id == physical_id (which in
5430
      # turn is the unique_id on that node)
5431

    
5432
      # FIXME(iustin): use a better name for the replaced LVs
5433
      temp_suffix = int(time.time())
5434
      ren_fn = lambda d, suff: (d.physical_id[0],
5435
                                d.physical_id[1] + "_replaced-%s" % suff)
5436
      # build the rename list based on what LVs exist on the node
5437
      rlist = []
5438
      for to_ren in old_lvs:
5439
        result = self.rpc.call_blockdev_find(tgt_node, to_ren)
5440
        if not result.RemoteFailMsg() and result.payload:
5441
          # device exists
5442
          rlist.append((to_ren, ren_fn(to_ren, temp_suffix)))
5443

    
5444
      info("renaming the old LVs on the target node")
5445
      result = self.rpc.call_blockdev_rename(tgt_node, rlist)
5446
      result.Raise()
5447
      if not result.data:
5448
        raise errors.OpExecError("Can't rename old LVs on node %s" % tgt_node)
5449
      # now we rename the new LVs to the old LVs
5450
      info("renaming the new LVs on the target node")
5451
      rlist = [(new, old.physical_id) for old, new in zip(old_lvs, new_lvs)]
5452
      result = self.rpc.call_blockdev_rename(tgt_node, rlist)
5453
      result.Raise()
5454
      if not result.data:
5455
        raise errors.OpExecError("Can't rename new LVs on node %s" % tgt_node)
5456

    
5457
      for old, new in zip(old_lvs, new_lvs):
5458
        new.logical_id = old.logical_id
5459
        cfg.SetDiskID(new, tgt_node)
5460

    
5461
      for disk in old_lvs:
5462
        disk.logical_id = ren_fn(disk, temp_suffix)
5463
        cfg.SetDiskID(disk, tgt_node)
5464

    
5465
      # now that the new lvs have the old name, we can add them to the device
5466
      info("adding new mirror component on %s" % tgt_node)
5467
      result = self.rpc.call_blockdev_addchildren(tgt_node, dev, new_lvs)
5468
      if result.failed or not result.data:
5469
        for new_lv in new_lvs:
5470
          msg = self.rpc.call_blockdev_remove(tgt_node, new_lv).RemoteFailMsg()
5471
          if msg:
5472
            warning("Can't rollback device %s: %s", dev, msg,
5473
                    hint="cleanup manually the unused logical volumes")
5474
        raise errors.OpExecError("Can't add local storage to drbd")
5475

    
5476
      dev.children = new_lvs
5477
      cfg.Update(instance)
5478

    
5479
    # Step: wait for sync
5480

    
5481
    # this can fail as the old devices are degraded and _WaitForSync
5482
    # does a combined result over all disks, so we don't check its
5483
    # return value
5484
    self.proc.LogStep(5, steps_total, "sync devices")
5485
    _WaitForSync(self, instance, unlock=True)
5486

    
5487
    # so check manually all the devices
5488
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
5489
      cfg.SetDiskID(dev, instance.primary_node)
5490
      result = self.rpc.call_blockdev_find(instance.primary_node, dev)
5491
      msg = result.RemoteFailMsg()
5492
      if not msg and not result.payload:
5493
        msg = "disk not found"
5494
      if msg:
5495
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
5496
                                 (name, msg))
5497
      if result.payload[5]:
5498
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
5499

    
5500
    # Step: remove old storage
5501
    self.proc.LogStep(6, steps_total, "removing old storage")
5502
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
5503
      info("remove logical volumes for %s" % name)
5504
      for lv in old_lvs:
5505
        cfg.SetDiskID(lv, tgt_node)
5506
        msg = self.rpc.call_blockdev_remove(tgt_node, lv).RemoteFailMsg()
5507
        if msg:
5508
          warning("Can't remove old LV: %s" % msg,
5509
                  hint="manually remove unused LVs")
5510
          continue
5511

    
5512
  def _ExecD8Secondary(self, feedback_fn):
5513
    """Replace the secondary node for drbd8.
5514

5515
    The algorithm for replace is quite complicated:
5516
      - for all disks of the instance:
5517
        - create new LVs on the new node with same names
5518
        - shutdown the drbd device on the old secondary
5519
        - disconnect the drbd network on the primary
5520
        - create the drbd device on the new secondary
5521
        - network attach the drbd on the primary, using an artifice:
5522
          the drbd code for Attach() will connect to the network if it
5523
          finds a device which is connected to the good local disks but
5524
          not network enabled
5525
      - wait for sync across all devices
5526
      - remove all disks from the old secondary
5527

5528
    Failures are not very well handled.
5529

5530
    """
5531
    steps_total = 6
5532
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
5533
    instance = self.instance
5534
    iv_names = {}
5535
    # start of work
5536
    cfg = self.cfg
5537
    old_node = self.tgt_node
5538
    new_node = self.new_node
5539
    pri_node = instance.primary_node
5540
    nodes_ip = {
5541
      old_node: self.cfg.GetNodeInfo(old_node).secondary_ip,
5542
      new_node: self.cfg.GetNodeInfo(new_node).secondary_ip,
5543
      pri_node: self.cfg.GetNodeInfo(pri_node).secondary_ip,
5544
      }
5545

    
5546
    # Step: check device activation
5547
    self.proc.LogStep(1, steps_total, "check device existence")
5548
    info("checking volume groups")
5549
    my_vg = cfg.GetVGName()
5550
    results = self.rpc.call_vg_list([pri_node, new_node])
5551
    for node in pri_node, new_node:
5552
      res = results[node]
5553
      if res.failed or not res.data or my_vg not in res.data:
5554
        raise errors.OpExecError("Volume group '%s' not found on %s" %
5555
                                 (my_vg, node))
5556
    for idx, dev in enumerate(instance.disks):
5557
      if idx not in self.op.disks:
5558
        continue
5559
      info("checking disk/%d on %s" % (idx, pri_node))
5560
      cfg.SetDiskID(dev, pri_node)
5561
      result = self.rpc.call_blockdev_find(pri_node, dev)
5562
      msg = result.RemoteFailMsg()
5563
      if not msg and not result.payload:
5564
        msg = "disk not found"
5565
      if msg:
5566
        raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
5567
                                 (idx, pri_node, msg))
5568

    
5569
    # Step: check other node consistency
5570
    self.proc.LogStep(2, steps_total, "check peer consistency")
5571
    for idx, dev in enumerate(instance.disks):
5572
      if idx not in self.op.disks:
5573
        continue
5574
      info("checking disk/%d consistency on %s" % (idx, pri_node))
5575
      if not _CheckDiskConsistency(self, dev, pri_node, True, ldisk=True):
5576
        raise errors.OpExecError("Primary node (%s) has degraded storage,"
5577
                                 " unsafe to replace the secondary" %
5578
                                 pri_node)
5579

    
5580
    # Step: create new storage
5581
    self.proc.LogStep(3, steps_total, "allocate new storage")
5582
    for idx, dev in enumerate(instance.disks):
5583
      info("adding new local storage on %s for disk/%d" %
5584
           (new_node, idx))
5585
      # we pass force_create=True to force LVM creation
5586
      for new_lv in dev.children:
5587
        _CreateBlockDev(self, new_node, instance, new_lv, True,
5588
                        _GetInstanceInfoText(instance), False)
5589

    
5590
    # Step 4: dbrd minors and drbd setups changes
5591
    # after this, we must manually remove the drbd minors on both the
5592
    # error and the success paths
5593
    minors = cfg.AllocateDRBDMinor([new_node for dev in instance.disks],
5594
                                   instance.name)
5595
    logging.debug("Allocated minors %s" % (minors,))
5596
    self.proc.LogStep(4, steps_total, "changing drbd configuration")
5597
    for idx, (dev, new_minor) in enumerate(zip(instance.disks, minors)):
5598
      info("activating a new drbd on %s for disk/%d" % (new_node, idx))
5599
      # create new devices on new_node; note that we create two IDs:
5600
      # one without port, so the drbd will be activated without
5601
      # networking information on the new node at this stage, and one
5602
      # with network, for the latter activation in step 4
5603
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
5604
      if pri_node == o_node1:
5605
        p_minor = o_minor1
5606
      else:
5607
        p_minor = o_minor2
5608

    
5609
      new_alone_id = (pri_node, new_node, None, p_minor, new_minor, o_secret)
5610
      new_net_id = (pri_node, new_node, o_port, p_minor, new_minor, o_secret)
5611

    
5612
      iv_names[idx] = (dev, dev.children, new_net_id)
5613
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
5614
                    new_net_id)
5615
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
5616
                              logical_id=new_alone_id,
5617
                              children=dev.children,
5618
                              size=dev.size)
5619
      try:
5620
        _CreateSingleBlockDev(self, new_node, instance, new_drbd,
5621
                              _GetInstanceInfoText(instance), False)
5622
      except errors.GenericError:
5623
        self.cfg.ReleaseDRBDMinors(instance.name)
5624
        raise
5625

    
5626
    for idx, dev in enumerate(instance.disks):
5627
      # we have new devices, shutdown the drbd on the old secondary
5628
      info("shutting down drbd for disk/%d on old node" % idx)
5629
      cfg.SetDiskID(dev, old_node)
5630
      msg = self.rpc.call_blockdev_shutdown(old_node, dev).RemoteFailMsg()
5631
      if msg:
5632
        warning("Failed to shutdown drbd for disk/%d on old node: %s" %
5633
                (idx, msg),
5634
                hint="Please cleanup this device manually as soon as possible")
5635

    
5636
    info("detaching primary drbds from the network (=> standalone)")
5637
    result = self.rpc.call_drbd_disconnect_net([pri_node], nodes_ip,
5638
                                               instance.disks)[pri_node]
5639

    
5640
    msg = result.RemoteFailMsg()
5641
    if msg:
5642
      # detaches didn't succeed (unlikely)
5643
      self.cfg.ReleaseDRBDMinors(instance.name)
5644
      raise errors.OpExecError("Can't detach the disks from the network on"
5645
                               " old node: %s" % (msg,))
5646

    
5647
    # if we managed to detach at least one, we update all the disks of
5648
    # the instance to point to the new secondary
5649
    info("updating instance configuration")
5650
    for dev, _, new_logical_id in iv_names.itervalues():
5651
      dev.logical_id = new_logical_id
5652
      cfg.SetDiskID(dev, pri_node)
5653
    cfg.Update(instance)
5654

    
5655
    # and now perform the drbd attach
5656
    info("attaching primary drbds to new secondary (standalone => connected)")
5657
    result = self.rpc.call_drbd_attach_net([pri_node, new_node], nodes_ip,
5658
                                           instance.disks, instance.name,
5659
                                           False)
5660
    for to_node, to_result in result.items():
5661
      msg = to_result.RemoteFailMsg()
5662
      if msg:
5663
        warning("can't attach drbd disks on node %s: %s", to_node, msg,
5664
                hint="please do a gnt-instance info to see the"
5665
                " status of disks")
5666

    
5667
    # this can fail as the old devices are degraded and _WaitForSync
5668
    # does a combined result over all disks, so we don't check its
5669
    # return value
5670
    self.proc.LogStep(5, steps_total, "sync devices")
5671
    _WaitForSync(self, instance, unlock=True)
5672

    
5673
    # so check manually all the devices
5674
    for idx, (dev, old_lvs, _) in iv_names.iteritems():
5675
      cfg.SetDiskID(dev, pri_node)
5676
      result = self.rpc.call_blockdev_find(pri_node, dev)
5677
      msg = result.RemoteFailMsg()
5678
      if not msg and not result.payload:
5679
        msg = "disk not found"
5680
      if msg:
5681
        raise errors.OpExecError("Can't find DRBD device disk/%d: %s" %
5682
                                 (idx, msg))
5683
      if result.payload[5]:
5684
        raise errors.OpExecError("DRBD device disk/%d is degraded!" % idx)
5685

    
5686
    self.proc.LogStep(6, steps_total, "removing old storage")
5687
    for idx, (dev, old_lvs, _) in iv_names.iteritems():
5688
      info("remove logical volumes for disk/%d" % idx)
5689
      for lv in old_lvs:
5690
        cfg.SetDiskID(lv, old_node)
5691
        msg = self.rpc.call_blockdev_remove(old_node, lv).RemoteFailMsg()
5692
        if msg:
5693
          warning("Can't remove LV on old secondary: %s", msg,
5694
                  hint="Cleanup stale volumes by hand")
5695

    
5696
  def Exec(self, feedback_fn):
5697
    """Execute disk replacement.
5698

5699
    This dispatches the disk replacement to the appropriate handler.
5700

5701
    """
5702
    instance = self.instance
5703

    
5704
    # Activate the instance disks if we're replacing them on a down instance
5705
    if not instance.admin_up:
5706
      _StartInstanceDisks(self, instance, True)
5707

    
5708
    if self.op.mode == constants.REPLACE_DISK_CHG:
5709
      fn = self._ExecD8Secondary
5710
    else:
5711
      fn = self._ExecD8DiskOnly
5712

    
5713
    ret = fn(feedback_fn)
5714

    
5715
    # Deactivate the instance disks if we're replacing them on a down instance
5716
    if not instance.admin_up:
5717
      _SafeShutdownInstanceDisks(self, instance)
5718

    
5719
    return ret
5720

    
5721

    
5722
class LUGrowDisk(LogicalUnit):
5723
  """Grow a disk of an instance.
5724

5725
  """
5726
  HPATH = "disk-grow"
5727
  HTYPE = constants.HTYPE_INSTANCE
5728
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
5729
  REQ_BGL = False
5730

    
5731
  def ExpandNames(self):
5732
    self._ExpandAndLockInstance()
5733
    self.needed_locks[locking.LEVEL_NODE] = []
5734
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5735

    
5736
  def DeclareLocks(self, level):
5737
    if level == locking.LEVEL_NODE:
5738
      self._LockInstancesNodes()
5739

    
5740
  def BuildHooksEnv(self):
5741
    """Build hooks env.
5742

5743
    This runs on the master, the primary and all the secondaries.
5744

5745
    """
5746
    env = {
5747
      "DISK": self.op.disk,
5748
      "AMOUNT": self.op.amount,
5749
      }
5750
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5751
    nl = [
5752
      self.cfg.GetMasterNode(),
5753
      self.instance.primary_node,
5754
      ]
5755
    return env, nl, nl
5756

    
5757
  def CheckPrereq(self):
5758
    """Check prerequisites.
5759

5760
    This checks that the instance is in the cluster.
5761

5762
    """
5763
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5764
    assert instance is not None, \
5765
      "Cannot retrieve locked instance %s" % self.op.instance_name
5766
    nodenames = list(instance.all_nodes)
5767
    for node in nodenames:
5768
      _CheckNodeOnline(self, node)
5769

    
5770

    
5771
    self.instance = instance
5772

    
5773
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
5774
      raise errors.OpPrereqError("Instance's disk layout does not support"
5775
                                 " growing.")
5776

    
5777
    self.disk = instance.FindDisk(self.op.disk)
5778

    
5779
    nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
5780
                                       instance.hypervisor)
5781
    for node in nodenames:
5782
      info = nodeinfo[node]
5783
      if info.failed or not info.data:
5784
        raise errors.OpPrereqError("Cannot get current information"
5785
                                   " from node '%s'" % node)
5786
      vg_free = info.data.get('vg_free', None)
5787
      if not isinstance(vg_free, int):
5788
        raise errors.OpPrereqError("Can't compute free disk space on"
5789
                                   " node %s" % node)
5790
      if self.op.amount > vg_free:
5791
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
5792
                                   " %d MiB available, %d MiB required" %
5793
                                   (node, vg_free, self.op.amount))
5794

    
5795
  def Exec(self, feedback_fn):
5796
    """Execute disk grow.
5797

5798
    """
5799
    instance = self.instance
5800
    disk = self.disk
5801
    for node in instance.all_nodes:
5802
      self.cfg.SetDiskID(disk, node)
5803
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
5804
      msg = result.RemoteFailMsg()
5805
      if msg:
5806
        raise errors.OpExecError("Grow request failed to node %s: %s" %
5807
                                 (node, msg))
5808
    disk.RecordGrow(self.op.amount)
5809
    self.cfg.Update(instance)
5810
    if self.op.wait_for_sync:
5811
      disk_abort = not _WaitForSync(self, instance)
5812
      if disk_abort:
5813
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
5814
                             " status.\nPlease check the instance.")
5815

    
5816

    
5817
class LUQueryInstanceData(NoHooksLU):
5818
  """Query runtime instance data.
5819

5820
  """
5821
  _OP_REQP = ["instances", "static"]
5822
  REQ_BGL = False
5823

    
5824
  def ExpandNames(self):
5825
    self.needed_locks = {}
5826
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
5827

    
5828
    if not isinstance(self.op.instances, list):
5829
      raise errors.OpPrereqError("Invalid argument type 'instances'")
5830

    
5831
    if self.op.instances:
5832
      self.wanted_names = []
5833
      for name in self.op.instances:
5834
        full_name = self.cfg.ExpandInstanceName(name)
5835
        if full_name is None:
5836
          raise errors.OpPrereqError("Instance '%s' not known" % name)
5837
        self.wanted_names.append(full_name)
5838
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
5839
    else:
5840
      self.wanted_names = None
5841
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
5842

    
5843
    self.needed_locks[locking.LEVEL_NODE] = []
5844
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5845

    
5846
  def DeclareLocks(self, level):
5847
    if level == locking.LEVEL_NODE:
5848
      self._LockInstancesNodes()
5849

    
5850
  def CheckPrereq(self):
5851
    """Check prerequisites.
5852

5853
    This only checks the optional instance list against the existing names.
5854

5855
    """
5856
    if self.wanted_names is None:
5857
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5858

    
5859
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
5860
                             in self.wanted_names]
5861
    return
5862

    
5863
  def _ComputeDiskStatus(self, instance, snode, dev):
5864
    """Compute block device status.
5865

5866
    """
5867
    static = self.op.static
5868
    if not static:
5869
      self.cfg.SetDiskID(dev, instance.primary_node)
5870
      dev_pstatus = self.rpc.call_blockdev_find(instance.primary_node, dev)
5871
      if dev_pstatus.offline:
5872
        dev_pstatus = None
5873
      else:
5874
        msg = dev_pstatus.RemoteFailMsg()
5875
        if msg:
5876
          raise errors.OpExecError("Can't compute disk status for %s: %s" %
5877
                                   (instance.name, msg))
5878
        dev_pstatus = dev_pstatus.payload
5879
    else:
5880
      dev_pstatus = None
5881

    
5882
    if dev.dev_type in constants.LDS_DRBD:
5883
      # we change the snode then (otherwise we use the one passed in)
5884
      if dev.logical_id[0] == instance.primary_node:
5885
        snode = dev.logical_id[1]
5886
      else:
5887
        snode = dev.logical_id[0]
5888

    
5889
    if snode and not static:
5890
      self.cfg.SetDiskID(dev, snode)
5891
      dev_sstatus = self.rpc.call_blockdev_find(snode, dev)
5892
      if dev_sstatus.offline:
5893
        dev_sstatus = None
5894
      else:
5895
        msg = dev_sstatus.RemoteFailMsg()
5896
        if msg:
5897
          raise errors.OpExecError("Can't compute disk status for %s: %s" %
5898
                                   (instance.name, msg))
5899
        dev_sstatus = dev_sstatus.payload
5900
    else:
5901
      dev_sstatus = None
5902

    
5903
    if dev.children:
5904
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
5905
                      for child in dev.children]
5906
    else:
5907
      dev_children = []
5908

    
5909
    data = {
5910
      "iv_name": dev.iv_name,
5911
      "dev_type": dev.dev_type,
5912
      "logical_id": dev.logical_id,
5913
      "physical_id": dev.physical_id,
5914
      "pstatus": dev_pstatus,
5915
      "sstatus": dev_sstatus,
5916
      "children": dev_children,
5917
      "mode": dev.mode,
5918
      "size": dev.size,
5919
      }
5920

    
5921
    return data
5922

    
5923
  def Exec(self, feedback_fn):
5924
    """Gather and return data"""
5925
    result = {}
5926

    
5927
    cluster = self.cfg.GetClusterInfo()
5928

    
5929
    for instance in self.wanted_instances:
5930
      if not self.op.static:
5931
        remote_info = self.rpc.call_instance_info(instance.primary_node,
5932
                                                  instance.name,
5933
                                                  instance.hypervisor)
5934
        remote_info.Raise()
5935
        remote_info = remote_info.data
5936
        if remote_info and "state" in remote_info:
5937
          remote_state = "up"
5938
        else:
5939
          remote_state = "down"
5940
      else:
5941
        remote_state = None
5942
      if instance.admin_up:
5943
        config_state = "up"
5944
      else:
5945
        config_state = "down"
5946

    
5947
      disks = [self._ComputeDiskStatus(instance, None, device)
5948
               for device in instance.disks]
5949

    
5950
      idict = {
5951
        "name": instance.name,
5952
        "config_state": config_state,
5953
        "run_state": remote_state,
5954
        "pnode": instance.primary_node,
5955
        "snodes": instance.secondary_nodes,
5956
        "os": instance.os,
5957
        "nics": [(nic.mac, nic.ip, nic.bridge) for nic in instance.nics],
5958
        "disks": disks,
5959
        "hypervisor": instance.hypervisor,
5960
        "network_port": instance.network_port,
5961
        "hv_instance": instance.hvparams,
5962
        "hv_actual": cluster.FillHV(instance),
5963
        "be_instance": instance.beparams,
5964
        "be_actual": cluster.FillBE(instance),
5965
        }
5966

    
5967
      result[instance.name] = idict
5968

    
5969
    return result
5970

    
5971

    
5972
class LUSetInstanceParams(LogicalUnit):
5973
  """Modifies an instances's parameters.
5974

5975
  """
5976
  HPATH = "instance-modify"
5977
  HTYPE = constants.HTYPE_INSTANCE
5978
  _OP_REQP = ["instance_name"]
5979
  REQ_BGL = False
5980

    
5981
  def CheckArguments(self):
5982
    if not hasattr(self.op, 'nics'):
5983
      self.op.nics = []
5984
    if not hasattr(self.op, 'disks'):
5985
      self.op.disks = []
5986
    if not hasattr(self.op, 'beparams'):
5987
      self.op.beparams = {}
5988
    if not hasattr(self.op, 'hvparams'):
5989
      self.op.hvparams = {}
5990
    self.op.force = getattr(self.op, "force", False)
5991
    if not (self.op.nics or self.op.disks or
5992
            self.op.hvparams or self.op.beparams):
5993
      raise errors.OpPrereqError("No changes submitted")
5994

    
5995
    # Disk validation
5996
    disk_addremove = 0
5997
    for disk_op, disk_dict in self.op.disks:
5998
      if disk_op == constants.DDM_REMOVE:
5999
        disk_addremove += 1
6000
        continue
6001
      elif disk_op == constants.DDM_ADD:
6002
        disk_addremove += 1
6003
      else:
6004
        if not isinstance(disk_op, int):
6005
          raise errors.OpPrereqError("Invalid disk index")
6006
      if disk_op == constants.DDM_ADD:
6007
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
6008
        if mode not in constants.DISK_ACCESS_SET:
6009
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode)
6010
        size = disk_dict.get('size', None)
6011
        if size is None:
6012
          raise errors.OpPrereqError("Required disk parameter size missing")
6013
        try:
6014
          size = int(size)
6015
        except ValueError, err:
6016
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
6017
                                     str(err))
6018
        disk_dict['size'] = size
6019
      else:
6020
        # modification of disk
6021
        if 'size' in disk_dict:
6022
          raise errors.OpPrereqError("Disk size change not possible, use"
6023
                                     " grow-disk")
6024

    
6025
    if disk_addremove > 1:
6026
      raise errors.OpPrereqError("Only one disk add or remove operation"
6027
                                 " supported at a time")
6028

    
6029
    # NIC validation
6030
    nic_addremove = 0
6031
    for nic_op, nic_dict in self.op.nics:
6032
      if nic_op == constants.DDM_REMOVE:
6033
        nic_addremove += 1
6034
        continue
6035
      elif nic_op == constants.DDM_ADD:
6036
        nic_addremove += 1
6037
      else:
6038
        if not isinstance(nic_op, int):
6039
          raise errors.OpPrereqError("Invalid nic index")
6040

    
6041
      # nic_dict should be a dict
6042
      nic_ip = nic_dict.get('ip', None)
6043
      if nic_ip is not None:
6044
        if nic_ip.lower() == constants.VALUE_NONE:
6045
          nic_dict['ip'] = None
6046
        else:
6047
          if not utils.IsValidIP(nic_ip):
6048
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip)
6049

    
6050
      if nic_op == constants.DDM_ADD:
6051
        nic_bridge = nic_dict.get('bridge', None)
6052
        if nic_bridge is None:
6053
          nic_dict['bridge'] = self.cfg.GetDefBridge()
6054
        nic_mac = nic_dict.get('mac', None)
6055
        if nic_mac is None:
6056
          nic_dict['mac'] = constants.VALUE_AUTO
6057

    
6058
      if 'mac' in nic_dict:
6059
        nic_mac = nic_dict['mac']
6060
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
6061
          if not utils.IsValidMac(nic_mac):
6062
            raise errors.OpPrereqError("Invalid MAC address %s" % nic_mac)
6063
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
6064
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
6065
                                     " modifying an existing nic")
6066

    
6067
    if nic_addremove > 1:
6068
      raise errors.OpPrereqError("Only one NIC add or remove operation"
6069
                                 " supported at a time")
6070

    
6071
  def ExpandNames(self):
6072
    self._ExpandAndLockInstance()
6073
    self.needed_locks[locking.LEVEL_NODE] = []
6074
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6075

    
6076
  def DeclareLocks(self, level):
6077
    if level == locking.LEVEL_NODE:
6078
      self._LockInstancesNodes()
6079

    
6080
  def BuildHooksEnv(self):
6081
    """Build hooks env.
6082

6083
    This runs on the master, primary and secondaries.
6084

6085
    """
6086
    args = dict()
6087
    if constants.BE_MEMORY in self.be_new:
6088
      args['memory'] = self.be_new[constants.BE_MEMORY]
6089
    if constants.BE_VCPUS in self.be_new:
6090
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
6091
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
6092
    # information at all.
6093
    if self.op.nics:
6094
      args['nics'] = []
6095
      nic_override = dict(self.op.nics)
6096
      for idx, nic in enumerate(self.instance.nics):
6097
        if idx in nic_override:
6098
          this_nic_override = nic_override[idx]
6099
        else:
6100
          this_nic_override = {}
6101
        if 'ip' in this_nic_override:
6102
          ip = this_nic_override['ip']
6103
        else:
6104
          ip = nic.ip
6105
        if 'bridge' in this_nic_override:
6106
          bridge = this_nic_override['bridge']
6107
        else:
6108
          bridge = nic.bridge
6109
        if 'mac' in this_nic_override:
6110
          mac = this_nic_override['mac']
6111
        else:
6112
          mac = nic.mac
6113
        args['nics'].append((ip, bridge, mac))
6114
      if constants.DDM_ADD in nic_override:
6115
        ip = nic_override[constants.DDM_ADD].get('ip', None)
6116
        bridge = nic_override[constants.DDM_ADD]['bridge']
6117
        mac = nic_override[constants.DDM_ADD]['mac']
6118
        args['nics'].append((ip, bridge, mac))
6119
      elif constants.DDM_REMOVE in nic_override:
6120
        del args['nics'][-1]
6121

    
6122
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
6123
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6124
    return env, nl, nl
6125

    
6126
  def CheckPrereq(self):
6127
    """Check prerequisites.
6128

6129
    This only checks the instance list against the existing names.
6130

6131
    """
6132
    self.force = self.op.force
6133

    
6134
    # checking the new params on the primary/secondary nodes
6135

    
6136
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6137
    assert self.instance is not None, \
6138
      "Cannot retrieve locked instance %s" % self.op.instance_name
6139
    pnode = instance.primary_node
6140
    nodelist = list(instance.all_nodes)
6141

    
6142
    # hvparams processing
6143
    if self.op.hvparams:
6144
      i_hvdict = copy.deepcopy(instance.hvparams)
6145
      for key, val in self.op.hvparams.iteritems():
6146
        if val == constants.VALUE_DEFAULT:
6147
          try:
6148
            del i_hvdict[key]
6149
          except KeyError:
6150
            pass
6151
        else:
6152
          i_hvdict[key] = val
6153
      cluster = self.cfg.GetClusterInfo()
6154
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
6155
      hv_new = cluster.FillDict(cluster.hvparams[instance.hypervisor],
6156
                                i_hvdict)
6157
      # local check
6158
      hypervisor.GetHypervisor(
6159
        instance.hypervisor).CheckParameterSyntax(hv_new)
6160
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
6161
      self.hv_new = hv_new # the new actual values
6162
      self.hv_inst = i_hvdict # the new dict (without defaults)
6163
    else:
6164
      self.hv_new = self.hv_inst = {}
6165

    
6166
    # beparams processing
6167
    if self.op.beparams:
6168
      i_bedict = copy.deepcopy(instance.beparams)
6169
      for key, val in self.op.beparams.iteritems():
6170
        if val == constants.VALUE_DEFAULT:
6171
          try:
6172
            del i_bedict[key]
6173
          except KeyError:
6174
            pass
6175
        else:
6176
          i_bedict[key] = val
6177
      cluster = self.cfg.GetClusterInfo()
6178
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
6179
      be_new = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
6180
                                i_bedict)
6181
      self.be_new = be_new # the new actual values
6182
      self.be_inst = i_bedict # the new dict (without defaults)
6183
    else:
6184
      self.be_new = self.be_inst = {}
6185

    
6186
    self.warn = []
6187

    
6188
    if constants.BE_MEMORY in self.op.beparams and not self.force:
6189
      mem_check_list = [pnode]
6190
      if be_new[constants.BE_AUTO_BALANCE]:
6191
        # either we changed auto_balance to yes or it was from before
6192
        mem_check_list.extend(instance.secondary_nodes)
6193
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
6194
                                                  instance.hypervisor)
6195
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
6196
                                         instance.hypervisor)
6197
      if nodeinfo[pnode].failed or not isinstance(nodeinfo[pnode].data, dict):
6198
        # Assume the primary node is unreachable and go ahead
6199
        self.warn.append("Can't get info from primary node %s" % pnode)
6200
      else:
6201
        if not instance_info.failed and instance_info.data:
6202
          current_mem = int(instance_info.data['memory'])
6203
        else:
6204
          # Assume instance not running
6205
          # (there is a slight race condition here, but it's not very probable,
6206
          # and we have no other way to check)
6207
          current_mem = 0
6208
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
6209
                    nodeinfo[pnode].data['memory_free'])
6210
        if miss_mem > 0:
6211
          raise errors.OpPrereqError("This change will prevent the instance"
6212
                                     " from starting, due to %d MB of memory"
6213
                                     " missing on its primary node" % miss_mem)
6214

    
6215
      if be_new[constants.BE_AUTO_BALANCE]:
6216
        for node, nres in nodeinfo.iteritems():
6217
          if node not in instance.secondary_nodes:
6218
            continue
6219
          if nres.failed or not isinstance(nres.data, dict):
6220
            self.warn.append("Can't get info from secondary node %s" % node)
6221
          elif be_new[constants.BE_MEMORY] > nres.data['memory_free']:
6222
            self.warn.append("Not enough memory to failover instance to"
6223
                             " secondary node %s" % node)
6224

    
6225
    # NIC processing
6226
    for nic_op, nic_dict in self.op.nics:
6227
      if nic_op == constants.DDM_REMOVE:
6228
        if not instance.nics:
6229
          raise errors.OpPrereqError("Instance has no NICs, cannot remove")
6230
        continue
6231
      if nic_op != constants.DDM_ADD:
6232
        # an existing nic
6233
        if nic_op < 0 or nic_op >= len(instance.nics):
6234
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
6235
                                     " are 0 to %d" %
6236
                                     (nic_op, len(instance.nics)))
6237
      if 'bridge' in nic_dict:
6238
        nic_bridge = nic_dict['bridge']
6239
        if nic_bridge is None:
6240
          raise errors.OpPrereqError('Cannot set the nic bridge to None')
6241
        if not self.rpc.call_bridges_exist(pnode, [nic_bridge]):
6242
          msg = ("Bridge '%s' doesn't exist on one of"
6243
                 " the instance nodes" % nic_bridge)
6244
          if self.force:
6245
            self.warn.append(msg)
6246
          else:
6247
            raise errors.OpPrereqError(msg)
6248
      if 'mac' in nic_dict:
6249
        nic_mac = nic_dict['mac']
6250
        if nic_mac is None:
6251
          raise errors.OpPrereqError('Cannot set the nic mac to None')
6252
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
6253
          # otherwise generate the mac
6254
          nic_dict['mac'] = self.cfg.GenerateMAC()
6255
        else:
6256
          # or validate/reserve the current one
6257
          if self.cfg.IsMacInUse(nic_mac):
6258
            raise errors.OpPrereqError("MAC address %s already in use"
6259
                                       " in cluster" % nic_mac)
6260

    
6261
    # DISK processing
6262
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
6263
      raise errors.OpPrereqError("Disk operations not supported for"
6264
                                 " diskless instances")
6265
    for disk_op, disk_dict in self.op.disks:
6266
      if disk_op == constants.DDM_REMOVE:
6267
        if len(instance.disks) == 1:
6268
          raise errors.OpPrereqError("Cannot remove the last disk of"
6269
                                     " an instance")
6270
        ins_l = self.rpc.call_instance_list([pnode], [instance.hypervisor])
6271
        ins_l = ins_l[pnode]
6272
        if ins_l.failed or not isinstance(ins_l.data, list):
6273
          raise errors.OpPrereqError("Can't contact node '%s'" % pnode)
6274
        if instance.name in ins_l.data:
6275
          raise errors.OpPrereqError("Instance is running, can't remove"
6276
                                     " disks.")
6277

    
6278
      if (disk_op == constants.DDM_ADD and
6279
          len(instance.nics) >= constants.MAX_DISKS):
6280
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
6281
                                   " add more" % constants.MAX_DISKS)
6282
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
6283
        # an existing disk
6284
        if disk_op < 0 or disk_op >= len(instance.disks):
6285
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
6286
                                     " are 0 to %d" %
6287
                                     (disk_op, len(instance.disks)))
6288

    
6289
    return
6290

    
6291
  def Exec(self, feedback_fn):
6292
    """Modifies an instance.
6293

6294
    All parameters take effect only at the next restart of the instance.
6295

6296
    """
6297
    # Process here the warnings from CheckPrereq, as we don't have a
6298
    # feedback_fn there.
6299
    for warn in self.warn:
6300
      feedback_fn("WARNING: %s" % warn)
6301

    
6302
    result = []
6303
    instance = self.instance
6304
    # disk changes
6305
    for disk_op, disk_dict in self.op.disks:
6306
      if disk_op == constants.DDM_REMOVE:
6307
        # remove the last disk
6308
        device = instance.disks.pop()
6309
        device_idx = len(instance.disks)
6310
        for node, disk in device.ComputeNodeTree(instance.primary_node):
6311
          self.cfg.SetDiskID(disk, node)
6312
          msg = self.rpc.call_blockdev_remove(node, disk).RemoteFailMsg()
6313
          if msg:
6314
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
6315
                            " continuing anyway", device_idx, node, msg)
6316
        result.append(("disk/%d" % device_idx, "remove"))
6317
      elif disk_op == constants.DDM_ADD:
6318
        # add a new disk
6319
        if instance.disk_template == constants.DT_FILE:
6320
          file_driver, file_path = instance.disks[0].logical_id
6321
          file_path = os.path.dirname(file_path)
6322
        else:
6323
          file_driver = file_path = None
6324
        disk_idx_base = len(instance.disks)
6325
        new_disk = _GenerateDiskTemplate(self,
6326
                                         instance.disk_template,
6327
                                         instance.name, instance.primary_node,
6328
                                         instance.secondary_nodes,
6329
                                         [disk_dict],
6330
                                         file_path,
6331
                                         file_driver,
6332
                                         disk_idx_base)[0]
6333
        instance.disks.append(new_disk)
6334
        info = _GetInstanceInfoText(instance)
6335

    
6336
        logging.info("Creating volume %s for instance %s",
6337
                     new_disk.iv_name, instance.name)
6338
        # Note: this needs to be kept in sync with _CreateDisks
6339
        #HARDCODE
6340
        for node in instance.all_nodes:
6341
          f_create = node == instance.primary_node
6342
          try:
6343
            _CreateBlockDev(self, node, instance, new_disk,
6344
                            f_create, info, f_create)
6345
          except errors.OpExecError, err:
6346
            self.LogWarning("Failed to create volume %s (%s) on"
6347
                            " node %s: %s",
6348
                            new_disk.iv_name, new_disk, node, err)
6349
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
6350
                       (new_disk.size, new_disk.mode)))
6351
      else:
6352
        # change a given disk
6353
        instance.disks[disk_op].mode = disk_dict['mode']
6354
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
6355
    # NIC changes
6356
    for nic_op, nic_dict in self.op.nics:
6357
      if nic_op == constants.DDM_REMOVE:
6358
        # remove the last nic
6359
        del instance.nics[-1]
6360
        result.append(("nic.%d" % len(instance.nics), "remove"))
6361
      elif nic_op == constants.DDM_ADD:
6362
        # mac and bridge should be set, by now
6363
        mac = nic_dict['mac']
6364
        bridge = nic_dict['bridge']
6365
        new_nic = objects.NIC(mac=mac, ip=nic_dict.get('ip', None),
6366
                              bridge=bridge)
6367
        instance.nics.append(new_nic)
6368
        result.append(("nic.%d" % (len(instance.nics) - 1),
6369
                       "add:mac=%s,ip=%s,bridge=%s" %
6370
                       (new_nic.mac, new_nic.ip, new_nic.bridge)))
6371
      else:
6372
        # change a given nic
6373
        for key in 'mac', 'ip', 'bridge':
6374
          if key in nic_dict:
6375
            setattr(instance.nics[nic_op], key, nic_dict[key])
6376
            result.append(("nic.%s/%d" % (key, nic_op), nic_dict[key]))
6377

    
6378
    # hvparams changes
6379
    if self.op.hvparams:
6380
      instance.hvparams = self.hv_inst
6381
      for key, val in self.op.hvparams.iteritems():
6382
        result.append(("hv/%s" % key, val))
6383

    
6384
    # beparams changes
6385
    if self.op.beparams:
6386
      instance.beparams = self.be_inst
6387
      for key, val in self.op.beparams.iteritems():
6388
        result.append(("be/%s" % key, val))
6389

    
6390
    self.cfg.Update(instance)
6391

    
6392
    return result
6393

    
6394

    
6395
class LUQueryExports(NoHooksLU):
6396
  """Query the exports list
6397

6398
  """
6399
  _OP_REQP = ['nodes']
6400
  REQ_BGL = False
6401

    
6402
  def ExpandNames(self):
6403
    self.needed_locks = {}
6404
    self.share_locks[locking.LEVEL_NODE] = 1
6405
    if not self.op.nodes:
6406
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6407
    else:
6408
      self.needed_locks[locking.LEVEL_NODE] = \
6409
        _GetWantedNodes(self, self.op.nodes)
6410

    
6411
  def CheckPrereq(self):
6412
    """Check prerequisites.
6413

6414
    """
6415
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
6416

    
6417
  def Exec(self, feedback_fn):
6418
    """Compute the list of all the exported system images.
6419

6420
    @rtype: dict
6421
    @return: a dictionary with the structure node->(export-list)
6422
        where export-list is a list of the instances exported on
6423
        that node.
6424

6425
    """
6426
    rpcresult = self.rpc.call_export_list(self.nodes)
6427
    result = {}
6428
    for node in rpcresult:
6429
      if rpcresult[node].failed:
6430
        result[node] = False
6431
      else:
6432
        result[node] = rpcresult[node].data
6433

    
6434
    return result
6435

    
6436

    
6437
class LUExportInstance(LogicalUnit):
6438
  """Export an instance to an image in the cluster.
6439

6440
  """
6441
  HPATH = "instance-export"
6442
  HTYPE = constants.HTYPE_INSTANCE
6443
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
6444
  REQ_BGL = False
6445

    
6446
  def ExpandNames(self):
6447
    self._ExpandAndLockInstance()
6448
    # FIXME: lock only instance primary and destination node
6449
    #
6450
    # Sad but true, for now we have do lock all nodes, as we don't know where
6451
    # the previous export might be, and and in this LU we search for it and
6452
    # remove it from its current node. In the future we could fix this by:
6453
    #  - making a tasklet to search (share-lock all), then create the new one,
6454
    #    then one to remove, after
6455
    #  - removing the removal operation altogether
6456
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6457

    
6458
  def DeclareLocks(self, level):
6459
    """Last minute lock declaration."""
6460
    # All nodes are locked anyway, so nothing to do here.
6461

    
6462
  def BuildHooksEnv(self):
6463
    """Build hooks env.
6464

6465
    This will run on the master, primary node and target node.
6466

6467
    """
6468
    env = {
6469
      "EXPORT_NODE": self.op.target_node,
6470
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
6471
      }
6472
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6473
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node,
6474
          self.op.target_node]
6475
    return env, nl, nl
6476

    
6477
  def CheckPrereq(self):
6478
    """Check prerequisites.
6479

6480
    This checks that the instance and node names are valid.
6481

6482
    """
6483
    instance_name = self.op.instance_name
6484
    self.instance = self.cfg.GetInstanceInfo(instance_name)
6485
    assert self.instance is not None, \
6486
          "Cannot retrieve locked instance %s" % self.op.instance_name
6487
    _CheckNodeOnline(self, self.instance.primary_node)
6488

    
6489
    self.dst_node = self.cfg.GetNodeInfo(
6490
      self.cfg.ExpandNodeName(self.op.target_node))
6491

    
6492
    if self.dst_node is None:
6493
      # This is wrong node name, not a non-locked node
6494
      raise errors.OpPrereqError("Wrong node name %s" % self.op.target_node)
6495
    _CheckNodeOnline(self, self.dst_node.name)
6496
    _CheckNodeNotDrained(self, self.dst_node.name)
6497

    
6498
    # instance disk type verification
6499
    for disk in self.instance.disks:
6500
      if disk.dev_type == constants.LD_FILE:
6501
        raise errors.OpPrereqError("Export not supported for instances with"
6502
                                   " file-based disks")
6503

    
6504
  def Exec(self, feedback_fn):
6505
    """Export an instance to an image in the cluster.
6506

6507
    """
6508
    instance = self.instance
6509
    dst_node = self.dst_node
6510
    src_node = instance.primary_node
6511
    if self.op.shutdown:
6512
      # shutdown the instance, but not the disks
6513
      result = self.rpc.call_instance_shutdown(src_node, instance)
6514
      msg = result.RemoteFailMsg()
6515
      if msg:
6516
        raise errors.OpExecError("Could not shutdown instance %s on"
6517
                                 " node %s: %s" %
6518
                                 (instance.name, src_node, msg))
6519

    
6520
    vgname = self.cfg.GetVGName()
6521

    
6522
    snap_disks = []
6523

    
6524
    # set the disks ID correctly since call_instance_start needs the
6525
    # correct drbd minor to create the symlinks
6526
    for disk in instance.disks:
6527
      self.cfg.SetDiskID(disk, src_node)
6528

    
6529
    # per-disk results
6530
    dresults = []
6531
    try:
6532
      for idx, disk in enumerate(instance.disks):
6533
        # new_dev_name will be a snapshot of an lvm leaf of the one we passed
6534
        new_dev_name = self.rpc.call_blockdev_snapshot(src_node, disk)
6535
        if new_dev_name.failed or not new_dev_name.data:
6536
          self.LogWarning("Could not snapshot disk/%d on node %s",
6537
                          idx, src_node)
6538
          snap_disks.append(False)
6539
        else:
6540
          new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
6541
                                 logical_id=(vgname, new_dev_name.data),
6542
                                 physical_id=(vgname, new_dev_name.data),
6543
                                 iv_name=disk.iv_name)
6544
          snap_disks.append(new_dev)
6545

    
6546
    finally:
6547
      if self.op.shutdown and instance.admin_up:
6548
        result = self.rpc.call_instance_start(src_node, instance, None, None)
6549
        msg = result.RemoteFailMsg()
6550
        if msg:
6551
          _ShutdownInstanceDisks(self, instance)
6552
          raise errors.OpExecError("Could not start instance: %s" % msg)
6553

    
6554
    # TODO: check for size
6555

    
6556
    cluster_name = self.cfg.GetClusterName()
6557
    for idx, dev in enumerate(snap_disks):
6558
      if dev:
6559
        result = self.rpc.call_snapshot_export(src_node, dev, dst_node.name,
6560
                                               instance, cluster_name, idx)
6561
        if result.failed or not result.data:
6562
          self.LogWarning("Could not export disk/%d from node %s to"
6563
                          " node %s", idx, src_node, dst_node.name)
6564
          dresults.append(False)
6565
        else:
6566
          dresults.append(True)
6567
        msg = self.rpc.call_blockdev_remove(src_node, dev).RemoteFailMsg()
6568
        if msg:
6569
          self.LogWarning("Could not remove snapshot for disk/%d from node"
6570
                          " %s: %s", idx, src_node, msg)
6571
      else:
6572
        dresults.append(False)
6573

    
6574
    result = self.rpc.call_finalize_export(dst_node.name, instance, snap_disks)
6575
    fin_resu = True
6576
    if result.failed or not result.data:
6577
      self.LogWarning("Could not finalize export for instance %s on node %s",
6578
                      instance.name, dst_node.name)
6579
      fin_resu = False
6580

    
6581
    nodelist = self.cfg.GetNodeList()
6582
    nodelist.remove(dst_node.name)
6583

    
6584
    # on one-node clusters nodelist will be empty after the removal
6585
    # if we proceed the backup would be removed because OpQueryExports
6586
    # substitutes an empty list with the full cluster node list.
6587
    if nodelist:
6588
      exportlist = self.rpc.call_export_list(nodelist)
6589
      for node in exportlist:
6590
        if exportlist[node].failed:
6591
          continue
6592
        if instance.name in exportlist[node].data:
6593
          if not self.rpc.call_export_remove(node, instance.name):
6594
            self.LogWarning("Could not remove older export for instance %s"
6595
                            " on node %s", instance.name, node)
6596
    return fin_resu, dresults
6597

    
6598

    
6599
class LURemoveExport(NoHooksLU):
6600
  """Remove exports related to the named instance.
6601

6602
  """
6603
  _OP_REQP = ["instance_name"]
6604
  REQ_BGL = False
6605

    
6606
  def ExpandNames(self):
6607
    self.needed_locks = {}
6608
    # We need all nodes to be locked in order for RemoveExport to work, but we
6609
    # don't need to lock the instance itself, as nothing will happen to it (and
6610
    # we can remove exports also for a removed instance)
6611
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6612

    
6613
  def CheckPrereq(self):
6614
    """Check prerequisites.
6615
    """
6616
    pass
6617

    
6618
  def Exec(self, feedback_fn):
6619
    """Remove any export.
6620

6621
    """
6622
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
6623
    # If the instance was not found we'll try with the name that was passed in.
6624
    # This will only work if it was an FQDN, though.
6625
    fqdn_warn = False
6626
    if not instance_name:
6627
      fqdn_warn = True
6628
      instance_name = self.op.instance_name
6629

    
6630
    exportlist = self.rpc.call_export_list(self.acquired_locks[
6631
      locking.LEVEL_NODE])
6632
    found = False
6633
    for node in exportlist:
6634
      if exportlist[node].failed:
6635
        self.LogWarning("Failed to query node %s, continuing" % node)
6636
        continue
6637
      if instance_name in exportlist[node].data:
6638
        found = True
6639
        result = self.rpc.call_export_remove(node, instance_name)
6640
        if result.failed or not result.data:
6641
          logging.error("Could not remove export for instance %s"
6642
                        " on node %s", instance_name, node)
6643

    
6644
    if fqdn_warn and not found:
6645
      feedback_fn("Export not found. If trying to remove an export belonging"
6646
                  " to a deleted instance please use its Fully Qualified"
6647
                  " Domain Name.")
6648

    
6649

    
6650
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
6651
  """Generic tags LU.
6652

6653
  This is an abstract class which is the parent of all the other tags LUs.
6654

6655
  """
6656

    
6657
  def ExpandNames(self):
6658
    self.needed_locks = {}
6659
    if self.op.kind == constants.TAG_NODE:
6660
      name = self.cfg.ExpandNodeName(self.op.name)
6661
      if name is None:
6662
        raise errors.OpPrereqError("Invalid node name (%s)" %
6663
                                   (self.op.name,))
6664
      self.op.name = name
6665
      self.needed_locks[locking.LEVEL_NODE] = name
6666
    elif self.op.kind == constants.TAG_INSTANCE:
6667
      name = self.cfg.ExpandInstanceName(self.op.name)
6668
      if name is None:
6669
        raise errors.OpPrereqError("Invalid instance name (%s)" %
6670
                                   (self.op.name,))
6671
      self.op.name = name
6672
      self.needed_locks[locking.LEVEL_INSTANCE] = name
6673

    
6674
  def CheckPrereq(self):
6675
    """Check prerequisites.
6676

6677
    """
6678
    if self.op.kind == constants.TAG_CLUSTER:
6679
      self.target = self.cfg.GetClusterInfo()
6680
    elif self.op.kind == constants.TAG_NODE:
6681
      self.target = self.cfg.GetNodeInfo(self.op.name)
6682
    elif self.op.kind == constants.TAG_INSTANCE:
6683
      self.target = self.cfg.GetInstanceInfo(self.op.name)
6684
    else:
6685
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
6686
                                 str(self.op.kind))
6687

    
6688

    
6689
class LUGetTags(TagsLU):
6690
  """Returns the tags of a given object.
6691

6692
  """
6693
  _OP_REQP = ["kind", "name"]
6694
  REQ_BGL = False
6695

    
6696
  def Exec(self, feedback_fn):
6697
    """Returns the tag list.
6698

6699
    """
6700
    return list(self.target.GetTags())
6701

    
6702

    
6703
class LUSearchTags(NoHooksLU):
6704
  """Searches the tags for a given pattern.
6705

6706
  """
6707
  _OP_REQP = ["pattern"]
6708
  REQ_BGL = False
6709

    
6710
  def ExpandNames(self):
6711
    self.needed_locks = {}
6712

    
6713
  def CheckPrereq(self):
6714
    """Check prerequisites.
6715

6716
    This checks the pattern passed for validity by compiling it.
6717

6718
    """
6719
    try:
6720
      self.re = re.compile(self.op.pattern)
6721
    except re.error, err:
6722
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
6723
                                 (self.op.pattern, err))
6724

    
6725
  def Exec(self, feedback_fn):
6726
    """Returns the tag list.
6727

6728
    """
6729
    cfg = self.cfg
6730
    tgts = [("/cluster", cfg.GetClusterInfo())]
6731
    ilist = cfg.GetAllInstancesInfo().values()
6732
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
6733
    nlist = cfg.GetAllNodesInfo().values()
6734
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
6735
    results = []
6736
    for path, target in tgts:
6737
      for tag in target.GetTags():
6738
        if self.re.search(tag):
6739
          results.append((path, tag))
6740
    return results
6741

    
6742

    
6743
class LUAddTags(TagsLU):
6744
  """Sets a tag on a given object.
6745

6746
  """
6747
  _OP_REQP = ["kind", "name", "tags"]
6748
  REQ_BGL = False
6749

    
6750
  def CheckPrereq(self):
6751
    """Check prerequisites.
6752

6753
    This checks the type and length of the tag name and value.
6754

6755
    """
6756
    TagsLU.CheckPrereq(self)
6757
    for tag in self.op.tags:
6758
      objects.TaggableObject.ValidateTag(tag)
6759

    
6760
  def Exec(self, feedback_fn):
6761
    """Sets the tag.
6762

6763
    """
6764
    try:
6765
      for tag in self.op.tags:
6766
        self.target.AddTag(tag)
6767
    except errors.TagError, err:
6768
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
6769
    try:
6770
      self.cfg.Update(self.target)
6771
    except errors.ConfigurationError:
6772
      raise errors.OpRetryError("There has been a modification to the"
6773
                                " config file and the operation has been"
6774
                                " aborted. Please retry.")
6775

    
6776

    
6777
class LUDelTags(TagsLU):
6778
  """Delete a list of tags from a given object.
6779

6780
  """
6781
  _OP_REQP = ["kind", "name", "tags"]
6782
  REQ_BGL = False
6783

    
6784
  def CheckPrereq(self):
6785
    """Check prerequisites.
6786

6787
    This checks that we have the given tag.
6788

6789
    """
6790
    TagsLU.CheckPrereq(self)
6791
    for tag in self.op.tags:
6792
      objects.TaggableObject.ValidateTag(tag)
6793
    del_tags = frozenset(self.op.tags)
6794
    cur_tags = self.target.GetTags()
6795
    if not del_tags <= cur_tags:
6796
      diff_tags = del_tags - cur_tags
6797
      diff_names = ["'%s'" % tag for tag in diff_tags]
6798
      diff_names.sort()
6799
      raise errors.OpPrereqError("Tag(s) %s not found" %
6800
                                 (",".join(diff_names)))
6801

    
6802
  def Exec(self, feedback_fn):
6803
    """Remove the tag from the object.
6804

6805
    """
6806
    for tag in self.op.tags:
6807
      self.target.RemoveTag(tag)
6808
    try:
6809
      self.cfg.Update(self.target)
6810
    except errors.ConfigurationError:
6811
      raise errors.OpRetryError("There has been a modification to the"
6812
                                " config file and the operation has been"
6813
                                " aborted. Please retry.")
6814

    
6815

    
6816
class LUTestDelay(NoHooksLU):
6817
  """Sleep for a specified amount of time.
6818

6819
  This LU sleeps on the master and/or nodes for a specified amount of
6820
  time.
6821

6822
  """
6823
  _OP_REQP = ["duration", "on_master", "on_nodes"]
6824
  REQ_BGL = False
6825

    
6826
  def ExpandNames(self):
6827
    """Expand names and set required locks.
6828

6829
    This expands the node list, if any.
6830

6831
    """
6832
    self.needed_locks = {}
6833
    if self.op.on_nodes:
6834
      # _GetWantedNodes can be used here, but is not always appropriate to use
6835
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
6836
      # more information.
6837
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
6838
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
6839

    
6840
  def CheckPrereq(self):
6841
    """Check prerequisites.
6842

6843
    """
6844

    
6845
  def Exec(self, feedback_fn):
6846
    """Do the actual sleep.
6847

6848
    """
6849
    if self.op.on_master:
6850
      if not utils.TestDelay(self.op.duration):
6851
        raise errors.OpExecError("Error during master delay test")
6852
    if self.op.on_nodes:
6853
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
6854
      if not result:
6855
        raise errors.OpExecError("Complete failure from rpc call")
6856
      for node, node_result in result.items():
6857
        node_result.Raise()
6858
        if not node_result.data:
6859
          raise errors.OpExecError("Failure during rpc call to node %s,"
6860
                                   " result: %s" % (node, node_result.data))
6861

    
6862

    
6863
class IAllocator(object):
6864
  """IAllocator framework.
6865

6866
  An IAllocator instance has three sets of attributes:
6867
    - cfg that is needed to query the cluster
6868
    - input data (all members of the _KEYS class attribute are required)
6869
    - four buffer attributes (in|out_data|text), that represent the
6870
      input (to the external script) in text and data structure format,
6871
      and the output from it, again in two formats
6872
    - the result variables from the script (success, info, nodes) for
6873
      easy usage
6874

6875
  """
6876
  _ALLO_KEYS = [
6877
    "mem_size", "disks", "disk_template",
6878
    "os", "tags", "nics", "vcpus", "hypervisor",
6879
    ]
6880
  _RELO_KEYS = [
6881
    "relocate_from",
6882
    ]
6883

    
6884
  def __init__(self, lu, mode, name, **kwargs):
6885
    self.lu = lu
6886
    # init buffer variables
6887
    self.in_text = self.out_text = self.in_data = self.out_data = None
6888
    # init all input fields so that pylint is happy
6889
    self.mode = mode
6890
    self.name = name
6891
    self.mem_size = self.disks = self.disk_template = None
6892
    self.os = self.tags = self.nics = self.vcpus = None
6893
    self.hypervisor = None
6894
    self.relocate_from = None
6895
    # computed fields
6896
    self.required_nodes = None
6897
    # init result fields
6898
    self.success = self.info = self.nodes = None
6899
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6900
      keyset = self._ALLO_KEYS
6901
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
6902
      keyset = self._RELO_KEYS
6903
    else:
6904
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
6905
                                   " IAllocator" % self.mode)
6906
    for key in kwargs:
6907
      if key not in keyset:
6908
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
6909
                                     " IAllocator" % key)
6910
      setattr(self, key, kwargs[key])
6911
    for key in keyset:
6912
      if key not in kwargs:
6913
        raise errors.ProgrammerError("Missing input parameter '%s' to"
6914
                                     " IAllocator" % key)
6915
    self._BuildInputData()
6916

    
6917
  def _ComputeClusterData(self):
6918
    """Compute the generic allocator input data.
6919

6920
    This is the data that is independent of the actual operation.
6921

6922
    """
6923
    cfg = self.lu.cfg
6924
    cluster_info = cfg.GetClusterInfo()
6925
    # cluster data
6926
    data = {
6927
      "version": constants.IALLOCATOR_VERSION,
6928
      "cluster_name": cfg.GetClusterName(),
6929
      "cluster_tags": list(cluster_info.GetTags()),
6930
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
6931
      # we don't have job IDs
6932
      }
6933
    iinfo = cfg.GetAllInstancesInfo().values()
6934
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
6935

    
6936
    # node data
6937
    node_results = {}
6938
    node_list = cfg.GetNodeList()
6939

    
6940
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6941
      hypervisor_name = self.hypervisor
6942
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
6943
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
6944

    
6945
    node_data = self.lu.rpc.call_node_info(node_list, cfg.GetVGName(),
6946
                                           hypervisor_name)
6947
    node_iinfo = self.lu.rpc.call_all_instances_info(node_list,
6948
                       cluster_info.enabled_hypervisors)
6949
    for nname, nresult in node_data.items():
6950
      # first fill in static (config-based) values
6951
      ninfo = cfg.GetNodeInfo(nname)
6952
      pnr = {
6953
        "tags": list(ninfo.GetTags()),
6954
        "primary_ip": ninfo.primary_ip,
6955
        "secondary_ip": ninfo.secondary_ip,
6956
        "offline": ninfo.offline,
6957
        "drained": ninfo.drained,
6958
        "master_candidate": ninfo.master_candidate,
6959
        }
6960

    
6961
      if not (ninfo.offline or ninfo.drained):
6962
        nresult.Raise()
6963
        if not isinstance(nresult.data, dict):
6964
          raise errors.OpExecError("Can't get data for node %s" % nname)
6965
        remote_info = nresult.data
6966
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
6967
                     'vg_size', 'vg_free', 'cpu_total']:
6968
          if attr not in remote_info:
6969
            raise errors.OpExecError("Node '%s' didn't return attribute"
6970
                                     " '%s'" % (nname, attr))
6971
          try:
6972
            remote_info[attr] = int(remote_info[attr])
6973
          except ValueError, err:
6974
            raise errors.OpExecError("Node '%s' returned invalid value"
6975
                                     " for '%s': %s" % (nname, attr, err))
6976
        # compute memory used by primary instances
6977
        i_p_mem = i_p_up_mem = 0
6978
        for iinfo, beinfo in i_list:
6979
          if iinfo.primary_node == nname:
6980
            i_p_mem += beinfo[constants.BE_MEMORY]
6981
            if iinfo.name not in node_iinfo[nname].data:
6982
              i_used_mem = 0
6983
            else:
6984
              i_used_mem = int(node_iinfo[nname].data[iinfo.name]['memory'])
6985
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
6986
            remote_info['memory_free'] -= max(0, i_mem_diff)
6987

    
6988
            if iinfo.admin_up:
6989
              i_p_up_mem += beinfo[constants.BE_MEMORY]
6990

    
6991
        # compute memory used by instances
6992
        pnr_dyn = {
6993
          "total_memory": remote_info['memory_total'],
6994
          "reserved_memory": remote_info['memory_dom0'],
6995
          "free_memory": remote_info['memory_free'],
6996
          "total_disk": remote_info['vg_size'],
6997
          "free_disk": remote_info['vg_free'],
6998
          "total_cpus": remote_info['cpu_total'],
6999
          "i_pri_memory": i_p_mem,
7000
          "i_pri_up_memory": i_p_up_mem,
7001
          }
7002
        pnr.update(pnr_dyn)
7003

    
7004
      node_results[nname] = pnr
7005
    data["nodes"] = node_results
7006

    
7007
    # instance data
7008
    instance_data = {}
7009
    for iinfo, beinfo in i_list:
7010
      nic_data = [{"mac": n.mac, "ip": n.ip, "bridge": n.bridge}
7011
                  for n in iinfo.nics]
7012
      pir = {
7013
        "tags": list(iinfo.GetTags()),
7014
        "admin_up": iinfo.admin_up,
7015
        "vcpus": beinfo[constants.BE_VCPUS],
7016
        "memory": beinfo[constants.BE_MEMORY],
7017
        "os": iinfo.os,
7018
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
7019
        "nics": nic_data,
7020
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
7021
        "disk_template": iinfo.disk_template,
7022
        "hypervisor": iinfo.hypervisor,
7023
        }
7024
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
7025
                                                 pir["disks"])
7026
      instance_data[iinfo.name] = pir
7027

    
7028
    data["instances"] = instance_data
7029

    
7030
    self.in_data = data
7031

    
7032
  def _AddNewInstance(self):
7033
    """Add new instance data to allocator structure.
7034

7035
    This in combination with _AllocatorGetClusterData will create the
7036
    correct structure needed as input for the allocator.
7037

7038
    The checks for the completeness of the opcode must have already been
7039
    done.
7040

7041
    """
7042
    data = self.in_data
7043

    
7044
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
7045

    
7046
    if self.disk_template in constants.DTS_NET_MIRROR:
7047
      self.required_nodes = 2
7048
    else:
7049
      self.required_nodes = 1
7050
    request = {
7051
      "type": "allocate",
7052
      "name": self.name,
7053
      "disk_template": self.disk_template,
7054
      "tags": self.tags,
7055
      "os": self.os,
7056
      "vcpus": self.vcpus,
7057
      "memory": self.mem_size,
7058
      "disks": self.disks,
7059
      "disk_space_total": disk_space,
7060
      "nics": self.nics,
7061
      "required_nodes": self.required_nodes,
7062
      }
7063
    data["request"] = request
7064

    
7065
  def _AddRelocateInstance(self):
7066
    """Add relocate instance data to allocator structure.
7067

7068
    This in combination with _IAllocatorGetClusterData will create the
7069
    correct structure needed as input for the allocator.
7070

7071
    The checks for the completeness of the opcode must have already been
7072
    done.
7073

7074
    """
7075
    instance = self.lu.cfg.GetInstanceInfo(self.name)
7076
    if instance is None:
7077
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
7078
                                   " IAllocator" % self.name)
7079

    
7080
    if instance.disk_template not in constants.DTS_NET_MIRROR:
7081
      raise errors.OpPrereqError("Can't relocate non-mirrored instances")
7082

    
7083
    if len(instance.secondary_nodes) != 1:
7084
      raise errors.OpPrereqError("Instance has not exactly one secondary node")
7085

    
7086
    self.required_nodes = 1
7087
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
7088
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
7089

    
7090
    request = {
7091
      "type": "relocate",
7092
      "name": self.name,
7093
      "disk_space_total": disk_space,
7094
      "required_nodes": self.required_nodes,
7095
      "relocate_from": self.relocate_from,
7096
      }
7097
    self.in_data["request"] = request
7098

    
7099
  def _BuildInputData(self):
7100
    """Build input data structures.
7101

7102
    """
7103
    self._ComputeClusterData()
7104

    
7105
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
7106
      self._AddNewInstance()
7107
    else:
7108
      self._AddRelocateInstance()
7109

    
7110
    self.in_text = serializer.Dump(self.in_data)
7111

    
7112
  def Run(self, name, validate=True, call_fn=None):
7113
    """Run an instance allocator and return the results.
7114

7115
    """
7116
    if call_fn is None:
7117
      call_fn = self.lu.rpc.call_iallocator_runner
7118

    
7119
    result = call_fn(self.lu.cfg.GetMasterNode(), name, self.in_text)
7120
    result.Raise()
7121

    
7122
    if not isinstance(result.data, (list, tuple)) or len(result.data) != 4:
7123
      raise errors.OpExecError("Invalid result from master iallocator runner")
7124

    
7125
    rcode, stdout, stderr, fail = result.data
7126

    
7127
    if rcode == constants.IARUN_NOTFOUND:
7128
      raise errors.OpExecError("Can't find allocator '%s'" % name)
7129
    elif rcode == constants.IARUN_FAILURE:
7130
      raise errors.OpExecError("Instance allocator call failed: %s,"
7131
                               " output: %s" % (fail, stdout+stderr))
7132
    self.out_text = stdout
7133
    if validate:
7134
      self._ValidateResult()
7135

    
7136
  def _ValidateResult(self):
7137
    """Process the allocator results.
7138

7139
    This will process and if successful save the result in
7140
    self.out_data and the other parameters.
7141

7142
    """
7143
    try:
7144
      rdict = serializer.Load(self.out_text)
7145
    except Exception, err:
7146
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
7147

    
7148
    if not isinstance(rdict, dict):
7149
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
7150

    
7151
    for key in "success", "info", "nodes":
7152
      if key not in rdict:
7153
        raise errors.OpExecError("Can't parse iallocator results:"
7154
                                 " missing key '%s'" % key)
7155
      setattr(self, key, rdict[key])
7156

    
7157
    if not isinstance(rdict["nodes"], list):
7158
      raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
7159
                               " is not a list")
7160
    self.out_data = rdict
7161

    
7162

    
7163
class LUTestAllocator(NoHooksLU):
7164
  """Run allocator tests.
7165

7166
  This LU runs the allocator tests
7167

7168
  """
7169
  _OP_REQP = ["direction", "mode", "name"]
7170

    
7171
  def CheckPrereq(self):
7172
    """Check prerequisites.
7173

7174
    This checks the opcode parameters depending on the director and mode test.
7175

7176
    """
7177
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
7178
      for attr in ["name", "mem_size", "disks", "disk_template",
7179
                   "os", "tags", "nics", "vcpus"]:
7180
        if not hasattr(self.op, attr):
7181
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
7182
                                     attr)
7183
      iname = self.cfg.ExpandInstanceName(self.op.name)
7184
      if iname is not None:
7185
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
7186
                                   iname)
7187
      if not isinstance(self.op.nics, list):
7188
        raise errors.OpPrereqError("Invalid parameter 'nics'")
7189
      for row in self.op.nics:
7190
        if (not isinstance(row, dict) or
7191
            "mac" not in row or
7192
            "ip" not in row or
7193
            "bridge" not in row):
7194
          raise errors.OpPrereqError("Invalid contents of the"
7195
                                     " 'nics' parameter")
7196
      if not isinstance(self.op.disks, list):
7197
        raise errors.OpPrereqError("Invalid parameter 'disks'")
7198
      for row in self.op.disks:
7199
        if (not isinstance(row, dict) or
7200
            "size" not in row or
7201
            not isinstance(row["size"], int) or
7202
            "mode" not in row or
7203
            row["mode"] not in ['r', 'w']):
7204
          raise errors.OpPrereqError("Invalid contents of the"
7205
                                     " 'disks' parameter")
7206
      if not hasattr(self.op, "hypervisor") or self.op.hypervisor is None:
7207
        self.op.hypervisor = self.cfg.GetHypervisorType()
7208
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
7209
      if not hasattr(self.op, "name"):
7210
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input")
7211
      fname = self.cfg.ExpandInstanceName(self.op.name)
7212
      if fname is None:
7213
        raise errors.OpPrereqError("Instance '%s' not found for relocation" %
7214
                                   self.op.name)
7215
      self.op.name = fname
7216
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
7217
    else:
7218
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
7219
                                 self.op.mode)
7220

    
7221
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
7222
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
7223
        raise errors.OpPrereqError("Missing allocator name")
7224
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
7225
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
7226
                                 self.op.direction)
7227

    
7228
  def Exec(self, feedback_fn):
7229
    """Run the allocator test.
7230

7231
    """
7232
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
7233
      ial = IAllocator(self,
7234
                       mode=self.op.mode,
7235
                       name=self.op.name,
7236
                       mem_size=self.op.mem_size,
7237
                       disks=self.op.disks,
7238
                       disk_template=self.op.disk_template,
7239
                       os=self.op.os,
7240
                       tags=self.op.tags,
7241
                       nics=self.op.nics,
7242
                       vcpus=self.op.vcpus,
7243
                       hypervisor=self.op.hypervisor,
7244
                       )
7245
    else:
7246
      ial = IAllocator(self,
7247
                       mode=self.op.mode,
7248
                       name=self.op.name,
7249
                       relocate_from=list(self.relocate_from),
7250
                       )
7251

    
7252
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
7253
      result = ial.in_text
7254
    else:
7255
      ial.Run(self.op.allocator, validate=False)
7256
      result = ial.out_text
7257
    return result