Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 1e288a26

History | View | Annotate | Download (292 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 time
29
import re
30
import platform
31
import logging
32
import copy
33

    
34
from ganeti import ssh
35
from ganeti import utils
36
from ganeti import errors
37
from ganeti import hypervisor
38
from ganeti import locking
39
from ganeti import constants
40
from ganeti import objects
41
from ganeti import serializer
42
from ganeti import ssconf
43

    
44

    
45
class LogicalUnit(object):
46
  """Logical Unit base class.
47

48
  Subclasses must follow these rules:
49
    - implement ExpandNames
50
    - implement CheckPrereq (except when tasklets are used)
51
    - implement Exec (except when tasklets are used)
52
    - implement BuildHooksEnv
53
    - redefine HPATH and HTYPE
54
    - optionally redefine their run requirements:
55
        REQ_BGL: the LU needs to hold the Big Ganeti Lock exclusively
56

57
  Note that all commands require root permissions.
58

59
  @ivar dry_run_result: the value (if any) that will be returned to the caller
60
      in dry-run mode (signalled by opcode dry_run parameter)
61

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

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

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

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

    
96
    # Tasklets
97
    self.tasklets = None
98

    
99
    for attr_name in self._OP_REQP:
100
      attr_val = getattr(op, attr_name, None)
101
      if attr_val is None:
102
        raise errors.OpPrereqError("Required parameter '%s' missing" %
103
                                   attr_name)
104

    
105
    self.CheckArguments()
106

    
107
  def __GetSSH(self):
108
    """Returns the SshRunner object
109

110
    """
111
    if not self.__ssh:
112
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
113
    return self.__ssh
114

    
115
  ssh = property(fget=__GetSSH)
116

    
117
  def CheckArguments(self):
118
    """Check syntactic validity for the opcode arguments.
119

120
    This method is for doing a simple syntactic check and ensure
121
    validity of opcode parameters, without any cluster-related
122
    checks. While the same can be accomplished in ExpandNames and/or
123
    CheckPrereq, doing these separate is better because:
124

125
      - ExpandNames is left as as purely a lock-related function
126
      - CheckPrereq is run after we have acquired locks (and possible
127
        waited for them)
128

129
    The function is allowed to change the self.op attribute so that
130
    later methods can no longer worry about missing parameters.
131

132
    """
133
    pass
134

    
135
  def ExpandNames(self):
136
    """Expand names for this LU.
137

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

143
    LUs which implement this method must also populate the self.needed_locks
144
    member, as a dict with lock levels as keys, and a list of needed lock names
145
    as values. Rules:
146

147
      - use an empty dict if you don't need any lock
148
      - if you don't need any lock at a particular level omit that level
149
      - don't put anything for the BGL level
150
      - if you want all locks at a level use locking.ALL_SET as a value
151

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

156
    This function can also define a list of tasklets, which then will be
157
    executed in order instead of the usual LU-level CheckPrereq and Exec
158
    functions, if those are not defined by the LU.
159

160
    Examples::
161

162
      # Acquire all nodes and one instance
163
      self.needed_locks = {
164
        locking.LEVEL_NODE: locking.ALL_SET,
165
        locking.LEVEL_INSTANCE: ['instance1.example.tld'],
166
      }
167
      # Acquire just two nodes
168
      self.needed_locks = {
169
        locking.LEVEL_NODE: ['node1.example.tld', 'node2.example.tld'],
170
      }
171
      # Acquire no locks
172
      self.needed_locks = {} # No, you can't leave it to the default value None
173

174
    """
175
    # The implementation of this method is mandatory only if the new LU is
176
    # concurrent, so that old LUs don't need to be changed all at the same
177
    # time.
178
    if self.REQ_BGL:
179
      self.needed_locks = {} # Exclusive LUs don't need locks.
180
    else:
181
      raise NotImplementedError
182

    
183
  def DeclareLocks(self, level):
184
    """Declare LU locking needs for a level
185

186
    While most LUs can just declare their locking needs at ExpandNames time,
187
    sometimes there's the need to calculate some locks after having acquired
188
    the ones before. This function is called just before acquiring locks at a
189
    particular level, but after acquiring the ones at lower levels, and permits
190
    such calculations. It can be used to modify self.needed_locks, and by
191
    default it does nothing.
192

193
    This function is only called if you have something already set in
194
    self.needed_locks for the level.
195

196
    @param level: Locking level which is going to be locked
197
    @type level: member of ganeti.locking.LEVELS
198

199
    """
200

    
201
  def CheckPrereq(self):
202
    """Check prerequisites for this LU.
203

204
    This method should check that the prerequisites for the execution
205
    of this LU are fulfilled. It can do internode communication, but
206
    it should be idempotent - no cluster or system changes are
207
    allowed.
208

209
    The method should raise errors.OpPrereqError in case something is
210
    not fulfilled. Its return value is ignored.
211

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

215
    """
216
    if self.tasklets is not None:
217
      for (idx, tl) in enumerate(self.tasklets):
218
        logging.debug("Checking prerequisites for tasklet %s/%s",
219
                      idx + 1, len(self.tasklets))
220
        tl.CheckPrereq()
221
    else:
222
      raise NotImplementedError
223

    
224
  def Exec(self, feedback_fn):
225
    """Execute the LU.
226

227
    This method should implement the actual work. It should raise
228
    errors.OpExecError for failures that are somewhat dealt with in
229
    code, or expected.
230

231
    """
232
    if self.tasklets is not None:
233
      for (idx, tl) in enumerate(self.tasklets):
234
        logging.debug("Executing tasklet %s/%s", idx + 1, len(self.tasklets))
235
        tl.Exec(feedback_fn)
236
    else:
237
      raise NotImplementedError
238

    
239
  def BuildHooksEnv(self):
240
    """Build hooks environment for this LU.
241

242
    This method should return a three-node tuple consisting of: a dict
243
    containing the environment that will be used for running the
244
    specific hook for this LU, a list of node names on which the hook
245
    should run before the execution, and a list of node names on which
246
    the hook should run after the execution.
247

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

253
    No nodes should be returned as an empty list (and not None).
254

255
    Note that if the HPATH for a LU class is None, this function will
256
    not be called.
257

258
    """
259
    raise NotImplementedError
260

    
261
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
262
    """Notify the LU about the results of its hooks.
263

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

270
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
271
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
272
    @param hook_results: the results of the multi-node hooks rpc call
273
    @param feedback_fn: function used send feedback back to the caller
274
    @param lu_result: the previous Exec result this LU had, or None
275
        in the PRE phase
276
    @return: the new Exec result, based on the previous result
277
        and hook results
278

279
    """
280
    return lu_result
281

    
282
  def _ExpandAndLockInstance(self):
283
    """Helper function to expand and lock an instance.
284

285
    Many LUs that work on an instance take its name in self.op.instance_name
286
    and need to expand it and then declare the expanded name for locking. This
287
    function does it, and then updates self.op.instance_name to the expanded
288
    name. It also initializes needed_locks as a dict, if this hasn't been done
289
    before.
290

291
    """
292
    if self.needed_locks is None:
293
      self.needed_locks = {}
294
    else:
295
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
296
        "_ExpandAndLockInstance called with instance-level locks set"
297
    expanded_name = self.cfg.ExpandInstanceName(self.op.instance_name)
298
    if expanded_name is None:
299
      raise errors.OpPrereqError("Instance '%s' not known" %
300
                                  self.op.instance_name)
301
    self.needed_locks[locking.LEVEL_INSTANCE] = expanded_name
302
    self.op.instance_name = expanded_name
303

    
304
  def _LockInstancesNodes(self, primary_only=False):
305
    """Helper function to declare instances' nodes for locking.
306

307
    This function should be called after locking one or more instances to lock
308
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
309
    with all primary or secondary nodes for instances already locked and
310
    present in self.needed_locks[locking.LEVEL_INSTANCE].
311

312
    It should be called from DeclareLocks, and for safety only works if
313
    self.recalculate_locks[locking.LEVEL_NODE] is set.
314

315
    In the future it may grow parameters to just lock some instance's nodes, or
316
    to just lock primaries or secondary nodes, if needed.
317

318
    If should be called in DeclareLocks in a way similar to::
319

320
      if level == locking.LEVEL_NODE:
321
        self._LockInstancesNodes()
322

323
    @type primary_only: boolean
324
    @param primary_only: only lock primary nodes of locked instances
325

326
    """
327
    assert locking.LEVEL_NODE in self.recalculate_locks, \
328
      "_LockInstancesNodes helper function called with no nodes to recalculate"
329

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

    
332
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
333
    # future we might want to have different behaviors depending on the value
334
    # of self.recalculate_locks[locking.LEVEL_NODE]
335
    wanted_nodes = []
336
    for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
337
      instance = self.context.cfg.GetInstanceInfo(instance_name)
338
      wanted_nodes.append(instance.primary_node)
339
      if not primary_only:
340
        wanted_nodes.extend(instance.secondary_nodes)
341

    
342
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
343
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
344
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
345
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
346

    
347
    del self.recalculate_locks[locking.LEVEL_NODE]
348

    
349

    
350
class NoHooksLU(LogicalUnit):
351
  """Simple LU which runs no hooks.
352

353
  This LU is intended as a parent for other LogicalUnits which will
354
  run no hooks, in order to reduce duplicate code.
355

356
  """
357
  HPATH = None
358
  HTYPE = None
359

    
360

    
361
class Tasklet:
362
  """Tasklet base class.
363

364
  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
365
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
366
  tasklets know nothing about locks.
367

368
  Subclasses must follow these rules:
369
    - Implement CheckPrereq
370
    - Implement Exec
371

372
  """
373
  def __init__(self, lu):
374
    self.lu = lu
375

    
376
    # Shortcuts
377
    self.cfg = lu.cfg
378
    self.rpc = lu.rpc
379

    
380
  def CheckPrereq(self):
381
    """Check prerequisites for this tasklets.
382

383
    This method should check whether the prerequisites for the execution of
384
    this tasklet are fulfilled. It can do internode communication, but it
385
    should be idempotent - no cluster or system changes are allowed.
386

387
    The method should raise errors.OpPrereqError in case something is not
388
    fulfilled. Its return value is ignored.
389

390
    This method should also update all parameters to their canonical form if it
391
    hasn't been done before.
392

393
    """
394
    raise NotImplementedError
395

    
396
  def Exec(self, feedback_fn):
397
    """Execute the tasklet.
398

399
    This method should implement the actual work. It should raise
400
    errors.OpExecError for failures that are somewhat dealt with in code, or
401
    expected.
402

403
    """
404
    raise NotImplementedError
405

    
406

    
407
def _GetWantedNodes(lu, nodes):
408
  """Returns list of checked and expanded node names.
409

410
  @type lu: L{LogicalUnit}
411
  @param lu: the logical unit on whose behalf we execute
412
  @type nodes: list
413
  @param nodes: list of node names or None for all nodes
414
  @rtype: list
415
  @return: the list of nodes, sorted
416
  @raise errors.OpProgrammerError: if the nodes parameter is wrong type
417

418
  """
419
  if not isinstance(nodes, list):
420
    raise errors.OpPrereqError("Invalid argument type 'nodes'")
421

    
422
  if not nodes:
423
    raise errors.ProgrammerError("_GetWantedNodes should only be called with a"
424
      " non-empty list of nodes whose name is to be expanded.")
425

    
426
  wanted = []
427
  for name in nodes:
428
    node = lu.cfg.ExpandNodeName(name)
429
    if node is None:
430
      raise errors.OpPrereqError("No such node name '%s'" % name)
431
    wanted.append(node)
432

    
433
  return utils.NiceSort(wanted)
434

    
435

    
436
def _GetWantedInstances(lu, instances):
437
  """Returns list of checked and expanded instance names.
438

439
  @type lu: L{LogicalUnit}
440
  @param lu: the logical unit on whose behalf we execute
441
  @type instances: list
442
  @param instances: list of instance names or None for all instances
443
  @rtype: list
444
  @return: the list of instances, sorted
445
  @raise errors.OpPrereqError: if the instances parameter is wrong type
446
  @raise errors.OpPrereqError: if any of the passed instances is not found
447

448
  """
449
  if not isinstance(instances, list):
450
    raise errors.OpPrereqError("Invalid argument type 'instances'")
451

    
452
  if instances:
453
    wanted = []
454

    
455
    for name in instances:
456
      instance = lu.cfg.ExpandInstanceName(name)
457
      if instance is None:
458
        raise errors.OpPrereqError("No such instance name '%s'" % name)
459
      wanted.append(instance)
460

    
461
  else:
462
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
463
  return wanted
464

    
465

    
466
def _CheckOutputFields(static, dynamic, selected):
467
  """Checks whether all selected fields are valid.
468

469
  @type static: L{utils.FieldSet}
470
  @param static: static fields set
471
  @type dynamic: L{utils.FieldSet}
472
  @param dynamic: dynamic fields set
473

474
  """
475
  f = utils.FieldSet()
476
  f.Extend(static)
477
  f.Extend(dynamic)
478

    
479
  delta = f.NonMatching(selected)
480
  if delta:
481
    raise errors.OpPrereqError("Unknown output fields selected: %s"
482
                               % ",".join(delta))
483

    
484

    
485
def _CheckBooleanOpField(op, name):
486
  """Validates boolean opcode parameters.
487

488
  This will ensure that an opcode parameter is either a boolean value,
489
  or None (but that it always exists).
490

491
  """
492
  val = getattr(op, name, None)
493
  if not (val is None or isinstance(val, bool)):
494
    raise errors.OpPrereqError("Invalid boolean parameter '%s' (%s)" %
495
                               (name, str(val)))
496
  setattr(op, name, val)
497

    
498

    
499
def _CheckNodeOnline(lu, node):
500
  """Ensure that a given node is online.
501

502
  @param lu: the LU on behalf of which we make the check
503
  @param node: the node to check
504
  @raise errors.OpPrereqError: if the node is offline
505

506
  """
507
  if lu.cfg.GetNodeInfo(node).offline:
508
    raise errors.OpPrereqError("Can't use offline node %s" % node)
509

    
510

    
511
def _CheckNodeNotDrained(lu, node):
512
  """Ensure that a given node is not drained.
513

514
  @param lu: the LU on behalf of which we make the check
515
  @param node: the node to check
516
  @raise errors.OpPrereqError: if the node is drained
517

518
  """
519
  if lu.cfg.GetNodeInfo(node).drained:
520
    raise errors.OpPrereqError("Can't use drained node %s" % node)
521

    
522

    
523
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
524
                          memory, vcpus, nics, disk_template, disks,
525
                          bep, hvp, hypervisor_name):
526
  """Builds instance related env variables for hooks
527

528
  This builds the hook environment from individual variables.
529

530
  @type name: string
531
  @param name: the name of the instance
532
  @type primary_node: string
533
  @param primary_node: the name of the instance's primary node
534
  @type secondary_nodes: list
535
  @param secondary_nodes: list of secondary nodes as strings
536
  @type os_type: string
537
  @param os_type: the name of the instance's OS
538
  @type status: boolean
539
  @param status: the should_run status of the instance
540
  @type memory: string
541
  @param memory: the memory size of the instance
542
  @type vcpus: string
543
  @param vcpus: the count of VCPUs the instance has
544
  @type nics: list
545
  @param nics: list of tuples (ip, mac, mode, link) representing
546
      the NICs the instance has
547
  @type disk_template: string
548
  @param disk_template: the disk template of the instance
549
  @type disks: list
550
  @param disks: the list of (size, mode) pairs
551
  @type bep: dict
552
  @param bep: the backend parameters for the instance
553
  @type hvp: dict
554
  @param hvp: the hypervisor parameters for the instance
555
  @type hypervisor_name: string
556
  @param hypervisor_name: the hypervisor for the instance
557
  @rtype: dict
558
  @return: the hook environment for this instance
559

560
  """
561
  if status:
562
    str_status = "up"
563
  else:
564
    str_status = "down"
565
  env = {
566
    "OP_TARGET": name,
567
    "INSTANCE_NAME": name,
568
    "INSTANCE_PRIMARY": primary_node,
569
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
570
    "INSTANCE_OS_TYPE": os_type,
571
    "INSTANCE_STATUS": str_status,
572
    "INSTANCE_MEMORY": memory,
573
    "INSTANCE_VCPUS": vcpus,
574
    "INSTANCE_DISK_TEMPLATE": disk_template,
575
    "INSTANCE_HYPERVISOR": hypervisor_name,
576
  }
577

    
578
  if nics:
579
    nic_count = len(nics)
580
    for idx, (ip, mac, mode, link) in enumerate(nics):
581
      if ip is None:
582
        ip = ""
583
      env["INSTANCE_NIC%d_IP" % idx] = ip
584
      env["INSTANCE_NIC%d_MAC" % idx] = mac
585
      env["INSTANCE_NIC%d_MODE" % idx] = mode
586
      env["INSTANCE_NIC%d_LINK" % idx] = link
587
      if mode == constants.NIC_MODE_BRIDGED:
588
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
589
  else:
590
    nic_count = 0
591

    
592
  env["INSTANCE_NIC_COUNT"] = nic_count
593

    
594
  if disks:
595
    disk_count = len(disks)
596
    for idx, (size, mode) in enumerate(disks):
597
      env["INSTANCE_DISK%d_SIZE" % idx] = size
598
      env["INSTANCE_DISK%d_MODE" % idx] = mode
599
  else:
600
    disk_count = 0
601

    
602
  env["INSTANCE_DISK_COUNT"] = disk_count
603

    
604
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
605
    for key, value in source.items():
606
      env["INSTANCE_%s_%s" % (kind, key)] = value
607

    
608
  return env
609

    
610

    
611
def _NICListToTuple(lu, nics):
612
  """Build a list of nic information tuples.
613

614
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
615
  value in LUQueryInstanceData.
616

617
  @type lu:  L{LogicalUnit}
618
  @param lu: the logical unit on whose behalf we execute
619
  @type nics: list of L{objects.NIC}
620
  @param nics: list of nics to convert to hooks tuples
621

622
  """
623
  hooks_nics = []
624
  c_nicparams = lu.cfg.GetClusterInfo().nicparams[constants.PP_DEFAULT]
625
  for nic in nics:
626
    ip = nic.ip
627
    mac = nic.mac
628
    filled_params = objects.FillDict(c_nicparams, nic.nicparams)
629
    mode = filled_params[constants.NIC_MODE]
630
    link = filled_params[constants.NIC_LINK]
631
    hooks_nics.append((ip, mac, mode, link))
632
  return hooks_nics
633

    
634

    
635
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
636
  """Builds instance related env variables for hooks from an object.
637

638
  @type lu: L{LogicalUnit}
639
  @param lu: the logical unit on whose behalf we execute
640
  @type instance: L{objects.Instance}
641
  @param instance: the instance for which we should build the
642
      environment
643
  @type override: dict
644
  @param override: dictionary with key/values that will override
645
      our values
646
  @rtype: dict
647
  @return: the hook environment dictionary
648

649
  """
650
  cluster = lu.cfg.GetClusterInfo()
651
  bep = cluster.FillBE(instance)
652
  hvp = cluster.FillHV(instance)
653
  args = {
654
    'name': instance.name,
655
    'primary_node': instance.primary_node,
656
    'secondary_nodes': instance.secondary_nodes,
657
    'os_type': instance.os,
658
    'status': instance.admin_up,
659
    'memory': bep[constants.BE_MEMORY],
660
    'vcpus': bep[constants.BE_VCPUS],
661
    'nics': _NICListToTuple(lu, instance.nics),
662
    'disk_template': instance.disk_template,
663
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
664
    'bep': bep,
665
    'hvp': hvp,
666
    'hypervisor_name': instance.hypervisor,
667
  }
668
  if override:
669
    args.update(override)
670
  return _BuildInstanceHookEnv(**args)
671

    
672

    
673
def _AdjustCandidatePool(lu, exceptions):
674
  """Adjust the candidate pool after node operations.
675

676
  """
677
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
678
  if mod_list:
679
    lu.LogInfo("Promoted nodes to master candidate role: %s",
680
               ", ".join(node.name for node in mod_list))
681
    for name in mod_list:
682
      lu.context.ReaddNode(name)
683
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
684
  if mc_now > mc_max:
685
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
686
               (mc_now, mc_max))
687

    
688

    
689
def _DecideSelfPromotion(lu, exceptions=None):
690
  """Decide whether I should promote myself as a master candidate.
691

692
  """
693
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
694
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
695
  # the new node will increase mc_max with one, so:
696
  mc_should = min(mc_should + 1, cp_size)
697
  return mc_now < mc_should
698

    
699

    
700
def _CheckNicsBridgesExist(lu, target_nics, target_node,
701
                               profile=constants.PP_DEFAULT):
702
  """Check that the brigdes needed by a list of nics exist.
703

704
  """
705
  c_nicparams = lu.cfg.GetClusterInfo().nicparams[profile]
706
  paramslist = [objects.FillDict(c_nicparams, nic.nicparams)
707
                for nic in target_nics]
708
  brlist = [params[constants.NIC_LINK] for params in paramslist
709
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
710
  if brlist:
711
    result = lu.rpc.call_bridges_exist(target_node, brlist)
712
    result.Raise("Error checking bridges on destination node '%s'" %
713
                 target_node, prereq=True)
714

    
715

    
716
def _CheckInstanceBridgesExist(lu, instance, node=None):
717
  """Check that the brigdes needed by an instance exist.
718

719
  """
720
  if node is None:
721
    node = instance.primary_node
722
  _CheckNicsBridgesExist(lu, instance.nics, node)
723

    
724

    
725
def _GetNodeInstancesInner(cfg, fn):
726
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
727

    
728

    
729
def _GetNodeInstances(cfg, node_name):
730
  """Returns a list of all primary and secondary instances on a node.
731

732
  """
733

    
734
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
735

    
736

    
737
def _GetNodePrimaryInstances(cfg, node_name):
738
  """Returns primary instances on a node.
739

740
  """
741
  return _GetNodeInstancesInner(cfg,
742
                                lambda inst: node_name == inst.primary_node)
743

    
744

    
745
def _GetNodeSecondaryInstances(cfg, node_name):
746
  """Returns secondary instances on a node.
747

748
  """
749
  return _GetNodeInstancesInner(cfg,
750
                                lambda inst: node_name in inst.secondary_nodes)
751

    
752

    
753
def _GetStorageTypeArgs(cfg, storage_type):
754
  """Returns the arguments for a storage type.
755

756
  """
757
  # Special case for file storage
758
  if storage_type == constants.ST_FILE:
759
    # storage.FileStorage wants a list of storage directories
760
    return [[cfg.GetFileStorageDir()]]
761

    
762
  return []
763

    
764

    
765
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
766
  faulty = []
767

    
768
  for dev in instance.disks:
769
    cfg.SetDiskID(dev, node_name)
770

    
771
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
772
  result.Raise("Failed to get disk status from node %s" % node_name,
773
               prereq=prereq)
774

    
775
  for idx, bdev_status in enumerate(result.payload):
776
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
777
      faulty.append(idx)
778

    
779
  return faulty
780

    
781

    
782
class LUPostInitCluster(LogicalUnit):
783
  """Logical unit for running hooks after cluster initialization.
784

785
  """
786
  HPATH = "cluster-init"
787
  HTYPE = constants.HTYPE_CLUSTER
788
  _OP_REQP = []
789

    
790
  def BuildHooksEnv(self):
791
    """Build hooks env.
792

793
    """
794
    env = {"OP_TARGET": self.cfg.GetClusterName()}
795
    mn = self.cfg.GetMasterNode()
796
    return env, [], [mn]
797

    
798
  def CheckPrereq(self):
799
    """No prerequisites to check.
800

801
    """
802
    return True
803

    
804
  def Exec(self, feedback_fn):
805
    """Nothing to do.
806

807
    """
808
    return True
809

    
810

    
811
class LUDestroyCluster(LogicalUnit):
812
  """Logical unit for destroying the cluster.
813

814
  """
815
  HPATH = "cluster-destroy"
816
  HTYPE = constants.HTYPE_CLUSTER
817
  _OP_REQP = []
818

    
819
  def BuildHooksEnv(self):
820
    """Build hooks env.
821

822
    """
823
    env = {"OP_TARGET": self.cfg.GetClusterName()}
824
    return env, [], []
825

    
826
  def CheckPrereq(self):
827
    """Check prerequisites.
828

829
    This checks whether the cluster is empty.
830

831
    Any errors are signaled by raising errors.OpPrereqError.
832

833
    """
834
    master = self.cfg.GetMasterNode()
835

    
836
    nodelist = self.cfg.GetNodeList()
837
    if len(nodelist) != 1 or nodelist[0] != master:
838
      raise errors.OpPrereqError("There are still %d node(s) in"
839
                                 " this cluster." % (len(nodelist) - 1))
840
    instancelist = self.cfg.GetInstanceList()
841
    if instancelist:
842
      raise errors.OpPrereqError("There are still %d instance(s) in"
843
                                 " this cluster." % len(instancelist))
844

    
845
  def Exec(self, feedback_fn):
846
    """Destroys the cluster.
847

848
    """
849
    master = self.cfg.GetMasterNode()
850

    
851
    # Run post hooks on master node before it's removed
852
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
853
    try:
854
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
855
    except:
856
      self.LogWarning("Errors occurred running hooks on %s" % master)
857

    
858
    result = self.rpc.call_node_stop_master(master, False)
859
    result.Raise("Could not disable the master role")
860
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
861
    utils.CreateBackup(priv_key)
862
    utils.CreateBackup(pub_key)
863
    return master
864

    
865

    
866
class LUVerifyCluster(LogicalUnit):
867
  """Verifies the cluster status.
868

869
  """
870
  HPATH = "cluster-verify"
871
  HTYPE = constants.HTYPE_CLUSTER
872
  _OP_REQP = ["skip_checks", "verbose", "error_codes", "debug_simulate_errors"]
873
  REQ_BGL = False
874

    
875
  TCLUSTER = "cluster"
876
  TNODE = "node"
877
  TINSTANCE = "instance"
878

    
879
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
880
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
881
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
882
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
883
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
884
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
885
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
886
  ENODEDRBD = (TNODE, "ENODEDRBD")
887
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
888
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
889
  ENODEHV = (TNODE, "ENODEHV")
890
  ENODELVM = (TNODE, "ENODELVM")
891
  ENODEN1 = (TNODE, "ENODEN1")
892
  ENODENET = (TNODE, "ENODENET")
893
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
894
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
895
  ENODERPC = (TNODE, "ENODERPC")
896
  ENODESSH = (TNODE, "ENODESSH")
897
  ENODEVERSION = (TNODE, "ENODEVERSION")
898

    
899
  ETYPE_FIELD = "code"
900
  ETYPE_ERROR = "ERROR"
901
  ETYPE_WARNING = "WARNING"
902

    
903
  def ExpandNames(self):
904
    self.needed_locks = {
905
      locking.LEVEL_NODE: locking.ALL_SET,
906
      locking.LEVEL_INSTANCE: locking.ALL_SET,
907
    }
908
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
909

    
910
  def _Error(self, ecode, item, msg, *args, **kwargs):
911
    """Format an error message.
912

913
    Based on the opcode's error_codes parameter, either format a
914
    parseable error code, or a simpler error string.
915

916
    This must be called only from Exec and functions called from Exec.
917

918
    """
919
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
920
    itype, etxt = ecode
921
    # first complete the msg
922
    if args:
923
      msg = msg % args
924
    # then format the whole message
925
    if self.op.error_codes:
926
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
927
    else:
928
      if item:
929
        item = " " + item
930
      else:
931
        item = ""
932
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
933
    # and finally report it via the feedback_fn
934
    self._feedback_fn("  - %s" % msg)
935

    
936
  def _ErrorIf(self, cond, *args, **kwargs):
937
    """Log an error message if the passed condition is True.
938

939
    """
940
    cond = bool(cond) or self.op.debug_simulate_errors
941
    if cond:
942
      self._Error(*args, **kwargs)
943
    # do not mark the operation as failed for WARN cases only
944
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
945
      self.bad = self.bad or cond
946

    
947
  def _VerifyNode(self, nodeinfo, file_list, local_cksum,
948
                  node_result, master_files, drbd_map, vg_name):
949
    """Run multiple tests against a node.
950

951
    Test list:
952

953
      - compares ganeti version
954
      - checks vg existence and size > 20G
955
      - checks config file checksum
956
      - checks ssh to other nodes
957

958
    @type nodeinfo: L{objects.Node}
959
    @param nodeinfo: the node to check
960
    @param file_list: required list of files
961
    @param local_cksum: dictionary of local files and their checksums
962
    @param node_result: the results from the node
963
    @param master_files: list of files that only masters should have
964
    @param drbd_map: the useddrbd minors for this node, in
965
        form of minor: (instance, must_exist) which correspond to instances
966
        and their running status
967
    @param vg_name: Ganeti Volume Group (result of self.cfg.GetVGName())
968

969
    """
970
    node = nodeinfo.name
971
    _ErrorIf = self._ErrorIf
972

    
973
    # main result, node_result should be a non-empty dict
974
    test = not node_result or not isinstance(node_result, dict)
975
    _ErrorIf(test, self.ENODERPC, node,
976
                  "unable to verify node: no data returned")
977
    if test:
978
      return
979

    
980
    # compares ganeti version
981
    local_version = constants.PROTOCOL_VERSION
982
    remote_version = node_result.get('version', None)
983
    test = not (remote_version and
984
                isinstance(remote_version, (list, tuple)) and
985
                len(remote_version) == 2)
986
    _ErrorIf(test, self.ENODERPC, node,
987
             "connection to node returned invalid data")
988
    if test:
989
      return
990

    
991
    test = local_version != remote_version[0]
992
    _ErrorIf(test, self.ENODEVERSION, node,
993
             "incompatible protocol versions: master %s,"
994
             " node %s", local_version, remote_version[0])
995
    if test:
996
      return
997

    
998
    # node seems compatible, we can actually try to look into its results
999

    
1000
    # full package version
1001
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1002
                  self.ENODEVERSION, node,
1003
                  "software version mismatch: master %s, node %s",
1004
                  constants.RELEASE_VERSION, remote_version[1],
1005
                  code=self.ETYPE_WARNING)
1006

    
1007
    # checks vg existence and size > 20G
1008
    if vg_name is not None:
1009
      vglist = node_result.get(constants.NV_VGLIST, None)
1010
      test = not vglist
1011
      _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1012
      if not test:
1013
        vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1014
                                              constants.MIN_VG_SIZE)
1015
        _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1016

    
1017
    # checks config file checksum
1018

    
1019
    remote_cksum = node_result.get(constants.NV_FILELIST, None)
1020
    test = not isinstance(remote_cksum, dict)
1021
    _ErrorIf(test, self.ENODEFILECHECK, node,
1022
             "node hasn't returned file checksum data")
1023
    if not test:
1024
      for file_name in file_list:
1025
        node_is_mc = nodeinfo.master_candidate
1026
        must_have = (file_name not in master_files) or node_is_mc
1027
        # missing
1028
        test1 = file_name not in remote_cksum
1029
        # invalid checksum
1030
        test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1031
        # existing and good
1032
        test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1033
        _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1034
                 "file '%s' missing", file_name)
1035
        _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1036
                 "file '%s' has wrong checksum", file_name)
1037
        # not candidate and this is not a must-have file
1038
        _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1039
                 "file '%s' should not exist on non master"
1040
                 " candidates (and the file is outdated)", file_name)
1041
        # all good, except non-master/non-must have combination
1042
        _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1043
                 "file '%s' should not exist"
1044
                 " on non master candidates", file_name)
1045

    
1046
    # checks ssh to any
1047

    
1048
    test = constants.NV_NODELIST not in node_result
1049
    _ErrorIf(test, self.ENODESSH, node,
1050
             "node hasn't returned node ssh connectivity data")
1051
    if not test:
1052
      if node_result[constants.NV_NODELIST]:
1053
        for a_node, a_msg in node_result[constants.NV_NODELIST].items():
1054
          _ErrorIf(True, self.ENODESSH, node,
1055
                   "ssh communication with node '%s': %s", a_node, a_msg)
1056

    
1057
    test = constants.NV_NODENETTEST not in node_result
1058
    _ErrorIf(test, self.ENODENET, node,
1059
             "node hasn't returned node tcp connectivity data")
1060
    if not test:
1061
      if node_result[constants.NV_NODENETTEST]:
1062
        nlist = utils.NiceSort(node_result[constants.NV_NODENETTEST].keys())
1063
        for anode in nlist:
1064
          _ErrorIf(True, self.ENODENET, node,
1065
                   "tcp communication with node '%s': %s",
1066
                   anode, node_result[constants.NV_NODENETTEST][anode])
1067

    
1068
    hyp_result = node_result.get(constants.NV_HYPERVISOR, None)
1069
    if isinstance(hyp_result, dict):
1070
      for hv_name, hv_result in hyp_result.iteritems():
1071
        test = hv_result is not None
1072
        _ErrorIf(test, self.ENODEHV, node,
1073
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1074

    
1075
    # check used drbd list
1076
    if vg_name is not None:
1077
      used_minors = node_result.get(constants.NV_DRBDLIST, [])
1078
      test = not isinstance(used_minors, (tuple, list))
1079
      _ErrorIf(test, self.ENODEDRBD, node,
1080
               "cannot parse drbd status file: %s", str(used_minors))
1081
      if not test:
1082
        for minor, (iname, must_exist) in drbd_map.items():
1083
          test = minor not in used_minors and must_exist
1084
          _ErrorIf(test, self.ENODEDRBD, node,
1085
                   "drbd minor %d of instance %s is not active",
1086
                   minor, iname)
1087
        for minor in used_minors:
1088
          test = minor not in drbd_map
1089
          _ErrorIf(test, self.ENODEDRBD, node,
1090
                   "unallocated drbd minor %d is in use", minor)
1091

    
1092
  def _VerifyInstance(self, instance, instanceconfig, node_vol_is,
1093
                      node_instance, n_offline):
1094
    """Verify an instance.
1095

1096
    This function checks to see if the required block devices are
1097
    available on the instance's node.
1098

1099
    """
1100
    _ErrorIf = self._ErrorIf
1101
    node_current = instanceconfig.primary_node
1102

    
1103
    node_vol_should = {}
1104
    instanceconfig.MapLVsByNode(node_vol_should)
1105

    
1106
    for node in node_vol_should:
1107
      if node in n_offline:
1108
        # ignore missing volumes on offline nodes
1109
        continue
1110
      for volume in node_vol_should[node]:
1111
        test = node not in node_vol_is or volume not in node_vol_is[node]
1112
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1113
                 "volume %s missing on node %s", volume, node)
1114

    
1115
    if instanceconfig.admin_up:
1116
      test = ((node_current not in node_instance or
1117
               not instance in node_instance[node_current]) and
1118
              node_current not in n_offline)
1119
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1120
               "instance not running on its primary node %s",
1121
               node_current)
1122

    
1123
    for node in node_instance:
1124
      if (not node == node_current):
1125
        test = instance in node_instance[node]
1126
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1127
                 "instance should not run on node %s", node)
1128

    
1129
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is):
1130
    """Verify if there are any unknown volumes in the cluster.
1131

1132
    The .os, .swap and backup volumes are ignored. All other volumes are
1133
    reported as unknown.
1134

1135
    """
1136
    for node in node_vol_is:
1137
      for volume in node_vol_is[node]:
1138
        test = (node not in node_vol_should or
1139
                volume not in node_vol_should[node])
1140
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1141
                      "volume %s is unknown", volume)
1142

    
1143
  def _VerifyOrphanInstances(self, instancelist, node_instance):
1144
    """Verify the list of running instances.
1145

1146
    This checks what instances are running but unknown to the cluster.
1147

1148
    """
1149
    for node in node_instance:
1150
      for o_inst in node_instance[node]:
1151
        test = o_inst not in instancelist
1152
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1153
                      "instance %s on node %s should not exist", o_inst, node)
1154

    
1155
  def _VerifyNPlusOneMemory(self, node_info, instance_cfg):
1156
    """Verify N+1 Memory Resilience.
1157

1158
    Check that if one single node dies we can still start all the instances it
1159
    was primary for.
1160

1161
    """
1162
    for node, nodeinfo in node_info.iteritems():
1163
      # This code checks that every node which is now listed as secondary has
1164
      # enough memory to host all instances it is supposed to should a single
1165
      # other node in the cluster fail.
1166
      # FIXME: not ready for failover to an arbitrary node
1167
      # FIXME: does not support file-backed instances
1168
      # WARNING: we currently take into account down instances as well as up
1169
      # ones, considering that even if they're down someone might want to start
1170
      # them even in the event of a node failure.
1171
      for prinode, instances in nodeinfo['sinst-by-pnode'].iteritems():
1172
        needed_mem = 0
1173
        for instance in instances:
1174
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1175
          if bep[constants.BE_AUTO_BALANCE]:
1176
            needed_mem += bep[constants.BE_MEMORY]
1177
        test = nodeinfo['mfree'] < needed_mem
1178
        self._ErrorIf(test, self.ENODEN1, node,
1179
                      "not enough memory on to accommodate"
1180
                      " failovers should peer node %s fail", prinode)
1181

    
1182
  def CheckPrereq(self):
1183
    """Check prerequisites.
1184

1185
    Transform the list of checks we're going to skip into a set and check that
1186
    all its members are valid.
1187

1188
    """
1189
    self.skip_set = frozenset(self.op.skip_checks)
1190
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
1191
      raise errors.OpPrereqError("Invalid checks to be skipped specified")
1192

    
1193
  def BuildHooksEnv(self):
1194
    """Build hooks env.
1195

1196
    Cluster-Verify hooks just ran in the post phase and their failure makes
1197
    the output be logged in the verify output and the verification to fail.
1198

1199
    """
1200
    all_nodes = self.cfg.GetNodeList()
1201
    env = {
1202
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
1203
      }
1204
    for node in self.cfg.GetAllNodesInfo().values():
1205
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
1206

    
1207
    return env, [], all_nodes
1208

    
1209
  def Exec(self, feedback_fn):
1210
    """Verify integrity of cluster, performing various test on nodes.
1211

1212
    """
1213
    self.bad = False
1214
    _ErrorIf = self._ErrorIf
1215
    verbose = self.op.verbose
1216
    self._feedback_fn = feedback_fn
1217
    feedback_fn("* Verifying global settings")
1218
    for msg in self.cfg.VerifyConfig():
1219
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
1220

    
1221
    vg_name = self.cfg.GetVGName()
1222
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
1223
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
1224
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
1225
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
1226
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
1227
                        for iname in instancelist)
1228
    i_non_redundant = [] # Non redundant instances
1229
    i_non_a_balanced = [] # Non auto-balanced instances
1230
    n_offline = [] # List of offline nodes
1231
    n_drained = [] # List of nodes being drained
1232
    node_volume = {}
1233
    node_instance = {}
1234
    node_info = {}
1235
    instance_cfg = {}
1236

    
1237
    # FIXME: verify OS list
1238
    # do local checksums
1239
    master_files = [constants.CLUSTER_CONF_FILE]
1240

    
1241
    file_names = ssconf.SimpleStore().GetFileList()
1242
    file_names.append(constants.SSL_CERT_FILE)
1243
    file_names.append(constants.RAPI_CERT_FILE)
1244
    file_names.extend(master_files)
1245

    
1246
    local_checksums = utils.FingerprintFiles(file_names)
1247

    
1248
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
1249
    node_verify_param = {
1250
      constants.NV_FILELIST: file_names,
1251
      constants.NV_NODELIST: [node.name for node in nodeinfo
1252
                              if not node.offline],
1253
      constants.NV_HYPERVISOR: hypervisors,
1254
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
1255
                                  node.secondary_ip) for node in nodeinfo
1256
                                 if not node.offline],
1257
      constants.NV_INSTANCELIST: hypervisors,
1258
      constants.NV_VERSION: None,
1259
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
1260
      }
1261
    if vg_name is not None:
1262
      node_verify_param[constants.NV_VGLIST] = None
1263
      node_verify_param[constants.NV_LVLIST] = vg_name
1264
      node_verify_param[constants.NV_DRBDLIST] = None
1265
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
1266
                                           self.cfg.GetClusterName())
1267

    
1268
    cluster = self.cfg.GetClusterInfo()
1269
    master_node = self.cfg.GetMasterNode()
1270
    all_drbd_map = self.cfg.ComputeDRBDMap()
1271

    
1272
    feedback_fn("* Verifying node status")
1273
    for node_i in nodeinfo:
1274
      node = node_i.name
1275

    
1276
      if node_i.offline:
1277
        if verbose:
1278
          feedback_fn("* Skipping offline node %s" % (node,))
1279
        n_offline.append(node)
1280
        continue
1281

    
1282
      if node == master_node:
1283
        ntype = "master"
1284
      elif node_i.master_candidate:
1285
        ntype = "master candidate"
1286
      elif node_i.drained:
1287
        ntype = "drained"
1288
        n_drained.append(node)
1289
      else:
1290
        ntype = "regular"
1291
      if verbose:
1292
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
1293

    
1294
      msg = all_nvinfo[node].fail_msg
1295
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
1296
      if msg:
1297
        continue
1298

    
1299
      nresult = all_nvinfo[node].payload
1300
      node_drbd = {}
1301
      for minor, instance in all_drbd_map[node].items():
1302
        test = instance not in instanceinfo
1303
        _ErrorIf(test, self.ECLUSTERCFG, None,
1304
                 "ghost instance '%s' in temporary DRBD map", instance)
1305
          # ghost instance should not be running, but otherwise we
1306
          # don't give double warnings (both ghost instance and
1307
          # unallocated minor in use)
1308
        if test:
1309
          node_drbd[minor] = (instance, False)
1310
        else:
1311
          instance = instanceinfo[instance]
1312
          node_drbd[minor] = (instance.name, instance.admin_up)
1313
      self._VerifyNode(node_i, file_names, local_checksums,
1314
                       nresult, master_files, node_drbd, vg_name)
1315

    
1316
      lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1317
      if vg_name is None:
1318
        node_volume[node] = {}
1319
      elif isinstance(lvdata, basestring):
1320
        _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1321
                 utils.SafeEncode(lvdata))
1322
        node_volume[node] = {}
1323
      elif not isinstance(lvdata, dict):
1324
        _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1325
        continue
1326
      else:
1327
        node_volume[node] = lvdata
1328

    
1329
      # node_instance
1330
      idata = nresult.get(constants.NV_INSTANCELIST, None)
1331
      test = not isinstance(idata, list)
1332
      _ErrorIf(test, self.ENODEHV, node,
1333
               "rpc call to node failed (instancelist)")
1334
      if test:
1335
        continue
1336

    
1337
      node_instance[node] = idata
1338

    
1339
      # node_info
1340
      nodeinfo = nresult.get(constants.NV_HVINFO, None)
1341
      test = not isinstance(nodeinfo, dict)
1342
      _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1343
      if test:
1344
        continue
1345

    
1346
      try:
1347
        node_info[node] = {
1348
          "mfree": int(nodeinfo['memory_free']),
1349
          "pinst": [],
1350
          "sinst": [],
1351
          # dictionary holding all instances this node is secondary for,
1352
          # grouped by their primary node. Each key is a cluster node, and each
1353
          # value is a list of instances which have the key as primary and the
1354
          # current node as secondary.  this is handy to calculate N+1 memory
1355
          # availability if you can only failover from a primary to its
1356
          # secondary.
1357
          "sinst-by-pnode": {},
1358
        }
1359
        # FIXME: devise a free space model for file based instances as well
1360
        if vg_name is not None:
1361
          test = (constants.NV_VGLIST not in nresult or
1362
                  vg_name not in nresult[constants.NV_VGLIST])
1363
          _ErrorIf(test, self.ENODELVM, node,
1364
                   "node didn't return data for the volume group '%s'"
1365
                   " - it is either missing or broken", vg_name)
1366
          if test:
1367
            continue
1368
          node_info[node]["dfree"] = int(nresult[constants.NV_VGLIST][vg_name])
1369
      except (ValueError, KeyError):
1370
        _ErrorIf(True, self.ENODERPC, node,
1371
                 "node returned invalid nodeinfo, check lvm/hypervisor")
1372
        continue
1373

    
1374
    node_vol_should = {}
1375

    
1376
    feedback_fn("* Verifying instance status")
1377
    for instance in instancelist:
1378
      if verbose:
1379
        feedback_fn("* Verifying instance %s" % instance)
1380
      inst_config = instanceinfo[instance]
1381
      self._VerifyInstance(instance, inst_config, node_volume,
1382
                           node_instance, n_offline)
1383
      inst_nodes_offline = []
1384

    
1385
      inst_config.MapLVsByNode(node_vol_should)
1386

    
1387
      instance_cfg[instance] = inst_config
1388

    
1389
      pnode = inst_config.primary_node
1390
      _ErrorIf(pnode not in node_info and pnode not in n_offline,
1391
               self.ENODERPC, pnode, "instance %s, connection to"
1392
               " primary node failed", instance)
1393
      if pnode in node_info:
1394
        node_info[pnode]['pinst'].append(instance)
1395

    
1396
      if pnode in n_offline:
1397
        inst_nodes_offline.append(pnode)
1398

    
1399
      # If the instance is non-redundant we cannot survive losing its primary
1400
      # node, so we are not N+1 compliant. On the other hand we have no disk
1401
      # templates with more than one secondary so that situation is not well
1402
      # supported either.
1403
      # FIXME: does not support file-backed instances
1404
      if len(inst_config.secondary_nodes) == 0:
1405
        i_non_redundant.append(instance)
1406
      _ErrorIf(len(inst_config.secondary_nodes) > 1,
1407
               self.EINSTANCELAYOUT, instance,
1408
               "instance has multiple secondary nodes", code="WARNING")
1409

    
1410
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1411
        i_non_a_balanced.append(instance)
1412

    
1413
      for snode in inst_config.secondary_nodes:
1414
        _ErrorIf(snode not in node_info and snode not in n_offline,
1415
                 self.ENODERPC, snode,
1416
                 "instance %s, connection to secondary node"
1417
                 "failed", instance)
1418

    
1419
        if snode in node_info:
1420
          node_info[snode]['sinst'].append(instance)
1421
          if pnode not in node_info[snode]['sinst-by-pnode']:
1422
            node_info[snode]['sinst-by-pnode'][pnode] = []
1423
          node_info[snode]['sinst-by-pnode'][pnode].append(instance)
1424

    
1425
        if snode in n_offline:
1426
          inst_nodes_offline.append(snode)
1427

    
1428
      # warn that the instance lives on offline nodes
1429
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
1430
               "instance lives on offline node(s) %s",
1431
               ", ".join(inst_nodes_offline))
1432

    
1433
    feedback_fn("* Verifying orphan volumes")
1434
    self._VerifyOrphanVolumes(node_vol_should, node_volume)
1435

    
1436
    feedback_fn("* Verifying remaining instances")
1437
    self._VerifyOrphanInstances(instancelist, node_instance)
1438

    
1439
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1440
      feedback_fn("* Verifying N+1 Memory redundancy")
1441
      self._VerifyNPlusOneMemory(node_info, instance_cfg)
1442

    
1443
    feedback_fn("* Other Notes")
1444
    if i_non_redundant:
1445
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1446
                  % len(i_non_redundant))
1447

    
1448
    if i_non_a_balanced:
1449
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1450
                  % len(i_non_a_balanced))
1451

    
1452
    if n_offline:
1453
      feedback_fn("  - NOTICE: %d offline node(s) found." % len(n_offline))
1454

    
1455
    if n_drained:
1456
      feedback_fn("  - NOTICE: %d drained node(s) found." % len(n_drained))
1457

    
1458
    return not self.bad
1459

    
1460
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1461
    """Analyze the post-hooks' result
1462

1463
    This method analyses the hook result, handles it, and sends some
1464
    nicely-formatted feedback back to the user.
1465

1466
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1467
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1468
    @param hooks_results: the results of the multi-node hooks rpc call
1469
    @param feedback_fn: function used send feedback back to the caller
1470
    @param lu_result: previous Exec result
1471
    @return: the new Exec result, based on the previous result
1472
        and hook results
1473

1474
    """
1475
    # We only really run POST phase hooks, and are only interested in
1476
    # their results
1477
    if phase == constants.HOOKS_PHASE_POST:
1478
      # Used to change hooks' output to proper indentation
1479
      indent_re = re.compile('^', re.M)
1480
      feedback_fn("* Hooks Results")
1481
      assert hooks_results, "invalid result from hooks"
1482

    
1483
      for node_name in hooks_results:
1484
        show_node_header = True
1485
        res = hooks_results[node_name]
1486
        msg = res.fail_msg
1487
        test = msg and not res.offline
1488
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
1489
                      "Communication failure in hooks execution: %s", msg)
1490
        if test:
1491
          # override manually lu_result here as _ErrorIf only
1492
          # overrides self.bad
1493
          lu_result = 1
1494
          continue
1495
        for script, hkr, output in res.payload:
1496
          test = hkr == constants.HKR_FAIL
1497
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
1498
                        "Script %s failed, output:", script)
1499
          if test:
1500
            output = indent_re.sub('      ', output)
1501
            feedback_fn("%s" % output)
1502
            lu_result = 1
1503

    
1504
      return lu_result
1505

    
1506

    
1507
class LUVerifyDisks(NoHooksLU):
1508
  """Verifies the cluster disks status.
1509

1510
  """
1511
  _OP_REQP = []
1512
  REQ_BGL = False
1513

    
1514
  def ExpandNames(self):
1515
    self.needed_locks = {
1516
      locking.LEVEL_NODE: locking.ALL_SET,
1517
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1518
    }
1519
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1520

    
1521
  def CheckPrereq(self):
1522
    """Check prerequisites.
1523

1524
    This has no prerequisites.
1525

1526
    """
1527
    pass
1528

    
1529
  def Exec(self, feedback_fn):
1530
    """Verify integrity of cluster disks.
1531

1532
    @rtype: tuple of three items
1533
    @return: a tuple of (dict of node-to-node_error, list of instances
1534
        which need activate-disks, dict of instance: (node, volume) for
1535
        missing volumes
1536

1537
    """
1538
    result = res_nodes, res_instances, res_missing = {}, [], {}
1539

    
1540
    vg_name = self.cfg.GetVGName()
1541
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1542
    instances = [self.cfg.GetInstanceInfo(name)
1543
                 for name in self.cfg.GetInstanceList()]
1544

    
1545
    nv_dict = {}
1546
    for inst in instances:
1547
      inst_lvs = {}
1548
      if (not inst.admin_up or
1549
          inst.disk_template not in constants.DTS_NET_MIRROR):
1550
        continue
1551
      inst.MapLVsByNode(inst_lvs)
1552
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1553
      for node, vol_list in inst_lvs.iteritems():
1554
        for vol in vol_list:
1555
          nv_dict[(node, vol)] = inst
1556

    
1557
    if not nv_dict:
1558
      return result
1559

    
1560
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
1561

    
1562
    for node in nodes:
1563
      # node_volume
1564
      node_res = node_lvs[node]
1565
      if node_res.offline:
1566
        continue
1567
      msg = node_res.fail_msg
1568
      if msg:
1569
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
1570
        res_nodes[node] = msg
1571
        continue
1572

    
1573
      lvs = node_res.payload
1574
      for lv_name, (_, lv_inactive, lv_online) in lvs.items():
1575
        inst = nv_dict.pop((node, lv_name), None)
1576
        if (not lv_online and inst is not None
1577
            and inst.name not in res_instances):
1578
          res_instances.append(inst.name)
1579

    
1580
    # any leftover items in nv_dict are missing LVs, let's arrange the
1581
    # data better
1582
    for key, inst in nv_dict.iteritems():
1583
      if inst.name not in res_missing:
1584
        res_missing[inst.name] = []
1585
      res_missing[inst.name].append(key)
1586

    
1587
    return result
1588

    
1589

    
1590
class LURepairDiskSizes(NoHooksLU):
1591
  """Verifies the cluster disks sizes.
1592

1593
  """
1594
  _OP_REQP = ["instances"]
1595
  REQ_BGL = False
1596

    
1597
  def ExpandNames(self):
1598
    if not isinstance(self.op.instances, list):
1599
      raise errors.OpPrereqError("Invalid argument type 'instances'")
1600

    
1601
    if self.op.instances:
1602
      self.wanted_names = []
1603
      for name in self.op.instances:
1604
        full_name = self.cfg.ExpandInstanceName(name)
1605
        if full_name is None:
1606
          raise errors.OpPrereqError("Instance '%s' not known" % name)
1607
        self.wanted_names.append(full_name)
1608
      self.needed_locks = {
1609
        locking.LEVEL_NODE: [],
1610
        locking.LEVEL_INSTANCE: self.wanted_names,
1611
        }
1612
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
1613
    else:
1614
      self.wanted_names = None
1615
      self.needed_locks = {
1616
        locking.LEVEL_NODE: locking.ALL_SET,
1617
        locking.LEVEL_INSTANCE: locking.ALL_SET,
1618
        }
1619
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
1620

    
1621
  def DeclareLocks(self, level):
1622
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
1623
      self._LockInstancesNodes(primary_only=True)
1624

    
1625
  def CheckPrereq(self):
1626
    """Check prerequisites.
1627

1628
    This only checks the optional instance list against the existing names.
1629

1630
    """
1631
    if self.wanted_names is None:
1632
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
1633

    
1634
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
1635
                             in self.wanted_names]
1636

    
1637
  def _EnsureChildSizes(self, disk):
1638
    """Ensure children of the disk have the needed disk size.
1639

1640
    This is valid mainly for DRBD8 and fixes an issue where the
1641
    children have smaller disk size.
1642

1643
    @param disk: an L{ganeti.objects.Disk} object
1644

1645
    """
1646
    if disk.dev_type == constants.LD_DRBD8:
1647
      assert disk.children, "Empty children for DRBD8?"
1648
      fchild = disk.children[0]
1649
      mismatch = fchild.size < disk.size
1650
      if mismatch:
1651
        self.LogInfo("Child disk has size %d, parent %d, fixing",
1652
                     fchild.size, disk.size)
1653
        fchild.size = disk.size
1654

    
1655
      # and we recurse on this child only, not on the metadev
1656
      return self._EnsureChildSizes(fchild) or mismatch
1657
    else:
1658
      return False
1659

    
1660
  def Exec(self, feedback_fn):
1661
    """Verify the size of cluster disks.
1662

1663
    """
1664
    # TODO: check child disks too
1665
    # TODO: check differences in size between primary/secondary nodes
1666
    per_node_disks = {}
1667
    for instance in self.wanted_instances:
1668
      pnode = instance.primary_node
1669
      if pnode not in per_node_disks:
1670
        per_node_disks[pnode] = []
1671
      for idx, disk in enumerate(instance.disks):
1672
        per_node_disks[pnode].append((instance, idx, disk))
1673

    
1674
    changed = []
1675
    for node, dskl in per_node_disks.items():
1676
      newl = [v[2].Copy() for v in dskl]
1677
      for dsk in newl:
1678
        self.cfg.SetDiskID(dsk, node)
1679
      result = self.rpc.call_blockdev_getsizes(node, newl)
1680
      if result.fail_msg:
1681
        self.LogWarning("Failure in blockdev_getsizes call to node"
1682
                        " %s, ignoring", node)
1683
        continue
1684
      if len(result.data) != len(dskl):
1685
        self.LogWarning("Invalid result from node %s, ignoring node results",
1686
                        node)
1687
        continue
1688
      for ((instance, idx, disk), size) in zip(dskl, result.data):
1689
        if size is None:
1690
          self.LogWarning("Disk %d of instance %s did not return size"
1691
                          " information, ignoring", idx, instance.name)
1692
          continue
1693
        if not isinstance(size, (int, long)):
1694
          self.LogWarning("Disk %d of instance %s did not return valid"
1695
                          " size information, ignoring", idx, instance.name)
1696
          continue
1697
        size = size >> 20
1698
        if size != disk.size:
1699
          self.LogInfo("Disk %d of instance %s has mismatched size,"
1700
                       " correcting: recorded %d, actual %d", idx,
1701
                       instance.name, disk.size, size)
1702
          disk.size = size
1703
          self.cfg.Update(instance)
1704
          changed.append((instance.name, idx, size))
1705
        if self._EnsureChildSizes(disk):
1706
          self.cfg.Update(instance)
1707
          changed.append((instance.name, idx, disk.size))
1708
    return changed
1709

    
1710

    
1711
class LURenameCluster(LogicalUnit):
1712
  """Rename the cluster.
1713

1714
  """
1715
  HPATH = "cluster-rename"
1716
  HTYPE = constants.HTYPE_CLUSTER
1717
  _OP_REQP = ["name"]
1718

    
1719
  def BuildHooksEnv(self):
1720
    """Build hooks env.
1721

1722
    """
1723
    env = {
1724
      "OP_TARGET": self.cfg.GetClusterName(),
1725
      "NEW_NAME": self.op.name,
1726
      }
1727
    mn = self.cfg.GetMasterNode()
1728
    return env, [mn], [mn]
1729

    
1730
  def CheckPrereq(self):
1731
    """Verify that the passed name is a valid one.
1732

1733
    """
1734
    hostname = utils.HostInfo(self.op.name)
1735

    
1736
    new_name = hostname.name
1737
    self.ip = new_ip = hostname.ip
1738
    old_name = self.cfg.GetClusterName()
1739
    old_ip = self.cfg.GetMasterIP()
1740
    if new_name == old_name and new_ip == old_ip:
1741
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1742
                                 " cluster has changed")
1743
    if new_ip != old_ip:
1744
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1745
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1746
                                   " reachable on the network. Aborting." %
1747
                                   new_ip)
1748

    
1749
    self.op.name = new_name
1750

    
1751
  def Exec(self, feedback_fn):
1752
    """Rename the cluster.
1753

1754
    """
1755
    clustername = self.op.name
1756
    ip = self.ip
1757

    
1758
    # shutdown the master IP
1759
    master = self.cfg.GetMasterNode()
1760
    result = self.rpc.call_node_stop_master(master, False)
1761
    result.Raise("Could not disable the master role")
1762

    
1763
    try:
1764
      cluster = self.cfg.GetClusterInfo()
1765
      cluster.cluster_name = clustername
1766
      cluster.master_ip = ip
1767
      self.cfg.Update(cluster)
1768

    
1769
      # update the known hosts file
1770
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
1771
      node_list = self.cfg.GetNodeList()
1772
      try:
1773
        node_list.remove(master)
1774
      except ValueError:
1775
        pass
1776
      result = self.rpc.call_upload_file(node_list,
1777
                                         constants.SSH_KNOWN_HOSTS_FILE)
1778
      for to_node, to_result in result.iteritems():
1779
        msg = to_result.fail_msg
1780
        if msg:
1781
          msg = ("Copy of file %s to node %s failed: %s" %
1782
                 (constants.SSH_KNOWN_HOSTS_FILE, to_node, msg))
1783
          self.proc.LogWarning(msg)
1784

    
1785
    finally:
1786
      result = self.rpc.call_node_start_master(master, False, False)
1787
      msg = result.fail_msg
1788
      if msg:
1789
        self.LogWarning("Could not re-enable the master role on"
1790
                        " the master, please restart manually: %s", msg)
1791

    
1792

    
1793
def _RecursiveCheckIfLVMBased(disk):
1794
  """Check if the given disk or its children are lvm-based.
1795

1796
  @type disk: L{objects.Disk}
1797
  @param disk: the disk to check
1798
  @rtype: boolean
1799
  @return: boolean indicating whether a LD_LV dev_type was found or not
1800

1801
  """
1802
  if disk.children:
1803
    for chdisk in disk.children:
1804
      if _RecursiveCheckIfLVMBased(chdisk):
1805
        return True
1806
  return disk.dev_type == constants.LD_LV
1807

    
1808

    
1809
class LUSetClusterParams(LogicalUnit):
1810
  """Change the parameters of the cluster.
1811

1812
  """
1813
  HPATH = "cluster-modify"
1814
  HTYPE = constants.HTYPE_CLUSTER
1815
  _OP_REQP = []
1816
  REQ_BGL = False
1817

    
1818
  def CheckArguments(self):
1819
    """Check parameters
1820

1821
    """
1822
    if not hasattr(self.op, "candidate_pool_size"):
1823
      self.op.candidate_pool_size = None
1824
    if self.op.candidate_pool_size is not None:
1825
      try:
1826
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
1827
      except (ValueError, TypeError), err:
1828
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
1829
                                   str(err))
1830
      if self.op.candidate_pool_size < 1:
1831
        raise errors.OpPrereqError("At least one master candidate needed")
1832

    
1833
  def ExpandNames(self):
1834
    # FIXME: in the future maybe other cluster params won't require checking on
1835
    # all nodes to be modified.
1836
    self.needed_locks = {
1837
      locking.LEVEL_NODE: locking.ALL_SET,
1838
    }
1839
    self.share_locks[locking.LEVEL_NODE] = 1
1840

    
1841
  def BuildHooksEnv(self):
1842
    """Build hooks env.
1843

1844
    """
1845
    env = {
1846
      "OP_TARGET": self.cfg.GetClusterName(),
1847
      "NEW_VG_NAME": self.op.vg_name,
1848
      }
1849
    mn = self.cfg.GetMasterNode()
1850
    return env, [mn], [mn]
1851

    
1852
  def CheckPrereq(self):
1853
    """Check prerequisites.
1854

1855
    This checks whether the given params don't conflict and
1856
    if the given volume group is valid.
1857

1858
    """
1859
    if self.op.vg_name is not None and not self.op.vg_name:
1860
      instances = self.cfg.GetAllInstancesInfo().values()
1861
      for inst in instances:
1862
        for disk in inst.disks:
1863
          if _RecursiveCheckIfLVMBased(disk):
1864
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1865
                                       " lvm-based instances exist")
1866

    
1867
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1868

    
1869
    # if vg_name not None, checks given volume group on all nodes
1870
    if self.op.vg_name:
1871
      vglist = self.rpc.call_vg_list(node_list)
1872
      for node in node_list:
1873
        msg = vglist[node].fail_msg
1874
        if msg:
1875
          # ignoring down node
1876
          self.LogWarning("Error while gathering data on node %s"
1877
                          " (ignoring node): %s", node, msg)
1878
          continue
1879
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
1880
                                              self.op.vg_name,
1881
                                              constants.MIN_VG_SIZE)
1882
        if vgstatus:
1883
          raise errors.OpPrereqError("Error on node '%s': %s" %
1884
                                     (node, vgstatus))
1885

    
1886
    self.cluster = cluster = self.cfg.GetClusterInfo()
1887
    # validate params changes
1888
    if self.op.beparams:
1889
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
1890
      self.new_beparams = objects.FillDict(
1891
        cluster.beparams[constants.PP_DEFAULT], self.op.beparams)
1892

    
1893
    if self.op.nicparams:
1894
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
1895
      self.new_nicparams = objects.FillDict(
1896
        cluster.nicparams[constants.PP_DEFAULT], self.op.nicparams)
1897
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
1898

    
1899
    # hypervisor list/parameters
1900
    self.new_hvparams = objects.FillDict(cluster.hvparams, {})
1901
    if self.op.hvparams:
1902
      if not isinstance(self.op.hvparams, dict):
1903
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input")
1904
      for hv_name, hv_dict in self.op.hvparams.items():
1905
        if hv_name not in self.new_hvparams:
1906
          self.new_hvparams[hv_name] = hv_dict
1907
        else:
1908
          self.new_hvparams[hv_name].update(hv_dict)
1909

    
1910
    if self.op.enabled_hypervisors is not None:
1911
      self.hv_list = self.op.enabled_hypervisors
1912
      if not self.hv_list:
1913
        raise errors.OpPrereqError("Enabled hypervisors list must contain at"
1914
                                   " least one member")
1915
      invalid_hvs = set(self.hv_list) - constants.HYPER_TYPES
1916
      if invalid_hvs:
1917
        raise errors.OpPrereqError("Enabled hypervisors contains invalid"
1918
                                   " entries: %s" %
1919
                                   utils.CommaJoin(invalid_hvs))
1920
    else:
1921
      self.hv_list = cluster.enabled_hypervisors
1922

    
1923
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
1924
      # either the enabled list has changed, or the parameters have, validate
1925
      for hv_name, hv_params in self.new_hvparams.items():
1926
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
1927
            (self.op.enabled_hypervisors and
1928
             hv_name in self.op.enabled_hypervisors)):
1929
          # either this is a new hypervisor, or its parameters have changed
1930
          hv_class = hypervisor.GetHypervisor(hv_name)
1931
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
1932
          hv_class.CheckParameterSyntax(hv_params)
1933
          _CheckHVParams(self, node_list, hv_name, hv_params)
1934

    
1935
  def Exec(self, feedback_fn):
1936
    """Change the parameters of the cluster.
1937

1938
    """
1939
    if self.op.vg_name is not None:
1940
      new_volume = self.op.vg_name
1941
      if not new_volume:
1942
        new_volume = None
1943
      if new_volume != self.cfg.GetVGName():
1944
        self.cfg.SetVGName(new_volume)
1945
      else:
1946
        feedback_fn("Cluster LVM configuration already in desired"
1947
                    " state, not changing")
1948
    if self.op.hvparams:
1949
      self.cluster.hvparams = self.new_hvparams
1950
    if self.op.enabled_hypervisors is not None:
1951
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
1952
    if self.op.beparams:
1953
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
1954
    if self.op.nicparams:
1955
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
1956

    
1957
    if self.op.candidate_pool_size is not None:
1958
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
1959
      # we need to update the pool size here, otherwise the save will fail
1960
      _AdjustCandidatePool(self, [])
1961

    
1962
    self.cfg.Update(self.cluster)
1963

    
1964

    
1965
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
1966
  """Distribute additional files which are part of the cluster configuration.
1967

1968
  ConfigWriter takes care of distributing the config and ssconf files, but
1969
  there are more files which should be distributed to all nodes. This function
1970
  makes sure those are copied.
1971

1972
  @param lu: calling logical unit
1973
  @param additional_nodes: list of nodes not in the config to distribute to
1974

1975
  """
1976
  # 1. Gather target nodes
1977
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
1978
  dist_nodes = lu.cfg.GetNodeList()
1979
  if additional_nodes is not None:
1980
    dist_nodes.extend(additional_nodes)
1981
  if myself.name in dist_nodes:
1982
    dist_nodes.remove(myself.name)
1983
  # 2. Gather files to distribute
1984
  dist_files = set([constants.ETC_HOSTS,
1985
                    constants.SSH_KNOWN_HOSTS_FILE,
1986
                    constants.RAPI_CERT_FILE,
1987
                    constants.RAPI_USERS_FILE,
1988
                    constants.HMAC_CLUSTER_KEY,
1989
                   ])
1990

    
1991
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
1992
  for hv_name in enabled_hypervisors:
1993
    hv_class = hypervisor.GetHypervisor(hv_name)
1994
    dist_files.update(hv_class.GetAncillaryFiles())
1995

    
1996
  # 3. Perform the files upload
1997
  for fname in dist_files:
1998
    if os.path.exists(fname):
1999
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2000
      for to_node, to_result in result.items():
2001
        msg = to_result.fail_msg
2002
        if msg:
2003
          msg = ("Copy of file %s to node %s failed: %s" %
2004
                 (fname, to_node, msg))
2005
          lu.proc.LogWarning(msg)
2006

    
2007

    
2008
class LURedistributeConfig(NoHooksLU):
2009
  """Force the redistribution of cluster configuration.
2010

2011
  This is a very simple LU.
2012

2013
  """
2014
  _OP_REQP = []
2015
  REQ_BGL = False
2016

    
2017
  def ExpandNames(self):
2018
    self.needed_locks = {
2019
      locking.LEVEL_NODE: locking.ALL_SET,
2020
    }
2021
    self.share_locks[locking.LEVEL_NODE] = 1
2022

    
2023
  def CheckPrereq(self):
2024
    """Check prerequisites.
2025

2026
    """
2027

    
2028
  def Exec(self, feedback_fn):
2029
    """Redistribute the configuration.
2030

2031
    """
2032
    self.cfg.Update(self.cfg.GetClusterInfo())
2033
    _RedistributeAncillaryFiles(self)
2034

    
2035

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

2039
  """
2040
  if not instance.disks:
2041
    return True
2042

    
2043
  if not oneshot:
2044
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2045

    
2046
  node = instance.primary_node
2047

    
2048
  for dev in instance.disks:
2049
    lu.cfg.SetDiskID(dev, node)
2050

    
2051
  retries = 0
2052
  degr_retries = 10 # in seconds, as we sleep 1 second each time
2053
  while True:
2054
    max_time = 0
2055
    done = True
2056
    cumul_degraded = False
2057
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
2058
    msg = rstats.fail_msg
2059
    if msg:
2060
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
2061
      retries += 1
2062
      if retries >= 10:
2063
        raise errors.RemoteError("Can't contact node %s for mirror data,"
2064
                                 " aborting." % node)
2065
      time.sleep(6)
2066
      continue
2067
    rstats = rstats.payload
2068
    retries = 0
2069
    for i, mstat in enumerate(rstats):
2070
      if mstat is None:
2071
        lu.LogWarning("Can't compute data for node %s/%s",
2072
                           node, instance.disks[i].iv_name)
2073
        continue
2074

    
2075
      cumul_degraded = (cumul_degraded or
2076
                        (mstat.is_degraded and mstat.sync_percent is None))
2077
      if mstat.sync_percent is not None:
2078
        done = False
2079
        if mstat.estimated_time is not None:
2080
          rem_time = "%d estimated seconds remaining" % mstat.estimated_time
2081
          max_time = mstat.estimated_time
2082
        else:
2083
          rem_time = "no time estimate"
2084
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
2085
                        (instance.disks[i].iv_name, mstat.sync_percent,
2086
                         rem_time))
2087

    
2088
    # if we're done but degraded, let's do a few small retries, to
2089
    # make sure we see a stable and not transient situation; therefore
2090
    # we force restart of the loop
2091
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
2092
      logging.info("Degraded disks found, %d retries left", degr_retries)
2093
      degr_retries -= 1
2094
      time.sleep(1)
2095
      continue
2096

    
2097
    if done or oneshot:
2098
      break
2099

    
2100
    time.sleep(min(60, max_time))
2101

    
2102
  if done:
2103
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
2104
  return not cumul_degraded
2105

    
2106

    
2107
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
2108
  """Check that mirrors are not degraded.
2109

2110
  The ldisk parameter, if True, will change the test from the
2111
  is_degraded attribute (which represents overall non-ok status for
2112
  the device(s)) to the ldisk (representing the local storage status).
2113

2114
  """
2115
  lu.cfg.SetDiskID(dev, node)
2116

    
2117
  result = True
2118

    
2119
  if on_primary or dev.AssembleOnSecondary():
2120
    rstats = lu.rpc.call_blockdev_find(node, dev)
2121
    msg = rstats.fail_msg
2122
    if msg:
2123
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
2124
      result = False
2125
    elif not rstats.payload:
2126
      lu.LogWarning("Can't find disk on node %s", node)
2127
      result = False
2128
    else:
2129
      if ldisk:
2130
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
2131
      else:
2132
        result = result and not rstats.payload.is_degraded
2133

    
2134
  if dev.children:
2135
    for child in dev.children:
2136
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
2137

    
2138
  return result
2139

    
2140

    
2141
class LUDiagnoseOS(NoHooksLU):
2142
  """Logical unit for OS diagnose/query.
2143

2144
  """
2145
  _OP_REQP = ["output_fields", "names"]
2146
  REQ_BGL = False
2147
  _FIELDS_STATIC = utils.FieldSet()
2148
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status", "variants")
2149
  # Fields that need calculation of global os validity
2150
  _FIELDS_NEEDVALID = frozenset(["valid", "variants"])
2151

    
2152
  def ExpandNames(self):
2153
    if self.op.names:
2154
      raise errors.OpPrereqError("Selective OS query not supported")
2155

    
2156
    _CheckOutputFields(static=self._FIELDS_STATIC,
2157
                       dynamic=self._FIELDS_DYNAMIC,
2158
                       selected=self.op.output_fields)
2159

    
2160
    # Lock all nodes, in shared mode
2161
    # Temporary removal of locks, should be reverted later
2162
    # TODO: reintroduce locks when they are lighter-weight
2163
    self.needed_locks = {}
2164
    #self.share_locks[locking.LEVEL_NODE] = 1
2165
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2166

    
2167
  def CheckPrereq(self):
2168
    """Check prerequisites.
2169

2170
    """
2171

    
2172
  @staticmethod
2173
  def _DiagnoseByOS(node_list, rlist):
2174
    """Remaps a per-node return list into an a per-os per-node dictionary
2175

2176
    @param node_list: a list with the names of all nodes
2177
    @param rlist: a map with node names as keys and OS objects as values
2178

2179
    @rtype: dict
2180
    @return: a dictionary with osnames as keys and as value another map, with
2181
        nodes as keys and tuples of (path, status, diagnose) as values, eg::
2182

2183
          {"debian-etch": {"node1": [(/usr/lib/..., True, ""),
2184
                                     (/srv/..., False, "invalid api")],
2185
                           "node2": [(/srv/..., True, "")]}
2186
          }
2187

2188
    """
2189
    all_os = {}
2190
    # we build here the list of nodes that didn't fail the RPC (at RPC
2191
    # level), so that nodes with a non-responding node daemon don't
2192
    # make all OSes invalid
2193
    good_nodes = [node_name for node_name in rlist
2194
                  if not rlist[node_name].fail_msg]
2195
    for node_name, nr in rlist.items():
2196
      if nr.fail_msg or not nr.payload:
2197
        continue
2198
      for name, path, status, diagnose, variants in nr.payload:
2199
        if name not in all_os:
2200
          # build a list of nodes for this os containing empty lists
2201
          # for each node in node_list
2202
          all_os[name] = {}
2203
          for nname in good_nodes:
2204
            all_os[name][nname] = []
2205
        all_os[name][node_name].append((path, status, diagnose, variants))
2206
    return all_os
2207

    
2208
  def Exec(self, feedback_fn):
2209
    """Compute the list of OSes.
2210

2211
    """
2212
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
2213
    node_data = self.rpc.call_os_diagnose(valid_nodes)
2214
    pol = self._DiagnoseByOS(valid_nodes, node_data)
2215
    output = []
2216
    calc_valid = self._FIELDS_NEEDVALID.intersection(self.op.output_fields)
2217
    calc_variants = "variants" in self.op.output_fields
2218

    
2219
    for os_name, os_data in pol.items():
2220
      row = []
2221
      if calc_valid:
2222
        valid = True
2223
        variants = None
2224
        for osl in os_data.values():
2225
          valid = valid and osl and osl[0][1]
2226
          if not valid:
2227
            variants = None
2228
            break
2229
          if calc_variants:
2230
            node_variants = osl[0][3]
2231
            if variants is None:
2232
              variants = node_variants
2233
            else:
2234
              variants = [v for v in variants if v in node_variants]
2235

    
2236
      for field in self.op.output_fields:
2237
        if field == "name":
2238
          val = os_name
2239
        elif field == "valid":
2240
          val = valid
2241
        elif field == "node_status":
2242
          # this is just a copy of the dict
2243
          val = {}
2244
          for node_name, nos_list in os_data.items():
2245
            val[node_name] = nos_list
2246
        elif field == "variants":
2247
          val =  variants
2248
        else:
2249
          raise errors.ParameterError(field)
2250
        row.append(val)
2251
      output.append(row)
2252

    
2253
    return output
2254

    
2255

    
2256
class LURemoveNode(LogicalUnit):
2257
  """Logical unit for removing a node.
2258

2259
  """
2260
  HPATH = "node-remove"
2261
  HTYPE = constants.HTYPE_NODE
2262
  _OP_REQP = ["node_name"]
2263

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

2267
    This doesn't run on the target node in the pre phase as a failed
2268
    node would then be impossible to remove.
2269

2270
    """
2271
    env = {
2272
      "OP_TARGET": self.op.node_name,
2273
      "NODE_NAME": self.op.node_name,
2274
      }
2275
    all_nodes = self.cfg.GetNodeList()
2276
    if self.op.node_name in all_nodes:
2277
      all_nodes.remove(self.op.node_name)
2278
    return env, all_nodes, all_nodes
2279

    
2280
  def CheckPrereq(self):
2281
    """Check prerequisites.
2282

2283
    This checks:
2284
     - the node exists in the configuration
2285
     - it does not have primary or secondary instances
2286
     - it's not the master
2287

2288
    Any errors are signaled by raising errors.OpPrereqError.
2289

2290
    """
2291
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
2292
    if node is None:
2293
      raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name)
2294

    
2295
    instance_list = self.cfg.GetInstanceList()
2296

    
2297
    masternode = self.cfg.GetMasterNode()
2298
    if node.name == masternode:
2299
      raise errors.OpPrereqError("Node is the master node,"
2300
                                 " you need to failover first.")
2301

    
2302
    for instance_name in instance_list:
2303
      instance = self.cfg.GetInstanceInfo(instance_name)
2304
      if node.name in instance.all_nodes:
2305
        raise errors.OpPrereqError("Instance %s is still running on the node,"
2306
                                   " please remove first." % instance_name)
2307
    self.op.node_name = node.name
2308
    self.node = node
2309

    
2310
  def Exec(self, feedback_fn):
2311
    """Removes the node from the cluster.
2312

2313
    """
2314
    node = self.node
2315
    logging.info("Stopping the node daemon and removing configs from node %s",
2316
                 node.name)
2317

    
2318
    # Promote nodes to master candidate as needed
2319
    _AdjustCandidatePool(self, exceptions=[node.name])
2320
    self.context.RemoveNode(node.name)
2321

    
2322
    # Run post hooks on the node before it's removed
2323
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
2324
    try:
2325
      h_results = hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
2326
    except:
2327
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
2328

    
2329
    result = self.rpc.call_node_leave_cluster(node.name)
2330
    msg = result.fail_msg
2331
    if msg:
2332
      self.LogWarning("Errors encountered on the remote node while leaving"
2333
                      " the cluster: %s", msg)
2334

    
2335

    
2336
class LUQueryNodes(NoHooksLU):
2337
  """Logical unit for querying nodes.
2338

2339
  """
2340
  _OP_REQP = ["output_fields", "names", "use_locking"]
2341
  REQ_BGL = False
2342

    
2343
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
2344
                    "master_candidate", "offline", "drained"]
2345

    
2346
  _FIELDS_DYNAMIC = utils.FieldSet(
2347
    "dtotal", "dfree",
2348
    "mtotal", "mnode", "mfree",
2349
    "bootid",
2350
    "ctotal", "cnodes", "csockets",
2351
    )
2352

    
2353
  _FIELDS_STATIC = utils.FieldSet(*[
2354
    "pinst_cnt", "sinst_cnt",
2355
    "pinst_list", "sinst_list",
2356
    "pip", "sip", "tags",
2357
    "master",
2358
    "role"] + _SIMPLE_FIELDS
2359
    )
2360

    
2361
  def ExpandNames(self):
2362
    _CheckOutputFields(static=self._FIELDS_STATIC,
2363
                       dynamic=self._FIELDS_DYNAMIC,
2364
                       selected=self.op.output_fields)
2365

    
2366
    self.needed_locks = {}
2367
    self.share_locks[locking.LEVEL_NODE] = 1
2368

    
2369
    if self.op.names:
2370
      self.wanted = _GetWantedNodes(self, self.op.names)
2371
    else:
2372
      self.wanted = locking.ALL_SET
2373

    
2374
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
2375
    self.do_locking = self.do_node_query and self.op.use_locking
2376
    if self.do_locking:
2377
      # if we don't request only static fields, we need to lock the nodes
2378
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
2379

    
2380

    
2381
  def CheckPrereq(self):
2382
    """Check prerequisites.
2383

2384
    """
2385
    # The validation of the node list is done in the _GetWantedNodes,
2386
    # if non empty, and if empty, there's no validation to do
2387
    pass
2388

    
2389
  def Exec(self, feedback_fn):
2390
    """Computes the list of nodes and their attributes.
2391

2392
    """
2393
    all_info = self.cfg.GetAllNodesInfo()
2394
    if self.do_locking:
2395
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
2396
    elif self.wanted != locking.ALL_SET:
2397
      nodenames = self.wanted
2398
      missing = set(nodenames).difference(all_info.keys())
2399
      if missing:
2400
        raise errors.OpExecError(
2401
          "Some nodes were removed before retrieving their data: %s" % missing)
2402
    else:
2403
      nodenames = all_info.keys()
2404

    
2405
    nodenames = utils.NiceSort(nodenames)
2406
    nodelist = [all_info[name] for name in nodenames]
2407

    
2408
    # begin data gathering
2409

    
2410
    if self.do_node_query:
2411
      live_data = {}
2412
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
2413
                                          self.cfg.GetHypervisorType())
2414
      for name in nodenames:
2415
        nodeinfo = node_data[name]
2416
        if not nodeinfo.fail_msg and nodeinfo.payload:
2417
          nodeinfo = nodeinfo.payload
2418
          fn = utils.TryConvert
2419
          live_data[name] = {
2420
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
2421
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
2422
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
2423
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
2424
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
2425
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
2426
            "bootid": nodeinfo.get('bootid', None),
2427
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
2428
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
2429
            }
2430
        else:
2431
          live_data[name] = {}
2432
    else:
2433
      live_data = dict.fromkeys(nodenames, {})
2434

    
2435
    node_to_primary = dict([(name, set()) for name in nodenames])
2436
    node_to_secondary = dict([(name, set()) for name in nodenames])
2437

    
2438
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
2439
                             "sinst_cnt", "sinst_list"))
2440
    if inst_fields & frozenset(self.op.output_fields):
2441
      instancelist = self.cfg.GetInstanceList()
2442

    
2443
      for instance_name in instancelist:
2444
        inst = self.cfg.GetInstanceInfo(instance_name)
2445
        if inst.primary_node in node_to_primary:
2446
          node_to_primary[inst.primary_node].add(inst.name)
2447
        for secnode in inst.secondary_nodes:
2448
          if secnode in node_to_secondary:
2449
            node_to_secondary[secnode].add(inst.name)
2450

    
2451
    master_node = self.cfg.GetMasterNode()
2452

    
2453
    # end data gathering
2454

    
2455
    output = []
2456
    for node in nodelist:
2457
      node_output = []
2458
      for field in self.op.output_fields:
2459
        if field in self._SIMPLE_FIELDS:
2460
          val = getattr(node, field)
2461
        elif field == "pinst_list":
2462
          val = list(node_to_primary[node.name])
2463
        elif field == "sinst_list":
2464
          val = list(node_to_secondary[node.name])
2465
        elif field == "pinst_cnt":
2466
          val = len(node_to_primary[node.name])
2467
        elif field == "sinst_cnt":
2468
          val = len(node_to_secondary[node.name])
2469
        elif field == "pip":
2470
          val = node.primary_ip
2471
        elif field == "sip":
2472
          val = node.secondary_ip
2473
        elif field == "tags":
2474
          val = list(node.GetTags())
2475
        elif field == "master":
2476
          val = node.name == master_node
2477
        elif self._FIELDS_DYNAMIC.Matches(field):
2478
          val = live_data[node.name].get(field, None)
2479
        elif field == "role":
2480
          if node.name == master_node:
2481
            val = "M"
2482
          elif node.master_candidate:
2483
            val = "C"
2484
          elif node.drained:
2485
            val = "D"
2486
          elif node.offline:
2487
            val = "O"
2488
          else:
2489
            val = "R"
2490
        else:
2491
          raise errors.ParameterError(field)
2492
        node_output.append(val)
2493
      output.append(node_output)
2494

    
2495
    return output
2496

    
2497

    
2498
class LUQueryNodeVolumes(NoHooksLU):
2499
  """Logical unit for getting volumes on node(s).
2500

2501
  """
2502
  _OP_REQP = ["nodes", "output_fields"]
2503
  REQ_BGL = False
2504
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
2505
  _FIELDS_STATIC = utils.FieldSet("node")
2506

    
2507
  def ExpandNames(self):
2508
    _CheckOutputFields(static=self._FIELDS_STATIC,
2509
                       dynamic=self._FIELDS_DYNAMIC,
2510
                       selected=self.op.output_fields)
2511

    
2512
    self.needed_locks = {}
2513
    self.share_locks[locking.LEVEL_NODE] = 1
2514
    if not self.op.nodes:
2515
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2516
    else:
2517
      self.needed_locks[locking.LEVEL_NODE] = \
2518
        _GetWantedNodes(self, self.op.nodes)
2519

    
2520
  def CheckPrereq(self):
2521
    """Check prerequisites.
2522

2523
    This checks that the fields required are valid output fields.
2524

2525
    """
2526
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
2527

    
2528
  def Exec(self, feedback_fn):
2529
    """Computes the list of nodes and their attributes.
2530

2531
    """
2532
    nodenames = self.nodes
2533
    volumes = self.rpc.call_node_volumes(nodenames)
2534

    
2535
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
2536
             in self.cfg.GetInstanceList()]
2537

    
2538
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
2539

    
2540
    output = []
2541
    for node in nodenames:
2542
      nresult = volumes[node]
2543
      if nresult.offline:
2544
        continue
2545
      msg = nresult.fail_msg
2546
      if msg:
2547
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
2548
        continue
2549

    
2550
      node_vols = nresult.payload[:]
2551
      node_vols.sort(key=lambda vol: vol['dev'])
2552

    
2553
      for vol in node_vols:
2554
        node_output = []
2555
        for field in self.op.output_fields:
2556
          if field == "node":
2557
            val = node
2558
          elif field == "phys":
2559
            val = vol['dev']
2560
          elif field == "vg":
2561
            val = vol['vg']
2562
          elif field == "name":
2563
            val = vol['name']
2564
          elif field == "size":
2565
            val = int(float(vol['size']))
2566
          elif field == "instance":
2567
            for inst in ilist:
2568
              if node not in lv_by_node[inst]:
2569
                continue
2570
              if vol['name'] in lv_by_node[inst][node]:
2571
                val = inst.name
2572
                break
2573
            else:
2574
              val = '-'
2575
          else:
2576
            raise errors.ParameterError(field)
2577
          node_output.append(str(val))
2578

    
2579
        output.append(node_output)
2580

    
2581
    return output
2582

    
2583

    
2584
class LUQueryNodeStorage(NoHooksLU):
2585
  """Logical unit for getting information on storage units on node(s).
2586

2587
  """
2588
  _OP_REQP = ["nodes", "storage_type", "output_fields"]
2589
  REQ_BGL = False
2590
  _FIELDS_STATIC = utils.FieldSet("node")
2591

    
2592
  def ExpandNames(self):
2593
    storage_type = self.op.storage_type
2594

    
2595
    if storage_type not in constants.VALID_STORAGE_FIELDS:
2596
      raise errors.OpPrereqError("Unknown storage type: %s" % storage_type)
2597

    
2598
    dynamic_fields = constants.VALID_STORAGE_FIELDS[storage_type]
2599

    
2600
    _CheckOutputFields(static=self._FIELDS_STATIC,
2601
                       dynamic=utils.FieldSet(*dynamic_fields),
2602
                       selected=self.op.output_fields)
2603

    
2604
    self.needed_locks = {}
2605
    self.share_locks[locking.LEVEL_NODE] = 1
2606

    
2607
    if self.op.nodes:
2608
      self.needed_locks[locking.LEVEL_NODE] = \
2609
        _GetWantedNodes(self, self.op.nodes)
2610
    else:
2611
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2612

    
2613
  def CheckPrereq(self):
2614
    """Check prerequisites.
2615

2616
    This checks that the fields required are valid output fields.
2617

2618
    """
2619
    self.op.name = getattr(self.op, "name", None)
2620

    
2621
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
2622

    
2623
  def Exec(self, feedback_fn):
2624
    """Computes the list of nodes and their attributes.
2625

2626
    """
2627
    # Always get name to sort by
2628
    if constants.SF_NAME in self.op.output_fields:
2629
      fields = self.op.output_fields[:]
2630
    else:
2631
      fields = [constants.SF_NAME] + self.op.output_fields
2632

    
2633
    # Never ask for node as it's only known to the LU
2634
    while "node" in fields:
2635
      fields.remove("node")
2636

    
2637
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
2638
    name_idx = field_idx[constants.SF_NAME]
2639

    
2640
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
2641
    data = self.rpc.call_storage_list(self.nodes,
2642
                                      self.op.storage_type, st_args,
2643
                                      self.op.name, fields)
2644

    
2645
    result = []
2646

    
2647
    for node in utils.NiceSort(self.nodes):
2648
      nresult = data[node]
2649
      if nresult.offline:
2650
        continue
2651

    
2652
      msg = nresult.fail_msg
2653
      if msg:
2654
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
2655
        continue
2656

    
2657
      rows = dict([(row[name_idx], row) for row in nresult.payload])
2658

    
2659
      for name in utils.NiceSort(rows.keys()):
2660
        row = rows[name]
2661

    
2662
        out = []
2663

    
2664
        for field in self.op.output_fields:
2665
          if field == "node":
2666
            val = node
2667
          elif field in field_idx:
2668
            val = row[field_idx[field]]
2669
          else:
2670
            raise errors.ParameterError(field)
2671

    
2672
          out.append(val)
2673

    
2674
        result.append(out)
2675

    
2676
    return result
2677

    
2678

    
2679
class LUModifyNodeStorage(NoHooksLU):
2680
  """Logical unit for modifying a storage volume on a node.
2681

2682
  """
2683
  _OP_REQP = ["node_name", "storage_type", "name", "changes"]
2684
  REQ_BGL = False
2685

    
2686
  def CheckArguments(self):
2687
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2688
    if node_name is None:
2689
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
2690

    
2691
    self.op.node_name = node_name
2692

    
2693
    storage_type = self.op.storage_type
2694
    if storage_type not in constants.VALID_STORAGE_FIELDS:
2695
      raise errors.OpPrereqError("Unknown storage type: %s" % storage_type)
2696

    
2697
  def ExpandNames(self):
2698
    self.needed_locks = {
2699
      locking.LEVEL_NODE: self.op.node_name,
2700
      }
2701

    
2702
  def CheckPrereq(self):
2703
    """Check prerequisites.
2704

2705
    """
2706
    storage_type = self.op.storage_type
2707

    
2708
    try:
2709
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
2710
    except KeyError:
2711
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
2712
                                 " modified" % storage_type)
2713

    
2714
    diff = set(self.op.changes.keys()) - modifiable
2715
    if diff:
2716
      raise errors.OpPrereqError("The following fields can not be modified for"
2717
                                 " storage units of type '%s': %r" %
2718
                                 (storage_type, list(diff)))
2719

    
2720
  def Exec(self, feedback_fn):
2721
    """Computes the list of nodes and their attributes.
2722

2723
    """
2724
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
2725
    result = self.rpc.call_storage_modify(self.op.node_name,
2726
                                          self.op.storage_type, st_args,
2727
                                          self.op.name, self.op.changes)
2728
    result.Raise("Failed to modify storage unit '%s' on %s" %
2729
                 (self.op.name, self.op.node_name))
2730

    
2731

    
2732
class LUAddNode(LogicalUnit):
2733
  """Logical unit for adding node to the cluster.
2734

2735
  """
2736
  HPATH = "node-add"
2737
  HTYPE = constants.HTYPE_NODE
2738
  _OP_REQP = ["node_name"]
2739

    
2740
  def BuildHooksEnv(self):
2741
    """Build hooks env.
2742

2743
    This will run on all nodes before, and on all nodes + the new node after.
2744

2745
    """
2746
    env = {
2747
      "OP_TARGET": self.op.node_name,
2748
      "NODE_NAME": self.op.node_name,
2749
      "NODE_PIP": self.op.primary_ip,
2750
      "NODE_SIP": self.op.secondary_ip,
2751
      }
2752
    nodes_0 = self.cfg.GetNodeList()
2753
    nodes_1 = nodes_0 + [self.op.node_name, ]
2754
    return env, nodes_0, nodes_1
2755

    
2756
  def CheckPrereq(self):
2757
    """Check prerequisites.
2758

2759
    This checks:
2760
     - the new node is not already in the config
2761
     - it is resolvable
2762
     - its parameters (single/dual homed) matches the cluster
2763

2764
    Any errors are signaled by raising errors.OpPrereqError.
2765

2766
    """
2767
    node_name = self.op.node_name
2768
    cfg = self.cfg
2769

    
2770
    dns_data = utils.HostInfo(node_name)
2771

    
2772
    node = dns_data.name
2773
    primary_ip = self.op.primary_ip = dns_data.ip
2774
    secondary_ip = getattr(self.op, "secondary_ip", None)
2775
    if secondary_ip is None:
2776
      secondary_ip = primary_ip
2777
    if not utils.IsValidIP(secondary_ip):
2778
      raise errors.OpPrereqError("Invalid secondary IP given")
2779
    self.op.secondary_ip = secondary_ip
2780

    
2781
    node_list = cfg.GetNodeList()
2782
    if not self.op.readd and node in node_list:
2783
      raise errors.OpPrereqError("Node %s is already in the configuration" %
2784
                                 node)
2785
    elif self.op.readd and node not in node_list:
2786
      raise errors.OpPrereqError("Node %s is not in the configuration" % node)
2787

    
2788
    for existing_node_name in node_list:
2789
      existing_node = cfg.GetNodeInfo(existing_node_name)
2790

    
2791
      if self.op.readd and node == existing_node_name:
2792
        if (existing_node.primary_ip != primary_ip or
2793
            existing_node.secondary_ip != secondary_ip):
2794
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
2795
                                     " address configuration as before")
2796
        continue
2797

    
2798
      if (existing_node.primary_ip == primary_ip or
2799
          existing_node.secondary_ip == primary_ip or
2800
          existing_node.primary_ip == secondary_ip or
2801
          existing_node.secondary_ip == secondary_ip):
2802
        raise errors.OpPrereqError("New node ip address(es) conflict with"
2803
                                   " existing node %s" % existing_node.name)
2804

    
2805
    # check that the type of the node (single versus dual homed) is the
2806
    # same as for the master
2807
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
2808
    master_singlehomed = myself.secondary_ip == myself.primary_ip
2809
    newbie_singlehomed = secondary_ip == primary_ip
2810
    if master_singlehomed != newbie_singlehomed:
2811
      if master_singlehomed:
2812
        raise errors.OpPrereqError("The master has no private ip but the"
2813
                                   " new node has one")
2814
      else:
2815
        raise errors.OpPrereqError("The master has a private ip but the"
2816
                                   " new node doesn't have one")
2817

    
2818
    # checks reachability
2819
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
2820
      raise errors.OpPrereqError("Node not reachable by ping")
2821

    
2822
    if not newbie_singlehomed:
2823
      # check reachability from my secondary ip to newbie's secondary ip
2824
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
2825
                           source=myself.secondary_ip):
2826
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
2827
                                   " based ping to noded port")
2828

    
2829
    if self.op.readd:
2830
      exceptions = [node]
2831
    else:
2832
      exceptions = []
2833

    
2834
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
2835

    
2836
    if self.op.readd:
2837
      self.new_node = self.cfg.GetNodeInfo(node)
2838
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
2839
    else:
2840
      self.new_node = objects.Node(name=node,
2841
                                   primary_ip=primary_ip,
2842
                                   secondary_ip=secondary_ip,
2843
                                   master_candidate=self.master_candidate,
2844
                                   offline=False, drained=False)
2845

    
2846
  def Exec(self, feedback_fn):
2847
    """Adds the new node to the cluster.
2848

2849
    """
2850
    new_node = self.new_node
2851
    node = new_node.name
2852

    
2853
    # for re-adds, reset the offline/drained/master-candidate flags;
2854
    # we need to reset here, otherwise offline would prevent RPC calls
2855
    # later in the procedure; this also means that if the re-add
2856
    # fails, we are left with a non-offlined, broken node
2857
    if self.op.readd:
2858
      new_node.drained = new_node.offline = False
2859
      self.LogInfo("Readding a node, the offline/drained flags were reset")
2860
      # if we demote the node, we do cleanup later in the procedure
2861
      new_node.master_candidate = self.master_candidate
2862

    
2863
    # notify the user about any possible mc promotion
2864
    if new_node.master_candidate:
2865
      self.LogInfo("Node will be a master candidate")
2866

    
2867
    # check connectivity
2868
    result = self.rpc.call_version([node])[node]
2869
    result.Raise("Can't get version information from node %s" % node)
2870
    if constants.PROTOCOL_VERSION == result.payload:
2871
      logging.info("Communication to node %s fine, sw version %s match",
2872
                   node, result.payload)
2873
    else:
2874
      raise errors.OpExecError("Version mismatch master version %s,"
2875
                               " node version %s" %
2876
                               (constants.PROTOCOL_VERSION, result.payload))
2877

    
2878
    # setup ssh on node
2879
    logging.info("Copy ssh key to node %s", node)
2880
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
2881
    keyarray = []
2882
    keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
2883
                constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
2884
                priv_key, pub_key]
2885

    
2886
    for i in keyfiles:
2887
      keyarray.append(utils.ReadFile(i))
2888

    
2889
    result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
2890
                                    keyarray[2],
2891
                                    keyarray[3], keyarray[4], keyarray[5])
2892
    result.Raise("Cannot transfer ssh keys to the new node")
2893

    
2894
    # Add node to our /etc/hosts, and add key to known_hosts
2895
    if self.cfg.GetClusterInfo().modify_etc_hosts:
2896
      utils.AddHostToEtcHosts(new_node.name)
2897

    
2898
    if new_node.secondary_ip != new_node.primary_ip:
2899
      result = self.rpc.call_node_has_ip_address(new_node.name,
2900
                                                 new_node.secondary_ip)
2901
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
2902
                   prereq=True)
2903
      if not result.payload:
2904
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
2905
                                 " you gave (%s). Please fix and re-run this"
2906
                                 " command." % new_node.secondary_ip)
2907

    
2908
    node_verify_list = [self.cfg.GetMasterNode()]
2909
    node_verify_param = {
2910
      constants.NV_NODELIST: [node],
2911
      # TODO: do a node-net-test as well?
2912
    }
2913

    
2914
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
2915
                                       self.cfg.GetClusterName())
2916
    for verifier in node_verify_list:
2917
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
2918
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
2919
      if nl_payload:
2920
        for failed in nl_payload:
2921
          feedback_fn("ssh/hostname verification failed"
2922
                      " (checking from %s): %s" %
2923
                      (verifier, nl_payload[failed]))
2924
        raise errors.OpExecError("ssh/hostname verification failed.")
2925

    
2926
    if self.op.readd:
2927
      _RedistributeAncillaryFiles(self)
2928
      self.context.ReaddNode(new_node)
2929
      # make sure we redistribute the config
2930
      self.cfg.Update(new_node)
2931
      # and make sure the new node will not have old files around
2932
      if not new_node.master_candidate:
2933
        result = self.rpc.call_node_demote_from_mc(new_node.name)
2934
        msg = result.fail_msg
2935
        if msg:
2936
          self.LogWarning("Node failed to demote itself from master"
2937
                          " candidate status: %s" % msg)
2938
    else:
2939
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
2940
      self.context.AddNode(new_node)
2941

    
2942

    
2943
class LUSetNodeParams(LogicalUnit):
2944
  """Modifies the parameters of a node.
2945

2946
  """
2947
  HPATH = "node-modify"
2948
  HTYPE = constants.HTYPE_NODE
2949
  _OP_REQP = ["node_name"]
2950
  REQ_BGL = False
2951

    
2952
  def CheckArguments(self):
2953
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2954
    if node_name is None:
2955
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
2956
    self.op.node_name = node_name
2957
    _CheckBooleanOpField(self.op, 'master_candidate')
2958
    _CheckBooleanOpField(self.op, 'offline')
2959
    _CheckBooleanOpField(self.op, 'drained')
2960
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
2961
    if all_mods.count(None) == 3:
2962
      raise errors.OpPrereqError("Please pass at least one modification")
2963
    if all_mods.count(True) > 1:
2964
      raise errors.OpPrereqError("Can't set the node into more than one"
2965
                                 " state at the same time")
2966

    
2967
  def ExpandNames(self):
2968
    self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
2969

    
2970
  def BuildHooksEnv(self):
2971
    """Build hooks env.
2972

2973
    This runs on the master node.
2974

2975
    """
2976
    env = {
2977
      "OP_TARGET": self.op.node_name,
2978
      "MASTER_CANDIDATE": str(self.op.master_candidate),
2979
      "OFFLINE": str(self.op.offline),
2980
      "DRAINED": str(self.op.drained),
2981
      }
2982
    nl = [self.cfg.GetMasterNode(),
2983
          self.op.node_name]
2984
    return env, nl, nl
2985

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

2989
    This only checks the instance list against the existing names.
2990

2991
    """
2992
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
2993

    
2994
    if (self.op.master_candidate is not None or
2995
        self.op.drained is not None or
2996
        self.op.offline is not None):
2997
      # we can't change the master's node flags
2998
      if self.op.node_name == self.cfg.GetMasterNode():
2999
        raise errors.OpPrereqError("The master role can be changed"
3000
                                   " only via masterfailover")
3001

    
3002
    # Boolean value that tells us whether we're offlining or draining the node
3003
    offline_or_drain = self.op.offline == True or self.op.drained == True
3004
    deoffline_or_drain = self.op.offline == False or self.op.drained == False
3005

    
3006
    if (node.master_candidate and
3007
        (self.op.master_candidate == False or offline_or_drain)):
3008
      cp_size = self.cfg.GetClusterInfo().candidate_pool_size
3009
      mc_now, mc_should, mc_max = self.cfg.GetMasterCandidateStats()
3010
      if mc_now <= cp_size:
3011
        msg = ("Not enough master candidates (desired"
3012
               " %d, new value will be %d)" % (cp_size, mc_now-1))
3013
        # Only allow forcing the operation if it's an offline/drain operation,
3014
        # and we could not possibly promote more nodes.
3015
        # FIXME: this can still lead to issues if in any way another node which
3016
        # could be promoted appears in the meantime.
3017
        if self.op.force and offline_or_drain and mc_should == mc_max:
3018
          self.LogWarning(msg)
3019
        else:
3020
          raise errors.OpPrereqError(msg)
3021

    
3022
    if (self.op.master_candidate == True and
3023
        ((node.offline and not self.op.offline == False) or
3024
         (node.drained and not self.op.drained == False))):
3025
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
3026
                                 " to master_candidate" % node.name)
3027

    
3028
    # If we're being deofflined/drained, we'll MC ourself if needed
3029
    if (deoffline_or_drain and not offline_or_drain and not
3030
        self.op.master_candidate == True):
3031
      self.op.master_candidate = _DecideSelfPromotion(self)
3032
      if self.op.master_candidate:
3033
        self.LogInfo("Autopromoting node to master candidate")
3034

    
3035
    return
3036

    
3037
  def Exec(self, feedback_fn):
3038
    """Modifies a node.
3039

3040
    """
3041
    node = self.node
3042

    
3043
    result = []
3044
    changed_mc = False
3045

    
3046
    if self.op.offline is not None:
3047
      node.offline = self.op.offline
3048
      result.append(("offline", str(self.op.offline)))
3049
      if self.op.offline == True:
3050
        if node.master_candidate:
3051
          node.master_candidate = False
3052
          changed_mc = True
3053
          result.append(("master_candidate", "auto-demotion due to offline"))
3054
        if node.drained:
3055
          node.drained = False
3056
          result.append(("drained", "clear drained status due to offline"))
3057

    
3058
    if self.op.master_candidate is not None:
3059
      node.master_candidate = self.op.master_candidate
3060
      changed_mc = True
3061
      result.append(("master_candidate", str(self.op.master_candidate)))
3062
      if self.op.master_candidate == False:
3063
        rrc = self.rpc.call_node_demote_from_mc(node.name)
3064
        msg = rrc.fail_msg
3065
        if msg:
3066
          self.LogWarning("Node failed to demote itself: %s" % msg)
3067

    
3068
    if self.op.drained is not None:
3069
      node.drained = self.op.drained
3070
      result.append(("drained", str(self.op.drained)))
3071
      if self.op.drained == True:
3072
        if node.master_candidate:
3073
          node.master_candidate = False
3074
          changed_mc = True
3075
          result.append(("master_candidate", "auto-demotion due to drain"))
3076
          rrc = self.rpc.call_node_demote_from_mc(node.name)
3077
          msg = rrc.fail_msg
3078
          if msg:
3079
            self.LogWarning("Node failed to demote itself: %s" % msg)
3080
        if node.offline:
3081
          node.offline = False
3082
          result.append(("offline", "clear offline status due to drain"))
3083

    
3084
    # this will trigger configuration file update, if needed
3085
    self.cfg.Update(node)
3086
    # this will trigger job queue propagation or cleanup
3087
    if changed_mc:
3088
      self.context.ReaddNode(node)
3089

    
3090
    return result
3091

    
3092

    
3093
class LUPowercycleNode(NoHooksLU):
3094
  """Powercycles a node.
3095

3096
  """
3097
  _OP_REQP = ["node_name", "force"]
3098
  REQ_BGL = False
3099

    
3100
  def CheckArguments(self):
3101
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
3102
    if node_name is None:
3103
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
3104
    self.op.node_name = node_name
3105
    if node_name == self.cfg.GetMasterNode() and not self.op.force:
3106
      raise errors.OpPrereqError("The node is the master and the force"
3107
                                 " parameter was not set")
3108

    
3109
  def ExpandNames(self):
3110
    """Locking for PowercycleNode.
3111

3112
    This is a last-resort option and shouldn't block on other
3113
    jobs. Therefore, we grab no locks.
3114

3115
    """
3116
    self.needed_locks = {}
3117

    
3118
  def CheckPrereq(self):
3119
    """Check prerequisites.
3120

3121
    This LU has no prereqs.
3122

3123
    """
3124
    pass
3125

    
3126
  def Exec(self, feedback_fn):
3127
    """Reboots a node.
3128

3129
    """
3130
    result = self.rpc.call_node_powercycle(self.op.node_name,
3131
                                           self.cfg.GetHypervisorType())
3132
    result.Raise("Failed to schedule the reboot")
3133
    return result.payload
3134

    
3135

    
3136
class LUQueryClusterInfo(NoHooksLU):
3137
  """Query cluster configuration.
3138

3139
  """
3140
  _OP_REQP = []
3141
  REQ_BGL = False
3142

    
3143
  def ExpandNames(self):
3144
    self.needed_locks = {}
3145

    
3146
  def CheckPrereq(self):
3147
    """No prerequsites needed for this LU.
3148

3149
    """
3150
    pass
3151

    
3152
  def Exec(self, feedback_fn):
3153
    """Return cluster config.
3154

3155
    """
3156
    cluster = self.cfg.GetClusterInfo()
3157
    result = {
3158
      "software_version": constants.RELEASE_VERSION,
3159
      "protocol_version": constants.PROTOCOL_VERSION,
3160
      "config_version": constants.CONFIG_VERSION,
3161
      "os_api_version": max(constants.OS_API_VERSIONS),
3162
      "export_version": constants.EXPORT_VERSION,
3163
      "architecture": (platform.architecture()[0], platform.machine()),
3164
      "name": cluster.cluster_name,
3165
      "master": cluster.master_node,
3166
      "default_hypervisor": cluster.enabled_hypervisors[0],
3167
      "enabled_hypervisors": cluster.enabled_hypervisors,
3168
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
3169
                        for hypervisor_name in cluster.enabled_hypervisors]),
3170
      "beparams": cluster.beparams,
3171
      "nicparams": cluster.nicparams,
3172
      "candidate_pool_size": cluster.candidate_pool_size,
3173
      "master_netdev": cluster.master_netdev,
3174
      "volume_group_name": cluster.volume_group_name,
3175
      "file_storage_dir": cluster.file_storage_dir,
3176
      "ctime": cluster.ctime,
3177
      "mtime": cluster.mtime,
3178
      "uuid": cluster.uuid,
3179
      "tags": list(cluster.GetTags()),
3180
      }
3181

    
3182
    return result
3183

    
3184

    
3185
class LUQueryConfigValues(NoHooksLU):
3186
  """Return configuration values.
3187

3188
  """
3189
  _OP_REQP = []
3190
  REQ_BGL = False
3191
  _FIELDS_DYNAMIC = utils.FieldSet()
3192
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
3193
                                  "watcher_pause")
3194

    
3195
  def ExpandNames(self):
3196
    self.needed_locks = {}
3197

    
3198
    _CheckOutputFields(static=self._FIELDS_STATIC,
3199
                       dynamic=self._FIELDS_DYNAMIC,
3200
                       selected=self.op.output_fields)
3201

    
3202
  def CheckPrereq(self):
3203
    """No prerequisites.
3204

3205
    """
3206
    pass
3207

    
3208
  def Exec(self, feedback_fn):
3209
    """Dump a representation of the cluster config to the standard output.
3210

3211
    """
3212
    values = []
3213
    for field in self.op.output_fields:
3214
      if field == "cluster_name":
3215
        entry = self.cfg.GetClusterName()
3216
      elif field == "master_node":
3217
        entry = self.cfg.GetMasterNode()
3218
      elif field == "drain_flag":
3219
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
3220
      elif field == "watcher_pause":
3221
        return utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
3222
      else:
3223
        raise errors.ParameterError(field)
3224
      values.append(entry)
3225
    return values
3226

    
3227

    
3228
class LUActivateInstanceDisks(NoHooksLU):
3229
  """Bring up an instance's disks.
3230

3231
  """
3232
  _OP_REQP = ["instance_name"]
3233
  REQ_BGL = False
3234

    
3235
  def ExpandNames(self):
3236
    self._ExpandAndLockInstance()
3237
    self.needed_locks[locking.LEVEL_NODE] = []
3238
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3239

    
3240
  def DeclareLocks(self, level):
3241
    if level == locking.LEVEL_NODE:
3242
      self._LockInstancesNodes()
3243

    
3244
  def CheckPrereq(self):
3245
    """Check prerequisites.
3246

3247
    This checks that the instance is in the cluster.
3248

3249
    """
3250
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3251
    assert self.instance is not None, \
3252
      "Cannot retrieve locked instance %s" % self.op.instance_name
3253
    _CheckNodeOnline(self, self.instance.primary_node)
3254
    if not hasattr(self.op, "ignore_size"):
3255
      self.op.ignore_size = False
3256

    
3257
  def Exec(self, feedback_fn):
3258
    """Activate the disks.
3259

3260
    """
3261
    disks_ok, disks_info = \
3262
              _AssembleInstanceDisks(self, self.instance,
3263
                                     ignore_size=self.op.ignore_size)
3264
    if not disks_ok:
3265
      raise errors.OpExecError("Cannot activate block devices")
3266

    
3267
    return disks_info
3268

    
3269

    
3270
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False,
3271
                           ignore_size=False):
3272
  """Prepare the block devices for an instance.
3273

3274
  This sets up the block devices on all nodes.
3275

3276
  @type lu: L{LogicalUnit}
3277
  @param lu: the logical unit on whose behalf we execute
3278
  @type instance: L{objects.Instance}
3279
  @param instance: the instance for whose disks we assemble
3280
  @type ignore_secondaries: boolean
3281
  @param ignore_secondaries: if true, errors on secondary nodes
3282
      won't result in an error return from the function
3283
  @type ignore_size: boolean
3284
  @param ignore_size: if true, the current known size of the disk
3285
      will not be used during the disk activation, useful for cases
3286
      when the size is wrong
3287
  @return: False if the operation failed, otherwise a list of
3288
      (host, instance_visible_name, node_visible_name)
3289
      with the mapping from node devices to instance devices
3290

3291
  """
3292
  device_info = []
3293
  disks_ok = True
3294
  iname = instance.name
3295
  # With the two passes mechanism we try to reduce the window of
3296
  # opportunity for the race condition of switching DRBD to primary
3297
  # before handshaking occured, but we do not eliminate it
3298

    
3299
  # The proper fix would be to wait (with some limits) until the
3300
  # connection has been made and drbd transitions from WFConnection
3301
  # into any other network-connected state (Connected, SyncTarget,
3302
  # SyncSource, etc.)
3303

    
3304
  # 1st pass, assemble on all nodes in secondary mode
3305
  for inst_disk in instance.disks:
3306
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3307
      if ignore_size:
3308
        node_disk = node_disk.Copy()
3309
        node_disk.UnsetSize()
3310
      lu.cfg.SetDiskID(node_disk, node)
3311
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
3312
      msg = result.fail_msg
3313
      if msg:
3314
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3315
                           " (is_primary=False, pass=1): %s",
3316
                           inst_disk.iv_name, node, msg)
3317
        if not ignore_secondaries:
3318
          disks_ok = False
3319

    
3320
  # FIXME: race condition on drbd migration to primary
3321

    
3322
  # 2nd pass, do only the primary node
3323
  for inst_disk in instance.disks:
3324
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3325
      if node != instance.primary_node:
3326
        continue
3327
      if ignore_size:
3328
        node_disk = node_disk.Copy()
3329
        node_disk.UnsetSize()
3330
      lu.cfg.SetDiskID(node_disk, node)
3331
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
3332
      msg = result.fail_msg
3333
      if msg:
3334
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3335
                           " (is_primary=True, pass=2): %s",
3336
                           inst_disk.iv_name, node, msg)
3337
        disks_ok = False
3338
    device_info.append((instance.primary_node, inst_disk.iv_name,
3339
                        result.payload))
3340

    
3341
  # leave the disks configured for the primary node
3342
  # this is a workaround that would be fixed better by
3343
  # improving the logical/physical id handling
3344
  for disk in instance.disks:
3345
    lu.cfg.SetDiskID(disk, instance.primary_node)
3346

    
3347
  return disks_ok, device_info
3348

    
3349

    
3350
def _StartInstanceDisks(lu, instance, force):
3351
  """Start the disks of an instance.
3352

3353
  """
3354
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
3355
                                           ignore_secondaries=force)
3356
  if not disks_ok:
3357
    _ShutdownInstanceDisks(lu, instance)
3358
    if force is not None and not force:
3359
      lu.proc.LogWarning("", hint="If the message above refers to a"
3360
                         " secondary node,"
3361
                         " you can retry the operation using '--force'.")
3362
    raise errors.OpExecError("Disk consistency error")
3363

    
3364

    
3365
class LUDeactivateInstanceDisks(NoHooksLU):
3366
  """Shutdown an instance's disks.
3367

3368
  """
3369
  _OP_REQP = ["instance_name"]
3370
  REQ_BGL = False
3371

    
3372
  def ExpandNames(self):
3373
    self._ExpandAndLockInstance()
3374
    self.needed_locks[locking.LEVEL_NODE] = []
3375
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3376

    
3377
  def DeclareLocks(self, level):
3378
    if level == locking.LEVEL_NODE:
3379
      self._LockInstancesNodes()
3380

    
3381
  def CheckPrereq(self):
3382
    """Check prerequisites.
3383

3384
    This checks that the instance is in the cluster.
3385

3386
    """
3387
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3388
    assert self.instance is not None, \
3389
      "Cannot retrieve locked instance %s" % self.op.instance_name
3390

    
3391
  def Exec(self, feedback_fn):
3392
    """Deactivate the disks
3393

3394
    """
3395
    instance = self.instance
3396
    _SafeShutdownInstanceDisks(self, instance)
3397

    
3398

    
3399
def _SafeShutdownInstanceDisks(lu, instance):
3400
  """Shutdown block devices of an instance.
3401

3402
  This function checks if an instance is running, before calling
3403
  _ShutdownInstanceDisks.
3404

3405
  """
3406
  pnode = instance.primary_node
3407
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
3408
  ins_l.Raise("Can't contact node %s" % pnode)
3409

    
3410
  if instance.name in ins_l.payload:
3411
    raise errors.OpExecError("Instance is running, can't shutdown"
3412
                             " block devices.")
3413

    
3414
  _ShutdownInstanceDisks(lu, instance)
3415

    
3416

    
3417
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
3418
  """Shutdown block devices of an instance.
3419

3420
  This does the shutdown on all nodes of the instance.
3421

3422
  If the ignore_primary is false, errors on the primary node are
3423
  ignored.
3424

3425
  """
3426
  all_result = True
3427
  for disk in instance.disks:
3428
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
3429
      lu.cfg.SetDiskID(top_disk, node)
3430
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
3431
      msg = result.fail_msg
3432
      if msg:
3433
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
3434
                      disk.iv_name, node, msg)
3435
        if not ignore_primary or node != instance.primary_node:
3436
          all_result = False
3437
  return all_result
3438

    
3439

    
3440
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
3441
  """Checks if a node has enough free memory.
3442

3443
  This function check if a given node has the needed amount of free
3444
  memory. In case the node has less memory or we cannot get the
3445
  information from the node, this function raise an OpPrereqError
3446
  exception.
3447

3448
  @type lu: C{LogicalUnit}
3449
  @param lu: a logical unit from which we get configuration data
3450
  @type node: C{str}
3451
  @param node: the node to check
3452
  @type reason: C{str}
3453
  @param reason: string to use in the error message
3454
  @type requested: C{int}
3455
  @param requested: the amount of memory in MiB to check for
3456
  @type hypervisor_name: C{str}
3457
  @param hypervisor_name: the hypervisor to ask for memory stats
3458
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
3459
      we cannot check the node
3460

3461
  """
3462
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
3463
  nodeinfo[node].Raise("Can't get data from node %s" % node, prereq=True)
3464
  free_mem = nodeinfo[node].payload.get('memory_free', None)
3465
  if not isinstance(free_mem, int):
3466
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
3467
                               " was '%s'" % (node, free_mem))
3468
  if requested > free_mem:
3469
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
3470
                               " needed %s MiB, available %s MiB" %
3471
                               (node, reason, requested, free_mem))
3472

    
3473

    
3474
class LUStartupInstance(LogicalUnit):
3475
  """Starts an instance.
3476

3477
  """
3478
  HPATH = "instance-start"
3479
  HTYPE = constants.HTYPE_INSTANCE
3480
  _OP_REQP = ["instance_name", "force"]
3481
  REQ_BGL = False
3482

    
3483
  def ExpandNames(self):
3484
    self._ExpandAndLockInstance()
3485

    
3486
  def BuildHooksEnv(self):
3487
    """Build hooks env.
3488

3489
    This runs on master, primary and secondary nodes of the instance.
3490

3491
    """
3492
    env = {
3493
      "FORCE": self.op.force,
3494
      }
3495
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3496
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3497
    return env, nl, nl
3498

    
3499
  def CheckPrereq(self):
3500
    """Check prerequisites.
3501

3502
    This checks that the instance is in the cluster.
3503

3504
    """
3505
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3506
    assert self.instance is not None, \
3507
      "Cannot retrieve locked instance %s" % self.op.instance_name
3508

    
3509
    # extra beparams
3510
    self.beparams = getattr(self.op, "beparams", {})
3511
    if self.beparams:
3512
      if not isinstance(self.beparams, dict):
3513
        raise errors.OpPrereqError("Invalid beparams passed: %s, expected"
3514
                                   " dict" % (type(self.beparams), ))
3515
      # fill the beparams dict
3516
      utils.ForceDictType(self.beparams, constants.BES_PARAMETER_TYPES)
3517
      self.op.beparams = self.beparams
3518

    
3519
    # extra hvparams
3520
    self.hvparams = getattr(self.op, "hvparams", {})
3521
    if self.hvparams:
3522
      if not isinstance(self.hvparams, dict):
3523
        raise errors.OpPrereqError("Invalid hvparams passed: %s, expected"
3524
                                   " dict" % (type(self.hvparams), ))
3525

    
3526
      # check hypervisor parameter syntax (locally)
3527
      cluster = self.cfg.GetClusterInfo()
3528
      utils.ForceDictType(self.hvparams, constants.HVS_PARAMETER_TYPES)
3529
      filled_hvp = objects.FillDict(cluster.hvparams[instance.hypervisor],
3530
                                    instance.hvparams)
3531
      filled_hvp.update(self.hvparams)
3532
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
3533
      hv_type.CheckParameterSyntax(filled_hvp)
3534
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
3535
      self.op.hvparams = self.hvparams
3536

    
3537
    _CheckNodeOnline(self, instance.primary_node)
3538

    
3539
    bep = self.cfg.GetClusterInfo().FillBE(instance)
3540
    # check bridges existence
3541
    _CheckInstanceBridgesExist(self, instance)
3542

    
3543
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3544
                                              instance.name,
3545
                                              instance.hypervisor)
3546
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3547
                      prereq=True)
3548
    if not remote_info.payload: # not running already
3549
      _CheckNodeFreeMemory(self, instance.primary_node,
3550
                           "starting instance %s" % instance.name,
3551
                           bep[constants.BE_MEMORY], instance.hypervisor)
3552

    
3553
  def Exec(self, feedback_fn):
3554
    """Start the instance.
3555

3556
    """
3557
    instance = self.instance
3558
    force = self.op.force
3559

    
3560
    self.cfg.MarkInstanceUp(instance.name)
3561

    
3562
    node_current = instance.primary_node
3563

    
3564
    _StartInstanceDisks(self, instance, force)
3565

    
3566
    result = self.rpc.call_instance_start(node_current, instance,
3567
                                          self.hvparams, self.beparams)
3568
    msg = result.fail_msg
3569
    if msg:
3570
      _ShutdownInstanceDisks(self, instance)
3571
      raise errors.OpExecError("Could not start instance: %s" % msg)
3572

    
3573

    
3574
class LURebootInstance(LogicalUnit):
3575
  """Reboot an instance.
3576

3577
  """
3578
  HPATH = "instance-reboot"
3579
  HTYPE = constants.HTYPE_INSTANCE
3580
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
3581
  REQ_BGL = False
3582

    
3583
  def ExpandNames(self):
3584
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
3585
                                   constants.INSTANCE_REBOOT_HARD,
3586
                                   constants.INSTANCE_REBOOT_FULL]:
3587
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
3588
                                  (constants.INSTANCE_REBOOT_SOFT,
3589
                                   constants.INSTANCE_REBOOT_HARD,
3590
                                   constants.INSTANCE_REBOOT_FULL))
3591
    self._ExpandAndLockInstance()
3592

    
3593
  def BuildHooksEnv(self):
3594
    """Build hooks env.
3595

3596
    This runs on master, primary and secondary nodes of the instance.
3597

3598
    """
3599
    env = {
3600
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
3601
      "REBOOT_TYPE": self.op.reboot_type,
3602
      }
3603
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3604
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3605
    return env, nl, nl
3606

    
3607
  def CheckPrereq(self):
3608
    """Check prerequisites.
3609

3610
    This checks that the instance is in the cluster.
3611

3612
    """
3613
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3614
    assert self.instance is not None, \
3615
      "Cannot retrieve locked instance %s" % self.op.instance_name
3616

    
3617
    _CheckNodeOnline(self, instance.primary_node)
3618

    
3619
    # check bridges existence
3620
    _CheckInstanceBridgesExist(self, instance)
3621

    
3622
  def Exec(self, feedback_fn):
3623
    """Reboot the instance.
3624

3625
    """
3626
    instance = self.instance
3627
    ignore_secondaries = self.op.ignore_secondaries
3628
    reboot_type = self.op.reboot_type
3629

    
3630
    node_current = instance.primary_node
3631

    
3632
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
3633
                       constants.INSTANCE_REBOOT_HARD]:
3634
      for disk in instance.disks:
3635
        self.cfg.SetDiskID(disk, node_current)
3636
      result = self.rpc.call_instance_reboot(node_current, instance,
3637
                                             reboot_type)
3638
      result.Raise("Could not reboot instance")
3639
    else:
3640
      result = self.rpc.call_instance_shutdown(node_current, instance)
3641
      result.Raise("Could not shutdown instance for full reboot")
3642
      _ShutdownInstanceDisks(self, instance)
3643
      _StartInstanceDisks(self, instance, ignore_secondaries)
3644
      result = self.rpc.call_instance_start(node_current, instance, None, None)
3645
      msg = result.fail_msg
3646
      if msg:
3647
        _ShutdownInstanceDisks(self, instance)
3648
        raise errors.OpExecError("Could not start instance for"
3649
                                 " full reboot: %s" % msg)
3650

    
3651
    self.cfg.MarkInstanceUp(instance.name)
3652

    
3653

    
3654
class LUShutdownInstance(LogicalUnit):
3655
  """Shutdown an instance.
3656

3657
  """
3658
  HPATH = "instance-stop"
3659
  HTYPE = constants.HTYPE_INSTANCE
3660
  _OP_REQP = ["instance_name"]
3661
  REQ_BGL = False
3662

    
3663
  def ExpandNames(self):
3664
    self._ExpandAndLockInstance()
3665

    
3666
  def BuildHooksEnv(self):
3667
    """Build hooks env.
3668

3669
    This runs on master, primary and secondary nodes of the instance.
3670

3671
    """
3672
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3673
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3674
    return env, nl, nl
3675

    
3676
  def CheckPrereq(self):
3677
    """Check prerequisites.
3678

3679
    This checks that the instance is in the cluster.
3680

3681
    """
3682
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3683
    assert self.instance is not None, \
3684
      "Cannot retrieve locked instance %s" % self.op.instance_name
3685
    _CheckNodeOnline(self, self.instance.primary_node)
3686

    
3687
  def Exec(self, feedback_fn):
3688
    """Shutdown the instance.
3689

3690
    """
3691
    instance = self.instance
3692
    node_current = instance.primary_node
3693
    self.cfg.MarkInstanceDown(instance.name)
3694
    result = self.rpc.call_instance_shutdown(node_current, instance)
3695
    msg = result.fail_msg
3696
    if msg:
3697
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
3698

    
3699
    _ShutdownInstanceDisks(self, instance)
3700

    
3701

    
3702
class LUReinstallInstance(LogicalUnit):
3703
  """Reinstall an instance.
3704

3705
  """
3706
  HPATH = "instance-reinstall"
3707
  HTYPE = constants.HTYPE_INSTANCE
3708
  _OP_REQP = ["instance_name"]
3709
  REQ_BGL = False
3710

    
3711
  def ExpandNames(self):
3712
    self._ExpandAndLockInstance()
3713

    
3714
  def BuildHooksEnv(self):
3715
    """Build hooks env.
3716

3717
    This runs on master, primary and secondary nodes of the instance.
3718

3719
    """
3720
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3721
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3722
    return env, nl, nl
3723

    
3724
  def CheckPrereq(self):
3725
    """Check prerequisites.
3726

3727
    This checks that the instance is in the cluster and is not running.
3728

3729
    """
3730
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3731
    assert instance is not None, \
3732
      "Cannot retrieve locked instance %s" % self.op.instance_name
3733
    _CheckNodeOnline(self, instance.primary_node)
3734

    
3735
    if instance.disk_template == constants.DT_DISKLESS:
3736
      raise errors.OpPrereqError("Instance '%s' has no disks" %
3737
                                 self.op.instance_name)
3738
    if instance.admin_up:
3739
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
3740
                                 self.op.instance_name)
3741
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3742
                                              instance.name,
3743
                                              instance.hypervisor)
3744
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3745
                      prereq=True)
3746
    if remote_info.payload:
3747
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
3748
                                 (self.op.instance_name,
3749
                                  instance.primary_node))
3750

    
3751
    self.op.os_type = getattr(self.op, "os_type", None)
3752
    if self.op.os_type is not None:
3753
      # OS verification
3754
      pnode = self.cfg.GetNodeInfo(
3755
        self.cfg.ExpandNodeName(instance.primary_node))
3756
      if pnode is None:
3757
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
3758
                                   self.op.pnode)
3759
      result = self.rpc.call_os_get(pnode.name, self.op.os_type)
3760
      result.Raise("OS '%s' not in supported OS list for primary node %s" %
3761
                   (self.op.os_type, pnode.name), prereq=True)
3762

    
3763
    self.instance = instance
3764

    
3765
  def Exec(self, feedback_fn):
3766
    """Reinstall the instance.
3767

3768
    """
3769
    inst = self.instance
3770

    
3771
    if self.op.os_type is not None:
3772
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
3773
      inst.os = self.op.os_type
3774
      self.cfg.Update(inst)
3775

    
3776
    _StartInstanceDisks(self, inst, None)
3777
    try:
3778
      feedback_fn("Running the instance OS create scripts...")
3779
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True)
3780
      result.Raise("Could not install OS for instance %s on node %s" %
3781
                   (inst.name, inst.primary_node))
3782
    finally:
3783
      _ShutdownInstanceDisks(self, inst)
3784

    
3785

    
3786
class LURecreateInstanceDisks(LogicalUnit):
3787
  """Recreate an instance's missing disks.
3788

3789
  """
3790
  HPATH = "instance-recreate-disks"
3791
  HTYPE = constants.HTYPE_INSTANCE
3792
  _OP_REQP = ["instance_name", "disks"]
3793
  REQ_BGL = False
3794

    
3795
  def CheckArguments(self):
3796
    """Check the arguments.
3797

3798
    """
3799
    if not isinstance(self.op.disks, list):
3800
      raise errors.OpPrereqError("Invalid disks parameter")
3801
    for item in self.op.disks:
3802
      if (not isinstance(item, int) or
3803
          item < 0):
3804
        raise errors.OpPrereqError("Invalid disk specification '%s'" %
3805
                                   str(item))
3806

    
3807
  def ExpandNames(self):
3808
    self._ExpandAndLockInstance()
3809

    
3810
  def BuildHooksEnv(self):
3811
    """Build hooks env.
3812

3813
    This runs on master, primary and secondary nodes of the instance.
3814

3815
    """
3816
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3817
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3818
    return env, nl, nl
3819

    
3820
  def CheckPrereq(self):
3821
    """Check prerequisites.
3822

3823
    This checks that the instance is in the cluster and is not running.
3824

3825
    """
3826
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3827
    assert instance is not None, \
3828
      "Cannot retrieve locked instance %s" % self.op.instance_name
3829
    _CheckNodeOnline(self, instance.primary_node)
3830

    
3831
    if instance.disk_template == constants.DT_DISKLESS:
3832
      raise errors.OpPrereqError("Instance '%s' has no disks" %
3833
                                 self.op.instance_name)
3834
    if instance.admin_up:
3835
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
3836
                                 self.op.instance_name)
3837
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3838
                                              instance.name,
3839
                                              instance.hypervisor)
3840
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3841
                      prereq=True)
3842
    if remote_info.payload:
3843
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
3844
                                 (self.op.instance_name,
3845
                                  instance.primary_node))
3846

    
3847
    if not self.op.disks:
3848
      self.op.disks = range(len(instance.disks))
3849
    else:
3850
      for idx in self.op.disks:
3851
        if idx >= len(instance.disks):
3852
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx)
3853

    
3854
    self.instance = instance
3855

    
3856
  def Exec(self, feedback_fn):
3857
    """Recreate the disks.
3858

3859
    """
3860
    to_skip = []
3861
    for idx, disk in enumerate(self.instance.disks):
3862
      if idx not in self.op.disks: # disk idx has not been passed in
3863
        to_skip.append(idx)
3864
        continue
3865

    
3866
    _CreateDisks(self, self.instance, to_skip=to_skip)
3867

    
3868

    
3869
class LURenameInstance(LogicalUnit):
3870
  """Rename an instance.
3871

3872
  """
3873
  HPATH = "instance-rename"
3874
  HTYPE = constants.HTYPE_INSTANCE
3875
  _OP_REQP = ["instance_name", "new_name"]
3876

    
3877
  def BuildHooksEnv(self):
3878
    """Build hooks env.
3879

3880
    This runs on master, primary and secondary nodes of the instance.
3881

3882
    """
3883
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3884
    env["INSTANCE_NEW_NAME"] = self.op.new_name
3885
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3886
    return env, nl, nl
3887

    
3888
  def CheckPrereq(self):
3889
    """Check prerequisites.
3890

3891
    This checks that the instance is in the cluster and is not running.
3892

3893
    """
3894
    instance = self.cfg.GetInstanceInfo(
3895
      self.cfg.ExpandInstanceName(self.op.instance_name))
3896
    if instance is None:
3897
      raise errors.OpPrereqError("Instance '%s' not known" %
3898
                                 self.op.instance_name)
3899
    _CheckNodeOnline(self, instance.primary_node)
3900

    
3901
    if instance.admin_up:
3902
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
3903
                                 self.op.instance_name)
3904
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3905
                                              instance.name,
3906
                                              instance.hypervisor)
3907
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3908
                      prereq=True)
3909
    if remote_info.payload:
3910
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
3911
                                 (self.op.instance_name,
3912
                                  instance.primary_node))
3913
    self.instance = instance
3914

    
3915
    # new name verification
3916
    name_info = utils.HostInfo(self.op.new_name)
3917

    
3918
    self.op.new_name = new_name = name_info.name
3919
    instance_list = self.cfg.GetInstanceList()
3920
    if new_name in instance_list:
3921
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
3922
                                 new_name)
3923

    
3924
    if not getattr(self.op, "ignore_ip", False):
3925
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
3926
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
3927
                                   (name_info.ip, new_name))
3928

    
3929

    
3930
  def Exec(self, feedback_fn):
3931
    """Reinstall the instance.
3932

3933
    """
3934
    inst = self.instance
3935
    old_name = inst.name
3936

    
3937
    if inst.disk_template == constants.DT_FILE:
3938
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
3939

    
3940
    self.cfg.RenameInstance(inst.name, self.op.new_name)
3941
    # Change the instance lock. This is definitely safe while we hold the BGL
3942
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
3943
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
3944

    
3945
    # re-read the instance from the configuration after rename
3946
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
3947

    
3948
    if inst.disk_template == constants.DT_FILE:
3949
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
3950
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
3951
                                                     old_file_storage_dir,
3952
                                                     new_file_storage_dir)
3953
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
3954
                   " (but the instance has been renamed in Ganeti)" %
3955
                   (inst.primary_node, old_file_storage_dir,
3956
                    new_file_storage_dir))
3957

    
3958
    _StartInstanceDisks(self, inst, None)
3959
    try:
3960
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
3961
                                                 old_name)
3962
      msg = result.fail_msg
3963
      if msg:
3964
        msg = ("Could not run OS rename script for instance %s on node %s"
3965
               " (but the instance has been renamed in Ganeti): %s" %
3966
               (inst.name, inst.primary_node, msg))
3967
        self.proc.LogWarning(msg)
3968
    finally:
3969
      _ShutdownInstanceDisks(self, inst)
3970

    
3971

    
3972
class LURemoveInstance(LogicalUnit):
3973
  """Remove an instance.
3974

3975
  """
3976
  HPATH = "instance-remove"
3977
  HTYPE = constants.HTYPE_INSTANCE
3978
  _OP_REQP = ["instance_name", "ignore_failures"]
3979
  REQ_BGL = False
3980

    
3981
  def ExpandNames(self):
3982
    self._ExpandAndLockInstance()
3983
    self.needed_locks[locking.LEVEL_NODE] = []
3984
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3985

    
3986
  def DeclareLocks(self, level):
3987
    if level == locking.LEVEL_NODE:
3988
      self._LockInstancesNodes()
3989

    
3990
  def BuildHooksEnv(self):
3991
    """Build hooks env.
3992

3993
    This runs on master, primary and secondary nodes of the instance.
3994

3995
    """
3996
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3997
    nl = [self.cfg.GetMasterNode()]
3998
    return env, nl, nl
3999

    
4000
  def CheckPrereq(self):
4001
    """Check prerequisites.
4002

4003
    This checks that the instance is in the cluster.
4004

4005
    """
4006
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4007
    assert self.instance is not None, \
4008
      "Cannot retrieve locked instance %s" % self.op.instance_name
4009

    
4010
  def Exec(self, feedback_fn):
4011
    """Remove the instance.
4012

4013
    """
4014
    instance = self.instance
4015
    logging.info("Shutting down instance %s on node %s",
4016
                 instance.name, instance.primary_node)
4017

    
4018
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance)
4019
    msg = result.fail_msg
4020
    if msg:
4021
      if self.op.ignore_failures:
4022
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
4023
      else:
4024
        raise errors.OpExecError("Could not shutdown instance %s on"
4025
                                 " node %s: %s" %
4026
                                 (instance.name, instance.primary_node, msg))
4027

    
4028
    logging.info("Removing block devices for instance %s", instance.name)
4029

    
4030
    if not _RemoveDisks(self, instance):
4031
      if self.op.ignore_failures:
4032
        feedback_fn("Warning: can't remove instance's disks")
4033
      else:
4034
        raise errors.OpExecError("Can't remove instance's disks")
4035

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

    
4038
    self.cfg.RemoveInstance(instance.name)
4039
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
4040

    
4041

    
4042
class LUQueryInstances(NoHooksLU):
4043
  """Logical unit for querying instances.
4044

4045
  """
4046
  _OP_REQP = ["output_fields", "names", "use_locking"]
4047
  REQ_BGL = False
4048
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
4049
                    "serial_no", "ctime", "mtime", "uuid"]
4050
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
4051
                                    "admin_state",
4052
                                    "disk_template", "ip", "mac", "bridge",
4053
                                    "nic_mode", "nic_link",
4054
                                    "sda_size", "sdb_size", "vcpus", "tags",
4055
                                    "network_port", "beparams",
4056
                                    r"(disk)\.(size)/([0-9]+)",
4057
                                    r"(disk)\.(sizes)", "disk_usage",
4058
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
4059
                                    r"(nic)\.(bridge)/([0-9]+)",
4060
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
4061
                                    r"(disk|nic)\.(count)",
4062
                                    "hvparams",
4063
                                    ] + _SIMPLE_FIELDS +
4064
                                  ["hv/%s" % name
4065
                                   for name in constants.HVS_PARAMETERS] +
4066
                                  ["be/%s" % name
4067
                                   for name in constants.BES_PARAMETERS])
4068
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
4069

    
4070

    
4071
  def ExpandNames(self):
4072
    _CheckOutputFields(static=self._FIELDS_STATIC,
4073
                       dynamic=self._FIELDS_DYNAMIC,
4074
                       selected=self.op.output_fields)
4075

    
4076
    self.needed_locks = {}
4077
    self.share_locks[locking.LEVEL_INSTANCE] = 1
4078
    self.share_locks[locking.LEVEL_NODE] = 1
4079

    
4080
    if self.op.names:
4081
      self.wanted = _GetWantedInstances(self, self.op.names)
4082
    else:
4083
      self.wanted = locking.ALL_SET
4084

    
4085
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
4086
    self.do_locking = self.do_node_query and self.op.use_locking
4087
    if self.do_locking:
4088
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4089
      self.needed_locks[locking.LEVEL_NODE] = []
4090
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4091

    
4092
  def DeclareLocks(self, level):
4093
    if level == locking.LEVEL_NODE and self.do_locking:
4094
      self._LockInstancesNodes()
4095

    
4096
  def CheckPrereq(self):
4097
    """Check prerequisites.
4098

4099
    """
4100
    pass
4101

    
4102
  def Exec(self, feedback_fn):
4103
    """Computes the list of nodes and their attributes.
4104

4105
    """
4106
    all_info = self.cfg.GetAllInstancesInfo()
4107
    if self.wanted == locking.ALL_SET:
4108
      # caller didn't specify instance names, so ordering is not important
4109
      if self.do_locking:
4110
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
4111
      else:
4112
        instance_names = all_info.keys()
4113
      instance_names = utils.NiceSort(instance_names)
4114
    else:
4115
      # caller did specify names, so we must keep the ordering
4116
      if self.do_locking:
4117
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
4118
      else:
4119
        tgt_set = all_info.keys()
4120
      missing = set(self.wanted).difference(tgt_set)
4121
      if missing:
4122
        raise errors.OpExecError("Some instances were removed before"
4123
                                 " retrieving their data: %s" % missing)
4124
      instance_names = self.wanted
4125

    
4126
    instance_list = [all_info[iname] for iname in instance_names]
4127

    
4128
    # begin data gathering
4129

    
4130
    nodes = frozenset([inst.primary_node for inst in instance_list])
4131
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
4132

    
4133
    bad_nodes = []
4134
    off_nodes = []
4135
    if self.do_node_query:
4136
      live_data = {}
4137
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
4138
      for name in nodes:
4139
        result = node_data[name]
4140
        if result.offline:
4141
          # offline nodes will be in both lists
4142
          off_nodes.append(name)
4143
        if result.fail_msg:
4144
          bad_nodes.append(name)
4145
        else:
4146
          if result.payload:
4147
            live_data.update(result.payload)
4148
          # else no instance is alive
4149
    else:
4150
      live_data = dict([(name, {}) for name in instance_names])
4151

    
4152
    # end data gathering
4153

    
4154
    HVPREFIX = "hv/"
4155
    BEPREFIX = "be/"
4156
    output = []
4157
    cluster = self.cfg.GetClusterInfo()
4158
    for instance in instance_list:
4159
      iout = []
4160
      i_hv = cluster.FillHV(instance)
4161
      i_be = cluster.FillBE(instance)
4162
      i_nicp = [objects.FillDict(cluster.nicparams[constants.PP_DEFAULT],
4163
                                 nic.nicparams) for nic in instance.nics]
4164
      for field in self.op.output_fields:
4165
        st_match = self._FIELDS_STATIC.Matches(field)
4166
        if field in self._SIMPLE_FIELDS:
4167
          val = getattr(instance, field)
4168
        elif field == "pnode":
4169
          val = instance.primary_node
4170
        elif field == "snodes":
4171
          val = list(instance.secondary_nodes)
4172
        elif field == "admin_state":
4173
          val = instance.admin_up
4174
        elif field == "oper_state":
4175
          if instance.primary_node in bad_nodes:
4176
            val = None
4177
          else:
4178
            val = bool(live_data.get(instance.name))
4179
        elif field == "status":
4180
          if instance.primary_node in off_nodes:
4181
            val = "ERROR_nodeoffline"
4182
          elif instance.primary_node in bad_nodes:
4183
            val = "ERROR_nodedown"
4184
          else:
4185
            running = bool(live_data.get(instance.name))
4186
            if running:
4187
              if instance.admin_up:
4188
                val = "running"
4189
              else:
4190
                val = "ERROR_up"
4191
            else:
4192
              if instance.admin_up:
4193
                val = "ERROR_down"
4194
              else:
4195
                val = "ADMIN_down"
4196
        elif field == "oper_ram":
4197
          if instance.primary_node in bad_nodes:
4198
            val = None
4199
          elif instance.name in live_data:
4200
            val = live_data[instance.name].get("memory", "?")
4201
          else:
4202
            val = "-"
4203
        elif field == "vcpus":
4204
          val = i_be[constants.BE_VCPUS]
4205
        elif field == "disk_template":
4206
          val = instance.disk_template
4207
        elif field == "ip":
4208
          if instance.nics:
4209
            val = instance.nics[0].ip
4210
          else:
4211
            val = None
4212
        elif field == "nic_mode":
4213
          if instance.nics:
4214
            val = i_nicp[0][constants.NIC_MODE]
4215
          else:
4216
            val = None
4217
        elif field == "nic_link":
4218
          if instance.nics:
4219
            val = i_nicp[0][constants.NIC_LINK]
4220
          else:
4221
            val = None
4222
        elif field == "bridge":
4223
          if (instance.nics and
4224
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
4225
            val = i_nicp[0][constants.NIC_LINK]
4226
          else:
4227
            val = None
4228
        elif field == "mac":
4229
          if instance.nics:
4230
            val = instance.nics[0].mac
4231
          else:
4232
            val = None
4233
        elif field == "sda_size" or field == "sdb_size":
4234
          idx = ord(field[2]) - ord('a')
4235
          try:
4236
            val = instance.FindDisk(idx).size
4237
          except errors.OpPrereqError:
4238
            val = None
4239
        elif field == "disk_usage": # total disk usage per node
4240
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
4241
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
4242
        elif field == "tags":
4243
          val = list(instance.GetTags())
4244
        elif field == "hvparams":
4245
          val = i_hv
4246
        elif (field.startswith(HVPREFIX) and
4247
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS):
4248
          val = i_hv.get(field[len(HVPREFIX):], None)
4249
        elif field == "beparams":
4250
          val = i_be
4251
        elif (field.startswith(BEPREFIX) and
4252
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
4253
          val = i_be.get(field[len(BEPREFIX):], None)
4254
        elif st_match and st_match.groups():
4255
          # matches a variable list
4256
          st_groups = st_match.groups()
4257
          if st_groups and st_groups[0] == "disk":
4258
            if st_groups[1] == "count":
4259
              val = len(instance.disks)
4260
            elif st_groups[1] == "sizes":
4261
              val = [disk.size for disk in instance.disks]
4262
            elif st_groups[1] == "size":
4263
              try:
4264
                val = instance.FindDisk(st_groups[2]).size
4265
              except errors.OpPrereqError:
4266
                val = None
4267
            else:
4268
              assert False, "Unhandled disk parameter"
4269
          elif st_groups[0] == "nic":
4270
            if st_groups[1] == "count":
4271
              val = len(instance.nics)
4272
            elif st_groups[1] == "macs":
4273
              val = [nic.mac for nic in instance.nics]
4274
            elif st_groups[1] == "ips":
4275
              val = [nic.ip for nic in instance.nics]
4276
            elif st_groups[1] == "modes":
4277
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
4278
            elif st_groups[1] == "links":
4279
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
4280
            elif st_groups[1] == "bridges":
4281
              val = []
4282
              for nicp in i_nicp:
4283
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
4284
                  val.append(nicp[constants.NIC_LINK])
4285
                else:
4286
                  val.append(None)
4287
            else:
4288
              # index-based item
4289
              nic_idx = int(st_groups[2])
4290
              if nic_idx >= len(instance.nics):
4291
                val = None
4292
              else:
4293
                if st_groups[1] == "mac":
4294
                  val = instance.nics[nic_idx].mac
4295
                elif st_groups[1] == "ip":
4296
                  val = instance.nics[nic_idx].ip
4297
                elif st_groups[1] == "mode":
4298
                  val = i_nicp[nic_idx][constants.NIC_MODE]
4299
                elif st_groups[1] == "link":
4300
                  val = i_nicp[nic_idx][constants.NIC_LINK]
4301
                elif st_groups[1] == "bridge":
4302
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
4303
                  if nic_mode == constants.NIC_MODE_BRIDGED:
4304
                    val = i_nicp[nic_idx][constants.NIC_LINK]
4305
                  else:
4306
                    val = None
4307
                else:
4308
                  assert False, "Unhandled NIC parameter"
4309
          else:
4310
            assert False, ("Declared but unhandled variable parameter '%s'" %
4311
                           field)
4312
        else:
4313
          assert False, "Declared but unhandled parameter '%s'" % field
4314
        iout.append(val)
4315
      output.append(iout)
4316

    
4317
    return output
4318

    
4319

    
4320
class LUFailoverInstance(LogicalUnit):
4321
  """Failover an instance.
4322

4323
  """
4324
  HPATH = "instance-failover"
4325
  HTYPE = constants.HTYPE_INSTANCE
4326
  _OP_REQP = ["instance_name", "ignore_consistency"]
4327
  REQ_BGL = False
4328

    
4329
  def ExpandNames(self):
4330
    self._ExpandAndLockInstance()
4331
    self.needed_locks[locking.LEVEL_NODE] = []
4332
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4333

    
4334
  def DeclareLocks(self, level):
4335
    if level == locking.LEVEL_NODE:
4336
      self._LockInstancesNodes()
4337

    
4338
  def BuildHooksEnv(self):
4339
    """Build hooks env.
4340

4341
    This runs on master, primary and secondary nodes of the instance.
4342

4343
    """
4344
    env = {
4345
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
4346
      }
4347
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4348
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
4349
    return env, nl, nl
4350

    
4351
  def CheckPrereq(self):
4352
    """Check prerequisites.
4353

4354
    This checks that the instance is in the cluster.
4355

4356
    """
4357
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4358
    assert self.instance is not None, \
4359
      "Cannot retrieve locked instance %s" % self.op.instance_name
4360

    
4361
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4362
    if instance.disk_template not in constants.DTS_NET_MIRROR:
4363
      raise errors.OpPrereqError("Instance's disk layout is not"
4364
                                 " network mirrored, cannot failover.")
4365

    
4366
    secondary_nodes = instance.secondary_nodes
4367
    if not secondary_nodes:
4368
      raise errors.ProgrammerError("no secondary node but using "
4369
                                   "a mirrored disk template")
4370

    
4371
    target_node = secondary_nodes[0]
4372
    _CheckNodeOnline(self, target_node)
4373
    _CheckNodeNotDrained(self, target_node)
4374
    if instance.admin_up:
4375
      # check memory requirements on the secondary node
4376
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
4377
                           instance.name, bep[constants.BE_MEMORY],
4378
                           instance.hypervisor)
4379
    else:
4380
      self.LogInfo("Not checking memory on the secondary node as"
4381
                   " instance will not be started")
4382

    
4383
    # check bridge existance
4384
    _CheckInstanceBridgesExist(self, instance, node=target_node)
4385

    
4386
  def Exec(self, feedback_fn):
4387
    """Failover an instance.
4388

4389
    The failover is done by shutting it down on its present node and
4390
    starting it on the secondary.
4391

4392
    """
4393
    instance = self.instance
4394

    
4395
    source_node = instance.primary_node
4396
    target_node = instance.secondary_nodes[0]
4397

    
4398
    feedback_fn("* checking disk consistency between source and target")
4399
    for dev in instance.disks:
4400
      # for drbd, these are drbd over lvm
4401
      if not _CheckDiskConsistency(self, dev, target_node, False):
4402
        if instance.admin_up and not self.op.ignore_consistency:
4403
          raise errors.OpExecError("Disk %s is degraded on target node,"
4404
                                   " aborting failover." % dev.iv_name)
4405

    
4406
    feedback_fn("* shutting down instance on source node")
4407
    logging.info("Shutting down instance %s on node %s",
4408
                 instance.name, source_node)
4409

    
4410
    result = self.rpc.call_instance_shutdown(source_node, instance)
4411
    msg = result.fail_msg
4412
    if msg:
4413
      if self.op.ignore_consistency:
4414
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
4415
                             " Proceeding anyway. Please make sure node"
4416
                             " %s is down. Error details: %s",
4417
                             instance.name, source_node, source_node, msg)
4418
      else:
4419
        raise errors.OpExecError("Could not shutdown instance %s on"
4420
                                 " node %s: %s" %
4421
                                 (instance.name, source_node, msg))
4422

    
4423
    feedback_fn("* deactivating the instance's disks on source node")
4424
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
4425
      raise errors.OpExecError("Can't shut down the instance's disks.")
4426

    
4427
    instance.primary_node = target_node
4428
    # distribute new instance config to the other nodes
4429
    self.cfg.Update(instance)
4430

    
4431
    # Only start the instance if it's marked as up
4432
    if instance.admin_up:
4433
      feedback_fn("* activating the instance's disks on target node")
4434
      logging.info("Starting instance %s on node %s",
4435
                   instance.name, target_node)
4436

    
4437
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
4438
                                               ignore_secondaries=True)
4439
      if not disks_ok:
4440
        _ShutdownInstanceDisks(self, instance)
4441
        raise errors.OpExecError("Can't activate the instance's disks")
4442

    
4443
      feedback_fn("* starting the instance on the target node")
4444
      result = self.rpc.call_instance_start(target_node, instance, None, None)
4445
      msg = result.fail_msg
4446
      if msg:
4447
        _ShutdownInstanceDisks(self, instance)
4448
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
4449
                                 (instance.name, target_node, msg))
4450

    
4451

    
4452
class LUMigrateInstance(LogicalUnit):
4453
  """Migrate an instance.
4454

4455
  This is migration without shutting down, compared to the failover,
4456
  which is done with shutdown.
4457

4458
  """
4459
  HPATH = "instance-migrate"
4460
  HTYPE = constants.HTYPE_INSTANCE
4461
  _OP_REQP = ["instance_name", "live", "cleanup"]
4462

    
4463
  REQ_BGL = False
4464

    
4465
  def ExpandNames(self):
4466
    self._ExpandAndLockInstance()
4467

    
4468
    self.needed_locks[locking.LEVEL_NODE] = []
4469
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4470

    
4471
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
4472
                                       self.op.live, self.op.cleanup)
4473
    self.tasklets = [self._migrater]
4474

    
4475
  def DeclareLocks(self, level):
4476
    if level == locking.LEVEL_NODE:
4477
      self._LockInstancesNodes()
4478

    
4479
  def BuildHooksEnv(self):
4480
    """Build hooks env.
4481

4482
    This runs on master, primary and secondary nodes of the instance.
4483

4484
    """
4485
    instance = self._migrater.instance
4486
    env = _BuildInstanceHookEnvByObject(self, instance)
4487
    env["MIGRATE_LIVE"] = self.op.live
4488
    env["MIGRATE_CLEANUP"] = self.op.cleanup
4489
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
4490
    return env, nl, nl
4491

    
4492

    
4493
class LUMoveInstance(LogicalUnit):
4494
  """Move an instance by data-copying.
4495

4496
  """
4497
  HPATH = "instance-move"
4498
  HTYPE = constants.HTYPE_INSTANCE
4499
  _OP_REQP = ["instance_name", "target_node"]
4500
  REQ_BGL = False
4501

    
4502
  def ExpandNames(self):
4503
    self._ExpandAndLockInstance()
4504
    target_node = self.cfg.ExpandNodeName(self.op.target_node)
4505
    if target_node is None:
4506
      raise errors.OpPrereqError("Node '%s' not known" %
4507
                                  self.op.target_node)
4508
    self.op.target_node = target_node
4509
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
4510
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4511

    
4512
  def DeclareLocks(self, level):
4513
    if level == locking.LEVEL_NODE:
4514
      self._LockInstancesNodes(primary_only=True)
4515

    
4516
  def BuildHooksEnv(self):
4517
    """Build hooks env.
4518

4519
    This runs on master, primary and secondary nodes of the instance.
4520

4521
    """
4522
    env = {
4523
      "TARGET_NODE": self.op.target_node,
4524
      }
4525
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4526
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
4527
                                       self.op.target_node]
4528
    return env, nl, nl
4529

    
4530
  def CheckPrereq(self):
4531
    """Check prerequisites.
4532

4533
    This checks that the instance is in the cluster.
4534

4535
    """
4536
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4537
    assert self.instance is not None, \
4538
      "Cannot retrieve locked instance %s" % self.op.instance_name
4539

    
4540
    node = self.cfg.GetNodeInfo(self.op.target_node)
4541
    assert node is not None, \
4542
      "Cannot retrieve locked node %s" % self.op.target_node
4543

    
4544
    self.target_node = target_node = node.name
4545

    
4546
    if target_node == instance.primary_node:
4547
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
4548
                                 (instance.name, target_node))
4549

    
4550
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4551

    
4552
    for idx, dsk in enumerate(instance.disks):
4553
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
4554
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
4555
                                   " cannot copy")
4556

    
4557
    _CheckNodeOnline(self, target_node)
4558
    _CheckNodeNotDrained(self, target_node)
4559

    
4560
    if instance.admin_up:
4561
      # check memory requirements on the secondary node
4562
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
4563
                           instance.name, bep[constants.BE_MEMORY],
4564
                           instance.hypervisor)
4565
    else:
4566
      self.LogInfo("Not checking memory on the secondary node as"
4567
                   " instance will not be started")
4568

    
4569
    # check bridge existance
4570
    _CheckInstanceBridgesExist(self, instance, node=target_node)
4571

    
4572
  def Exec(self, feedback_fn):
4573
    """Move an instance.
4574

4575
    The move is done by shutting it down on its present node, copying
4576
    the data over (slow) and starting it on the new node.
4577

4578
    """
4579
    instance = self.instance
4580

    
4581
    source_node = instance.primary_node
4582
    target_node = self.target_node
4583

    
4584
    self.LogInfo("Shutting down instance %s on source node %s",
4585
                 instance.name, source_node)
4586

    
4587
    result = self.rpc.call_instance_shutdown(source_node, instance)
4588
    msg = result.fail_msg
4589
    if msg:
4590
      if self.op.ignore_consistency:
4591
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
4592
                             " Proceeding anyway. Please make sure node"
4593
                             " %s is down. Error details: %s",
4594
                             instance.name, source_node, source_node, msg)
4595
      else:
4596
        raise errors.OpExecError("Could not shutdown instance %s on"
4597
                                 " node %s: %s" %
4598
                                 (instance.name, source_node, msg))
4599

    
4600
    # create the target disks
4601
    try:
4602
      _CreateDisks(self, instance, target_node=target_node)
4603
    except errors.OpExecError:
4604
      self.LogWarning("Device creation failed, reverting...")
4605
      try:
4606
        _RemoveDisks(self, instance, target_node=target_node)
4607
      finally:
4608
        self.cfg.ReleaseDRBDMinors(instance.name)
4609
        raise
4610

    
4611
    cluster_name = self.cfg.GetClusterInfo().cluster_name
4612

    
4613
    errs = []
4614
    # activate, get path, copy the data over
4615
    for idx, disk in enumerate(instance.disks):
4616
      self.LogInfo("Copying data for disk %d", idx)
4617
      result = self.rpc.call_blockdev_assemble(target_node, disk,
4618
                                               instance.name, True)
4619
      if result.fail_msg:
4620
        self.LogWarning("Can't assemble newly created disk %d: %s",
4621
                        idx, result.fail_msg)
4622
        errs.append(result.fail_msg)
4623
        break
4624
      dev_path = result.payload
4625
      result = self.rpc.call_blockdev_export(source_node, disk,
4626
                                             target_node, dev_path,
4627
                                             cluster_name)
4628
      if result.fail_msg:
4629
        self.LogWarning("Can't copy data over for disk %d: %s",
4630
                        idx, result.fail_msg)
4631
        errs.append(result.fail_msg)
4632
        break
4633

    
4634
    if errs:
4635
      self.LogWarning("Some disks failed to copy, aborting")
4636
      try:
4637
        _RemoveDisks(self, instance, target_node=target_node)
4638
      finally:
4639
        self.cfg.ReleaseDRBDMinors(instance.name)
4640
        raise errors.OpExecError("Errors during disk copy: %s" %
4641
                                 (",".join(errs),))
4642

    
4643
    instance.primary_node = target_node
4644
    self.cfg.Update(instance)
4645

    
4646
    self.LogInfo("Removing the disks on the original node")
4647
    _RemoveDisks(self, instance, target_node=source_node)
4648

    
4649
    # Only start the instance if it's marked as up
4650
    if instance.admin_up:
4651
      self.LogInfo("Starting instance %s on node %s",
4652
                   instance.name, target_node)
4653

    
4654
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
4655
                                           ignore_secondaries=True)
4656
      if not disks_ok:
4657
        _ShutdownInstanceDisks(self, instance)
4658
        raise errors.OpExecError("Can't activate the instance's disks")
4659

    
4660
      result = self.rpc.call_instance_start(target_node, instance, None, None)
4661
      msg = result.fail_msg
4662
      if msg:
4663
        _ShutdownInstanceDisks(self, instance)
4664
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
4665
                                 (instance.name, target_node, msg))
4666

    
4667

    
4668
class LUMigrateNode(LogicalUnit):
4669
  """Migrate all instances from a node.
4670

4671
  """
4672
  HPATH = "node-migrate"
4673
  HTYPE = constants.HTYPE_NODE
4674
  _OP_REQP = ["node_name", "live"]
4675
  REQ_BGL = False
4676

    
4677
  def ExpandNames(self):
4678
    self.op.node_name = self.cfg.ExpandNodeName(self.op.node_name)
4679
    if self.op.node_name is None:
4680
      raise errors.OpPrereqError("Node '%s' not known" % self.op.node_name)
4681

    
4682
    self.needed_locks = {
4683
      locking.LEVEL_NODE: [self.op.node_name],
4684
      }
4685

    
4686
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4687

    
4688
    # Create tasklets for migrating instances for all instances on this node
4689
    names = []
4690
    tasklets = []
4691

    
4692
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
4693
      logging.debug("Migrating instance %s", inst.name)
4694
      names.append(inst.name)
4695

    
4696
      tasklets.append(TLMigrateInstance(self, inst.name, self.op.live, False))
4697

    
4698
    self.tasklets = tasklets
4699

    
4700
    # Declare instance locks
4701
    self.needed_locks[locking.LEVEL_INSTANCE] = names
4702

    
4703
  def DeclareLocks(self, level):
4704
    if level == locking.LEVEL_NODE:
4705
      self._LockInstancesNodes()
4706

    
4707
  def BuildHooksEnv(self):
4708
    """Build hooks env.
4709

4710
    This runs on the master, the primary and all the secondaries.
4711

4712
    """
4713
    env = {
4714
      "NODE_NAME": self.op.node_name,
4715
      }
4716

    
4717
    nl = [self.cfg.GetMasterNode()]
4718

    
4719
    return (env, nl, nl)
4720

    
4721

    
4722
class TLMigrateInstance(Tasklet):
4723
  def __init__(self, lu, instance_name, live, cleanup):
4724
    """Initializes this class.
4725

4726
    """
4727
    Tasklet.__init__(self, lu)
4728

    
4729
    # Parameters
4730
    self.instance_name = instance_name
4731
    self.live = live
4732
    self.cleanup = cleanup
4733

    
4734
  def CheckPrereq(self):
4735
    """Check prerequisites.
4736

4737
    This checks that the instance is in the cluster.
4738

4739
    """
4740
    instance = self.cfg.GetInstanceInfo(
4741
      self.cfg.ExpandInstanceName(self.instance_name))
4742
    if instance is None:
4743
      raise errors.OpPrereqError("Instance '%s' not known" %
4744
                                 self.instance_name)
4745

    
4746
    if instance.disk_template != constants.DT_DRBD8:
4747
      raise errors.OpPrereqError("Instance's disk layout is not"
4748
                                 " drbd8, cannot migrate.")
4749

    
4750
    secondary_nodes = instance.secondary_nodes
4751
    if not secondary_nodes:
4752
      raise errors.ConfigurationError("No secondary node but using"
4753
                                      " drbd8 disk template")
4754

    
4755
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
4756

    
4757
    target_node = secondary_nodes[0]
4758
    # check memory requirements on the secondary node
4759
    _CheckNodeFreeMemory(self, target_node, "migrating instance %s" %
4760
                         instance.name, i_be[constants.BE_MEMORY],
4761
                         instance.hypervisor)
4762

    
4763
    # check bridge existance
4764
    _CheckInstanceBridgesExist(self, instance, node=target_node)
4765

    
4766
    if not self.cleanup:
4767
      _CheckNodeNotDrained(self, target_node)
4768
      result = self.rpc.call_instance_migratable(instance.primary_node,
4769
                                                 instance)
4770
      result.Raise("Can't migrate, please use failover", prereq=True)
4771

    
4772
    self.instance = instance
4773

    
4774
  def _WaitUntilSync(self):
4775
    """Poll with custom rpc for disk sync.
4776

4777
    This uses our own step-based rpc call.
4778

4779
    """
4780
    self.feedback_fn("* wait until resync is done")
4781
    all_done = False
4782
    while not all_done:
4783
      all_done = True
4784
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
4785
                                            self.nodes_ip,
4786
                                            self.instance.disks)
4787
      min_percent = 100
4788
      for node, nres in result.items():
4789
        nres.Raise("Cannot resync disks on node %s" % node)
4790
        node_done, node_percent = nres.payload
4791
        all_done = all_done and node_done
4792
        if node_percent is not None:
4793
          min_percent = min(min_percent, node_percent)
4794
      if not all_done:
4795
        if min_percent < 100:
4796
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
4797
        time.sleep(2)
4798

    
4799
  def _EnsureSecondary(self, node):
4800
    """Demote a node to secondary.
4801

4802
    """
4803
    self.feedback_fn("* switching node %s to secondary mode" % node)
4804

    
4805
    for dev in self.instance.disks:
4806
      self.cfg.SetDiskID(dev, node)
4807

    
4808
    result = self.rpc.call_blockdev_close(node, self.instance.name,
4809
                                          self.instance.disks)
4810
    result.Raise("Cannot change disk to secondary on node %s" % node)
4811

    
4812
  def _GoStandalone(self):
4813
    """Disconnect from the network.
4814

4815
    """
4816
    self.feedback_fn("* changing into standalone mode")
4817
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
4818
                                               self.instance.disks)
4819
    for node, nres in result.items():
4820
      nres.Raise("Cannot disconnect disks node %s" % node)
4821

    
4822
  def _GoReconnect(self, multimaster):
4823
    """Reconnect to the network.
4824

4825
    """
4826
    if multimaster:
4827
      msg = "dual-master"
4828
    else:
4829
      msg = "single-master"
4830
    self.feedback_fn("* changing disks into %s mode" % msg)
4831
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
4832
                                           self.instance.disks,
4833
                                           self.instance.name, multimaster)
4834
    for node, nres in result.items():
4835
      nres.Raise("Cannot change disks config on node %s" % node)
4836

    
4837
  def _ExecCleanup(self):
4838
    """Try to cleanup after a failed migration.
4839

4840
    The cleanup is done by:
4841
      - check that the instance is running only on one node
4842
        (and update the config if needed)
4843
      - change disks on its secondary node to secondary
4844
      - wait until disks are fully synchronized
4845
      - disconnect from the network
4846
      - change disks into single-master mode
4847
      - wait again until disks are fully synchronized
4848

4849
    """
4850
    instance = self.instance
4851
    target_node = self.target_node
4852
    source_node = self.source_node
4853

    
4854
    # check running on only one node
4855
    self.feedback_fn("* checking where the instance actually runs"
4856
                     " (if this hangs, the hypervisor might be in"
4857
                     " a bad state)")
4858
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
4859
    for node, result in ins_l.items():
4860
      result.Raise("Can't contact node %s" % node)
4861

    
4862
    runningon_source = instance.name in ins_l[source_node].payload
4863
    runningon_target = instance.name in ins_l[target_node].payload
4864

    
4865
    if runningon_source and runningon_target:
4866
      raise errors.OpExecError("Instance seems to be running on two nodes,"
4867
                               " or the hypervisor is confused. You will have"
4868
                               " to ensure manually that it runs only on one"
4869
                               " and restart this operation.")
4870

    
4871
    if not (runningon_source or runningon_target):
4872
      raise errors.OpExecError("Instance does not seem to be running at all."
4873
                               " In this case, it's safer to repair by"
4874
                               " running 'gnt-instance stop' to ensure disk"
4875
                               " shutdown, and then restarting it.")
4876

    
4877
    if runningon_target:
4878
      # the migration has actually succeeded, we need to update the config
4879
      self.feedback_fn("* instance running on secondary node (%s),"
4880
                       " updating config" % target_node)
4881
      instance.primary_node = target_node
4882
      self.cfg.Update(instance)
4883
      demoted_node = source_node
4884
    else:
4885
      self.feedback_fn("* instance confirmed to be running on its"
4886
                       " primary node (%s)" % source_node)
4887
      demoted_node = target_node
4888

    
4889
    self._EnsureSecondary(demoted_node)
4890
    try:
4891
      self._WaitUntilSync()
4892
    except errors.OpExecError:
4893
      # we ignore here errors, since if the device is standalone, it
4894
      # won't be able to sync
4895
      pass
4896
    self._GoStandalone()
4897
    self._GoReconnect(False)
4898
    self._WaitUntilSync()
4899

    
4900
    self.feedback_fn("* done")
4901

    
4902
  def _RevertDiskStatus(self):
4903
    """Try to revert the disk status after a failed migration.
4904

4905
    """
4906
    target_node = self.target_node
4907
    try:
4908
      self._EnsureSecondary(target_node)
4909
      self._GoStandalone()
4910
      self._GoReconnect(False)
4911
      self._WaitUntilSync()
4912
    except errors.OpExecError, err:
4913
      self.lu.LogWarning("Migration failed and I can't reconnect the"
4914
                         " drives: error '%s'\n"
4915
                         "Please look and recover the instance status" %
4916
                         str(err))
4917

    
4918
  def _AbortMigration(self):
4919
    """Call the hypervisor code to abort a started migration.
4920

4921
    """
4922
    instance = self.instance
4923
    target_node = self.target_node
4924
    migration_info = self.migration_info
4925

    
4926
    abort_result = self.rpc.call_finalize_migration(target_node,
4927
                                                    instance,
4928
                                                    migration_info,
4929
                                                    False)
4930
    abort_msg = abort_result.fail_msg
4931
    if abort_msg:
4932
      logging.error("Aborting migration failed on target node %s: %s" %
4933
                    (target_node, abort_msg))
4934
      # Don't raise an exception here, as we stil have to try to revert the
4935
      # disk status, even if this step failed.
4936

    
4937
  def _ExecMigration(self):
4938
    """Migrate an instance.
4939

4940
    The migrate is done by:
4941
      - change the disks into dual-master mode
4942
      - wait until disks are fully synchronized again
4943
      - migrate the instance
4944
      - change disks on the new secondary node (the old primary) to secondary
4945
      - wait until disks are fully synchronized
4946
      - change disks into single-master mode
4947

4948
    """
4949
    instance = self.instance
4950
    target_node = self.target_node
4951
    source_node = self.source_node
4952

    
4953
    self.feedback_fn("* checking disk consistency between source and target")
4954
    for dev in instance.disks:
4955
      if not _CheckDiskConsistency(self, dev, target_node, False):
4956
        raise errors.OpExecError("Disk %s is degraded or not fully"
4957
                                 " synchronized on target node,"
4958
                                 " aborting migrate." % dev.iv_name)
4959

    
4960
    # First get the migration information from the remote node
4961
    result = self.rpc.call_migration_info(source_node, instance)
4962
    msg = result.fail_msg
4963
    if msg:
4964
      log_err = ("Failed fetching source migration information from %s: %s" %
4965
                 (source_node, msg))
4966
      logging.error(log_err)
4967
      raise errors.OpExecError(log_err)
4968

    
4969
    self.migration_info = migration_info = result.payload
4970

    
4971
    # Then switch the disks to master/master mode
4972
    self._EnsureSecondary(target_node)
4973
    self._GoStandalone()
4974
    self._GoReconnect(True)
4975
    self._WaitUntilSync()
4976

    
4977
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
4978
    result = self.rpc.call_accept_instance(target_node,
4979
                                           instance,
4980
                                           migration_info,
4981
                                           self.nodes_ip[target_node])
4982

    
4983
    msg = result.fail_msg
4984
    if msg:
4985
      logging.error("Instance pre-migration failed, trying to revert"
4986
                    " disk status: %s", msg)
4987
      self._AbortMigration()
4988
      self._RevertDiskStatus()
4989
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
4990
                               (instance.name, msg))
4991

    
4992
    self.feedback_fn("* migrating instance to %s" % target_node)
4993
    time.sleep(10)
4994
    result = self.rpc.call_instance_migrate(source_node, instance,
4995
                                            self.nodes_ip[target_node],
4996
                                            self.live)
4997
    msg = result.fail_msg
4998
    if msg:
4999
      logging.error("Instance migration failed, trying to revert"
5000
                    " disk status: %s", msg)
5001
      self._AbortMigration()
5002
      self._RevertDiskStatus()
5003
      raise errors.OpExecError("Could not migrate instance %s: %s" %
5004
                               (instance.name, msg))
5005
    time.sleep(10)
5006

    
5007
    instance.primary_node = target_node
5008
    # distribute new instance config to the other nodes
5009
    self.cfg.Update(instance)
5010

    
5011
    result = self.rpc.call_finalize_migration(target_node,
5012
                                              instance,
5013
                                              migration_info,
5014
                                              True)
5015
    msg = result.fail_msg
5016
    if msg:
5017
      logging.error("Instance migration succeeded, but finalization failed:"
5018
                    " %s" % msg)
5019
      raise errors.OpExecError("Could not finalize instance migration: %s" %
5020
                               msg)
5021

    
5022
    self._EnsureSecondary(source_node)
5023
    self._WaitUntilSync()
5024
    self._GoStandalone()
5025
    self._GoReconnect(False)
5026
    self._WaitUntilSync()
5027

    
5028
    self.feedback_fn("* done")
5029

    
5030
  def Exec(self, feedback_fn):
5031
    """Perform the migration.
5032

5033
    """
5034
    feedback_fn("Migrating instance %s" % self.instance.name)
5035

    
5036
    self.feedback_fn = feedback_fn
5037

    
5038
    self.source_node = self.instance.primary_node
5039
    self.target_node = self.instance.secondary_nodes[0]
5040
    self.all_nodes = [self.source_node, self.target_node]
5041
    self.nodes_ip = {
5042
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
5043
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
5044
      }
5045

    
5046
    if self.cleanup:
5047
      return self._ExecCleanup()
5048
    else:
5049
      return self._ExecMigration()
5050

    
5051

    
5052
def _CreateBlockDev(lu, node, instance, device, force_create,
5053
                    info, force_open):
5054
  """Create a tree of block devices on a given node.
5055

5056
  If this device type has to be created on secondaries, create it and
5057
  all its children.
5058

5059
  If not, just recurse to children keeping the same 'force' value.
5060

5061
  @param lu: the lu on whose behalf we execute
5062
  @param node: the node on which to create the device
5063
  @type instance: L{objects.Instance}
5064
  @param instance: the instance which owns the device
5065
  @type device: L{objects.Disk}
5066
  @param device: the device to create
5067
  @type force_create: boolean
5068
  @param force_create: whether to force creation of this device; this
5069
      will be change to True whenever we find a device which has
5070
      CreateOnSecondary() attribute
5071
  @param info: the extra 'metadata' we should attach to the device
5072
      (this will be represented as a LVM tag)
5073
  @type force_open: boolean
5074
  @param force_open: this parameter will be passes to the
5075
      L{backend.BlockdevCreate} function where it specifies
5076
      whether we run on primary or not, and it affects both
5077
      the child assembly and the device own Open() execution
5078

5079
  """
5080
  if device.CreateOnSecondary():
5081
    force_create = True
5082

    
5083
  if device.children:
5084
    for child in device.children:
5085
      _CreateBlockDev(lu, node, instance, child, force_create,
5086
                      info, force_open)
5087

    
5088
  if not force_create:
5089
    return
5090

    
5091
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
5092

    
5093

    
5094
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
5095
  """Create a single block device on a given node.
5096

5097
  This will not recurse over children of the device, so they must be
5098
  created in advance.
5099

5100
  @param lu: the lu on whose behalf we execute
5101
  @param node: the node on which to create the device
5102
  @type instance: L{objects.Instance}
5103
  @param instance: the instance which owns the device
5104
  @type device: L{objects.Disk}
5105
  @param device: the device to create
5106
  @param info: the extra 'metadata' we should attach to the device
5107
      (this will be represented as a LVM tag)
5108
  @type force_open: boolean
5109
  @param force_open: this parameter will be passes to the
5110
      L{backend.BlockdevCreate} function where it specifies
5111
      whether we run on primary or not, and it affects both
5112
      the child assembly and the device own Open() execution
5113

5114
  """
5115
  lu.cfg.SetDiskID(device, node)
5116
  result = lu.rpc.call_blockdev_create(node, device, device.size,
5117
                                       instance.name, force_open, info)
5118
  result.Raise("Can't create block device %s on"
5119
               " node %s for instance %s" % (device, node, instance.name))
5120
  if device.physical_id is None:
5121
    device.physical_id = result.payload
5122

    
5123

    
5124
def _GenerateUniqueNames(lu, exts):
5125
  """Generate a suitable LV name.
5126

5127
  This will generate a logical volume name for the given instance.
5128

5129
  """
5130
  results = []
5131
  for val in exts:
5132
    new_id = lu.cfg.GenerateUniqueID()
5133
    results.append("%s%s" % (new_id, val))
5134
  return results
5135

    
5136

    
5137
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
5138
                         p_minor, s_minor):
5139
  """Generate a drbd8 device complete with its children.
5140

5141
  """
5142
  port = lu.cfg.AllocatePort()
5143
  vgname = lu.cfg.GetVGName()
5144
  shared_secret = lu.cfg.GenerateDRBDSecret()
5145
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
5146
                          logical_id=(vgname, names[0]))
5147
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
5148
                          logical_id=(vgname, names[1]))
5149
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
5150
                          logical_id=(primary, secondary, port,
5151
                                      p_minor, s_minor,
5152
                                      shared_secret),
5153
                          children=[dev_data, dev_meta],
5154
                          iv_name=iv_name)
5155
  return drbd_dev
5156

    
5157

    
5158
def _GenerateDiskTemplate(lu, template_name,
5159
                          instance_name, primary_node,
5160
                          secondary_nodes, disk_info,
5161
                          file_storage_dir, file_driver,
5162
                          base_index):
5163
  """Generate the entire disk layout for a given template type.
5164

5165
  """
5166
  #TODO: compute space requirements
5167

    
5168
  vgname = lu.cfg.GetVGName()
5169
  disk_count = len(disk_info)
5170
  disks = []
5171
  if template_name == constants.DT_DISKLESS:
5172
    pass
5173
  elif template_name == constants.DT_PLAIN:
5174
    if len(secondary_nodes) != 0:
5175
      raise errors.ProgrammerError("Wrong template configuration")
5176

    
5177
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5178
                                      for i in range(disk_count)])
5179
    for idx, disk in enumerate(disk_info):
5180
      disk_index = idx + base_index
5181
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
5182
                              logical_id=(vgname, names[idx]),
5183
                              iv_name="disk/%d" % disk_index,
5184
                              mode=disk["mode"])
5185
      disks.append(disk_dev)
5186
  elif template_name == constants.DT_DRBD8:
5187
    if len(secondary_nodes) != 1:
5188
      raise errors.ProgrammerError("Wrong template configuration")
5189
    remote_node = secondary_nodes[0]
5190
    minors = lu.cfg.AllocateDRBDMinor(
5191
      [primary_node, remote_node] * len(disk_info), instance_name)
5192

    
5193
    names = []
5194
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5195
                                               for i in range(disk_count)]):
5196
      names.append(lv_prefix + "_data")
5197
      names.append(lv_prefix + "_meta")
5198
    for idx, disk in enumerate(disk_info):
5199
      disk_index = idx + base_index
5200
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
5201
                                      disk["size"], names[idx*2:idx*2+2],
5202
                                      "disk/%d" % disk_index,
5203
                                      minors[idx*2], minors[idx*2+1])
5204
      disk_dev.mode = disk["mode"]
5205
      disks.append(disk_dev)
5206
  elif template_name == constants.DT_FILE:
5207
    if len(secondary_nodes) != 0:
5208
      raise errors.ProgrammerError("Wrong template configuration")
5209

    
5210
    for idx, disk in enumerate(disk_info):
5211
      disk_index = idx + base_index
5212
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
5213
                              iv_name="disk/%d" % disk_index,
5214
                              logical_id=(file_driver,
5215
                                          "%s/disk%d" % (file_storage_dir,
5216
                                                         disk_index)),
5217
                              mode=disk["mode"])
5218
      disks.append(disk_dev)
5219
  else:
5220
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
5221
  return disks
5222

    
5223

    
5224
def _GetInstanceInfoText(instance):
5225
  """Compute that text that should be added to the disk's metadata.
5226

5227
  """
5228
  return "originstname+%s" % instance.name
5229

    
5230

    
5231
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
5232
  """Create all disks for an instance.
5233

5234
  This abstracts away some work from AddInstance.
5235

5236
  @type lu: L{LogicalUnit}
5237
  @param lu: the logical unit on whose behalf we execute
5238
  @type instance: L{objects.Instance}
5239
  @param instance: the instance whose disks we should create
5240
  @type to_skip: list
5241
  @param to_skip: list of indices to skip
5242
  @type target_node: string
5243
  @param target_node: if passed, overrides the target node for creation
5244
  @rtype: boolean
5245
  @return: the success of the creation
5246

5247
  """
5248
  info = _GetInstanceInfoText(instance)
5249
  if target_node is None:
5250
    pnode = instance.primary_node
5251
    all_nodes = instance.all_nodes
5252
  else:
5253
    pnode = target_node
5254
    all_nodes = [pnode]
5255

    
5256
  if instance.disk_template == constants.DT_FILE:
5257
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
5258
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
5259

    
5260
    result.Raise("Failed to create directory '%s' on"
5261
                 " node %s" % (file_storage_dir, pnode))
5262

    
5263
  # Note: this needs to be kept in sync with adding of disks in
5264
  # LUSetInstanceParams
5265
  for idx, device in enumerate(instance.disks):
5266
    if to_skip and idx in to_skip:
5267
      continue
5268
    logging.info("Creating volume %s for instance %s",
5269
                 device.iv_name, instance.name)
5270
    #HARDCODE
5271
    for node in all_nodes:
5272
      f_create = node == pnode
5273
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
5274

    
5275

    
5276
def _RemoveDisks(lu, instance, target_node=None):
5277
  """Remove all disks for an instance.
5278

5279
  This abstracts away some work from `AddInstance()` and
5280
  `RemoveInstance()`. Note that in case some of the devices couldn't
5281
  be removed, the removal will continue with the other ones (compare
5282
  with `_CreateDisks()`).
5283

5284
  @type lu: L{LogicalUnit}
5285
  @param lu: the logical unit on whose behalf we execute
5286
  @type instance: L{objects.Instance}
5287
  @param instance: the instance whose disks we should remove
5288
  @type target_node: string
5289
  @param target_node: used to override the node on which to remove the disks
5290
  @rtype: boolean
5291
  @return: the success of the removal
5292

5293
  """
5294
  logging.info("Removing block devices for instance %s", instance.name)
5295

    
5296
  all_result = True
5297
  for device in instance.disks:
5298
    if target_node:
5299
      edata = [(target_node, device)]
5300
    else:
5301
      edata = device.ComputeNodeTree(instance.primary_node)
5302
    for node, disk in edata:
5303
      lu.cfg.SetDiskID(disk, node)
5304
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
5305
      if msg:
5306
        lu.LogWarning("Could not remove block device %s on node %s,"
5307
                      " continuing anyway: %s", device.iv_name, node, msg)
5308
        all_result = False
5309

    
5310
  if instance.disk_template == constants.DT_FILE:
5311
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
5312
    if target_node:
5313
      tgt = target_node
5314
    else:
5315
      tgt = instance.primary_node
5316
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
5317
    if result.fail_msg:
5318
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
5319
                    file_storage_dir, instance.primary_node, result.fail_msg)
5320
      all_result = False
5321

    
5322
  return all_result
5323

    
5324

    
5325
def _ComputeDiskSize(disk_template, disks):
5326
  """Compute disk size requirements in the volume group
5327

5328
  """
5329
  # Required free disk space as a function of disk and swap space
5330
  req_size_dict = {
5331
    constants.DT_DISKLESS: None,
5332
    constants.DT_PLAIN: sum(d["size"] for d in disks),
5333
    # 128 MB are added for drbd metadata for each disk
5334
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
5335
    constants.DT_FILE: None,
5336
  }
5337

    
5338
  if disk_template not in req_size_dict:
5339
    raise errors.ProgrammerError("Disk template '%s' size requirement"
5340
                                 " is unknown" %  disk_template)
5341

    
5342
  return req_size_dict[disk_template]
5343

    
5344

    
5345
def _CheckHVParams(lu, nodenames, hvname, hvparams):
5346
  """Hypervisor parameter validation.
5347

5348
  This function abstract the hypervisor parameter validation to be
5349
  used in both instance create and instance modify.
5350

5351
  @type lu: L{LogicalUnit}
5352
  @param lu: the logical unit for which we check
5353
  @type nodenames: list
5354
  @param nodenames: the list of nodes on which we should check
5355
  @type hvname: string
5356
  @param hvname: the name of the hypervisor we should use
5357
  @type hvparams: dict
5358
  @param hvparams: the parameters which we need to check
5359
  @raise errors.OpPrereqError: if the parameters are not valid
5360

5361
  """
5362
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
5363
                                                  hvname,
5364
                                                  hvparams)
5365
  for node in nodenames:
5366
    info = hvinfo[node]
5367
    if info.offline:
5368
      continue
5369
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
5370

    
5371

    
5372
class LUCreateInstance(LogicalUnit):
5373
  """Create an instance.
5374

5375
  """
5376
  HPATH = "instance-add"
5377
  HTYPE = constants.HTYPE_INSTANCE
5378
  _OP_REQP = ["instance_name", "disks", "disk_template",
5379
              "mode", "start",
5380
              "wait_for_sync", "ip_check", "nics",
5381
              "hvparams", "beparams"]
5382
  REQ_BGL = False
5383

    
5384
  def _ExpandNode(self, node):
5385
    """Expands and checks one node name.
5386

5387
    """
5388
    node_full = self.cfg.ExpandNodeName(node)
5389
    if node_full is None:
5390
      raise errors.OpPrereqError("Unknown node %s" % node)
5391
    return node_full
5392

    
5393
  def ExpandNames(self):
5394
    """ExpandNames for CreateInstance.
5395

5396
    Figure out the right locks for instance creation.
5397

5398
    """
5399
    self.needed_locks = {}
5400

    
5401
    # set optional parameters to none if they don't exist
5402
    for attr in ["pnode", "snode", "iallocator", "hypervisor"]:
5403
      if not hasattr(self.op, attr):
5404
        setattr(self.op, attr, None)
5405

    
5406
    # cheap checks, mostly valid constants given
5407

    
5408
    # verify creation mode
5409
    if self.op.mode not in (constants.INSTANCE_CREATE,
5410
                            constants.INSTANCE_IMPORT):
5411
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
5412
                                 self.op.mode)
5413

    
5414
    # disk template and mirror node verification
5415
    if self.op.disk_template not in constants.DISK_TEMPLATES:
5416
      raise errors.OpPrereqError("Invalid disk template name")
5417

    
5418
    if self.op.hypervisor is None:
5419
      self.op.hypervisor = self.cfg.GetHypervisorType()
5420

    
5421
    cluster = self.cfg.GetClusterInfo()
5422
    enabled_hvs = cluster.enabled_hypervisors
5423
    if self.op.hypervisor not in enabled_hvs:
5424
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
5425
                                 " cluster (%s)" % (self.op.hypervisor,
5426
                                  ",".join(enabled_hvs)))
5427

    
5428
    # check hypervisor parameter syntax (locally)
5429
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5430
    filled_hvp = objects.FillDict(cluster.hvparams[self.op.hypervisor],
5431
                                  self.op.hvparams)
5432
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
5433
    hv_type.CheckParameterSyntax(filled_hvp)
5434
    self.hv_full = filled_hvp
5435

    
5436
    # fill and remember the beparams dict
5437
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5438
    self.be_full = objects.FillDict(cluster.beparams[constants.PP_DEFAULT],
5439
                                    self.op.beparams)
5440

    
5441
    #### instance parameters check
5442

    
5443
    # instance name verification
5444
    hostname1 = utils.HostInfo(self.op.instance_name)
5445
    self.op.instance_name = instance_name = hostname1.name
5446

    
5447
    # this is just a preventive check, but someone might still add this
5448
    # instance in the meantime, and creation will fail at lock-add time
5449
    if instance_name in self.cfg.GetInstanceList():
5450
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5451
                                 instance_name)
5452

    
5453
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
5454

    
5455
    # NIC buildup
5456
    self.nics = []
5457
    for idx, nic in enumerate(self.op.nics):
5458
      nic_mode_req = nic.get("mode", None)
5459
      nic_mode = nic_mode_req
5460
      if nic_mode is None:
5461
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
5462

    
5463
      # in routed mode, for the first nic, the default ip is 'auto'
5464
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
5465
        default_ip_mode = constants.VALUE_AUTO
5466
      else:
5467
        default_ip_mode = constants.VALUE_NONE
5468

    
5469
      # ip validity checks
5470
      ip = nic.get("ip", default_ip_mode)
5471
      if ip is None or ip.lower() == constants.VALUE_NONE:
5472
        nic_ip = None
5473
      elif ip.lower() == constants.VALUE_AUTO:
5474
        nic_ip = hostname1.ip
5475
      else:
5476
        if not utils.IsValidIP(ip):
5477
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
5478
                                     " like a valid IP" % ip)
5479
        nic_ip = ip
5480

    
5481
      # TODO: check the ip for uniqueness !!
5482
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
5483
        raise errors.OpPrereqError("Routed nic mode requires an ip address")
5484

    
5485
      # MAC address verification
5486
      mac = nic.get("mac", constants.VALUE_AUTO)
5487
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5488
        if not utils.IsValidMac(mac.lower()):
5489
          raise errors.OpPrereqError("Invalid MAC address specified: %s" %
5490
                                     mac)
5491
        else:
5492
          # or validate/reserve the current one
5493
          if self.cfg.IsMacInUse(mac):
5494
            raise errors.OpPrereqError("MAC address %s already in use"
5495
                                       " in cluster" % mac)
5496

    
5497
      # bridge verification
5498
      bridge = nic.get("bridge", None)
5499
      link = nic.get("link", None)
5500
      if bridge and link:
5501
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
5502
                                   " at the same time")
5503
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
5504
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic")
5505
      elif bridge:
5506
        link = bridge
5507

    
5508
      nicparams = {}
5509
      if nic_mode_req:
5510
        nicparams[constants.NIC_MODE] = nic_mode_req
5511
      if link:
5512
        nicparams[constants.NIC_LINK] = link
5513

    
5514
      check_params = objects.FillDict(cluster.nicparams[constants.PP_DEFAULT],
5515
                                      nicparams)
5516
      objects.NIC.CheckParameterSyntax(check_params)
5517
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
5518

    
5519
    # disk checks/pre-build
5520
    self.disks = []
5521
    for disk in self.op.disks:
5522
      mode = disk.get("mode", constants.DISK_RDWR)
5523
      if mode not in constants.DISK_ACCESS_SET:
5524
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
5525
                                   mode)
5526
      size = disk.get("size", None)
5527
      if size is None:
5528
        raise errors.OpPrereqError("Missing disk size")
5529
      try:
5530
        size = int(size)
5531
      except ValueError:
5532
        raise errors.OpPrereqError("Invalid disk size '%s'" % size)
5533
      self.disks.append({"size": size, "mode": mode})
5534

    
5535
    # used in CheckPrereq for ip ping check
5536
    self.check_ip = hostname1.ip
5537

    
5538
    # file storage checks
5539
    if (self.op.file_driver and
5540
        not self.op.file_driver in constants.FILE_DRIVER):
5541
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
5542
                                 self.op.file_driver)
5543

    
5544
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
5545
      raise errors.OpPrereqError("File storage directory path not absolute")
5546

    
5547
    ### Node/iallocator related checks
5548
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
5549
      raise errors.OpPrereqError("One and only one of iallocator and primary"
5550
                                 " node must be given")
5551

    
5552
    if self.op.iallocator:
5553
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5554
    else:
5555
      self.op.pnode = self._ExpandNode(self.op.pnode)
5556
      nodelist = [self.op.pnode]
5557
      if self.op.snode is not None:
5558
        self.op.snode = self._ExpandNode(self.op.snode)
5559
        nodelist.append(self.op.snode)
5560
      self.needed_locks[locking.LEVEL_NODE] = nodelist
5561

    
5562
    # in case of import lock the source node too
5563
    if self.op.mode == constants.INSTANCE_IMPORT:
5564
      src_node = getattr(self.op, "src_node", None)
5565
      src_path = getattr(self.op, "src_path", None)
5566

    
5567
      if src_path is None:
5568
        self.op.src_path = src_path = self.op.instance_name
5569

    
5570
      if src_node is None:
5571
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5572
        self.op.src_node = None
5573
        if os.path.isabs(src_path):
5574
          raise errors.OpPrereqError("Importing an instance from an absolute"
5575
                                     " path requires a source node option.")
5576
      else:
5577
        self.op.src_node = src_node = self._ExpandNode(src_node)
5578
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
5579
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
5580
        if not os.path.isabs(src_path):
5581
          self.op.src_path = src_path = \
5582
            os.path.join(constants.EXPORT_DIR, src_path)
5583

    
5584
    else: # INSTANCE_CREATE
5585
      if getattr(self.op, "os_type", None) is None:
5586
        raise errors.OpPrereqError("No guest OS specified")
5587

    
5588
  def _RunAllocator(self):
5589
    """Run the allocator based on input opcode.
5590

5591
    """
5592
    nics = [n.ToDict() for n in self.nics]
5593
    ial = IAllocator(self.cfg, self.rpc,
5594
                     mode=constants.IALLOCATOR_MODE_ALLOC,
5595
                     name=self.op.instance_name,
5596
                     disk_template=self.op.disk_template,
5597
                     tags=[],
5598
                     os=self.op.os_type,
5599
                     vcpus=self.be_full[constants.BE_VCPUS],
5600
                     mem_size=self.be_full[constants.BE_MEMORY],
5601
                     disks=self.disks,
5602
                     nics=nics,
5603
                     hypervisor=self.op.hypervisor,
5604
                     )
5605

    
5606
    ial.Run(self.op.iallocator)
5607

    
5608
    if not ial.success:
5609
      raise errors.OpPrereqError("Can't compute nodes using"
5610
                                 " iallocator '%s': %s" % (self.op.iallocator,
5611
                                                           ial.info))
5612
    if len(ial.nodes) != ial.required_nodes:
5613
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
5614
                                 " of nodes (%s), required %s" %
5615
                                 (self.op.iallocator, len(ial.nodes),
5616
                                  ial.required_nodes))
5617
    self.op.pnode = ial.nodes[0]
5618
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
5619
                 self.op.instance_name, self.op.iallocator,
5620
                 ", ".join(ial.nodes))
5621
    if ial.required_nodes == 2:
5622
      self.op.snode = ial.nodes[1]
5623

    
5624
  def BuildHooksEnv(self):
5625
    """Build hooks env.
5626

5627
    This runs on master, primary and secondary nodes of the instance.
5628

5629
    """
5630
    env = {
5631
      "ADD_MODE": self.op.mode,
5632
      }
5633
    if self.op.mode == constants.INSTANCE_IMPORT:
5634
      env["SRC_NODE"] = self.op.src_node
5635
      env["SRC_PATH"] = self.op.src_path
5636
      env["SRC_IMAGES"] = self.src_images
5637

    
5638
    env.update(_BuildInstanceHookEnv(
5639
      name=self.op.instance_name,
5640
      primary_node=self.op.pnode,
5641
      secondary_nodes=self.secondaries,
5642
      status=self.op.start,
5643
      os_type=self.op.os_type,
5644
      memory=self.be_full[constants.BE_MEMORY],
5645
      vcpus=self.be_full[constants.BE_VCPUS],
5646
      nics=_NICListToTuple(self, self.nics),
5647
      disk_template=self.op.disk_template,
5648
      disks=[(d["size"], d["mode"]) for d in self.disks],
5649
      bep=self.be_full,
5650
      hvp=self.hv_full,
5651
      hypervisor_name=self.op.hypervisor,
5652
    ))
5653

    
5654
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
5655
          self.secondaries)
5656
    return env, nl, nl
5657

    
5658

    
5659
  def CheckPrereq(self):
5660
    """Check prerequisites.
5661

5662
    """
5663
    if (not self.cfg.GetVGName() and
5664
        self.op.disk_template not in constants.DTS_NOT_LVM):
5665
      raise errors.OpPrereqError("Cluster does not support lvm-based"
5666
                                 " instances")
5667

    
5668
    if self.op.mode == constants.INSTANCE_IMPORT:
5669
      src_node = self.op.src_node
5670
      src_path = self.op.src_path
5671

    
5672
      if src_node is None:
5673
        locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
5674
        exp_list = self.rpc.call_export_list(locked_nodes)
5675
        found = False
5676
        for node in exp_list:
5677
          if exp_list[node].fail_msg:
5678
            continue
5679
          if src_path in exp_list[node].payload:
5680
            found = True
5681
            self.op.src_node = src_node = node
5682
            self.op.src_path = src_path = os.path.join(constants.EXPORT_DIR,
5683
                                                       src_path)
5684
            break
5685
        if not found:
5686
          raise errors.OpPrereqError("No export found for relative path %s" %
5687
                                      src_path)
5688

    
5689
      _CheckNodeOnline(self, src_node)
5690
      result = self.rpc.call_export_info(src_node, src_path)
5691
      result.Raise("No export or invalid export found in dir %s" % src_path)
5692

    
5693
      export_info = objects.SerializableConfigParser.Loads(str(result.payload))
5694
      if not export_info.has_section(constants.INISECT_EXP):
5695
        raise errors.ProgrammerError("Corrupted export config")
5696

    
5697
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
5698
      if (int(ei_version) != constants.EXPORT_VERSION):
5699
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
5700
                                   (ei_version, constants.EXPORT_VERSION))
5701

    
5702
      # Check that the new instance doesn't have less disks than the export
5703
      instance_disks = len(self.disks)
5704
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
5705
      if instance_disks < export_disks:
5706
        raise errors.OpPrereqError("Not enough disks to import."
5707
                                   " (instance: %d, export: %d)" %
5708
                                   (instance_disks, export_disks))
5709

    
5710
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
5711
      disk_images = []
5712
      for idx in range(export_disks):
5713
        option = 'disk%d_dump' % idx
5714
        if export_info.has_option(constants.INISECT_INS, option):
5715
          # FIXME: are the old os-es, disk sizes, etc. useful?
5716
          export_name = export_info.get(constants.INISECT_INS, option)
5717
          image = os.path.join(src_path, export_name)
5718
          disk_images.append(image)
5719
        else:
5720
          disk_images.append(False)
5721

    
5722
      self.src_images = disk_images
5723

    
5724
      old_name = export_info.get(constants.INISECT_INS, 'name')
5725
      # FIXME: int() here could throw a ValueError on broken exports
5726
      exp_nic_count = int(export_info.get(constants.INISECT_INS, 'nic_count'))
5727
      if self.op.instance_name == old_name:
5728
        for idx, nic in enumerate(self.nics):
5729
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
5730
            nic_mac_ini = 'nic%d_mac' % idx
5731
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
5732

    
5733
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
5734
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
5735
    if self.op.start and not self.op.ip_check:
5736
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
5737
                                 " adding an instance in start mode")
5738

    
5739
    if self.op.ip_check:
5740
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
5741
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
5742
                                   (self.check_ip, self.op.instance_name))
5743

    
5744
    #### mac address generation
5745
    # By generating here the mac address both the allocator and the hooks get
5746
    # the real final mac address rather than the 'auto' or 'generate' value.
5747
    # There is a race condition between the generation and the instance object
5748
    # creation, which means that we know the mac is valid now, but we're not
5749
    # sure it will be when we actually add the instance. If things go bad
5750
    # adding the instance will abort because of a duplicate mac, and the
5751
    # creation job will fail.
5752
    for nic in self.nics:
5753
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5754
        nic.mac = self.cfg.GenerateMAC()
5755

    
5756
    #### allocator run
5757

    
5758
    if self.op.iallocator is not None:
5759
      self._RunAllocator()
5760

    
5761
    #### node related checks
5762

    
5763
    # check primary node
5764
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
5765
    assert self.pnode is not None, \
5766
      "Cannot retrieve locked node %s" % self.op.pnode
5767
    if pnode.offline:
5768
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
5769
                                 pnode.name)
5770
    if pnode.drained:
5771
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
5772
                                 pnode.name)
5773

    
5774
    self.secondaries = []
5775

    
5776
    # mirror node verification
5777
    if self.op.disk_template in constants.DTS_NET_MIRROR:
5778
      if self.op.snode is None:
5779
        raise errors.OpPrereqError("The networked disk templates need"
5780
                                   " a mirror node")
5781
      if self.op.snode == pnode.name:
5782
        raise errors.OpPrereqError("The secondary node cannot be"
5783
                                   " the primary node.")
5784
      _CheckNodeOnline(self, self.op.snode)
5785
      _CheckNodeNotDrained(self, self.op.snode)
5786
      self.secondaries.append(self.op.snode)
5787

    
5788
    nodenames = [pnode.name] + self.secondaries
5789

    
5790
    req_size = _ComputeDiskSize(self.op.disk_template,
5791
                                self.disks)
5792

    
5793
    # Check lv size requirements
5794
    if req_size is not None:
5795
      nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
5796
                                         self.op.hypervisor)
5797
      for node in nodenames:
5798
        info = nodeinfo[node]
5799
        info.Raise("Cannot get current information from node %s" % node)
5800
        info = info.payload
5801
        vg_free = info.get('vg_free', None)
5802
        if not isinstance(vg_free, int):
5803
          raise errors.OpPrereqError("Can't compute free disk space on"
5804
                                     " node %s" % node)
5805
        if req_size > vg_free:
5806
          raise errors.OpPrereqError("Not enough disk space on target node %s."
5807
                                     " %d MB available, %d MB required" %
5808
                                     (node, vg_free, req_size))
5809

    
5810
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
5811

    
5812
    # os verification
5813
    result = self.rpc.call_os_get(pnode.name, self.op.os_type)
5814
    result.Raise("OS '%s' not in supported os list for primary node %s" %
5815
                 (self.op.os_type, pnode.name), prereq=True)
5816

    
5817
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
5818

    
5819
    # memory check on primary node
5820
    if self.op.start:
5821
      _CheckNodeFreeMemory(self, self.pnode.name,
5822
                           "creating instance %s" % self.op.instance_name,
5823
                           self.be_full[constants.BE_MEMORY],
5824
                           self.op.hypervisor)
5825

    
5826
    self.dry_run_result = list(nodenames)
5827

    
5828
  def Exec(self, feedback_fn):
5829
    """Create and add the instance to the cluster.
5830

5831
    """
5832
    instance = self.op.instance_name
5833
    pnode_name = self.pnode.name
5834

    
5835
    ht_kind = self.op.hypervisor
5836
    if ht_kind in constants.HTS_REQ_PORT:
5837
      network_port = self.cfg.AllocatePort()
5838
    else:
5839
      network_port = None
5840

    
5841
    ##if self.op.vnc_bind_address is None:
5842
    ##  self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
5843

    
5844
    # this is needed because os.path.join does not accept None arguments
5845
    if self.op.file_storage_dir is None:
5846
      string_file_storage_dir = ""
5847
    else:
5848
      string_file_storage_dir = self.op.file_storage_dir
5849

    
5850
    # build the full file storage dir path
5851
    file_storage_dir = os.path.normpath(os.path.join(
5852
                                        self.cfg.GetFileStorageDir(),
5853
                                        string_file_storage_dir, instance))
5854

    
5855

    
5856
    disks = _GenerateDiskTemplate(self,
5857
                                  self.op.disk_template,
5858
                                  instance, pnode_name,
5859
                                  self.secondaries,
5860
                                  self.disks,
5861
                                  file_storage_dir,
5862
                                  self.op.file_driver,
5863
                                  0)
5864

    
5865
    iobj = objects.Instance(name=instance, os=self.op.os_type,
5866
                            primary_node=pnode_name,
5867
                            nics=self.nics, disks=disks,
5868
                            disk_template=self.op.disk_template,
5869
                            admin_up=False,
5870
                            network_port=network_port,
5871
                            beparams=self.op.beparams,
5872
                            hvparams=self.op.hvparams,
5873
                            hypervisor=self.op.hypervisor,
5874
                            )
5875

    
5876
    feedback_fn("* creating instance disks...")
5877
    try:
5878
      _CreateDisks(self, iobj)
5879
    except errors.OpExecError:
5880
      self.LogWarning("Device creation failed, reverting...")
5881
      try:
5882
        _RemoveDisks(self, iobj)
5883
      finally:
5884
        self.cfg.ReleaseDRBDMinors(instance)
5885
        raise
5886

    
5887
    feedback_fn("adding instance %s to cluster config" % instance)
5888

    
5889
    self.cfg.AddInstance(iobj)
5890
    # Declare that we don't want to remove the instance lock anymore, as we've
5891
    # added the instance to the config
5892
    del self.remove_locks[locking.LEVEL_INSTANCE]
5893
    # Unlock all the nodes
5894
    if self.op.mode == constants.INSTANCE_IMPORT:
5895
      nodes_keep = [self.op.src_node]
5896
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
5897
                       if node != self.op.src_node]
5898
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
5899
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
5900
    else:
5901
      self.context.glm.release(locking.LEVEL_NODE)
5902
      del self.acquired_locks[locking.LEVEL_NODE]
5903

    
5904
    if self.op.wait_for_sync:
5905
      disk_abort = not _WaitForSync(self, iobj)
5906
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
5907
      # make sure the disks are not degraded (still sync-ing is ok)
5908
      time.sleep(15)
5909
      feedback_fn("* checking mirrors status")
5910
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
5911
    else:
5912
      disk_abort = False
5913

    
5914
    if disk_abort:
5915
      _RemoveDisks(self, iobj)
5916
      self.cfg.RemoveInstance(iobj.name)
5917
      # Make sure the instance lock gets removed
5918
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
5919
      raise errors.OpExecError("There are some degraded disks for"
5920
                               " this instance")
5921

    
5922
    feedback_fn("creating os for instance %s on node %s" %
5923
                (instance, pnode_name))
5924

    
5925
    if iobj.disk_template != constants.DT_DISKLESS:
5926
      if self.op.mode == constants.INSTANCE_CREATE:
5927
        feedback_fn("* running the instance OS create scripts...")
5928
        result = self.rpc.call_instance_os_add(pnode_name, iobj, False)
5929
        result.Raise("Could not add os for instance %s"
5930
                     " on node %s" % (instance, pnode_name))
5931

    
5932
      elif self.op.mode == constants.INSTANCE_IMPORT:
5933
        feedback_fn("* running the instance OS import scripts...")
5934
        src_node = self.op.src_node
5935
        src_images = self.src_images
5936
        cluster_name = self.cfg.GetClusterName()
5937
        import_result = self.rpc.call_instance_os_import(pnode_name, iobj,
5938
                                                         src_node, src_images,
5939
                                                         cluster_name)
5940
        msg = import_result.fail_msg
5941
        if msg:
5942
          self.LogWarning("Error while importing the disk images for instance"
5943
                          " %s on node %s: %s" % (instance, pnode_name, msg))
5944
      else:
5945
        # also checked in the prereq part
5946
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
5947
                                     % self.op.mode)
5948

    
5949
    if self.op.start:
5950
      iobj.admin_up = True
5951
      self.cfg.Update(iobj)
5952
      logging.info("Starting instance %s on node %s", instance, pnode_name)
5953
      feedback_fn("* starting instance...")
5954
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
5955
      result.Raise("Could not start instance")
5956

    
5957
    return list(iobj.all_nodes)
5958

    
5959

    
5960
class LUConnectConsole(NoHooksLU):
5961
  """Connect to an instance's console.
5962

5963
  This is somewhat special in that it returns the command line that
5964
  you need to run on the master node in order to connect to the
5965
  console.
5966

5967
  """
5968
  _OP_REQP = ["instance_name"]
5969
  REQ_BGL = False
5970

    
5971
  def ExpandNames(self):
5972
    self._ExpandAndLockInstance()
5973

    
5974
  def CheckPrereq(self):
5975
    """Check prerequisites.
5976

5977
    This checks that the instance is in the cluster.
5978

5979
    """
5980
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5981
    assert self.instance is not None, \
5982
      "Cannot retrieve locked instance %s" % self.op.instance_name
5983
    _CheckNodeOnline(self, self.instance.primary_node)
5984

    
5985
  def Exec(self, feedback_fn):
5986
    """Connect to the console of an instance
5987

5988
    """
5989
    instance = self.instance
5990
    node = instance.primary_node
5991

    
5992
    node_insts = self.rpc.call_instance_list([node],
5993
                                             [instance.hypervisor])[node]
5994
    node_insts.Raise("Can't get node information from %s" % node)
5995

    
5996
    if instance.name not in node_insts.payload:
5997
      raise errors.OpExecError("Instance %s is not running." % instance.name)
5998

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

    
6001
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
6002
    cluster = self.cfg.GetClusterInfo()
6003
    # beparams and hvparams are passed separately, to avoid editing the
6004
    # instance and then saving the defaults in the instance itself.
6005
    hvparams = cluster.FillHV(instance)
6006
    beparams = cluster.FillBE(instance)
6007
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
6008

    
6009
    # build ssh cmdline
6010
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
6011

    
6012

    
6013
class LUReplaceDisks(LogicalUnit):
6014
  """Replace the disks of an instance.
6015

6016
  """
6017
  HPATH = "mirrors-replace"
6018
  HTYPE = constants.HTYPE_INSTANCE
6019
  _OP_REQP = ["instance_name", "mode", "disks"]
6020
  REQ_BGL = False
6021

    
6022
  def CheckArguments(self):
6023
    if not hasattr(self.op, "remote_node"):
6024
      self.op.remote_node = None
6025
    if not hasattr(self.op, "iallocator"):
6026
      self.op.iallocator = None
6027

    
6028
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
6029
                                  self.op.iallocator)
6030

    
6031
  def ExpandNames(self):
6032
    self._ExpandAndLockInstance()
6033

    
6034
    if self.op.iallocator is not None:
6035
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6036

    
6037
    elif self.op.remote_node is not None:
6038
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
6039
      if remote_node is None:
6040
        raise errors.OpPrereqError("Node '%s' not known" %
6041
                                   self.op.remote_node)
6042

    
6043
      self.op.remote_node = remote_node
6044

    
6045
      # Warning: do not remove the locking of the new secondary here
6046
      # unless DRBD8.AddChildren is changed to work in parallel;
6047
      # currently it doesn't since parallel invocations of
6048
      # FindUnusedMinor will conflict
6049
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
6050
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6051

    
6052
    else:
6053
      self.needed_locks[locking.LEVEL_NODE] = []
6054
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6055

    
6056
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
6057
                                   self.op.iallocator, self.op.remote_node,
6058
                                   self.op.disks)
6059

    
6060
    self.tasklets = [self.replacer]
6061

    
6062
  def DeclareLocks(self, level):
6063
    # If we're not already locking all nodes in the set we have to declare the
6064
    # instance's primary/secondary nodes.
6065
    if (level == locking.LEVEL_NODE and
6066
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
6067
      self._LockInstancesNodes()
6068

    
6069
  def BuildHooksEnv(self):
6070
    """Build hooks env.
6071

6072
    This runs on the master, the primary and all the secondaries.
6073

6074
    """
6075
    instance = self.replacer.instance
6076
    env = {
6077
      "MODE": self.op.mode,
6078
      "NEW_SECONDARY": self.op.remote_node,
6079
      "OLD_SECONDARY": instance.secondary_nodes[0],
6080
      }
6081
    env.update(_BuildInstanceHookEnvByObject(self, instance))
6082
    nl = [
6083
      self.cfg.GetMasterNode(),
6084
      instance.primary_node,
6085
      ]
6086
    if self.op.remote_node is not None:
6087
      nl.append(self.op.remote_node)
6088
    return env, nl, nl
6089

    
6090

    
6091
class LUEvacuateNode(LogicalUnit):
6092
  """Relocate the secondary instances from a node.
6093

6094
  """
6095
  HPATH = "node-evacuate"
6096
  HTYPE = constants.HTYPE_NODE
6097
  _OP_REQP = ["node_name"]
6098
  REQ_BGL = False
6099

    
6100
  def CheckArguments(self):
6101
    if not hasattr(self.op, "remote_node"):
6102
      self.op.remote_node = None
6103
    if not hasattr(self.op, "iallocator"):
6104
      self.op.iallocator = None
6105

    
6106
    TLReplaceDisks.CheckArguments(constants.REPLACE_DISK_CHG,
6107
                                  self.op.remote_node,
6108
                                  self.op.iallocator)
6109

    
6110
  def ExpandNames(self):
6111
    self.op.node_name = self.cfg.ExpandNodeName(self.op.node_name)
6112
    if self.op.node_name is None:
6113
      raise errors.OpPrereqError("Node '%s' not known" % self.op.node_name)
6114

    
6115
    self.needed_locks = {}
6116

    
6117
    # Declare node locks
6118
    if self.op.iallocator is not None:
6119
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6120

    
6121
    elif self.op.remote_node is not None:
6122
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
6123
      if remote_node is None:
6124
        raise errors.OpPrereqError("Node '%s' not known" %
6125
                                   self.op.remote_node)
6126

    
6127
      self.op.remote_node = remote_node
6128

    
6129
      # Warning: do not remove the locking of the new secondary here
6130
      # unless DRBD8.AddChildren is changed to work in parallel;
6131
      # currently it doesn't since parallel invocations of
6132
      # FindUnusedMinor will conflict
6133
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
6134
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6135

    
6136
    else:
6137
      raise errors.OpPrereqError("Invalid parameters")
6138

    
6139
    # Create tasklets for replacing disks for all secondary instances on this
6140
    # node
6141
    names = []
6142
    tasklets = []
6143

    
6144
    for inst in _GetNodeSecondaryInstances(self.cfg, self.op.node_name):
6145
      logging.debug("Replacing disks for instance %s", inst.name)
6146
      names.append(inst.name)
6147

    
6148
      replacer = TLReplaceDisks(self, inst.name, constants.REPLACE_DISK_CHG,
6149
                                self.op.iallocator, self.op.remote_node, [])
6150
      tasklets.append(replacer)
6151

    
6152
    self.tasklets = tasklets
6153
    self.instance_names = names
6154

    
6155
    # Declare instance locks
6156
    self.needed_locks[locking.LEVEL_INSTANCE] = self.instance_names
6157

    
6158
  def DeclareLocks(self, level):
6159
    # If we're not already locking all nodes in the set we have to declare the
6160
    # instance's primary/secondary nodes.
6161
    if (level == locking.LEVEL_NODE and
6162
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
6163
      self._LockInstancesNodes()
6164

    
6165
  def BuildHooksEnv(self):
6166
    """Build hooks env.
6167

6168
    This runs on the master, the primary and all the secondaries.
6169

6170
    """
6171
    env = {
6172
      "NODE_NAME": self.op.node_name,
6173
      }
6174

    
6175
    nl = [self.cfg.GetMasterNode()]
6176

    
6177
    if self.op.remote_node is not None:
6178
      env["NEW_SECONDARY"] = self.op.remote_node
6179
      nl.append(self.op.remote_node)
6180

    
6181
    return (env, nl, nl)
6182

    
6183

    
6184
class TLReplaceDisks(Tasklet):
6185
  """Replaces disks for an instance.
6186

6187
  Note: Locking is not within the scope of this class.
6188

6189
  """
6190
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
6191
               disks):
6192
    """Initializes this class.
6193

6194
    """
6195
    Tasklet.__init__(self, lu)
6196

    
6197
    # Parameters
6198
    self.instance_name = instance_name
6199
    self.mode = mode
6200
    self.iallocator_name = iallocator_name
6201
    self.remote_node = remote_node
6202
    self.disks = disks
6203

    
6204
    # Runtime data
6205
    self.instance = None
6206
    self.new_node = None
6207
    self.target_node = None
6208
    self.other_node = None
6209
    self.remote_node_info = None
6210
    self.node_secondary_ip = None
6211

    
6212
  @staticmethod
6213
  def CheckArguments(mode, remote_node, iallocator):
6214
    """Helper function for users of this class.
6215

6216
    """
6217
    # check for valid parameter combination
6218
    if mode == constants.REPLACE_DISK_CHG:
6219
      if remote_node is None and iallocator is None:
6220
        raise errors.OpPrereqError("When changing the secondary either an"
6221
                                   " iallocator script must be used or the"
6222
                                   " new node given")
6223

    
6224
      if remote_node is not None and iallocator is not None:
6225
        raise errors.OpPrereqError("Give either the iallocator or the new"
6226
                                   " secondary, not both")
6227

    
6228
    elif remote_node is not None or iallocator is not None:
6229
      # Not replacing the secondary
6230
      raise errors.OpPrereqError("The iallocator and new node options can"
6231
                                 " only be used when changing the"
6232
                                 " secondary node")
6233

    
6234
  @staticmethod
6235
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
6236
    """Compute a new secondary node using an IAllocator.
6237

6238
    """
6239
    ial = IAllocator(lu.cfg, lu.rpc,
6240
                     mode=constants.IALLOCATOR_MODE_RELOC,
6241
                     name=instance_name,
6242
                     relocate_from=relocate_from)
6243

    
6244
    ial.Run(iallocator_name)
6245

    
6246
    if not ial.success:
6247
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
6248
                                 " %s" % (iallocator_name, ial.info))
6249

    
6250
    if len(ial.nodes) != ial.required_nodes:
6251
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6252
                                 " of nodes (%s), required %s" %
6253
                                 (len(ial.nodes), ial.required_nodes))
6254

    
6255
    remote_node_name = ial.nodes[0]
6256

    
6257
    lu.LogInfo("Selected new secondary for instance '%s': %s",
6258
               instance_name, remote_node_name)
6259

    
6260
    return remote_node_name
6261

    
6262
  def _FindFaultyDisks(self, node_name):
6263
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
6264
                                    node_name, True)
6265

    
6266
  def CheckPrereq(self):
6267
    """Check prerequisites.
6268

6269
    This checks that the instance is in the cluster.
6270

6271
    """
6272
    self.instance = self.cfg.GetInstanceInfo(self.instance_name)
6273
    assert self.instance is not None, \
6274
      "Cannot retrieve locked instance %s" % self.instance_name
6275

    
6276
    if self.instance.disk_template != constants.DT_DRBD8:
6277
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
6278
                                 " instances")
6279

    
6280
    if len(self.instance.secondary_nodes) != 1:
6281
      raise errors.OpPrereqError("The instance has a strange layout,"
6282
                                 " expected one secondary but found %d" %
6283
                                 len(self.instance.secondary_nodes))
6284

    
6285
    secondary_node = self.instance.secondary_nodes[0]
6286

    
6287
    if self.iallocator_name is None:
6288
      remote_node = self.remote_node
6289
    else:
6290
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
6291
                                       self.instance.name, secondary_node)
6292

    
6293
    if remote_node is not None:
6294
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
6295
      assert self.remote_node_info is not None, \
6296
        "Cannot retrieve locked node %s" % remote_node
6297
    else:
6298
      self.remote_node_info = None
6299

    
6300
    if remote_node == self.instance.primary_node:
6301
      raise errors.OpPrereqError("The specified node is the primary node of"
6302
                                 " the instance.")
6303

    
6304
    if remote_node == secondary_node:
6305
      raise errors.OpPrereqError("The specified node is already the"
6306
                                 " secondary node of the instance.")
6307

    
6308
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
6309
                                    constants.REPLACE_DISK_CHG):
6310
      raise errors.OpPrereqError("Cannot specify disks to be replaced")
6311

    
6312
    if self.mode == constants.REPLACE_DISK_AUTO:
6313
      faulty_primary = self._FindFaultyDisks(self.instance.primary_node)
6314
      faulty_secondary = self._FindFaultyDisks(secondary_node)
6315

    
6316
      if faulty_primary and faulty_secondary:
6317
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
6318
                                   " one node and can not be repaired"
6319
                                   " automatically" % self.instance_name)
6320

    
6321
      if faulty_primary:
6322
        self.disks = faulty_primary
6323
        self.target_node = self.instance.primary_node
6324
        self.other_node = secondary_node
6325
        check_nodes = [self.target_node, self.other_node]
6326
      elif faulty_secondary:
6327
        self.disks = faulty_secondary
6328
        self.target_node = secondary_node
6329
        self.other_node = self.instance.primary_node
6330
        check_nodes = [self.target_node, self.other_node]
6331
      else:
6332
        self.disks = []
6333
        check_nodes = []
6334

    
6335
    else:
6336
      # Non-automatic modes
6337
      if self.mode == constants.REPLACE_DISK_PRI:
6338
        self.target_node = self.instance.primary_node
6339
        self.other_node = secondary_node
6340
        check_nodes = [self.target_node, self.other_node]
6341

    
6342
      elif self.mode == constants.REPLACE_DISK_SEC:
6343
        self.target_node = secondary_node
6344
        self.other_node = self.instance.primary_node
6345
        check_nodes = [self.target_node, self.other_node]
6346

    
6347
      elif self.mode == constants.REPLACE_DISK_CHG:
6348
        self.new_node = remote_node
6349
        self.other_node = self.instance.primary_node
6350
        self.target_node = secondary_node
6351
        check_nodes = [self.new_node, self.other_node]
6352

    
6353
        _CheckNodeNotDrained(self.lu, remote_node)
6354

    
6355
      else:
6356
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
6357
                                     self.mode)
6358

    
6359
      # If not specified all disks should be replaced
6360
      if not self.disks:
6361
        self.disks = range(len(self.instance.disks))
6362

    
6363
    for node in check_nodes:
6364
      _CheckNodeOnline(self.lu, node)
6365

    
6366
    # Check whether disks are valid
6367
    for disk_idx in self.disks:
6368
      self.instance.FindDisk(disk_idx)
6369

    
6370
    # Get secondary node IP addresses
6371
    node_2nd_ip = {}
6372

    
6373
    for node_name in [self.target_node, self.other_node, self.new_node]:
6374
      if node_name is not None:
6375
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
6376

    
6377
    self.node_secondary_ip = node_2nd_ip
6378

    
6379
  def Exec(self, feedback_fn):
6380
    """Execute disk replacement.
6381

6382
    This dispatches the disk replacement to the appropriate handler.
6383

6384
    """
6385
    if not self.disks:
6386
      feedback_fn("No disks need replacement")
6387
      return
6388

    
6389
    feedback_fn("Replacing disk(s) %s for %s" %
6390
                (", ".join([str(i) for i in self.disks]), self.instance.name))
6391

    
6392
    activate_disks = (not self.instance.admin_up)
6393

    
6394
    # Activate the instance disks if we're replacing them on a down instance
6395
    if activate_disks:
6396
      _StartInstanceDisks(self.lu, self.instance, True)
6397

    
6398
    try:
6399
      # Should we replace the secondary node?
6400
      if self.new_node is not None:
6401
        return self._ExecDrbd8Secondary()
6402
      else:
6403
        return self._ExecDrbd8DiskOnly()
6404

    
6405
    finally:
6406
      # Deactivate the instance disks if we're replacing them on a down instance
6407
      if activate_disks:
6408
        _SafeShutdownInstanceDisks(self.lu, self.instance)
6409

    
6410
  def _CheckVolumeGroup(self, nodes):
6411
    self.lu.LogInfo("Checking volume groups")
6412

    
6413
    vgname = self.cfg.GetVGName()
6414

    
6415
    # Make sure volume group exists on all involved nodes
6416
    results = self.rpc.call_vg_list(nodes)
6417
    if not results:
6418
      raise errors.OpExecError("Can't list volume groups on the nodes")
6419

    
6420
    for node in nodes:
6421
      res = results[node]
6422
      res.Raise("Error checking node %s" % node)
6423
      if vgname not in res.payload:
6424
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
6425
                                 (vgname, node))
6426

    
6427
  def _CheckDisksExistence(self, nodes):
6428
    # Check disk existence
6429
    for idx, dev in enumerate(self.instance.disks):
6430
      if idx not in self.disks:
6431
        continue
6432

    
6433
      for node in nodes:
6434
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
6435
        self.cfg.SetDiskID(dev, node)
6436

    
6437
        result = self.rpc.call_blockdev_find(node, dev)
6438

    
6439
        msg = result.fail_msg
6440
        if msg or not result.payload:
6441
          if not msg:
6442
            msg = "disk not found"
6443
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
6444
                                   (idx, node, msg))
6445

    
6446
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
6447
    for idx, dev in enumerate(self.instance.disks):
6448
      if idx not in self.disks:
6449
        continue
6450

    
6451
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
6452
                      (idx, node_name))
6453

    
6454
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
6455
                                   ldisk=ldisk):
6456
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
6457
                                 " replace disks for instance %s" %
6458
                                 (node_name, self.instance.name))
6459

    
6460
  def _CreateNewStorage(self, node_name):
6461
    vgname = self.cfg.GetVGName()
6462
    iv_names = {}
6463

    
6464
    for idx, dev in enumerate(self.instance.disks):
6465
      if idx not in self.disks:
6466
        continue
6467

    
6468
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
6469

    
6470
      self.cfg.SetDiskID(dev, node_name)
6471

    
6472
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
6473
      names = _GenerateUniqueNames(self.lu, lv_names)
6474

    
6475
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
6476
                             logical_id=(vgname, names[0]))
6477
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6478
                             logical_id=(vgname, names[1]))
6479

    
6480
      new_lvs = [lv_data, lv_meta]
6481
      old_lvs = dev.children
6482
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
6483

    
6484
      # we pass force_create=True to force the LVM creation
6485
      for new_lv in new_lvs:
6486
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
6487
                        _GetInstanceInfoText(self.instance), False)
6488

    
6489
    return iv_names
6490

    
6491
  def _CheckDevices(self, node_name, iv_names):
6492
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
6493
      self.cfg.SetDiskID(dev, node_name)
6494

    
6495
      result = self.rpc.call_blockdev_find(node_name, dev)
6496

    
6497
      msg = result.fail_msg
6498
      if msg or not result.payload:
6499
        if not msg:
6500
          msg = "disk not found"
6501
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
6502
                                 (name, msg))
6503

    
6504
      if result.payload.is_degraded:
6505
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
6506

    
6507
  def _RemoveOldStorage(self, node_name, iv_names):
6508
    for name, (dev, old_lvs, _) in iv_names.iteritems():
6509
      self.lu.LogInfo("Remove logical volumes for %s" % name)
6510

    
6511
      for lv in old_lvs:
6512
        self.cfg.SetDiskID(lv, node_name)
6513

    
6514
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
6515
        if msg:
6516
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
6517
                             hint="remove unused LVs manually")
6518

    
6519
  def _ExecDrbd8DiskOnly(self):
6520
    """Replace a disk on the primary or secondary for DRBD 8.
6521

6522
    The algorithm for replace is quite complicated:
6523

6524
      1. for each disk to be replaced:
6525

6526
        1. create new LVs on the target node with unique names
6527
        1. detach old LVs from the drbd device
6528
        1. rename old LVs to name_replaced.<time_t>
6529
        1. rename new LVs to old LVs
6530
        1. attach the new LVs (with the old names now) to the drbd device
6531

6532
      1. wait for sync across all devices
6533

6534
      1. for each modified disk:
6535

6536
        1. remove old LVs (which have the name name_replaces.<time_t>)
6537

6538
    Failures are not very well handled.
6539

6540
    """
6541
    steps_total = 6
6542

    
6543
    # Step: check device activation
6544
    self.lu.LogStep(1, steps_total, "Check device existence")
6545
    self._CheckDisksExistence([self.other_node, self.target_node])
6546
    self._CheckVolumeGroup([self.target_node, self.other_node])
6547

    
6548
    # Step: check other node consistency
6549
    self.lu.LogStep(2, steps_total, "Check peer consistency")
6550
    self._CheckDisksConsistency(self.other_node,
6551
                                self.other_node == self.instance.primary_node,
6552
                                False)
6553

    
6554
    # Step: create new storage
6555
    self.lu.LogStep(3, steps_total, "Allocate new storage")
6556
    iv_names = self._CreateNewStorage(self.target_node)
6557

    
6558
    # Step: for each lv, detach+rename*2+attach
6559
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
6560
    for dev, old_lvs, new_lvs in iv_names.itervalues():
6561
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
6562

    
6563
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
6564
                                                     old_lvs)
6565
      result.Raise("Can't detach drbd from local storage on node"
6566
                   " %s for device %s" % (self.target_node, dev.iv_name))
6567
      #dev.children = []
6568
      #cfg.Update(instance)
6569

    
6570
      # ok, we created the new LVs, so now we know we have the needed
6571
      # storage; as such, we proceed on the target node to rename
6572
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
6573
      # using the assumption that logical_id == physical_id (which in
6574
      # turn is the unique_id on that node)
6575

    
6576
      # FIXME(iustin): use a better name for the replaced LVs
6577
      temp_suffix = int(time.time())
6578
      ren_fn = lambda d, suff: (d.physical_id[0],
6579
                                d.physical_id[1] + "_replaced-%s" % suff)
6580

    
6581
      # Build the rename list based on what LVs exist on the node
6582
      rename_old_to_new = []
6583
      for to_ren in old_lvs:
6584
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
6585
        if not result.fail_msg and result.payload:
6586
          # device exists
6587
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
6588

    
6589
      self.lu.LogInfo("Renaming the old LVs on the target node")
6590
      result = self.rpc.call_blockdev_rename(self.target_node,
6591
                                             rename_old_to_new)
6592
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
6593

    
6594
      # Now we rename the new LVs to the old LVs
6595
      self.lu.LogInfo("Renaming the new LVs on the target node")
6596
      rename_new_to_old = [(new, old.physical_id)
6597
                           for old, new in zip(old_lvs, new_lvs)]
6598
      result = self.rpc.call_blockdev_rename(self.target_node,
6599
                                             rename_new_to_old)
6600
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
6601

    
6602
      for old, new in zip(old_lvs, new_lvs):
6603
        new.logical_id = old.logical_id
6604
        self.cfg.SetDiskID(new, self.target_node)
6605

    
6606
      for disk in old_lvs:
6607
        disk.logical_id = ren_fn(disk, temp_suffix)
6608
        self.cfg.SetDiskID(disk, self.target_node)
6609

    
6610
      # Now that the new lvs have the old name, we can add them to the device
6611
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
6612
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
6613
                                                  new_lvs)
6614
      msg = result.fail_msg
6615
      if msg:
6616
        for new_lv in new_lvs:
6617
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
6618
                                               new_lv).fail_msg
6619
          if msg2:
6620
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
6621
                               hint=("cleanup manually the unused logical"
6622
                                     "volumes"))
6623
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
6624

    
6625
      dev.children = new_lvs
6626

    
6627
      self.cfg.Update(self.instance)
6628

    
6629
    # Wait for sync
6630
    # This can fail as the old devices are degraded and _WaitForSync
6631
    # does a combined result over all disks, so we don't check its return value
6632
    self.lu.LogStep(5, steps_total, "Sync devices")
6633
    _WaitForSync(self.lu, self.instance, unlock=True)
6634

    
6635
    # Check all devices manually
6636
    self._CheckDevices(self.instance.primary_node, iv_names)
6637

    
6638
    # Step: remove old storage
6639
    self.lu.LogStep(6, steps_total, "Removing old storage")
6640
    self._RemoveOldStorage(self.target_node, iv_names)
6641

    
6642
  def _ExecDrbd8Secondary(self):
6643
    """Replace the secondary node for DRBD 8.
6644

6645
    The algorithm for replace is quite complicated:
6646
      - for all disks of the instance:
6647
        - create new LVs on the new node with same names
6648
        - shutdown the drbd device on the old secondary
6649
        - disconnect the drbd network on the primary
6650
        - create the drbd device on the new secondary
6651
        - network attach the drbd on the primary, using an artifice:
6652
          the drbd code for Attach() will connect to the network if it
6653
          finds a device which is connected to the good local disks but
6654
          not network enabled
6655
      - wait for sync across all devices
6656
      - remove all disks from the old secondary
6657

6658
    Failures are not very well handled.
6659

6660
    """
6661
    steps_total = 6
6662

    
6663
    # Step: check device activation
6664
    self.lu.LogStep(1, steps_total, "Check device existence")
6665
    self._CheckDisksExistence([self.instance.primary_node])
6666
    self._CheckVolumeGroup([self.instance.primary_node])
6667

    
6668
    # Step: check other node consistency
6669
    self.lu.LogStep(2, steps_total, "Check peer consistency")
6670
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
6671

    
6672
    # Step: create new storage
6673
    self.lu.LogStep(3, steps_total, "Allocate new storage")
6674
    for idx, dev in enumerate(self.instance.disks):
6675
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
6676
                      (self.new_node, idx))
6677
      # we pass force_create=True to force LVM creation
6678
      for new_lv in dev.children:
6679
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
6680
                        _GetInstanceInfoText(self.instance), False)
6681

    
6682
    # Step 4: dbrd minors and drbd setups changes
6683
    # after this, we must manually remove the drbd minors on both the
6684
    # error and the success paths
6685
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
6686
    minors = self.cfg.AllocateDRBDMinor([self.new_node
6687
                                         for dev in self.instance.disks],
6688
                                        self.instance.name)
6689
    logging.debug("Allocated minors %r" % (minors,))
6690

    
6691
    iv_names = {}
6692
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
6693
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
6694
                      (self.new_node, idx))
6695
      # create new devices on new_node; note that we create two IDs:
6696
      # one without port, so the drbd will be activated without
6697
      # networking information on the new node at this stage, and one
6698
      # with network, for the latter activation in step 4
6699
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
6700
      if self.instance.primary_node == o_node1:
6701
        p_minor = o_minor1
6702
      else:
6703
        p_minor = o_minor2
6704

    
6705
      new_alone_id = (self.instance.primary_node, self.new_node, None,
6706
                      p_minor, new_minor, o_secret)
6707
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
6708
                    p_minor, new_minor, o_secret)
6709

    
6710
      iv_names[idx] = (dev, dev.children, new_net_id)
6711
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
6712
                    new_net_id)
6713
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
6714
                              logical_id=new_alone_id,
6715
                              children=dev.children,
6716
                              size=dev.size)
6717
      try:
6718
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
6719
                              _GetInstanceInfoText(self.instance), False)
6720
      except errors.GenericError:
6721
        self.cfg.ReleaseDRBDMinors(self.instance.name)
6722
        raise
6723

    
6724
    # We have new devices, shutdown the drbd on the old secondary
6725
    for idx, dev in enumerate(self.instance.disks):
6726
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
6727
      self.cfg.SetDiskID(dev, self.target_node)
6728
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
6729
      if msg:
6730
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
6731
                           "node: %s" % (idx, msg),
6732
                           hint=("Please cleanup this device manually as"
6733
                                 " soon as possible"))
6734

    
6735
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
6736
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
6737
                                               self.node_secondary_ip,
6738
                                               self.instance.disks)\
6739
                                              [self.instance.primary_node]
6740

    
6741
    msg = result.fail_msg
6742
    if msg:
6743
      # detaches didn't succeed (unlikely)
6744
      self.cfg.ReleaseDRBDMinors(self.instance.name)
6745
      raise errors.OpExecError("Can't detach the disks from the network on"
6746
                               " old node: %s" % (msg,))
6747

    
6748
    # if we managed to detach at least one, we update all the disks of
6749
    # the instance to point to the new secondary
6750
    self.lu.LogInfo("Updating instance configuration")
6751
    for dev, _, new_logical_id in iv_names.itervalues():
6752
      dev.logical_id = new_logical_id
6753
      self.cfg.SetDiskID(dev, self.instance.primary_node)
6754

    
6755
    self.cfg.Update(self.instance)
6756

    
6757
    # and now perform the drbd attach
6758
    self.lu.LogInfo("Attaching primary drbds to new secondary"
6759
                    " (standalone => connected)")
6760
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
6761
                                            self.new_node],
6762
                                           self.node_secondary_ip,
6763
                                           self.instance.disks,
6764
                                           self.instance.name,
6765
                                           False)
6766
    for to_node, to_result in result.items():
6767
      msg = to_result.fail_msg
6768
      if msg:
6769
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
6770
                           to_node, msg,
6771
                           hint=("please do a gnt-instance info to see the"
6772
                                 " status of disks"))
6773

    
6774
    # Wait for sync
6775
    # This can fail as the old devices are degraded and _WaitForSync
6776
    # does a combined result over all disks, so we don't check its return value
6777
    self.lu.LogStep(5, steps_total, "Sync devices")
6778
    _WaitForSync(self.lu, self.instance, unlock=True)
6779

    
6780
    # Check all devices manually
6781
    self._CheckDevices(self.instance.primary_node, iv_names)
6782

    
6783
    # Step: remove old storage
6784
    self.lu.LogStep(6, steps_total, "Removing old storage")
6785
    self._RemoveOldStorage(self.target_node, iv_names)
6786

    
6787

    
6788
class LURepairNodeStorage(NoHooksLU):
6789
  """Repairs the volume group on a node.
6790

6791
  """
6792
  _OP_REQP = ["node_name"]
6793
  REQ_BGL = False
6794

    
6795
  def CheckArguments(self):
6796
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
6797
    if node_name is None:
6798
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
6799

    
6800
    self.op.node_name = node_name
6801

    
6802
  def ExpandNames(self):
6803
    self.needed_locks = {
6804
      locking.LEVEL_NODE: [self.op.node_name],
6805
      }
6806

    
6807
  def _CheckFaultyDisks(self, instance, node_name):
6808
    if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
6809
                                node_name, True):
6810
      raise errors.OpPrereqError("Instance '%s' has faulty disks on"
6811
                                 " node '%s'" % (instance.name, node_name))
6812

    
6813
  def CheckPrereq(self):
6814
    """Check prerequisites.
6815

6816
    """
6817
    storage_type = self.op.storage_type
6818

    
6819
    if (constants.SO_FIX_CONSISTENCY not in
6820
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
6821
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
6822
                                 " repaired" % storage_type)
6823

    
6824
    # Check whether any instance on this node has faulty disks
6825
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
6826
      check_nodes = set(inst.all_nodes)
6827
      check_nodes.discard(self.op.node_name)
6828
      for inst_node_name in check_nodes:
6829
        self._CheckFaultyDisks(inst, inst_node_name)
6830

    
6831
  def Exec(self, feedback_fn):
6832
    feedback_fn("Repairing storage unit '%s' on %s ..." %
6833
                (self.op.name, self.op.node_name))
6834

    
6835
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
6836
    result = self.rpc.call_storage_execute(self.op.node_name,
6837
                                           self.op.storage_type, st_args,
6838
                                           self.op.name,
6839
                                           constants.SO_FIX_CONSISTENCY)
6840
    result.Raise("Failed to repair storage unit '%s' on %s" %
6841
                 (self.op.name, self.op.node_name))
6842

    
6843

    
6844
class LUGrowDisk(LogicalUnit):
6845
  """Grow a disk of an instance.
6846

6847
  """
6848
  HPATH = "disk-grow"
6849
  HTYPE = constants.HTYPE_INSTANCE
6850
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
6851
  REQ_BGL = False
6852

    
6853
  def ExpandNames(self):
6854
    self._ExpandAndLockInstance()
6855
    self.needed_locks[locking.LEVEL_NODE] = []
6856
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6857

    
6858
  def DeclareLocks(self, level):
6859
    if level == locking.LEVEL_NODE:
6860
      self._LockInstancesNodes()
6861

    
6862
  def BuildHooksEnv(self):
6863
    """Build hooks env.
6864

6865
    This runs on the master, the primary and all the secondaries.
6866

6867
    """
6868
    env = {
6869
      "DISK": self.op.disk,
6870
      "AMOUNT": self.op.amount,
6871
      }
6872
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6873
    nl = [
6874
      self.cfg.GetMasterNode(),
6875
      self.instance.primary_node,
6876
      ]
6877
    return env, nl, nl
6878

    
6879
  def CheckPrereq(self):
6880
    """Check prerequisites.
6881

6882
    This checks that the instance is in the cluster.
6883

6884
    """
6885
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6886
    assert instance is not None, \
6887
      "Cannot retrieve locked instance %s" % self.op.instance_name
6888
    nodenames = list(instance.all_nodes)
6889
    for node in nodenames:
6890
      _CheckNodeOnline(self, node)
6891

    
6892

    
6893
    self.instance = instance
6894

    
6895
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
6896
      raise errors.OpPrereqError("Instance's disk layout does not support"
6897
                                 " growing.")
6898

    
6899
    self.disk = instance.FindDisk(self.op.disk)
6900

    
6901
    nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
6902
                                       instance.hypervisor)
6903
    for node in nodenames:
6904
      info = nodeinfo[node]
6905
      info.Raise("Cannot get current information from node %s" % node)
6906
      vg_free = info.payload.get('vg_free', None)
6907
      if not isinstance(vg_free, int):
6908
        raise errors.OpPrereqError("Can't compute free disk space on"
6909
                                   " node %s" % node)
6910
      if self.op.amount > vg_free:
6911
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
6912
                                   " %d MiB available, %d MiB required" %
6913
                                   (node, vg_free, self.op.amount))
6914

    
6915
  def Exec(self, feedback_fn):
6916
    """Execute disk grow.
6917

6918
    """
6919
    instance = self.instance
6920
    disk = self.disk
6921
    for node in instance.all_nodes:
6922
      self.cfg.SetDiskID(disk, node)
6923
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
6924
      result.Raise("Grow request failed to node %s" % node)
6925
    disk.RecordGrow(self.op.amount)
6926
    self.cfg.Update(instance)
6927
    if self.op.wait_for_sync:
6928
      disk_abort = not _WaitForSync(self, instance)
6929
      if disk_abort:
6930
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
6931
                             " status.\nPlease check the instance.")
6932

    
6933

    
6934
class LUQueryInstanceData(NoHooksLU):
6935
  """Query runtime instance data.
6936

6937
  """
6938
  _OP_REQP = ["instances", "static"]
6939
  REQ_BGL = False
6940

    
6941
  def ExpandNames(self):
6942
    self.needed_locks = {}
6943
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
6944

    
6945
    if not isinstance(self.op.instances, list):
6946
      raise errors.OpPrereqError("Invalid argument type 'instances'")
6947

    
6948
    if self.op.instances:
6949
      self.wanted_names = []
6950
      for name in self.op.instances:
6951
        full_name = self.cfg.ExpandInstanceName(name)
6952
        if full_name is None:
6953
          raise errors.OpPrereqError("Instance '%s' not known" % name)
6954
        self.wanted_names.append(full_name)
6955
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
6956
    else:
6957
      self.wanted_names = None
6958
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
6959

    
6960
    self.needed_locks[locking.LEVEL_NODE] = []
6961
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6962

    
6963
  def DeclareLocks(self, level):
6964
    if level == locking.LEVEL_NODE:
6965
      self._LockInstancesNodes()
6966

    
6967
  def CheckPrereq(self):
6968
    """Check prerequisites.
6969

6970
    This only checks the optional instance list against the existing names.
6971

6972
    """
6973
    if self.wanted_names is None:
6974
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
6975

    
6976
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
6977
                             in self.wanted_names]
6978
    return
6979

    
6980
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
6981
    """Returns the status of a block device
6982

6983
    """
6984
    if self.op.static or not node:
6985
      return None
6986

    
6987
    self.cfg.SetDiskID(dev, node)
6988

    
6989
    result = self.rpc.call_blockdev_find(node, dev)
6990
    if result.offline:
6991
      return None
6992

    
6993
    result.Raise("Can't compute disk status for %s" % instance_name)
6994

    
6995
    status = result.payload
6996
    if status is None:
6997
      return None
6998

    
6999
    return (status.dev_path, status.major, status.minor,
7000
            status.sync_percent, status.estimated_time,
7001
            status.is_degraded, status.ldisk_status)
7002

    
7003
  def _ComputeDiskStatus(self, instance, snode, dev):
7004
    """Compute block device status.
7005

7006
    """
7007
    if dev.dev_type in constants.LDS_DRBD:
7008
      # we change the snode then (otherwise we use the one passed in)
7009
      if dev.logical_id[0] == instance.primary_node:
7010
        snode = dev.logical_id[1]
7011
      else:
7012
        snode = dev.logical_id[0]
7013

    
7014
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
7015
                                              instance.name, dev)
7016
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
7017

    
7018
    if dev.children:
7019
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
7020
                      for child in dev.children]
7021
    else:
7022
      dev_children = []
7023

    
7024
    data = {
7025
      "iv_name": dev.iv_name,
7026
      "dev_type": dev.dev_type,
7027
      "logical_id": dev.logical_id,
7028
      "physical_id": dev.physical_id,
7029
      "pstatus": dev_pstatus,
7030
      "sstatus": dev_sstatus,
7031
      "children": dev_children,
7032
      "mode": dev.mode,
7033
      "size": dev.size,
7034
      }
7035

    
7036
    return data
7037

    
7038
  def Exec(self, feedback_fn):
7039
    """Gather and return data"""
7040
    result = {}
7041

    
7042
    cluster = self.cfg.GetClusterInfo()
7043

    
7044
    for instance in self.wanted_instances:
7045
      if not self.op.static:
7046
        remote_info = self.rpc.call_instance_info(instance.primary_node,
7047
                                                  instance.name,
7048
                                                  instance.hypervisor)
7049
        remote_info.Raise("Error checking node %s" % instance.primary_node)
7050
        remote_info = remote_info.payload
7051
        if remote_info and "state" in remote_info:
7052
          remote_state = "up"
7053
        else:
7054
          remote_state = "down"
7055
      else:
7056
        remote_state = None
7057
      if instance.admin_up:
7058
        config_state = "up"
7059
      else:
7060
        config_state = "down"
7061

    
7062
      disks = [self._ComputeDiskStatus(instance, None, device)
7063
               for device in instance.disks]
7064

    
7065
      idict = {
7066
        "name": instance.name,
7067
        "config_state": config_state,
7068
        "run_state": remote_state,
7069
        "pnode": instance.primary_node,
7070
        "snodes": instance.secondary_nodes,
7071
        "os": instance.os,
7072
        # this happens to be the same format used for hooks
7073
        "nics": _NICListToTuple(self, instance.nics),
7074
        "disks": disks,
7075
        "hypervisor": instance.hypervisor,
7076
        "network_port": instance.network_port,
7077
        "hv_instance": instance.hvparams,
7078
        "hv_actual": cluster.FillHV(instance),
7079
        "be_instance": instance.beparams,
7080
        "be_actual": cluster.FillBE(instance),
7081
        "serial_no": instance.serial_no,
7082
        "mtime": instance.mtime,
7083
        "ctime": instance.ctime,
7084
        "uuid": instance.uuid,
7085
        }
7086

    
7087
      result[instance.name] = idict
7088

    
7089
    return result
7090

    
7091

    
7092
class LUSetInstanceParams(LogicalUnit):
7093
  """Modifies an instances's parameters.
7094

7095
  """
7096
  HPATH = "instance-modify"
7097
  HTYPE = constants.HTYPE_INSTANCE
7098
  _OP_REQP = ["instance_name"]
7099
  REQ_BGL = False
7100

    
7101
  def CheckArguments(self):
7102
    if not hasattr(self.op, 'nics'):
7103
      self.op.nics = []
7104
    if not hasattr(self.op, 'disks'):
7105
      self.op.disks = []
7106
    if not hasattr(self.op, 'beparams'):
7107
      self.op.beparams = {}
7108
    if not hasattr(self.op, 'hvparams'):
7109
      self.op.hvparams = {}
7110
    self.op.force = getattr(self.op, "force", False)
7111
    if not (self.op.nics or self.op.disks or
7112
            self.op.hvparams or self.op.beparams):
7113
      raise errors.OpPrereqError("No changes submitted")
7114

    
7115
    # Disk validation
7116
    disk_addremove = 0
7117
    for disk_op, disk_dict in self.op.disks:
7118
      if disk_op == constants.DDM_REMOVE:
7119
        disk_addremove += 1
7120
        continue
7121
      elif disk_op == constants.DDM_ADD:
7122
        disk_addremove += 1
7123
      else:
7124
        if not isinstance(disk_op, int):
7125
          raise errors.OpPrereqError("Invalid disk index")
7126
        if not isinstance(disk_dict, dict):
7127
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
7128
          raise errors.OpPrereqError(msg)
7129

    
7130
      if disk_op == constants.DDM_ADD:
7131
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
7132
        if mode not in constants.DISK_ACCESS_SET:
7133
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode)
7134
        size = disk_dict.get('size', None)
7135
        if size is None:
7136
          raise errors.OpPrereqError("Required disk parameter size missing")
7137
        try:
7138
          size = int(size)
7139
        except ValueError, err:
7140
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
7141
                                     str(err))
7142
        disk_dict['size'] = size
7143
      else:
7144
        # modification of disk
7145
        if 'size' in disk_dict:
7146
          raise errors.OpPrereqError("Disk size change not possible, use"
7147
                                     " grow-disk")
7148

    
7149
    if disk_addremove > 1:
7150
      raise errors.OpPrereqError("Only one disk add or remove operation"
7151
                                 " supported at a time")
7152

    
7153
    # NIC validation
7154
    nic_addremove = 0
7155
    for nic_op, nic_dict in self.op.nics:
7156
      if nic_op == constants.DDM_REMOVE:
7157
        nic_addremove += 1
7158
        continue
7159
      elif nic_op == constants.DDM_ADD:
7160
        nic_addremove += 1
7161
      else:
7162
        if not isinstance(nic_op, int):
7163
          raise errors.OpPrereqError("Invalid nic index")
7164
        if not isinstance(nic_dict, dict):
7165
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
7166
          raise errors.OpPrereqError(msg)
7167

    
7168
      # nic_dict should be a dict
7169
      nic_ip = nic_dict.get('ip', None)
7170
      if nic_ip is not None:
7171
        if nic_ip.lower() == constants.VALUE_NONE:
7172
          nic_dict['ip'] = None
7173
        else:
7174
          if not utils.IsValidIP(nic_ip):
7175
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip)
7176

    
7177
      nic_bridge = nic_dict.get('bridge', None)
7178
      nic_link = nic_dict.get('link', None)
7179
      if nic_bridge and nic_link:
7180
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7181
                                   " at the same time")
7182
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
7183
        nic_dict['bridge'] = None
7184
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
7185
        nic_dict['link'] = None
7186

    
7187
      if nic_op == constants.DDM_ADD:
7188
        nic_mac = nic_dict.get('mac', None)
7189
        if nic_mac is None:
7190
          nic_dict['mac'] = constants.VALUE_AUTO
7191

    
7192
      if 'mac' in nic_dict:
7193
        nic_mac = nic_dict['mac']
7194
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7195
          if not utils.IsValidMac(nic_mac):
7196
            raise errors.OpPrereqError("Invalid MAC address %s" % nic_mac)
7197
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
7198
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
7199
                                     " modifying an existing nic")
7200

    
7201
    if nic_addremove > 1:
7202
      raise errors.OpPrereqError("Only one NIC add or remove operation"
7203
                                 " supported at a time")
7204

    
7205
  def ExpandNames(self):
7206
    self._ExpandAndLockInstance()
7207
    self.needed_locks[locking.LEVEL_NODE] = []
7208
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7209

    
7210
  def DeclareLocks(self, level):
7211
    if level == locking.LEVEL_NODE:
7212
      self._LockInstancesNodes()
7213

    
7214
  def BuildHooksEnv(self):
7215
    """Build hooks env.
7216

7217
    This runs on the master, primary and secondaries.
7218

7219
    """
7220
    args = dict()
7221
    if constants.BE_MEMORY in self.be_new:
7222
      args['memory'] = self.be_new[constants.BE_MEMORY]
7223
    if constants.BE_VCPUS in self.be_new:
7224
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
7225
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
7226
    # information at all.
7227
    if self.op.nics:
7228
      args['nics'] = []
7229
      nic_override = dict(self.op.nics)
7230
      c_nicparams = self.cluster.nicparams[constants.PP_DEFAULT]
7231
      for idx, nic in enumerate(self.instance.nics):
7232
        if idx in nic_override:
7233
          this_nic_override = nic_override[idx]
7234
        else:
7235
          this_nic_override = {}
7236
        if 'ip' in this_nic_override:
7237
          ip = this_nic_override['ip']
7238
        else:
7239
          ip = nic.ip
7240
        if 'mac' in this_nic_override:
7241
          mac = this_nic_override['mac']
7242
        else:
7243
          mac = nic.mac
7244
        if idx in self.nic_pnew:
7245
          nicparams = self.nic_pnew[idx]
7246
        else:
7247
          nicparams = objects.FillDict(c_nicparams, nic.nicparams)
7248
        mode = nicparams[constants.NIC_MODE]
7249
        link = nicparams[constants.NIC_LINK]
7250
        args['nics'].append((ip, mac, mode, link))
7251
      if constants.DDM_ADD in nic_override:
7252
        ip = nic_override[constants.DDM_ADD].get('ip', None)
7253
        mac = nic_override[constants.DDM_ADD]['mac']
7254
        nicparams = self.nic_pnew[constants.DDM_ADD]
7255
        mode = nicparams[constants.NIC_MODE]
7256
        link = nicparams[constants.NIC_LINK]
7257
        args['nics'].append((ip, mac, mode, link))
7258
      elif constants.DDM_REMOVE in nic_override:
7259
        del args['nics'][-1]
7260

    
7261
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
7262
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
7263
    return env, nl, nl
7264

    
7265
  def _GetUpdatedParams(self, old_params, update_dict,
7266
                        default_values, parameter_types):
7267
    """Return the new params dict for the given params.
7268

7269
    @type old_params: dict
7270
    @param old_params: old parameters
7271
    @type update_dict: dict
7272
    @param update_dict: dict containing new parameter values,
7273
                        or constants.VALUE_DEFAULT to reset the
7274
                        parameter to its default value
7275
    @type default_values: dict
7276
    @param default_values: default values for the filled parameters
7277
    @type parameter_types: dict
7278
    @param parameter_types: dict mapping target dict keys to types
7279
                            in constants.ENFORCEABLE_TYPES
7280
    @rtype: (dict, dict)
7281
    @return: (new_parameters, filled_parameters)
7282

7283
    """
7284
    params_copy = copy.deepcopy(old_params)
7285
    for key, val in update_dict.iteritems():
7286
      if val == constants.VALUE_DEFAULT:
7287
        try:
7288
          del params_copy[key]
7289
        except KeyError:
7290
          pass
7291
      else:
7292
        params_copy[key] = val
7293
    utils.ForceDictType(params_copy, parameter_types)
7294
    params_filled = objects.FillDict(default_values, params_copy)
7295
    return (params_copy, params_filled)
7296

    
7297
  def CheckPrereq(self):
7298
    """Check prerequisites.
7299

7300
    This only checks the instance list against the existing names.
7301

7302
    """
7303
    self.force = self.op.force
7304

    
7305
    # checking the new params on the primary/secondary nodes
7306

    
7307
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7308
    cluster = self.cluster = self.cfg.GetClusterInfo()
7309
    assert self.instance is not None, \
7310
      "Cannot retrieve locked instance %s" % self.op.instance_name
7311
    pnode = instance.primary_node
7312
    nodelist = list(instance.all_nodes)
7313

    
7314
    # hvparams processing
7315
    if self.op.hvparams:
7316
      i_hvdict, hv_new = self._GetUpdatedParams(
7317
                             instance.hvparams, self.op.hvparams,
7318
                             cluster.hvparams[instance.hypervisor],
7319
                             constants.HVS_PARAMETER_TYPES)
7320
      # local check
7321
      hypervisor.GetHypervisor(
7322
        instance.hypervisor).CheckParameterSyntax(hv_new)
7323
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
7324
      self.hv_new = hv_new # the new actual values
7325
      self.hv_inst = i_hvdict # the new dict (without defaults)
7326
    else:
7327
      self.hv_new = self.hv_inst = {}
7328

    
7329
    # beparams processing
7330
    if self.op.beparams:
7331
      i_bedict, be_new = self._GetUpdatedParams(
7332
                             instance.beparams, self.op.beparams,
7333
                             cluster.beparams[constants.PP_DEFAULT],
7334
                             constants.BES_PARAMETER_TYPES)
7335
      self.be_new = be_new # the new actual values
7336
      self.be_inst = i_bedict # the new dict (without defaults)
7337
    else:
7338
      self.be_new = self.be_inst = {}
7339

    
7340
    self.warn = []
7341

    
7342
    if constants.BE_MEMORY in self.op.beparams and not self.force:
7343
      mem_check_list = [pnode]
7344
      if be_new[constants.BE_AUTO_BALANCE]:
7345
        # either we changed auto_balance to yes or it was from before
7346
        mem_check_list.extend(instance.secondary_nodes)
7347
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
7348
                                                  instance.hypervisor)
7349
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
7350
                                         instance.hypervisor)
7351
      pninfo = nodeinfo[pnode]
7352
      msg = pninfo.fail_msg
7353
      if msg:
7354
        # Assume the primary node is unreachable and go ahead
7355
        self.warn.append("Can't get info from primary node %s: %s" %
7356
                         (pnode,  msg))
7357
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
7358
        self.warn.append("Node data from primary node %s doesn't contain"
7359
                         " free memory information" % pnode)
7360
      elif instance_info.fail_msg:
7361
        self.warn.append("Can't get instance runtime information: %s" %
7362
                        instance_info.fail_msg)
7363
      else:
7364
        if instance_info.payload:
7365
          current_mem = int(instance_info.payload['memory'])
7366
        else:
7367
          # Assume instance not running
7368
          # (there is a slight race condition here, but it's not very probable,
7369
          # and we have no other way to check)
7370
          current_mem = 0
7371
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
7372
                    pninfo.payload['memory_free'])
7373
        if miss_mem > 0:
7374
          raise errors.OpPrereqError("This change will prevent the instance"
7375
                                     " from starting, due to %d MB of memory"
7376
                                     " missing on its primary node" % miss_mem)
7377

    
7378
      if be_new[constants.BE_AUTO_BALANCE]:
7379
        for node, nres in nodeinfo.items():
7380
          if node not in instance.secondary_nodes:
7381
            continue
7382
          msg = nres.fail_msg
7383
          if msg:
7384
            self.warn.append("Can't get info from secondary node %s: %s" %
7385
                             (node, msg))
7386
          elif not isinstance(nres.payload.get('memory_free', None), int):
7387
            self.warn.append("Secondary node %s didn't return free"
7388
                             " memory information" % node)
7389
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
7390
            self.warn.append("Not enough memory to failover instance to"
7391
                             " secondary node %s" % node)
7392

    
7393
    # NIC processing
7394
    self.nic_pnew = {}
7395
    self.nic_pinst = {}
7396
    for nic_op, nic_dict in self.op.nics:
7397
      if nic_op == constants.DDM_REMOVE:
7398
        if not instance.nics:
7399
          raise errors.OpPrereqError("Instance has no NICs, cannot remove")
7400
        continue
7401
      if nic_op != constants.DDM_ADD:
7402
        # an existing nic
7403
        if nic_op < 0 or nic_op >= len(instance.nics):
7404
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
7405
                                     " are 0 to %d" %
7406
                                     (nic_op, len(instance.nics)))
7407
        old_nic_params = instance.nics[nic_op].nicparams
7408
        old_nic_ip = instance.nics[nic_op].ip
7409
      else:
7410
        old_nic_params = {}
7411
        old_nic_ip = None
7412

    
7413
      update_params_dict = dict([(key, nic_dict[key])
7414
                                 for key in constants.NICS_PARAMETERS
7415
                                 if key in nic_dict])
7416

    
7417
      if 'bridge' in nic_dict:
7418
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
7419

    
7420
      new_nic_params, new_filled_nic_params = \
7421
          self._GetUpdatedParams(old_nic_params, update_params_dict,
7422
                                 cluster.nicparams[constants.PP_DEFAULT],
7423
                                 constants.NICS_PARAMETER_TYPES)
7424
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
7425
      self.nic_pinst[nic_op] = new_nic_params
7426
      self.nic_pnew[nic_op] = new_filled_nic_params
7427
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
7428

    
7429
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
7430
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
7431
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
7432
        if msg:
7433
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
7434
          if self.force:
7435
            self.warn.append(msg)
7436
          else:
7437
            raise errors.OpPrereqError(msg)
7438
      if new_nic_mode == constants.NIC_MODE_ROUTED:
7439
        if 'ip' in nic_dict:
7440
          nic_ip = nic_dict['ip']
7441
        else:
7442
          nic_ip = old_nic_ip
7443
        if nic_ip is None:
7444
          raise errors.OpPrereqError('Cannot set the nic ip to None'
7445
                                     ' on a routed nic')
7446
      if 'mac' in nic_dict:
7447
        nic_mac = nic_dict['mac']
7448
        if nic_mac is None:
7449
          raise errors.OpPrereqError('Cannot set the nic mac to None')
7450
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7451
          # otherwise generate the mac
7452
          nic_dict['mac'] = self.cfg.GenerateMAC()
7453
        else:
7454
          # or validate/reserve the current one
7455
          if self.cfg.IsMacInUse(nic_mac):
7456
            raise errors.OpPrereqError("MAC address %s already in use"
7457
                                       " in cluster" % nic_mac)
7458

    
7459
    # DISK processing
7460
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
7461
      raise errors.OpPrereqError("Disk operations not supported for"
7462
                                 " diskless instances")
7463
    for disk_op, disk_dict in self.op.disks:
7464
      if disk_op == constants.DDM_REMOVE:
7465
        if len(instance.disks) == 1:
7466
          raise errors.OpPrereqError("Cannot remove the last disk of"
7467
                                     " an instance")
7468
        ins_l = self.rpc.call_instance_list([pnode], [instance.hypervisor])
7469
        ins_l = ins_l[pnode]
7470
        msg = ins_l.fail_msg
7471
        if msg:
7472
          raise errors.OpPrereqError("Can't contact node %s: %s" %
7473
                                     (pnode, msg))
7474
        if instance.name in ins_l.payload:
7475
          raise errors.OpPrereqError("Instance is running, can't remove"
7476
                                     " disks.")
7477

    
7478
      if (disk_op == constants.DDM_ADD and
7479
          len(instance.nics) >= constants.MAX_DISKS):
7480
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
7481
                                   " add more" % constants.MAX_DISKS)
7482
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
7483
        # an existing disk
7484
        if disk_op < 0 or disk_op >= len(instance.disks):
7485
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
7486
                                     " are 0 to %d" %
7487
                                     (disk_op, len(instance.disks)))
7488

    
7489
    return
7490

    
7491
  def Exec(self, feedback_fn):
7492
    """Modifies an instance.
7493

7494
    All parameters take effect only at the next restart of the instance.
7495

7496
    """
7497
    # Process here the warnings from CheckPrereq, as we don't have a
7498
    # feedback_fn there.
7499
    for warn in self.warn:
7500
      feedback_fn("WARNING: %s" % warn)
7501

    
7502
    result = []
7503
    instance = self.instance
7504
    cluster = self.cluster
7505
    # disk changes
7506
    for disk_op, disk_dict in self.op.disks:
7507
      if disk_op == constants.DDM_REMOVE:
7508
        # remove the last disk
7509
        device = instance.disks.pop()
7510
        device_idx = len(instance.disks)
7511
        for node, disk in device.ComputeNodeTree(instance.primary_node):
7512
          self.cfg.SetDiskID(disk, node)
7513
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
7514
          if msg:
7515
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
7516
                            " continuing anyway", device_idx, node, msg)
7517
        result.append(("disk/%d" % device_idx, "remove"))
7518
      elif disk_op == constants.DDM_ADD:
7519
        # add a new disk
7520
        if instance.disk_template == constants.DT_FILE:
7521
          file_driver, file_path = instance.disks[0].logical_id
7522
          file_path = os.path.dirname(file_path)
7523
        else:
7524
          file_driver = file_path = None
7525
        disk_idx_base = len(instance.disks)
7526
        new_disk = _GenerateDiskTemplate(self,
7527
                                         instance.disk_template,
7528
                                         instance.name, instance.primary_node,
7529
                                         instance.secondary_nodes,
7530
                                         [disk_dict],
7531
                                         file_path,
7532
                                         file_driver,
7533
                                         disk_idx_base)[0]
7534
        instance.disks.append(new_disk)
7535
        info = _GetInstanceInfoText(instance)
7536

    
7537
        logging.info("Creating volume %s for instance %s",
7538
                     new_disk.iv_name, instance.name)
7539
        # Note: this needs to be kept in sync with _CreateDisks
7540
        #HARDCODE
7541
        for node in instance.all_nodes:
7542
          f_create = node == instance.primary_node
7543
          try:
7544
            _CreateBlockDev(self, node, instance, new_disk,
7545
                            f_create, info, f_create)
7546
          except errors.OpExecError, err:
7547
            self.LogWarning("Failed to create volume %s (%s) on"
7548
                            " node %s: %s",
7549
                            new_disk.iv_name, new_disk, node, err)
7550
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
7551
                       (new_disk.size, new_disk.mode)))
7552
      else:
7553
        # change a given disk
7554
        instance.disks[disk_op].mode = disk_dict['mode']
7555
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
7556
    # NIC changes
7557
    for nic_op, nic_dict in self.op.nics:
7558
      if nic_op == constants.DDM_REMOVE:
7559
        # remove the last nic
7560
        del instance.nics[-1]
7561
        result.append(("nic.%d" % len(instance.nics), "remove"))
7562
      elif nic_op == constants.DDM_ADD:
7563
        # mac and bridge should be set, by now
7564
        mac = nic_dict['mac']
7565
        ip = nic_dict.get('ip', None)
7566
        nicparams = self.nic_pinst[constants.DDM_ADD]
7567
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
7568
        instance.nics.append(new_nic)
7569
        result.append(("nic.%d" % (len(instance.nics) - 1),
7570
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
7571
                       (new_nic.mac, new_nic.ip,
7572
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
7573
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
7574
                       )))
7575
      else:
7576
        for key in 'mac', 'ip':
7577
          if key in nic_dict:
7578
            setattr(instance.nics[nic_op], key, nic_dict[key])
7579
        if nic_op in self.nic_pnew:
7580
          instance.nics[nic_op].nicparams = self.nic_pnew[nic_op]
7581
        for key, val in nic_dict.iteritems():
7582
          result.append(("nic.%s/%d" % (key, nic_op), val))
7583

    
7584
    # hvparams changes
7585
    if self.op.hvparams:
7586
      instance.hvparams = self.hv_inst
7587
      for key, val in self.op.hvparams.iteritems():
7588
        result.append(("hv/%s" % key, val))
7589

    
7590
    # beparams changes
7591
    if self.op.beparams:
7592
      instance.beparams = self.be_inst
7593
      for key, val in self.op.beparams.iteritems():
7594
        result.append(("be/%s" % key, val))
7595

    
7596
    self.cfg.Update(instance)
7597

    
7598
    return result
7599

    
7600

    
7601
class LUQueryExports(NoHooksLU):
7602
  """Query the exports list
7603

7604
  """
7605
  _OP_REQP = ['nodes']
7606
  REQ_BGL = False
7607

    
7608
  def ExpandNames(self):
7609
    self.needed_locks = {}
7610
    self.share_locks[locking.LEVEL_NODE] = 1
7611
    if not self.op.nodes:
7612
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7613
    else:
7614
      self.needed_locks[locking.LEVEL_NODE] = \
7615
        _GetWantedNodes(self, self.op.nodes)
7616

    
7617
  def CheckPrereq(self):
7618
    """Check prerequisites.
7619

7620
    """
7621
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
7622

    
7623
  def Exec(self, feedback_fn):
7624
    """Compute the list of all the exported system images.
7625

7626
    @rtype: dict
7627
    @return: a dictionary with the structure node->(export-list)
7628
        where export-list is a list of the instances exported on
7629
        that node.
7630

7631
    """
7632
    rpcresult = self.rpc.call_export_list(self.nodes)
7633
    result = {}
7634
    for node in rpcresult:
7635
      if rpcresult[node].fail_msg:
7636
        result[node] = False
7637
      else:
7638
        result[node] = rpcresult[node].payload
7639

    
7640
    return result
7641

    
7642

    
7643
class LUExportInstance(LogicalUnit):
7644
  """Export an instance to an image in the cluster.
7645

7646
  """
7647
  HPATH = "instance-export"
7648
  HTYPE = constants.HTYPE_INSTANCE
7649
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
7650
  REQ_BGL = False
7651

    
7652
  def ExpandNames(self):
7653
    self._ExpandAndLockInstance()
7654
    # FIXME: lock only instance primary and destination node
7655
    #
7656
    # Sad but true, for now we have do lock all nodes, as we don't know where
7657
    # the previous export might be, and and in this LU we search for it and
7658
    # remove it from its current node. In the future we could fix this by:
7659
    #  - making a tasklet to search (share-lock all), then create the new one,
7660
    #    then one to remove, after
7661
    #  - removing the removal operation altogether
7662
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7663

    
7664
  def DeclareLocks(self, level):
7665
    """Last minute lock declaration."""
7666
    # All nodes are locked anyway, so nothing to do here.
7667

    
7668
  def BuildHooksEnv(self):
7669
    """Build hooks env.
7670

7671
    This will run on the master, primary node and target node.
7672

7673
    """
7674
    env = {
7675
      "EXPORT_NODE": self.op.target_node,
7676
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
7677
      }
7678
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
7679
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node,
7680
          self.op.target_node]
7681
    return env, nl, nl
7682

    
7683
  def CheckPrereq(self):
7684
    """Check prerequisites.
7685

7686
    This checks that the instance and node names are valid.
7687

7688
    """
7689
    instance_name = self.op.instance_name
7690
    self.instance = self.cfg.GetInstanceInfo(instance_name)
7691
    assert self.instance is not None, \
7692
          "Cannot retrieve locked instance %s" % self.op.instance_name
7693
    _CheckNodeOnline(self, self.instance.primary_node)
7694

    
7695
    self.dst_node = self.cfg.GetNodeInfo(
7696
      self.cfg.ExpandNodeName(self.op.target_node))
7697

    
7698
    if self.dst_node is None:
7699
      # This is wrong node name, not a non-locked node
7700
      raise errors.OpPrereqError("Wrong node name %s" % self.op.target_node)
7701
    _CheckNodeOnline(self, self.dst_node.name)
7702
    _CheckNodeNotDrained(self, self.dst_node.name)
7703

    
7704
    # instance disk type verification
7705
    for disk in self.instance.disks:
7706
      if disk.dev_type == constants.LD_FILE:
7707
        raise errors.OpPrereqError("Export not supported for instances with"
7708
                                   " file-based disks")
7709

    
7710
  def Exec(self, feedback_fn):
7711
    """Export an instance to an image in the cluster.
7712

7713
    """
7714
    instance = self.instance
7715
    dst_node = self.dst_node
7716
    src_node = instance.primary_node
7717

    
7718
    if self.op.shutdown:
7719
      # shutdown the instance, but not the disks
7720
      feedback_fn("Shutting down instance %s" % instance.name)
7721
      result = self.rpc.call_instance_shutdown(src_node, instance)
7722
      result.Raise("Could not shutdown instance %s on"
7723
                   " node %s" % (instance.name, src_node))
7724

    
7725
    vgname = self.cfg.GetVGName()
7726

    
7727
    snap_disks = []
7728

    
7729
    # set the disks ID correctly since call_instance_start needs the
7730
    # correct drbd minor to create the symlinks
7731
    for disk in instance.disks:
7732
      self.cfg.SetDiskID(disk, src_node)
7733

    
7734
    # per-disk results
7735
    dresults = []
7736
    try:
7737
      for idx, disk in enumerate(instance.disks):
7738
        feedback_fn("Creating a snapshot of disk/%s on node %s" %
7739
                    (idx, src_node))
7740

    
7741
        # result.payload will be a snapshot of an lvm leaf of the one we passed
7742
        result = self.rpc.call_blockdev_snapshot(src_node, disk)
7743
        msg = result.fail_msg
7744
        if msg:
7745
          self.LogWarning("Could not snapshot disk/%s on node %s: %s",
7746
                          idx, src_node, msg)
7747
          snap_disks.append(False)
7748
        else:
7749
          disk_id = (vgname, result.payload)
7750
          new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
7751
                                 logical_id=disk_id, physical_id=disk_id,
7752
                                 iv_name=disk.iv_name)
7753
          snap_disks.append(new_dev)
7754

    
7755
    finally:
7756
      if self.op.shutdown and instance.admin_up:
7757
        feedback_fn("Starting instance %s" % instance.name)
7758
        result = self.rpc.call_instance_start(src_node, instance, None, None)
7759
        msg = result.fail_msg
7760
        if msg:
7761
          _ShutdownInstanceDisks(self, instance)
7762
          raise errors.OpExecError("Could not start instance: %s" % msg)
7763

    
7764
    # TODO: check for size
7765

    
7766
    cluster_name = self.cfg.GetClusterName()
7767
    for idx, dev in enumerate(snap_disks):
7768
      feedback_fn("Exporting snapshot %s from %s to %s" %
7769
                  (idx, src_node, dst_node.name))
7770
      if dev:
7771
        result = self.rpc.call_snapshot_export(src_node, dev, dst_node.name,
7772
                                               instance, cluster_name, idx)
7773
        msg = result.fail_msg
7774
        if msg:
7775
          self.LogWarning("Could not export disk/%s from node %s to"
7776
                          " node %s: %s", idx, src_node, dst_node.name, msg)
7777
          dresults.append(False)
7778
        else:
7779
          dresults.append(True)
7780
        msg = self.rpc.call_blockdev_remove(src_node, dev).fail_msg
7781
        if msg:
7782
          self.LogWarning("Could not remove snapshot for disk/%d from node"
7783
                          " %s: %s", idx, src_node, msg)
7784
      else:
7785
        dresults.append(False)
7786

    
7787
    feedback_fn("Finalizing export on %s" % dst_node.name)
7788
    result = self.rpc.call_finalize_export(dst_node.name, instance, snap_disks)
7789
    fin_resu = True
7790
    msg = result.fail_msg
7791
    if msg:
7792
      self.LogWarning("Could not finalize export for instance %s"
7793
                      " on node %s: %s", instance.name, dst_node.name, msg)
7794
      fin_resu = False
7795

    
7796
    nodelist = self.cfg.GetNodeList()
7797
    nodelist.remove(dst_node.name)
7798

    
7799
    # on one-node clusters nodelist will be empty after the removal
7800
    # if we proceed the backup would be removed because OpQueryExports
7801
    # substitutes an empty list with the full cluster node list.
7802
    iname = instance.name
7803
    if nodelist:
7804
      feedback_fn("Removing old exports for instance %s" % iname)
7805
      exportlist = self.rpc.call_export_list(nodelist)
7806
      for node in exportlist:
7807
        if exportlist[node].fail_msg:
7808
          continue
7809
        if iname in exportlist[node].payload:
7810
          msg = self.rpc.call_export_remove(node, iname).fail_msg
7811
          if msg:
7812
            self.LogWarning("Could not remove older export for instance %s"
7813
                            " on node %s: %s", iname, node, msg)
7814
    return fin_resu, dresults
7815

    
7816

    
7817
class LURemoveExport(NoHooksLU):
7818
  """Remove exports related to the named instance.
7819

7820
  """
7821
  _OP_REQP = ["instance_name"]
7822
  REQ_BGL = False
7823

    
7824
  def ExpandNames(self):
7825
    self.needed_locks = {}
7826
    # We need all nodes to be locked in order for RemoveExport to work, but we
7827
    # don't need to lock the instance itself, as nothing will happen to it (and
7828
    # we can remove exports also for a removed instance)
7829
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7830

    
7831
  def CheckPrereq(self):
7832
    """Check prerequisites.
7833
    """
7834
    pass
7835

    
7836
  def Exec(self, feedback_fn):
7837
    """Remove any export.
7838

7839
    """
7840
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
7841
    # If the instance was not found we'll try with the name that was passed in.
7842
    # This will only work if it was an FQDN, though.
7843
    fqdn_warn = False
7844
    if not instance_name:
7845
      fqdn_warn = True
7846
      instance_name = self.op.instance_name
7847

    
7848
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
7849
    exportlist = self.rpc.call_export_list(locked_nodes)
7850
    found = False
7851
    for node in exportlist:
7852
      msg = exportlist[node].fail_msg
7853
      if msg:
7854
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
7855
        continue
7856
      if instance_name in exportlist[node].payload:
7857
        found = True
7858
        result = self.rpc.call_export_remove(node, instance_name)
7859
        msg = result.fail_msg
7860
        if msg:
7861
          logging.error("Could not remove export for instance %s"
7862
                        " on node %s: %s", instance_name, node, msg)
7863

    
7864
    if fqdn_warn and not found:
7865
      feedback_fn("Export not found. If trying to remove an export belonging"
7866
                  " to a deleted instance please use its Fully Qualified"
7867
                  " Domain Name.")
7868

    
7869

    
7870
class TagsLU(NoHooksLU):
7871
  """Generic tags LU.
7872

7873
  This is an abstract class which is the parent of all the other tags LUs.
7874

7875
  """
7876

    
7877
  def ExpandNames(self):
7878
    self.needed_locks = {}
7879
    if self.op.kind == constants.TAG_NODE:
7880
      name = self.cfg.ExpandNodeName(self.op.name)
7881
      if name is None:
7882
        raise errors.OpPrereqError("Invalid node name (%s)" %
7883
                                   (self.op.name,))
7884
      self.op.name = name
7885
      self.needed_locks[locking.LEVEL_NODE] = name
7886
    elif self.op.kind == constants.TAG_INSTANCE:
7887
      name = self.cfg.ExpandInstanceName(self.op.name)
7888
      if name is None:
7889
        raise errors.OpPrereqError("Invalid instance name (%s)" %
7890
                                   (self.op.name,))
7891
      self.op.name = name
7892
      self.needed_locks[locking.LEVEL_INSTANCE] = name
7893

    
7894
  def CheckPrereq(self):
7895
    """Check prerequisites.
7896

7897
    """
7898
    if self.op.kind == constants.TAG_CLUSTER:
7899
      self.target = self.cfg.GetClusterInfo()
7900
    elif self.op.kind == constants.TAG_NODE:
7901
      self.target = self.cfg.GetNodeInfo(self.op.name)
7902
    elif self.op.kind == constants.TAG_INSTANCE:
7903
      self.target = self.cfg.GetInstanceInfo(self.op.name)
7904
    else:
7905
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
7906
                                 str(self.op.kind))
7907

    
7908

    
7909
class LUGetTags(TagsLU):
7910
  """Returns the tags of a given object.
7911

7912
  """
7913
  _OP_REQP = ["kind", "name"]
7914
  REQ_BGL = False
7915

    
7916
  def Exec(self, feedback_fn):
7917
    """Returns the tag list.
7918

7919
    """
7920
    return list(self.target.GetTags())
7921

    
7922

    
7923
class LUSearchTags(NoHooksLU):
7924
  """Searches the tags for a given pattern.
7925

7926
  """
7927
  _OP_REQP = ["pattern"]
7928
  REQ_BGL = False
7929

    
7930
  def ExpandNames(self):
7931
    self.needed_locks = {}
7932

    
7933
  def CheckPrereq(self):
7934
    """Check prerequisites.
7935

7936
    This checks the pattern passed for validity by compiling it.
7937

7938
    """
7939
    try:
7940
      self.re = re.compile(self.op.pattern)
7941
    except re.error, err:
7942
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
7943
                                 (self.op.pattern, err))
7944

    
7945
  def Exec(self, feedback_fn):
7946
    """Returns the tag list.
7947

7948
    """
7949
    cfg = self.cfg
7950
    tgts = [("/cluster", cfg.GetClusterInfo())]
7951
    ilist = cfg.GetAllInstancesInfo().values()
7952
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
7953
    nlist = cfg.GetAllNodesInfo().values()
7954
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
7955
    results = []
7956
    for path, target in tgts:
7957
      for tag in target.GetTags():
7958
        if self.re.search(tag):
7959
          results.append((path, tag))
7960
    return results
7961

    
7962

    
7963
class LUAddTags(TagsLU):
7964
  """Sets a tag on a given object.
7965

7966
  """
7967
  _OP_REQP = ["kind", "name", "tags"]
7968
  REQ_BGL = False
7969

    
7970
  def CheckPrereq(self):
7971
    """Check prerequisites.
7972

7973
    This checks the type and length of the tag name and value.
7974

7975
    """
7976
    TagsLU.CheckPrereq(self)
7977
    for tag in self.op.tags:
7978
      objects.TaggableObject.ValidateTag(tag)
7979

    
7980
  def Exec(self, feedback_fn):
7981
    """Sets the tag.
7982

7983
    """
7984
    try:
7985
      for tag in self.op.tags:
7986
        self.target.AddTag(tag)
7987
    except errors.TagError, err:
7988
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
7989
    try:
7990
      self.cfg.Update(self.target)
7991
    except errors.ConfigurationError:
7992
      raise errors.OpRetryError("There has been a modification to the"
7993
                                " config file and the operation has been"
7994
                                " aborted. Please retry.")
7995

    
7996

    
7997
class LUDelTags(TagsLU):
7998
  """Delete a list of tags from a given object.
7999

8000
  """
8001
  _OP_REQP = ["kind", "name", "tags"]
8002
  REQ_BGL = False
8003

    
8004
  def CheckPrereq(self):
8005
    """Check prerequisites.
8006

8007
    This checks that we have the given tag.
8008

8009
    """
8010
    TagsLU.CheckPrereq(self)
8011
    for tag in self.op.tags:
8012
      objects.TaggableObject.ValidateTag(tag)
8013
    del_tags = frozenset(self.op.tags)
8014
    cur_tags = self.target.GetTags()
8015
    if not del_tags <= cur_tags:
8016
      diff_tags = del_tags - cur_tags
8017
      diff_names = ["'%s'" % tag for tag in diff_tags]
8018
      diff_names.sort()
8019
      raise errors.OpPrereqError("Tag(s) %s not found" %
8020
                                 (",".join(diff_names)))
8021

    
8022
  def Exec(self, feedback_fn):
8023
    """Remove the tag from the object.
8024

8025
    """
8026
    for tag in self.op.tags:
8027
      self.target.RemoveTag(tag)
8028
    try:
8029
      self.cfg.Update(self.target)
8030
    except errors.ConfigurationError:
8031
      raise errors.OpRetryError("There has been a modification to the"
8032
                                " config file and the operation has been"
8033
                                " aborted. Please retry.")
8034

    
8035

    
8036
class LUTestDelay(NoHooksLU):
8037
  """Sleep for a specified amount of time.
8038

8039
  This LU sleeps on the master and/or nodes for a specified amount of
8040
  time.
8041

8042
  """
8043
  _OP_REQP = ["duration", "on_master", "on_nodes"]
8044
  REQ_BGL = False
8045

    
8046
  def ExpandNames(self):
8047
    """Expand names and set required locks.
8048

8049
    This expands the node list, if any.
8050

8051
    """
8052
    self.needed_locks = {}
8053
    if self.op.on_nodes:
8054
      # _GetWantedNodes can be used here, but is not always appropriate to use
8055
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
8056
      # more information.
8057
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
8058
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
8059

    
8060
  def CheckPrereq(self):
8061
    """Check prerequisites.
8062

8063
    """
8064

    
8065
  def Exec(self, feedback_fn):
8066
    """Do the actual sleep.
8067

8068
    """
8069
    if self.op.on_master:
8070
      if not utils.TestDelay(self.op.duration):
8071
        raise errors.OpExecError("Error during master delay test")
8072
    if self.op.on_nodes:
8073
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
8074
      for node, node_result in result.items():
8075
        node_result.Raise("Failure during rpc call to node %s" % node)
8076

    
8077

    
8078
class IAllocator(object):
8079
  """IAllocator framework.
8080

8081
  An IAllocator instance has three sets of attributes:
8082
    - cfg that is needed to query the cluster
8083
    - input data (all members of the _KEYS class attribute are required)
8084
    - four buffer attributes (in|out_data|text), that represent the
8085
      input (to the external script) in text and data structure format,
8086
      and the output from it, again in two formats
8087
    - the result variables from the script (success, info, nodes) for
8088
      easy usage
8089

8090
  """
8091
  _ALLO_KEYS = [
8092
    "mem_size", "disks", "disk_template",
8093
    "os", "tags", "nics", "vcpus", "hypervisor",
8094
    ]
8095
  _RELO_KEYS = [
8096
    "relocate_from",
8097
    ]
8098

    
8099
  def __init__(self, cfg, rpc, mode, name, **kwargs):
8100
    self.cfg = cfg
8101
    self.rpc = rpc
8102
    # init buffer variables
8103
    self.in_text = self.out_text = self.in_data = self.out_data = None
8104
    # init all input fields so that pylint is happy
8105
    self.mode = mode
8106
    self.name = name
8107
    self.mem_size = self.disks = self.disk_template = None
8108
    self.os = self.tags = self.nics = self.vcpus = None
8109
    self.hypervisor = None
8110
    self.relocate_from = None
8111
    # computed fields
8112
    self.required_nodes = None
8113
    # init result fields
8114
    self.success = self.info = self.nodes = None
8115
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
8116
      keyset = self._ALLO_KEYS
8117
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
8118
      keyset = self._RELO_KEYS
8119
    else:
8120
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
8121
                                   " IAllocator" % self.mode)
8122
    for key in kwargs:
8123
      if key not in keyset:
8124
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
8125
                                     " IAllocator" % key)
8126
      setattr(self, key, kwargs[key])
8127
    for key in keyset:
8128
      if key not in kwargs:
8129
        raise errors.ProgrammerError("Missing input parameter '%s' to"
8130
                                     " IAllocator" % key)
8131
    self._BuildInputData()
8132

    
8133
  def _ComputeClusterData(self):
8134
    """Compute the generic allocator input data.
8135

8136
    This is the data that is independent of the actual operation.
8137

8138
    """
8139
    cfg = self.cfg
8140
    cluster_info = cfg.GetClusterInfo()
8141
    # cluster data
8142
    data = {
8143
      "version": constants.IALLOCATOR_VERSION,
8144
      "cluster_name": cfg.GetClusterName(),
8145
      "cluster_tags": list(cluster_info.GetTags()),
8146
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
8147
      # we don't have job IDs
8148
      }
8149
    iinfo = cfg.GetAllInstancesInfo().values()
8150
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
8151

    
8152
    # node data
8153
    node_results = {}
8154
    node_list = cfg.GetNodeList()
8155

    
8156
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
8157
      hypervisor_name = self.hypervisor
8158
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
8159
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
8160

    
8161
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
8162
                                        hypervisor_name)
8163
    node_iinfo = \
8164
      self.rpc.call_all_instances_info(node_list,
8165
                                       cluster_info.enabled_hypervisors)
8166
    for nname, nresult in node_data.items():
8167
      # first fill in static (config-based) values
8168
      ninfo = cfg.GetNodeInfo(nname)
8169
      pnr = {
8170
        "tags": list(ninfo.GetTags()),
8171
        "primary_ip": ninfo.primary_ip,
8172
        "secondary_ip": ninfo.secondary_ip,
8173
        "offline": ninfo.offline,
8174
        "drained": ninfo.drained,
8175
        "master_candidate": ninfo.master_candidate,
8176
        }
8177

    
8178
      if not (ninfo.offline or ninfo.drained):
8179
        nresult.Raise("Can't get data for node %s" % nname)
8180
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
8181
                                nname)
8182
        remote_info = nresult.payload
8183

    
8184
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
8185
                     'vg_size', 'vg_free', 'cpu_total']:
8186
          if attr not in remote_info:
8187
            raise errors.OpExecError("Node '%s' didn't return attribute"
8188
                                     " '%s'" % (nname, attr))
8189
          if not isinstance(remote_info[attr], int):
8190
            raise errors.OpExecError("Node '%s' returned invalid value"
8191
                                     " for '%s': %s" %
8192
                                     (nname, attr, remote_info[attr]))
8193
        # compute memory used by primary instances
8194
        i_p_mem = i_p_up_mem = 0
8195
        for iinfo, beinfo in i_list:
8196
          if iinfo.primary_node == nname:
8197
            i_p_mem += beinfo[constants.BE_MEMORY]
8198
            if iinfo.name not in node_iinfo[nname].payload:
8199
              i_used_mem = 0
8200
            else:
8201
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
8202
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
8203
            remote_info['memory_free'] -= max(0, i_mem_diff)
8204

    
8205
            if iinfo.admin_up:
8206
              i_p_up_mem += beinfo[constants.BE_MEMORY]
8207

    
8208
        # compute memory used by instances
8209
        pnr_dyn = {
8210
          "total_memory": remote_info['memory_total'],
8211
          "reserved_memory": remote_info['memory_dom0'],
8212
          "free_memory": remote_info['memory_free'],
8213
          "total_disk": remote_info['vg_size'],
8214
          "free_disk": remote_info['vg_free'],
8215
          "total_cpus": remote_info['cpu_total'],
8216
          "i_pri_memory": i_p_mem,
8217
          "i_pri_up_memory": i_p_up_mem,
8218
          }
8219
        pnr.update(pnr_dyn)
8220

    
8221
      node_results[nname] = pnr
8222
    data["nodes"] = node_results
8223

    
8224
    # instance data
8225
    instance_data = {}
8226
    for iinfo, beinfo in i_list:
8227
      nic_data = []
8228
      for nic in iinfo.nics:
8229
        filled_params = objects.FillDict(
8230
            cluster_info.nicparams[constants.PP_DEFAULT],
8231
            nic.nicparams)
8232
        nic_dict = {"mac": nic.mac,
8233
                    "ip": nic.ip,
8234
                    "mode": filled_params[constants.NIC_MODE],
8235
                    "link": filled_params[constants.NIC_LINK],
8236
                   }
8237
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
8238
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
8239
        nic_data.append(nic_dict)
8240
      pir = {
8241
        "tags": list(iinfo.GetTags()),
8242
        "admin_up": iinfo.admin_up,
8243
        "vcpus": beinfo[constants.BE_VCPUS],
8244
        "memory": beinfo[constants.BE_MEMORY],
8245
        "os": iinfo.os,
8246
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
8247
        "nics": nic_data,
8248
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
8249
        "disk_template": iinfo.disk_template,
8250
        "hypervisor": iinfo.hypervisor,
8251
        }
8252
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
8253
                                                 pir["disks"])
8254
      instance_data[iinfo.name] = pir
8255

    
8256
    data["instances"] = instance_data
8257

    
8258
    self.in_data = data
8259

    
8260
  def _AddNewInstance(self):
8261
    """Add new instance data to allocator structure.
8262

8263
    This in combination with _AllocatorGetClusterData will create the
8264
    correct structure needed as input for the allocator.
8265

8266
    The checks for the completeness of the opcode must have already been
8267
    done.
8268

8269
    """
8270
    data = self.in_data
8271

    
8272
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
8273

    
8274
    if self.disk_template in constants.DTS_NET_MIRROR:
8275
      self.required_nodes = 2
8276
    else:
8277
      self.required_nodes = 1
8278
    request = {
8279
      "type": "allocate",
8280
      "name": self.name,
8281
      "disk_template": self.disk_template,
8282
      "tags": self.tags,
8283
      "os": self.os,
8284
      "vcpus": self.vcpus,
8285
      "memory": self.mem_size,
8286
      "disks": self.disks,
8287
      "disk_space_total": disk_space,
8288
      "nics": self.nics,
8289
      "required_nodes": self.required_nodes,
8290
      }
8291
    data["request"] = request
8292

    
8293
  def _AddRelocateInstance(self):
8294
    """Add relocate instance data to allocator structure.
8295

8296
    This in combination with _IAllocatorGetClusterData will create the
8297
    correct structure needed as input for the allocator.
8298

8299
    The checks for the completeness of the opcode must have already been
8300
    done.
8301

8302
    """
8303
    instance = self.cfg.GetInstanceInfo(self.name)
8304
    if instance is None:
8305
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
8306
                                   " IAllocator" % self.name)
8307

    
8308
    if instance.disk_template not in constants.DTS_NET_MIRROR:
8309
      raise errors.OpPrereqError("Can't relocate non-mirrored instances")
8310

    
8311
    if len(instance.secondary_nodes) != 1:
8312
      raise errors.OpPrereqError("Instance has not exactly one secondary node")
8313

    
8314
    self.required_nodes = 1
8315
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
8316
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
8317

    
8318
    request = {
8319
      "type": "relocate",
8320
      "name": self.name,
8321
      "disk_space_total": disk_space,
8322
      "required_nodes": self.required_nodes,
8323
      "relocate_from": self.relocate_from,
8324
      }
8325
    self.in_data["request"] = request
8326

    
8327
  def _BuildInputData(self):
8328
    """Build input data structures.
8329

8330
    """
8331
    self._ComputeClusterData()
8332

    
8333
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
8334
      self._AddNewInstance()
8335
    else:
8336
      self._AddRelocateInstance()
8337

    
8338
    self.in_text = serializer.Dump(self.in_data)
8339

    
8340
  def Run(self, name, validate=True, call_fn=None):
8341
    """Run an instance allocator and return the results.
8342

8343
    """
8344
    if call_fn is None:
8345
      call_fn = self.rpc.call_iallocator_runner
8346

    
8347
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
8348
    result.Raise("Failure while running the iallocator script")
8349

    
8350
    self.out_text = result.payload
8351
    if validate:
8352
      self._ValidateResult()
8353

    
8354
  def _ValidateResult(self):
8355
    """Process the allocator results.
8356

8357
    This will process and if successful save the result in
8358
    self.out_data and the other parameters.
8359

8360
    """
8361
    try:
8362
      rdict = serializer.Load(self.out_text)
8363
    except Exception, err:
8364
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
8365

    
8366
    if not isinstance(rdict, dict):
8367
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
8368

    
8369
    for key in "success", "info", "nodes":
8370
      if key not in rdict:
8371
        raise errors.OpExecError("Can't parse iallocator results:"
8372
                                 " missing key '%s'" % key)
8373
      setattr(self, key, rdict[key])
8374

    
8375
    if not isinstance(rdict["nodes"], list):
8376
      raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
8377
                               " is not a list")
8378
    self.out_data = rdict
8379

    
8380

    
8381
class LUTestAllocator(NoHooksLU):
8382
  """Run allocator tests.
8383

8384
  This LU runs the allocator tests
8385

8386
  """
8387
  _OP_REQP = ["direction", "mode", "name"]
8388

    
8389
  def CheckPrereq(self):
8390
    """Check prerequisites.
8391

8392
    This checks the opcode parameters depending on the director and mode test.
8393

8394
    """
8395
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
8396
      for attr in ["name", "mem_size", "disks", "disk_template",
8397
                   "os", "tags", "nics", "vcpus"]:
8398
        if not hasattr(self.op, attr):
8399
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
8400
                                     attr)
8401
      iname = self.cfg.ExpandInstanceName(self.op.name)
8402
      if iname is not None:
8403
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
8404
                                   iname)
8405
      if not isinstance(self.op.nics, list):
8406
        raise errors.OpPrereqError("Invalid parameter 'nics'")
8407
      for row in self.op.nics:
8408
        if (not isinstance(row, dict) or
8409
            "mac" not in row or
8410
            "ip" not in row or
8411
            "bridge" not in row):
8412
          raise errors.OpPrereqError("Invalid contents of the"
8413
                                     " 'nics' parameter")
8414
      if not isinstance(self.op.disks, list):
8415
        raise errors.OpPrereqError("Invalid parameter 'disks'")
8416
      for row in self.op.disks:
8417
        if (not isinstance(row, dict) or
8418
            "size" not in row or
8419
            not isinstance(row["size"], int) or
8420
            "mode" not in row or
8421
            row["mode"] not in ['r', 'w']):
8422
          raise errors.OpPrereqError("Invalid contents of the"
8423
                                     " 'disks' parameter")
8424
      if not hasattr(self.op, "hypervisor") or self.op.hypervisor is None:
8425
        self.op.hypervisor = self.cfg.GetHypervisorType()
8426
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
8427
      if not hasattr(self.op, "name"):
8428
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input")
8429
      fname = self.cfg.ExpandInstanceName(self.op.name)
8430
      if fname is None:
8431
        raise errors.OpPrereqError("Instance '%s' not found for relocation" %
8432
                                   self.op.name)
8433
      self.op.name = fname
8434
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
8435
    else:
8436
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
8437
                                 self.op.mode)
8438

    
8439
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
8440
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
8441
        raise errors.OpPrereqError("Missing allocator name")
8442
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
8443
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
8444
                                 self.op.direction)
8445

    
8446
  def Exec(self, feedback_fn):
8447
    """Run the allocator test.
8448

8449
    """
8450
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
8451
      ial = IAllocator(self.cfg, self.rpc,
8452
                       mode=self.op.mode,
8453
                       name=self.op.name,
8454
                       mem_size=self.op.mem_size,
8455
                       disks=self.op.disks,
8456
                       disk_template=self.op.disk_template,
8457
                       os=self.op.os,
8458
                       tags=self.op.tags,
8459
                       nics=self.op.nics,
8460
                       vcpus=self.op.vcpus,
8461
                       hypervisor=self.op.hypervisor,
8462
                       )
8463
    else:
8464
      ial = IAllocator(self.cfg, self.rpc,
8465
                       mode=self.op.mode,
8466
                       name=self.op.name,
8467
                       relocate_from=list(self.relocate_from),
8468
                       )
8469

    
8470
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
8471
      result = ial.in_text
8472
    else:
8473
      ial.Run(self.op.allocator, validate=False)
8474
      result = ial.out_text
8475
    return result