Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 1492cca7

History | View | Annotate | Download (228.3 kB)

1
#
2
#
3

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

    
21

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

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

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

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

    
48

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

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

61
  Note that all commands require root permissions.
62

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

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

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

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

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

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

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

    
109
  ssh = property(fget=__GetSSH)
110

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

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

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

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

126
    """
127
    pass
128

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

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

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

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

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

150
    Examples::
151

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

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

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

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

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

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

189
    """
190

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

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

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

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

205
    """
206
    raise NotImplementedError
207

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

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

215
    """
216
    raise NotImplementedError
217

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

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

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

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

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

237
    """
238
    raise NotImplementedError
239

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

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

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

258
    """
259
    return lu_result
260

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
326
    del self.recalculate_locks[locking.LEVEL_NODE]
327

    
328

    
329
class NoHooksLU(LogicalUnit):
330
  """Simple LU which runs no hooks.
331

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

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

    
339

    
340
def _GetWantedNodes(lu, nodes):
341
  """Returns list of checked and expanded node names.
342

343
  @type lu: L{LogicalUnit}
344
  @param lu: the logical unit on whose behalf we execute
345
  @type nodes: list
346
  @param nodes: list of node names or None for all nodes
347
  @rtype: list
348
  @return: the list of nodes, sorted
349
  @raise errors.OpProgrammerError: if the nodes parameter is wrong type
350

351
  """
352
  if not isinstance(nodes, list):
353
    raise errors.OpPrereqError("Invalid argument type 'nodes'")
354

    
355
  if not nodes:
356
    raise errors.ProgrammerError("_GetWantedNodes should only be called with a"
357
      " non-empty list of nodes whose name is to be expanded.")
358

    
359
  wanted = []
360
  for name in nodes:
361
    node = lu.cfg.ExpandNodeName(name)
362
    if node is None:
363
      raise errors.OpPrereqError("No such node name '%s'" % name)
364
    wanted.append(node)
365

    
366
  return utils.NiceSort(wanted)
367

    
368

    
369
def _GetWantedInstances(lu, instances):
370
  """Returns list of checked and expanded instance names.
371

372
  @type lu: L{LogicalUnit}
373
  @param lu: the logical unit on whose behalf we execute
374
  @type instances: list
375
  @param instances: list of instance names or None for all instances
376
  @rtype: list
377
  @return: the list of instances, sorted
378
  @raise errors.OpPrereqError: if the instances parameter is wrong type
379
  @raise errors.OpPrereqError: if any of the passed instances is not found
380

381
  """
382
  if not isinstance(instances, list):
383
    raise errors.OpPrereqError("Invalid argument type 'instances'")
384

    
385
  if instances:
386
    wanted = []
387

    
388
    for name in instances:
389
      instance = lu.cfg.ExpandInstanceName(name)
390
      if instance is None:
391
        raise errors.OpPrereqError("No such instance name '%s'" % name)
392
      wanted.append(instance)
393

    
394
  else:
395
    wanted = lu.cfg.GetInstanceList()
396
  return utils.NiceSort(wanted)
397

    
398

    
399
def _CheckOutputFields(static, dynamic, selected):
400
  """Checks whether all selected fields are valid.
401

402
  @type static: L{utils.FieldSet}
403
  @param static: static fields set
404
  @type dynamic: L{utils.FieldSet}
405
  @param dynamic: dynamic fields set
406

407
  """
408
  f = utils.FieldSet()
409
  f.Extend(static)
410
  f.Extend(dynamic)
411

    
412
  delta = f.NonMatching(selected)
413
  if delta:
414
    raise errors.OpPrereqError("Unknown output fields selected: %s"
415
                               % ",".join(delta))
416

    
417

    
418
def _CheckBooleanOpField(op, name):
419
  """Validates boolean opcode parameters.
420

421
  This will ensure that an opcode parameter is either a boolean value,
422
  or None (but that it always exists).
423

424
  """
425
  val = getattr(op, name, None)
426
  if not (val is None or isinstance(val, bool)):
427
    raise errors.OpPrereqError("Invalid boolean parameter '%s' (%s)" %
428
                               (name, str(val)))
429
  setattr(op, name, val)
430

    
431

    
432
def _CheckNodeOnline(lu, node):
433
  """Ensure that a given node is online.
434

435
  @param lu: the LU on behalf of which we make the check
436
  @param node: the node to check
437
  @raise errors.OpPrereqError: if the nodes is offline
438

439
  """
440
  if lu.cfg.GetNodeInfo(node).offline:
441
    raise errors.OpPrereqError("Can't use offline node %s" % node)
442

    
443

    
444
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
445
                          memory, vcpus, nics):
446
  """Builds instance related env variables for hooks
447

448
  This builds the hook environment from individual variables.
449

450
  @type name: string
451
  @param name: the name of the instance
452
  @type primary_node: string
453
  @param primary_node: the name of the instance's primary node
454
  @type secondary_nodes: list
455
  @param secondary_nodes: list of secondary nodes as strings
456
  @type os_type: string
457
  @param os_type: the name of the instance's OS
458
  @type status: string
459
  @param status: the desired status of the instances
460
  @type memory: string
461
  @param memory: the memory size of the instance
462
  @type vcpus: string
463
  @param vcpus: the count of VCPUs the instance has
464
  @type nics: list
465
  @param nics: list of tuples (ip, bridge, mac) representing
466
      the NICs the instance  has
467
  @rtype: dict
468
  @return: the hook environment for this instance
469

470
  """
471
  env = {
472
    "OP_TARGET": name,
473
    "INSTANCE_NAME": name,
474
    "INSTANCE_PRIMARY": primary_node,
475
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
476
    "INSTANCE_OS_TYPE": os_type,
477
    "INSTANCE_STATUS": status,
478
    "INSTANCE_MEMORY": memory,
479
    "INSTANCE_VCPUS": vcpus,
480
  }
481

    
482
  if nics:
483
    nic_count = len(nics)
484
    for idx, (ip, bridge, mac) in enumerate(nics):
485
      if ip is None:
486
        ip = ""
487
      env["INSTANCE_NIC%d_IP" % idx] = ip
488
      env["INSTANCE_NIC%d_BRIDGE" % idx] = bridge
489
      env["INSTANCE_NIC%d_HWADDR" % idx] = mac
490
  else:
491
    nic_count = 0
492

    
493
  env["INSTANCE_NIC_COUNT"] = nic_count
494

    
495
  return env
496

    
497

    
498
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
499
  """Builds instance related env variables for hooks from an object.
500

501
  @type lu: L{LogicalUnit}
502
  @param lu: the logical unit on whose behalf we execute
503
  @type instance: L{objects.Instance}
504
  @param instance: the instance for which we should build the
505
      environment
506
  @type override: dict
507
  @param override: dictionary with key/values that will override
508
      our values
509
  @rtype: dict
510
  @return: the hook environment dictionary
511

512
  """
513
  bep = lu.cfg.GetClusterInfo().FillBE(instance)
514
  args = {
515
    'name': instance.name,
516
    'primary_node': instance.primary_node,
517
    'secondary_nodes': instance.secondary_nodes,
518
    'os_type': instance.os,
519
    'status': instance.os,
520
    'memory': bep[constants.BE_MEMORY],
521
    'vcpus': bep[constants.BE_VCPUS],
522
    'nics': [(nic.ip, nic.bridge, nic.mac) for nic in instance.nics],
523
  }
524
  if override:
525
    args.update(override)
526
  return _BuildInstanceHookEnv(**args)
527

    
528

    
529
def _AdjustCandidatePool(lu):
530
  """Adjust the candidate pool after node operations.
531

532
  """
533
  mod_list = lu.cfg.MaintainCandidatePool()
534
  if mod_list:
535
    lu.LogInfo("Promoted nodes to master candidate role: %s",
536
               ", ".join(node.name for node in mod_list))
537
    for name in mod_list:
538
      lu.context.ReaddNode(name)
539
  mc_now, mc_max = lu.cfg.GetMasterCandidateStats()
540
  if mc_now > mc_max:
541
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
542
               (mc_now, mc_max))
543

    
544

    
545
def _CheckInstanceBridgesExist(lu, instance):
546
  """Check that the brigdes needed by an instance exist.
547

548
  """
549
  # check bridges existance
550
  brlist = [nic.bridge for nic in instance.nics]
551
  result = lu.rpc.call_bridges_exist(instance.primary_node, brlist)
552
  result.Raise()
553
  if not result.data:
554
    raise errors.OpPrereqError("One or more target bridges %s does not"
555
                               " exist on destination node '%s'" %
556
                               (brlist, instance.primary_node))
557

    
558

    
559
class LUDestroyCluster(NoHooksLU):
560
  """Logical unit for destroying the cluster.
561

562
  """
563
  _OP_REQP = []
564

    
565
  def CheckPrereq(self):
566
    """Check prerequisites.
567

568
    This checks whether the cluster is empty.
569

570
    Any errors are signalled by raising errors.OpPrereqError.
571

572
    """
573
    master = self.cfg.GetMasterNode()
574

    
575
    nodelist = self.cfg.GetNodeList()
576
    if len(nodelist) != 1 or nodelist[0] != master:
577
      raise errors.OpPrereqError("There are still %d node(s) in"
578
                                 " this cluster." % (len(nodelist) - 1))
579
    instancelist = self.cfg.GetInstanceList()
580
    if instancelist:
581
      raise errors.OpPrereqError("There are still %d instance(s) in"
582
                                 " this cluster." % len(instancelist))
583

    
584
  def Exec(self, feedback_fn):
585
    """Destroys the cluster.
586

587
    """
588
    master = self.cfg.GetMasterNode()
589
    result = self.rpc.call_node_stop_master(master, False)
590
    result.Raise()
591
    if not result.data:
592
      raise errors.OpExecError("Could not disable the master role")
593
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
594
    utils.CreateBackup(priv_key)
595
    utils.CreateBackup(pub_key)
596
    return master
597

    
598

    
599
class LUVerifyCluster(LogicalUnit):
600
  """Verifies the cluster status.
601

602
  """
603
  HPATH = "cluster-verify"
604
  HTYPE = constants.HTYPE_CLUSTER
605
  _OP_REQP = ["skip_checks"]
606
  REQ_BGL = False
607

    
608
  def ExpandNames(self):
609
    self.needed_locks = {
610
      locking.LEVEL_NODE: locking.ALL_SET,
611
      locking.LEVEL_INSTANCE: locking.ALL_SET,
612
    }
613
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
614

    
615
  def _VerifyNode(self, nodeinfo, file_list, local_cksum,
616
                  node_result, feedback_fn, master_files):
617
    """Run multiple tests against a node.
618

619
    Test list:
620

621
      - compares ganeti version
622
      - checks vg existance and size > 20G
623
      - checks config file checksum
624
      - checks ssh to other nodes
625

626
    @type nodeinfo: L{objects.Node}
627
    @param nodeinfo: the node to check
628
    @param file_list: required list of files
629
    @param local_cksum: dictionary of local files and their checksums
630
    @param node_result: the results from the node
631
    @param feedback_fn: function used to accumulate results
632
    @param master_files: list of files that only masters should have
633

634
    """
635
    node = nodeinfo.name
636

    
637
    # main result, node_result should be a non-empty dict
638
    if not node_result or not isinstance(node_result, dict):
639
      feedback_fn("  - ERROR: unable to verify node %s." % (node,))
640
      return True
641

    
642
    # compares ganeti version
643
    local_version = constants.PROTOCOL_VERSION
644
    remote_version = node_result.get('version', None)
645
    if not remote_version:
646
      feedback_fn("  - ERROR: connection to %s failed" % (node))
647
      return True
648

    
649
    if local_version != remote_version:
650
      feedback_fn("  - ERROR: sw version mismatch: master %s, node(%s) %s" %
651
                      (local_version, node, remote_version))
652
      return True
653

    
654
    # checks vg existance and size > 20G
655

    
656
    bad = False
657
    vglist = node_result.get(constants.NV_VGLIST, None)
658
    if not vglist:
659
      feedback_fn("  - ERROR: unable to check volume groups on node %s." %
660
                      (node,))
661
      bad = True
662
    else:
663
      vgstatus = utils.CheckVolumeGroupSize(vglist, self.cfg.GetVGName(),
664
                                            constants.MIN_VG_SIZE)
665
      if vgstatus:
666
        feedback_fn("  - ERROR: %s on node %s" % (vgstatus, node))
667
        bad = True
668

    
669
    # checks config file checksum
670

    
671
    remote_cksum = node_result.get(constants.NV_FILELIST, None)
672
    if not isinstance(remote_cksum, dict):
673
      bad = True
674
      feedback_fn("  - ERROR: node hasn't returned file checksum data")
675
    else:
676
      for file_name in file_list:
677
        node_is_mc = nodeinfo.master_candidate
678
        must_have_file = file_name not in master_files
679
        if file_name not in remote_cksum:
680
          if node_is_mc or must_have_file:
681
            bad = True
682
            feedback_fn("  - ERROR: file '%s' missing" % file_name)
683
        elif remote_cksum[file_name] != local_cksum[file_name]:
684
          if node_is_mc or must_have_file:
685
            bad = True
686
            feedback_fn("  - ERROR: file '%s' has wrong checksum" % file_name)
687
          else:
688
            # not candidate and this is not a must-have file
689
            bad = True
690
            feedback_fn("  - ERROR: non master-candidate has old/wrong file"
691
                        " '%s'" % file_name)
692
        else:
693
          # all good, except non-master/non-must have combination
694
          if not node_is_mc and not must_have_file:
695
            feedback_fn("  - ERROR: file '%s' should not exist on non master"
696
                        " candidates" % file_name)
697

    
698
    # checks ssh to any
699

    
700
    if constants.NV_NODELIST not in node_result:
701
      bad = True
702
      feedback_fn("  - ERROR: node hasn't returned node ssh connectivity data")
703
    else:
704
      if node_result[constants.NV_NODELIST]:
705
        bad = True
706
        for node in node_result[constants.NV_NODELIST]:
707
          feedback_fn("  - ERROR: ssh communication with node '%s': %s" %
708
                          (node, node_result[constants.NV_NODELIST][node]))
709

    
710
    if constants.NV_NODENETTEST not in node_result:
711
      bad = True
712
      feedback_fn("  - ERROR: node hasn't returned node tcp connectivity data")
713
    else:
714
      if node_result[constants.NV_NODENETTEST]:
715
        bad = True
716
        nlist = utils.NiceSort(node_result[constants.NV_NODENETTEST].keys())
717
        for node in nlist:
718
          feedback_fn("  - ERROR: tcp communication with node '%s': %s" %
719
                          (node, node_result[constants.NV_NODENETTEST][node]))
720

    
721
    hyp_result = node_result.get(constants.NV_HYPERVISOR, None)
722
    if isinstance(hyp_result, dict):
723
      for hv_name, hv_result in hyp_result.iteritems():
724
        if hv_result is not None:
725
          feedback_fn("  - ERROR: hypervisor %s verify failure: '%s'" %
726
                      (hv_name, hv_result))
727
    return bad
728

    
729
  def _VerifyInstance(self, instance, instanceconfig, node_vol_is,
730
                      node_instance, feedback_fn, n_offline):
731
    """Verify an instance.
732

733
    This function checks to see if the required block devices are
734
    available on the instance's node.
735

736
    """
737
    bad = False
738

    
739
    node_current = instanceconfig.primary_node
740

    
741
    node_vol_should = {}
742
    instanceconfig.MapLVsByNode(node_vol_should)
743

    
744
    for node in node_vol_should:
745
      if node in n_offline:
746
        # ignore missing volumes on offline nodes
747
        continue
748
      for volume in node_vol_should[node]:
749
        if node not in node_vol_is or volume not in node_vol_is[node]:
750
          feedback_fn("  - ERROR: volume %s missing on node %s" %
751
                          (volume, node))
752
          bad = True
753

    
754
    if not instanceconfig.status == 'down':
755
      if ((node_current not in node_instance or
756
          not instance in node_instance[node_current]) and
757
          node_current not in n_offline):
758
        feedback_fn("  - ERROR: instance %s not running on node %s" %
759
                        (instance, node_current))
760
        bad = True
761

    
762
    for node in node_instance:
763
      if (not node == node_current):
764
        if instance in node_instance[node]:
765
          feedback_fn("  - ERROR: instance %s should not run on node %s" %
766
                          (instance, node))
767
          bad = True
768

    
769
    return bad
770

    
771
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is, feedback_fn):
772
    """Verify if there are any unknown volumes in the cluster.
773

774
    The .os, .swap and backup volumes are ignored. All other volumes are
775
    reported as unknown.
776

777
    """
778
    bad = False
779

    
780
    for node in node_vol_is:
781
      for volume in node_vol_is[node]:
782
        if node not in node_vol_should or volume not in node_vol_should[node]:
783
          feedback_fn("  - ERROR: volume %s on node %s should not exist" %
784
                      (volume, node))
785
          bad = True
786
    return bad
787

    
788
  def _VerifyOrphanInstances(self, instancelist, node_instance, feedback_fn):
789
    """Verify the list of running instances.
790

791
    This checks what instances are running but unknown to the cluster.
792

793
    """
794
    bad = False
795
    for node in node_instance:
796
      for runninginstance in node_instance[node]:
797
        if runninginstance not in instancelist:
798
          feedback_fn("  - ERROR: instance %s on node %s should not exist" %
799
                          (runninginstance, node))
800
          bad = True
801
    return bad
802

    
803
  def _VerifyNPlusOneMemory(self, node_info, instance_cfg, feedback_fn):
804
    """Verify N+1 Memory Resilience.
805

806
    Check that if one single node dies we can still start all the instances it
807
    was primary for.
808

809
    """
810
    bad = False
811

    
812
    for node, nodeinfo in node_info.iteritems():
813
      # This code checks that every node which is now listed as secondary has
814
      # enough memory to host all instances it is supposed to should a single
815
      # other node in the cluster fail.
816
      # FIXME: not ready for failover to an arbitrary node
817
      # FIXME: does not support file-backed instances
818
      # WARNING: we currently take into account down instances as well as up
819
      # ones, considering that even if they're down someone might want to start
820
      # them even in the event of a node failure.
821
      for prinode, instances in nodeinfo['sinst-by-pnode'].iteritems():
822
        needed_mem = 0
823
        for instance in instances:
824
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
825
          if bep[constants.BE_AUTO_BALANCE]:
826
            needed_mem += bep[constants.BE_MEMORY]
827
        if nodeinfo['mfree'] < needed_mem:
828
          feedback_fn("  - ERROR: not enough memory on node %s to accomodate"
829
                      " failovers should node %s fail" % (node, prinode))
830
          bad = True
831
    return bad
832

    
833
  def CheckPrereq(self):
834
    """Check prerequisites.
835

836
    Transform the list of checks we're going to skip into a set and check that
837
    all its members are valid.
838

839
    """
840
    self.skip_set = frozenset(self.op.skip_checks)
841
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
842
      raise errors.OpPrereqError("Invalid checks to be skipped specified")
843

    
844
  def BuildHooksEnv(self):
845
    """Build hooks env.
846

847
    Cluster-Verify hooks just rone in the post phase and their failure makes
848
    the output be logged in the verify output and the verification to fail.
849

850
    """
851
    all_nodes = self.cfg.GetNodeList()
852
    # TODO: populate the environment with useful information for verify hooks
853
    env = {}
854
    return env, [], all_nodes
855

    
856
  def Exec(self, feedback_fn):
857
    """Verify integrity of cluster, performing various test on nodes.
858

859
    """
860
    bad = False
861
    feedback_fn("* Verifying global settings")
862
    for msg in self.cfg.VerifyConfig():
863
      feedback_fn("  - ERROR: %s" % msg)
864

    
865
    vg_name = self.cfg.GetVGName()
866
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
867
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
868
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
869
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
870
    i_non_redundant = [] # Non redundant instances
871
    i_non_a_balanced = [] # Non auto-balanced instances
872
    n_offline = [] # List of offline nodes
873
    node_volume = {}
874
    node_instance = {}
875
    node_info = {}
876
    instance_cfg = {}
877

    
878
    # FIXME: verify OS list
879
    # do local checksums
880
    master_files = [constants.CLUSTER_CONF_FILE]
881

    
882
    file_names = ssconf.SimpleStore().GetFileList()
883
    file_names.append(constants.SSL_CERT_FILE)
884
    file_names.append(constants.RAPI_CERT_FILE)
885
    file_names.extend(master_files)
886

    
887
    local_checksums = utils.FingerprintFiles(file_names)
888

    
889
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
890
    node_verify_param = {
891
      constants.NV_FILELIST: file_names,
892
      constants.NV_NODELIST: [node.name for node in nodeinfo
893
                              if not node.offline],
894
      constants.NV_HYPERVISOR: hypervisors,
895
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
896
                                  node.secondary_ip) for node in nodeinfo
897
                                 if not node.offline],
898
      constants.NV_LVLIST: vg_name,
899
      constants.NV_INSTANCELIST: hypervisors,
900
      constants.NV_VGLIST: None,
901
      constants.NV_VERSION: None,
902
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
903
      }
904
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
905
                                           self.cfg.GetClusterName())
906

    
907
    cluster = self.cfg.GetClusterInfo()
908
    master_node = self.cfg.GetMasterNode()
909
    for node_i in nodeinfo:
910
      node = node_i.name
911
      nresult = all_nvinfo[node].data
912

    
913
      if node_i.offline:
914
        feedback_fn("* Skipping offline node %s" % (node,))
915
        n_offline.append(node)
916
        continue
917

    
918
      if node == master_node:
919
        ntype = "master"
920
      elif node_i.master_candidate:
921
        ntype = "master candidate"
922
      else:
923
        ntype = "regular"
924
      feedback_fn("* Verifying node %s (%s)" % (node, ntype))
925

    
926
      if all_nvinfo[node].failed or not isinstance(nresult, dict):
927
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
928
        bad = True
929
        continue
930

    
931
      result = self._VerifyNode(node_i, file_names, local_checksums,
932
                                nresult, feedback_fn, master_files)
933
      bad = bad or result
934

    
935
      lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
936
      if isinstance(lvdata, basestring):
937
        feedback_fn("  - ERROR: LVM problem on node %s: %s" %
938
                    (node, lvdata.encode('string_escape')))
939
        bad = True
940
        node_volume[node] = {}
941
      elif not isinstance(lvdata, dict):
942
        feedback_fn("  - ERROR: connection to %s failed (lvlist)" % (node,))
943
        bad = True
944
        continue
945
      else:
946
        node_volume[node] = lvdata
947

    
948
      # node_instance
949
      idata = nresult.get(constants.NV_INSTANCELIST, None)
950
      if not isinstance(idata, list):
951
        feedback_fn("  - ERROR: connection to %s failed (instancelist)" %
952
                    (node,))
953
        bad = True
954
        continue
955

    
956
      node_instance[node] = idata
957

    
958
      # node_info
959
      nodeinfo = nresult.get(constants.NV_HVINFO, None)
960
      if not isinstance(nodeinfo, dict):
961
        feedback_fn("  - ERROR: connection to %s failed (hvinfo)" % (node,))
962
        bad = True
963
        continue
964

    
965
      try:
966
        node_info[node] = {
967
          "mfree": int(nodeinfo['memory_free']),
968
          "dfree": int(nresult[constants.NV_VGLIST][vg_name]),
969
          "pinst": [],
970
          "sinst": [],
971
          # dictionary holding all instances this node is secondary for,
972
          # grouped by their primary node. Each key is a cluster node, and each
973
          # value is a list of instances which have the key as primary and the
974
          # current node as secondary.  this is handy to calculate N+1 memory
975
          # availability if you can only failover from a primary to its
976
          # secondary.
977
          "sinst-by-pnode": {},
978
        }
979
      except ValueError:
980
        feedback_fn("  - ERROR: invalid value returned from node %s" % (node,))
981
        bad = True
982
        continue
983

    
984
    node_vol_should = {}
985

    
986
    for instance in instancelist:
987
      feedback_fn("* Verifying instance %s" % instance)
988
      inst_config = self.cfg.GetInstanceInfo(instance)
989
      result =  self._VerifyInstance(instance, inst_config, node_volume,
990
                                     node_instance, feedback_fn, n_offline)
991
      bad = bad or result
992
      inst_nodes_offline = []
993

    
994
      inst_config.MapLVsByNode(node_vol_should)
995

    
996
      instance_cfg[instance] = inst_config
997

    
998
      pnode = inst_config.primary_node
999
      if pnode in node_info:
1000
        node_info[pnode]['pinst'].append(instance)
1001
      elif pnode not in n_offline:
1002
        feedback_fn("  - ERROR: instance %s, connection to primary node"
1003
                    " %s failed" % (instance, pnode))
1004
        bad = True
1005

    
1006
      if pnode in n_offline:
1007
        inst_nodes_offline.append(pnode)
1008

    
1009
      # If the instance is non-redundant we cannot survive losing its primary
1010
      # node, so we are not N+1 compliant. On the other hand we have no disk
1011
      # templates with more than one secondary so that situation is not well
1012
      # supported either.
1013
      # FIXME: does not support file-backed instances
1014
      if len(inst_config.secondary_nodes) == 0:
1015
        i_non_redundant.append(instance)
1016
      elif len(inst_config.secondary_nodes) > 1:
1017
        feedback_fn("  - WARNING: multiple secondaries for instance %s"
1018
                    % instance)
1019

    
1020
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1021
        i_non_a_balanced.append(instance)
1022

    
1023
      for snode in inst_config.secondary_nodes:
1024
        if snode in node_info:
1025
          node_info[snode]['sinst'].append(instance)
1026
          if pnode not in node_info[snode]['sinst-by-pnode']:
1027
            node_info[snode]['sinst-by-pnode'][pnode] = []
1028
          node_info[snode]['sinst-by-pnode'][pnode].append(instance)
1029
        elif snode not in n_offline:
1030
          feedback_fn("  - ERROR: instance %s, connection to secondary node"
1031
                      " %s failed" % (instance, snode))
1032
          bad = True
1033
        if snode in n_offline:
1034
          inst_nodes_offline.append(snode)
1035

    
1036
      if inst_nodes_offline:
1037
        # warn that the instance lives on offline nodes, and set bad=True
1038
        feedback_fn("  - ERROR: instance lives on offline node(s) %s" %
1039
                    ", ".join(inst_nodes_offline))
1040
        bad = True
1041

    
1042
    feedback_fn("* Verifying orphan volumes")
1043
    result = self._VerifyOrphanVolumes(node_vol_should, node_volume,
1044
                                       feedback_fn)
1045
    bad = bad or result
1046

    
1047
    feedback_fn("* Verifying remaining instances")
1048
    result = self._VerifyOrphanInstances(instancelist, node_instance,
1049
                                         feedback_fn)
1050
    bad = bad or result
1051

    
1052
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1053
      feedback_fn("* Verifying N+1 Memory redundancy")
1054
      result = self._VerifyNPlusOneMemory(node_info, instance_cfg, feedback_fn)
1055
      bad = bad or result
1056

    
1057
    feedback_fn("* Other Notes")
1058
    if i_non_redundant:
1059
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1060
                  % len(i_non_redundant))
1061

    
1062
    if i_non_a_balanced:
1063
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1064
                  % len(i_non_a_balanced))
1065

    
1066
    if n_offline:
1067
      feedback_fn("  - NOTICE: %d offline node(s) found." % len(n_offline))
1068

    
1069
    return not bad
1070

    
1071
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1072
    """Analize the post-hooks' result
1073

1074
    This method analyses the hook result, handles it, and sends some
1075
    nicely-formatted feedback back to the user.
1076

1077
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1078
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1079
    @param hooks_results: the results of the multi-node hooks rpc call
1080
    @param feedback_fn: function used send feedback back to the caller
1081
    @param lu_result: previous Exec result
1082
    @return: the new Exec result, based on the previous result
1083
        and hook results
1084

1085
    """
1086
    # We only really run POST phase hooks, and are only interested in
1087
    # their results
1088
    if phase == constants.HOOKS_PHASE_POST:
1089
      # Used to change hooks' output to proper indentation
1090
      indent_re = re.compile('^', re.M)
1091
      feedback_fn("* Hooks Results")
1092
      if not hooks_results:
1093
        feedback_fn("  - ERROR: general communication failure")
1094
        lu_result = 1
1095
      else:
1096
        for node_name in hooks_results:
1097
          show_node_header = True
1098
          res = hooks_results[node_name]
1099
          if res.failed or res.data is False or not isinstance(res.data, list):
1100
            if res.offline:
1101
              # no need to warn or set fail return value
1102
              continue
1103
            feedback_fn("    Communication failure in hooks execution")
1104
            lu_result = 1
1105
            continue
1106
          for script, hkr, output in res.data:
1107
            if hkr == constants.HKR_FAIL:
1108
              # The node header is only shown once, if there are
1109
              # failing hooks on that node
1110
              if show_node_header:
1111
                feedback_fn("  Node %s:" % node_name)
1112
                show_node_header = False
1113
              feedback_fn("    ERROR: Script %s failed, output:" % script)
1114
              output = indent_re.sub('      ', output)
1115
              feedback_fn("%s" % output)
1116
              lu_result = 1
1117

    
1118
      return lu_result
1119

    
1120

    
1121
class LUVerifyDisks(NoHooksLU):
1122
  """Verifies the cluster disks status.
1123

1124
  """
1125
  _OP_REQP = []
1126
  REQ_BGL = False
1127

    
1128
  def ExpandNames(self):
1129
    self.needed_locks = {
1130
      locking.LEVEL_NODE: locking.ALL_SET,
1131
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1132
    }
1133
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
1134

    
1135
  def CheckPrereq(self):
1136
    """Check prerequisites.
1137

1138
    This has no prerequisites.
1139

1140
    """
1141
    pass
1142

    
1143
  def Exec(self, feedback_fn):
1144
    """Verify integrity of cluster disks.
1145

1146
    """
1147
    result = res_nodes, res_nlvm, res_instances, res_missing = [], {}, [], {}
1148

    
1149
    vg_name = self.cfg.GetVGName()
1150
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1151
    instances = [self.cfg.GetInstanceInfo(name)
1152
                 for name in self.cfg.GetInstanceList()]
1153

    
1154
    nv_dict = {}
1155
    for inst in instances:
1156
      inst_lvs = {}
1157
      if (inst.status != "up" or
1158
          inst.disk_template not in constants.DTS_NET_MIRROR):
1159
        continue
1160
      inst.MapLVsByNode(inst_lvs)
1161
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1162
      for node, vol_list in inst_lvs.iteritems():
1163
        for vol in vol_list:
1164
          nv_dict[(node, vol)] = inst
1165

    
1166
    if not nv_dict:
1167
      return result
1168

    
1169
    node_lvs = self.rpc.call_volume_list(nodes, vg_name)
1170

    
1171
    to_act = set()
1172
    for node in nodes:
1173
      # node_volume
1174
      lvs = node_lvs[node]
1175
      if lvs.failed:
1176
        if not lvs.offline:
1177
          self.LogWarning("Connection to node %s failed: %s" %
1178
                          (node, lvs.data))
1179
        continue
1180
      lvs = lvs.data
1181
      if isinstance(lvs, basestring):
1182
        logging.warning("Error enumerating LVs on node %s: %s", node, lvs)
1183
        res_nlvm[node] = lvs
1184
      elif not isinstance(lvs, dict):
1185
        logging.warning("Connection to node %s failed or invalid data"
1186
                        " returned", node)
1187
        res_nodes.append(node)
1188
        continue
1189

    
1190
      for lv_name, (_, lv_inactive, lv_online) in lvs.iteritems():
1191
        inst = nv_dict.pop((node, lv_name), None)
1192
        if (not lv_online and inst is not None
1193
            and inst.name not in res_instances):
1194
          res_instances.append(inst.name)
1195

    
1196
    # any leftover items in nv_dict are missing LVs, let's arrange the
1197
    # data better
1198
    for key, inst in nv_dict.iteritems():
1199
      if inst.name not in res_missing:
1200
        res_missing[inst.name] = []
1201
      res_missing[inst.name].append(key)
1202

    
1203
    return result
1204

    
1205

    
1206
class LURenameCluster(LogicalUnit):
1207
  """Rename the cluster.
1208

1209
  """
1210
  HPATH = "cluster-rename"
1211
  HTYPE = constants.HTYPE_CLUSTER
1212
  _OP_REQP = ["name"]
1213

    
1214
  def BuildHooksEnv(self):
1215
    """Build hooks env.
1216

1217
    """
1218
    env = {
1219
      "OP_TARGET": self.cfg.GetClusterName(),
1220
      "NEW_NAME": self.op.name,
1221
      }
1222
    mn = self.cfg.GetMasterNode()
1223
    return env, [mn], [mn]
1224

    
1225
  def CheckPrereq(self):
1226
    """Verify that the passed name is a valid one.
1227

1228
    """
1229
    hostname = utils.HostInfo(self.op.name)
1230

    
1231
    new_name = hostname.name
1232
    self.ip = new_ip = hostname.ip
1233
    old_name = self.cfg.GetClusterName()
1234
    old_ip = self.cfg.GetMasterIP()
1235
    if new_name == old_name and new_ip == old_ip:
1236
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1237
                                 " cluster has changed")
1238
    if new_ip != old_ip:
1239
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1240
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1241
                                   " reachable on the network. Aborting." %
1242
                                   new_ip)
1243

    
1244
    self.op.name = new_name
1245

    
1246
  def Exec(self, feedback_fn):
1247
    """Rename the cluster.
1248

1249
    """
1250
    clustername = self.op.name
1251
    ip = self.ip
1252

    
1253
    # shutdown the master IP
1254
    master = self.cfg.GetMasterNode()
1255
    result = self.rpc.call_node_stop_master(master, False)
1256
    if result.failed or not result.data:
1257
      raise errors.OpExecError("Could not disable the master role")
1258

    
1259
    try:
1260
      cluster = self.cfg.GetClusterInfo()
1261
      cluster.cluster_name = clustername
1262
      cluster.master_ip = ip
1263
      self.cfg.Update(cluster)
1264

    
1265
      # update the known hosts file
1266
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
1267
      node_list = self.cfg.GetNodeList()
1268
      try:
1269
        node_list.remove(master)
1270
      except ValueError:
1271
        pass
1272
      result = self.rpc.call_upload_file(node_list,
1273
                                         constants.SSH_KNOWN_HOSTS_FILE)
1274
      for to_node, to_result in result.iteritems():
1275
        if to_result.failed or not to_result.data:
1276
          logging.error("Copy of file %s to node %s failed",
1277
                        constants.SSH_KNOWN_HOSTS_FILE, to_node)
1278

    
1279
    finally:
1280
      result = self.rpc.call_node_start_master(master, False)
1281
      if result.failed or not result.data:
1282
        self.LogWarning("Could not re-enable the master role on"
1283
                        " the master, please restart manually.")
1284

    
1285

    
1286
def _RecursiveCheckIfLVMBased(disk):
1287
  """Check if the given disk or its children are lvm-based.
1288

1289
  @type disk: L{objects.Disk}
1290
  @param disk: the disk to check
1291
  @rtype: booleean
1292
  @return: boolean indicating whether a LD_LV dev_type was found or not
1293

1294
  """
1295
  if disk.children:
1296
    for chdisk in disk.children:
1297
      if _RecursiveCheckIfLVMBased(chdisk):
1298
        return True
1299
  return disk.dev_type == constants.LD_LV
1300

    
1301

    
1302
class LUSetClusterParams(LogicalUnit):
1303
  """Change the parameters of the cluster.
1304

1305
  """
1306
  HPATH = "cluster-modify"
1307
  HTYPE = constants.HTYPE_CLUSTER
1308
  _OP_REQP = []
1309
  REQ_BGL = False
1310

    
1311
  def CheckParameters(self):
1312
    """Check parameters
1313

1314
    """
1315
    if not hasattr(self.op, "candidate_pool_size"):
1316
      self.op.candidate_pool_size = None
1317
    if self.op.candidate_pool_size is not None:
1318
      try:
1319
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
1320
      except ValueError, err:
1321
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
1322
                                   str(err))
1323
      if self.op.candidate_pool_size < 1:
1324
        raise errors.OpPrereqError("At least one master candidate needed")
1325

    
1326
  def ExpandNames(self):
1327
    # FIXME: in the future maybe other cluster params won't require checking on
1328
    # all nodes to be modified.
1329
    self.needed_locks = {
1330
      locking.LEVEL_NODE: locking.ALL_SET,
1331
    }
1332
    self.share_locks[locking.LEVEL_NODE] = 1
1333

    
1334
  def BuildHooksEnv(self):
1335
    """Build hooks env.
1336

1337
    """
1338
    env = {
1339
      "OP_TARGET": self.cfg.GetClusterName(),
1340
      "NEW_VG_NAME": self.op.vg_name,
1341
      }
1342
    mn = self.cfg.GetMasterNode()
1343
    return env, [mn], [mn]
1344

    
1345
  def CheckPrereq(self):
1346
    """Check prerequisites.
1347

1348
    This checks whether the given params don't conflict and
1349
    if the given volume group is valid.
1350

1351
    """
1352
    # FIXME: This only works because there is only one parameter that can be
1353
    # changed or removed.
1354
    if self.op.vg_name is not None and not self.op.vg_name:
1355
      instances = self.cfg.GetAllInstancesInfo().values()
1356
      for inst in instances:
1357
        for disk in inst.disks:
1358
          if _RecursiveCheckIfLVMBased(disk):
1359
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1360
                                       " lvm-based instances exist")
1361

    
1362
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1363

    
1364
    # if vg_name not None, checks given volume group on all nodes
1365
    if self.op.vg_name:
1366
      vglist = self.rpc.call_vg_list(node_list)
1367
      for node in node_list:
1368
        if vglist[node].failed:
1369
          # ignoring down node
1370
          self.LogWarning("Node %s unreachable/error, ignoring" % node)
1371
          continue
1372
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].data,
1373
                                              self.op.vg_name,
1374
                                              constants.MIN_VG_SIZE)
1375
        if vgstatus:
1376
          raise errors.OpPrereqError("Error on node '%s': %s" %
1377
                                     (node, vgstatus))
1378

    
1379
    self.cluster = cluster = self.cfg.GetClusterInfo()
1380
    # validate beparams changes
1381
    if self.op.beparams:
1382
      utils.CheckBEParams(self.op.beparams)
1383
      self.new_beparams = cluster.FillDict(
1384
        cluster.beparams[constants.BEGR_DEFAULT], self.op.beparams)
1385

    
1386
    # hypervisor list/parameters
1387
    self.new_hvparams = cluster.FillDict(cluster.hvparams, {})
1388
    if self.op.hvparams:
1389
      if not isinstance(self.op.hvparams, dict):
1390
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input")
1391
      for hv_name, hv_dict in self.op.hvparams.items():
1392
        if hv_name not in self.new_hvparams:
1393
          self.new_hvparams[hv_name] = hv_dict
1394
        else:
1395
          self.new_hvparams[hv_name].update(hv_dict)
1396

    
1397
    if self.op.enabled_hypervisors is not None:
1398
      self.hv_list = self.op.enabled_hypervisors
1399
    else:
1400
      self.hv_list = cluster.enabled_hypervisors
1401

    
1402
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
1403
      # either the enabled list has changed, or the parameters have, validate
1404
      for hv_name, hv_params in self.new_hvparams.items():
1405
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
1406
            (self.op.enabled_hypervisors and
1407
             hv_name in self.op.enabled_hypervisors)):
1408
          # either this is a new hypervisor, or its parameters have changed
1409
          hv_class = hypervisor.GetHypervisor(hv_name)
1410
          hv_class.CheckParameterSyntax(hv_params)
1411
          _CheckHVParams(self, node_list, hv_name, hv_params)
1412

    
1413
  def Exec(self, feedback_fn):
1414
    """Change the parameters of the cluster.
1415

1416
    """
1417
    if self.op.vg_name is not None:
1418
      if self.op.vg_name != self.cfg.GetVGName():
1419
        self.cfg.SetVGName(self.op.vg_name)
1420
      else:
1421
        feedback_fn("Cluster LVM configuration already in desired"
1422
                    " state, not changing")
1423
    if self.op.hvparams:
1424
      self.cluster.hvparams = self.new_hvparams
1425
    if self.op.enabled_hypervisors is not None:
1426
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
1427
    if self.op.beparams:
1428
      self.cluster.beparams[constants.BEGR_DEFAULT] = self.new_beparams
1429
    if self.op.candidate_pool_size is not None:
1430
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
1431

    
1432
    self.cfg.Update(self.cluster)
1433

    
1434
    # we want to update nodes after the cluster so that if any errors
1435
    # happen, we have recorded and saved the cluster info
1436
    if self.op.candidate_pool_size is not None:
1437
      _AdjustCandidatePool(self)
1438

    
1439

    
1440
class LURedistributeConfig(NoHooksLU):
1441
  """Force the redistribution of cluster configuration.
1442

1443
  This is a very simple LU.
1444

1445
  """
1446
  _OP_REQP = []
1447
  REQ_BGL = False
1448

    
1449
  def ExpandNames(self):
1450
    self.needed_locks = {
1451
      locking.LEVEL_NODE: locking.ALL_SET,
1452
    }
1453
    self.share_locks[locking.LEVEL_NODE] = 1
1454

    
1455
  def CheckPrereq(self):
1456
    """Check prerequisites.
1457

1458
    """
1459

    
1460
  def Exec(self, feedback_fn):
1461
    """Redistribute the configuration.
1462

1463
    """
1464
    self.cfg.Update(self.cfg.GetClusterInfo())
1465

    
1466

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

1470
  """
1471
  if not instance.disks:
1472
    return True
1473

    
1474
  if not oneshot:
1475
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
1476

    
1477
  node = instance.primary_node
1478

    
1479
  for dev in instance.disks:
1480
    lu.cfg.SetDiskID(dev, node)
1481

    
1482
  retries = 0
1483
  while True:
1484
    max_time = 0
1485
    done = True
1486
    cumul_degraded = False
1487
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
1488
    if rstats.failed or not rstats.data:
1489
      lu.LogWarning("Can't get any data from node %s", node)
1490
      retries += 1
1491
      if retries >= 10:
1492
        raise errors.RemoteError("Can't contact node %s for mirror data,"
1493
                                 " aborting." % node)
1494
      time.sleep(6)
1495
      continue
1496
    rstats = rstats.data
1497
    retries = 0
1498
    for i, mstat in enumerate(rstats):
1499
      if mstat is None:
1500
        lu.LogWarning("Can't compute data for node %s/%s",
1501
                           node, instance.disks[i].iv_name)
1502
        continue
1503
      # we ignore the ldisk parameter
1504
      perc_done, est_time, is_degraded, _ = mstat
1505
      cumul_degraded = cumul_degraded or (is_degraded and perc_done is None)
1506
      if perc_done is not None:
1507
        done = False
1508
        if est_time is not None:
1509
          rem_time = "%d estimated seconds remaining" % est_time
1510
          max_time = est_time
1511
        else:
1512
          rem_time = "no time estimate"
1513
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
1514
                        (instance.disks[i].iv_name, perc_done, rem_time))
1515
    if done or oneshot:
1516
      break
1517

    
1518
    time.sleep(min(60, max_time))
1519

    
1520
  if done:
1521
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
1522
  return not cumul_degraded
1523

    
1524

    
1525
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
1526
  """Check that mirrors are not degraded.
1527

1528
  The ldisk parameter, if True, will change the test from the
1529
  is_degraded attribute (which represents overall non-ok status for
1530
  the device(s)) to the ldisk (representing the local storage status).
1531

1532
  """
1533
  lu.cfg.SetDiskID(dev, node)
1534
  if ldisk:
1535
    idx = 6
1536
  else:
1537
    idx = 5
1538

    
1539
  result = True
1540
  if on_primary or dev.AssembleOnSecondary():
1541
    rstats = lu.rpc.call_blockdev_find(node, dev)
1542
    if rstats.failed or not rstats.data:
1543
      logging.warning("Node %s: disk degraded, not found or node down", node)
1544
      result = False
1545
    else:
1546
      result = result and (not rstats.data[idx])
1547
  if dev.children:
1548
    for child in dev.children:
1549
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
1550

    
1551
  return result
1552

    
1553

    
1554
class LUDiagnoseOS(NoHooksLU):
1555
  """Logical unit for OS diagnose/query.
1556

1557
  """
1558
  _OP_REQP = ["output_fields", "names"]
1559
  REQ_BGL = False
1560
  _FIELDS_STATIC = utils.FieldSet()
1561
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status")
1562

    
1563
  def ExpandNames(self):
1564
    if self.op.names:
1565
      raise errors.OpPrereqError("Selective OS query not supported")
1566

    
1567
    _CheckOutputFields(static=self._FIELDS_STATIC,
1568
                       dynamic=self._FIELDS_DYNAMIC,
1569
                       selected=self.op.output_fields)
1570

    
1571
    # Lock all nodes, in shared mode
1572
    self.needed_locks = {}
1573
    self.share_locks[locking.LEVEL_NODE] = 1
1574
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1575

    
1576
  def CheckPrereq(self):
1577
    """Check prerequisites.
1578

1579
    """
1580

    
1581
  @staticmethod
1582
  def _DiagnoseByOS(node_list, rlist):
1583
    """Remaps a per-node return list into an a per-os per-node dictionary
1584

1585
    @param node_list: a list with the names of all nodes
1586
    @param rlist: a map with node names as keys and OS objects as values
1587

1588
    @rtype: dict
1589
    @returns: a dictionary with osnames as keys and as value another map, with
1590
        nodes as keys and list of OS objects as values, eg::
1591

1592
          {"debian-etch": {"node1": [<object>,...],
1593
                           "node2": [<object>,]}
1594
          }
1595

1596
    """
1597
    all_os = {}
1598
    for node_name, nr in rlist.iteritems():
1599
      if nr.failed or not nr.data:
1600
        continue
1601
      for os_obj in nr.data:
1602
        if os_obj.name not in all_os:
1603
          # build a list of nodes for this os containing empty lists
1604
          # for each node in node_list
1605
          all_os[os_obj.name] = {}
1606
          for nname in node_list:
1607
            all_os[os_obj.name][nname] = []
1608
        all_os[os_obj.name][node_name].append(os_obj)
1609
    return all_os
1610

    
1611
  def Exec(self, feedback_fn):
1612
    """Compute the list of OSes.
1613

1614
    """
1615
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1616
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()
1617
                   if node in node_list]
1618
    node_data = self.rpc.call_os_diagnose(valid_nodes)
1619
    if node_data == False:
1620
      raise errors.OpExecError("Can't gather the list of OSes")
1621
    pol = self._DiagnoseByOS(valid_nodes, node_data)
1622
    output = []
1623
    for os_name, os_data in pol.iteritems():
1624
      row = []
1625
      for field in self.op.output_fields:
1626
        if field == "name":
1627
          val = os_name
1628
        elif field == "valid":
1629
          val = utils.all([osl and osl[0] for osl in os_data.values()])
1630
        elif field == "node_status":
1631
          val = {}
1632
          for node_name, nos_list in os_data.iteritems():
1633
            val[node_name] = [(v.status, v.path) for v in nos_list]
1634
        else:
1635
          raise errors.ParameterError(field)
1636
        row.append(val)
1637
      output.append(row)
1638

    
1639
    return output
1640

    
1641

    
1642
class LURemoveNode(LogicalUnit):
1643
  """Logical unit for removing a node.
1644

1645
  """
1646
  HPATH = "node-remove"
1647
  HTYPE = constants.HTYPE_NODE
1648
  _OP_REQP = ["node_name"]
1649

    
1650
  def BuildHooksEnv(self):
1651
    """Build hooks env.
1652

1653
    This doesn't run on the target node in the pre phase as a failed
1654
    node would then be impossible to remove.
1655

1656
    """
1657
    env = {
1658
      "OP_TARGET": self.op.node_name,
1659
      "NODE_NAME": self.op.node_name,
1660
      }
1661
    all_nodes = self.cfg.GetNodeList()
1662
    all_nodes.remove(self.op.node_name)
1663
    return env, all_nodes, all_nodes
1664

    
1665
  def CheckPrereq(self):
1666
    """Check prerequisites.
1667

1668
    This checks:
1669
     - the node exists in the configuration
1670
     - it does not have primary or secondary instances
1671
     - it's not the master
1672

1673
    Any errors are signalled by raising errors.OpPrereqError.
1674

1675
    """
1676
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
1677
    if node is None:
1678
      raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name)
1679

    
1680
    instance_list = self.cfg.GetInstanceList()
1681

    
1682
    masternode = self.cfg.GetMasterNode()
1683
    if node.name == masternode:
1684
      raise errors.OpPrereqError("Node is the master node,"
1685
                                 " you need to failover first.")
1686

    
1687
    for instance_name in instance_list:
1688
      instance = self.cfg.GetInstanceInfo(instance_name)
1689
      if node.name in instance.all_nodes:
1690
        raise errors.OpPrereqError("Instance %s is still running on the node,"
1691
                                   " please remove first." % instance_name)
1692
    self.op.node_name = node.name
1693
    self.node = node
1694

    
1695
  def Exec(self, feedback_fn):
1696
    """Removes the node from the cluster.
1697

1698
    """
1699
    node = self.node
1700
    logging.info("Stopping the node daemon and removing configs from node %s",
1701
                 node.name)
1702

    
1703
    self.context.RemoveNode(node.name)
1704

    
1705
    self.rpc.call_node_leave_cluster(node.name)
1706

    
1707
    # Promote nodes to master candidate as needed
1708
    _AdjustCandidatePool(self)
1709

    
1710

    
1711
class LUQueryNodes(NoHooksLU):
1712
  """Logical unit for querying nodes.
1713

1714
  """
1715
  _OP_REQP = ["output_fields", "names"]
1716
  REQ_BGL = False
1717
  _FIELDS_DYNAMIC = utils.FieldSet(
1718
    "dtotal", "dfree",
1719
    "mtotal", "mnode", "mfree",
1720
    "bootid",
1721
    "ctotal",
1722
    )
1723

    
1724
  _FIELDS_STATIC = utils.FieldSet(
1725
    "name", "pinst_cnt", "sinst_cnt",
1726
    "pinst_list", "sinst_list",
1727
    "pip", "sip", "tags",
1728
    "serial_no",
1729
    "master_candidate",
1730
    "master",
1731
    "offline",
1732
    )
1733

    
1734
  def ExpandNames(self):
1735
    _CheckOutputFields(static=self._FIELDS_STATIC,
1736
                       dynamic=self._FIELDS_DYNAMIC,
1737
                       selected=self.op.output_fields)
1738

    
1739
    self.needed_locks = {}
1740
    self.share_locks[locking.LEVEL_NODE] = 1
1741

    
1742
    if self.op.names:
1743
      self.wanted = _GetWantedNodes(self, self.op.names)
1744
    else:
1745
      self.wanted = locking.ALL_SET
1746

    
1747
    self.do_locking = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
1748
    if self.do_locking:
1749
      # if we don't request only static fields, we need to lock the nodes
1750
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
1751

    
1752

    
1753
  def CheckPrereq(self):
1754
    """Check prerequisites.
1755

1756
    """
1757
    # The validation of the node list is done in the _GetWantedNodes,
1758
    # if non empty, and if empty, there's no validation to do
1759
    pass
1760

    
1761
  def Exec(self, feedback_fn):
1762
    """Computes the list of nodes and their attributes.
1763

1764
    """
1765
    all_info = self.cfg.GetAllNodesInfo()
1766
    if self.do_locking:
1767
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
1768
    elif self.wanted != locking.ALL_SET:
1769
      nodenames = self.wanted
1770
      missing = set(nodenames).difference(all_info.keys())
1771
      if missing:
1772
        raise errors.OpExecError(
1773
          "Some nodes were removed before retrieving their data: %s" % missing)
1774
    else:
1775
      nodenames = all_info.keys()
1776

    
1777
    nodenames = utils.NiceSort(nodenames)
1778
    nodelist = [all_info[name] for name in nodenames]
1779

    
1780
    # begin data gathering
1781

    
1782
    if self.do_locking:
1783
      live_data = {}
1784
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
1785
                                          self.cfg.GetHypervisorType())
1786
      for name in nodenames:
1787
        nodeinfo = node_data[name]
1788
        if not nodeinfo.failed and nodeinfo.data:
1789
          nodeinfo = nodeinfo.data
1790
          fn = utils.TryConvert
1791
          live_data[name] = {
1792
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
1793
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
1794
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
1795
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
1796
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
1797
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
1798
            "bootid": nodeinfo.get('bootid', None),
1799
            }
1800
        else:
1801
          live_data[name] = {}
1802
    else:
1803
      live_data = dict.fromkeys(nodenames, {})
1804

    
1805
    node_to_primary = dict([(name, set()) for name in nodenames])
1806
    node_to_secondary = dict([(name, set()) for name in nodenames])
1807

    
1808
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
1809
                             "sinst_cnt", "sinst_list"))
1810
    if inst_fields & frozenset(self.op.output_fields):
1811
      instancelist = self.cfg.GetInstanceList()
1812

    
1813
      for instance_name in instancelist:
1814
        inst = self.cfg.GetInstanceInfo(instance_name)
1815
        if inst.primary_node in node_to_primary:
1816
          node_to_primary[inst.primary_node].add(inst.name)
1817
        for secnode in inst.secondary_nodes:
1818
          if secnode in node_to_secondary:
1819
            node_to_secondary[secnode].add(inst.name)
1820

    
1821
    master_node = self.cfg.GetMasterNode()
1822

    
1823
    # end data gathering
1824

    
1825
    output = []
1826
    for node in nodelist:
1827
      node_output = []
1828
      for field in self.op.output_fields:
1829
        if field == "name":
1830
          val = node.name
1831
        elif field == "pinst_list":
1832
          val = list(node_to_primary[node.name])
1833
        elif field == "sinst_list":
1834
          val = list(node_to_secondary[node.name])
1835
        elif field == "pinst_cnt":
1836
          val = len(node_to_primary[node.name])
1837
        elif field == "sinst_cnt":
1838
          val = len(node_to_secondary[node.name])
1839
        elif field == "pip":
1840
          val = node.primary_ip
1841
        elif field == "sip":
1842
          val = node.secondary_ip
1843
        elif field == "tags":
1844
          val = list(node.GetTags())
1845
        elif field == "serial_no":
1846
          val = node.serial_no
1847
        elif field == "master_candidate":
1848
          val = node.master_candidate
1849
        elif field == "master":
1850
          val = node.name == master_node
1851
        elif field == "offline":
1852
          val = node.offline
1853
        elif self._FIELDS_DYNAMIC.Matches(field):
1854
          val = live_data[node.name].get(field, None)
1855
        else:
1856
          raise errors.ParameterError(field)
1857
        node_output.append(val)
1858
      output.append(node_output)
1859

    
1860
    return output
1861

    
1862

    
1863
class LUQueryNodeVolumes(NoHooksLU):
1864
  """Logical unit for getting volumes on node(s).
1865

1866
  """
1867
  _OP_REQP = ["nodes", "output_fields"]
1868
  REQ_BGL = False
1869
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
1870
  _FIELDS_STATIC = utils.FieldSet("node")
1871

    
1872
  def ExpandNames(self):
1873
    _CheckOutputFields(static=self._FIELDS_STATIC,
1874
                       dynamic=self._FIELDS_DYNAMIC,
1875
                       selected=self.op.output_fields)
1876

    
1877
    self.needed_locks = {}
1878
    self.share_locks[locking.LEVEL_NODE] = 1
1879
    if not self.op.nodes:
1880
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1881
    else:
1882
      self.needed_locks[locking.LEVEL_NODE] = \
1883
        _GetWantedNodes(self, self.op.nodes)
1884

    
1885
  def CheckPrereq(self):
1886
    """Check prerequisites.
1887

1888
    This checks that the fields required are valid output fields.
1889

1890
    """
1891
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
1892

    
1893
  def Exec(self, feedback_fn):
1894
    """Computes the list of nodes and their attributes.
1895

1896
    """
1897
    nodenames = self.nodes
1898
    volumes = self.rpc.call_node_volumes(nodenames)
1899

    
1900
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
1901
             in self.cfg.GetInstanceList()]
1902

    
1903
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
1904

    
1905
    output = []
1906
    for node in nodenames:
1907
      if node not in volumes or volumes[node].failed or not volumes[node].data:
1908
        continue
1909

    
1910
      node_vols = volumes[node].data[:]
1911
      node_vols.sort(key=lambda vol: vol['dev'])
1912

    
1913
      for vol in node_vols:
1914
        node_output = []
1915
        for field in self.op.output_fields:
1916
          if field == "node":
1917
            val = node
1918
          elif field == "phys":
1919
            val = vol['dev']
1920
          elif field == "vg":
1921
            val = vol['vg']
1922
          elif field == "name":
1923
            val = vol['name']
1924
          elif field == "size":
1925
            val = int(float(vol['size']))
1926
          elif field == "instance":
1927
            for inst in ilist:
1928
              if node not in lv_by_node[inst]:
1929
                continue
1930
              if vol['name'] in lv_by_node[inst][node]:
1931
                val = inst.name
1932
                break
1933
            else:
1934
              val = '-'
1935
          else:
1936
            raise errors.ParameterError(field)
1937
          node_output.append(str(val))
1938

    
1939
        output.append(node_output)
1940

    
1941
    return output
1942

    
1943

    
1944
class LUAddNode(LogicalUnit):
1945
  """Logical unit for adding node to the cluster.
1946

1947
  """
1948
  HPATH = "node-add"
1949
  HTYPE = constants.HTYPE_NODE
1950
  _OP_REQP = ["node_name"]
1951

    
1952
  def BuildHooksEnv(self):
1953
    """Build hooks env.
1954

1955
    This will run on all nodes before, and on all nodes + the new node after.
1956

1957
    """
1958
    env = {
1959
      "OP_TARGET": self.op.node_name,
1960
      "NODE_NAME": self.op.node_name,
1961
      "NODE_PIP": self.op.primary_ip,
1962
      "NODE_SIP": self.op.secondary_ip,
1963
      }
1964
    nodes_0 = self.cfg.GetNodeList()
1965
    nodes_1 = nodes_0 + [self.op.node_name, ]
1966
    return env, nodes_0, nodes_1
1967

    
1968
  def CheckPrereq(self):
1969
    """Check prerequisites.
1970

1971
    This checks:
1972
     - the new node is not already in the config
1973
     - it is resolvable
1974
     - its parameters (single/dual homed) matches the cluster
1975

1976
    Any errors are signalled by raising errors.OpPrereqError.
1977

1978
    """
1979
    node_name = self.op.node_name
1980
    cfg = self.cfg
1981

    
1982
    dns_data = utils.HostInfo(node_name)
1983

    
1984
    node = dns_data.name
1985
    primary_ip = self.op.primary_ip = dns_data.ip
1986
    secondary_ip = getattr(self.op, "secondary_ip", None)
1987
    if secondary_ip is None:
1988
      secondary_ip = primary_ip
1989
    if not utils.IsValidIP(secondary_ip):
1990
      raise errors.OpPrereqError("Invalid secondary IP given")
1991
    self.op.secondary_ip = secondary_ip
1992

    
1993
    node_list = cfg.GetNodeList()
1994
    if not self.op.readd and node in node_list:
1995
      raise errors.OpPrereqError("Node %s is already in the configuration" %
1996
                                 node)
1997
    elif self.op.readd and node not in node_list:
1998
      raise errors.OpPrereqError("Node %s is not in the configuration" % node)
1999

    
2000
    for existing_node_name in node_list:
2001
      existing_node = cfg.GetNodeInfo(existing_node_name)
2002

    
2003
      if self.op.readd and node == existing_node_name:
2004
        if (existing_node.primary_ip != primary_ip or
2005
            existing_node.secondary_ip != secondary_ip):
2006
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
2007
                                     " address configuration as before")
2008
        continue
2009

    
2010
      if (existing_node.primary_ip == primary_ip or
2011
          existing_node.secondary_ip == primary_ip or
2012
          existing_node.primary_ip == secondary_ip or
2013
          existing_node.secondary_ip == secondary_ip):
2014
        raise errors.OpPrereqError("New node ip address(es) conflict with"
2015
                                   " existing node %s" % existing_node.name)
2016

    
2017
    # check that the type of the node (single versus dual homed) is the
2018
    # same as for the master
2019
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
2020
    master_singlehomed = myself.secondary_ip == myself.primary_ip
2021
    newbie_singlehomed = secondary_ip == primary_ip
2022
    if master_singlehomed != newbie_singlehomed:
2023
      if master_singlehomed:
2024
        raise errors.OpPrereqError("The master has no private ip but the"
2025
                                   " new node has one")
2026
      else:
2027
        raise errors.OpPrereqError("The master has a private ip but the"
2028
                                   " new node doesn't have one")
2029

    
2030
    # checks reachablity
2031
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
2032
      raise errors.OpPrereqError("Node not reachable by ping")
2033

    
2034
    if not newbie_singlehomed:
2035
      # check reachability from my secondary ip to newbie's secondary ip
2036
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
2037
                           source=myself.secondary_ip):
2038
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
2039
                                   " based ping to noded port")
2040

    
2041
    cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2042
    mc_now, _ = self.cfg.GetMasterCandidateStats()
2043
    master_candidate = mc_now < cp_size
2044

    
2045
    self.new_node = objects.Node(name=node,
2046
                                 primary_ip=primary_ip,
2047
                                 secondary_ip=secondary_ip,
2048
                                 master_candidate=master_candidate,
2049
                                 offline=False)
2050

    
2051
  def Exec(self, feedback_fn):
2052
    """Adds the new node to the cluster.
2053

2054
    """
2055
    new_node = self.new_node
2056
    node = new_node.name
2057

    
2058
    # check connectivity
2059
    result = self.rpc.call_version([node])[node]
2060
    result.Raise()
2061
    if result.data:
2062
      if constants.PROTOCOL_VERSION == result.data:
2063
        logging.info("Communication to node %s fine, sw version %s match",
2064
                     node, result.data)
2065
      else:
2066
        raise errors.OpExecError("Version mismatch master version %s,"
2067
                                 " node version %s" %
2068
                                 (constants.PROTOCOL_VERSION, result.data))
2069
    else:
2070
      raise errors.OpExecError("Cannot get version from the new node")
2071

    
2072
    # setup ssh on node
2073
    logging.info("Copy ssh key to node %s", node)
2074
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
2075
    keyarray = []
2076
    keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
2077
                constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
2078
                priv_key, pub_key]
2079

    
2080
    for i in keyfiles:
2081
      f = open(i, 'r')
2082
      try:
2083
        keyarray.append(f.read())
2084
      finally:
2085
        f.close()
2086

    
2087
    result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
2088
                                    keyarray[2],
2089
                                    keyarray[3], keyarray[4], keyarray[5])
2090

    
2091
    if result.failed or not result.data:
2092
      raise errors.OpExecError("Cannot transfer ssh keys to the new node")
2093

    
2094
    # Add node to our /etc/hosts, and add key to known_hosts
2095
    utils.AddHostToEtcHosts(new_node.name)
2096

    
2097
    if new_node.secondary_ip != new_node.primary_ip:
2098
      result = self.rpc.call_node_has_ip_address(new_node.name,
2099
                                                 new_node.secondary_ip)
2100
      if result.failed or not result.data:
2101
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
2102
                                 " you gave (%s). Please fix and re-run this"
2103
                                 " command." % new_node.secondary_ip)
2104

    
2105
    node_verify_list = [self.cfg.GetMasterNode()]
2106
    node_verify_param = {
2107
      'nodelist': [node],
2108
      # TODO: do a node-net-test as well?
2109
    }
2110

    
2111
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
2112
                                       self.cfg.GetClusterName())
2113
    for verifier in node_verify_list:
2114
      if result[verifier].failed or not result[verifier].data:
2115
        raise errors.OpExecError("Cannot communicate with %s's node daemon"
2116
                                 " for remote verification" % verifier)
2117
      if result[verifier].data['nodelist']:
2118
        for failed in result[verifier].data['nodelist']:
2119
          feedback_fn("ssh/hostname verification failed %s -> %s" %
2120
                      (verifier, result[verifier]['nodelist'][failed]))
2121
        raise errors.OpExecError("ssh/hostname verification failed.")
2122

    
2123
    # Distribute updated /etc/hosts and known_hosts to all nodes,
2124
    # including the node just added
2125
    myself = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
2126
    dist_nodes = self.cfg.GetNodeList()
2127
    if not self.op.readd:
2128
      dist_nodes.append(node)
2129
    if myself.name in dist_nodes:
2130
      dist_nodes.remove(myself.name)
2131

    
2132
    logging.debug("Copying hosts and known_hosts to all nodes")
2133
    for fname in (constants.ETC_HOSTS, constants.SSH_KNOWN_HOSTS_FILE):
2134
      result = self.rpc.call_upload_file(dist_nodes, fname)
2135
      for to_node, to_result in result.iteritems():
2136
        if to_result.failed or not to_result.data:
2137
          logging.error("Copy of file %s to node %s failed", fname, to_node)
2138

    
2139
    to_copy = []
2140
    if constants.HT_XEN_HVM in self.cfg.GetClusterInfo().enabled_hypervisors:
2141
      to_copy.append(constants.VNC_PASSWORD_FILE)
2142
    for fname in to_copy:
2143
      result = self.rpc.call_upload_file([node], fname)
2144
      if result[node].failed or not result[node]:
2145
        logging.error("Could not copy file %s to node %s", fname, node)
2146

    
2147
    if self.op.readd:
2148
      self.context.ReaddNode(new_node)
2149
    else:
2150
      self.context.AddNode(new_node)
2151

    
2152

    
2153
class LUSetNodeParams(LogicalUnit):
2154
  """Modifies the parameters of a node.
2155

2156
  """
2157
  HPATH = "node-modify"
2158
  HTYPE = constants.HTYPE_NODE
2159
  _OP_REQP = ["node_name"]
2160
  REQ_BGL = False
2161

    
2162
  def CheckArguments(self):
2163
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2164
    if node_name is None:
2165
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
2166
    self.op.node_name = node_name
2167
    _CheckBooleanOpField(self.op, 'master_candidate')
2168
    _CheckBooleanOpField(self.op, 'offline')
2169
    if self.op.master_candidate is None and self.op.offline is None:
2170
      raise errors.OpPrereqError("Please pass at least one modification")
2171
    if self.op.offline == True and self.op.master_candidate == True:
2172
      raise errors.OpPrereqError("Can't set the node into offline and"
2173
                                 " master_candidate at the same time")
2174

    
2175
  def ExpandNames(self):
2176
    self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
2177

    
2178
  def BuildHooksEnv(self):
2179
    """Build hooks env.
2180

2181
    This runs on the master node.
2182

2183
    """
2184
    env = {
2185
      "OP_TARGET": self.op.node_name,
2186
      "MASTER_CANDIDATE": str(self.op.master_candidate),
2187
      "OFFLINE": str(self.op.offline),
2188
      }
2189
    nl = [self.cfg.GetMasterNode(),
2190
          self.op.node_name]
2191
    return env, nl, nl
2192

    
2193
  def CheckPrereq(self):
2194
    """Check prerequisites.
2195

2196
    This only checks the instance list against the existing names.
2197

2198
    """
2199
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
2200

    
2201
    if ((self.op.master_candidate == False or self.op.offline == True)
2202
        and node.master_candidate):
2203
      # we will demote the node from master_candidate
2204
      if self.op.node_name == self.cfg.GetMasterNode():
2205
        raise errors.OpPrereqError("The master node has to be a"
2206
                                   " master candidate and online")
2207
      cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2208
      num_candidates, _ = self.cfg.GetMasterCandidateStats()
2209
      if num_candidates <= cp_size:
2210
        msg = ("Not enough master candidates (desired"
2211
               " %d, new value will be %d)" % (cp_size, num_candidates-1))
2212
        if self.op.force:
2213
          self.LogWarning(msg)
2214
        else:
2215
          raise errors.OpPrereqError(msg)
2216

    
2217
    if (self.op.master_candidate == True and node.offline and
2218
        not self.op.offline == False):
2219
      raise errors.OpPrereqError("Can't set an offline node to"
2220
                                 " master_candidate")
2221

    
2222
    return
2223

    
2224
  def Exec(self, feedback_fn):
2225
    """Modifies a node.
2226

2227
    """
2228
    node = self.node
2229

    
2230
    result = []
2231

    
2232
    if self.op.offline is not None:
2233
      node.offline = self.op.offline
2234
      result.append(("offline", str(self.op.offline)))
2235
      if self.op.offline == True and node.master_candidate:
2236
        node.master_candidate = False
2237
        result.append(("master_candidate", "auto-demotion due to offline"))
2238

    
2239
    if self.op.master_candidate is not None:
2240
      node.master_candidate = self.op.master_candidate
2241
      result.append(("master_candidate", str(self.op.master_candidate)))
2242
      if self.op.master_candidate == False:
2243
        rrc = self.rpc.call_node_demote_from_mc(node.name)
2244
        if (rrc.failed or not isinstance(rrc.data, (tuple, list))
2245
            or len(rrc.data) != 2):
2246
          self.LogWarning("Node rpc error: %s" % rrc.error)
2247
        elif not rrc.data[0]:
2248
          self.LogWarning("Node failed to demote itself: %s" % rrc.data[1])
2249

    
2250
    # this will trigger configuration file update, if needed
2251
    self.cfg.Update(node)
2252
    # this will trigger job queue propagation or cleanup
2253
    if self.op.node_name != self.cfg.GetMasterNode():
2254
      self.context.ReaddNode(node)
2255

    
2256
    return result
2257

    
2258

    
2259
class LUQueryClusterInfo(NoHooksLU):
2260
  """Query cluster configuration.
2261

2262
  """
2263
  _OP_REQP = []
2264
  REQ_BGL = False
2265

    
2266
  def ExpandNames(self):
2267
    self.needed_locks = {}
2268

    
2269
  def CheckPrereq(self):
2270
    """No prerequsites needed for this LU.
2271

2272
    """
2273
    pass
2274

    
2275
  def Exec(self, feedback_fn):
2276
    """Return cluster config.
2277

2278
    """
2279
    cluster = self.cfg.GetClusterInfo()
2280
    result = {
2281
      "software_version": constants.RELEASE_VERSION,
2282
      "protocol_version": constants.PROTOCOL_VERSION,
2283
      "config_version": constants.CONFIG_VERSION,
2284
      "os_api_version": constants.OS_API_VERSION,
2285
      "export_version": constants.EXPORT_VERSION,
2286
      "architecture": (platform.architecture()[0], platform.machine()),
2287
      "name": cluster.cluster_name,
2288
      "master": cluster.master_node,
2289
      "default_hypervisor": cluster.default_hypervisor,
2290
      "enabled_hypervisors": cluster.enabled_hypervisors,
2291
      "hvparams": cluster.hvparams,
2292
      "beparams": cluster.beparams,
2293
      "candidate_pool_size": cluster.candidate_pool_size,
2294
      }
2295

    
2296
    return result
2297

    
2298

    
2299
class LUQueryConfigValues(NoHooksLU):
2300
  """Return configuration values.
2301

2302
  """
2303
  _OP_REQP = []
2304
  REQ_BGL = False
2305
  _FIELDS_DYNAMIC = utils.FieldSet()
2306
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag")
2307

    
2308
  def ExpandNames(self):
2309
    self.needed_locks = {}
2310

    
2311
    _CheckOutputFields(static=self._FIELDS_STATIC,
2312
                       dynamic=self._FIELDS_DYNAMIC,
2313
                       selected=self.op.output_fields)
2314

    
2315
  def CheckPrereq(self):
2316
    """No prerequisites.
2317

2318
    """
2319
    pass
2320

    
2321
  def Exec(self, feedback_fn):
2322
    """Dump a representation of the cluster config to the standard output.
2323

2324
    """
2325
    values = []
2326
    for field in self.op.output_fields:
2327
      if field == "cluster_name":
2328
        entry = self.cfg.GetClusterName()
2329
      elif field == "master_node":
2330
        entry = self.cfg.GetMasterNode()
2331
      elif field == "drain_flag":
2332
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
2333
      else:
2334
        raise errors.ParameterError(field)
2335
      values.append(entry)
2336
    return values
2337

    
2338

    
2339
class LUActivateInstanceDisks(NoHooksLU):
2340
  """Bring up an instance's disks.
2341

2342
  """
2343
  _OP_REQP = ["instance_name"]
2344
  REQ_BGL = False
2345

    
2346
  def ExpandNames(self):
2347
    self._ExpandAndLockInstance()
2348
    self.needed_locks[locking.LEVEL_NODE] = []
2349
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2350

    
2351
  def DeclareLocks(self, level):
2352
    if level == locking.LEVEL_NODE:
2353
      self._LockInstancesNodes()
2354

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

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

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

    
2366
  def Exec(self, feedback_fn):
2367
    """Activate the disks.
2368

2369
    """
2370
    disks_ok, disks_info = _AssembleInstanceDisks(self, self.instance)
2371
    if not disks_ok:
2372
      raise errors.OpExecError("Cannot activate block devices")
2373

    
2374
    return disks_info
2375

    
2376

    
2377
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False):
2378
  """Prepare the block devices for an instance.
2379

2380
  This sets up the block devices on all nodes.
2381

2382
  @type lu: L{LogicalUnit}
2383
  @param lu: the logical unit on whose behalf we execute
2384
  @type instance: L{objects.Instance}
2385
  @param instance: the instance for whose disks we assemble
2386
  @type ignore_secondaries: boolean
2387
  @param ignore_secondaries: if true, errors on secondary nodes
2388
      won't result in an error return from the function
2389
  @return: False if the operation failed, otherwise a list of
2390
      (host, instance_visible_name, node_visible_name)
2391
      with the mapping from node devices to instance devices
2392

2393
  """
2394
  device_info = []
2395
  disks_ok = True
2396
  iname = instance.name
2397
  # With the two passes mechanism we try to reduce the window of
2398
  # opportunity for the race condition of switching DRBD to primary
2399
  # before handshaking occured, but we do not eliminate it
2400

    
2401
  # The proper fix would be to wait (with some limits) until the
2402
  # connection has been made and drbd transitions from WFConnection
2403
  # into any other network-connected state (Connected, SyncTarget,
2404
  # SyncSource, etc.)
2405

    
2406
  # 1st pass, assemble on all nodes in secondary mode
2407
  for inst_disk in instance.disks:
2408
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2409
      lu.cfg.SetDiskID(node_disk, node)
2410
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
2411
      if result.failed or not result:
2412
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2413
                           " (is_primary=False, pass=1)",
2414
                           inst_disk.iv_name, node)
2415
        if not ignore_secondaries:
2416
          disks_ok = False
2417

    
2418
  # FIXME: race condition on drbd migration to primary
2419

    
2420
  # 2nd pass, do only the primary node
2421
  for inst_disk in instance.disks:
2422
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2423
      if node != instance.primary_node:
2424
        continue
2425
      lu.cfg.SetDiskID(node_disk, node)
2426
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
2427
      if result.failed or not result:
2428
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2429
                           " (is_primary=True, pass=2)",
2430
                           inst_disk.iv_name, node)
2431
        disks_ok = False
2432
    device_info.append((instance.primary_node, inst_disk.iv_name, result.data))
2433

    
2434
  # leave the disks configured for the primary node
2435
  # this is a workaround that would be fixed better by
2436
  # improving the logical/physical id handling
2437
  for disk in instance.disks:
2438
    lu.cfg.SetDiskID(disk, instance.primary_node)
2439

    
2440
  return disks_ok, device_info
2441

    
2442

    
2443
def _StartInstanceDisks(lu, instance, force):
2444
  """Start the disks of an instance.
2445

2446
  """
2447
  disks_ok, dummy = _AssembleInstanceDisks(lu, instance,
2448
                                           ignore_secondaries=force)
2449
  if not disks_ok:
2450
    _ShutdownInstanceDisks(lu, instance)
2451
    if force is not None and not force:
2452
      lu.proc.LogWarning("", hint="If the message above refers to a"
2453
                         " secondary node,"
2454
                         " you can retry the operation using '--force'.")
2455
    raise errors.OpExecError("Disk consistency error")
2456

    
2457

    
2458
class LUDeactivateInstanceDisks(NoHooksLU):
2459
  """Shutdown an instance's disks.
2460

2461
  """
2462
  _OP_REQP = ["instance_name"]
2463
  REQ_BGL = False
2464

    
2465
  def ExpandNames(self):
2466
    self._ExpandAndLockInstance()
2467
    self.needed_locks[locking.LEVEL_NODE] = []
2468
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2469

    
2470
  def DeclareLocks(self, level):
2471
    if level == locking.LEVEL_NODE:
2472
      self._LockInstancesNodes()
2473

    
2474
  def CheckPrereq(self):
2475
    """Check prerequisites.
2476

2477
    This checks that the instance is in the cluster.
2478

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

    
2484
  def Exec(self, feedback_fn):
2485
    """Deactivate the disks
2486

2487
    """
2488
    instance = self.instance
2489
    _SafeShutdownInstanceDisks(self, instance)
2490

    
2491

    
2492
def _SafeShutdownInstanceDisks(lu, instance):
2493
  """Shutdown block devices of an instance.
2494

2495
  This function checks if an instance is running, before calling
2496
  _ShutdownInstanceDisks.
2497

2498
  """
2499
  ins_l = lu.rpc.call_instance_list([instance.primary_node],
2500
                                      [instance.hypervisor])
2501
  ins_l = ins_l[instance.primary_node]
2502
  if ins_l.failed or not isinstance(ins_l.data, list):
2503
    raise errors.OpExecError("Can't contact node '%s'" %
2504
                             instance.primary_node)
2505

    
2506
  if instance.name in ins_l.data:
2507
    raise errors.OpExecError("Instance is running, can't shutdown"
2508
                             " block devices.")
2509

    
2510
  _ShutdownInstanceDisks(lu, instance)
2511

    
2512

    
2513
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
2514
  """Shutdown block devices of an instance.
2515

2516
  This does the shutdown on all nodes of the instance.
2517

2518
  If the ignore_primary is false, errors on the primary node are
2519
  ignored.
2520

2521
  """
2522
  result = True
2523
  for disk in instance.disks:
2524
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
2525
      lu.cfg.SetDiskID(top_disk, node)
2526
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
2527
      if result.failed or not result.data:
2528
        logging.error("Could not shutdown block device %s on node %s",
2529
                      disk.iv_name, node)
2530
        if not ignore_primary or node != instance.primary_node:
2531
          result = False
2532
  return result
2533

    
2534

    
2535
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
2536
  """Checks if a node has enough free memory.
2537

2538
  This function check if a given node has the needed amount of free
2539
  memory. In case the node has less memory or we cannot get the
2540
  information from the node, this function raise an OpPrereqError
2541
  exception.
2542

2543
  @type lu: C{LogicalUnit}
2544
  @param lu: a logical unit from which we get configuration data
2545
  @type node: C{str}
2546
  @param node: the node to check
2547
  @type reason: C{str}
2548
  @param reason: string to use in the error message
2549
  @type requested: C{int}
2550
  @param requested: the amount of memory in MiB to check for
2551
  @type hypervisor_name: C{str}
2552
  @param hypervisor_name: the hypervisor to ask for memory stats
2553
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
2554
      we cannot check the node
2555

2556
  """
2557
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
2558
  nodeinfo[node].Raise()
2559
  free_mem = nodeinfo[node].data.get('memory_free')
2560
  if not isinstance(free_mem, int):
2561
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
2562
                             " was '%s'" % (node, free_mem))
2563
  if requested > free_mem:
2564
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
2565
                             " needed %s MiB, available %s MiB" %
2566
                             (node, reason, requested, free_mem))
2567

    
2568

    
2569
class LUStartupInstance(LogicalUnit):
2570
  """Starts an instance.
2571

2572
  """
2573
  HPATH = "instance-start"
2574
  HTYPE = constants.HTYPE_INSTANCE
2575
  _OP_REQP = ["instance_name", "force"]
2576
  REQ_BGL = False
2577

    
2578
  def ExpandNames(self):
2579
    self._ExpandAndLockInstance()
2580

    
2581
  def BuildHooksEnv(self):
2582
    """Build hooks env.
2583

2584
    This runs on master, primary and secondary nodes of the instance.
2585

2586
    """
2587
    env = {
2588
      "FORCE": self.op.force,
2589
      }
2590
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2591
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2592
    return env, nl, nl
2593

    
2594
  def CheckPrereq(self):
2595
    """Check prerequisites.
2596

2597
    This checks that the instance is in the cluster.
2598

2599
    """
2600
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2601
    assert self.instance is not None, \
2602
      "Cannot retrieve locked instance %s" % self.op.instance_name
2603

    
2604
    _CheckNodeOnline(self, instance.primary_node)
2605

    
2606
    bep = self.cfg.GetClusterInfo().FillBE(instance)
2607
    # check bridges existance
2608
    _CheckInstanceBridgesExist(self, instance)
2609

    
2610
    _CheckNodeFreeMemory(self, instance.primary_node,
2611
                         "starting instance %s" % instance.name,
2612
                         bep[constants.BE_MEMORY], instance.hypervisor)
2613

    
2614
  def Exec(self, feedback_fn):
2615
    """Start the instance.
2616

2617
    """
2618
    instance = self.instance
2619
    force = self.op.force
2620
    extra_args = getattr(self.op, "extra_args", "")
2621

    
2622
    self.cfg.MarkInstanceUp(instance.name)
2623

    
2624
    node_current = instance.primary_node
2625

    
2626
    _StartInstanceDisks(self, instance, force)
2627

    
2628
    result = self.rpc.call_instance_start(node_current, instance, extra_args)
2629
    msg = result.RemoteFailMsg()
2630
    if msg:
2631
      _ShutdownInstanceDisks(self, instance)
2632
      raise errors.OpExecError("Could not start instance: %s" % msg)
2633

    
2634

    
2635
class LURebootInstance(LogicalUnit):
2636
  """Reboot an instance.
2637

2638
  """
2639
  HPATH = "instance-reboot"
2640
  HTYPE = constants.HTYPE_INSTANCE
2641
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
2642
  REQ_BGL = False
2643

    
2644
  def ExpandNames(self):
2645
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
2646
                                   constants.INSTANCE_REBOOT_HARD,
2647
                                   constants.INSTANCE_REBOOT_FULL]:
2648
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
2649
                                  (constants.INSTANCE_REBOOT_SOFT,
2650
                                   constants.INSTANCE_REBOOT_HARD,
2651
                                   constants.INSTANCE_REBOOT_FULL))
2652
    self._ExpandAndLockInstance()
2653

    
2654
  def BuildHooksEnv(self):
2655
    """Build hooks env.
2656

2657
    This runs on master, primary and secondary nodes of the instance.
2658

2659
    """
2660
    env = {
2661
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
2662
      }
2663
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2664
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2665
    return env, nl, nl
2666

    
2667
  def CheckPrereq(self):
2668
    """Check prerequisites.
2669

2670
    This checks that the instance is in the cluster.
2671

2672
    """
2673
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2674
    assert self.instance is not None, \
2675
      "Cannot retrieve locked instance %s" % self.op.instance_name
2676

    
2677
    _CheckNodeOnline(self, instance.primary_node)
2678

    
2679
    # check bridges existance
2680
    _CheckInstanceBridgesExist(self, instance)
2681

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

2685
    """
2686
    instance = self.instance
2687
    ignore_secondaries = self.op.ignore_secondaries
2688
    reboot_type = self.op.reboot_type
2689
    extra_args = getattr(self.op, "extra_args", "")
2690

    
2691
    node_current = instance.primary_node
2692

    
2693
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
2694
                       constants.INSTANCE_REBOOT_HARD]:
2695
      result = self.rpc.call_instance_reboot(node_current, instance,
2696
                                             reboot_type, extra_args)
2697
      if result.failed or not result.data:
2698
        raise errors.OpExecError("Could not reboot instance")
2699
    else:
2700
      if not self.rpc.call_instance_shutdown(node_current, instance):
2701
        raise errors.OpExecError("could not shutdown instance for full reboot")
2702
      _ShutdownInstanceDisks(self, instance)
2703
      _StartInstanceDisks(self, instance, ignore_secondaries)
2704
      result = self.rpc.call_instance_start(node_current, instance, extra_args)
2705
      msg = result.RemoteFailMsg()
2706
      if msg:
2707
        _ShutdownInstanceDisks(self, instance)
2708
        raise errors.OpExecError("Could not start instance for"
2709
                                 " full reboot: %s" % msg)
2710

    
2711
    self.cfg.MarkInstanceUp(instance.name)
2712

    
2713

    
2714
class LUShutdownInstance(LogicalUnit):
2715
  """Shutdown an instance.
2716

2717
  """
2718
  HPATH = "instance-stop"
2719
  HTYPE = constants.HTYPE_INSTANCE
2720
  _OP_REQP = ["instance_name"]
2721
  REQ_BGL = False
2722

    
2723
  def ExpandNames(self):
2724
    self._ExpandAndLockInstance()
2725

    
2726
  def BuildHooksEnv(self):
2727
    """Build hooks env.
2728

2729
    This runs on master, primary and secondary nodes of the instance.
2730

2731
    """
2732
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2733
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2734
    return env, nl, nl
2735

    
2736
  def CheckPrereq(self):
2737
    """Check prerequisites.
2738

2739
    This checks that the instance is in the cluster.
2740

2741
    """
2742
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2743
    assert self.instance is not None, \
2744
      "Cannot retrieve locked instance %s" % self.op.instance_name
2745
    _CheckNodeOnline(self, self.instance.primary_node)
2746

    
2747
  def Exec(self, feedback_fn):
2748
    """Shutdown the instance.
2749

2750
    """
2751
    instance = self.instance
2752
    node_current = instance.primary_node
2753
    self.cfg.MarkInstanceDown(instance.name)
2754
    result = self.rpc.call_instance_shutdown(node_current, instance)
2755
    if result.failed or not result.data:
2756
      self.proc.LogWarning("Could not shutdown instance")
2757

    
2758
    _ShutdownInstanceDisks(self, instance)
2759

    
2760

    
2761
class LUReinstallInstance(LogicalUnit):
2762
  """Reinstall an instance.
2763

2764
  """
2765
  HPATH = "instance-reinstall"
2766
  HTYPE = constants.HTYPE_INSTANCE
2767
  _OP_REQP = ["instance_name"]
2768
  REQ_BGL = False
2769

    
2770
  def ExpandNames(self):
2771
    self._ExpandAndLockInstance()
2772

    
2773
  def BuildHooksEnv(self):
2774
    """Build hooks env.
2775

2776
    This runs on master, primary and secondary nodes of the instance.
2777

2778
    """
2779
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2780
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2781
    return env, nl, nl
2782

    
2783
  def CheckPrereq(self):
2784
    """Check prerequisites.
2785

2786
    This checks that the instance is in the cluster and is not running.
2787

2788
    """
2789
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2790
    assert instance is not None, \
2791
      "Cannot retrieve locked instance %s" % self.op.instance_name
2792
    _CheckNodeOnline(self, instance.primary_node)
2793

    
2794
    if instance.disk_template == constants.DT_DISKLESS:
2795
      raise errors.OpPrereqError("Instance '%s' has no disks" %
2796
                                 self.op.instance_name)
2797
    if instance.status != "down":
2798
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2799
                                 self.op.instance_name)
2800
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2801
                                              instance.name,
2802
                                              instance.hypervisor)
2803
    if remote_info.failed or remote_info.data:
2804
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2805
                                 (self.op.instance_name,
2806
                                  instance.primary_node))
2807

    
2808
    self.op.os_type = getattr(self.op, "os_type", None)
2809
    if self.op.os_type is not None:
2810
      # OS verification
2811
      pnode = self.cfg.GetNodeInfo(
2812
        self.cfg.ExpandNodeName(instance.primary_node))
2813
      if pnode is None:
2814
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
2815
                                   self.op.pnode)
2816
      result = self.rpc.call_os_get(pnode.name, self.op.os_type)
2817
      result.Raise()
2818
      if not isinstance(result.data, objects.OS):
2819
        raise errors.OpPrereqError("OS '%s' not in supported OS list for"
2820
                                   " primary node"  % self.op.os_type)
2821

    
2822
    self.instance = instance
2823

    
2824
  def Exec(self, feedback_fn):
2825
    """Reinstall the instance.
2826

2827
    """
2828
    inst = self.instance
2829

    
2830
    if self.op.os_type is not None:
2831
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
2832
      inst.os = self.op.os_type
2833
      self.cfg.Update(inst)
2834

    
2835
    _StartInstanceDisks(self, inst, None)
2836
    try:
2837
      feedback_fn("Running the instance OS create scripts...")
2838
      result = self.rpc.call_instance_os_add(inst.primary_node, inst)
2839
      msg = result.RemoteFailMsg()
2840
      if msg:
2841
        raise errors.OpExecError("Could not install OS for instance %s"
2842
                                 " on node %s: %s" %
2843
                                 (inst.name, inst.primary_node, msg))
2844
    finally:
2845
      _ShutdownInstanceDisks(self, inst)
2846

    
2847

    
2848
class LURenameInstance(LogicalUnit):
2849
  """Rename an instance.
2850

2851
  """
2852
  HPATH = "instance-rename"
2853
  HTYPE = constants.HTYPE_INSTANCE
2854
  _OP_REQP = ["instance_name", "new_name"]
2855

    
2856
  def BuildHooksEnv(self):
2857
    """Build hooks env.
2858

2859
    This runs on master, primary and secondary nodes of the instance.
2860

2861
    """
2862
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2863
    env["INSTANCE_NEW_NAME"] = self.op.new_name
2864
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2865
    return env, nl, nl
2866

    
2867
  def CheckPrereq(self):
2868
    """Check prerequisites.
2869

2870
    This checks that the instance is in the cluster and is not running.
2871

2872
    """
2873
    instance = self.cfg.GetInstanceInfo(
2874
      self.cfg.ExpandInstanceName(self.op.instance_name))
2875
    if instance is None:
2876
      raise errors.OpPrereqError("Instance '%s' not known" %
2877
                                 self.op.instance_name)
2878
    _CheckNodeOnline(self, instance.primary_node)
2879

    
2880
    if instance.status != "down":
2881
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2882
                                 self.op.instance_name)
2883
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2884
                                              instance.name,
2885
                                              instance.hypervisor)
2886
    remote_info.Raise()
2887
    if remote_info.data:
2888
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2889
                                 (self.op.instance_name,
2890
                                  instance.primary_node))
2891
    self.instance = instance
2892

    
2893
    # new name verification
2894
    name_info = utils.HostInfo(self.op.new_name)
2895

    
2896
    self.op.new_name = new_name = name_info.name
2897
    instance_list = self.cfg.GetInstanceList()
2898
    if new_name in instance_list:
2899
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
2900
                                 new_name)
2901

    
2902
    if not getattr(self.op, "ignore_ip", False):
2903
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
2904
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
2905
                                   (name_info.ip, new_name))
2906

    
2907

    
2908
  def Exec(self, feedback_fn):
2909
    """Reinstall the instance.
2910

2911
    """
2912
    inst = self.instance
2913
    old_name = inst.name
2914

    
2915
    if inst.disk_template == constants.DT_FILE:
2916
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2917

    
2918
    self.cfg.RenameInstance(inst.name, self.op.new_name)
2919
    # Change the instance lock. This is definitely safe while we hold the BGL
2920
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
2921
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
2922

    
2923
    # re-read the instance from the configuration after rename
2924
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
2925

    
2926
    if inst.disk_template == constants.DT_FILE:
2927
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2928
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
2929
                                                     old_file_storage_dir,
2930
                                                     new_file_storage_dir)
2931
      result.Raise()
2932
      if not result.data:
2933
        raise errors.OpExecError("Could not connect to node '%s' to rename"
2934
                                 " directory '%s' to '%s' (but the instance"
2935
                                 " has been renamed in Ganeti)" % (
2936
                                 inst.primary_node, old_file_storage_dir,
2937
                                 new_file_storage_dir))
2938

    
2939
      if not result.data[0]:
2940
        raise errors.OpExecError("Could not rename directory '%s' to '%s'"
2941
                                 " (but the instance has been renamed in"
2942
                                 " Ganeti)" % (old_file_storage_dir,
2943
                                               new_file_storage_dir))
2944

    
2945
    _StartInstanceDisks(self, inst, None)
2946
    try:
2947
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
2948
                                                 old_name)
2949
      if result.failed or not result.data:
2950
        msg = ("Could not run OS rename script for instance %s on node %s"
2951
               " (but the instance has been renamed in Ganeti)" %
2952
               (inst.name, inst.primary_node))
2953
        self.proc.LogWarning(msg)
2954
    finally:
2955
      _ShutdownInstanceDisks(self, inst)
2956

    
2957

    
2958
class LURemoveInstance(LogicalUnit):
2959
  """Remove an instance.
2960

2961
  """
2962
  HPATH = "instance-remove"
2963
  HTYPE = constants.HTYPE_INSTANCE
2964
  _OP_REQP = ["instance_name", "ignore_failures"]
2965
  REQ_BGL = False
2966

    
2967
  def ExpandNames(self):
2968
    self._ExpandAndLockInstance()
2969
    self.needed_locks[locking.LEVEL_NODE] = []
2970
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2971

    
2972
  def DeclareLocks(self, level):
2973
    if level == locking.LEVEL_NODE:
2974
      self._LockInstancesNodes()
2975

    
2976
  def BuildHooksEnv(self):
2977
    """Build hooks env.
2978

2979
    This runs on master, primary and secondary nodes of the instance.
2980

2981
    """
2982
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2983
    nl = [self.cfg.GetMasterNode()]
2984
    return env, nl, nl
2985

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

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

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

    
2996
  def Exec(self, feedback_fn):
2997
    """Remove the instance.
2998

2999
    """
3000
    instance = self.instance
3001
    logging.info("Shutting down instance %s on node %s",
3002
                 instance.name, instance.primary_node)
3003

    
3004
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance)
3005
    if result.failed or not result.data:
3006
      if self.op.ignore_failures:
3007
        feedback_fn("Warning: can't shutdown instance")
3008
      else:
3009
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
3010
                                 (instance.name, instance.primary_node))
3011

    
3012
    logging.info("Removing block devices for instance %s", instance.name)
3013

    
3014
    if not _RemoveDisks(self, instance):
3015
      if self.op.ignore_failures:
3016
        feedback_fn("Warning: can't remove instance's disks")
3017
      else:
3018
        raise errors.OpExecError("Can't remove instance's disks")
3019

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

    
3022
    self.cfg.RemoveInstance(instance.name)
3023
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
3024

    
3025

    
3026
class LUQueryInstances(NoHooksLU):
3027
  """Logical unit for querying instances.
3028

3029
  """
3030
  _OP_REQP = ["output_fields", "names"]
3031
  REQ_BGL = False
3032
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
3033
                                    "admin_state", "admin_ram",
3034
                                    "disk_template", "ip", "mac", "bridge",
3035
                                    "sda_size", "sdb_size", "vcpus", "tags",
3036
                                    "network_port", "beparams",
3037
                                    "(disk).(size)/([0-9]+)",
3038
                                    "(disk).(sizes)",
3039
                                    "(nic).(mac|ip|bridge)/([0-9]+)",
3040
                                    "(nic).(macs|ips|bridges)",
3041
                                    "(disk|nic).(count)",
3042
                                    "serial_no", "hypervisor", "hvparams",] +
3043
                                  ["hv/%s" % name
3044
                                   for name in constants.HVS_PARAMETERS] +
3045
                                  ["be/%s" % name
3046
                                   for name in constants.BES_PARAMETERS])
3047
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
3048

    
3049

    
3050
  def ExpandNames(self):
3051
    _CheckOutputFields(static=self._FIELDS_STATIC,
3052
                       dynamic=self._FIELDS_DYNAMIC,
3053
                       selected=self.op.output_fields)
3054

    
3055
    self.needed_locks = {}
3056
    self.share_locks[locking.LEVEL_INSTANCE] = 1
3057
    self.share_locks[locking.LEVEL_NODE] = 1
3058

    
3059
    if self.op.names:
3060
      self.wanted = _GetWantedInstances(self, self.op.names)
3061
    else:
3062
      self.wanted = locking.ALL_SET
3063

    
3064
    self.do_locking = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3065
    if self.do_locking:
3066
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
3067
      self.needed_locks[locking.LEVEL_NODE] = []
3068
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3069

    
3070
  def DeclareLocks(self, level):
3071
    if level == locking.LEVEL_NODE and self.do_locking:
3072
      self._LockInstancesNodes()
3073

    
3074
  def CheckPrereq(self):
3075
    """Check prerequisites.
3076

3077
    """
3078
    pass
3079

    
3080
  def Exec(self, feedback_fn):
3081
    """Computes the list of nodes and their attributes.
3082

3083
    """
3084
    all_info = self.cfg.GetAllInstancesInfo()
3085
    if self.do_locking:
3086
      instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
3087
    elif self.wanted != locking.ALL_SET:
3088
      instance_names = self.wanted
3089
      missing = set(instance_names).difference(all_info.keys())
3090
      if missing:
3091
        raise errors.OpExecError(
3092
          "Some instances were removed before retrieving their data: %s"
3093
          % missing)
3094
    else:
3095
      instance_names = all_info.keys()
3096

    
3097
    instance_names = utils.NiceSort(instance_names)
3098
    instance_list = [all_info[iname] for iname in instance_names]
3099

    
3100
    # begin data gathering
3101

    
3102
    nodes = frozenset([inst.primary_node for inst in instance_list])
3103
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
3104

    
3105
    bad_nodes = []
3106
    off_nodes = []
3107
    if self.do_locking:
3108
      live_data = {}
3109
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
3110
      for name in nodes:
3111
        result = node_data[name]
3112
        if result.offline:
3113
          # offline nodes will be in both lists
3114
          off_nodes.append(name)
3115
        if result.failed:
3116
          bad_nodes.append(name)
3117
        else:
3118
          if result.data:
3119
            live_data.update(result.data)
3120
            # else no instance is alive
3121
    else:
3122
      live_data = dict([(name, {}) for name in instance_names])
3123

    
3124
    # end data gathering
3125

    
3126
    HVPREFIX = "hv/"
3127
    BEPREFIX = "be/"
3128
    output = []
3129
    for instance in instance_list:
3130
      iout = []
3131
      i_hv = self.cfg.GetClusterInfo().FillHV(instance)
3132
      i_be = self.cfg.GetClusterInfo().FillBE(instance)
3133
      for field in self.op.output_fields:
3134
        st_match = self._FIELDS_STATIC.Matches(field)
3135
        if field == "name":
3136
          val = instance.name
3137
        elif field == "os":
3138
          val = instance.os
3139
        elif field == "pnode":
3140
          val = instance.primary_node
3141
        elif field == "snodes":
3142
          val = list(instance.secondary_nodes)
3143
        elif field == "admin_state":
3144
          val = (instance.status != "down")
3145
        elif field == "oper_state":
3146
          if instance.primary_node in bad_nodes:
3147
            val = None
3148
          else:
3149
            val = bool(live_data.get(instance.name))
3150
        elif field == "status":
3151
          if instance.primary_node in off_nodes:
3152
            val = "ERROR_nodeoffline"
3153
          elif instance.primary_node in bad_nodes:
3154
            val = "ERROR_nodedown"
3155
          else:
3156
            running = bool(live_data.get(instance.name))
3157
            if running:
3158
              if instance.status != "down":
3159
                val = "running"
3160
              else:
3161
                val = "ERROR_up"
3162
            else:
3163
              if instance.status != "down":
3164
                val = "ERROR_down"
3165
              else:
3166
                val = "ADMIN_down"
3167
        elif field == "oper_ram":
3168
          if instance.primary_node in bad_nodes:
3169
            val = None
3170
          elif instance.name in live_data:
3171
            val = live_data[instance.name].get("memory", "?")
3172
          else:
3173
            val = "-"
3174
        elif field == "disk_template":
3175
          val = instance.disk_template
3176
        elif field == "ip":
3177
          val = instance.nics[0].ip
3178
        elif field == "bridge":
3179
          val = instance.nics[0].bridge
3180
        elif field == "mac":
3181
          val = instance.nics[0].mac
3182
        elif field == "sda_size" or field == "sdb_size":
3183
          idx = ord(field[2]) - ord('a')
3184
          try:
3185
            val = instance.FindDisk(idx).size
3186
          except errors.OpPrereqError:
3187
            val = None
3188
        elif field == "tags":
3189
          val = list(instance.GetTags())
3190
        elif field == "serial_no":
3191
          val = instance.serial_no
3192
        elif field == "network_port":
3193
          val = instance.network_port
3194
        elif field == "hypervisor":
3195
          val = instance.hypervisor
3196
        elif field == "hvparams":
3197
          val = i_hv
3198
        elif (field.startswith(HVPREFIX) and
3199
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS):
3200
          val = i_hv.get(field[len(HVPREFIX):], None)
3201
        elif field == "beparams":
3202
          val = i_be
3203
        elif (field.startswith(BEPREFIX) and
3204
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
3205
          val = i_be.get(field[len(BEPREFIX):], None)
3206
        elif st_match and st_match.groups():
3207
          # matches a variable list
3208
          st_groups = st_match.groups()
3209
          if st_groups and st_groups[0] == "disk":
3210
            if st_groups[1] == "count":
3211
              val = len(instance.disks)
3212
            elif st_groups[1] == "sizes":
3213
              val = [disk.size for disk in instance.disks]
3214
            elif st_groups[1] == "size":
3215
              try:
3216
                val = instance.FindDisk(st_groups[2]).size
3217
              except errors.OpPrereqError:
3218
                val = None
3219
            else:
3220
              assert False, "Unhandled disk parameter"
3221
          elif st_groups[0] == "nic":
3222
            if st_groups[1] == "count":
3223
              val = len(instance.nics)
3224
            elif st_groups[1] == "macs":
3225
              val = [nic.mac for nic in instance.nics]
3226
            elif st_groups[1] == "ips":
3227
              val = [nic.ip for nic in instance.nics]
3228
            elif st_groups[1] == "bridges":
3229
              val = [nic.bridge for nic in instance.nics]
3230
            else:
3231
              # index-based item
3232
              nic_idx = int(st_groups[2])
3233
              if nic_idx >= len(instance.nics):
3234
                val = None
3235
              else:
3236
                if st_groups[1] == "mac":
3237
                  val = instance.nics[nic_idx].mac
3238
                elif st_groups[1] == "ip":
3239
                  val = instance.nics[nic_idx].ip
3240
                elif st_groups[1] == "bridge":
3241
                  val = instance.nics[nic_idx].bridge
3242
                else:
3243
                  assert False, "Unhandled NIC parameter"
3244
          else:
3245
            assert False, "Unhandled variable parameter"
3246
        else:
3247
          raise errors.ParameterError(field)
3248
        iout.append(val)
3249
      output.append(iout)
3250

    
3251
    return output
3252

    
3253

    
3254
class LUFailoverInstance(LogicalUnit):
3255
  """Failover an instance.
3256

3257
  """
3258
  HPATH = "instance-failover"
3259
  HTYPE = constants.HTYPE_INSTANCE
3260
  _OP_REQP = ["instance_name", "ignore_consistency"]
3261
  REQ_BGL = False
3262

    
3263
  def ExpandNames(self):
3264
    self._ExpandAndLockInstance()
3265
    self.needed_locks[locking.LEVEL_NODE] = []
3266
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3267

    
3268
  def DeclareLocks(self, level):
3269
    if level == locking.LEVEL_NODE:
3270
      self._LockInstancesNodes()
3271

    
3272
  def BuildHooksEnv(self):
3273
    """Build hooks env.
3274

3275
    This runs on master, primary and secondary nodes of the instance.
3276

3277
    """
3278
    env = {
3279
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
3280
      }
3281
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3282
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
3283
    return env, nl, nl
3284

    
3285
  def CheckPrereq(self):
3286
    """Check prerequisites.
3287

3288
    This checks that the instance is in the cluster.
3289

3290
    """
3291
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3292
    assert self.instance is not None, \
3293
      "Cannot retrieve locked instance %s" % self.op.instance_name
3294

    
3295
    bep = self.cfg.GetClusterInfo().FillBE(instance)
3296
    if instance.disk_template not in constants.DTS_NET_MIRROR:
3297
      raise errors.OpPrereqError("Instance's disk layout is not"
3298
                                 " network mirrored, cannot failover.")
3299

    
3300
    secondary_nodes = instance.secondary_nodes
3301
    if not secondary_nodes:
3302
      raise errors.ProgrammerError("no secondary node but using "
3303
                                   "a mirrored disk template")
3304

    
3305
    target_node = secondary_nodes[0]
3306
    _CheckNodeOnline(self, target_node)
3307
    # check memory requirements on the secondary node
3308
    _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
3309
                         instance.name, bep[constants.BE_MEMORY],
3310
                         instance.hypervisor)
3311

    
3312
    # check bridge existance
3313
    brlist = [nic.bridge for nic in instance.nics]
3314
    result = self.rpc.call_bridges_exist(target_node, brlist)
3315
    result.Raise()
3316
    if not result.data:
3317
      raise errors.OpPrereqError("One or more target bridges %s does not"
3318
                                 " exist on destination node '%s'" %
3319
                                 (brlist, target_node))
3320

    
3321
  def Exec(self, feedback_fn):
3322
    """Failover an instance.
3323

3324
    The failover is done by shutting it down on its present node and
3325
    starting it on the secondary.
3326

3327
    """
3328
    instance = self.instance
3329

    
3330
    source_node = instance.primary_node
3331
    target_node = instance.secondary_nodes[0]
3332

    
3333
    feedback_fn("* checking disk consistency between source and target")
3334
    for dev in instance.disks:
3335
      # for drbd, these are drbd over lvm
3336
      if not _CheckDiskConsistency(self, dev, target_node, False):
3337
        if instance.status == "up" and not self.op.ignore_consistency:
3338
          raise errors.OpExecError("Disk %s is degraded on target node,"
3339
                                   " aborting failover." % dev.iv_name)
3340

    
3341
    feedback_fn("* shutting down instance on source node")
3342
    logging.info("Shutting down instance %s on node %s",
3343
                 instance.name, source_node)
3344

    
3345
    result = self.rpc.call_instance_shutdown(source_node, instance)
3346
    if result.failed or not result.data:
3347
      if self.op.ignore_consistency:
3348
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
3349
                             " Proceeding"
3350
                             " anyway. Please make sure node %s is down",
3351
                             instance.name, source_node, source_node)
3352
      else:
3353
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
3354
                                 (instance.name, source_node))
3355

    
3356
    feedback_fn("* deactivating the instance's disks on source node")
3357
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
3358
      raise errors.OpExecError("Can't shut down the instance's disks.")
3359

    
3360
    instance.primary_node = target_node
3361
    # distribute new instance config to the other nodes
3362
    self.cfg.Update(instance)
3363

    
3364
    # Only start the instance if it's marked as up
3365
    if instance.status == "up":
3366
      feedback_fn("* activating the instance's disks on target node")
3367
      logging.info("Starting instance %s on node %s",
3368
                   instance.name, target_node)
3369

    
3370
      disks_ok, dummy = _AssembleInstanceDisks(self, instance,
3371
                                               ignore_secondaries=True)
3372
      if not disks_ok:
3373
        _ShutdownInstanceDisks(self, instance)
3374
        raise errors.OpExecError("Can't activate the instance's disks")
3375

    
3376
      feedback_fn("* starting the instance on the target node")
3377
      result = self.rpc.call_instance_start(target_node, instance, None)
3378
      msg = result.RemoteFailMsg()
3379
      if msg:
3380
        _ShutdownInstanceDisks(self, instance)
3381
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
3382
                                 (instance.name, target_node, msg))
3383

    
3384

    
3385
class LUMigrateInstance(LogicalUnit):
3386
  """Migrate an instance.
3387

3388
  This is migration without shutting down, compared to the failover,
3389
  which is done with shutdown.
3390

3391
  """
3392
  HPATH = "instance-migrate"
3393
  HTYPE = constants.HTYPE_INSTANCE
3394
  _OP_REQP = ["instance_name", "live", "cleanup"]
3395

    
3396
  REQ_BGL = False
3397

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

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

    
3407
  def BuildHooksEnv(self):
3408
    """Build hooks env.
3409

3410
    This runs on master, primary and secondary nodes of the instance.
3411

3412
    """
3413
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3414
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
3415
    return env, nl, nl
3416

    
3417
  def CheckPrereq(self):
3418
    """Check prerequisites.
3419

3420
    This checks that the instance is in the cluster.
3421

3422
    """
3423
    instance = self.cfg.GetInstanceInfo(
3424
      self.cfg.ExpandInstanceName(self.op.instance_name))
3425
    if instance is None:
3426
      raise errors.OpPrereqError("Instance '%s' not known" %
3427
                                 self.op.instance_name)
3428

    
3429
    if instance.disk_template != constants.DT_DRBD8:
3430
      raise errors.OpPrereqError("Instance's disk layout is not"
3431
                                 " drbd8, cannot migrate.")
3432

    
3433
    secondary_nodes = instance.secondary_nodes
3434
    if not secondary_nodes:
3435
      raise errors.ProgrammerError("no secondary node but using "
3436
                                   "drbd8 disk template")
3437

    
3438
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
3439

    
3440
    target_node = secondary_nodes[0]
3441
    # check memory requirements on the secondary node
3442
    _CheckNodeFreeMemory(self, target_node, "migrating instance %s" %
3443
                         instance.name, i_be[constants.BE_MEMORY],
3444
                         instance.hypervisor)
3445

    
3446
    # check bridge existance
3447
    brlist = [nic.bridge for nic in instance.nics]
3448
    result = self.rpc.call_bridges_exist(target_node, brlist)
3449
    if result.failed or not result.data:
3450
      raise errors.OpPrereqError("One or more target bridges %s does not"
3451
                                 " exist on destination node '%s'" %
3452
                                 (brlist, target_node))
3453

    
3454
    if not self.op.cleanup:
3455
      result = self.rpc.call_instance_migratable(instance.primary_node,
3456
                                                 instance)
3457
      msg = result.RemoteFailMsg()
3458
      if msg:
3459
        raise errors.OpPrereqError("Can't migrate: %s - please use failover" %
3460
                                   msg)
3461

    
3462
    self.instance = instance
3463

    
3464
  def _WaitUntilSync(self):
3465
    """Poll with custom rpc for disk sync.
3466

3467
    This uses our own step-based rpc call.
3468

3469
    """
3470
    self.feedback_fn("* wait until resync is done")
3471
    all_done = False
3472
    while not all_done:
3473
      all_done = True
3474
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
3475
                                            self.nodes_ip,
3476
                                            self.instance.disks)
3477
      min_percent = 100
3478
      for node, nres in result.items():
3479
        msg = nres.RemoteFailMsg()
3480
        if msg:
3481
          raise errors.OpExecError("Cannot resync disks on node %s: %s" %
3482
                                   (node, msg))
3483
        node_done, node_percent = nres.data[1]
3484
        all_done = all_done and node_done
3485
        if node_percent is not None:
3486
          min_percent = min(min_percent, node_percent)
3487
      if not all_done:
3488
        if min_percent < 100:
3489
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
3490
        time.sleep(2)
3491

    
3492
  def _EnsureSecondary(self, node):
3493
    """Demote a node to secondary.
3494

3495
    """
3496
    self.feedback_fn("* switching node %s to secondary mode" % node)
3497

    
3498
    for dev in self.instance.disks:
3499
      self.cfg.SetDiskID(dev, node)
3500

    
3501
    result = self.rpc.call_blockdev_close(node, self.instance.name,
3502
                                          self.instance.disks)
3503
    msg = result.RemoteFailMsg()
3504
    if msg:
3505
      raise errors.OpExecError("Cannot change disk to secondary on node %s,"
3506
                               " error %s" % (node, msg))
3507

    
3508
  def _GoStandalone(self):
3509
    """Disconnect from the network.
3510

3511
    """
3512
    self.feedback_fn("* changing into standalone mode")
3513
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
3514
                                               self.instance.disks)
3515
    for node, nres in result.items():
3516
      msg = nres.RemoteFailMsg()
3517
      if msg:
3518
        raise errors.OpExecError("Cannot disconnect disks node %s,"
3519
                                 " error %s" % (node, msg))
3520

    
3521
  def _GoReconnect(self, multimaster):
3522
    """Reconnect to the network.
3523

3524
    """
3525
    if multimaster:
3526
      msg = "dual-master"
3527
    else:
3528
      msg = "single-master"
3529
    self.feedback_fn("* changing disks into %s mode" % msg)
3530
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
3531
                                           self.instance.disks,
3532
                                           self.instance.name, multimaster)
3533
    for node, nres in result.items():
3534
      msg = nres.RemoteFailMsg()
3535
      if msg:
3536
        raise errors.OpExecError("Cannot change disks config on node %s,"
3537
                                 " error: %s" % (node, msg))
3538

    
3539
  def _ExecCleanup(self):
3540
    """Try to cleanup after a failed migration.
3541

3542
    The cleanup is done by:
3543
      - check that the instance is running only on one node
3544
        (and update the config if needed)
3545
      - change disks on its secondary node to secondary
3546
      - wait until disks are fully synchronized
3547
      - disconnect from the network
3548
      - change disks into single-master mode
3549
      - wait again until disks are fully synchronized
3550

3551
    """
3552
    instance = self.instance
3553
    target_node = self.target_node
3554
    source_node = self.source_node
3555

    
3556
    # check running on only one node
3557
    self.feedback_fn("* checking where the instance actually runs"
3558
                     " (if this hangs, the hypervisor might be in"
3559
                     " a bad state)")
3560
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
3561
    for node, result in ins_l.items():
3562
      result.Raise()
3563
      if not isinstance(result.data, list):
3564
        raise errors.OpExecError("Can't contact node '%s'" % node)
3565

    
3566
    runningon_source = instance.name in ins_l[source_node].data
3567
    runningon_target = instance.name in ins_l[target_node].data
3568

    
3569
    if runningon_source and runningon_target:
3570
      raise errors.OpExecError("Instance seems to be running on two nodes,"
3571
                               " or the hypervisor is confused. You will have"
3572
                               " to ensure manually that it runs only on one"
3573
                               " and restart this operation.")
3574

    
3575
    if not (runningon_source or runningon_target):
3576
      raise errors.OpExecError("Instance does not seem to be running at all."
3577
                               " In this case, it's safer to repair by"
3578
                               " running 'gnt-instance stop' to ensure disk"
3579
                               " shutdown, and then restarting it.")
3580

    
3581
    if runningon_target:
3582
      # the migration has actually succeeded, we need to update the config
3583
      self.feedback_fn("* instance running on secondary node (%s),"
3584
                       " updating config" % target_node)
3585
      instance.primary_node = target_node
3586
      self.cfg.Update(instance)
3587
      demoted_node = source_node
3588
    else:
3589
      self.feedback_fn("* instance confirmed to be running on its"
3590
                       " primary node (%s)" % source_node)
3591
      demoted_node = target_node
3592

    
3593
    self._EnsureSecondary(demoted_node)
3594
    try:
3595
      self._WaitUntilSync()
3596
    except errors.OpExecError:
3597
      # we ignore here errors, since if the device is standalone, it
3598
      # won't be able to sync
3599
      pass
3600
    self._GoStandalone()
3601
    self._GoReconnect(False)
3602
    self._WaitUntilSync()
3603

    
3604
    self.feedback_fn("* done")
3605

    
3606
  def _ExecMigration(self):
3607
    """Migrate an instance.
3608

3609
    The migrate is done by:
3610
      - change the disks into dual-master mode
3611
      - wait until disks are fully synchronized again
3612
      - migrate the instance
3613
      - change disks on the new secondary node (the old primary) to secondary
3614
      - wait until disks are fully synchronized
3615
      - change disks into single-master mode
3616

3617
    """
3618
    instance = self.instance
3619
    target_node = self.target_node
3620
    source_node = self.source_node
3621

    
3622
    self.feedback_fn("* checking disk consistency between source and target")
3623
    for dev in instance.disks:
3624
      if not _CheckDiskConsistency(self, dev, target_node, False):
3625
        raise errors.OpExecError("Disk %s is degraded or not fully"
3626
                                 " synchronized on target node,"
3627
                                 " aborting migrate." % dev.iv_name)
3628

    
3629
    self._EnsureSecondary(target_node)
3630
    self._GoStandalone()
3631
    self._GoReconnect(True)
3632
    self._WaitUntilSync()
3633

    
3634
    self.feedback_fn("* migrating instance to %s" % target_node)
3635
    time.sleep(10)
3636
    result = self.rpc.call_instance_migrate(source_node, instance,
3637
                                            self.nodes_ip[target_node],
3638
                                            self.op.live)
3639
    msg = result.RemoteFailMsg()
3640
    if msg:
3641
      logging.error("Instance migration failed, trying to revert"
3642
                    " disk status: %s", msg)
3643
      try:
3644
        self._EnsureSecondary(target_node)
3645
        self._GoStandalone()
3646
        self._GoReconnect(False)
3647
        self._WaitUntilSync()
3648
      except errors.OpExecError, err:
3649
        self.LogWarning("Migration failed and I can't reconnect the"
3650
                        " drives: error '%s'\n"
3651
                        "Please look and recover the instance status" %
3652
                        str(err))
3653

    
3654
      raise errors.OpExecError("Could not migrate instance %s: %s" %
3655
                               (instance.name, msg))
3656
    time.sleep(10)
3657

    
3658
    instance.primary_node = target_node
3659
    # distribute new instance config to the other nodes
3660
    self.cfg.Update(instance)
3661

    
3662
    self._EnsureSecondary(source_node)
3663
    self._WaitUntilSync()
3664
    self._GoStandalone()
3665
    self._GoReconnect(False)
3666
    self._WaitUntilSync()
3667

    
3668
    self.feedback_fn("* done")
3669

    
3670
  def Exec(self, feedback_fn):
3671
    """Perform the migration.
3672

3673
    """
3674
    self.feedback_fn = feedback_fn
3675

    
3676
    self.source_node = self.instance.primary_node
3677
    self.target_node = self.instance.secondary_nodes[0]
3678
    self.all_nodes = [self.source_node, self.target_node]
3679
    self.nodes_ip = {
3680
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
3681
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
3682
      }
3683
    if self.op.cleanup:
3684
      return self._ExecCleanup()
3685
    else:
3686
      return self._ExecMigration()
3687

    
3688

    
3689
def _CreateBlockDev(lu, node, instance, device, force_create,
3690
                    info, force_open):
3691
  """Create a tree of block devices on a given node.
3692

3693
  If this device type has to be created on secondaries, create it and
3694
  all its children.
3695

3696
  If not, just recurse to children keeping the same 'force' value.
3697

3698
  @param lu: the lu on whose behalf we execute
3699
  @param node: the node on which to create the device
3700
  @type instance: L{objects.Instance}
3701
  @param instance: the instance which owns the device
3702
  @type device: L{objects.Disk}
3703
  @param device: the device to create
3704
  @type force_create: boolean
3705
  @param force_create: whether to force creation of this device; this
3706
      will be change to True whenever we find a device which has
3707
      CreateOnSecondary() attribute
3708
  @param info: the extra 'metadata' we should attach to the device
3709
      (this will be represented as a LVM tag)
3710
  @type force_open: boolean
3711
  @param force_open: this parameter will be passes to the
3712
      L{backend.CreateBlockDevice} function where it specifies
3713
      whether we run on primary or not, and it affects both
3714
      the child assembly and the device own Open() execution
3715

3716
  """
3717
  if device.CreateOnSecondary():
3718
    force_create = True
3719

    
3720
  if device.children:
3721
    for child in device.children:
3722
      _CreateBlockDev(lu, node, instance, child, force_create,
3723
                      info, force_open)
3724

    
3725
  if not force_create:
3726
    return
3727

    
3728
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
3729

    
3730

    
3731
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
3732
  """Create a single block device on a given node.
3733

3734
  This will not recurse over children of the device, so they must be
3735
  created in advance.
3736

3737
  @param lu: the lu on whose behalf we execute
3738
  @param node: the node on which to create the device
3739
  @type instance: L{objects.Instance}
3740
  @param instance: the instance which owns the device
3741
  @type device: L{objects.Disk}
3742
  @param device: the device to create
3743
  @param info: the extra 'metadata' we should attach to the device
3744
      (this will be represented as a LVM tag)
3745
  @type force_open: boolean
3746
  @param force_open: this parameter will be passes to the
3747
      L{backend.CreateBlockDevice} function where it specifies
3748
      whether we run on primary or not, and it affects both
3749
      the child assembly and the device own Open() execution
3750

3751
  """
3752
  lu.cfg.SetDiskID(device, node)
3753
  result = lu.rpc.call_blockdev_create(node, device, device.size,
3754
                                       instance.name, force_open, info)
3755
  msg = result.RemoteFailMsg()
3756
  if msg:
3757
    raise errors.OpExecError("Can't create block device %s on"
3758
                             " node %s for instance %s: %s" %
3759
                             (device, node, instance.name, msg))
3760
  if device.physical_id is None:
3761
    device.physical_id = result.data[1]
3762

    
3763

    
3764
def _GenerateUniqueNames(lu, exts):
3765
  """Generate a suitable LV name.
3766

3767
  This will generate a logical volume name for the given instance.
3768

3769
  """
3770
  results = []
3771
  for val in exts:
3772
    new_id = lu.cfg.GenerateUniqueID()
3773
    results.append("%s%s" % (new_id, val))
3774
  return results
3775

    
3776

    
3777
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
3778
                         p_minor, s_minor):
3779
  """Generate a drbd8 device complete with its children.
3780

3781
  """
3782
  port = lu.cfg.AllocatePort()
3783
  vgname = lu.cfg.GetVGName()
3784
  shared_secret = lu.cfg.GenerateDRBDSecret()
3785
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
3786
                          logical_id=(vgname, names[0]))
3787
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
3788
                          logical_id=(vgname, names[1]))
3789
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
3790
                          logical_id=(primary, secondary, port,
3791
                                      p_minor, s_minor,
3792
                                      shared_secret),
3793
                          children=[dev_data, dev_meta],
3794
                          iv_name=iv_name)
3795
  return drbd_dev
3796

    
3797

    
3798
def _GenerateDiskTemplate(lu, template_name,
3799
                          instance_name, primary_node,
3800
                          secondary_nodes, disk_info,
3801
                          file_storage_dir, file_driver,
3802
                          base_index):
3803
  """Generate the entire disk layout for a given template type.
3804

3805
  """
3806
  #TODO: compute space requirements
3807

    
3808
  vgname = lu.cfg.GetVGName()
3809
  disk_count = len(disk_info)
3810
  disks = []
3811
  if template_name == constants.DT_DISKLESS:
3812
    pass
3813
  elif template_name == constants.DT_PLAIN:
3814
    if len(secondary_nodes) != 0:
3815
      raise errors.ProgrammerError("Wrong template configuration")
3816

    
3817
    names = _GenerateUniqueNames(lu, [".disk%d" % i
3818
                                      for i in range(disk_count)])
3819
    for idx, disk in enumerate(disk_info):
3820
      disk_index = idx + base_index
3821
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
3822
                              logical_id=(vgname, names[idx]),
3823
                              iv_name="disk/%d" % disk_index)
3824
      disks.append(disk_dev)
3825
  elif template_name == constants.DT_DRBD8:
3826
    if len(secondary_nodes) != 1:
3827
      raise errors.ProgrammerError("Wrong template configuration")
3828
    remote_node = secondary_nodes[0]
3829
    minors = lu.cfg.AllocateDRBDMinor(
3830
      [primary_node, remote_node] * len(disk_info), instance_name)
3831

    
3832
    names = []
3833
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % i
3834
                                               for i in range(disk_count)]):
3835
      names.append(lv_prefix + "_data")
3836
      names.append(lv_prefix + "_meta")
3837
    for idx, disk in enumerate(disk_info):
3838
      disk_index = idx + base_index
3839
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
3840
                                      disk["size"], names[idx*2:idx*2+2],
3841
                                      "disk/%d" % disk_index,
3842
                                      minors[idx*2], minors[idx*2+1])
3843
      disks.append(disk_dev)
3844
  elif template_name == constants.DT_FILE:
3845
    if len(secondary_nodes) != 0:
3846
      raise errors.ProgrammerError("Wrong template configuration")
3847

    
3848
    for idx, disk in enumerate(disk_info):
3849
      disk_index = idx + base_index
3850
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
3851
                              iv_name="disk/%d" % disk_index,
3852
                              logical_id=(file_driver,
3853
                                          "%s/disk%d" % (file_storage_dir,
3854
                                                         idx)))
3855
      disks.append(disk_dev)
3856
  else:
3857
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
3858
  return disks
3859

    
3860

    
3861
def _GetInstanceInfoText(instance):
3862
  """Compute that text that should be added to the disk's metadata.
3863

3864
  """
3865
  return "originstname+%s" % instance.name
3866

    
3867

    
3868
def _CreateDisks(lu, instance):
3869
  """Create all disks for an instance.
3870

3871
  This abstracts away some work from AddInstance.
3872

3873
  @type lu: L{LogicalUnit}
3874
  @param lu: the logical unit on whose behalf we execute
3875
  @type instance: L{objects.Instance}
3876
  @param instance: the instance whose disks we should create
3877
  @rtype: boolean
3878
  @return: the success of the creation
3879

3880
  """
3881
  info = _GetInstanceInfoText(instance)
3882
  pnode = instance.primary_node
3883

    
3884
  if instance.disk_template == constants.DT_FILE:
3885
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
3886
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
3887

    
3888
    if result.failed or not result.data:
3889
      raise errors.OpExecError("Could not connect to node '%s'" % pnode)
3890

    
3891
    if not result.data[0]:
3892
      raise errors.OpExecError("Failed to create directory '%s'" %
3893
                               file_storage_dir)
3894

    
3895
  # Note: this needs to be kept in sync with adding of disks in
3896
  # LUSetInstanceParams
3897
  for device in instance.disks:
3898
    logging.info("Creating volume %s for instance %s",
3899
                 device.iv_name, instance.name)
3900
    #HARDCODE
3901
    for node in instance.all_nodes:
3902
      f_create = node == pnode
3903
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
3904

    
3905

    
3906
def _RemoveDisks(lu, instance):
3907
  """Remove all disks for an instance.
3908

3909
  This abstracts away some work from `AddInstance()` and
3910
  `RemoveInstance()`. Note that in case some of the devices couldn't
3911
  be removed, the removal will continue with the other ones (compare
3912
  with `_CreateDisks()`).
3913

3914
  @type lu: L{LogicalUnit}
3915
  @param lu: the logical unit on whose behalf we execute
3916
  @type instance: L{objects.Instance}
3917
  @param instance: the instance whose disks we should remove
3918
  @rtype: boolean
3919
  @return: the success of the removal
3920

3921
  """
3922
  logging.info("Removing block devices for instance %s", instance.name)
3923

    
3924
  result = True
3925
  for device in instance.disks:
3926
    for node, disk in device.ComputeNodeTree(instance.primary_node):
3927
      lu.cfg.SetDiskID(disk, node)
3928
      result = lu.rpc.call_blockdev_remove(node, disk)
3929
      if result.failed or not result.data:
3930
        lu.proc.LogWarning("Could not remove block device %s on node %s,"
3931
                           " continuing anyway", device.iv_name, node)
3932
        result = False
3933

    
3934
  if instance.disk_template == constants.DT_FILE:
3935
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
3936
    result = lu.rpc.call_file_storage_dir_remove(instance.primary_node,
3937
                                                 file_storage_dir)
3938
    if result.failed or not result.data:
3939
      logging.error("Could not remove directory '%s'", file_storage_dir)
3940
      result = False
3941

    
3942
  return result
3943

    
3944

    
3945
def _ComputeDiskSize(disk_template, disks):
3946
  """Compute disk size requirements in the volume group
3947

3948
  """
3949
  # Required free disk space as a function of disk and swap space
3950
  req_size_dict = {
3951
    constants.DT_DISKLESS: None,
3952
    constants.DT_PLAIN: sum(d["size"] for d in disks),
3953
    # 128 MB are added for drbd metadata for each disk
3954
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
3955
    constants.DT_FILE: None,
3956
  }
3957

    
3958
  if disk_template not in req_size_dict:
3959
    raise errors.ProgrammerError("Disk template '%s' size requirement"
3960
                                 " is unknown" %  disk_template)
3961

    
3962
  return req_size_dict[disk_template]
3963

    
3964

    
3965
def _CheckHVParams(lu, nodenames, hvname, hvparams):
3966
  """Hypervisor parameter validation.
3967

3968
  This function abstract the hypervisor parameter validation to be
3969
  used in both instance create and instance modify.
3970

3971
  @type lu: L{LogicalUnit}
3972
  @param lu: the logical unit for which we check
3973
  @type nodenames: list
3974
  @param nodenames: the list of nodes on which we should check
3975
  @type hvname: string
3976
  @param hvname: the name of the hypervisor we should use
3977
  @type hvparams: dict
3978
  @param hvparams: the parameters which we need to check
3979
  @raise errors.OpPrereqError: if the parameters are not valid
3980

3981
  """
3982
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
3983
                                                  hvname,
3984
                                                  hvparams)
3985
  for node in nodenames:
3986
    info = hvinfo[node]
3987
    info.Raise()
3988
    if not info.data or not isinstance(info.data, (tuple, list)):
3989
      raise errors.OpPrereqError("Cannot get current information"
3990
                                 " from node '%s' (%s)" % (node, info.data))
3991
    if not info.data[0]:
3992
      raise errors.OpPrereqError("Hypervisor parameter validation failed:"
3993
                                 " %s" % info.data[1])
3994

    
3995

    
3996
class LUCreateInstance(LogicalUnit):
3997
  """Create an instance.
3998

3999
  """
4000
  HPATH = "instance-add"
4001
  HTYPE = constants.HTYPE_INSTANCE
4002
  _OP_REQP = ["instance_name", "disks", "disk_template",
4003
              "mode", "start",
4004
              "wait_for_sync", "ip_check", "nics",
4005
              "hvparams", "beparams"]
4006
  REQ_BGL = False
4007

    
4008
  def _ExpandNode(self, node):
4009
    """Expands and checks one node name.
4010

4011
    """
4012
    node_full = self.cfg.ExpandNodeName(node)
4013
    if node_full is None:
4014
      raise errors.OpPrereqError("Unknown node %s" % node)
4015
    return node_full
4016

    
4017
  def ExpandNames(self):
4018
    """ExpandNames for CreateInstance.
4019

4020
    Figure out the right locks for instance creation.
4021

4022
    """
4023
    self.needed_locks = {}
4024

    
4025
    # set optional parameters to none if they don't exist
4026
    for attr in ["pnode", "snode", "iallocator", "hypervisor"]:
4027
      if not hasattr(self.op, attr):
4028
        setattr(self.op, attr, None)
4029

    
4030
    # cheap checks, mostly valid constants given
4031

    
4032
    # verify creation mode
4033
    if self.op.mode not in (constants.INSTANCE_CREATE,
4034
                            constants.INSTANCE_IMPORT):
4035
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
4036
                                 self.op.mode)
4037

    
4038
    # disk template and mirror node verification
4039
    if self.op.disk_template not in constants.DISK_TEMPLATES:
4040
      raise errors.OpPrereqError("Invalid disk template name")
4041

    
4042
    if self.op.hypervisor is None:
4043
      self.op.hypervisor = self.cfg.GetHypervisorType()
4044

    
4045
    cluster = self.cfg.GetClusterInfo()
4046
    enabled_hvs = cluster.enabled_hypervisors
4047
    if self.op.hypervisor not in enabled_hvs:
4048
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
4049
                                 " cluster (%s)" % (self.op.hypervisor,
4050
                                  ",".join(enabled_hvs)))
4051

    
4052
    # check hypervisor parameter syntax (locally)
4053

    
4054
    filled_hvp = cluster.FillDict(cluster.hvparams[self.op.hypervisor],
4055
                                  self.op.hvparams)
4056
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
4057
    hv_type.CheckParameterSyntax(filled_hvp)
4058

    
4059
    # fill and remember the beparams dict
4060
    utils.CheckBEParams(self.op.beparams)
4061
    self.be_full = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
4062
                                    self.op.beparams)
4063

    
4064
    #### instance parameters check
4065

    
4066
    # instance name verification
4067
    hostname1 = utils.HostInfo(self.op.instance_name)
4068
    self.op.instance_name = instance_name = hostname1.name
4069

    
4070
    # this is just a preventive check, but someone might still add this
4071
    # instance in the meantime, and creation will fail at lock-add time
4072
    if instance_name in self.cfg.GetInstanceList():
4073
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4074
                                 instance_name)
4075

    
4076
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
4077

    
4078
    # NIC buildup
4079
    self.nics = []
4080
    for nic in self.op.nics:
4081
      # ip validity checks
4082
      ip = nic.get("ip", None)
4083
      if ip is None or ip.lower() == "none":
4084
        nic_ip = None
4085
      elif ip.lower() == constants.VALUE_AUTO:
4086
        nic_ip = hostname1.ip
4087
      else:
4088
        if not utils.IsValidIP(ip):
4089
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
4090
                                     " like a valid IP" % ip)
4091
        nic_ip = ip
4092

    
4093
      # MAC address verification
4094
      mac = nic.get("mac", constants.VALUE_AUTO)
4095
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
4096
        if not utils.IsValidMac(mac.lower()):
4097
          raise errors.OpPrereqError("Invalid MAC address specified: %s" %
4098
                                     mac)
4099
      # bridge verification
4100
      bridge = nic.get("bridge", self.cfg.GetDefBridge())
4101
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, bridge=bridge))
4102

    
4103
    # disk checks/pre-build
4104
    self.disks = []
4105
    for disk in self.op.disks:
4106
      mode = disk.get("mode", constants.DISK_RDWR)
4107
      if mode not in constants.DISK_ACCESS_SET:
4108
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
4109
                                   mode)
4110
      size = disk.get("size", None)
4111
      if size is None:
4112
        raise errors.OpPrereqError("Missing disk size")
4113
      try:
4114
        size = int(size)
4115
      except ValueError:
4116
        raise errors.OpPrereqError("Invalid disk size '%s'" % size)
4117
      self.disks.append({"size": size, "mode": mode})
4118

    
4119
    # used in CheckPrereq for ip ping check
4120
    self.check_ip = hostname1.ip
4121

    
4122
    # file storage checks
4123
    if (self.op.file_driver and
4124
        not self.op.file_driver in constants.FILE_DRIVER):
4125
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
4126
                                 self.op.file_driver)
4127

    
4128
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
4129
      raise errors.OpPrereqError("File storage directory path not absolute")
4130

    
4131
    ### Node/iallocator related checks
4132
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
4133
      raise errors.OpPrereqError("One and only one of iallocator and primary"
4134
                                 " node must be given")
4135

    
4136
    if self.op.iallocator:
4137
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4138
    else:
4139
      self.op.pnode = self._ExpandNode(self.op.pnode)
4140
      nodelist = [self.op.pnode]
4141
      if self.op.snode is not None:
4142
        self.op.snode = self._ExpandNode(self.op.snode)
4143
        nodelist.append(self.op.snode)
4144
      self.needed_locks[locking.LEVEL_NODE] = nodelist
4145

    
4146
    # in case of import lock the source node too
4147
    if self.op.mode == constants.INSTANCE_IMPORT:
4148
      src_node = getattr(self.op, "src_node", None)
4149
      src_path = getattr(self.op, "src_path", None)
4150

    
4151
      if src_path is None:
4152
        self.op.src_path = src_path = self.op.instance_name
4153

    
4154
      if src_node is None:
4155
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4156
        self.op.src_node = None
4157
        if os.path.isabs(src_path):
4158
          raise errors.OpPrereqError("Importing an instance from an absolute"
4159
                                     " path requires a source node option.")
4160
      else:
4161
        self.op.src_node = src_node = self._ExpandNode(src_node)
4162
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4163
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
4164
        if not os.path.isabs(src_path):
4165
          self.op.src_path = src_path = \
4166
            os.path.join(constants.EXPORT_DIR, src_path)
4167

    
4168
    else: # INSTANCE_CREATE
4169
      if getattr(self.op, "os_type", None) is None:
4170
        raise errors.OpPrereqError("No guest OS specified")
4171

    
4172
  def _RunAllocator(self):
4173
    """Run the allocator based on input opcode.
4174

4175
    """
4176
    nics = [n.ToDict() for n in self.nics]
4177
    ial = IAllocator(self,
4178
                     mode=constants.IALLOCATOR_MODE_ALLOC,
4179
                     name=self.op.instance_name,
4180
                     disk_template=self.op.disk_template,
4181
                     tags=[],
4182
                     os=self.op.os_type,
4183
                     vcpus=self.be_full[constants.BE_VCPUS],
4184
                     mem_size=self.be_full[constants.BE_MEMORY],
4185
                     disks=self.disks,
4186
                     nics=nics,
4187
                     hypervisor=self.op.hypervisor,
4188
                     )
4189

    
4190
    ial.Run(self.op.iallocator)
4191

    
4192
    if not ial.success:
4193
      raise errors.OpPrereqError("Can't compute nodes using"
4194
                                 " iallocator '%s': %s" % (self.op.iallocator,
4195
                                                           ial.info))
4196
    if len(ial.nodes) != ial.required_nodes:
4197
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
4198
                                 " of nodes (%s), required %s" %
4199
                                 (self.op.iallocator, len(ial.nodes),
4200
                                  ial.required_nodes))
4201
    self.op.pnode = ial.nodes[0]
4202
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
4203
                 self.op.instance_name, self.op.iallocator,
4204
                 ", ".join(ial.nodes))
4205
    if ial.required_nodes == 2:
4206
      self.op.snode = ial.nodes[1]
4207

    
4208
  def BuildHooksEnv(self):
4209
    """Build hooks env.
4210

4211
    This runs on master, primary and secondary nodes of the instance.
4212

4213
    """
4214
    env = {
4215
      "INSTANCE_DISK_TEMPLATE": self.op.disk_template,
4216
      "INSTANCE_DISK_SIZE": ",".join(str(d["size"]) for d in self.disks),
4217
      "INSTANCE_ADD_MODE": self.op.mode,
4218
      }
4219
    if self.op.mode == constants.INSTANCE_IMPORT:
4220
      env["INSTANCE_SRC_NODE"] = self.op.src_node
4221
      env["INSTANCE_SRC_PATH"] = self.op.src_path
4222
      env["INSTANCE_SRC_IMAGES"] = self.src_images
4223

    
4224
    env.update(_BuildInstanceHookEnv(name=self.op.instance_name,
4225
      primary_node=self.op.pnode,
4226
      secondary_nodes=self.secondaries,
4227
      status=self.instance_status,
4228
      os_type=self.op.os_type,
4229
      memory=self.be_full[constants.BE_MEMORY],
4230
      vcpus=self.be_full[constants.BE_VCPUS],
4231
      nics=[(n.ip, n.bridge, n.mac) for n in self.nics],
4232
    ))
4233

    
4234
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
4235
          self.secondaries)
4236
    return env, nl, nl
4237

    
4238

    
4239
  def CheckPrereq(self):
4240
    """Check prerequisites.
4241

4242
    """
4243
    if (not self.cfg.GetVGName() and
4244
        self.op.disk_template not in constants.DTS_NOT_LVM):
4245
      raise errors.OpPrereqError("Cluster does not support lvm-based"
4246
                                 " instances")
4247

    
4248

    
4249
    if self.op.mode == constants.INSTANCE_IMPORT:
4250
      src_node = self.op.src_node
4251
      src_path = self.op.src_path
4252

    
4253
      if src_node is None:
4254
        exp_list = self.rpc.call_export_list(
4255
          self.acquired_locks[locking.LEVEL_NODE])
4256
        found = False
4257
        for node in exp_list:
4258
          if not exp_list[node].failed and src_path in exp_list[node].data:
4259
            found = True
4260
            self.op.src_node = src_node = node
4261
            self.op.src_path = src_path = os.path.join(constants.EXPORT_DIR,
4262
                                                       src_path)
4263
            break
4264
        if not found:
4265
          raise errors.OpPrereqError("No export found for relative path %s" %
4266
                                      src_path)
4267

    
4268
      _CheckNodeOnline(self, src_node)
4269
      result = self.rpc.call_export_info(src_node, src_path)
4270
      result.Raise()
4271
      if not result.data:
4272
        raise errors.OpPrereqError("No export found in dir %s" % src_path)
4273

    
4274
      export_info = result.data
4275
      if not export_info.has_section(constants.INISECT_EXP):
4276
        raise errors.ProgrammerError("Corrupted export config")
4277

    
4278
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
4279
      if (int(ei_version) != constants.EXPORT_VERSION):
4280
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
4281
                                   (ei_version, constants.EXPORT_VERSION))
4282

    
4283
      # Check that the new instance doesn't have less disks than the export
4284
      instance_disks = len(self.disks)
4285
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
4286
      if instance_disks < export_disks:
4287
        raise errors.OpPrereqError("Not enough disks to import."
4288
                                   " (instance: %d, export: %d)" %
4289
                                   (instance_disks, export_disks))
4290

    
4291
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
4292
      disk_images = []
4293
      for idx in range(export_disks):
4294
        option = 'disk%d_dump' % idx
4295
        if export_info.has_option(constants.INISECT_INS, option):
4296
          # FIXME: are the old os-es, disk sizes, etc. useful?
4297
          export_name = export_info.get(constants.INISECT_INS, option)
4298
          image = os.path.join(src_path, export_name)
4299
          disk_images.append(image)
4300
        else:
4301
          disk_images.append(False)
4302

    
4303
      self.src_images = disk_images
4304

    
4305
      old_name = export_info.get(constants.INISECT_INS, 'name')
4306
      # FIXME: int() here could throw a ValueError on broken exports
4307
      exp_nic_count = int(export_info.get(constants.INISECT_INS, 'nic_count'))
4308
      if self.op.instance_name == old_name:
4309
        for idx, nic in enumerate(self.nics):
4310
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
4311
            nic_mac_ini = 'nic%d_mac' % idx
4312
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
4313

    
4314
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
4315
    if self.op.start and not self.op.ip_check:
4316
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
4317
                                 " adding an instance in start mode")
4318

    
4319
    if self.op.ip_check:
4320
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
4321
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4322
                                   (self.check_ip, self.op.instance_name))
4323

    
4324
    #### allocator run
4325

    
4326
    if self.op.iallocator is not None:
4327
      self._RunAllocator()
4328

    
4329
    #### node related checks
4330

    
4331
    # check primary node
4332
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
4333
    assert self.pnode is not None, \
4334
      "Cannot retrieve locked node %s" % self.op.pnode
4335
    if pnode.offline:
4336
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
4337
                                 pnode.name)
4338

    
4339
    self.secondaries = []
4340

    
4341
    # mirror node verification
4342
    if self.op.disk_template in constants.DTS_NET_MIRROR:
4343
      if self.op.snode is None:
4344
        raise errors.OpPrereqError("The networked disk templates need"
4345
                                   " a mirror node")
4346
      if self.op.snode == pnode.name:
4347
        raise errors.OpPrereqError("The secondary node cannot be"
4348
                                   " the primary node.")
4349
      self.secondaries.append(self.op.snode)
4350
      _CheckNodeOnline(self, self.op.snode)
4351

    
4352
    nodenames = [pnode.name] + self.secondaries
4353

    
4354
    req_size = _ComputeDiskSize(self.op.disk_template,
4355
                                self.disks)
4356

    
4357
    # Check lv size requirements
4358
    if req_size is not None:
4359
      nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
4360
                                         self.op.hypervisor)
4361
      for node in nodenames:
4362
        info = nodeinfo[node]
4363
        info.Raise()
4364
        info = info.data
4365
        if not info:
4366
          raise errors.OpPrereqError("Cannot get current information"
4367
                                     " from node '%s'" % node)
4368
        vg_free = info.get('vg_free', None)
4369
        if not isinstance(vg_free, int):
4370
          raise errors.OpPrereqError("Can't compute free disk space on"
4371
                                     " node %s" % node)
4372
        if req_size > info['vg_free']:
4373
          raise errors.OpPrereqError("Not enough disk space on target node %s."
4374
                                     " %d MB available, %d MB required" %
4375
                                     (node, info['vg_free'], req_size))
4376

    
4377
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
4378

    
4379
    # os verification
4380
    result = self.rpc.call_os_get(pnode.name, self.op.os_type)
4381
    result.Raise()
4382
    if not isinstance(result.data, objects.OS):
4383
      raise errors.OpPrereqError("OS '%s' not in supported os list for"
4384
                                 " primary node"  % self.op.os_type)
4385

    
4386
    # bridge check on primary node
4387
    bridges = [n.bridge for n in self.nics]
4388
    result = self.rpc.call_bridges_exist(self.pnode.name, bridges)
4389
    result.Raise()
4390
    if not result.data:
4391
      raise errors.OpPrereqError("One of the target bridges '%s' does not"
4392
                                 " exist on destination node '%s'" %
4393
                                 (",".join(bridges), pnode.name))
4394

    
4395
    # memory check on primary node
4396
    if self.op.start:
4397
      _CheckNodeFreeMemory(self, self.pnode.name,
4398
                           "creating instance %s" % self.op.instance_name,
4399
                           self.be_full[constants.BE_MEMORY],
4400
                           self.op.hypervisor)
4401

    
4402
    if self.op.start:
4403
      self.instance_status = 'up'
4404
    else:
4405
      self.instance_status = 'down'
4406

    
4407
  def Exec(self, feedback_fn):
4408
    """Create and add the instance to the cluster.
4409

4410
    """
4411
    instance = self.op.instance_name
4412
    pnode_name = self.pnode.name
4413

    
4414
    for nic in self.nics:
4415
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
4416
        nic.mac = self.cfg.GenerateMAC()
4417

    
4418
    ht_kind = self.op.hypervisor
4419
    if ht_kind in constants.HTS_REQ_PORT:
4420
      network_port = self.cfg.AllocatePort()
4421
    else:
4422
      network_port = None
4423

    
4424
    ##if self.op.vnc_bind_address is None:
4425
    ##  self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
4426

    
4427
    # this is needed because os.path.join does not accept None arguments
4428
    if self.op.file_storage_dir is None:
4429
      string_file_storage_dir = ""
4430
    else:
4431
      string_file_storage_dir = self.op.file_storage_dir
4432

    
4433
    # build the full file storage dir path
4434
    file_storage_dir = os.path.normpath(os.path.join(
4435
                                        self.cfg.GetFileStorageDir(),
4436
                                        string_file_storage_dir, instance))
4437

    
4438

    
4439
    disks = _GenerateDiskTemplate(self,
4440
                                  self.op.disk_template,
4441
                                  instance, pnode_name,
4442
                                  self.secondaries,
4443
                                  self.disks,
4444
                                  file_storage_dir,
4445
                                  self.op.file_driver,
4446
                                  0)
4447

    
4448
    iobj = objects.Instance(name=instance, os=self.op.os_type,
4449
                            primary_node=pnode_name,
4450
                            nics=self.nics, disks=disks,
4451
                            disk_template=self.op.disk_template,
4452
                            status=self.instance_status,
4453
                            network_port=network_port,
4454
                            beparams=self.op.beparams,
4455
                            hvparams=self.op.hvparams,
4456
                            hypervisor=self.op.hypervisor,
4457
                            )
4458

    
4459
    feedback_fn("* creating instance disks...")
4460
    try:
4461
      _CreateDisks(self, iobj)
4462
    except errors.OpExecError:
4463
      self.LogWarning("Device creation failed, reverting...")
4464
      try:
4465
        _RemoveDisks(self, iobj)
4466
      finally:
4467
        self.cfg.ReleaseDRBDMinors(instance)
4468
        raise
4469

    
4470
    feedback_fn("adding instance %s to cluster config" % instance)
4471

    
4472
    self.cfg.AddInstance(iobj)
4473
    # Declare that we don't want to remove the instance lock anymore, as we've
4474
    # added the instance to the config
4475
    del self.remove_locks[locking.LEVEL_INSTANCE]
4476
    # Remove the temp. assignements for the instance's drbds
4477
    self.cfg.ReleaseDRBDMinors(instance)
4478
    # Unlock all the nodes
4479
    if self.op.mode == constants.INSTANCE_IMPORT:
4480
      nodes_keep = [self.op.src_node]
4481
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
4482
                       if node != self.op.src_node]
4483
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
4484
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
4485
    else:
4486
      self.context.glm.release(locking.LEVEL_NODE)
4487
      del self.acquired_locks[locking.LEVEL_NODE]
4488

    
4489
    if self.op.wait_for_sync:
4490
      disk_abort = not _WaitForSync(self, iobj)
4491
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
4492
      # make sure the disks are not degraded (still sync-ing is ok)
4493
      time.sleep(15)
4494
      feedback_fn("* checking mirrors status")
4495
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
4496
    else:
4497
      disk_abort = False
4498

    
4499
    if disk_abort:
4500
      _RemoveDisks(self, iobj)
4501
      self.cfg.RemoveInstance(iobj.name)
4502
      # Make sure the instance lock gets removed
4503
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
4504
      raise errors.OpExecError("There are some degraded disks for"
4505
                               " this instance")
4506

    
4507
    feedback_fn("creating os for instance %s on node %s" %
4508
                (instance, pnode_name))
4509

    
4510
    if iobj.disk_template != constants.DT_DISKLESS:
4511
      if self.op.mode == constants.INSTANCE_CREATE:
4512
        feedback_fn("* running the instance OS create scripts...")
4513
        result = self.rpc.call_instance_os_add(pnode_name, iobj)
4514
        msg = result.RemoteFailMsg()
4515
        if msg:
4516
          raise errors.OpExecError("Could not add os for instance %s"
4517
                                   " on node %s: %s" %
4518
                                   (instance, pnode_name, msg))
4519

    
4520
      elif self.op.mode == constants.INSTANCE_IMPORT:
4521
        feedback_fn("* running the instance OS import scripts...")
4522
        src_node = self.op.src_node
4523
        src_images = self.src_images
4524
        cluster_name = self.cfg.GetClusterName()
4525
        import_result = self.rpc.call_instance_os_import(pnode_name, iobj,
4526
                                                         src_node, src_images,
4527
                                                         cluster_name)
4528
        import_result.Raise()
4529
        for idx, result in enumerate(import_result.data):
4530
          if not result:
4531
            self.LogWarning("Could not import the image %s for instance"
4532
                            " %s, disk %d, on node %s" %
4533
                            (src_images[idx], instance, idx, pnode_name))
4534
      else:
4535
        # also checked in the prereq part
4536
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
4537
                                     % self.op.mode)
4538

    
4539
    if self.op.start:
4540
      logging.info("Starting instance %s on node %s", instance, pnode_name)
4541
      feedback_fn("* starting instance...")
4542
      result = self.rpc.call_instance_start(pnode_name, iobj, None)
4543
      msg = result.RemoteFailMsg()
4544
      if msg:
4545
        raise errors.OpExecError("Could not start instance: %s" % msg)
4546

    
4547

    
4548
class LUConnectConsole(NoHooksLU):
4549
  """Connect to an instance's console.
4550

4551
  This is somewhat special in that it returns the command line that
4552
  you need to run on the master node in order to connect to the
4553
  console.
4554

4555
  """
4556
  _OP_REQP = ["instance_name"]
4557
  REQ_BGL = False
4558

    
4559
  def ExpandNames(self):
4560
    self._ExpandAndLockInstance()
4561

    
4562
  def CheckPrereq(self):
4563
    """Check prerequisites.
4564

4565
    This checks that the instance is in the cluster.
4566

4567
    """
4568
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4569
    assert self.instance is not None, \
4570
      "Cannot retrieve locked instance %s" % self.op.instance_name
4571
    _CheckNodeOnline(self, self.instance.primary_node)
4572

    
4573
  def Exec(self, feedback_fn):
4574
    """Connect to the console of an instance
4575

4576
    """
4577
    instance = self.instance
4578
    node = instance.primary_node
4579

    
4580
    node_insts = self.rpc.call_instance_list([node],
4581
                                             [instance.hypervisor])[node]
4582
    node_insts.Raise()
4583

    
4584
    if instance.name not in node_insts.data:
4585
      raise errors.OpExecError("Instance %s is not running." % instance.name)
4586

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

    
4589
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
4590
    console_cmd = hyper.GetShellCommandForConsole(instance)
4591

    
4592
    # build ssh cmdline
4593
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
4594

    
4595

    
4596
class LUReplaceDisks(LogicalUnit):
4597
  """Replace the disks of an instance.
4598

4599
  """
4600
  HPATH = "mirrors-replace"
4601
  HTYPE = constants.HTYPE_INSTANCE
4602
  _OP_REQP = ["instance_name", "mode", "disks"]
4603
  REQ_BGL = False
4604

    
4605
  def CheckArguments(self):
4606
    if not hasattr(self.op, "remote_node"):
4607
      self.op.remote_node = None
4608
    if not hasattr(self.op, "iallocator"):
4609
      self.op.iallocator = None
4610

    
4611
    # check for valid parameter combination
4612
    cnt = [self.op.remote_node, self.op.iallocator].count(None)
4613
    if self.op.mode == constants.REPLACE_DISK_CHG:
4614
      if cnt == 2:
4615
        raise errors.OpPrereqError("When changing the secondary either an"
4616
                                   " iallocator script must be used or the"
4617
                                   " new node given")
4618
      elif cnt == 0:
4619
        raise errors.OpPrereqError("Give either the iallocator or the new"
4620
                                   " secondary, not both")
4621
    else: # not replacing the secondary
4622
      if cnt != 2:
4623
        raise errors.OpPrereqError("The iallocator and new node options can"
4624
                                   " be used only when changing the"
4625
                                   " secondary node")
4626

    
4627
  def ExpandNames(self):
4628
    self._ExpandAndLockInstance()
4629

    
4630
    if self.op.iallocator is not None:
4631
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4632
    elif self.op.remote_node is not None:
4633
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
4634
      if remote_node is None:
4635
        raise errors.OpPrereqError("Node '%s' not known" %
4636
                                   self.op.remote_node)
4637
      self.op.remote_node = remote_node
4638
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
4639
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4640
    else:
4641
      self.needed_locks[locking.LEVEL_NODE] = []
4642
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4643

    
4644
  def DeclareLocks(self, level):
4645
    # If we're not already locking all nodes in the set we have to declare the
4646
    # instance's primary/secondary nodes.
4647
    if (level == locking.LEVEL_NODE and
4648
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
4649
      self._LockInstancesNodes()
4650

    
4651
  def _RunAllocator(self):
4652
    """Compute a new secondary node using an IAllocator.
4653

4654
    """
4655
    ial = IAllocator(self,
4656
                     mode=constants.IALLOCATOR_MODE_RELOC,
4657
                     name=self.op.instance_name,
4658
                     relocate_from=[self.sec_node])
4659

    
4660
    ial.Run(self.op.iallocator)
4661

    
4662
    if not ial.success:
4663
      raise errors.OpPrereqError("Can't compute nodes using"
4664
                                 " iallocator '%s': %s" % (self.op.iallocator,
4665
                                                           ial.info))
4666
    if len(ial.nodes) != ial.required_nodes:
4667
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
4668
                                 " of nodes (%s), required %s" %
4669
                                 (len(ial.nodes), ial.required_nodes))
4670
    self.op.remote_node = ial.nodes[0]
4671
    self.LogInfo("Selected new secondary for the instance: %s",
4672
                 self.op.remote_node)
4673

    
4674
  def BuildHooksEnv(self):
4675
    """Build hooks env.
4676

4677
    This runs on the master, the primary and all the secondaries.
4678

4679
    """
4680
    env = {
4681
      "MODE": self.op.mode,
4682
      "NEW_SECONDARY": self.op.remote_node,
4683
      "OLD_SECONDARY": self.instance.secondary_nodes[0],
4684
      }
4685
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4686
    nl = [
4687
      self.cfg.GetMasterNode(),
4688
      self.instance.primary_node,
4689
      ]
4690
    if self.op.remote_node is not None:
4691
      nl.append(self.op.remote_node)
4692
    return env, nl, nl
4693

    
4694
  def CheckPrereq(self):
4695
    """Check prerequisites.
4696

4697
    This checks that the instance is in the cluster.
4698

4699
    """
4700
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4701
    assert instance is not None, \
4702
      "Cannot retrieve locked instance %s" % self.op.instance_name
4703
    self.instance = instance
4704

    
4705
    if instance.disk_template != constants.DT_DRBD8:
4706
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
4707
                                 " instances")
4708

    
4709
    if len(instance.secondary_nodes) != 1:
4710
      raise errors.OpPrereqError("The instance has a strange layout,"
4711
                                 " expected one secondary but found %d" %
4712
                                 len(instance.secondary_nodes))
4713

    
4714
    self.sec_node = instance.secondary_nodes[0]
4715

    
4716
    if self.op.iallocator is not None:
4717
      self._RunAllocator()
4718

    
4719
    remote_node = self.op.remote_node
4720
    if remote_node is not None:
4721
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
4722
      assert self.remote_node_info is not None, \
4723
        "Cannot retrieve locked node %s" % remote_node
4724
    else:
4725
      self.remote_node_info = None
4726
    if remote_node == instance.primary_node:
4727
      raise errors.OpPrereqError("The specified node is the primary node of"
4728
                                 " the instance.")
4729
    elif remote_node == self.sec_node:
4730
      raise errors.OpPrereqError("The specified node is already the"
4731
                                 " secondary node of the instance.")
4732

    
4733
    if self.op.mode == constants.REPLACE_DISK_PRI:
4734
      n1 = self.tgt_node = instance.primary_node
4735
      n2 = self.oth_node = self.sec_node
4736
    elif self.op.mode == constants.REPLACE_DISK_SEC:
4737
      n1 = self.tgt_node = self.sec_node
4738
      n2 = self.oth_node = instance.primary_node
4739
    elif self.op.mode == constants.REPLACE_DISK_CHG:
4740
      n1 = self.new_node = remote_node
4741
      n2 = self.oth_node = instance.primary_node
4742
      self.tgt_node = self.sec_node
4743
    else:
4744
      raise errors.ProgrammerError("Unhandled disk replace mode")
4745

    
4746
    _CheckNodeOnline(self, n1)
4747
    _CheckNodeOnline(self, n2)
4748

    
4749
    if not self.op.disks:
4750
      self.op.disks = range(len(instance.disks))
4751

    
4752
    for disk_idx in self.op.disks:
4753
      instance.FindDisk(disk_idx)
4754

    
4755
  def _ExecD8DiskOnly(self, feedback_fn):
4756
    """Replace a disk on the primary or secondary for dbrd8.
4757

4758
    The algorithm for replace is quite complicated:
4759

4760
      1. for each disk to be replaced:
4761

4762
        1. create new LVs on the target node with unique names
4763
        1. detach old LVs from the drbd device
4764
        1. rename old LVs to name_replaced.<time_t>
4765
        1. rename new LVs to old LVs
4766
        1. attach the new LVs (with the old names now) to the drbd device
4767

4768
      1. wait for sync across all devices
4769

4770
      1. for each modified disk:
4771

4772
        1. remove old LVs (which have the name name_replaces.<time_t>)
4773

4774
    Failures are not very well handled.
4775

4776
    """
4777
    steps_total = 6
4778
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
4779
    instance = self.instance
4780
    iv_names = {}
4781
    vgname = self.cfg.GetVGName()
4782
    # start of work
4783
    cfg = self.cfg
4784
    tgt_node = self.tgt_node
4785
    oth_node = self.oth_node
4786

    
4787
    # Step: check device activation
4788
    self.proc.LogStep(1, steps_total, "check device existence")
4789
    info("checking volume groups")
4790
    my_vg = cfg.GetVGName()
4791
    results = self.rpc.call_vg_list([oth_node, tgt_node])
4792
    if not results:
4793
      raise errors.OpExecError("Can't list volume groups on the nodes")
4794
    for node in oth_node, tgt_node:
4795
      res = results[node]
4796
      if res.failed or not res.data or my_vg not in res.data:
4797
        raise errors.OpExecError("Volume group '%s' not found on %s" %
4798
                                 (my_vg, node))
4799
    for idx, dev in enumerate(instance.disks):
4800
      if idx not in self.op.disks:
4801
        continue
4802
      for node in tgt_node, oth_node:
4803
        info("checking disk/%d on %s" % (idx, node))
4804
        cfg.SetDiskID(dev, node)
4805
        if not self.rpc.call_blockdev_find(node, dev):
4806
          raise errors.OpExecError("Can't find disk/%d on node %s" %
4807
                                   (idx, node))
4808

    
4809
    # Step: check other node consistency
4810
    self.proc.LogStep(2, steps_total, "check peer consistency")
4811
    for idx, dev in enumerate(instance.disks):
4812
      if idx not in self.op.disks:
4813
        continue
4814
      info("checking disk/%d consistency on %s" % (idx, oth_node))
4815
      if not _CheckDiskConsistency(self, dev, oth_node,
4816
                                   oth_node==instance.primary_node):
4817
        raise errors.OpExecError("Peer node (%s) has degraded storage, unsafe"
4818
                                 " to replace disks on this node (%s)" %
4819
                                 (oth_node, tgt_node))
4820

    
4821
    # Step: create new storage
4822
    self.proc.LogStep(3, steps_total, "allocate new storage")
4823
    for idx, dev in enumerate(instance.disks):
4824
      if idx not in self.op.disks:
4825
        continue
4826
      size = dev.size
4827
      cfg.SetDiskID(dev, tgt_node)
4828
      lv_names = [".disk%d_%s" % (idx, suf)
4829
                  for suf in ["data", "meta"]]
4830
      names = _GenerateUniqueNames(self, lv_names)
4831
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=size,
4832
                             logical_id=(vgname, names[0]))
4833
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
4834
                             logical_id=(vgname, names[1]))
4835
      new_lvs = [lv_data, lv_meta]
4836
      old_lvs = dev.children
4837
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
4838
      info("creating new local storage on %s for %s" %
4839
           (tgt_node, dev.iv_name))
4840
      # we pass force_create=True to force the LVM creation
4841
      for new_lv in new_lvs:
4842
        _CreateBlockDev(self, tgt_node, instance, new_lv, True,
4843
                        _GetInstanceInfoText(instance), False)
4844

    
4845
    # Step: for each lv, detach+rename*2+attach
4846
    self.proc.LogStep(4, steps_total, "change drbd configuration")
4847
    for dev, old_lvs, new_lvs in iv_names.itervalues():
4848
      info("detaching %s drbd from local storage" % dev.iv_name)
4849
      result = self.rpc.call_blockdev_removechildren(tgt_node, dev, old_lvs)
4850
      result.Raise()
4851
      if not result.data:
4852
        raise errors.OpExecError("Can't detach drbd from local storage on node"
4853
                                 " %s for device %s" % (tgt_node, dev.iv_name))
4854
      #dev.children = []
4855
      #cfg.Update(instance)
4856

    
4857
      # ok, we created the new LVs, so now we know we have the needed
4858
      # storage; as such, we proceed on the target node to rename
4859
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
4860
      # using the assumption that logical_id == physical_id (which in
4861
      # turn is the unique_id on that node)
4862

    
4863
      # FIXME(iustin): use a better name for the replaced LVs
4864
      temp_suffix = int(time.time())
4865
      ren_fn = lambda d, suff: (d.physical_id[0],
4866
                                d.physical_id[1] + "_replaced-%s" % suff)
4867
      # build the rename list based on what LVs exist on the node
4868
      rlist = []
4869
      for to_ren in old_lvs:
4870
        find_res = self.rpc.call_blockdev_find(tgt_node, to_ren)
4871
        if not find_res.failed and find_res.data is not None: # device exists
4872
          rlist.append((to_ren, ren_fn(to_ren, temp_suffix)))
4873

    
4874
      info("renaming the old LVs on the target node")
4875
      result = self.rpc.call_blockdev_rename(tgt_node, rlist)
4876
      result.Raise()
4877
      if not result.data:
4878
        raise errors.OpExecError("Can't rename old LVs on node %s" % tgt_node)
4879
      # now we rename the new LVs to the old LVs
4880
      info("renaming the new LVs on the target node")
4881
      rlist = [(new, old.physical_id) for old, new in zip(old_lvs, new_lvs)]
4882
      result = self.rpc.call_blockdev_rename(tgt_node, rlist)
4883
      result.Raise()
4884
      if not result.data:
4885
        raise errors.OpExecError("Can't rename new LVs on node %s" % tgt_node)
4886

    
4887
      for old, new in zip(old_lvs, new_lvs):
4888
        new.logical_id = old.logical_id
4889
        cfg.SetDiskID(new, tgt_node)
4890

    
4891
      for disk in old_lvs:
4892
        disk.logical_id = ren_fn(disk, temp_suffix)
4893
        cfg.SetDiskID(disk, tgt_node)
4894

    
4895
      # now that the new lvs have the old name, we can add them to the device
4896
      info("adding new mirror component on %s" % tgt_node)
4897
      result = self.rpc.call_blockdev_addchildren(tgt_node, dev, new_lvs)
4898
      if result.failed or not result.data:
4899
        for new_lv in new_lvs:
4900
          result = self.rpc.call_blockdev_remove(tgt_node, new_lv)
4901
          if result.failed or not result.data:
4902
            warning("Can't rollback device %s", hint="manually cleanup unused"
4903
                    " logical volumes")
4904
        raise errors.OpExecError("Can't add local storage to drbd")
4905

    
4906
      dev.children = new_lvs
4907
      cfg.Update(instance)
4908

    
4909
    # Step: wait for sync
4910

    
4911
    # this can fail as the old devices are degraded and _WaitForSync
4912
    # does a combined result over all disks, so we don't check its
4913
    # return value
4914
    self.proc.LogStep(5, steps_total, "sync devices")
4915
    _WaitForSync(self, instance, unlock=True)
4916

    
4917
    # so check manually all the devices
4918
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
4919
      cfg.SetDiskID(dev, instance.primary_node)
4920
      result = self.rpc.call_blockdev_find(instance.primary_node, dev)
4921
      if result.failed or result.data[5]:
4922
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
4923

    
4924
    # Step: remove old storage
4925
    self.proc.LogStep(6, steps_total, "removing old storage")
4926
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
4927
      info("remove logical volumes for %s" % name)
4928
      for lv in old_lvs:
4929
        cfg.SetDiskID(lv, tgt_node)
4930
        result = self.rpc.call_blockdev_remove(tgt_node, lv)
4931
        if result.failed or not result.data:
4932
          warning("Can't remove old LV", hint="manually remove unused LVs")
4933
          continue
4934

    
4935
  def _ExecD8Secondary(self, feedback_fn):
4936
    """Replace the secondary node for drbd8.
4937

4938
    The algorithm for replace is quite complicated:
4939
      - for all disks of the instance:
4940
        - create new LVs on the new node with same names
4941
        - shutdown the drbd device on the old secondary
4942
        - disconnect the drbd network on the primary
4943
        - create the drbd device on the new secondary
4944
        - network attach the drbd on the primary, using an artifice:
4945
          the drbd code for Attach() will connect to the network if it
4946
          finds a device which is connected to the good local disks but
4947
          not network enabled
4948
      - wait for sync across all devices
4949
      - remove all disks from the old secondary
4950

4951
    Failures are not very well handled.
4952

4953
    """
4954
    steps_total = 6
4955
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
4956
    instance = self.instance
4957
    iv_names = {}
4958
    # start of work
4959
    cfg = self.cfg
4960
    old_node = self.tgt_node
4961
    new_node = self.new_node
4962
    pri_node = instance.primary_node
4963
    nodes_ip = {
4964
      old_node: self.cfg.GetNodeInfo(old_node).secondary_ip,
4965
      new_node: self.cfg.GetNodeInfo(new_node).secondary_ip,
4966
      pri_node: self.cfg.GetNodeInfo(pri_node).secondary_ip,
4967
      }
4968

    
4969
    # Step: check device activation
4970
    self.proc.LogStep(1, steps_total, "check device existence")
4971
    info("checking volume groups")
4972
    my_vg = cfg.GetVGName()
4973
    results = self.rpc.call_vg_list([pri_node, new_node])
4974
    for node in pri_node, new_node:
4975
      res = results[node]
4976
      if res.failed or not res.data or my_vg not in res.data:
4977
        raise errors.OpExecError("Volume group '%s' not found on %s" %
4978
                                 (my_vg, node))
4979
    for idx, dev in enumerate(instance.disks):
4980
      if idx not in self.op.disks:
4981
        continue
4982
      info("checking disk/%d on %s" % (idx, pri_node))
4983
      cfg.SetDiskID(dev, pri_node)
4984
      result = self.rpc.call_blockdev_find(pri_node, dev)
4985
      result.Raise()
4986
      if not result.data:
4987
        raise errors.OpExecError("Can't find disk/%d on node %s" %
4988
                                 (idx, pri_node))
4989

    
4990
    # Step: check other node consistency
4991
    self.proc.LogStep(2, steps_total, "check peer consistency")
4992
    for idx, dev in enumerate(instance.disks):
4993
      if idx not in self.op.disks:
4994
        continue
4995
      info("checking disk/%d consistency on %s" % (idx, pri_node))
4996
      if not _CheckDiskConsistency(self, dev, pri_node, True, ldisk=True):
4997
        raise errors.OpExecError("Primary node (%s) has degraded storage,"
4998
                                 " unsafe to replace the secondary" %
4999
                                 pri_node)
5000

    
5001
    # Step: create new storage
5002
    self.proc.LogStep(3, steps_total, "allocate new storage")
5003
    for idx, dev in enumerate(instance.disks):
5004
      info("adding new local storage on %s for disk/%d" %
5005
           (new_node, idx))
5006
      # we pass force_create=True to force LVM creation
5007
      for new_lv in dev.children:
5008
        _CreateBlockDev(self, new_node, instance, new_lv, True,
5009
                        _GetInstanceInfoText(instance), False)
5010

    
5011
    # Step 4: dbrd minors and drbd setups changes
5012
    # after this, we must manually remove the drbd minors on both the
5013
    # error and the success paths
5014
    minors = cfg.AllocateDRBDMinor([new_node for dev in instance.disks],
5015
                                   instance.name)
5016
    logging.debug("Allocated minors %s" % (minors,))
5017
    self.proc.LogStep(4, steps_total, "changing drbd configuration")
5018
    for idx, (dev, new_minor) in enumerate(zip(instance.disks, minors)):
5019
      size = dev.size
5020
      info("activating a new drbd on %s for disk/%d" % (new_node, idx))
5021
      # create new devices on new_node; note that we create two IDs:
5022
      # one without port, so the drbd will be activated without
5023
      # networking information on the new node at this stage, and one
5024
      # with network, for the latter activation in step 4
5025
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
5026
      if pri_node == o_node1:
5027
        p_minor = o_minor1
5028
      else:
5029
        p_minor = o_minor2
5030

    
5031
      new_alone_id = (pri_node, new_node, None, p_minor, new_minor, o_secret)
5032
      new_net_id = (pri_node, new_node, o_port, p_minor, new_minor, o_secret)
5033

    
5034
      iv_names[idx] = (dev, dev.children, new_net_id)
5035
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
5036
                    new_net_id)
5037
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
5038
                              logical_id=new_alone_id,
5039
                              children=dev.children)
5040
      try:
5041
        _CreateSingleBlockDev(self, new_node, instance, new_drbd,
5042
                              _GetInstanceInfoText(instance), False)
5043
      except errors.BlockDeviceError:
5044
        self.cfg.ReleaseDRBDMinors(instance.name)
5045
        raise
5046

    
5047
    for idx, dev in enumerate(instance.disks):
5048
      # we have new devices, shutdown the drbd on the old secondary
5049
      info("shutting down drbd for disk/%d on old node" % idx)
5050
      cfg.SetDiskID(dev, old_node)
5051
      result = self.rpc.call_blockdev_shutdown(old_node, dev)
5052
      if result.failed or not result.data:
5053
        warning("Failed to shutdown drbd for disk/%d on old node" % idx,
5054
                hint="Please cleanup this device manually as soon as possible")
5055

    
5056
    info("detaching primary drbds from the network (=> standalone)")
5057
    result = self.rpc.call_drbd_disconnect_net([pri_node], nodes_ip,
5058
                                               instance.disks)[pri_node]
5059

    
5060
    msg = result.RemoteFailMsg()
5061
    if msg:
5062
      # detaches didn't succeed (unlikely)
5063
      self.cfg.ReleaseDRBDMinors(instance.name)
5064
      raise errors.OpExecError("Can't detach the disks from the network on"
5065
                               " old node: %s" % (msg,))
5066

    
5067
    # if we managed to detach at least one, we update all the disks of
5068
    # the instance to point to the new secondary
5069
    info("updating instance configuration")
5070
    for dev, _, new_logical_id in iv_names.itervalues():
5071
      dev.logical_id = new_logical_id
5072
      cfg.SetDiskID(dev, pri_node)
5073
    cfg.Update(instance)
5074
    # we can remove now the temp minors as now the new values are
5075
    # written to the config file (and therefore stable)
5076
    self.cfg.ReleaseDRBDMinors(instance.name)
5077

    
5078
    # and now perform the drbd attach
5079
    info("attaching primary drbds to new secondary (standalone => connected)")
5080
    result = self.rpc.call_drbd_attach_net([pri_node, new_node], nodes_ip,
5081
                                           instance.disks, instance.name,
5082
                                           False)
5083
    for to_node, to_result in result.items():
5084
      msg = to_result.RemoteFailMsg()
5085
      if msg:
5086
        warning("can't attach drbd disks on node %s: %s", to_node, msg,
5087
                hint="please do a gnt-instance info to see the"
5088
                " status of disks")
5089

    
5090
    # this can fail as the old devices are degraded and _WaitForSync
5091
    # does a combined result over all disks, so we don't check its
5092
    # return value
5093
    self.proc.LogStep(5, steps_total, "sync devices")
5094
    _WaitForSync(self, instance, unlock=True)
5095

    
5096
    # so check manually all the devices
5097
    for idx, (dev, old_lvs, _) in iv_names.iteritems():
5098
      cfg.SetDiskID(dev, pri_node)
5099
      result = self.rpc.call_blockdev_find(pri_node, dev)
5100
      result.Raise()
5101
      if result.data[5]:
5102
        raise errors.OpExecError("DRBD device disk/%d is degraded!" % idx)
5103

    
5104
    self.proc.LogStep(6, steps_total, "removing old storage")
5105
    for idx, (dev, old_lvs, _) in iv_names.iteritems():
5106
      info("remove logical volumes for disk/%d" % idx)
5107
      for lv in old_lvs:
5108
        cfg.SetDiskID(lv, old_node)
5109
        result = self.rpc.call_blockdev_remove(old_node, lv)
5110
        if result.failed or not result.data:
5111
          warning("Can't remove LV on old secondary",
5112
                  hint="Cleanup stale volumes by hand")
5113

    
5114
  def Exec(self, feedback_fn):
5115
    """Execute disk replacement.
5116

5117
    This dispatches the disk replacement to the appropriate handler.
5118

5119
    """
5120
    instance = self.instance
5121

    
5122
    # Activate the instance disks if we're replacing them on a down instance
5123
    if instance.status == "down":
5124
      _StartInstanceDisks(self, instance, True)
5125

    
5126
    if self.op.mode == constants.REPLACE_DISK_CHG:
5127
      fn = self._ExecD8Secondary
5128
    else:
5129
      fn = self._ExecD8DiskOnly
5130

    
5131
    ret = fn(feedback_fn)
5132

    
5133
    # Deactivate the instance disks if we're replacing them on a down instance
5134
    if instance.status == "down":
5135
      _SafeShutdownInstanceDisks(self, instance)
5136

    
5137
    return ret
5138

    
5139

    
5140
class LUGrowDisk(LogicalUnit):
5141
  """Grow a disk of an instance.
5142

5143
  """
5144
  HPATH = "disk-grow"
5145
  HTYPE = constants.HTYPE_INSTANCE
5146
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
5147
  REQ_BGL = False
5148

    
5149
  def ExpandNames(self):
5150
    self._ExpandAndLockInstance()
5151
    self.needed_locks[locking.LEVEL_NODE] = []
5152
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5153

    
5154
  def DeclareLocks(self, level):
5155
    if level == locking.LEVEL_NODE:
5156
      self._LockInstancesNodes()
5157

    
5158
  def BuildHooksEnv(self):
5159
    """Build hooks env.
5160

5161
    This runs on the master, the primary and all the secondaries.
5162

5163
    """
5164
    env = {
5165
      "DISK": self.op.disk,
5166
      "AMOUNT": self.op.amount,
5167
      }
5168
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5169
    nl = [
5170
      self.cfg.GetMasterNode(),
5171
      self.instance.primary_node,
5172
      ]
5173
    return env, nl, nl
5174

    
5175
  def CheckPrereq(self):
5176
    """Check prerequisites.
5177

5178
    This checks that the instance is in the cluster.
5179

5180
    """
5181
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5182
    assert instance is not None, \
5183
      "Cannot retrieve locked instance %s" % self.op.instance_name
5184
    nodenames = list(instance.all_nodes)
5185
    for node in nodenames:
5186
      _CheckNodeOnline(self, node)
5187

    
5188

    
5189
    self.instance = instance
5190

    
5191
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
5192
      raise errors.OpPrereqError("Instance's disk layout does not support"
5193
                                 " growing.")
5194

    
5195
    self.disk = instance.FindDisk(self.op.disk)
5196

    
5197
    nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
5198
                                       instance.hypervisor)
5199
    for node in nodenames:
5200
      info = nodeinfo[node]
5201
      if info.failed or not info.data:
5202
        raise errors.OpPrereqError("Cannot get current information"
5203
                                   " from node '%s'" % node)
5204
      vg_free = info.data.get('vg_free', None)
5205
      if not isinstance(vg_free, int):
5206
        raise errors.OpPrereqError("Can't compute free disk space on"
5207
                                   " node %s" % node)
5208
      if self.op.amount > vg_free:
5209
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
5210
                                   " %d MiB available, %d MiB required" %
5211
                                   (node, vg_free, self.op.amount))
5212

    
5213
  def Exec(self, feedback_fn):
5214
    """Execute disk grow.
5215

5216
    """
5217
    instance = self.instance
5218
    disk = self.disk
5219
    for node in instance.all_nodes:
5220
      self.cfg.SetDiskID(disk, node)
5221
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
5222
      result.Raise()
5223
      if (not result.data or not isinstance(result.data, (list, tuple)) or
5224
          len(result.data) != 2):
5225
        raise errors.OpExecError("Grow request failed to node %s" % node)
5226
      elif not result.data[0]:
5227
        raise errors.OpExecError("Grow request failed to node %s: %s" %
5228
                                 (node, result.data[1]))
5229
    disk.RecordGrow(self.op.amount)
5230
    self.cfg.Update(instance)
5231
    if self.op.wait_for_sync:
5232
      disk_abort = not _WaitForSync(self, instance)
5233
      if disk_abort:
5234
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
5235
                             " status.\nPlease check the instance.")
5236

    
5237

    
5238
class LUQueryInstanceData(NoHooksLU):
5239
  """Query runtime instance data.
5240

5241
  """
5242
  _OP_REQP = ["instances", "static"]
5243
  REQ_BGL = False
5244

    
5245
  def ExpandNames(self):
5246
    self.needed_locks = {}
5247
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
5248

    
5249
    if not isinstance(self.op.instances, list):
5250
      raise errors.OpPrereqError("Invalid argument type 'instances'")
5251

    
5252
    if self.op.instances:
5253
      self.wanted_names = []
5254
      for name in self.op.instances:
5255
        full_name = self.cfg.ExpandInstanceName(name)
5256
        if full_name is None:
5257
          raise errors.OpPrereqError("Instance '%s' not known" % name)
5258
        self.wanted_names.append(full_name)
5259
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
5260
    else:
5261
      self.wanted_names = None
5262
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
5263

    
5264
    self.needed_locks[locking.LEVEL_NODE] = []
5265
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5266

    
5267
  def DeclareLocks(self, level):
5268
    if level == locking.LEVEL_NODE:
5269
      self._LockInstancesNodes()
5270

    
5271
  def CheckPrereq(self):
5272
    """Check prerequisites.
5273

5274
    This only checks the optional instance list against the existing names.
5275

5276
    """
5277
    if self.wanted_names is None:
5278
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5279

    
5280
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
5281
                             in self.wanted_names]
5282
    return
5283

    
5284
  def _ComputeDiskStatus(self, instance, snode, dev):
5285
    """Compute block device status.
5286

5287
    """
5288
    static = self.op.static
5289
    if not static:
5290
      self.cfg.SetDiskID(dev, instance.primary_node)
5291
      dev_pstatus = self.rpc.call_blockdev_find(instance.primary_node, dev)
5292
      dev_pstatus.Raise()
5293
      dev_pstatus = dev_pstatus.data
5294
    else:
5295
      dev_pstatus = None
5296

    
5297
    if dev.dev_type in constants.LDS_DRBD:
5298
      # we change the snode then (otherwise we use the one passed in)
5299
      if dev.logical_id[0] == instance.primary_node:
5300
        snode = dev.logical_id[1]
5301
      else:
5302
        snode = dev.logical_id[0]
5303

    
5304
    if snode and not static:
5305
      self.cfg.SetDiskID(dev, snode)
5306
      dev_sstatus = self.rpc.call_blockdev_find(snode, dev)
5307
      dev_sstatus.Raise()
5308
      dev_sstatus = dev_sstatus.data
5309
    else:
5310
      dev_sstatus = None
5311

    
5312
    if dev.children:
5313
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
5314
                      for child in dev.children]
5315
    else:
5316
      dev_children = []
5317

    
5318
    data = {
5319
      "iv_name": dev.iv_name,
5320
      "dev_type": dev.dev_type,
5321
      "logical_id": dev.logical_id,
5322
      "physical_id": dev.physical_id,
5323
      "pstatus": dev_pstatus,
5324
      "sstatus": dev_sstatus,
5325
      "children": dev_children,
5326
      "mode": dev.mode,
5327
      }
5328

    
5329
    return data
5330

    
5331
  def Exec(self, feedback_fn):
5332
    """Gather and return data"""
5333
    result = {}
5334

    
5335
    cluster = self.cfg.GetClusterInfo()
5336

    
5337
    for instance in self.wanted_instances:
5338
      if not self.op.static:
5339
        remote_info = self.rpc.call_instance_info(instance.primary_node,
5340
                                                  instance.name,
5341
                                                  instance.hypervisor)
5342
        remote_info.Raise()
5343
        remote_info = remote_info.data
5344
        if remote_info and "state" in remote_info:
5345
          remote_state = "up"
5346
        else:
5347
          remote_state = "down"
5348
      else:
5349
        remote_state = None
5350
      if instance.status == "down":
5351
        config_state = "down"
5352
      else:
5353
        config_state = "up"
5354

    
5355
      disks = [self._ComputeDiskStatus(instance, None, device)
5356
               for device in instance.disks]
5357

    
5358
      idict = {
5359
        "name": instance.name,
5360
        "config_state": config_state,
5361
        "run_state": remote_state,
5362
        "pnode": instance.primary_node,
5363
        "snodes": instance.secondary_nodes,
5364
        "os": instance.os,
5365
        "nics": [(nic.mac, nic.ip, nic.bridge) for nic in instance.nics],
5366
        "disks": disks,
5367
        "hypervisor": instance.hypervisor,
5368
        "network_port": instance.network_port,
5369
        "hv_instance": instance.hvparams,
5370
        "hv_actual": cluster.FillHV(instance),
5371
        "be_instance": instance.beparams,
5372
        "be_actual": cluster.FillBE(instance),
5373
        }
5374

    
5375
      result[instance.name] = idict
5376

    
5377
    return result
5378

    
5379

    
5380
class LUSetInstanceParams(LogicalUnit):
5381
  """Modifies an instances's parameters.
5382

5383
  """
5384
  HPATH = "instance-modify"
5385
  HTYPE = constants.HTYPE_INSTANCE
5386
  _OP_REQP = ["instance_name"]
5387
  REQ_BGL = False
5388

    
5389
  def CheckArguments(self):
5390
    if not hasattr(self.op, 'nics'):
5391
      self.op.nics = []
5392
    if not hasattr(self.op, 'disks'):
5393
      self.op.disks = []
5394
    if not hasattr(self.op, 'beparams'):
5395
      self.op.beparams = {}
5396
    if not hasattr(self.op, 'hvparams'):
5397
      self.op.hvparams = {}
5398
    self.op.force = getattr(self.op, "force", False)
5399
    if not (self.op.nics or self.op.disks or
5400
            self.op.hvparams or self.op.beparams):
5401
      raise errors.OpPrereqError("No changes submitted")
5402

    
5403
    utils.CheckBEParams(self.op.beparams)
5404

    
5405
    # Disk validation
5406
    disk_addremove = 0
5407
    for disk_op, disk_dict in self.op.disks:
5408
      if disk_op == constants.DDM_REMOVE:
5409
        disk_addremove += 1
5410
        continue
5411
      elif disk_op == constants.DDM_ADD:
5412
        disk_addremove += 1
5413
      else:
5414
        if not isinstance(disk_op, int):
5415
          raise errors.OpPrereqError("Invalid disk index")
5416
      if disk_op == constants.DDM_ADD:
5417
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
5418
        if mode not in (constants.DISK_RDONLY, constants.DISK_RDWR):
5419
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode)
5420
        size = disk_dict.get('size', None)
5421
        if size is None:
5422
          raise errors.OpPrereqError("Required disk parameter size missing")
5423
        try:
5424
          size = int(size)
5425
        except ValueError, err:
5426
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
5427
                                     str(err))
5428
        disk_dict['size'] = size
5429
      else:
5430
        # modification of disk
5431
        if 'size' in disk_dict:
5432
          raise errors.OpPrereqError("Disk size change not possible, use"
5433
                                     " grow-disk")
5434

    
5435
    if disk_addremove > 1:
5436
      raise errors.OpPrereqError("Only one disk add or remove operation"
5437
                                 " supported at a time")
5438

    
5439
    # NIC validation
5440
    nic_addremove = 0
5441
    for nic_op, nic_dict in self.op.nics:
5442
      if nic_op == constants.DDM_REMOVE:
5443
        nic_addremove += 1
5444
        continue
5445
      elif nic_op == constants.DDM_ADD:
5446
        nic_addremove += 1
5447
      else:
5448
        if not isinstance(nic_op, int):
5449
          raise errors.OpPrereqError("Invalid nic index")
5450

    
5451
      # nic_dict should be a dict
5452
      nic_ip = nic_dict.get('ip', None)
5453
      if nic_ip is not None:
5454
        if nic_ip.lower() == "none":
5455
          nic_dict['ip'] = None
5456
        else:
5457
          if not utils.IsValidIP(nic_ip):
5458
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip)
5459
      # we can only check None bridges and assign the default one
5460
      nic_bridge = nic_dict.get('bridge', None)
5461
      if nic_bridge is None:
5462
        nic_dict['bridge'] = self.cfg.GetDefBridge()
5463
      # but we can validate MACs
5464
      nic_mac = nic_dict.get('mac', None)
5465
      if nic_mac is not None:
5466
        if self.cfg.IsMacInUse(nic_mac):
5467
          raise errors.OpPrereqError("MAC address %s already in use"
5468
                                     " in cluster" % nic_mac)
5469
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5470
          if not utils.IsValidMac(nic_mac):
5471
            raise errors.OpPrereqError("Invalid MAC address %s" % nic_mac)
5472
    if nic_addremove > 1:
5473
      raise errors.OpPrereqError("Only one NIC add or remove operation"
5474
                                 " supported at a time")
5475

    
5476
  def ExpandNames(self):
5477
    self._ExpandAndLockInstance()
5478
    self.needed_locks[locking.LEVEL_NODE] = []
5479
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5480

    
5481
  def DeclareLocks(self, level):
5482
    if level == locking.LEVEL_NODE:
5483
      self._LockInstancesNodes()
5484

    
5485
  def BuildHooksEnv(self):
5486
    """Build hooks env.
5487

5488
    This runs on the master, primary and secondaries.
5489

5490
    """
5491
    args = dict()
5492
    if constants.BE_MEMORY in self.be_new:
5493
      args['memory'] = self.be_new[constants.BE_MEMORY]
5494
    if constants.BE_VCPUS in self.be_new:
5495
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
5496
    # FIXME: readd disk/nic changes
5497
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
5498
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5499
    return env, nl, nl
5500

    
5501
  def CheckPrereq(self):
5502
    """Check prerequisites.
5503

5504
    This only checks the instance list against the existing names.
5505

5506
    """
5507
    force = self.force = self.op.force
5508

    
5509
    # checking the new params on the primary/secondary nodes
5510

    
5511
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5512
    assert self.instance is not None, \
5513
      "Cannot retrieve locked instance %s" % self.op.instance_name
5514
    pnode = instance.primary_node
5515
    nodelist = list(instance.all_nodes)
5516

    
5517
    # hvparams processing
5518
    if self.op.hvparams:
5519
      i_hvdict = copy.deepcopy(instance.hvparams)
5520
      for key, val in self.op.hvparams.iteritems():
5521
        if val == constants.VALUE_DEFAULT:
5522
          try:
5523
            del i_hvdict[key]
5524
          except KeyError:
5525
            pass
5526
        elif val == constants.VALUE_NONE:
5527
          i_hvdict[key] = None
5528
        else:
5529
          i_hvdict[key] = val
5530
      cluster = self.cfg.GetClusterInfo()
5531
      hv_new = cluster.FillDict(cluster.hvparams[instance.hypervisor],
5532
                                i_hvdict)
5533
      # local check
5534
      hypervisor.GetHypervisor(
5535
        instance.hypervisor).CheckParameterSyntax(hv_new)
5536
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
5537
      self.hv_new = hv_new # the new actual values
5538
      self.hv_inst = i_hvdict # the new dict (without defaults)
5539
    else:
5540
      self.hv_new = self.hv_inst = {}
5541

    
5542
    # beparams processing
5543
    if self.op.beparams:
5544
      i_bedict = copy.deepcopy(instance.beparams)
5545
      for key, val in self.op.beparams.iteritems():
5546
        if val == constants.VALUE_DEFAULT:
5547
          try:
5548
            del i_bedict[key]
5549
          except KeyError:
5550
            pass
5551
        else:
5552
          i_bedict[key] = val
5553
      cluster = self.cfg.GetClusterInfo()
5554
      be_new = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
5555
                                i_bedict)
5556
      self.be_new = be_new # the new actual values
5557
      self.be_inst = i_bedict # the new dict (without defaults)
5558
    else:
5559
      self.be_new = self.be_inst = {}
5560

    
5561
    self.warn = []
5562

    
5563
    if constants.BE_MEMORY in self.op.beparams and not self.force:
5564
      mem_check_list = [pnode]
5565
      if be_new[constants.BE_AUTO_BALANCE]:
5566
        # either we changed auto_balance to yes or it was from before
5567
        mem_check_list.extend(instance.secondary_nodes)
5568
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
5569
                                                  instance.hypervisor)
5570
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
5571
                                         instance.hypervisor)
5572
      if nodeinfo[pnode].failed or not isinstance(nodeinfo[pnode].data, dict):
5573
        # Assume the primary node is unreachable and go ahead
5574
        self.warn.append("Can't get info from primary node %s" % pnode)
5575
      else:
5576
        if not instance_info.failed and instance_info.data:
5577
          current_mem = instance_info.data['memory']
5578
        else:
5579
          # Assume instance not running
5580
          # (there is a slight race condition here, but it's not very probable,
5581
          # and we have no other way to check)
5582
          current_mem = 0
5583
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
5584
                    nodeinfo[pnode].data['memory_free'])
5585
        if miss_mem > 0:
5586
          raise errors.OpPrereqError("This change will prevent the instance"
5587
                                     " from starting, due to %d MB of memory"
5588
                                     " missing on its primary node" % miss_mem)
5589

    
5590
      if be_new[constants.BE_AUTO_BALANCE]:
5591
        for node, nres in nodeinfo.iteritems():
5592
          if node not in instance.secondary_nodes:
5593
            continue
5594
          if nres.failed or not isinstance(nres.data, dict):
5595
            self.warn.append("Can't get info from secondary node %s" % node)
5596
          elif be_new[constants.BE_MEMORY] > nres.data['memory_free']:
5597
            self.warn.append("Not enough memory to failover instance to"
5598
                             " secondary node %s" % node)
5599

    
5600
    # NIC processing
5601
    for nic_op, nic_dict in self.op.nics:
5602
      if nic_op == constants.DDM_REMOVE:
5603
        if not instance.nics:
5604
          raise errors.OpPrereqError("Instance has no NICs, cannot remove")
5605
        continue
5606
      if nic_op != constants.DDM_ADD:
5607
        # an existing nic
5608
        if nic_op < 0 or nic_op >= len(instance.nics):
5609
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
5610
                                     " are 0 to %d" %
5611
                                     (nic_op, len(instance.nics)))
5612
      nic_bridge = nic_dict.get('bridge', None)
5613
      if nic_bridge is not None:
5614
        if not self.rpc.call_bridges_exist(pnode, [nic_bridge]):
5615
          msg = ("Bridge '%s' doesn't exist on one of"
5616
                 " the instance nodes" % nic_bridge)
5617
          if self.force:
5618
            self.warn.append(msg)
5619
          else:
5620
            raise errors.OpPrereqError(msg)
5621

    
5622
    # DISK processing
5623
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
5624
      raise errors.OpPrereqError("Disk operations not supported for"
5625
                                 " diskless instances")
5626
    for disk_op, disk_dict in self.op.disks:
5627
      if disk_op == constants.DDM_REMOVE:
5628
        if len(instance.disks) == 1:
5629
          raise errors.OpPrereqError("Cannot remove the last disk of"
5630
                                     " an instance")
5631
        ins_l = self.rpc.call_instance_list([pnode], [instance.hypervisor])
5632
        ins_l = ins_l[pnode]
5633
        if ins_l.failed or not isinstance(ins_l.data, list):
5634
          raise errors.OpPrereqError("Can't contact node '%s'" % pnode)
5635
        if instance.name in ins_l.data:
5636
          raise errors.OpPrereqError("Instance is running, can't remove"
5637
                                     " disks.")
5638

    
5639
      if (disk_op == constants.DDM_ADD and
5640
          len(instance.nics) >= constants.MAX_DISKS):
5641
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
5642
                                   " add more" % constants.MAX_DISKS)
5643
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
5644
        # an existing disk
5645
        if disk_op < 0 or disk_op >= len(instance.disks):
5646
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
5647
                                     " are 0 to %d" %
5648
                                     (disk_op, len(instance.disks)))
5649

    
5650
    return
5651

    
5652
  def Exec(self, feedback_fn):
5653
    """Modifies an instance.
5654

5655
    All parameters take effect only at the next restart of the instance.
5656

5657
    """
5658
    # Process here the warnings from CheckPrereq, as we don't have a
5659
    # feedback_fn there.
5660
    for warn in self.warn:
5661
      feedback_fn("WARNING: %s" % warn)
5662

    
5663
    result = []
5664
    instance = self.instance
5665
    # disk changes
5666
    for disk_op, disk_dict in self.op.disks:
5667
      if disk_op == constants.DDM_REMOVE:
5668
        # remove the last disk
5669
        device = instance.disks.pop()
5670
        device_idx = len(instance.disks)
5671
        for node, disk in device.ComputeNodeTree(instance.primary_node):
5672
          self.cfg.SetDiskID(disk, node)
5673
          rpc_result = self.rpc.call_blockdev_remove(node, disk)
5674
          if rpc_result.failed or not rpc_result.data:
5675
            self.proc.LogWarning("Could not remove disk/%d on node %s,"
5676
                                 " continuing anyway", device_idx, node)
5677
        result.append(("disk/%d" % device_idx, "remove"))
5678
      elif disk_op == constants.DDM_ADD:
5679
        # add a new disk
5680
        if instance.disk_template == constants.DT_FILE:
5681
          file_driver, file_path = instance.disks[0].logical_id
5682
          file_path = os.path.dirname(file_path)
5683
        else:
5684
          file_driver = file_path = None
5685
        disk_idx_base = len(instance.disks)
5686
        new_disk = _GenerateDiskTemplate(self,
5687
                                         instance.disk_template,
5688
                                         instance, instance.primary_node,
5689
                                         instance.secondary_nodes,
5690
                                         [disk_dict],
5691
                                         file_path,
5692
                                         file_driver,
5693
                                         disk_idx_base)[0]
5694
        new_disk.mode = disk_dict['mode']
5695
        instance.disks.append(new_disk)
5696
        info = _GetInstanceInfoText(instance)
5697

    
5698
        logging.info("Creating volume %s for instance %s",
5699
                     new_disk.iv_name, instance.name)
5700
        # Note: this needs to be kept in sync with _CreateDisks
5701
        #HARDCODE
5702
        for node in instance.all_nodes:
5703
          f_create = node == instance.primary_node
5704
          try:
5705
            _CreateBlockDev(self, node, instance, new_disk,
5706
                            f_create, info, f_create)
5707
          except errors.OpExecError, err:
5708
            self.LogWarning("Failed to create volume %s (%s) on"
5709
                            " node %s: %s",
5710
                            new_disk.iv_name, new_disk, node, err)
5711
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
5712
                       (new_disk.size, new_disk.mode)))
5713
      else:
5714
        # change a given disk
5715
        instance.disks[disk_op].mode = disk_dict['mode']
5716
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
5717
    # NIC changes
5718
    for nic_op, nic_dict in self.op.nics:
5719
      if nic_op == constants.DDM_REMOVE:
5720
        # remove the last nic
5721
        del instance.nics[-1]
5722
        result.append(("nic.%d" % len(instance.nics), "remove"))
5723
      elif nic_op == constants.DDM_ADD:
5724
        # add a new nic
5725
        if 'mac' not in nic_dict:
5726
          mac = constants.VALUE_GENERATE
5727
        else:
5728
          mac = nic_dict['mac']
5729
        if mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5730
          mac = self.cfg.GenerateMAC()
5731
        new_nic = objects.NIC(mac=mac, ip=nic_dict.get('ip', None),
5732
                              bridge=nic_dict.get('bridge', None))
5733
        instance.nics.append(new_nic)
5734
        result.append(("nic.%d" % (len(instance.nics) - 1),
5735
                       "add:mac=%s,ip=%s,bridge=%s" %
5736
                       (new_nic.mac, new_nic.ip, new_nic.bridge)))
5737
      else:
5738
        # change a given nic
5739
        for key in 'mac', 'ip', 'bridge':
5740
          if key in nic_dict:
5741
            setattr(instance.nics[nic_op], key, nic_dict[key])
5742
            result.append(("nic.%s/%d" % (key, nic_op), nic_dict[key]))
5743

    
5744
    # hvparams changes
5745
    if self.op.hvparams:
5746
      instance.hvparams = self.hv_new
5747
      for key, val in self.op.hvparams.iteritems():
5748
        result.append(("hv/%s" % key, val))
5749

    
5750
    # beparams changes
5751
    if self.op.beparams:
5752
      instance.beparams = self.be_inst
5753
      for key, val in self.op.beparams.iteritems():
5754
        result.append(("be/%s" % key, val))
5755

    
5756
    self.cfg.Update(instance)
5757

    
5758
    return result
5759

    
5760

    
5761
class LUQueryExports(NoHooksLU):
5762
  """Query the exports list
5763

5764
  """
5765
  _OP_REQP = ['nodes']
5766
  REQ_BGL = False
5767

    
5768
  def ExpandNames(self):
5769
    self.needed_locks = {}
5770
    self.share_locks[locking.LEVEL_NODE] = 1
5771
    if not self.op.nodes:
5772
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5773
    else:
5774
      self.needed_locks[locking.LEVEL_NODE] = \
5775
        _GetWantedNodes(self, self.op.nodes)
5776

    
5777
  def CheckPrereq(self):
5778
    """Check prerequisites.
5779

5780
    """
5781
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
5782

    
5783
  def Exec(self, feedback_fn):
5784
    """Compute the list of all the exported system images.
5785

5786
    @rtype: dict
5787
    @return: a dictionary with the structure node->(export-list)
5788
        where export-list is a list of the instances exported on
5789
        that node.
5790

5791
    """
5792
    rpcresult = self.rpc.call_export_list(self.nodes)
5793
    result = {}
5794
    for node in rpcresult:
5795
      if rpcresult[node].failed:
5796
        result[node] = False
5797
      else:
5798
        result[node] = rpcresult[node].data
5799

    
5800
    return result
5801

    
5802

    
5803
class LUExportInstance(LogicalUnit):
5804
  """Export an instance to an image in the cluster.
5805

5806
  """
5807
  HPATH = "instance-export"
5808
  HTYPE = constants.HTYPE_INSTANCE
5809
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
5810
  REQ_BGL = False
5811

    
5812
  def ExpandNames(self):
5813
    self._ExpandAndLockInstance()
5814
    # FIXME: lock only instance primary and destination node
5815
    #
5816
    # Sad but true, for now we have do lock all nodes, as we don't know where
5817
    # the previous export might be, and and in this LU we search for it and
5818
    # remove it from its current node. In the future we could fix this by:
5819
    #  - making a tasklet to search (share-lock all), then create the new one,
5820
    #    then one to remove, after
5821
    #  - removing the removal operation altoghether
5822
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5823

    
5824
  def DeclareLocks(self, level):
5825
    """Last minute lock declaration."""
5826
    # All nodes are locked anyway, so nothing to do here.
5827

    
5828
  def BuildHooksEnv(self):
5829
    """Build hooks env.
5830

5831
    This will run on the master, primary node and target node.
5832

5833
    """
5834
    env = {
5835
      "EXPORT_NODE": self.op.target_node,
5836
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
5837
      }
5838
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5839
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node,
5840
          self.op.target_node]
5841
    return env, nl, nl
5842

    
5843
  def CheckPrereq(self):
5844
    """Check prerequisites.
5845

5846
    This checks that the instance and node names are valid.
5847

5848
    """
5849
    instance_name = self.op.instance_name
5850
    self.instance = self.cfg.GetInstanceInfo(instance_name)
5851
    assert self.instance is not None, \
5852
          "Cannot retrieve locked instance %s" % self.op.instance_name
5853
    _CheckNodeOnline(self, self.instance.primary_node)
5854

    
5855
    self.dst_node = self.cfg.GetNodeInfo(
5856
      self.cfg.ExpandNodeName(self.op.target_node))
5857

    
5858
    if self.dst_node is None:
5859
      # This is wrong node name, not a non-locked node
5860
      raise errors.OpPrereqError("Wrong node name %s" % self.op.target_node)
5861
    _CheckNodeOnline(self, self.dst_node.name)
5862

    
5863
    # instance disk type verification
5864
    for disk in self.instance.disks:
5865
      if disk.dev_type == constants.LD_FILE:
5866
        raise errors.OpPrereqError("Export not supported for instances with"
5867
                                   " file-based disks")
5868

    
5869
  def Exec(self, feedback_fn):
5870
    """Export an instance to an image in the cluster.
5871

5872
    """
5873
    instance = self.instance
5874
    dst_node = self.dst_node
5875
    src_node = instance.primary_node
5876
    if self.op.shutdown:
5877
      # shutdown the instance, but not the disks
5878
      result = self.rpc.call_instance_shutdown(src_node, instance)
5879
      result.Raise()
5880
      if not result.data:
5881
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
5882
                                 (instance.name, src_node))
5883

    
5884
    vgname = self.cfg.GetVGName()
5885

    
5886
    snap_disks = []
5887

    
5888
    # set the disks ID correctly since call_instance_start needs the
5889
    # correct drbd minor to create the symlinks
5890
    for disk in instance.disks:
5891
      self.cfg.SetDiskID(disk, src_node)
5892

    
5893
    try:
5894
      for disk in instance.disks:
5895
        # new_dev_name will be a snapshot of an lvm leaf of the one we passed
5896
        new_dev_name = self.rpc.call_blockdev_snapshot(src_node, disk)
5897
        if new_dev_name.failed or not new_dev_name.data:
5898
          self.LogWarning("Could not snapshot block device %s on node %s",
5899
                          disk.logical_id[1], src_node)
5900
          snap_disks.append(False)
5901
        else:
5902
          new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
5903
                                 logical_id=(vgname, new_dev_name.data),
5904
                                 physical_id=(vgname, new_dev_name.data),
5905
                                 iv_name=disk.iv_name)
5906
          snap_disks.append(new_dev)
5907

    
5908
    finally:
5909
      if self.op.shutdown and instance.status == "up":
5910
        result = self.rpc.call_instance_start(src_node, instance, None)
5911
        msg = result.RemoteFailMsg()
5912
        if msg:
5913
          _ShutdownInstanceDisks(self, instance)
5914
          raise errors.OpExecError("Could not start instance: %s" % msg)
5915

    
5916
    # TODO: check for size
5917

    
5918
    cluster_name = self.cfg.GetClusterName()
5919
    for idx, dev in enumerate(snap_disks):
5920
      if dev:
5921
        result = self.rpc.call_snapshot_export(src_node, dev, dst_node.name,
5922
                                               instance, cluster_name, idx)
5923
        if result.failed or not result.data:
5924
          self.LogWarning("Could not export block device %s from node %s to"
5925
                          " node %s", dev.logical_id[1], src_node,
5926
                          dst_node.name)
5927
        result = self.rpc.call_blockdev_remove(src_node, dev)
5928
        if result.failed or not result.data:
5929
          self.LogWarning("Could not remove snapshot block device %s from node"
5930
                          " %s", dev.logical_id[1], src_node)
5931

    
5932
    result = self.rpc.call_finalize_export(dst_node.name, instance, snap_disks)
5933
    if result.failed or not result.data:
5934
      self.LogWarning("Could not finalize export for instance %s on node %s",
5935
                      instance.name, dst_node.name)
5936

    
5937
    nodelist = self.cfg.GetNodeList()
5938
    nodelist.remove(dst_node.name)
5939

    
5940
    # on one-node clusters nodelist will be empty after the removal
5941
    # if we proceed the backup would be removed because OpQueryExports
5942
    # substitutes an empty list with the full cluster node list.
5943
    if nodelist:
5944
      exportlist = self.rpc.call_export_list(nodelist)
5945
      for node in exportlist:
5946
        if exportlist[node].failed:
5947
          continue
5948
        if instance.name in exportlist[node].data:
5949
          if not self.rpc.call_export_remove(node, instance.name):
5950
            self.LogWarning("Could not remove older export for instance %s"
5951
                            " on node %s", instance.name, node)
5952

    
5953

    
5954
class LURemoveExport(NoHooksLU):
5955
  """Remove exports related to the named instance.
5956

5957
  """
5958
  _OP_REQP = ["instance_name"]
5959
  REQ_BGL = False
5960

    
5961
  def ExpandNames(self):
5962
    self.needed_locks = {}
5963
    # We need all nodes to be locked in order for RemoveExport to work, but we
5964
    # don't need to lock the instance itself, as nothing will happen to it (and
5965
    # we can remove exports also for a removed instance)
5966
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5967

    
5968
  def CheckPrereq(self):
5969
    """Check prerequisites.
5970
    """
5971
    pass
5972

    
5973
  def Exec(self, feedback_fn):
5974
    """Remove any export.
5975

5976
    """
5977
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
5978
    # If the instance was not found we'll try with the name that was passed in.
5979
    # This will only work if it was an FQDN, though.
5980
    fqdn_warn = False
5981
    if not instance_name:
5982
      fqdn_warn = True
5983
      instance_name = self.op.instance_name
5984

    
5985
    exportlist = self.rpc.call_export_list(self.acquired_locks[
5986
      locking.LEVEL_NODE])
5987
    found = False
5988
    for node in exportlist:
5989
      if exportlist[node].failed:
5990
        self.LogWarning("Failed to query node %s, continuing" % node)
5991
        continue
5992
      if instance_name in exportlist[node].data:
5993
        found = True
5994
        result = self.rpc.call_export_remove(node, instance_name)
5995
        if result.failed or not result.data:
5996
          logging.error("Could not remove export for instance %s"
5997
                        " on node %s", instance_name, node)
5998

    
5999
    if fqdn_warn and not found:
6000
      feedback_fn("Export not found. If trying to remove an export belonging"
6001
                  " to a deleted instance please use its Fully Qualified"
6002
                  " Domain Name.")
6003

    
6004

    
6005
class TagsLU(NoHooksLU):
6006
  """Generic tags LU.
6007

6008
  This is an abstract class which is the parent of all the other tags LUs.
6009

6010
  """
6011

    
6012
  def ExpandNames(self):
6013
    self.needed_locks = {}
6014
    if self.op.kind == constants.TAG_NODE:
6015
      name = self.cfg.ExpandNodeName(self.op.name)
6016
      if name is None:
6017
        raise errors.OpPrereqError("Invalid node name (%s)" %
6018
                                   (self.op.name,))
6019
      self.op.name = name
6020
      self.needed_locks[locking.LEVEL_NODE] = name
6021
    elif self.op.kind == constants.TAG_INSTANCE:
6022
      name = self.cfg.ExpandInstanceName(self.op.name)
6023
      if name is None:
6024
        raise errors.OpPrereqError("Invalid instance name (%s)" %
6025
                                   (self.op.name,))
6026
      self.op.name = name
6027
      self.needed_locks[locking.LEVEL_INSTANCE] = name
6028

    
6029
  def CheckPrereq(self):
6030
    """Check prerequisites.
6031

6032
    """
6033
    if self.op.kind == constants.TAG_CLUSTER:
6034
      self.target = self.cfg.GetClusterInfo()
6035
    elif self.op.kind == constants.TAG_NODE:
6036
      self.target = self.cfg.GetNodeInfo(self.op.name)
6037
    elif self.op.kind == constants.TAG_INSTANCE:
6038
      self.target = self.cfg.GetInstanceInfo(self.op.name)
6039
    else:
6040
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
6041
                                 str(self.op.kind))
6042

    
6043

    
6044
class LUGetTags(TagsLU):
6045
  """Returns the tags of a given object.
6046

6047
  """
6048
  _OP_REQP = ["kind", "name"]
6049
  REQ_BGL = False
6050

    
6051
  def Exec(self, feedback_fn):
6052
    """Returns the tag list.
6053

6054
    """
6055
    return list(self.target.GetTags())
6056

    
6057

    
6058
class LUSearchTags(NoHooksLU):
6059
  """Searches the tags for a given pattern.
6060

6061
  """
6062
  _OP_REQP = ["pattern"]
6063
  REQ_BGL = False
6064

    
6065
  def ExpandNames(self):
6066
    self.needed_locks = {}
6067

    
6068
  def CheckPrereq(self):
6069
    """Check prerequisites.
6070

6071
    This checks the pattern passed for validity by compiling it.
6072

6073
    """
6074
    try:
6075
      self.re = re.compile(self.op.pattern)
6076
    except re.error, err:
6077
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
6078
                                 (self.op.pattern, err))
6079

    
6080
  def Exec(self, feedback_fn):
6081
    """Returns the tag list.
6082

6083
    """
6084
    cfg = self.cfg
6085
    tgts = [("/cluster", cfg.GetClusterInfo())]
6086
    ilist = cfg.GetAllInstancesInfo().values()
6087
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
6088
    nlist = cfg.GetAllNodesInfo().values()
6089
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
6090
    results = []
6091
    for path, target in tgts:
6092
      for tag in target.GetTags():
6093
        if self.re.search(tag):
6094
          results.append((path, tag))
6095
    return results
6096

    
6097

    
6098
class LUAddTags(TagsLU):
6099
  """Sets a tag on a given object.
6100

6101
  """
6102
  _OP_REQP = ["kind", "name", "tags"]
6103
  REQ_BGL = False
6104

    
6105
  def CheckPrereq(self):
6106
    """Check prerequisites.
6107

6108
    This checks the type and length of the tag name and value.
6109

6110
    """
6111
    TagsLU.CheckPrereq(self)
6112
    for tag in self.op.tags:
6113
      objects.TaggableObject.ValidateTag(tag)
6114

    
6115
  def Exec(self, feedback_fn):
6116
    """Sets the tag.
6117

6118
    """
6119
    try:
6120
      for tag in self.op.tags:
6121
        self.target.AddTag(tag)
6122
    except errors.TagError, err:
6123
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
6124
    try:
6125
      self.cfg.Update(self.target)
6126
    except errors.ConfigurationError:
6127
      raise errors.OpRetryError("There has been a modification to the"
6128
                                " config file and the operation has been"
6129
                                " aborted. Please retry.")
6130

    
6131

    
6132
class LUDelTags(TagsLU):
6133
  """Delete a list of tags from a given object.
6134

6135
  """
6136
  _OP_REQP = ["kind", "name", "tags"]
6137
  REQ_BGL = False
6138

    
6139
  def CheckPrereq(self):
6140
    """Check prerequisites.
6141

6142
    This checks that we have the given tag.
6143

6144
    """
6145
    TagsLU.CheckPrereq(self)
6146
    for tag in self.op.tags:
6147
      objects.TaggableObject.ValidateTag(tag)
6148
    del_tags = frozenset(self.op.tags)
6149
    cur_tags = self.target.GetTags()
6150
    if not del_tags <= cur_tags:
6151
      diff_tags = del_tags - cur_tags
6152
      diff_names = ["'%s'" % tag for tag in diff_tags]
6153
      diff_names.sort()
6154
      raise errors.OpPrereqError("Tag(s) %s not found" %
6155
                                 (",".join(diff_names)))
6156

    
6157
  def Exec(self, feedback_fn):
6158
    """Remove the tag from the object.
6159

6160
    """
6161
    for tag in self.op.tags:
6162
      self.target.RemoveTag(tag)
6163
    try:
6164
      self.cfg.Update(self.target)
6165
    except errors.ConfigurationError:
6166
      raise errors.OpRetryError("There has been a modification to the"
6167
                                " config file and the operation has been"
6168
                                " aborted. Please retry.")
6169

    
6170

    
6171
class LUTestDelay(NoHooksLU):
6172
  """Sleep for a specified amount of time.
6173

6174
  This LU sleeps on the master and/or nodes for a specified amount of
6175
  time.
6176

6177
  """
6178
  _OP_REQP = ["duration", "on_master", "on_nodes"]
6179
  REQ_BGL = False
6180

    
6181
  def ExpandNames(self):
6182
    """Expand names and set required locks.
6183

6184
    This expands the node list, if any.
6185

6186
    """
6187
    self.needed_locks = {}
6188
    if self.op.on_nodes:
6189
      # _GetWantedNodes can be used here, but is not always appropriate to use
6190
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
6191
      # more information.
6192
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
6193
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
6194

    
6195
  def CheckPrereq(self):
6196
    """Check prerequisites.
6197

6198
    """
6199

    
6200
  def Exec(self, feedback_fn):
6201
    """Do the actual sleep.
6202

6203
    """
6204
    if self.op.on_master:
6205
      if not utils.TestDelay(self.op.duration):
6206
        raise errors.OpExecError("Error during master delay test")
6207
    if self.op.on_nodes:
6208
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
6209
      if not result:
6210
        raise errors.OpExecError("Complete failure from rpc call")
6211
      for node, node_result in result.items():
6212
        node_result.Raise()
6213
        if not node_result.data:
6214
          raise errors.OpExecError("Failure during rpc call to node %s,"
6215
                                   " result: %s" % (node, node_result.data))
6216

    
6217

    
6218
class IAllocator(object):
6219
  """IAllocator framework.
6220

6221
  An IAllocator instance has three sets of attributes:
6222
    - cfg that is needed to query the cluster
6223
    - input data (all members of the _KEYS class attribute are required)
6224
    - four buffer attributes (in|out_data|text), that represent the
6225
      input (to the external script) in text and data structure format,
6226
      and the output from it, again in two formats
6227
    - the result variables from the script (success, info, nodes) for
6228
      easy usage
6229

6230
  """
6231
  _ALLO_KEYS = [
6232
    "mem_size", "disks", "disk_template",
6233
    "os", "tags", "nics", "vcpus", "hypervisor",
6234
    ]
6235
  _RELO_KEYS = [
6236
    "relocate_from",
6237
    ]
6238

    
6239
  def __init__(self, lu, mode, name, **kwargs):
6240
    self.lu = lu
6241
    # init buffer variables
6242
    self.in_text = self.out_text = self.in_data = self.out_data = None
6243
    # init all input fields so that pylint is happy
6244
    self.mode = mode
6245
    self.name = name
6246
    self.mem_size = self.disks = self.disk_template = None
6247
    self.os = self.tags = self.nics = self.vcpus = None
6248
    self.hypervisor = None
6249
    self.relocate_from = None
6250
    # computed fields
6251
    self.required_nodes = None
6252
    # init result fields
6253
    self.success = self.info = self.nodes = None
6254
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6255
      keyset = self._ALLO_KEYS
6256
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
6257
      keyset = self._RELO_KEYS
6258
    else:
6259
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
6260
                                   " IAllocator" % self.mode)
6261
    for key in kwargs:
6262
      if key not in keyset:
6263
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
6264
                                     " IAllocator" % key)
6265
      setattr(self, key, kwargs[key])
6266
    for key in keyset:
6267
      if key not in kwargs:
6268
        raise errors.ProgrammerError("Missing input parameter '%s' to"
6269
                                     " IAllocator" % key)
6270
    self._BuildInputData()
6271

    
6272
  def _ComputeClusterData(self):
6273
    """Compute the generic allocator input data.
6274

6275
    This is the data that is independent of the actual operation.
6276

6277
    """
6278
    cfg = self.lu.cfg
6279
    cluster_info = cfg.GetClusterInfo()
6280
    # cluster data
6281
    data = {
6282
      "version": 1,
6283
      "cluster_name": cfg.GetClusterName(),
6284
      "cluster_tags": list(cluster_info.GetTags()),
6285
      "enable_hypervisors": list(cluster_info.enabled_hypervisors),
6286
      # we don't have job IDs
6287
      }
6288
    iinfo = cfg.GetAllInstancesInfo().values()
6289
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
6290

    
6291
    # node data
6292
    node_results = {}
6293
    node_list = cfg.GetNodeList()
6294

    
6295
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6296
      hypervisor_name = self.hypervisor
6297
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
6298
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
6299

    
6300
    node_data = self.lu.rpc.call_node_info(node_list, cfg.GetVGName(),
6301
                                           hypervisor_name)
6302
    node_iinfo = self.lu.rpc.call_all_instances_info(node_list,
6303
                       cluster_info.enabled_hypervisors)
6304
    for nname in node_list:
6305
      ninfo = cfg.GetNodeInfo(nname)
6306
      node_data[nname].Raise()
6307
      if not isinstance(node_data[nname].data, dict):
6308
        raise errors.OpExecError("Can't get data for node %s" % nname)
6309
      remote_info = node_data[nname].data
6310
      for attr in ['memory_total', 'memory_free', 'memory_dom0',
6311
                   'vg_size', 'vg_free', 'cpu_total']:
6312
        if attr not in remote_info:
6313
          raise errors.OpExecError("Node '%s' didn't return attribute '%s'" %
6314
                                   (nname, attr))
6315
        try:
6316
          remote_info[attr] = int(remote_info[attr])
6317
        except ValueError, err:
6318
          raise errors.OpExecError("Node '%s' returned invalid value for '%s':"
6319
                                   " %s" % (nname, attr, str(err)))
6320
      # compute memory used by primary instances
6321
      i_p_mem = i_p_up_mem = 0
6322
      for iinfo, beinfo in i_list:
6323
        if iinfo.primary_node == nname:
6324
          i_p_mem += beinfo[constants.BE_MEMORY]
6325
          if iinfo.name not in node_iinfo[nname]:
6326
            i_used_mem = 0
6327
          else:
6328
            i_used_mem = int(node_iinfo[nname][iinfo.name]['memory'])
6329
          i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
6330
          remote_info['memory_free'] -= max(0, i_mem_diff)
6331

    
6332
          if iinfo.status == "up":
6333
            i_p_up_mem += beinfo[constants.BE_MEMORY]
6334

    
6335
      # compute memory used by instances
6336
      pnr = {
6337
        "tags": list(ninfo.GetTags()),
6338
        "total_memory": remote_info['memory_total'],
6339
        "reserved_memory": remote_info['memory_dom0'],
6340
        "free_memory": remote_info['memory_free'],
6341
        "i_pri_memory": i_p_mem,
6342
        "i_pri_up_memory": i_p_up_mem,
6343
        "total_disk": remote_info['vg_size'],
6344
        "free_disk": remote_info['vg_free'],
6345
        "primary_ip": ninfo.primary_ip,
6346
        "secondary_ip": ninfo.secondary_ip,
6347
        "total_cpus": remote_info['cpu_total'],
6348
        "offline": ninfo.offline,
6349
        }
6350
      node_results[nname] = pnr
6351
    data["nodes"] = node_results
6352

    
6353
    # instance data
6354
    instance_data = {}
6355
    for iinfo, beinfo in i_list:
6356
      nic_data = [{"mac": n.mac, "ip": n.ip, "bridge": n.bridge}
6357
                  for n in iinfo.nics]
6358
      pir = {
6359
        "tags": list(iinfo.GetTags()),
6360
        "should_run": iinfo.status == "up",
6361
        "vcpus": beinfo[constants.BE_VCPUS],
6362
        "memory": beinfo[constants.BE_MEMORY],
6363
        "os": iinfo.os,
6364
        "nodes": list(iinfo.all_nodes),
6365
        "nics": nic_data,
6366
        "disks": [{"size": dsk.size, "mode": "w"} for dsk in iinfo.disks],
6367
        "disk_template": iinfo.disk_template,
6368
        "hypervisor": iinfo.hypervisor,
6369
        }
6370
      instance_data[iinfo.name] = pir
6371

    
6372
    data["instances"] = instance_data
6373

    
6374
    self.in_data = data
6375

    
6376
  def _AddNewInstance(self):
6377
    """Add new instance data to allocator structure.
6378

6379
    This in combination with _AllocatorGetClusterData will create the
6380
    correct structure needed as input for the allocator.
6381

6382
    The checks for the completeness of the opcode must have already been
6383
    done.
6384

6385
    """
6386
    data = self.in_data
6387
    if len(self.disks) != 2:
6388
      raise errors.OpExecError("Only two-disk configurations supported")
6389

    
6390
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
6391

    
6392
    if self.disk_template in constants.DTS_NET_MIRROR:
6393
      self.required_nodes = 2
6394
    else:
6395
      self.required_nodes = 1
6396
    request = {
6397
      "type": "allocate",
6398
      "name": self.name,
6399
      "disk_template": self.disk_template,
6400
      "tags": self.tags,
6401
      "os": self.os,
6402
      "vcpus": self.vcpus,
6403
      "memory": self.mem_size,
6404
      "disks": self.disks,
6405
      "disk_space_total": disk_space,
6406
      "nics": self.nics,
6407
      "required_nodes": self.required_nodes,
6408
      }
6409
    data["request"] = request
6410

    
6411
  def _AddRelocateInstance(self):
6412
    """Add relocate instance data to allocator structure.
6413

6414
    This in combination with _IAllocatorGetClusterData will create the
6415
    correct structure needed as input for the allocator.
6416

6417
    The checks for the completeness of the opcode must have already been
6418
    done.
6419

6420
    """
6421
    instance = self.lu.cfg.GetInstanceInfo(self.name)
6422
    if instance is None:
6423
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
6424
                                   " IAllocator" % self.name)
6425

    
6426
    if instance.disk_template not in constants.DTS_NET_MIRROR:
6427
      raise errors.OpPrereqError("Can't relocate non-mirrored instances")
6428

    
6429
    if len(instance.secondary_nodes) != 1:
6430
      raise errors.OpPrereqError("Instance has not exactly one secondary node")
6431

    
6432
    self.required_nodes = 1
6433
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
6434
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
6435

    
6436
    request = {
6437
      "type": "relocate",
6438
      "name": self.name,
6439
      "disk_space_total": disk_space,
6440
      "required_nodes": self.required_nodes,
6441
      "relocate_from": self.relocate_from,
6442
      }
6443
    self.in_data["request"] = request
6444

    
6445
  def _BuildInputData(self):
6446
    """Build input data structures.
6447

6448
    """
6449
    self._ComputeClusterData()
6450

    
6451
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6452
      self._AddNewInstance()
6453
    else:
6454
      self._AddRelocateInstance()
6455

    
6456
    self.in_text = serializer.Dump(self.in_data)
6457

    
6458
  def Run(self, name, validate=True, call_fn=None):
6459
    """Run an instance allocator and return the results.
6460

6461
    """
6462
    if call_fn is None:
6463
      call_fn = self.lu.rpc.call_iallocator_runner
6464
    data = self.in_text
6465

    
6466
    result = call_fn(self.lu.cfg.GetMasterNode(), name, self.in_text)
6467
    result.Raise()
6468

    
6469
    if not isinstance(result.data, (list, tuple)) or len(result.data) != 4:
6470
      raise errors.OpExecError("Invalid result from master iallocator runner")
6471

    
6472
    rcode, stdout, stderr, fail = result.data
6473

    
6474
    if rcode == constants.IARUN_NOTFOUND:
6475
      raise errors.OpExecError("Can't find allocator '%s'" % name)
6476
    elif rcode == constants.IARUN_FAILURE:
6477
      raise errors.OpExecError("Instance allocator call failed: %s,"
6478
                               " output: %s" % (fail, stdout+stderr))
6479
    self.out_text = stdout
6480
    if validate:
6481
      self._ValidateResult()
6482

    
6483
  def _ValidateResult(self):
6484
    """Process the allocator results.
6485

6486
    This will process and if successful save the result in
6487
    self.out_data and the other parameters.
6488

6489
    """
6490
    try:
6491
      rdict = serializer.Load(self.out_text)
6492
    except Exception, err:
6493
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
6494

    
6495
    if not isinstance(rdict, dict):
6496
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
6497

    
6498
    for key in "success", "info", "nodes":
6499
      if key not in rdict:
6500
        raise errors.OpExecError("Can't parse iallocator results:"
6501
                                 " missing key '%s'" % key)
6502
      setattr(self, key, rdict[key])
6503

    
6504
    if not isinstance(rdict["nodes"], list):
6505
      raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
6506
                               " is not a list")
6507
    self.out_data = rdict
6508

    
6509

    
6510
class LUTestAllocator(NoHooksLU):
6511
  """Run allocator tests.
6512

6513
  This LU runs the allocator tests
6514

6515
  """
6516
  _OP_REQP = ["direction", "mode", "name"]
6517

    
6518
  def CheckPrereq(self):
6519
    """Check prerequisites.
6520

6521
    This checks the opcode parameters depending on the director and mode test.
6522

6523
    """
6524
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
6525
      for attr in ["name", "mem_size", "disks", "disk_template",
6526
                   "os", "tags", "nics", "vcpus"]:
6527
        if not hasattr(self.op, attr):
6528
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
6529
                                     attr)
6530
      iname = self.cfg.ExpandInstanceName(self.op.name)
6531
      if iname is not None:
6532
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
6533
                                   iname)
6534
      if not isinstance(self.op.nics, list):
6535
        raise errors.OpPrereqError("Invalid parameter 'nics'")
6536
      for row in self.op.nics:
6537
        if (not isinstance(row, dict) or
6538
            "mac" not in row or
6539
            "ip" not in row or
6540
            "bridge" not in row):
6541
          raise errors.OpPrereqError("Invalid contents of the"
6542
                                     " 'nics' parameter")
6543
      if not isinstance(self.op.disks, list):
6544
        raise errors.OpPrereqError("Invalid parameter 'disks'")
6545
      if len(self.op.disks) != 2:
6546
        raise errors.OpPrereqError("Only two-disk configurations supported")
6547
      for row in self.op.disks:
6548
        if (not isinstance(row, dict) or
6549
            "size" not in row or
6550
            not isinstance(row["size"], int) or
6551
            "mode" not in row or
6552
            row["mode"] not in ['r', 'w']):
6553
          raise errors.OpPrereqError("Invalid contents of the"
6554
                                     " 'disks' parameter")
6555
      if self.op.hypervisor is None:
6556
        self.op.hypervisor = self.cfg.GetHypervisorType()
6557
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
6558
      if not hasattr(self.op, "name"):
6559
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input")
6560
      fname = self.cfg.ExpandInstanceName(self.op.name)
6561
      if fname is None:
6562
        raise errors.OpPrereqError("Instance '%s' not found for relocation" %
6563
                                   self.op.name)
6564
      self.op.name = fname
6565
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
6566
    else:
6567
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
6568
                                 self.op.mode)
6569

    
6570
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
6571
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
6572
        raise errors.OpPrereqError("Missing allocator name")
6573
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
6574
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
6575
                                 self.op.direction)
6576

    
6577
  def Exec(self, feedback_fn):
6578
    """Run the allocator test.
6579

6580
    """
6581
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
6582
      ial = IAllocator(self,
6583
                       mode=self.op.mode,
6584
                       name=self.op.name,
6585
                       mem_size=self.op.mem_size,
6586
                       disks=self.op.disks,
6587
                       disk_template=self.op.disk_template,
6588
                       os=self.op.os,
6589
                       tags=self.op.tags,
6590
                       nics=self.op.nics,
6591
                       vcpus=self.op.vcpus,
6592
                       hypervisor=self.op.hypervisor,
6593
                       )
6594
    else:
6595
      ial = IAllocator(self,
6596
                       mode=self.op.mode,
6597
                       name=self.op.name,
6598
                       relocate_from=list(self.relocate_from),
6599
                       )
6600

    
6601
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
6602
      result = ial.in_text
6603
    else:
6604
      ial.Run(self.op.allocator, validate=False)
6605
      result = ial.out_text
6606
    return result