Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 9af0fa6a

History | View | Annotate | Download (313.3 kB)

1
#
2
#
3

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

    
21

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

    
24
# pylint: disable-msg=W0201
25

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

    
29
import os
30
import os.path
31
import time
32
import re
33
import platform
34
import logging
35
import copy
36

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

    
47

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

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

60
  Note that all commands require root permissions.
61

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

65
  """
66
  HPATH = None
67
  HTYPE = None
68
  _OP_REQP = []
69
  REQ_BGL = True
70

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

74
    This needs to be overridden in derived classes in order to check op
75
    validity.
76

77
    """
78
    self.proc = processor
79
    self.op = op
80
    self.cfg = context.cfg
81
    self.context = context
82
    self.rpc = rpc
83
    # Dicts used to declare locking needs to mcpu
84
    self.needed_locks = None
85
    self.acquired_locks = {}
86
    self.share_locks = dict.fromkeys(locking.LEVELS, 0)
87
    self.add_locks = {}
88
    self.remove_locks = {}
89
    # Used to force good behavior when calling helper functions
90
    self.recalculate_locks = {}
91
    self.__ssh = None
92
    # logging
93
    self.LogWarning = processor.LogWarning # pylint: disable-msg=C0103
94
    self.LogInfo = processor.LogInfo # pylint: disable-msg=C0103
95
    self.LogStep = processor.LogStep # pylint: disable-msg=C0103
96
    # support for dry-run
97
    self.dry_run_result = None
98
    # support for generic debug attribute
99
    if (not hasattr(self.op, "debug_level") or
100
        not isinstance(self.op.debug_level, int)):
101
      self.op.debug_level = 0
102

    
103
    # Tasklets
104
    self.tasklets = None
105

    
106
    for attr_name in self._OP_REQP:
107
      attr_val = getattr(op, attr_name, None)
108
      if attr_val is None:
109
        raise errors.OpPrereqError("Required parameter '%s' missing" %
110
                                   attr_name, errors.ECODE_INVAL)
111

    
112
    self.CheckArguments()
113

    
114
  def __GetSSH(self):
115
    """Returns the SshRunner object
116

117
    """
118
    if not self.__ssh:
119
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
120
    return self.__ssh
121

    
122
  ssh = property(fget=__GetSSH)
123

    
124
  def CheckArguments(self):
125
    """Check syntactic validity for the opcode arguments.
126

127
    This method is for doing a simple syntactic check and ensure
128
    validity of opcode parameters, without any cluster-related
129
    checks. While the same can be accomplished in ExpandNames and/or
130
    CheckPrereq, doing these separate is better because:
131

132
      - ExpandNames is left as as purely a lock-related function
133
      - CheckPrereq is run after we have acquired locks (and possible
134
        waited for them)
135

136
    The function is allowed to change the self.op attribute so that
137
    later methods can no longer worry about missing parameters.
138

139
    """
140
    pass
141

    
142
  def ExpandNames(self):
143
    """Expand names for this LU.
144

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

150
    LUs which implement this method must also populate the self.needed_locks
151
    member, as a dict with lock levels as keys, and a list of needed lock names
152
    as values. Rules:
153

154
      - use an empty dict if you don't need any lock
155
      - if you don't need any lock at a particular level omit that level
156
      - don't put anything for the BGL level
157
      - if you want all locks at a level use locking.ALL_SET as a value
158

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

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

167
    Examples::
168

169
      # Acquire all nodes and one instance
170
      self.needed_locks = {
171
        locking.LEVEL_NODE: locking.ALL_SET,
172
        locking.LEVEL_INSTANCE: ['instance1.example.tld'],
173
      }
174
      # Acquire just two nodes
175
      self.needed_locks = {
176
        locking.LEVEL_NODE: ['node1.example.tld', 'node2.example.tld'],
177
      }
178
      # Acquire no locks
179
      self.needed_locks = {} # No, you can't leave it to the default value None
180

181
    """
182
    # The implementation of this method is mandatory only if the new LU is
183
    # concurrent, so that old LUs don't need to be changed all at the same
184
    # time.
185
    if self.REQ_BGL:
186
      self.needed_locks = {} # Exclusive LUs don't need locks.
187
    else:
188
      raise NotImplementedError
189

    
190
  def DeclareLocks(self, level):
191
    """Declare LU locking needs for a level
192

193
    While most LUs can just declare their locking needs at ExpandNames time,
194
    sometimes there's the need to calculate some locks after having acquired
195
    the ones before. This function is called just before acquiring locks at a
196
    particular level, but after acquiring the ones at lower levels, and permits
197
    such calculations. It can be used to modify self.needed_locks, and by
198
    default it does nothing.
199

200
    This function is only called if you have something already set in
201
    self.needed_locks for the level.
202

203
    @param level: Locking level which is going to be locked
204
    @type level: member of ganeti.locking.LEVELS
205

206
    """
207

    
208
  def CheckPrereq(self):
209
    """Check prerequisites for this LU.
210

211
    This method should check that the prerequisites for the execution
212
    of this LU are fulfilled. It can do internode communication, but
213
    it should be idempotent - no cluster or system changes are
214
    allowed.
215

216
    The method should raise errors.OpPrereqError in case something is
217
    not fulfilled. Its return value is ignored.
218

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

222
    """
223
    if self.tasklets is not None:
224
      for (idx, tl) in enumerate(self.tasklets):
225
        logging.debug("Checking prerequisites for tasklet %s/%s",
226
                      idx + 1, len(self.tasklets))
227
        tl.CheckPrereq()
228
    else:
229
      raise NotImplementedError
230

    
231
  def Exec(self, feedback_fn):
232
    """Execute the LU.
233

234
    This method should implement the actual work. It should raise
235
    errors.OpExecError for failures that are somewhat dealt with in
236
    code, or expected.
237

238
    """
239
    if self.tasklets is not None:
240
      for (idx, tl) in enumerate(self.tasklets):
241
        logging.debug("Executing tasklet %s/%s", idx + 1, len(self.tasklets))
242
        tl.Exec(feedback_fn)
243
    else:
244
      raise NotImplementedError
245

    
246
  def BuildHooksEnv(self):
247
    """Build hooks environment for this LU.
248

249
    This method should return a three-node tuple consisting of: a dict
250
    containing the environment that will be used for running the
251
    specific hook for this LU, a list of node names on which the hook
252
    should run before the execution, and a list of node names on which
253
    the hook should run after the execution.
254

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

260
    No nodes should be returned as an empty list (and not None).
261

262
    Note that if the HPATH for a LU class is None, this function will
263
    not be called.
264

265
    """
266
    raise NotImplementedError
267

    
268
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
269
    """Notify the LU about the results of its hooks.
270

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

277
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
278
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
279
    @param hook_results: the results of the multi-node hooks rpc call
280
    @param feedback_fn: function used send feedback back to the caller
281
    @param lu_result: the previous Exec result this LU had, or None
282
        in the PRE phase
283
    @return: the new Exec result, based on the previous result
284
        and hook results
285

286
    """
287
    # API must be kept, thus we ignore the unused argument and could
288
    # be a function warnings
289
    # pylint: disable-msg=W0613,R0201
290
    return lu_result
291

    
292
  def _ExpandAndLockInstance(self):
293
    """Helper function to expand and lock an instance.
294

295
    Many LUs that work on an instance take its name in self.op.instance_name
296
    and need to expand it and then declare the expanded name for locking. This
297
    function does it, and then updates self.op.instance_name to the expanded
298
    name. It also initializes needed_locks as a dict, if this hasn't been done
299
    before.
300

301
    """
302
    if self.needed_locks is None:
303
      self.needed_locks = {}
304
    else:
305
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
306
        "_ExpandAndLockInstance called with instance-level locks set"
307
    expanded_name = self.cfg.ExpandInstanceName(self.op.instance_name)
308
    if expanded_name is None:
309
      raise errors.OpPrereqError("Instance '%s' not known" %
310
                                 self.op.instance_name, errors.ECODE_NOENT)
311
    self.needed_locks[locking.LEVEL_INSTANCE] = expanded_name
312
    self.op.instance_name = expanded_name
313

    
314
  def _LockInstancesNodes(self, primary_only=False):
315
    """Helper function to declare instances' nodes for locking.
316

317
    This function should be called after locking one or more instances to lock
318
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
319
    with all primary or secondary nodes for instances already locked and
320
    present in self.needed_locks[locking.LEVEL_INSTANCE].
321

322
    It should be called from DeclareLocks, and for safety only works if
323
    self.recalculate_locks[locking.LEVEL_NODE] is set.
324

325
    In the future it may grow parameters to just lock some instance's nodes, or
326
    to just lock primaries or secondary nodes, if needed.
327

328
    If should be called in DeclareLocks in a way similar to::
329

330
      if level == locking.LEVEL_NODE:
331
        self._LockInstancesNodes()
332

333
    @type primary_only: boolean
334
    @param primary_only: only lock primary nodes of locked instances
335

336
    """
337
    assert locking.LEVEL_NODE in self.recalculate_locks, \
338
      "_LockInstancesNodes helper function called with no nodes to recalculate"
339

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

    
342
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
343
    # future we might want to have different behaviors depending on the value
344
    # of self.recalculate_locks[locking.LEVEL_NODE]
345
    wanted_nodes = []
346
    for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
347
      instance = self.context.cfg.GetInstanceInfo(instance_name)
348
      wanted_nodes.append(instance.primary_node)
349
      if not primary_only:
350
        wanted_nodes.extend(instance.secondary_nodes)
351

    
352
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
353
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
354
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
355
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
356

    
357
    del self.recalculate_locks[locking.LEVEL_NODE]
358

    
359

    
360
class NoHooksLU(LogicalUnit): # pylint: disable-msg=W0223
361
  """Simple LU which runs no hooks.
362

363
  This LU is intended as a parent for other LogicalUnits which will
364
  run no hooks, in order to reduce duplicate code.
365

366
  """
367
  HPATH = None
368
  HTYPE = None
369

    
370
  def BuildHooksEnv(self):
371
    """Empty BuildHooksEnv for NoHooksLu.
372

373
    This just raises an error.
374

375
    """
376
    assert False, "BuildHooksEnv called for NoHooksLUs"
377

    
378

    
379
class Tasklet:
380
  """Tasklet base class.
381

382
  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
383
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
384
  tasklets know nothing about locks.
385

386
  Subclasses must follow these rules:
387
    - Implement CheckPrereq
388
    - Implement Exec
389

390
  """
391
  def __init__(self, lu):
392
    self.lu = lu
393

    
394
    # Shortcuts
395
    self.cfg = lu.cfg
396
    self.rpc = lu.rpc
397

    
398
  def CheckPrereq(self):
399
    """Check prerequisites for this tasklets.
400

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

405
    The method should raise errors.OpPrereqError in case something is not
406
    fulfilled. Its return value is ignored.
407

408
    This method should also update all parameters to their canonical form if it
409
    hasn't been done before.
410

411
    """
412
    raise NotImplementedError
413

    
414
  def Exec(self, feedback_fn):
415
    """Execute the tasklet.
416

417
    This method should implement the actual work. It should raise
418
    errors.OpExecError for failures that are somewhat dealt with in code, or
419
    expected.
420

421
    """
422
    raise NotImplementedError
423

    
424

    
425
def _GetWantedNodes(lu, nodes):
426
  """Returns list of checked and expanded node names.
427

428
  @type lu: L{LogicalUnit}
429
  @param lu: the logical unit on whose behalf we execute
430
  @type nodes: list
431
  @param nodes: list of node names or None for all nodes
432
  @rtype: list
433
  @return: the list of nodes, sorted
434
  @raise errors.OpProgrammerError: if the nodes parameter is wrong type
435

436
  """
437
  if not isinstance(nodes, list):
438
    raise errors.OpPrereqError("Invalid argument type 'nodes'",
439
                               errors.ECODE_INVAL)
440

    
441
  if not nodes:
442
    raise errors.ProgrammerError("_GetWantedNodes should only be called with a"
443
      " non-empty list of nodes whose name is to be expanded.")
444

    
445
  wanted = []
446
  for name in nodes:
447
    node = lu.cfg.ExpandNodeName(name)
448
    if node is None:
449
      raise errors.OpPrereqError("No such node name '%s'" % name,
450
                                 errors.ECODE_NOENT)
451
    wanted.append(node)
452

    
453
  return utils.NiceSort(wanted)
454

    
455

    
456
def _GetWantedInstances(lu, instances):
457
  """Returns list of checked and expanded instance names.
458

459
  @type lu: L{LogicalUnit}
460
  @param lu: the logical unit on whose behalf we execute
461
  @type instances: list
462
  @param instances: list of instance names or None for all instances
463
  @rtype: list
464
  @return: the list of instances, sorted
465
  @raise errors.OpPrereqError: if the instances parameter is wrong type
466
  @raise errors.OpPrereqError: if any of the passed instances is not found
467

468
  """
469
  if not isinstance(instances, list):
470
    raise errors.OpPrereqError("Invalid argument type 'instances'",
471
                               errors.ECODE_INVAL)
472

    
473
  if instances:
474
    wanted = []
475

    
476
    for name in instances:
477
      instance = lu.cfg.ExpandInstanceName(name)
478
      if instance is None:
479
        raise errors.OpPrereqError("No such instance name '%s'" % name,
480
                                   errors.ECODE_NOENT)
481
      wanted.append(instance)
482

    
483
  else:
484
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
485
  return wanted
486

    
487

    
488
def _CheckOutputFields(static, dynamic, selected):
489
  """Checks whether all selected fields are valid.
490

491
  @type static: L{utils.FieldSet}
492
  @param static: static fields set
493
  @type dynamic: L{utils.FieldSet}
494
  @param dynamic: dynamic fields set
495

496
  """
497
  f = utils.FieldSet()
498
  f.Extend(static)
499
  f.Extend(dynamic)
500

    
501
  delta = f.NonMatching(selected)
502
  if delta:
503
    raise errors.OpPrereqError("Unknown output fields selected: %s"
504
                               % ",".join(delta), errors.ECODE_INVAL)
505

    
506

    
507
def _CheckBooleanOpField(op, name):
508
  """Validates boolean opcode parameters.
509

510
  This will ensure that an opcode parameter is either a boolean value,
511
  or None (but that it always exists).
512

513
  """
514
  val = getattr(op, name, None)
515
  if not (val is None or isinstance(val, bool)):
516
    raise errors.OpPrereqError("Invalid boolean parameter '%s' (%s)" %
517
                               (name, str(val)), errors.ECODE_INVAL)
518
  setattr(op, name, val)
519

    
520

    
521
def _CheckGlobalHvParams(params):
522
  """Validates that given hypervisor params are not global ones.
523

524
  This will ensure that instances don't get customised versions of
525
  global params.
526

527
  """
528
  used_globals = constants.HVC_GLOBALS.intersection(params)
529
  if used_globals:
530
    msg = ("The following hypervisor parameters are global and cannot"
531
           " be customized at instance level, please modify them at"
532
           " cluster level: %s" % utils.CommaJoin(used_globals))
533
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
534

    
535

    
536
def _CheckNodeOnline(lu, node):
537
  """Ensure that a given node is online.
538

539
  @param lu: the LU on behalf of which we make the check
540
  @param node: the node to check
541
  @raise errors.OpPrereqError: if the node is offline
542

543
  """
544
  if lu.cfg.GetNodeInfo(node).offline:
545
    raise errors.OpPrereqError("Can't use offline node %s" % node,
546
                               errors.ECODE_INVAL)
547

    
548

    
549
def _CheckNodeNotDrained(lu, node):
550
  """Ensure that a given node is not drained.
551

552
  @param lu: the LU on behalf of which we make the check
553
  @param node: the node to check
554
  @raise errors.OpPrereqError: if the node is drained
555

556
  """
557
  if lu.cfg.GetNodeInfo(node).drained:
558
    raise errors.OpPrereqError("Can't use drained node %s" % node,
559
                               errors.ECODE_INVAL)
560

    
561

    
562
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
563
                          memory, vcpus, nics, disk_template, disks,
564
                          bep, hvp, hypervisor_name):
565
  """Builds instance related env variables for hooks
566

567
  This builds the hook environment from individual variables.
568

569
  @type name: string
570
  @param name: the name of the instance
571
  @type primary_node: string
572
  @param primary_node: the name of the instance's primary node
573
  @type secondary_nodes: list
574
  @param secondary_nodes: list of secondary nodes as strings
575
  @type os_type: string
576
  @param os_type: the name of the instance's OS
577
  @type status: boolean
578
  @param status: the should_run status of the instance
579
  @type memory: string
580
  @param memory: the memory size of the instance
581
  @type vcpus: string
582
  @param vcpus: the count of VCPUs the instance has
583
  @type nics: list
584
  @param nics: list of tuples (ip, mac, mode, link) representing
585
      the NICs the instance has
586
  @type disk_template: string
587
  @param disk_template: the disk template of the instance
588
  @type disks: list
589
  @param disks: the list of (size, mode) pairs
590
  @type bep: dict
591
  @param bep: the backend parameters for the instance
592
  @type hvp: dict
593
  @param hvp: the hypervisor parameters for the instance
594
  @type hypervisor_name: string
595
  @param hypervisor_name: the hypervisor for the instance
596
  @rtype: dict
597
  @return: the hook environment for this instance
598

599
  """
600
  if status:
601
    str_status = "up"
602
  else:
603
    str_status = "down"
604
  env = {
605
    "OP_TARGET": name,
606
    "INSTANCE_NAME": name,
607
    "INSTANCE_PRIMARY": primary_node,
608
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
609
    "INSTANCE_OS_TYPE": os_type,
610
    "INSTANCE_STATUS": str_status,
611
    "INSTANCE_MEMORY": memory,
612
    "INSTANCE_VCPUS": vcpus,
613
    "INSTANCE_DISK_TEMPLATE": disk_template,
614
    "INSTANCE_HYPERVISOR": hypervisor_name,
615
  }
616

    
617
  if nics:
618
    nic_count = len(nics)
619
    for idx, (ip, mac, mode, link) in enumerate(nics):
620
      if ip is None:
621
        ip = ""
622
      env["INSTANCE_NIC%d_IP" % idx] = ip
623
      env["INSTANCE_NIC%d_MAC" % idx] = mac
624
      env["INSTANCE_NIC%d_MODE" % idx] = mode
625
      env["INSTANCE_NIC%d_LINK" % idx] = link
626
      if mode == constants.NIC_MODE_BRIDGED:
627
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
628
  else:
629
    nic_count = 0
630

    
631
  env["INSTANCE_NIC_COUNT"] = nic_count
632

    
633
  if disks:
634
    disk_count = len(disks)
635
    for idx, (size, mode) in enumerate(disks):
636
      env["INSTANCE_DISK%d_SIZE" % idx] = size
637
      env["INSTANCE_DISK%d_MODE" % idx] = mode
638
  else:
639
    disk_count = 0
640

    
641
  env["INSTANCE_DISK_COUNT"] = disk_count
642

    
643
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
644
    for key, value in source.items():
645
      env["INSTANCE_%s_%s" % (kind, key)] = value
646

    
647
  return env
648

    
649

    
650
def _NICListToTuple(lu, nics):
651
  """Build a list of nic information tuples.
652

653
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
654
  value in LUQueryInstanceData.
655

656
  @type lu:  L{LogicalUnit}
657
  @param lu: the logical unit on whose behalf we execute
658
  @type nics: list of L{objects.NIC}
659
  @param nics: list of nics to convert to hooks tuples
660

661
  """
662
  hooks_nics = []
663
  c_nicparams = lu.cfg.GetClusterInfo().nicparams[constants.PP_DEFAULT]
664
  for nic in nics:
665
    ip = nic.ip
666
    mac = nic.mac
667
    filled_params = objects.FillDict(c_nicparams, nic.nicparams)
668
    mode = filled_params[constants.NIC_MODE]
669
    link = filled_params[constants.NIC_LINK]
670
    hooks_nics.append((ip, mac, mode, link))
671
  return hooks_nics
672

    
673

    
674
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
675
  """Builds instance related env variables for hooks from an object.
676

677
  @type lu: L{LogicalUnit}
678
  @param lu: the logical unit on whose behalf we execute
679
  @type instance: L{objects.Instance}
680
  @param instance: the instance for which we should build the
681
      environment
682
  @type override: dict
683
  @param override: dictionary with key/values that will override
684
      our values
685
  @rtype: dict
686
  @return: the hook environment dictionary
687

688
  """
689
  cluster = lu.cfg.GetClusterInfo()
690
  bep = cluster.FillBE(instance)
691
  hvp = cluster.FillHV(instance)
692
  args = {
693
    'name': instance.name,
694
    'primary_node': instance.primary_node,
695
    'secondary_nodes': instance.secondary_nodes,
696
    'os_type': instance.os,
697
    'status': instance.admin_up,
698
    'memory': bep[constants.BE_MEMORY],
699
    'vcpus': bep[constants.BE_VCPUS],
700
    'nics': _NICListToTuple(lu, instance.nics),
701
    'disk_template': instance.disk_template,
702
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
703
    'bep': bep,
704
    'hvp': hvp,
705
    'hypervisor_name': instance.hypervisor,
706
  }
707
  if override:
708
    args.update(override)
709
  return _BuildInstanceHookEnv(**args) # pylint: disable-msg=W0142
710

    
711

    
712
def _AdjustCandidatePool(lu, exceptions):
713
  """Adjust the candidate pool after node operations.
714

715
  """
716
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
717
  if mod_list:
718
    lu.LogInfo("Promoted nodes to master candidate role: %s",
719
               utils.CommaJoin(node.name for node in mod_list))
720
    for name in mod_list:
721
      lu.context.ReaddNode(name)
722
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
723
  if mc_now > mc_max:
724
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
725
               (mc_now, mc_max))
726

    
727

    
728
def _DecideSelfPromotion(lu, exceptions=None):
729
  """Decide whether I should promote myself as a master candidate.
730

731
  """
732
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
733
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
734
  # the new node will increase mc_max with one, so:
735
  mc_should = min(mc_should + 1, cp_size)
736
  return mc_now < mc_should
737

    
738

    
739
def _CheckNicsBridgesExist(lu, target_nics, target_node,
740
                               profile=constants.PP_DEFAULT):
741
  """Check that the brigdes needed by a list of nics exist.
742

743
  """
744
  c_nicparams = lu.cfg.GetClusterInfo().nicparams[profile]
745
  paramslist = [objects.FillDict(c_nicparams, nic.nicparams)
746
                for nic in target_nics]
747
  brlist = [params[constants.NIC_LINK] for params in paramslist
748
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
749
  if brlist:
750
    result = lu.rpc.call_bridges_exist(target_node, brlist)
751
    result.Raise("Error checking bridges on destination node '%s'" %
752
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
753

    
754

    
755
def _CheckInstanceBridgesExist(lu, instance, node=None):
756
  """Check that the brigdes needed by an instance exist.
757

758
  """
759
  if node is None:
760
    node = instance.primary_node
761
  _CheckNicsBridgesExist(lu, instance.nics, node)
762

    
763

    
764
def _CheckOSVariant(os_obj, name):
765
  """Check whether an OS name conforms to the os variants specification.
766

767
  @type os_obj: L{objects.OS}
768
  @param os_obj: OS object to check
769
  @type name: string
770
  @param name: OS name passed by the user, to check for validity
771

772
  """
773
  if not os_obj.supported_variants:
774
    return
775
  try:
776
    variant = name.split("+", 1)[1]
777
  except IndexError:
778
    raise errors.OpPrereqError("OS name must include a variant",
779
                               errors.ECODE_INVAL)
780

    
781
  if variant not in os_obj.supported_variants:
782
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
783

    
784

    
785
def _GetNodeInstancesInner(cfg, fn):
786
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
787

    
788

    
789
def _GetNodeInstances(cfg, node_name):
790
  """Returns a list of all primary and secondary instances on a node.
791

792
  """
793

    
794
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
795

    
796

    
797
def _GetNodePrimaryInstances(cfg, node_name):
798
  """Returns primary instances on a node.
799

800
  """
801
  return _GetNodeInstancesInner(cfg,
802
                                lambda inst: node_name == inst.primary_node)
803

    
804

    
805
def _GetNodeSecondaryInstances(cfg, node_name):
806
  """Returns secondary instances on a node.
807

808
  """
809
  return _GetNodeInstancesInner(cfg,
810
                                lambda inst: node_name in inst.secondary_nodes)
811

    
812

    
813
def _GetStorageTypeArgs(cfg, storage_type):
814
  """Returns the arguments for a storage type.
815

816
  """
817
  # Special case for file storage
818
  if storage_type == constants.ST_FILE:
819
    # storage.FileStorage wants a list of storage directories
820
    return [[cfg.GetFileStorageDir()]]
821

    
822
  return []
823

    
824

    
825
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
826
  faulty = []
827

    
828
  for dev in instance.disks:
829
    cfg.SetDiskID(dev, node_name)
830

    
831
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
832
  result.Raise("Failed to get disk status from node %s" % node_name,
833
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
834

    
835
  for idx, bdev_status in enumerate(result.payload):
836
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
837
      faulty.append(idx)
838

    
839
  return faulty
840

    
841

    
842
class LUPostInitCluster(LogicalUnit):
843
  """Logical unit for running hooks after cluster initialization.
844

845
  """
846
  HPATH = "cluster-init"
847
  HTYPE = constants.HTYPE_CLUSTER
848
  _OP_REQP = []
849

    
850
  def BuildHooksEnv(self):
851
    """Build hooks env.
852

853
    """
854
    env = {"OP_TARGET": self.cfg.GetClusterName()}
855
    mn = self.cfg.GetMasterNode()
856
    return env, [], [mn]
857

    
858
  def CheckPrereq(self):
859
    """No prerequisites to check.
860

861
    """
862
    return True
863

    
864
  def Exec(self, feedback_fn):
865
    """Nothing to do.
866

867
    """
868
    return True
869

    
870

    
871
class LUDestroyCluster(LogicalUnit):
872
  """Logical unit for destroying the cluster.
873

874
  """
875
  HPATH = "cluster-destroy"
876
  HTYPE = constants.HTYPE_CLUSTER
877
  _OP_REQP = []
878

    
879
  def BuildHooksEnv(self):
880
    """Build hooks env.
881

882
    """
883
    env = {"OP_TARGET": self.cfg.GetClusterName()}
884
    return env, [], []
885

    
886
  def CheckPrereq(self):
887
    """Check prerequisites.
888

889
    This checks whether the cluster is empty.
890

891
    Any errors are signaled by raising errors.OpPrereqError.
892

893
    """
894
    master = self.cfg.GetMasterNode()
895

    
896
    nodelist = self.cfg.GetNodeList()
897
    if len(nodelist) != 1 or nodelist[0] != master:
898
      raise errors.OpPrereqError("There are still %d node(s) in"
899
                                 " this cluster." % (len(nodelist) - 1),
900
                                 errors.ECODE_INVAL)
901
    instancelist = self.cfg.GetInstanceList()
902
    if instancelist:
903
      raise errors.OpPrereqError("There are still %d instance(s) in"
904
                                 " this cluster." % len(instancelist),
905
                                 errors.ECODE_INVAL)
906

    
907
  def Exec(self, feedback_fn):
908
    """Destroys the cluster.
909

910
    """
911
    master = self.cfg.GetMasterNode()
912
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
913

    
914
    # Run post hooks on master node before it's removed
915
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
916
    try:
917
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
918
    except:
919
      # pylint: disable-msg=W0702
920
      self.LogWarning("Errors occurred running hooks on %s" % master)
921

    
922
    result = self.rpc.call_node_stop_master(master, False)
923
    result.Raise("Could not disable the master role")
924

    
925
    if modify_ssh_setup:
926
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
927
      utils.CreateBackup(priv_key)
928
      utils.CreateBackup(pub_key)
929

    
930
    return master
931

    
932

    
933
class LUVerifyCluster(LogicalUnit):
934
  """Verifies the cluster status.
935

936
  """
937
  HPATH = "cluster-verify"
938
  HTYPE = constants.HTYPE_CLUSTER
939
  _OP_REQP = ["skip_checks", "verbose", "error_codes", "debug_simulate_errors"]
940
  REQ_BGL = False
941

    
942
  TCLUSTER = "cluster"
943
  TNODE = "node"
944
  TINSTANCE = "instance"
945

    
946
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
947
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
948
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
949
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
950
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
951
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
952
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
953
  ENODEDRBD = (TNODE, "ENODEDRBD")
954
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
955
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
956
  ENODEHV = (TNODE, "ENODEHV")
957
  ENODELVM = (TNODE, "ENODELVM")
958
  ENODEN1 = (TNODE, "ENODEN1")
959
  ENODENET = (TNODE, "ENODENET")
960
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
961
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
962
  ENODERPC = (TNODE, "ENODERPC")
963
  ENODESSH = (TNODE, "ENODESSH")
964
  ENODEVERSION = (TNODE, "ENODEVERSION")
965
  ENODESETUP = (TNODE, "ENODESETUP")
966
  ENODETIME = (TNODE, "ENODETIME")
967

    
968
  ETYPE_FIELD = "code"
969
  ETYPE_ERROR = "ERROR"
970
  ETYPE_WARNING = "WARNING"
971

    
972
  def ExpandNames(self):
973
    self.needed_locks = {
974
      locking.LEVEL_NODE: locking.ALL_SET,
975
      locking.LEVEL_INSTANCE: locking.ALL_SET,
976
    }
977
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
978

    
979
  def _Error(self, ecode, item, msg, *args, **kwargs):
980
    """Format an error message.
981

982
    Based on the opcode's error_codes parameter, either format a
983
    parseable error code, or a simpler error string.
984

985
    This must be called only from Exec and functions called from Exec.
986

987
    """
988
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
989
    itype, etxt = ecode
990
    # first complete the msg
991
    if args:
992
      msg = msg % args
993
    # then format the whole message
994
    if self.op.error_codes:
995
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
996
    else:
997
      if item:
998
        item = " " + item
999
      else:
1000
        item = ""
1001
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1002
    # and finally report it via the feedback_fn
1003
    self._feedback_fn("  - %s" % msg)
1004

    
1005
  def _ErrorIf(self, cond, *args, **kwargs):
1006
    """Log an error message if the passed condition is True.
1007

1008
    """
1009
    cond = bool(cond) or self.op.debug_simulate_errors
1010
    if cond:
1011
      self._Error(*args, **kwargs)
1012
    # do not mark the operation as failed for WARN cases only
1013
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1014
      self.bad = self.bad or cond
1015

    
1016
  def _VerifyNode(self, nodeinfo, file_list, local_cksum,
1017
                  node_result, master_files, drbd_map, vg_name):
1018
    """Run multiple tests against a node.
1019

1020
    Test list:
1021

1022
      - compares ganeti version
1023
      - checks vg existence and size > 20G
1024
      - checks config file checksum
1025
      - checks ssh to other nodes
1026

1027
    @type nodeinfo: L{objects.Node}
1028
    @param nodeinfo: the node to check
1029
    @param file_list: required list of files
1030
    @param local_cksum: dictionary of local files and their checksums
1031
    @param node_result: the results from the node
1032
    @param master_files: list of files that only masters should have
1033
    @param drbd_map: the useddrbd minors for this node, in
1034
        form of minor: (instance, must_exist) which correspond to instances
1035
        and their running status
1036
    @param vg_name: Ganeti Volume Group (result of self.cfg.GetVGName())
1037

1038
    """
1039
    node = nodeinfo.name
1040
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1041

    
1042
    # main result, node_result should be a non-empty dict
1043
    test = not node_result or not isinstance(node_result, dict)
1044
    _ErrorIf(test, self.ENODERPC, node,
1045
                  "unable to verify node: no data returned")
1046
    if test:
1047
      return
1048

    
1049
    # compares ganeti version
1050
    local_version = constants.PROTOCOL_VERSION
1051
    remote_version = node_result.get('version', None)
1052
    test = not (remote_version and
1053
                isinstance(remote_version, (list, tuple)) and
1054
                len(remote_version) == 2)
1055
    _ErrorIf(test, self.ENODERPC, node,
1056
             "connection to node returned invalid data")
1057
    if test:
1058
      return
1059

    
1060
    test = local_version != remote_version[0]
1061
    _ErrorIf(test, self.ENODEVERSION, node,
1062
             "incompatible protocol versions: master %s,"
1063
             " node %s", local_version, remote_version[0])
1064
    if test:
1065
      return
1066

    
1067
    # node seems compatible, we can actually try to look into its results
1068

    
1069
    # full package version
1070
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1071
                  self.ENODEVERSION, node,
1072
                  "software version mismatch: master %s, node %s",
1073
                  constants.RELEASE_VERSION, remote_version[1],
1074
                  code=self.ETYPE_WARNING)
1075

    
1076
    # checks vg existence and size > 20G
1077
    if vg_name is not None:
1078
      vglist = node_result.get(constants.NV_VGLIST, None)
1079
      test = not vglist
1080
      _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1081
      if not test:
1082
        vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1083
                                              constants.MIN_VG_SIZE)
1084
        _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1085

    
1086
    # checks config file checksum
1087

    
1088
    remote_cksum = node_result.get(constants.NV_FILELIST, None)
1089
    test = not isinstance(remote_cksum, dict)
1090
    _ErrorIf(test, self.ENODEFILECHECK, node,
1091
             "node hasn't returned file checksum data")
1092
    if not test:
1093
      for file_name in file_list:
1094
        node_is_mc = nodeinfo.master_candidate
1095
        must_have = (file_name not in master_files) or node_is_mc
1096
        # missing
1097
        test1 = file_name not in remote_cksum
1098
        # invalid checksum
1099
        test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1100
        # existing and good
1101
        test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1102
        _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1103
                 "file '%s' missing", file_name)
1104
        _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1105
                 "file '%s' has wrong checksum", file_name)
1106
        # not candidate and this is not a must-have file
1107
        _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1108
                 "file '%s' should not exist on non master"
1109
                 " candidates (and the file is outdated)", file_name)
1110
        # all good, except non-master/non-must have combination
1111
        _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1112
                 "file '%s' should not exist"
1113
                 " on non master candidates", file_name)
1114

    
1115
    # checks ssh to any
1116

    
1117
    test = constants.NV_NODELIST not in node_result
1118
    _ErrorIf(test, self.ENODESSH, node,
1119
             "node hasn't returned node ssh connectivity data")
1120
    if not test:
1121
      if node_result[constants.NV_NODELIST]:
1122
        for a_node, a_msg in node_result[constants.NV_NODELIST].items():
1123
          _ErrorIf(True, self.ENODESSH, node,
1124
                   "ssh communication with node '%s': %s", a_node, a_msg)
1125

    
1126
    test = constants.NV_NODENETTEST not in node_result
1127
    _ErrorIf(test, self.ENODENET, node,
1128
             "node hasn't returned node tcp connectivity data")
1129
    if not test:
1130
      if node_result[constants.NV_NODENETTEST]:
1131
        nlist = utils.NiceSort(node_result[constants.NV_NODENETTEST].keys())
1132
        for anode in nlist:
1133
          _ErrorIf(True, self.ENODENET, node,
1134
                   "tcp communication with node '%s': %s",
1135
                   anode, node_result[constants.NV_NODENETTEST][anode])
1136

    
1137
    hyp_result = node_result.get(constants.NV_HYPERVISOR, None)
1138
    if isinstance(hyp_result, dict):
1139
      for hv_name, hv_result in hyp_result.iteritems():
1140
        test = hv_result is not None
1141
        _ErrorIf(test, self.ENODEHV, node,
1142
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1143

    
1144
    # check used drbd list
1145
    if vg_name is not None:
1146
      used_minors = node_result.get(constants.NV_DRBDLIST, [])
1147
      test = not isinstance(used_minors, (tuple, list))
1148
      _ErrorIf(test, self.ENODEDRBD, node,
1149
               "cannot parse drbd status file: %s", str(used_minors))
1150
      if not test:
1151
        for minor, (iname, must_exist) in drbd_map.items():
1152
          test = minor not in used_minors and must_exist
1153
          _ErrorIf(test, self.ENODEDRBD, node,
1154
                   "drbd minor %d of instance %s is not active",
1155
                   minor, iname)
1156
        for minor in used_minors:
1157
          test = minor not in drbd_map
1158
          _ErrorIf(test, self.ENODEDRBD, node,
1159
                   "unallocated drbd minor %d is in use", minor)
1160
    test = node_result.get(constants.NV_NODESETUP,
1161
                           ["Missing NODESETUP results"])
1162
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1163
             "; ".join(test))
1164

    
1165
    # check pv names
1166
    if vg_name is not None:
1167
      pvlist = node_result.get(constants.NV_PVLIST, None)
1168
      test = pvlist is None
1169
      _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1170
      if not test:
1171
        # check that ':' is not present in PV names, since it's a
1172
        # special character for lvcreate (denotes the range of PEs to
1173
        # use on the PV)
1174
        for _, pvname, owner_vg in pvlist:
1175
          test = ":" in pvname
1176
          _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1177
                   " '%s' of VG '%s'", pvname, owner_vg)
1178

    
1179
  def _VerifyInstance(self, instance, instanceconfig, node_vol_is,
1180
                      node_instance, n_offline):
1181
    """Verify an instance.
1182

1183
    This function checks to see if the required block devices are
1184
    available on the instance's node.
1185

1186
    """
1187
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1188
    node_current = instanceconfig.primary_node
1189

    
1190
    node_vol_should = {}
1191
    instanceconfig.MapLVsByNode(node_vol_should)
1192

    
1193
    for node in node_vol_should:
1194
      if node in n_offline:
1195
        # ignore missing volumes on offline nodes
1196
        continue
1197
      for volume in node_vol_should[node]:
1198
        test = node not in node_vol_is or volume not in node_vol_is[node]
1199
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1200
                 "volume %s missing on node %s", volume, node)
1201

    
1202
    if instanceconfig.admin_up:
1203
      test = ((node_current not in node_instance or
1204
               not instance in node_instance[node_current]) and
1205
              node_current not in n_offline)
1206
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1207
               "instance not running on its primary node %s",
1208
               node_current)
1209

    
1210
    for node in node_instance:
1211
      if (not node == node_current):
1212
        test = instance in node_instance[node]
1213
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1214
                 "instance should not run on node %s", node)
1215

    
1216
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is):
1217
    """Verify if there are any unknown volumes in the cluster.
1218

1219
    The .os, .swap and backup volumes are ignored. All other volumes are
1220
    reported as unknown.
1221

1222
    """
1223
    for node in node_vol_is:
1224
      for volume in node_vol_is[node]:
1225
        test = (node not in node_vol_should or
1226
                volume not in node_vol_should[node])
1227
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1228
                      "volume %s is unknown", volume)
1229

    
1230
  def _VerifyOrphanInstances(self, instancelist, node_instance):
1231
    """Verify the list of running instances.
1232

1233
    This checks what instances are running but unknown to the cluster.
1234

1235
    """
1236
    for node in node_instance:
1237
      for o_inst in node_instance[node]:
1238
        test = o_inst not in instancelist
1239
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1240
                      "instance %s on node %s should not exist", o_inst, node)
1241

    
1242
  def _VerifyNPlusOneMemory(self, node_info, instance_cfg):
1243
    """Verify N+1 Memory Resilience.
1244

1245
    Check that if one single node dies we can still start all the instances it
1246
    was primary for.
1247

1248
    """
1249
    for node, nodeinfo in node_info.iteritems():
1250
      # This code checks that every node which is now listed as secondary has
1251
      # enough memory to host all instances it is supposed to should a single
1252
      # other node in the cluster fail.
1253
      # FIXME: not ready for failover to an arbitrary node
1254
      # FIXME: does not support file-backed instances
1255
      # WARNING: we currently take into account down instances as well as up
1256
      # ones, considering that even if they're down someone might want to start
1257
      # them even in the event of a node failure.
1258
      for prinode, instances in nodeinfo['sinst-by-pnode'].iteritems():
1259
        needed_mem = 0
1260
        for instance in instances:
1261
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1262
          if bep[constants.BE_AUTO_BALANCE]:
1263
            needed_mem += bep[constants.BE_MEMORY]
1264
        test = nodeinfo['mfree'] < needed_mem
1265
        self._ErrorIf(test, self.ENODEN1, node,
1266
                      "not enough memory on to accommodate"
1267
                      " failovers should peer node %s fail", prinode)
1268

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

1272
    Transform the list of checks we're going to skip into a set and check that
1273
    all its members are valid.
1274

1275
    """
1276
    self.skip_set = frozenset(self.op.skip_checks)
1277
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
1278
      raise errors.OpPrereqError("Invalid checks to be skipped specified",
1279
                                 errors.ECODE_INVAL)
1280

    
1281
  def BuildHooksEnv(self):
1282
    """Build hooks env.
1283

1284
    Cluster-Verify hooks just ran in the post phase and their failure makes
1285
    the output be logged in the verify output and the verification to fail.
1286

1287
    """
1288
    all_nodes = self.cfg.GetNodeList()
1289
    env = {
1290
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
1291
      }
1292
    for node in self.cfg.GetAllNodesInfo().values():
1293
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
1294

    
1295
    return env, [], all_nodes
1296

    
1297
  def Exec(self, feedback_fn):
1298
    """Verify integrity of cluster, performing various test on nodes.
1299

1300
    """
1301
    self.bad = False
1302
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1303
    verbose = self.op.verbose
1304
    self._feedback_fn = feedback_fn
1305
    feedback_fn("* Verifying global settings")
1306
    for msg in self.cfg.VerifyConfig():
1307
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
1308

    
1309
    vg_name = self.cfg.GetVGName()
1310
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
1311
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
1312
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
1313
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
1314
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
1315
                        for iname in instancelist)
1316
    i_non_redundant = [] # Non redundant instances
1317
    i_non_a_balanced = [] # Non auto-balanced instances
1318
    n_offline = [] # List of offline nodes
1319
    n_drained = [] # List of nodes being drained
1320
    node_volume = {}
1321
    node_instance = {}
1322
    node_info = {}
1323
    instance_cfg = {}
1324

    
1325
    # FIXME: verify OS list
1326
    # do local checksums
1327
    master_files = [constants.CLUSTER_CONF_FILE]
1328

    
1329
    file_names = ssconf.SimpleStore().GetFileList()
1330
    file_names.append(constants.SSL_CERT_FILE)
1331
    file_names.append(constants.RAPI_CERT_FILE)
1332
    file_names.extend(master_files)
1333

    
1334
    local_checksums = utils.FingerprintFiles(file_names)
1335

    
1336
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
1337
    node_verify_param = {
1338
      constants.NV_FILELIST: file_names,
1339
      constants.NV_NODELIST: [node.name for node in nodeinfo
1340
                              if not node.offline],
1341
      constants.NV_HYPERVISOR: hypervisors,
1342
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
1343
                                  node.secondary_ip) for node in nodeinfo
1344
                                 if not node.offline],
1345
      constants.NV_INSTANCELIST: hypervisors,
1346
      constants.NV_VERSION: None,
1347
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
1348
      constants.NV_NODESETUP: None,
1349
      constants.NV_TIME: None,
1350
      }
1351

    
1352
    if vg_name is not None:
1353
      node_verify_param[constants.NV_VGLIST] = None
1354
      node_verify_param[constants.NV_LVLIST] = vg_name
1355
      node_verify_param[constants.NV_PVLIST] = [vg_name]
1356
      node_verify_param[constants.NV_DRBDLIST] = None
1357

    
1358
    # Due to the way our RPC system works, exact response times cannot be
1359
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
1360
    # time before and after executing the request, we can at least have a time
1361
    # window.
1362
    nvinfo_starttime = time.time()
1363
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
1364
                                           self.cfg.GetClusterName())
1365
    nvinfo_endtime = time.time()
1366

    
1367
    cluster = self.cfg.GetClusterInfo()
1368
    master_node = self.cfg.GetMasterNode()
1369
    all_drbd_map = self.cfg.ComputeDRBDMap()
1370

    
1371
    feedback_fn("* Verifying node status")
1372
    for node_i in nodeinfo:
1373
      node = node_i.name
1374

    
1375
      if node_i.offline:
1376
        if verbose:
1377
          feedback_fn("* Skipping offline node %s" % (node,))
1378
        n_offline.append(node)
1379
        continue
1380

    
1381
      if node == master_node:
1382
        ntype = "master"
1383
      elif node_i.master_candidate:
1384
        ntype = "master candidate"
1385
      elif node_i.drained:
1386
        ntype = "drained"
1387
        n_drained.append(node)
1388
      else:
1389
        ntype = "regular"
1390
      if verbose:
1391
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
1392

    
1393
      msg = all_nvinfo[node].fail_msg
1394
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
1395
      if msg:
1396
        continue
1397

    
1398
      nresult = all_nvinfo[node].payload
1399
      node_drbd = {}
1400
      for minor, instance in all_drbd_map[node].items():
1401
        test = instance not in instanceinfo
1402
        _ErrorIf(test, self.ECLUSTERCFG, None,
1403
                 "ghost instance '%s' in temporary DRBD map", instance)
1404
          # ghost instance should not be running, but otherwise we
1405
          # don't give double warnings (both ghost instance and
1406
          # unallocated minor in use)
1407
        if test:
1408
          node_drbd[minor] = (instance, False)
1409
        else:
1410
          instance = instanceinfo[instance]
1411
          node_drbd[minor] = (instance.name, instance.admin_up)
1412

    
1413
      self._VerifyNode(node_i, file_names, local_checksums,
1414
                       nresult, master_files, node_drbd, vg_name)
1415

    
1416
      lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1417
      if vg_name is None:
1418
        node_volume[node] = {}
1419
      elif isinstance(lvdata, basestring):
1420
        _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1421
                 utils.SafeEncode(lvdata))
1422
        node_volume[node] = {}
1423
      elif not isinstance(lvdata, dict):
1424
        _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1425
        continue
1426
      else:
1427
        node_volume[node] = lvdata
1428

    
1429
      # node_instance
1430
      idata = nresult.get(constants.NV_INSTANCELIST, None)
1431
      test = not isinstance(idata, list)
1432
      _ErrorIf(test, self.ENODEHV, node,
1433
               "rpc call to node failed (instancelist)")
1434
      if test:
1435
        continue
1436

    
1437
      node_instance[node] = idata
1438

    
1439
      # node_info
1440
      nodeinfo = nresult.get(constants.NV_HVINFO, None)
1441
      test = not isinstance(nodeinfo, dict)
1442
      _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1443
      if test:
1444
        continue
1445

    
1446
      # Node time
1447
      ntime = nresult.get(constants.NV_TIME, None)
1448
      try:
1449
        ntime_merged = utils.MergeTime(ntime)
1450
      except (ValueError, TypeError):
1451
        _ErrorIf(test, self.ENODETIME, node, "Node returned invalid time")
1452

    
1453
      if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1454
        ntime_diff = abs(nvinfo_starttime - ntime_merged)
1455
      elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1456
        ntime_diff = abs(ntime_merged - nvinfo_endtime)
1457
      else:
1458
        ntime_diff = None
1459

    
1460
      _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1461
               "Node time diverges by at least %0.1fs from master node time",
1462
               ntime_diff)
1463

    
1464
      if ntime_diff is not None:
1465
        continue
1466

    
1467
      try:
1468
        node_info[node] = {
1469
          "mfree": int(nodeinfo['memory_free']),
1470
          "pinst": [],
1471
          "sinst": [],
1472
          # dictionary holding all instances this node is secondary for,
1473
          # grouped by their primary node. Each key is a cluster node, and each
1474
          # value is a list of instances which have the key as primary and the
1475
          # current node as secondary.  this is handy to calculate N+1 memory
1476
          # availability if you can only failover from a primary to its
1477
          # secondary.
1478
          "sinst-by-pnode": {},
1479
        }
1480
        # FIXME: devise a free space model for file based instances as well
1481
        if vg_name is not None:
1482
          test = (constants.NV_VGLIST not in nresult or
1483
                  vg_name not in nresult[constants.NV_VGLIST])
1484
          _ErrorIf(test, self.ENODELVM, node,
1485
                   "node didn't return data for the volume group '%s'"
1486
                   " - it is either missing or broken", vg_name)
1487
          if test:
1488
            continue
1489
          node_info[node]["dfree"] = int(nresult[constants.NV_VGLIST][vg_name])
1490
      except (ValueError, KeyError):
1491
        _ErrorIf(True, self.ENODERPC, node,
1492
                 "node returned invalid nodeinfo, check lvm/hypervisor")
1493
        continue
1494

    
1495
    node_vol_should = {}
1496

    
1497
    feedback_fn("* Verifying instance status")
1498
    for instance in instancelist:
1499
      if verbose:
1500
        feedback_fn("* Verifying instance %s" % instance)
1501
      inst_config = instanceinfo[instance]
1502
      self._VerifyInstance(instance, inst_config, node_volume,
1503
                           node_instance, n_offline)
1504
      inst_nodes_offline = []
1505

    
1506
      inst_config.MapLVsByNode(node_vol_should)
1507

    
1508
      instance_cfg[instance] = inst_config
1509

    
1510
      pnode = inst_config.primary_node
1511
      _ErrorIf(pnode not in node_info and pnode not in n_offline,
1512
               self.ENODERPC, pnode, "instance %s, connection to"
1513
               " primary node failed", instance)
1514
      if pnode in node_info:
1515
        node_info[pnode]['pinst'].append(instance)
1516

    
1517
      if pnode in n_offline:
1518
        inst_nodes_offline.append(pnode)
1519

    
1520
      # If the instance is non-redundant we cannot survive losing its primary
1521
      # node, so we are not N+1 compliant. On the other hand we have no disk
1522
      # templates with more than one secondary so that situation is not well
1523
      # supported either.
1524
      # FIXME: does not support file-backed instances
1525
      if len(inst_config.secondary_nodes) == 0:
1526
        i_non_redundant.append(instance)
1527
      _ErrorIf(len(inst_config.secondary_nodes) > 1,
1528
               self.EINSTANCELAYOUT, instance,
1529
               "instance has multiple secondary nodes", code="WARNING")
1530

    
1531
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1532
        i_non_a_balanced.append(instance)
1533

    
1534
      for snode in inst_config.secondary_nodes:
1535
        _ErrorIf(snode not in node_info and snode not in n_offline,
1536
                 self.ENODERPC, snode,
1537
                 "instance %s, connection to secondary node"
1538
                 "failed", instance)
1539

    
1540
        if snode in node_info:
1541
          node_info[snode]['sinst'].append(instance)
1542
          if pnode not in node_info[snode]['sinst-by-pnode']:
1543
            node_info[snode]['sinst-by-pnode'][pnode] = []
1544
          node_info[snode]['sinst-by-pnode'][pnode].append(instance)
1545

    
1546
        if snode in n_offline:
1547
          inst_nodes_offline.append(snode)
1548

    
1549
      # warn that the instance lives on offline nodes
1550
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
1551
               "instance lives on offline node(s) %s",
1552
               utils.CommaJoin(inst_nodes_offline))
1553

    
1554
    feedback_fn("* Verifying orphan volumes")
1555
    self._VerifyOrphanVolumes(node_vol_should, node_volume)
1556

    
1557
    feedback_fn("* Verifying remaining instances")
1558
    self._VerifyOrphanInstances(instancelist, node_instance)
1559

    
1560
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1561
      feedback_fn("* Verifying N+1 Memory redundancy")
1562
      self._VerifyNPlusOneMemory(node_info, instance_cfg)
1563

    
1564
    feedback_fn("* Other Notes")
1565
    if i_non_redundant:
1566
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1567
                  % len(i_non_redundant))
1568

    
1569
    if i_non_a_balanced:
1570
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1571
                  % len(i_non_a_balanced))
1572

    
1573
    if n_offline:
1574
      feedback_fn("  - NOTICE: %d offline node(s) found." % len(n_offline))
1575

    
1576
    if n_drained:
1577
      feedback_fn("  - NOTICE: %d drained node(s) found." % len(n_drained))
1578

    
1579
    return not self.bad
1580

    
1581
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1582
    """Analyze the post-hooks' result
1583

1584
    This method analyses the hook result, handles it, and sends some
1585
    nicely-formatted feedback back to the user.
1586

1587
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1588
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1589
    @param hooks_results: the results of the multi-node hooks rpc call
1590
    @param feedback_fn: function used send feedback back to the caller
1591
    @param lu_result: previous Exec result
1592
    @return: the new Exec result, based on the previous result
1593
        and hook results
1594

1595
    """
1596
    # We only really run POST phase hooks, and are only interested in
1597
    # their results
1598
    if phase == constants.HOOKS_PHASE_POST:
1599
      # Used to change hooks' output to proper indentation
1600
      indent_re = re.compile('^', re.M)
1601
      feedback_fn("* Hooks Results")
1602
      assert hooks_results, "invalid result from hooks"
1603

    
1604
      for node_name in hooks_results:
1605
        res = hooks_results[node_name]
1606
        msg = res.fail_msg
1607
        test = msg and not res.offline
1608
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
1609
                      "Communication failure in hooks execution: %s", msg)
1610
        if res.offline or msg:
1611
          # No need to investigate payload if node is offline or gave an error.
1612
          # override manually lu_result here as _ErrorIf only
1613
          # overrides self.bad
1614
          lu_result = 1
1615
          continue
1616
        for script, hkr, output in res.payload:
1617
          test = hkr == constants.HKR_FAIL
1618
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
1619
                        "Script %s failed, output:", script)
1620
          if test:
1621
            output = indent_re.sub('      ', output)
1622
            feedback_fn("%s" % output)
1623
            lu_result = 1
1624

    
1625
      return lu_result
1626

    
1627

    
1628
class LUVerifyDisks(NoHooksLU):
1629
  """Verifies the cluster disks status.
1630

1631
  """
1632
  _OP_REQP = []
1633
  REQ_BGL = False
1634

    
1635
  def ExpandNames(self):
1636
    self.needed_locks = {
1637
      locking.LEVEL_NODE: locking.ALL_SET,
1638
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1639
    }
1640
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1641

    
1642
  def CheckPrereq(self):
1643
    """Check prerequisites.
1644

1645
    This has no prerequisites.
1646

1647
    """
1648
    pass
1649

    
1650
  def Exec(self, feedback_fn):
1651
    """Verify integrity of cluster disks.
1652

1653
    @rtype: tuple of three items
1654
    @return: a tuple of (dict of node-to-node_error, list of instances
1655
        which need activate-disks, dict of instance: (node, volume) for
1656
        missing volumes
1657

1658
    """
1659
    result = res_nodes, res_instances, res_missing = {}, [], {}
1660

    
1661
    vg_name = self.cfg.GetVGName()
1662
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1663
    instances = [self.cfg.GetInstanceInfo(name)
1664
                 for name in self.cfg.GetInstanceList()]
1665

    
1666
    nv_dict = {}
1667
    for inst in instances:
1668
      inst_lvs = {}
1669
      if (not inst.admin_up or
1670
          inst.disk_template not in constants.DTS_NET_MIRROR):
1671
        continue
1672
      inst.MapLVsByNode(inst_lvs)
1673
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1674
      for node, vol_list in inst_lvs.iteritems():
1675
        for vol in vol_list:
1676
          nv_dict[(node, vol)] = inst
1677

    
1678
    if not nv_dict:
1679
      return result
1680

    
1681
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
1682

    
1683
    for node in nodes:
1684
      # node_volume
1685
      node_res = node_lvs[node]
1686
      if node_res.offline:
1687
        continue
1688
      msg = node_res.fail_msg
1689
      if msg:
1690
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
1691
        res_nodes[node] = msg
1692
        continue
1693

    
1694
      lvs = node_res.payload
1695
      for lv_name, (_, _, lv_online) in lvs.items():
1696
        inst = nv_dict.pop((node, lv_name), None)
1697
        if (not lv_online and inst is not None
1698
            and inst.name not in res_instances):
1699
          res_instances.append(inst.name)
1700

    
1701
    # any leftover items in nv_dict are missing LVs, let's arrange the
1702
    # data better
1703
    for key, inst in nv_dict.iteritems():
1704
      if inst.name not in res_missing:
1705
        res_missing[inst.name] = []
1706
      res_missing[inst.name].append(key)
1707

    
1708
    return result
1709

    
1710

    
1711
class LURepairDiskSizes(NoHooksLU):
1712
  """Verifies the cluster disks sizes.
1713

1714
  """
1715
  _OP_REQP = ["instances"]
1716
  REQ_BGL = False
1717

    
1718
  def ExpandNames(self):
1719
    if not isinstance(self.op.instances, list):
1720
      raise errors.OpPrereqError("Invalid argument type 'instances'",
1721
                                 errors.ECODE_INVAL)
1722

    
1723
    if self.op.instances:
1724
      self.wanted_names = []
1725
      for name in self.op.instances:
1726
        full_name = self.cfg.ExpandInstanceName(name)
1727
        if full_name is None:
1728
          raise errors.OpPrereqError("Instance '%s' not known" % name,
1729
                                     errors.ECODE_NOENT)
1730
        self.wanted_names.append(full_name)
1731
      self.needed_locks = {
1732
        locking.LEVEL_NODE: [],
1733
        locking.LEVEL_INSTANCE: self.wanted_names,
1734
        }
1735
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
1736
    else:
1737
      self.wanted_names = None
1738
      self.needed_locks = {
1739
        locking.LEVEL_NODE: locking.ALL_SET,
1740
        locking.LEVEL_INSTANCE: locking.ALL_SET,
1741
        }
1742
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
1743

    
1744
  def DeclareLocks(self, level):
1745
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
1746
      self._LockInstancesNodes(primary_only=True)
1747

    
1748
  def CheckPrereq(self):
1749
    """Check prerequisites.
1750

1751
    This only checks the optional instance list against the existing names.
1752

1753
    """
1754
    if self.wanted_names is None:
1755
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
1756

    
1757
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
1758
                             in self.wanted_names]
1759

    
1760
  def _EnsureChildSizes(self, disk):
1761
    """Ensure children of the disk have the needed disk size.
1762

1763
    This is valid mainly for DRBD8 and fixes an issue where the
1764
    children have smaller disk size.
1765

1766
    @param disk: an L{ganeti.objects.Disk} object
1767

1768
    """
1769
    if disk.dev_type == constants.LD_DRBD8:
1770
      assert disk.children, "Empty children for DRBD8?"
1771
      fchild = disk.children[0]
1772
      mismatch = fchild.size < disk.size
1773
      if mismatch:
1774
        self.LogInfo("Child disk has size %d, parent %d, fixing",
1775
                     fchild.size, disk.size)
1776
        fchild.size = disk.size
1777

    
1778
      # and we recurse on this child only, not on the metadev
1779
      return self._EnsureChildSizes(fchild) or mismatch
1780
    else:
1781
      return False
1782

    
1783
  def Exec(self, feedback_fn):
1784
    """Verify the size of cluster disks.
1785

1786
    """
1787
    # TODO: check child disks too
1788
    # TODO: check differences in size between primary/secondary nodes
1789
    per_node_disks = {}
1790
    for instance in self.wanted_instances:
1791
      pnode = instance.primary_node
1792
      if pnode not in per_node_disks:
1793
        per_node_disks[pnode] = []
1794
      for idx, disk in enumerate(instance.disks):
1795
        per_node_disks[pnode].append((instance, idx, disk))
1796

    
1797
    changed = []
1798
    for node, dskl in per_node_disks.items():
1799
      newl = [v[2].Copy() for v in dskl]
1800
      for dsk in newl:
1801
        self.cfg.SetDiskID(dsk, node)
1802
      result = self.rpc.call_blockdev_getsizes(node, newl)
1803
      if result.fail_msg:
1804
        self.LogWarning("Failure in blockdev_getsizes call to node"
1805
                        " %s, ignoring", node)
1806
        continue
1807
      if len(result.data) != len(dskl):
1808
        self.LogWarning("Invalid result from node %s, ignoring node results",
1809
                        node)
1810
        continue
1811
      for ((instance, idx, disk), size) in zip(dskl, result.data):
1812
        if size is None:
1813
          self.LogWarning("Disk %d of instance %s did not return size"
1814
                          " information, ignoring", idx, instance.name)
1815
          continue
1816
        if not isinstance(size, (int, long)):
1817
          self.LogWarning("Disk %d of instance %s did not return valid"
1818
                          " size information, ignoring", idx, instance.name)
1819
          continue
1820
        size = size >> 20
1821
        if size != disk.size:
1822
          self.LogInfo("Disk %d of instance %s has mismatched size,"
1823
                       " correcting: recorded %d, actual %d", idx,
1824
                       instance.name, disk.size, size)
1825
          disk.size = size
1826
          self.cfg.Update(instance, feedback_fn)
1827
          changed.append((instance.name, idx, size))
1828
        if self._EnsureChildSizes(disk):
1829
          self.cfg.Update(instance, feedback_fn)
1830
          changed.append((instance.name, idx, disk.size))
1831
    return changed
1832

    
1833

    
1834
class LURenameCluster(LogicalUnit):
1835
  """Rename the cluster.
1836

1837
  """
1838
  HPATH = "cluster-rename"
1839
  HTYPE = constants.HTYPE_CLUSTER
1840
  _OP_REQP = ["name"]
1841

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

1845
    """
1846
    env = {
1847
      "OP_TARGET": self.cfg.GetClusterName(),
1848
      "NEW_NAME": self.op.name,
1849
      }
1850
    mn = self.cfg.GetMasterNode()
1851
    all_nodes = self.cfg.GetNodeList()
1852
    return env, [mn], all_nodes
1853

    
1854
  def CheckPrereq(self):
1855
    """Verify that the passed name is a valid one.
1856

1857
    """
1858
    hostname = utils.GetHostInfo(self.op.name)
1859

    
1860
    new_name = hostname.name
1861
    self.ip = new_ip = hostname.ip
1862
    old_name = self.cfg.GetClusterName()
1863
    old_ip = self.cfg.GetMasterIP()
1864
    if new_name == old_name and new_ip == old_ip:
1865
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1866
                                 " cluster has changed",
1867
                                 errors.ECODE_INVAL)
1868
    if new_ip != old_ip:
1869
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1870
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1871
                                   " reachable on the network. Aborting." %
1872
                                   new_ip, errors.ECODE_NOTUNIQUE)
1873

    
1874
    self.op.name = new_name
1875

    
1876
  def Exec(self, feedback_fn):
1877
    """Rename the cluster.
1878

1879
    """
1880
    clustername = self.op.name
1881
    ip = self.ip
1882

    
1883
    # shutdown the master IP
1884
    master = self.cfg.GetMasterNode()
1885
    result = self.rpc.call_node_stop_master(master, False)
1886
    result.Raise("Could not disable the master role")
1887

    
1888
    try:
1889
      cluster = self.cfg.GetClusterInfo()
1890
      cluster.cluster_name = clustername
1891
      cluster.master_ip = ip
1892
      self.cfg.Update(cluster, feedback_fn)
1893

    
1894
      # update the known hosts file
1895
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
1896
      node_list = self.cfg.GetNodeList()
1897
      try:
1898
        node_list.remove(master)
1899
      except ValueError:
1900
        pass
1901
      result = self.rpc.call_upload_file(node_list,
1902
                                         constants.SSH_KNOWN_HOSTS_FILE)
1903
      for to_node, to_result in result.iteritems():
1904
        msg = to_result.fail_msg
1905
        if msg:
1906
          msg = ("Copy of file %s to node %s failed: %s" %
1907
                 (constants.SSH_KNOWN_HOSTS_FILE, to_node, msg))
1908
          self.proc.LogWarning(msg)
1909

    
1910
    finally:
1911
      result = self.rpc.call_node_start_master(master, False, False)
1912
      msg = result.fail_msg
1913
      if msg:
1914
        self.LogWarning("Could not re-enable the master role on"
1915
                        " the master, please restart manually: %s", msg)
1916

    
1917

    
1918
def _RecursiveCheckIfLVMBased(disk):
1919
  """Check if the given disk or its children are lvm-based.
1920

1921
  @type disk: L{objects.Disk}
1922
  @param disk: the disk to check
1923
  @rtype: boolean
1924
  @return: boolean indicating whether a LD_LV dev_type was found or not
1925

1926
  """
1927
  if disk.children:
1928
    for chdisk in disk.children:
1929
      if _RecursiveCheckIfLVMBased(chdisk):
1930
        return True
1931
  return disk.dev_type == constants.LD_LV
1932

    
1933

    
1934
class LUSetClusterParams(LogicalUnit):
1935
  """Change the parameters of the cluster.
1936

1937
  """
1938
  HPATH = "cluster-modify"
1939
  HTYPE = constants.HTYPE_CLUSTER
1940
  _OP_REQP = []
1941
  REQ_BGL = False
1942

    
1943
  def CheckArguments(self):
1944
    """Check parameters
1945

1946
    """
1947
    if not hasattr(self.op, "candidate_pool_size"):
1948
      self.op.candidate_pool_size = None
1949
    if self.op.candidate_pool_size is not None:
1950
      try:
1951
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
1952
      except (ValueError, TypeError), err:
1953
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
1954
                                   str(err), errors.ECODE_INVAL)
1955
      if self.op.candidate_pool_size < 1:
1956
        raise errors.OpPrereqError("At least one master candidate needed",
1957
                                   errors.ECODE_INVAL)
1958

    
1959
  def ExpandNames(self):
1960
    # FIXME: in the future maybe other cluster params won't require checking on
1961
    # all nodes to be modified.
1962
    self.needed_locks = {
1963
      locking.LEVEL_NODE: locking.ALL_SET,
1964
    }
1965
    self.share_locks[locking.LEVEL_NODE] = 1
1966

    
1967
  def BuildHooksEnv(self):
1968
    """Build hooks env.
1969

1970
    """
1971
    env = {
1972
      "OP_TARGET": self.cfg.GetClusterName(),
1973
      "NEW_VG_NAME": self.op.vg_name,
1974
      }
1975
    mn = self.cfg.GetMasterNode()
1976
    return env, [mn], [mn]
1977

    
1978
  def CheckPrereq(self):
1979
    """Check prerequisites.
1980

1981
    This checks whether the given params don't conflict and
1982
    if the given volume group is valid.
1983

1984
    """
1985
    if self.op.vg_name is not None and not self.op.vg_name:
1986
      instances = self.cfg.GetAllInstancesInfo().values()
1987
      for inst in instances:
1988
        for disk in inst.disks:
1989
          if _RecursiveCheckIfLVMBased(disk):
1990
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1991
                                       " lvm-based instances exist",
1992
                                       errors.ECODE_INVAL)
1993

    
1994
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1995

    
1996
    # if vg_name not None, checks given volume group on all nodes
1997
    if self.op.vg_name:
1998
      vglist = self.rpc.call_vg_list(node_list)
1999
      for node in node_list:
2000
        msg = vglist[node].fail_msg
2001
        if msg:
2002
          # ignoring down node
2003
          self.LogWarning("Error while gathering data on node %s"
2004
                          " (ignoring node): %s", node, msg)
2005
          continue
2006
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2007
                                              self.op.vg_name,
2008
                                              constants.MIN_VG_SIZE)
2009
        if vgstatus:
2010
          raise errors.OpPrereqError("Error on node '%s': %s" %
2011
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2012

    
2013
    self.cluster = cluster = self.cfg.GetClusterInfo()
2014
    # validate params changes
2015
    if self.op.beparams:
2016
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2017
      self.new_beparams = objects.FillDict(
2018
        cluster.beparams[constants.PP_DEFAULT], self.op.beparams)
2019

    
2020
    if self.op.nicparams:
2021
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2022
      self.new_nicparams = objects.FillDict(
2023
        cluster.nicparams[constants.PP_DEFAULT], self.op.nicparams)
2024
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2025
      nic_errors = []
2026

    
2027
      # check all instances for consistency
2028
      for instance in self.cfg.GetAllInstancesInfo().values():
2029
        for nic_idx, nic in enumerate(instance.nics):
2030
          params_copy = copy.deepcopy(nic.nicparams)
2031
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2032

    
2033
          # check parameter syntax
2034
          try:
2035
            objects.NIC.CheckParameterSyntax(params_filled)
2036
          except errors.ConfigurationError, err:
2037
            nic_errors.append("Instance %s, nic/%d: %s" %
2038
                              (instance.name, nic_idx, err))
2039

    
2040
          # if we're moving instances to routed, check that they have an ip
2041
          target_mode = params_filled[constants.NIC_MODE]
2042
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2043
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2044
                              (instance.name, nic_idx))
2045
      if nic_errors:
2046
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2047
                                   "\n".join(nic_errors))
2048

    
2049
    # hypervisor list/parameters
2050
    self.new_hvparams = objects.FillDict(cluster.hvparams, {})
2051
    if self.op.hvparams:
2052
      if not isinstance(self.op.hvparams, dict):
2053
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input",
2054
                                   errors.ECODE_INVAL)
2055
      for hv_name, hv_dict in self.op.hvparams.items():
2056
        if hv_name not in self.new_hvparams:
2057
          self.new_hvparams[hv_name] = hv_dict
2058
        else:
2059
          self.new_hvparams[hv_name].update(hv_dict)
2060

    
2061
    if self.op.enabled_hypervisors is not None:
2062
      self.hv_list = self.op.enabled_hypervisors
2063
      if not self.hv_list:
2064
        raise errors.OpPrereqError("Enabled hypervisors list must contain at"
2065
                                   " least one member",
2066
                                   errors.ECODE_INVAL)
2067
      invalid_hvs = set(self.hv_list) - constants.HYPER_TYPES
2068
      if invalid_hvs:
2069
        raise errors.OpPrereqError("Enabled hypervisors contains invalid"
2070
                                   " entries: %s" %
2071
                                   utils.CommaJoin(invalid_hvs),
2072
                                   errors.ECODE_INVAL)
2073
    else:
2074
      self.hv_list = cluster.enabled_hypervisors
2075

    
2076
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2077
      # either the enabled list has changed, or the parameters have, validate
2078
      for hv_name, hv_params in self.new_hvparams.items():
2079
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2080
            (self.op.enabled_hypervisors and
2081
             hv_name in self.op.enabled_hypervisors)):
2082
          # either this is a new hypervisor, or its parameters have changed
2083
          hv_class = hypervisor.GetHypervisor(hv_name)
2084
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2085
          hv_class.CheckParameterSyntax(hv_params)
2086
          _CheckHVParams(self, node_list, hv_name, hv_params)
2087

    
2088
  def Exec(self, feedback_fn):
2089
    """Change the parameters of the cluster.
2090

2091
    """
2092
    if self.op.vg_name is not None:
2093
      new_volume = self.op.vg_name
2094
      if not new_volume:
2095
        new_volume = None
2096
      if new_volume != self.cfg.GetVGName():
2097
        self.cfg.SetVGName(new_volume)
2098
      else:
2099
        feedback_fn("Cluster LVM configuration already in desired"
2100
                    " state, not changing")
2101
    if self.op.hvparams:
2102
      self.cluster.hvparams = self.new_hvparams
2103
    if self.op.enabled_hypervisors is not None:
2104
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2105
    if self.op.beparams:
2106
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2107
    if self.op.nicparams:
2108
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2109

    
2110
    if self.op.candidate_pool_size is not None:
2111
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2112
      # we need to update the pool size here, otherwise the save will fail
2113
      _AdjustCandidatePool(self, [])
2114

    
2115
    self.cfg.Update(self.cluster, feedback_fn)
2116

    
2117

    
2118
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
2119
  """Distribute additional files which are part of the cluster configuration.
2120

2121
  ConfigWriter takes care of distributing the config and ssconf files, but
2122
  there are more files which should be distributed to all nodes. This function
2123
  makes sure those are copied.
2124

2125
  @param lu: calling logical unit
2126
  @param additional_nodes: list of nodes not in the config to distribute to
2127

2128
  """
2129
  # 1. Gather target nodes
2130
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2131
  dist_nodes = lu.cfg.GetNodeList()
2132
  if additional_nodes is not None:
2133
    dist_nodes.extend(additional_nodes)
2134
  if myself.name in dist_nodes:
2135
    dist_nodes.remove(myself.name)
2136

    
2137
  # 2. Gather files to distribute
2138
  dist_files = set([constants.ETC_HOSTS,
2139
                    constants.SSH_KNOWN_HOSTS_FILE,
2140
                    constants.RAPI_CERT_FILE,
2141
                    constants.RAPI_USERS_FILE,
2142
                    constants.HMAC_CLUSTER_KEY,
2143
                   ])
2144

    
2145
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2146
  for hv_name in enabled_hypervisors:
2147
    hv_class = hypervisor.GetHypervisor(hv_name)
2148
    dist_files.update(hv_class.GetAncillaryFiles())
2149

    
2150
  # 3. Perform the files upload
2151
  for fname in dist_files:
2152
    if os.path.exists(fname):
2153
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2154
      for to_node, to_result in result.items():
2155
        msg = to_result.fail_msg
2156
        if msg:
2157
          msg = ("Copy of file %s to node %s failed: %s" %
2158
                 (fname, to_node, msg))
2159
          lu.proc.LogWarning(msg)
2160

    
2161

    
2162
class LURedistributeConfig(NoHooksLU):
2163
  """Force the redistribution of cluster configuration.
2164

2165
  This is a very simple LU.
2166

2167
  """
2168
  _OP_REQP = []
2169
  REQ_BGL = False
2170

    
2171
  def ExpandNames(self):
2172
    self.needed_locks = {
2173
      locking.LEVEL_NODE: locking.ALL_SET,
2174
    }
2175
    self.share_locks[locking.LEVEL_NODE] = 1
2176

    
2177
  def CheckPrereq(self):
2178
    """Check prerequisites.
2179

2180
    """
2181

    
2182
  def Exec(self, feedback_fn):
2183
    """Redistribute the configuration.
2184

2185
    """
2186
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2187
    _RedistributeAncillaryFiles(self)
2188

    
2189

    
2190
def _WaitForSync(lu, instance, oneshot=False):
2191
  """Sleep and poll for an instance's disk to sync.
2192

2193
  """
2194
  if not instance.disks:
2195
    return True
2196

    
2197
  if not oneshot:
2198
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2199

    
2200
  node = instance.primary_node
2201

    
2202
  for dev in instance.disks:
2203
    lu.cfg.SetDiskID(dev, node)
2204

    
2205
  # TODO: Convert to utils.Retry
2206

    
2207
  retries = 0
2208
  degr_retries = 10 # in seconds, as we sleep 1 second each time
2209
  while True:
2210
    max_time = 0
2211
    done = True
2212
    cumul_degraded = False
2213
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
2214
    msg = rstats.fail_msg
2215
    if msg:
2216
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
2217
      retries += 1
2218
      if retries >= 10:
2219
        raise errors.RemoteError("Can't contact node %s for mirror data,"
2220
                                 " aborting." % node)
2221
      time.sleep(6)
2222
      continue
2223
    rstats = rstats.payload
2224
    retries = 0
2225
    for i, mstat in enumerate(rstats):
2226
      if mstat is None:
2227
        lu.LogWarning("Can't compute data for node %s/%s",
2228
                           node, instance.disks[i].iv_name)
2229
        continue
2230

    
2231
      cumul_degraded = (cumul_degraded or
2232
                        (mstat.is_degraded and mstat.sync_percent is None))
2233
      if mstat.sync_percent is not None:
2234
        done = False
2235
        if mstat.estimated_time is not None:
2236
          rem_time = "%d estimated seconds remaining" % mstat.estimated_time
2237
          max_time = mstat.estimated_time
2238
        else:
2239
          rem_time = "no time estimate"
2240
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
2241
                        (instance.disks[i].iv_name, mstat.sync_percent,
2242
                         rem_time))
2243

    
2244
    # if we're done but degraded, let's do a few small retries, to
2245
    # make sure we see a stable and not transient situation; therefore
2246
    # we force restart of the loop
2247
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
2248
      logging.info("Degraded disks found, %d retries left", degr_retries)
2249
      degr_retries -= 1
2250
      time.sleep(1)
2251
      continue
2252

    
2253
    if done or oneshot:
2254
      break
2255

    
2256
    time.sleep(min(60, max_time))
2257

    
2258
  if done:
2259
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
2260
  return not cumul_degraded
2261

    
2262

    
2263
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
2264
  """Check that mirrors are not degraded.
2265

2266
  The ldisk parameter, if True, will change the test from the
2267
  is_degraded attribute (which represents overall non-ok status for
2268
  the device(s)) to the ldisk (representing the local storage status).
2269

2270
  """
2271
  lu.cfg.SetDiskID(dev, node)
2272

    
2273
  result = True
2274

    
2275
  if on_primary or dev.AssembleOnSecondary():
2276
    rstats = lu.rpc.call_blockdev_find(node, dev)
2277
    msg = rstats.fail_msg
2278
    if msg:
2279
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
2280
      result = False
2281
    elif not rstats.payload:
2282
      lu.LogWarning("Can't find disk on node %s", node)
2283
      result = False
2284
    else:
2285
      if ldisk:
2286
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
2287
      else:
2288
        result = result and not rstats.payload.is_degraded
2289

    
2290
  if dev.children:
2291
    for child in dev.children:
2292
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
2293

    
2294
  return result
2295

    
2296

    
2297
class LUDiagnoseOS(NoHooksLU):
2298
  """Logical unit for OS diagnose/query.
2299

2300
  """
2301
  _OP_REQP = ["output_fields", "names"]
2302
  REQ_BGL = False
2303
  _FIELDS_STATIC = utils.FieldSet()
2304
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status", "variants")
2305
  # Fields that need calculation of global os validity
2306
  _FIELDS_NEEDVALID = frozenset(["valid", "variants"])
2307

    
2308
  def ExpandNames(self):
2309
    if self.op.names:
2310
      raise errors.OpPrereqError("Selective OS query not supported",
2311
                                 errors.ECODE_INVAL)
2312

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

    
2317
    # Lock all nodes, in shared mode
2318
    # Temporary removal of locks, should be reverted later
2319
    # TODO: reintroduce locks when they are lighter-weight
2320
    self.needed_locks = {}
2321
    #self.share_locks[locking.LEVEL_NODE] = 1
2322
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2323

    
2324
  def CheckPrereq(self):
2325
    """Check prerequisites.
2326

2327
    """
2328

    
2329
  @staticmethod
2330
  def _DiagnoseByOS(rlist):
2331
    """Remaps a per-node return list into an a per-os per-node dictionary
2332

2333
    @param rlist: a map with node names as keys and OS objects as values
2334

2335
    @rtype: dict
2336
    @return: a dictionary with osnames as keys and as value another map, with
2337
        nodes as keys and tuples of (path, status, diagnose) as values, eg::
2338

2339
          {"debian-etch": {"node1": [(/usr/lib/..., True, ""),
2340
                                     (/srv/..., False, "invalid api")],
2341
                           "node2": [(/srv/..., True, "")]}
2342
          }
2343

2344
    """
2345
    all_os = {}
2346
    # we build here the list of nodes that didn't fail the RPC (at RPC
2347
    # level), so that nodes with a non-responding node daemon don't
2348
    # make all OSes invalid
2349
    good_nodes = [node_name for node_name in rlist
2350
                  if not rlist[node_name].fail_msg]
2351
    for node_name, nr in rlist.items():
2352
      if nr.fail_msg or not nr.payload:
2353
        continue
2354
      for name, path, status, diagnose, variants in nr.payload:
2355
        if name not in all_os:
2356
          # build a list of nodes for this os containing empty lists
2357
          # for each node in node_list
2358
          all_os[name] = {}
2359
          for nname in good_nodes:
2360
            all_os[name][nname] = []
2361
        all_os[name][node_name].append((path, status, diagnose, variants))
2362
    return all_os
2363

    
2364
  def Exec(self, feedback_fn):
2365
    """Compute the list of OSes.
2366

2367
    """
2368
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
2369
    node_data = self.rpc.call_os_diagnose(valid_nodes)
2370
    pol = self._DiagnoseByOS(node_data)
2371
    output = []
2372
    calc_valid = self._FIELDS_NEEDVALID.intersection(self.op.output_fields)
2373
    calc_variants = "variants" in self.op.output_fields
2374

    
2375
    for os_name, os_data in pol.items():
2376
      row = []
2377
      if calc_valid:
2378
        valid = True
2379
        variants = None
2380
        for osl in os_data.values():
2381
          valid = valid and osl and osl[0][1]
2382
          if not valid:
2383
            variants = None
2384
            break
2385
          if calc_variants:
2386
            node_variants = osl[0][3]
2387
            if variants is None:
2388
              variants = node_variants
2389
            else:
2390
              variants = [v for v in variants if v in node_variants]
2391

    
2392
      for field in self.op.output_fields:
2393
        if field == "name":
2394
          val = os_name
2395
        elif field == "valid":
2396
          val = valid
2397
        elif field == "node_status":
2398
          # this is just a copy of the dict
2399
          val = {}
2400
          for node_name, nos_list in os_data.items():
2401
            val[node_name] = nos_list
2402
        elif field == "variants":
2403
          val =  variants
2404
        else:
2405
          raise errors.ParameterError(field)
2406
        row.append(val)
2407
      output.append(row)
2408

    
2409
    return output
2410

    
2411

    
2412
class LURemoveNode(LogicalUnit):
2413
  """Logical unit for removing a node.
2414

2415
  """
2416
  HPATH = "node-remove"
2417
  HTYPE = constants.HTYPE_NODE
2418
  _OP_REQP = ["node_name"]
2419

    
2420
  def BuildHooksEnv(self):
2421
    """Build hooks env.
2422

2423
    This doesn't run on the target node in the pre phase as a failed
2424
    node would then be impossible to remove.
2425

2426
    """
2427
    env = {
2428
      "OP_TARGET": self.op.node_name,
2429
      "NODE_NAME": self.op.node_name,
2430
      }
2431
    all_nodes = self.cfg.GetNodeList()
2432
    try:
2433
      all_nodes.remove(self.op.node_name)
2434
    except ValueError:
2435
      logging.warning("Node %s which is about to be removed not found"
2436
                      " in the all nodes list", self.op.node_name)
2437
    return env, all_nodes, all_nodes
2438

    
2439
  def CheckPrereq(self):
2440
    """Check prerequisites.
2441

2442
    This checks:
2443
     - the node exists in the configuration
2444
     - it does not have primary or secondary instances
2445
     - it's not the master
2446

2447
    Any errors are signaled by raising errors.OpPrereqError.
2448

2449
    """
2450
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
2451
    if node is None:
2452
      raise errors.OpPrereqError("Node '%s' is unknown." % self.op.node_name,
2453
                                 errors.ECODE_NOENT)
2454

    
2455
    instance_list = self.cfg.GetInstanceList()
2456

    
2457
    masternode = self.cfg.GetMasterNode()
2458
    if node.name == masternode:
2459
      raise errors.OpPrereqError("Node is the master node,"
2460
                                 " you need to failover first.",
2461
                                 errors.ECODE_INVAL)
2462

    
2463
    for instance_name in instance_list:
2464
      instance = self.cfg.GetInstanceInfo(instance_name)
2465
      if node.name in instance.all_nodes:
2466
        raise errors.OpPrereqError("Instance %s is still running on the node,"
2467
                                   " please remove first." % instance_name,
2468
                                   errors.ECODE_INVAL)
2469
    self.op.node_name = node.name
2470
    self.node = node
2471

    
2472
  def Exec(self, feedback_fn):
2473
    """Removes the node from the cluster.
2474

2475
    """
2476
    node = self.node
2477
    logging.info("Stopping the node daemon and removing configs from node %s",
2478
                 node.name)
2479

    
2480
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
2481

    
2482
    # Promote nodes to master candidate as needed
2483
    _AdjustCandidatePool(self, exceptions=[node.name])
2484
    self.context.RemoveNode(node.name)
2485

    
2486
    # Run post hooks on the node before it's removed
2487
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
2488
    try:
2489
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
2490
    except:
2491
      # pylint: disable-msg=W0702
2492
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
2493

    
2494
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
2495
    msg = result.fail_msg
2496
    if msg:
2497
      self.LogWarning("Errors encountered on the remote node while leaving"
2498
                      " the cluster: %s", msg)
2499

    
2500

    
2501
class LUQueryNodes(NoHooksLU):
2502
  """Logical unit for querying nodes.
2503

2504
  """
2505
  # pylint: disable-msg=W0142
2506
  _OP_REQP = ["output_fields", "names", "use_locking"]
2507
  REQ_BGL = False
2508

    
2509
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
2510
                    "master_candidate", "offline", "drained"]
2511

    
2512
  _FIELDS_DYNAMIC = utils.FieldSet(
2513
    "dtotal", "dfree",
2514
    "mtotal", "mnode", "mfree",
2515
    "bootid",
2516
    "ctotal", "cnodes", "csockets",
2517
    )
2518

    
2519
  _FIELDS_STATIC = utils.FieldSet(*[
2520
    "pinst_cnt", "sinst_cnt",
2521
    "pinst_list", "sinst_list",
2522
    "pip", "sip", "tags",
2523
    "master",
2524
    "role"] + _SIMPLE_FIELDS
2525
    )
2526

    
2527
  def ExpandNames(self):
2528
    _CheckOutputFields(static=self._FIELDS_STATIC,
2529
                       dynamic=self._FIELDS_DYNAMIC,
2530
                       selected=self.op.output_fields)
2531

    
2532
    self.needed_locks = {}
2533
    self.share_locks[locking.LEVEL_NODE] = 1
2534

    
2535
    if self.op.names:
2536
      self.wanted = _GetWantedNodes(self, self.op.names)
2537
    else:
2538
      self.wanted = locking.ALL_SET
2539

    
2540
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
2541
    self.do_locking = self.do_node_query and self.op.use_locking
2542
    if self.do_locking:
2543
      # if we don't request only static fields, we need to lock the nodes
2544
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
2545

    
2546
  def CheckPrereq(self):
2547
    """Check prerequisites.
2548

2549
    """
2550
    # The validation of the node list is done in the _GetWantedNodes,
2551
    # if non empty, and if empty, there's no validation to do
2552
    pass
2553

    
2554
  def Exec(self, feedback_fn):
2555
    """Computes the list of nodes and their attributes.
2556

2557
    """
2558
    all_info = self.cfg.GetAllNodesInfo()
2559
    if self.do_locking:
2560
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
2561
    elif self.wanted != locking.ALL_SET:
2562
      nodenames = self.wanted
2563
      missing = set(nodenames).difference(all_info.keys())
2564
      if missing:
2565
        raise errors.OpExecError(
2566
          "Some nodes were removed before retrieving their data: %s" % missing)
2567
    else:
2568
      nodenames = all_info.keys()
2569

    
2570
    nodenames = utils.NiceSort(nodenames)
2571
    nodelist = [all_info[name] for name in nodenames]
2572

    
2573
    # begin data gathering
2574

    
2575
    if self.do_node_query:
2576
      live_data = {}
2577
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
2578
                                          self.cfg.GetHypervisorType())
2579
      for name in nodenames:
2580
        nodeinfo = node_data[name]
2581
        if not nodeinfo.fail_msg and nodeinfo.payload:
2582
          nodeinfo = nodeinfo.payload
2583
          fn = utils.TryConvert
2584
          live_data[name] = {
2585
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
2586
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
2587
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
2588
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
2589
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
2590
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
2591
            "bootid": nodeinfo.get('bootid', None),
2592
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
2593
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
2594
            }
2595
        else:
2596
          live_data[name] = {}
2597
    else:
2598
      live_data = dict.fromkeys(nodenames, {})
2599

    
2600
    node_to_primary = dict([(name, set()) for name in nodenames])
2601
    node_to_secondary = dict([(name, set()) for name in nodenames])
2602

    
2603
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
2604
                             "sinst_cnt", "sinst_list"))
2605
    if inst_fields & frozenset(self.op.output_fields):
2606
      inst_data = self.cfg.GetAllInstancesInfo()
2607

    
2608
      for inst in inst_data.values():
2609
        if inst.primary_node in node_to_primary:
2610
          node_to_primary[inst.primary_node].add(inst.name)
2611
        for secnode in inst.secondary_nodes:
2612
          if secnode in node_to_secondary:
2613
            node_to_secondary[secnode].add(inst.name)
2614

    
2615
    master_node = self.cfg.GetMasterNode()
2616

    
2617
    # end data gathering
2618

    
2619
    output = []
2620
    for node in nodelist:
2621
      node_output = []
2622
      for field in self.op.output_fields:
2623
        if field in self._SIMPLE_FIELDS:
2624
          val = getattr(node, field)
2625
        elif field == "pinst_list":
2626
          val = list(node_to_primary[node.name])
2627
        elif field == "sinst_list":
2628
          val = list(node_to_secondary[node.name])
2629
        elif field == "pinst_cnt":
2630
          val = len(node_to_primary[node.name])
2631
        elif field == "sinst_cnt":
2632
          val = len(node_to_secondary[node.name])
2633
        elif field == "pip":
2634
          val = node.primary_ip
2635
        elif field == "sip":
2636
          val = node.secondary_ip
2637
        elif field == "tags":
2638
          val = list(node.GetTags())
2639
        elif field == "master":
2640
          val = node.name == master_node
2641
        elif self._FIELDS_DYNAMIC.Matches(field):
2642
          val = live_data[node.name].get(field, None)
2643
        elif field == "role":
2644
          if node.name == master_node:
2645
            val = "M"
2646
          elif node.master_candidate:
2647
            val = "C"
2648
          elif node.drained:
2649
            val = "D"
2650
          elif node.offline:
2651
            val = "O"
2652
          else:
2653
            val = "R"
2654
        else:
2655
          raise errors.ParameterError(field)
2656
        node_output.append(val)
2657
      output.append(node_output)
2658

    
2659
    return output
2660

    
2661

    
2662
class LUQueryNodeVolumes(NoHooksLU):
2663
  """Logical unit for getting volumes on node(s).
2664

2665
  """
2666
  _OP_REQP = ["nodes", "output_fields"]
2667
  REQ_BGL = False
2668
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
2669
  _FIELDS_STATIC = utils.FieldSet("node")
2670

    
2671
  def ExpandNames(self):
2672
    _CheckOutputFields(static=self._FIELDS_STATIC,
2673
                       dynamic=self._FIELDS_DYNAMIC,
2674
                       selected=self.op.output_fields)
2675

    
2676
    self.needed_locks = {}
2677
    self.share_locks[locking.LEVEL_NODE] = 1
2678
    if not self.op.nodes:
2679
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2680
    else:
2681
      self.needed_locks[locking.LEVEL_NODE] = \
2682
        _GetWantedNodes(self, self.op.nodes)
2683

    
2684
  def CheckPrereq(self):
2685
    """Check prerequisites.
2686

2687
    This checks that the fields required are valid output fields.
2688

2689
    """
2690
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
2691

    
2692
  def Exec(self, feedback_fn):
2693
    """Computes the list of nodes and their attributes.
2694

2695
    """
2696
    nodenames = self.nodes
2697
    volumes = self.rpc.call_node_volumes(nodenames)
2698

    
2699
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
2700
             in self.cfg.GetInstanceList()]
2701

    
2702
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
2703

    
2704
    output = []
2705
    for node in nodenames:
2706
      nresult = volumes[node]
2707
      if nresult.offline:
2708
        continue
2709
      msg = nresult.fail_msg
2710
      if msg:
2711
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
2712
        continue
2713

    
2714
      node_vols = nresult.payload[:]
2715
      node_vols.sort(key=lambda vol: vol['dev'])
2716

    
2717
      for vol in node_vols:
2718
        node_output = []
2719
        for field in self.op.output_fields:
2720
          if field == "node":
2721
            val = node
2722
          elif field == "phys":
2723
            val = vol['dev']
2724
          elif field == "vg":
2725
            val = vol['vg']
2726
          elif field == "name":
2727
            val = vol['name']
2728
          elif field == "size":
2729
            val = int(float(vol['size']))
2730
          elif field == "instance":
2731
            for inst in ilist:
2732
              if node not in lv_by_node[inst]:
2733
                continue
2734
              if vol['name'] in lv_by_node[inst][node]:
2735
                val = inst.name
2736
                break
2737
            else:
2738
              val = '-'
2739
          else:
2740
            raise errors.ParameterError(field)
2741
          node_output.append(str(val))
2742

    
2743
        output.append(node_output)
2744

    
2745
    return output
2746

    
2747

    
2748
class LUQueryNodeStorage(NoHooksLU):
2749
  """Logical unit for getting information on storage units on node(s).
2750

2751
  """
2752
  _OP_REQP = ["nodes", "storage_type", "output_fields"]
2753
  REQ_BGL = False
2754
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
2755

    
2756
  def ExpandNames(self):
2757
    storage_type = self.op.storage_type
2758

    
2759
    if storage_type not in constants.VALID_STORAGE_TYPES:
2760
      raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
2761
                                 errors.ECODE_INVAL)
2762

    
2763
    _CheckOutputFields(static=self._FIELDS_STATIC,
2764
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
2765
                       selected=self.op.output_fields)
2766

    
2767
    self.needed_locks = {}
2768
    self.share_locks[locking.LEVEL_NODE] = 1
2769

    
2770
    if self.op.nodes:
2771
      self.needed_locks[locking.LEVEL_NODE] = \
2772
        _GetWantedNodes(self, self.op.nodes)
2773
    else:
2774
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2775

    
2776
  def CheckPrereq(self):
2777
    """Check prerequisites.
2778

2779
    This checks that the fields required are valid output fields.
2780

2781
    """
2782
    self.op.name = getattr(self.op, "name", None)
2783

    
2784
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
2785

    
2786
  def Exec(self, feedback_fn):
2787
    """Computes the list of nodes and their attributes.
2788

2789
    """
2790
    # Always get name to sort by
2791
    if constants.SF_NAME in self.op.output_fields:
2792
      fields = self.op.output_fields[:]
2793
    else:
2794
      fields = [constants.SF_NAME] + self.op.output_fields
2795

    
2796
    # Never ask for node or type as it's only known to the LU
2797
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
2798
      while extra in fields:
2799
        fields.remove(extra)
2800

    
2801
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
2802
    name_idx = field_idx[constants.SF_NAME]
2803

    
2804
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
2805
    data = self.rpc.call_storage_list(self.nodes,
2806
                                      self.op.storage_type, st_args,
2807
                                      self.op.name, fields)
2808

    
2809
    result = []
2810

    
2811
    for node in utils.NiceSort(self.nodes):
2812
      nresult = data[node]
2813
      if nresult.offline:
2814
        continue
2815

    
2816
      msg = nresult.fail_msg
2817
      if msg:
2818
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
2819
        continue
2820

    
2821
      rows = dict([(row[name_idx], row) for row in nresult.payload])
2822

    
2823
      for name in utils.NiceSort(rows.keys()):
2824
        row = rows[name]
2825

    
2826
        out = []
2827

    
2828
        for field in self.op.output_fields:
2829
          if field == constants.SF_NODE:
2830
            val = node
2831
          elif field == constants.SF_TYPE:
2832
            val = self.op.storage_type
2833
          elif field in field_idx:
2834
            val = row[field_idx[field]]
2835
          else:
2836
            raise errors.ParameterError(field)
2837

    
2838
          out.append(val)
2839

    
2840
        result.append(out)
2841

    
2842
    return result
2843

    
2844

    
2845
class LUModifyNodeStorage(NoHooksLU):
2846
  """Logical unit for modifying a storage volume on a node.
2847

2848
  """
2849
  _OP_REQP = ["node_name", "storage_type", "name", "changes"]
2850
  REQ_BGL = False
2851

    
2852
  def CheckArguments(self):
2853
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2854
    if node_name is None:
2855
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name,
2856
                                 errors.ECODE_NOENT)
2857

    
2858
    self.op.node_name = node_name
2859

    
2860
    storage_type = self.op.storage_type
2861
    if storage_type not in constants.VALID_STORAGE_TYPES:
2862
      raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
2863
                                 errors.ECODE_INVAL)
2864

    
2865
  def ExpandNames(self):
2866
    self.needed_locks = {
2867
      locking.LEVEL_NODE: self.op.node_name,
2868
      }
2869

    
2870
  def CheckPrereq(self):
2871
    """Check prerequisites.
2872

2873
    """
2874
    storage_type = self.op.storage_type
2875

    
2876
    try:
2877
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
2878
    except KeyError:
2879
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
2880
                                 " modified" % storage_type,
2881
                                 errors.ECODE_INVAL)
2882

    
2883
    diff = set(self.op.changes.keys()) - modifiable
2884
    if diff:
2885
      raise errors.OpPrereqError("The following fields can not be modified for"
2886
                                 " storage units of type '%s': %r" %
2887
                                 (storage_type, list(diff)),
2888
                                 errors.ECODE_INVAL)
2889

    
2890
  def Exec(self, feedback_fn):
2891
    """Computes the list of nodes and their attributes.
2892

2893
    """
2894
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
2895
    result = self.rpc.call_storage_modify(self.op.node_name,
2896
                                          self.op.storage_type, st_args,
2897
                                          self.op.name, self.op.changes)
2898
    result.Raise("Failed to modify storage unit '%s' on %s" %
2899
                 (self.op.name, self.op.node_name))
2900

    
2901

    
2902
class LUAddNode(LogicalUnit):
2903
  """Logical unit for adding node to the cluster.
2904

2905
  """
2906
  HPATH = "node-add"
2907
  HTYPE = constants.HTYPE_NODE
2908
  _OP_REQP = ["node_name"]
2909

    
2910
  def BuildHooksEnv(self):
2911
    """Build hooks env.
2912

2913
    This will run on all nodes before, and on all nodes + the new node after.
2914

2915
    """
2916
    env = {
2917
      "OP_TARGET": self.op.node_name,
2918
      "NODE_NAME": self.op.node_name,
2919
      "NODE_PIP": self.op.primary_ip,
2920
      "NODE_SIP": self.op.secondary_ip,
2921
      }
2922
    nodes_0 = self.cfg.GetNodeList()
2923
    nodes_1 = nodes_0 + [self.op.node_name, ]
2924
    return env, nodes_0, nodes_1
2925

    
2926
  def CheckPrereq(self):
2927
    """Check prerequisites.
2928

2929
    This checks:
2930
     - the new node is not already in the config
2931
     - it is resolvable
2932
     - its parameters (single/dual homed) matches the cluster
2933

2934
    Any errors are signaled by raising errors.OpPrereqError.
2935

2936
    """
2937
    node_name = self.op.node_name
2938
    cfg = self.cfg
2939

    
2940
    dns_data = utils.GetHostInfo(node_name)
2941

    
2942
    node = dns_data.name
2943
    primary_ip = self.op.primary_ip = dns_data.ip
2944
    secondary_ip = getattr(self.op, "secondary_ip", None)
2945
    if secondary_ip is None:
2946
      secondary_ip = primary_ip
2947
    if not utils.IsValidIP(secondary_ip):
2948
      raise errors.OpPrereqError("Invalid secondary IP given",
2949
                                 errors.ECODE_INVAL)
2950
    self.op.secondary_ip = secondary_ip
2951

    
2952
    node_list = cfg.GetNodeList()
2953
    if not self.op.readd and node in node_list:
2954
      raise errors.OpPrereqError("Node %s is already in the configuration" %
2955
                                 node, errors.ECODE_EXISTS)
2956
    elif self.op.readd and node not in node_list:
2957
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
2958
                                 errors.ECODE_NOENT)
2959

    
2960
    for existing_node_name in node_list:
2961
      existing_node = cfg.GetNodeInfo(existing_node_name)
2962

    
2963
      if self.op.readd and node == existing_node_name:
2964
        if (existing_node.primary_ip != primary_ip or
2965
            existing_node.secondary_ip != secondary_ip):
2966
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
2967
                                     " address configuration as before",
2968
                                     errors.ECODE_INVAL)
2969
        continue
2970

    
2971
      if (existing_node.primary_ip == primary_ip or
2972
          existing_node.secondary_ip == primary_ip or
2973
          existing_node.primary_ip == secondary_ip or
2974
          existing_node.secondary_ip == secondary_ip):
2975
        raise errors.OpPrereqError("New node ip address(es) conflict with"
2976
                                   " existing node %s" % existing_node.name,
2977
                                   errors.ECODE_NOTUNIQUE)
2978

    
2979
    # check that the type of the node (single versus dual homed) is the
2980
    # same as for the master
2981
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
2982
    master_singlehomed = myself.secondary_ip == myself.primary_ip
2983
    newbie_singlehomed = secondary_ip == primary_ip
2984
    if master_singlehomed != newbie_singlehomed:
2985
      if master_singlehomed:
2986
        raise errors.OpPrereqError("The master has no private ip but the"
2987
                                   " new node has one",
2988
                                   errors.ECODE_INVAL)
2989
      else:
2990
        raise errors.OpPrereqError("The master has a private ip but the"
2991
                                   " new node doesn't have one",
2992
                                   errors.ECODE_INVAL)
2993

    
2994
    # checks reachability
2995
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
2996
      raise errors.OpPrereqError("Node not reachable by ping",
2997
                                 errors.ECODE_ENVIRON)
2998

    
2999
    if not newbie_singlehomed:
3000
      # check reachability from my secondary ip to newbie's secondary ip
3001
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3002
                           source=myself.secondary_ip):
3003
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3004
                                   " based ping to noded port",
3005
                                   errors.ECODE_ENVIRON)
3006

    
3007
    if self.op.readd:
3008
      exceptions = [node]
3009
    else:
3010
      exceptions = []
3011

    
3012
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3013

    
3014
    if self.op.readd:
3015
      self.new_node = self.cfg.GetNodeInfo(node)
3016
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
3017
    else:
3018
      self.new_node = objects.Node(name=node,
3019
                                   primary_ip=primary_ip,
3020
                                   secondary_ip=secondary_ip,
3021
                                   master_candidate=self.master_candidate,
3022
                                   offline=False, drained=False)
3023

    
3024
  def Exec(self, feedback_fn):
3025
    """Adds the new node to the cluster.
3026

3027
    """
3028
    new_node = self.new_node
3029
    node = new_node.name
3030

    
3031
    # for re-adds, reset the offline/drained/master-candidate flags;
3032
    # we need to reset here, otherwise offline would prevent RPC calls
3033
    # later in the procedure; this also means that if the re-add
3034
    # fails, we are left with a non-offlined, broken node
3035
    if self.op.readd:
3036
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3037
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3038
      # if we demote the node, we do cleanup later in the procedure
3039
      new_node.master_candidate = self.master_candidate
3040

    
3041
    # notify the user about any possible mc promotion
3042
    if new_node.master_candidate:
3043
      self.LogInfo("Node will be a master candidate")
3044

    
3045
    # check connectivity
3046
    result = self.rpc.call_version([node])[node]
3047
    result.Raise("Can't get version information from node %s" % node)
3048
    if constants.PROTOCOL_VERSION == result.payload:
3049
      logging.info("Communication to node %s fine, sw version %s match",
3050
                   node, result.payload)
3051
    else:
3052
      raise errors.OpExecError("Version mismatch master version %s,"
3053
                               " node version %s" %
3054
                               (constants.PROTOCOL_VERSION, result.payload))
3055

    
3056
    # setup ssh on node
3057
    if self.cfg.GetClusterInfo().modify_ssh_setup:
3058
      logging.info("Copy ssh key to node %s", node)
3059
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
3060
      keyarray = []
3061
      keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
3062
                  constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
3063
                  priv_key, pub_key]
3064

    
3065
      for i in keyfiles:
3066
        keyarray.append(utils.ReadFile(i))
3067

    
3068
      result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
3069
                                      keyarray[2], keyarray[3], keyarray[4],
3070
                                      keyarray[5])
3071
      result.Raise("Cannot transfer ssh keys to the new node")
3072

    
3073
    # Add node to our /etc/hosts, and add key to known_hosts
3074
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3075
      utils.AddHostToEtcHosts(new_node.name)
3076

    
3077
    if new_node.secondary_ip != new_node.primary_ip:
3078
      result = self.rpc.call_node_has_ip_address(new_node.name,
3079
                                                 new_node.secondary_ip)
3080
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
3081
                   prereq=True, ecode=errors.ECODE_ENVIRON)
3082
      if not result.payload:
3083
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
3084
                                 " you gave (%s). Please fix and re-run this"
3085
                                 " command." % new_node.secondary_ip)
3086

    
3087
    node_verify_list = [self.cfg.GetMasterNode()]
3088
    node_verify_param = {
3089
      constants.NV_NODELIST: [node],
3090
      # TODO: do a node-net-test as well?
3091
    }
3092

    
3093
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3094
                                       self.cfg.GetClusterName())
3095
    for verifier in node_verify_list:
3096
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3097
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3098
      if nl_payload:
3099
        for failed in nl_payload:
3100
          feedback_fn("ssh/hostname verification failed"
3101
                      " (checking from %s): %s" %
3102
                      (verifier, nl_payload[failed]))
3103
        raise errors.OpExecError("ssh/hostname verification failed.")
3104

    
3105
    if self.op.readd:
3106
      _RedistributeAncillaryFiles(self)
3107
      self.context.ReaddNode(new_node)
3108
      # make sure we redistribute the config
3109
      self.cfg.Update(new_node, feedback_fn)
3110
      # and make sure the new node will not have old files around
3111
      if not new_node.master_candidate:
3112
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3113
        msg = result.fail_msg
3114
        if msg:
3115
          self.LogWarning("Node failed to demote itself from master"
3116
                          " candidate status: %s" % msg)
3117
    else:
3118
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
3119
      self.context.AddNode(new_node, self.proc.GetECId())
3120

    
3121

    
3122
class LUSetNodeParams(LogicalUnit):
3123
  """Modifies the parameters of a node.
3124

3125
  """
3126
  HPATH = "node-modify"
3127
  HTYPE = constants.HTYPE_NODE
3128
  _OP_REQP = ["node_name"]
3129
  REQ_BGL = False
3130

    
3131
  def CheckArguments(self):
3132
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
3133
    if node_name is None:
3134
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name,
3135
                                 errors.ECODE_INVAL)
3136
    self.op.node_name = node_name
3137
    _CheckBooleanOpField(self.op, 'master_candidate')
3138
    _CheckBooleanOpField(self.op, 'offline')
3139
    _CheckBooleanOpField(self.op, 'drained')
3140
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
3141
    if all_mods.count(None) == 3:
3142
      raise errors.OpPrereqError("Please pass at least one modification",
3143
                                 errors.ECODE_INVAL)
3144
    if all_mods.count(True) > 1:
3145
      raise errors.OpPrereqError("Can't set the node into more than one"
3146
                                 " state at the same time",
3147
                                 errors.ECODE_INVAL)
3148

    
3149
  def ExpandNames(self):
3150
    self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3151

    
3152
  def BuildHooksEnv(self):
3153
    """Build hooks env.
3154

3155
    This runs on the master node.
3156

3157
    """
3158
    env = {
3159
      "OP_TARGET": self.op.node_name,
3160
      "MASTER_CANDIDATE": str(self.op.master_candidate),
3161
      "OFFLINE": str(self.op.offline),
3162
      "DRAINED": str(self.op.drained),
3163
      }
3164
    nl = [self.cfg.GetMasterNode(),
3165
          self.op.node_name]
3166
    return env, nl, nl
3167

    
3168
  def CheckPrereq(self):
3169
    """Check prerequisites.
3170

3171
    This only checks the instance list against the existing names.
3172

3173
    """
3174
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3175

    
3176
    if (self.op.master_candidate is not None or
3177
        self.op.drained is not None or
3178
        self.op.offline is not None):
3179
      # we can't change the master's node flags
3180
      if self.op.node_name == self.cfg.GetMasterNode():
3181
        raise errors.OpPrereqError("The master role can be changed"
3182
                                   " only via masterfailover",
3183
                                   errors.ECODE_INVAL)
3184

    
3185
    # Boolean value that tells us whether we're offlining or draining the node
3186
    offline_or_drain = self.op.offline == True or self.op.drained == True
3187
    deoffline_or_drain = self.op.offline == False or self.op.drained == False
3188

    
3189
    if (node.master_candidate and
3190
        (self.op.master_candidate == False or offline_or_drain)):
3191
      cp_size = self.cfg.GetClusterInfo().candidate_pool_size
3192
      mc_now, mc_should, mc_max = self.cfg.GetMasterCandidateStats()
3193
      if mc_now <= cp_size:
3194
        msg = ("Not enough master candidates (desired"
3195
               " %d, new value will be %d)" % (cp_size, mc_now-1))
3196
        # Only allow forcing the operation if it's an offline/drain operation,
3197
        # and we could not possibly promote more nodes.
3198
        # FIXME: this can still lead to issues if in any way another node which
3199
        # could be promoted appears in the meantime.
3200
        if self.op.force and offline_or_drain and mc_should == mc_max:
3201
          self.LogWarning(msg)
3202
        else:
3203
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
3204

    
3205
    if (self.op.master_candidate == True and
3206
        ((node.offline and not self.op.offline == False) or
3207
         (node.drained and not self.op.drained == False))):
3208
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
3209
                                 " to master_candidate" % node.name,
3210
                                 errors.ECODE_INVAL)
3211

    
3212
    # If we're being deofflined/drained, we'll MC ourself if needed
3213
    if (deoffline_or_drain and not offline_or_drain and not
3214
        self.op.master_candidate == True and not node.master_candidate):
3215
      self.op.master_candidate = _DecideSelfPromotion(self)
3216
      if self.op.master_candidate:
3217
        self.LogInfo("Autopromoting node to master candidate")
3218

    
3219
    return
3220

    
3221
  def Exec(self, feedback_fn):
3222
    """Modifies a node.
3223

3224
    """
3225
    node = self.node
3226

    
3227
    result = []
3228
    changed_mc = False
3229

    
3230
    if self.op.offline is not None:
3231
      node.offline = self.op.offline
3232
      result.append(("offline", str(self.op.offline)))
3233
      if self.op.offline == True:
3234
        if node.master_candidate:
3235
          node.master_candidate = False
3236
          changed_mc = True
3237
          result.append(("master_candidate", "auto-demotion due to offline"))
3238
        if node.drained:
3239
          node.drained = False
3240
          result.append(("drained", "clear drained status due to offline"))
3241

    
3242
    if self.op.master_candidate is not None:
3243
      node.master_candidate = self.op.master_candidate
3244
      changed_mc = True
3245
      result.append(("master_candidate", str(self.op.master_candidate)))
3246
      if self.op.master_candidate == False:
3247
        rrc = self.rpc.call_node_demote_from_mc(node.name)
3248
        msg = rrc.fail_msg
3249
        if msg:
3250
          self.LogWarning("Node failed to demote itself: %s" % msg)
3251

    
3252
    if self.op.drained is not None:
3253
      node.drained = self.op.drained
3254
      result.append(("drained", str(self.op.drained)))
3255
      if self.op.drained == True:
3256
        if node.master_candidate:
3257
          node.master_candidate = False
3258
          changed_mc = True
3259
          result.append(("master_candidate", "auto-demotion due to drain"))
3260
          rrc = self.rpc.call_node_demote_from_mc(node.name)
3261
          msg = rrc.fail_msg
3262
          if msg:
3263
            self.LogWarning("Node failed to demote itself: %s" % msg)
3264
        if node.offline:
3265
          node.offline = False
3266
          result.append(("offline", "clear offline status due to drain"))
3267

    
3268
    # this will trigger configuration file update, if needed
3269
    self.cfg.Update(node, feedback_fn)
3270
    # this will trigger job queue propagation or cleanup
3271
    if changed_mc:
3272
      self.context.ReaddNode(node)
3273

    
3274
    return result
3275

    
3276

    
3277
class LUPowercycleNode(NoHooksLU):
3278
  """Powercycles a node.
3279

3280
  """
3281
  _OP_REQP = ["node_name", "force"]
3282
  REQ_BGL = False
3283

    
3284
  def CheckArguments(self):
3285
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
3286
    if node_name is None:
3287
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name,
3288
                                 errors.ECODE_NOENT)
3289
    self.op.node_name = node_name
3290
    if node_name == self.cfg.GetMasterNode() and not self.op.force:
3291
      raise errors.OpPrereqError("The node is the master and the force"
3292
                                 " parameter was not set",
3293
                                 errors.ECODE_INVAL)
3294

    
3295
  def ExpandNames(self):
3296
    """Locking for PowercycleNode.
3297

3298
    This is a last-resort option and shouldn't block on other
3299
    jobs. Therefore, we grab no locks.
3300

3301
    """
3302
    self.needed_locks = {}
3303

    
3304
  def CheckPrereq(self):
3305
    """Check prerequisites.
3306

3307
    This LU has no prereqs.
3308

3309
    """
3310
    pass
3311

    
3312
  def Exec(self, feedback_fn):
3313
    """Reboots a node.
3314

3315
    """
3316
    result = self.rpc.call_node_powercycle(self.op.node_name,
3317
                                           self.cfg.GetHypervisorType())
3318
    result.Raise("Failed to schedule the reboot")
3319
    return result.payload
3320

    
3321

    
3322
class LUQueryClusterInfo(NoHooksLU):
3323
  """Query cluster configuration.
3324

3325
  """
3326
  _OP_REQP = []
3327
  REQ_BGL = False
3328

    
3329
  def ExpandNames(self):
3330
    self.needed_locks = {}
3331

    
3332
  def CheckPrereq(self):
3333
    """No prerequsites needed for this LU.
3334

3335
    """
3336
    pass
3337

    
3338
  def Exec(self, feedback_fn):
3339
    """Return cluster config.
3340

3341
    """
3342
    cluster = self.cfg.GetClusterInfo()
3343
    result = {
3344
      "software_version": constants.RELEASE_VERSION,
3345
      "protocol_version": constants.PROTOCOL_VERSION,
3346
      "config_version": constants.CONFIG_VERSION,
3347
      "os_api_version": max(constants.OS_API_VERSIONS),
3348
      "export_version": constants.EXPORT_VERSION,
3349
      "architecture": (platform.architecture()[0], platform.machine()),
3350
      "name": cluster.cluster_name,
3351
      "master": cluster.master_node,
3352
      "default_hypervisor": cluster.enabled_hypervisors[0],
3353
      "enabled_hypervisors": cluster.enabled_hypervisors,
3354
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
3355
                        for hypervisor_name in cluster.enabled_hypervisors]),
3356
      "beparams": cluster.beparams,
3357
      "nicparams": cluster.nicparams,
3358
      "candidate_pool_size": cluster.candidate_pool_size,
3359
      "master_netdev": cluster.master_netdev,
3360
      "volume_group_name": cluster.volume_group_name,
3361
      "file_storage_dir": cluster.file_storage_dir,
3362
      "ctime": cluster.ctime,
3363
      "mtime": cluster.mtime,
3364
      "uuid": cluster.uuid,
3365
      "tags": list(cluster.GetTags()),
3366
      }
3367

    
3368
    return result
3369

    
3370

    
3371
class LUQueryConfigValues(NoHooksLU):
3372
  """Return configuration values.
3373

3374
  """
3375
  _OP_REQP = []
3376
  REQ_BGL = False
3377
  _FIELDS_DYNAMIC = utils.FieldSet()
3378
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
3379
                                  "watcher_pause")
3380

    
3381
  def ExpandNames(self):
3382
    self.needed_locks = {}
3383

    
3384
    _CheckOutputFields(static=self._FIELDS_STATIC,
3385
                       dynamic=self._FIELDS_DYNAMIC,
3386
                       selected=self.op.output_fields)
3387

    
3388
  def CheckPrereq(self):
3389
    """No prerequisites.
3390

3391
    """
3392
    pass
3393

    
3394
  def Exec(self, feedback_fn):
3395
    """Dump a representation of the cluster config to the standard output.
3396

3397
    """
3398
    values = []
3399
    for field in self.op.output_fields:
3400
      if field == "cluster_name":
3401
        entry = self.cfg.GetClusterName()
3402
      elif field == "master_node":
3403
        entry = self.cfg.GetMasterNode()
3404
      elif field == "drain_flag":
3405
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
3406
      elif field == "watcher_pause":
3407
        return utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
3408
      else:
3409
        raise errors.ParameterError(field)
3410
      values.append(entry)
3411
    return values
3412

    
3413

    
3414
class LUActivateInstanceDisks(NoHooksLU):
3415
  """Bring up an instance's disks.
3416

3417
  """
3418
  _OP_REQP = ["instance_name"]
3419
  REQ_BGL = False
3420

    
3421
  def ExpandNames(self):
3422
    self._ExpandAndLockInstance()
3423
    self.needed_locks[locking.LEVEL_NODE] = []
3424
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3425

    
3426
  def DeclareLocks(self, level):
3427
    if level == locking.LEVEL_NODE:
3428
      self._LockInstancesNodes()
3429

    
3430
  def CheckPrereq(self):
3431
    """Check prerequisites.
3432

3433
    This checks that the instance is in the cluster.
3434

3435
    """
3436
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3437
    assert self.instance is not None, \
3438
      "Cannot retrieve locked instance %s" % self.op.instance_name
3439
    _CheckNodeOnline(self, self.instance.primary_node)
3440
    if not hasattr(self.op, "ignore_size"):
3441
      self.op.ignore_size = False
3442

    
3443
  def Exec(self, feedback_fn):
3444
    """Activate the disks.
3445

3446
    """
3447
    disks_ok, disks_info = \
3448
              _AssembleInstanceDisks(self, self.instance,
3449
                                     ignore_size=self.op.ignore_size)
3450
    if not disks_ok:
3451
      raise errors.OpExecError("Cannot activate block devices")
3452

    
3453
    return disks_info
3454

    
3455

    
3456
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False,
3457
                           ignore_size=False):
3458
  """Prepare the block devices for an instance.
3459

3460
  This sets up the block devices on all nodes.
3461

3462
  @type lu: L{LogicalUnit}
3463
  @param lu: the logical unit on whose behalf we execute
3464
  @type instance: L{objects.Instance}
3465
  @param instance: the instance for whose disks we assemble
3466
  @type ignore_secondaries: boolean
3467
  @param ignore_secondaries: if true, errors on secondary nodes
3468
      won't result in an error return from the function
3469
  @type ignore_size: boolean
3470
  @param ignore_size: if true, the current known size of the disk
3471
      will not be used during the disk activation, useful for cases
3472
      when the size is wrong
3473
  @return: False if the operation failed, otherwise a list of
3474
      (host, instance_visible_name, node_visible_name)
3475
      with the mapping from node devices to instance devices
3476

3477
  """
3478
  device_info = []
3479
  disks_ok = True
3480
  iname = instance.name
3481
  # With the two passes mechanism we try to reduce the window of
3482
  # opportunity for the race condition of switching DRBD to primary
3483
  # before handshaking occured, but we do not eliminate it
3484

    
3485
  # The proper fix would be to wait (with some limits) until the
3486
  # connection has been made and drbd transitions from WFConnection
3487
  # into any other network-connected state (Connected, SyncTarget,
3488
  # SyncSource, etc.)
3489

    
3490
  # 1st pass, assemble on all nodes in secondary mode
3491
  for inst_disk in instance.disks:
3492
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3493
      if ignore_size:
3494
        node_disk = node_disk.Copy()
3495
        node_disk.UnsetSize()
3496
      lu.cfg.SetDiskID(node_disk, node)
3497
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
3498
      msg = result.fail_msg
3499
      if msg:
3500
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3501
                           " (is_primary=False, pass=1): %s",
3502
                           inst_disk.iv_name, node, msg)
3503
        if not ignore_secondaries:
3504
          disks_ok = False
3505

    
3506
  # FIXME: race condition on drbd migration to primary
3507

    
3508
  # 2nd pass, do only the primary node
3509
  for inst_disk in instance.disks:
3510
    dev_path = None
3511

    
3512
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3513
      if node != instance.primary_node:
3514
        continue
3515
      if ignore_size:
3516
        node_disk = node_disk.Copy()
3517
        node_disk.UnsetSize()
3518
      lu.cfg.SetDiskID(node_disk, node)
3519
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
3520
      msg = result.fail_msg
3521
      if msg:
3522
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3523
                           " (is_primary=True, pass=2): %s",
3524
                           inst_disk.iv_name, node, msg)
3525
        disks_ok = False
3526
      else:
3527
        dev_path = result.payload
3528

    
3529
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
3530

    
3531
  # leave the disks configured for the primary node
3532
  # this is a workaround that would be fixed better by
3533
  # improving the logical/physical id handling
3534
  for disk in instance.disks:
3535
    lu.cfg.SetDiskID(disk, instance.primary_node)
3536

    
3537
  return disks_ok, device_info
3538

    
3539

    
3540
def _StartInstanceDisks(lu, instance, force):
3541
  """Start the disks of an instance.
3542

3543
  """
3544
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
3545
                                           ignore_secondaries=force)
3546
  if not disks_ok:
3547
    _ShutdownInstanceDisks(lu, instance)
3548
    if force is not None and not force:
3549
      lu.proc.LogWarning("", hint="If the message above refers to a"
3550
                         " secondary node,"
3551
                         " you can retry the operation using '--force'.")
3552
    raise errors.OpExecError("Disk consistency error")
3553

    
3554

    
3555
class LUDeactivateInstanceDisks(NoHooksLU):
3556
  """Shutdown an instance's disks.
3557

3558
  """
3559
  _OP_REQP = ["instance_name"]
3560
  REQ_BGL = False
3561

    
3562
  def ExpandNames(self):
3563
    self._ExpandAndLockInstance()
3564
    self.needed_locks[locking.LEVEL_NODE] = []
3565
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3566

    
3567
  def DeclareLocks(self, level):
3568
    if level == locking.LEVEL_NODE:
3569
      self._LockInstancesNodes()
3570

    
3571
  def CheckPrereq(self):
3572
    """Check prerequisites.
3573

3574
    This checks that the instance is in the cluster.
3575

3576
    """
3577
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3578
    assert self.instance is not None, \
3579
      "Cannot retrieve locked instance %s" % self.op.instance_name
3580

    
3581
  def Exec(self, feedback_fn):
3582
    """Deactivate the disks
3583

3584
    """
3585
    instance = self.instance
3586
    _SafeShutdownInstanceDisks(self, instance)
3587

    
3588

    
3589
def _SafeShutdownInstanceDisks(lu, instance):
3590
  """Shutdown block devices of an instance.
3591

3592
  This function checks if an instance is running, before calling
3593
  _ShutdownInstanceDisks.
3594

3595
  """
3596
  pnode = instance.primary_node
3597
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
3598
  ins_l.Raise("Can't contact node %s" % pnode)
3599

    
3600
  if instance.name in ins_l.payload:
3601
    raise errors.OpExecError("Instance is running, can't shutdown"
3602
                             " block devices.")
3603

    
3604
  _ShutdownInstanceDisks(lu, instance)
3605

    
3606

    
3607
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
3608
  """Shutdown block devices of an instance.
3609

3610
  This does the shutdown on all nodes of the instance.
3611

3612
  If the ignore_primary is false, errors on the primary node are
3613
  ignored.
3614

3615
  """
3616
  all_result = True
3617
  for disk in instance.disks:
3618
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
3619
      lu.cfg.SetDiskID(top_disk, node)
3620
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
3621
      msg = result.fail_msg
3622
      if msg:
3623
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
3624
                      disk.iv_name, node, msg)
3625
        if not ignore_primary or node != instance.primary_node:
3626
          all_result = False
3627
  return all_result
3628

    
3629

    
3630
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
3631
  """Checks if a node has enough free memory.
3632

3633
  This function check if a given node has the needed amount of free
3634
  memory. In case the node has less memory or we cannot get the
3635
  information from the node, this function raise an OpPrereqError
3636
  exception.
3637

3638
  @type lu: C{LogicalUnit}
3639
  @param lu: a logical unit from which we get configuration data
3640
  @type node: C{str}
3641
  @param node: the node to check
3642
  @type reason: C{str}
3643
  @param reason: string to use in the error message
3644
  @type requested: C{int}
3645
  @param requested: the amount of memory in MiB to check for
3646
  @type hypervisor_name: C{str}
3647
  @param hypervisor_name: the hypervisor to ask for memory stats
3648
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
3649
      we cannot check the node
3650

3651
  """
3652
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
3653
  nodeinfo[node].Raise("Can't get data from node %s" % node,
3654
                       prereq=True, ecode=errors.ECODE_ENVIRON)
3655
  free_mem = nodeinfo[node].payload.get('memory_free', None)
3656
  if not isinstance(free_mem, int):
3657
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
3658
                               " was '%s'" % (node, free_mem),
3659
                               errors.ECODE_ENVIRON)
3660
  if requested > free_mem:
3661
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
3662
                               " needed %s MiB, available %s MiB" %
3663
                               (node, reason, requested, free_mem),
3664
                               errors.ECODE_NORES)
3665

    
3666

    
3667
class LUStartupInstance(LogicalUnit):
3668
  """Starts an instance.
3669

3670
  """
3671
  HPATH = "instance-start"
3672
  HTYPE = constants.HTYPE_INSTANCE
3673
  _OP_REQP = ["instance_name", "force"]
3674
  REQ_BGL = False
3675

    
3676
  def ExpandNames(self):
3677
    self._ExpandAndLockInstance()
3678

    
3679
  def BuildHooksEnv(self):
3680
    """Build hooks env.
3681

3682
    This runs on master, primary and secondary nodes of the instance.
3683

3684
    """
3685
    env = {
3686
      "FORCE": self.op.force,
3687
      }
3688
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3689
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3690
    return env, nl, nl
3691

    
3692
  def CheckPrereq(self):
3693
    """Check prerequisites.
3694

3695
    This checks that the instance is in the cluster.
3696

3697
    """
3698
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3699
    assert self.instance is not None, \
3700
      "Cannot retrieve locked instance %s" % self.op.instance_name
3701

    
3702
    # extra beparams
3703
    self.beparams = getattr(self.op, "beparams", {})
3704
    if self.beparams:
3705
      if not isinstance(self.beparams, dict):
3706
        raise errors.OpPrereqError("Invalid beparams passed: %s, expected"
3707
                                   " dict" % (type(self.beparams), ),
3708
                                   errors.ECODE_INVAL)
3709
      # fill the beparams dict
3710
      utils.ForceDictType(self.beparams, constants.BES_PARAMETER_TYPES)
3711
      self.op.beparams = self.beparams
3712

    
3713
    # extra hvparams
3714
    self.hvparams = getattr(self.op, "hvparams", {})
3715
    if self.hvparams:
3716
      if not isinstance(self.hvparams, dict):
3717
        raise errors.OpPrereqError("Invalid hvparams passed: %s, expected"
3718
                                   " dict" % (type(self.hvparams), ),
3719
                                   errors.ECODE_INVAL)
3720

    
3721
      # check hypervisor parameter syntax (locally)
3722
      cluster = self.cfg.GetClusterInfo()
3723
      utils.ForceDictType(self.hvparams, constants.HVS_PARAMETER_TYPES)
3724
      filled_hvp = objects.FillDict(cluster.hvparams[instance.hypervisor],
3725
                                    instance.hvparams)
3726
      filled_hvp.update(self.hvparams)
3727
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
3728
      hv_type.CheckParameterSyntax(filled_hvp)
3729
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
3730
      self.op.hvparams = self.hvparams
3731

    
3732
    _CheckNodeOnline(self, instance.primary_node)
3733

    
3734
    bep = self.cfg.GetClusterInfo().FillBE(instance)
3735
    # check bridges existence
3736
    _CheckInstanceBridgesExist(self, instance)
3737

    
3738
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3739
                                              instance.name,
3740
                                              instance.hypervisor)
3741
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3742
                      prereq=True, ecode=errors.ECODE_ENVIRON)
3743
    if not remote_info.payload: # not running already
3744
      _CheckNodeFreeMemory(self, instance.primary_node,
3745
                           "starting instance %s" % instance.name,
3746
                           bep[constants.BE_MEMORY], instance.hypervisor)
3747

    
3748
  def Exec(self, feedback_fn):
3749
    """Start the instance.
3750

3751
    """
3752
    instance = self.instance
3753
    force = self.op.force
3754

    
3755
    self.cfg.MarkInstanceUp(instance.name)
3756

    
3757
    node_current = instance.primary_node
3758

    
3759
    _StartInstanceDisks(self, instance, force)
3760

    
3761
    result = self.rpc.call_instance_start(node_current, instance,
3762
                                          self.hvparams, self.beparams)
3763
    msg = result.fail_msg
3764
    if msg:
3765
      _ShutdownInstanceDisks(self, instance)
3766
      raise errors.OpExecError("Could not start instance: %s" % msg)
3767

    
3768

    
3769
class LURebootInstance(LogicalUnit):
3770
  """Reboot an instance.
3771

3772
  """
3773
  HPATH = "instance-reboot"
3774
  HTYPE = constants.HTYPE_INSTANCE
3775
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
3776
  REQ_BGL = False
3777

    
3778
  def CheckArguments(self):
3779
    """Check the arguments.
3780

3781
    """
3782
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
3783
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
3784

    
3785
  def ExpandNames(self):
3786
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
3787
                                   constants.INSTANCE_REBOOT_HARD,
3788
                                   constants.INSTANCE_REBOOT_FULL]:
3789
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
3790
                                  (constants.INSTANCE_REBOOT_SOFT,
3791
                                   constants.INSTANCE_REBOOT_HARD,
3792
                                   constants.INSTANCE_REBOOT_FULL))
3793
    self._ExpandAndLockInstance()
3794

    
3795
  def BuildHooksEnv(self):
3796
    """Build hooks env.
3797

3798
    This runs on master, primary and secondary nodes of the instance.
3799

3800
    """
3801
    env = {
3802
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
3803
      "REBOOT_TYPE": self.op.reboot_type,
3804
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
3805
      }
3806
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3807
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3808
    return env, nl, nl
3809

    
3810
  def CheckPrereq(self):
3811
    """Check prerequisites.
3812

3813
    This checks that the instance is in the cluster.
3814

3815
    """
3816
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3817
    assert self.instance is not None, \
3818
      "Cannot retrieve locked instance %s" % self.op.instance_name
3819

    
3820
    _CheckNodeOnline(self, instance.primary_node)
3821

    
3822
    # check bridges existence
3823
    _CheckInstanceBridgesExist(self, instance)
3824

    
3825
  def Exec(self, feedback_fn):
3826
    """Reboot the instance.
3827

3828
    """
3829
    instance = self.instance
3830
    ignore_secondaries = self.op.ignore_secondaries
3831
    reboot_type = self.op.reboot_type
3832

    
3833
    node_current = instance.primary_node
3834

    
3835
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
3836
                       constants.INSTANCE_REBOOT_HARD]:
3837
      for disk in instance.disks:
3838
        self.cfg.SetDiskID(disk, node_current)
3839
      result = self.rpc.call_instance_reboot(node_current, instance,
3840
                                             reboot_type,
3841
                                             self.shutdown_timeout)
3842
      result.Raise("Could not reboot instance")
3843
    else:
3844
      result = self.rpc.call_instance_shutdown(node_current, instance,
3845
                                               self.shutdown_timeout)
3846
      result.Raise("Could not shutdown instance for full reboot")
3847
      _ShutdownInstanceDisks(self, instance)
3848
      _StartInstanceDisks(self, instance, ignore_secondaries)
3849
      result = self.rpc.call_instance_start(node_current, instance, None, None)
3850
      msg = result.fail_msg
3851
      if msg:
3852
        _ShutdownInstanceDisks(self, instance)
3853
        raise errors.OpExecError("Could not start instance for"
3854
                                 " full reboot: %s" % msg)
3855

    
3856
    self.cfg.MarkInstanceUp(instance.name)
3857

    
3858

    
3859
class LUShutdownInstance(LogicalUnit):
3860
  """Shutdown an instance.
3861

3862
  """
3863
  HPATH = "instance-stop"
3864
  HTYPE = constants.HTYPE_INSTANCE
3865
  _OP_REQP = ["instance_name"]
3866
  REQ_BGL = False
3867

    
3868
  def CheckArguments(self):
3869
    """Check the arguments.
3870

3871
    """
3872
    self.timeout = getattr(self.op, "timeout",
3873
                           constants.DEFAULT_SHUTDOWN_TIMEOUT)
3874

    
3875
  def ExpandNames(self):
3876
    self._ExpandAndLockInstance()
3877

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

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

3883
    """
3884
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3885
    env["TIMEOUT"] = self.timeout
3886
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3887
    return env, nl, nl
3888

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

3892
    This checks that the instance is in the cluster.
3893

3894
    """
3895
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3896
    assert self.instance is not None, \
3897
      "Cannot retrieve locked instance %s" % self.op.instance_name
3898
    _CheckNodeOnline(self, self.instance.primary_node)
3899

    
3900
  def Exec(self, feedback_fn):
3901
    """Shutdown the instance.
3902

3903
    """
3904
    instance = self.instance
3905
    node_current = instance.primary_node
3906
    timeout = self.timeout
3907
    self.cfg.MarkInstanceDown(instance.name)
3908
    result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
3909
    msg = result.fail_msg
3910
    if msg:
3911
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
3912

    
3913
    _ShutdownInstanceDisks(self, instance)
3914

    
3915

    
3916
class LUReinstallInstance(LogicalUnit):
3917
  """Reinstall an instance.
3918

3919
  """
3920
  HPATH = "instance-reinstall"
3921
  HTYPE = constants.HTYPE_INSTANCE
3922
  _OP_REQP = ["instance_name"]
3923
  REQ_BGL = False
3924

    
3925
  def ExpandNames(self):
3926
    self._ExpandAndLockInstance()
3927

    
3928
  def BuildHooksEnv(self):
3929
    """Build hooks env.
3930

3931
    This runs on master, primary and secondary nodes of the instance.
3932

3933
    """
3934
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3935
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3936
    return env, nl, nl
3937

    
3938
  def CheckPrereq(self):
3939
    """Check prerequisites.
3940

3941
    This checks that the instance is in the cluster and is not running.
3942

3943
    """
3944
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3945
    assert instance is not None, \
3946
      "Cannot retrieve locked instance %s" % self.op.instance_name
3947
    _CheckNodeOnline(self, instance.primary_node)
3948

    
3949
    if instance.disk_template == constants.DT_DISKLESS:
3950
      raise errors.OpPrereqError("Instance '%s' has no disks" %
3951
                                 self.op.instance_name,
3952
                                 errors.ECODE_INVAL)
3953
    if instance.admin_up:
3954
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
3955
                                 self.op.instance_name,
3956
                                 errors.ECODE_STATE)
3957
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3958
                                              instance.name,
3959
                                              instance.hypervisor)
3960
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3961
                      prereq=True, ecode=errors.ECODE_ENVIRON)
3962
    if remote_info.payload:
3963
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
3964
                                 (self.op.instance_name,
3965
                                  instance.primary_node),
3966
                                 errors.ECODE_STATE)
3967

    
3968
    self.op.os_type = getattr(self.op, "os_type", None)
3969
    self.op.force_variant = getattr(self.op, "force_variant", False)
3970
    if self.op.os_type is not None:
3971
      # OS verification
3972
      pnode = self.cfg.GetNodeInfo(
3973
        self.cfg.ExpandNodeName(instance.primary_node))
3974
      if pnode is None:
3975
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
3976
                                   self.op.pnode, errors.ECODE_NOENT)
3977
      result = self.rpc.call_os_get(pnode.name, self.op.os_type)
3978
      result.Raise("OS '%s' not in supported OS list for primary node %s" %
3979
                   (self.op.os_type, pnode.name),
3980
                   prereq=True, ecode=errors.ECODE_INVAL)
3981
      if not self.op.force_variant:
3982
        _CheckOSVariant(result.payload, self.op.os_type)
3983

    
3984
    self.instance = instance
3985

    
3986
  def Exec(self, feedback_fn):
3987
    """Reinstall the instance.
3988

3989
    """
3990
    inst = self.instance
3991

    
3992
    if self.op.os_type is not None:
3993
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
3994
      inst.os = self.op.os_type
3995
      self.cfg.Update(inst, feedback_fn)
3996

    
3997
    _StartInstanceDisks(self, inst, None)
3998
    try:
3999
      feedback_fn("Running the instance OS create scripts...")
4000
      # FIXME: pass debug option from opcode to backend
4001
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
4002
                                             self.op.debug_level)
4003
      result.Raise("Could not install OS for instance %s on node %s" %
4004
                   (inst.name, inst.primary_node))
4005
    finally:
4006
      _ShutdownInstanceDisks(self, inst)
4007

    
4008

    
4009
class LURecreateInstanceDisks(LogicalUnit):
4010
  """Recreate an instance's missing disks.
4011

4012
  """
4013
  HPATH = "instance-recreate-disks"
4014
  HTYPE = constants.HTYPE_INSTANCE
4015
  _OP_REQP = ["instance_name", "disks"]
4016
  REQ_BGL = False
4017

    
4018
  def CheckArguments(self):
4019
    """Check the arguments.
4020

4021
    """
4022
    if not isinstance(self.op.disks, list):
4023
      raise errors.OpPrereqError("Invalid disks parameter", errors.ECODE_INVAL)
4024
    for item in self.op.disks:
4025
      if (not isinstance(item, int) or
4026
          item < 0):
4027
        raise errors.OpPrereqError("Invalid disk specification '%s'" %
4028
                                   str(item), errors.ECODE_INVAL)
4029

    
4030
  def ExpandNames(self):
4031
    self._ExpandAndLockInstance()
4032

    
4033
  def BuildHooksEnv(self):
4034
    """Build hooks env.
4035

4036
    This runs on master, primary and secondary nodes of the instance.
4037

4038
    """
4039
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4040
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4041
    return env, nl, nl
4042

    
4043
  def CheckPrereq(self):
4044
    """Check prerequisites.
4045

4046
    This checks that the instance is in the cluster and is not running.
4047

4048
    """
4049
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4050
    assert instance is not None, \
4051
      "Cannot retrieve locked instance %s" % self.op.instance_name
4052
    _CheckNodeOnline(self, instance.primary_node)
4053

    
4054
    if instance.disk_template == constants.DT_DISKLESS:
4055
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4056
                                 self.op.instance_name, errors.ECODE_INVAL)
4057
    if instance.admin_up:
4058
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
4059
                                 self.op.instance_name, errors.ECODE_STATE)
4060
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4061
                                              instance.name,
4062
                                              instance.hypervisor)
4063
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4064
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4065
    if remote_info.payload:
4066
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
4067
                                 (self.op.instance_name,
4068
                                  instance.primary_node), errors.ECODE_STATE)
4069

    
4070
    if not self.op.disks:
4071
      self.op.disks = range(len(instance.disks))
4072
    else:
4073
      for idx in self.op.disks:
4074
        if idx >= len(instance.disks):
4075
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
4076
                                     errors.ECODE_INVAL)
4077

    
4078
    self.instance = instance
4079

    
4080
  def Exec(self, feedback_fn):
4081
    """Recreate the disks.
4082

4083
    """
4084
    to_skip = []
4085
    for idx, _ in enumerate(self.instance.disks):
4086
      if idx not in self.op.disks: # disk idx has not been passed in
4087
        to_skip.append(idx)
4088
        continue
4089

    
4090
    _CreateDisks(self, self.instance, to_skip=to_skip)
4091

    
4092

    
4093
class LURenameInstance(LogicalUnit):
4094
  """Rename an instance.
4095

4096
  """
4097
  HPATH = "instance-rename"
4098
  HTYPE = constants.HTYPE_INSTANCE
4099
  _OP_REQP = ["instance_name", "new_name"]
4100

    
4101
  def BuildHooksEnv(self):
4102
    """Build hooks env.
4103

4104
    This runs on master, primary and secondary nodes of the instance.
4105

4106
    """
4107
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4108
    env["INSTANCE_NEW_NAME"] = self.op.new_name
4109
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4110
    return env, nl, nl
4111

    
4112
  def CheckPrereq(self):
4113
    """Check prerequisites.
4114

4115
    This checks that the instance is in the cluster and is not running.
4116

4117
    """
4118
    instance = self.cfg.GetInstanceInfo(
4119
      self.cfg.ExpandInstanceName(self.op.instance_name))
4120
    if instance is None:
4121
      raise errors.OpPrereqError("Instance '%s' not known" %
4122
                                 self.op.instance_name, errors.ECODE_NOENT)
4123
    _CheckNodeOnline(self, instance.primary_node)
4124

    
4125
    if instance.admin_up:
4126
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
4127
                                 self.op.instance_name, errors.ECODE_STATE)
4128
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4129
                                              instance.name,
4130
                                              instance.hypervisor)
4131
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4132
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4133
    if remote_info.payload:
4134
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
4135
                                 (self.op.instance_name,
4136
                                  instance.primary_node), errors.ECODE_STATE)
4137
    self.instance = instance
4138

    
4139
    # new name verification
4140
    name_info = utils.GetHostInfo(self.op.new_name)
4141

    
4142
    self.op.new_name = new_name = name_info.name
4143
    instance_list = self.cfg.GetInstanceList()
4144
    if new_name in instance_list:
4145
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4146
                                 new_name, errors.ECODE_EXISTS)
4147

    
4148
    if not getattr(self.op, "ignore_ip", False):
4149
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
4150
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4151
                                   (name_info.ip, new_name),
4152
                                   errors.ECODE_NOTUNIQUE)
4153

    
4154

    
4155
  def Exec(self, feedback_fn):
4156
    """Reinstall the instance.
4157

4158
    """
4159
    inst = self.instance
4160
    old_name = inst.name
4161

    
4162
    if inst.disk_template == constants.DT_FILE:
4163
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4164

    
4165
    self.cfg.RenameInstance(inst.name, self.op.new_name)
4166
    # Change the instance lock. This is definitely safe while we hold the BGL
4167
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
4168
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
4169

    
4170
    # re-read the instance from the configuration after rename
4171
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
4172

    
4173
    if inst.disk_template == constants.DT_FILE:
4174
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4175
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
4176
                                                     old_file_storage_dir,
4177
                                                     new_file_storage_dir)
4178
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
4179
                   " (but the instance has been renamed in Ganeti)" %
4180
                   (inst.primary_node, old_file_storage_dir,
4181
                    new_file_storage_dir))
4182

    
4183
    _StartInstanceDisks(self, inst, None)
4184
    try:
4185
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
4186
                                                 old_name, self.op.debug_level)
4187
      msg = result.fail_msg
4188
      if msg:
4189
        msg = ("Could not run OS rename script for instance %s on node %s"
4190
               " (but the instance has been renamed in Ganeti): %s" %
4191
               (inst.name, inst.primary_node, msg))
4192
        self.proc.LogWarning(msg)
4193
    finally:
4194
      _ShutdownInstanceDisks(self, inst)
4195

    
4196

    
4197
class LURemoveInstance(LogicalUnit):
4198
  """Remove an instance.
4199

4200
  """
4201
  HPATH = "instance-remove"
4202
  HTYPE = constants.HTYPE_INSTANCE
4203
  _OP_REQP = ["instance_name", "ignore_failures"]
4204
  REQ_BGL = False
4205

    
4206
  def CheckArguments(self):
4207
    """Check the arguments.
4208

4209
    """
4210
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4211
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4212

    
4213
  def ExpandNames(self):
4214
    self._ExpandAndLockInstance()
4215
    self.needed_locks[locking.LEVEL_NODE] = []
4216
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4217

    
4218
  def DeclareLocks(self, level):
4219
    if level == locking.LEVEL_NODE:
4220
      self._LockInstancesNodes()
4221

    
4222
  def BuildHooksEnv(self):
4223
    """Build hooks env.
4224

4225
    This runs on master, primary and secondary nodes of the instance.
4226

4227
    """
4228
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4229
    env["SHUTDOWN_TIMEOUT"] = self.shutdown_timeout
4230
    nl = [self.cfg.GetMasterNode()]
4231
    nl_post = list(self.instance.all_nodes) + nl
4232
    return env, nl, nl_post
4233

    
4234
  def CheckPrereq(self):
4235
    """Check prerequisites.
4236

4237
    This checks that the instance is in the cluster.
4238

4239
    """
4240
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4241
    assert self.instance is not None, \
4242
      "Cannot retrieve locked instance %s" % self.op.instance_name
4243

    
4244
  def Exec(self, feedback_fn):
4245
    """Remove the instance.
4246

4247
    """
4248
    instance = self.instance
4249
    logging.info("Shutting down instance %s on node %s",
4250
                 instance.name, instance.primary_node)
4251

    
4252
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
4253
                                             self.shutdown_timeout)
4254
    msg = result.fail_msg
4255
    if msg:
4256
      if self.op.ignore_failures:
4257
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
4258
      else:
4259
        raise errors.OpExecError("Could not shutdown instance %s on"
4260
                                 " node %s: %s" %
4261
                                 (instance.name, instance.primary_node, msg))
4262

    
4263
    logging.info("Removing block devices for instance %s", instance.name)
4264

    
4265
    if not _RemoveDisks(self, instance):
4266
      if self.op.ignore_failures:
4267
        feedback_fn("Warning: can't remove instance's disks")
4268
      else:
4269
        raise errors.OpExecError("Can't remove instance's disks")
4270

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

    
4273
    self.cfg.RemoveInstance(instance.name)
4274
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
4275

    
4276

    
4277
class LUQueryInstances(NoHooksLU):
4278
  """Logical unit for querying instances.
4279

4280
  """
4281
  # pylint: disable-msg=W0142
4282
  _OP_REQP = ["output_fields", "names", "use_locking"]
4283
  REQ_BGL = False
4284
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
4285
                    "serial_no", "ctime", "mtime", "uuid"]
4286
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
4287
                                    "admin_state",
4288
                                    "disk_template", "ip", "mac", "bridge",
4289
                                    "nic_mode", "nic_link",
4290
                                    "sda_size", "sdb_size", "vcpus", "tags",
4291
                                    "network_port", "beparams",
4292
                                    r"(disk)\.(size)/([0-9]+)",
4293
                                    r"(disk)\.(sizes)", "disk_usage",
4294
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
4295
                                    r"(nic)\.(bridge)/([0-9]+)",
4296
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
4297
                                    r"(disk|nic)\.(count)",
4298
                                    "hvparams",
4299
                                    ] + _SIMPLE_FIELDS +
4300
                                  ["hv/%s" % name
4301
                                   for name in constants.HVS_PARAMETERS
4302
                                   if name not in constants.HVC_GLOBALS] +
4303
                                  ["be/%s" % name
4304
                                   for name in constants.BES_PARAMETERS])
4305
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
4306

    
4307

    
4308
  def ExpandNames(self):
4309
    _CheckOutputFields(static=self._FIELDS_STATIC,
4310
                       dynamic=self._FIELDS_DYNAMIC,
4311
                       selected=self.op.output_fields)
4312

    
4313
    self.needed_locks = {}
4314
    self.share_locks[locking.LEVEL_INSTANCE] = 1
4315
    self.share_locks[locking.LEVEL_NODE] = 1
4316

    
4317
    if self.op.names:
4318
      self.wanted = _GetWantedInstances(self, self.op.names)
4319
    else:
4320
      self.wanted = locking.ALL_SET
4321

    
4322
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
4323
    self.do_locking = self.do_node_query and self.op.use_locking
4324
    if self.do_locking:
4325
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4326
      self.needed_locks[locking.LEVEL_NODE] = []
4327
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4328

    
4329
  def DeclareLocks(self, level):
4330
    if level == locking.LEVEL_NODE and self.do_locking:
4331
      self._LockInstancesNodes()
4332

    
4333
  def CheckPrereq(self):
4334
    """Check prerequisites.
4335

4336
    """
4337
    pass
4338

    
4339
  def Exec(self, feedback_fn):
4340
    """Computes the list of nodes and their attributes.
4341

4342
    """
4343
    # pylint: disable-msg=R0912
4344
    # way too many branches here
4345
    all_info = self.cfg.GetAllInstancesInfo()
4346
    if self.wanted == locking.ALL_SET:
4347
      # caller didn't specify instance names, so ordering is not important
4348
      if self.do_locking:
4349
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
4350
      else:
4351
        instance_names = all_info.keys()
4352
      instance_names = utils.NiceSort(instance_names)
4353
    else:
4354
      # caller did specify names, so we must keep the ordering
4355
      if self.do_locking:
4356
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
4357
      else:
4358
        tgt_set = all_info.keys()
4359
      missing = set(self.wanted).difference(tgt_set)
4360
      if missing:
4361
        raise errors.OpExecError("Some instances were removed before"
4362
                                 " retrieving their data: %s" % missing)
4363
      instance_names = self.wanted
4364

    
4365
    instance_list = [all_info[iname] for iname in instance_names]
4366

    
4367
    # begin data gathering
4368

    
4369
    nodes = frozenset([inst.primary_node for inst in instance_list])
4370
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
4371

    
4372
    bad_nodes = []
4373
    off_nodes = []
4374
    if self.do_node_query:
4375
      live_data = {}
4376
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
4377
      for name in nodes:
4378
        result = node_data[name]
4379
        if result.offline:
4380
          # offline nodes will be in both lists
4381
          off_nodes.append(name)
4382
        if result.fail_msg:
4383
          bad_nodes.append(name)
4384
        else:
4385
          if result.payload:
4386
            live_data.update(result.payload)
4387
          # else no instance is alive
4388
    else:
4389
      live_data = dict([(name, {}) for name in instance_names])
4390

    
4391
    # end data gathering
4392

    
4393
    HVPREFIX = "hv/"
4394
    BEPREFIX = "be/"
4395
    output = []
4396
    cluster = self.cfg.GetClusterInfo()
4397
    for instance in instance_list:
4398
      iout = []
4399
      i_hv = cluster.FillHV(instance, skip_globals=True)
4400
      i_be = cluster.FillBE(instance)
4401
      i_nicp = [objects.FillDict(cluster.nicparams[constants.PP_DEFAULT],
4402
                                 nic.nicparams) for nic in instance.nics]
4403
      for field in self.op.output_fields:
4404
        st_match = self._FIELDS_STATIC.Matches(field)
4405
        if field in self._SIMPLE_FIELDS:
4406
          val = getattr(instance, field)
4407
        elif field == "pnode":
4408
          val = instance.primary_node
4409
        elif field == "snodes":
4410
          val = list(instance.secondary_nodes)
4411
        elif field == "admin_state":
4412
          val = instance.admin_up
4413
        elif field == "oper_state":
4414
          if instance.primary_node in bad_nodes:
4415
            val = None
4416
          else:
4417
            val = bool(live_data.get(instance.name))
4418
        elif field == "status":
4419
          if instance.primary_node in off_nodes:
4420
            val = "ERROR_nodeoffline"
4421
          elif instance.primary_node in bad_nodes:
4422
            val = "ERROR_nodedown"
4423
          else:
4424
            running = bool(live_data.get(instance.name))
4425
            if running:
4426
              if instance.admin_up:
4427
                val = "running"
4428
              else:
4429
                val = "ERROR_up"
4430
            else:
4431
              if instance.admin_up:
4432
                val = "ERROR_down"
4433
              else:
4434
                val = "ADMIN_down"
4435
        elif field == "oper_ram":
4436
          if instance.primary_node in bad_nodes:
4437
            val = None
4438
          elif instance.name in live_data:
4439
            val = live_data[instance.name].get("memory", "?")
4440
          else:
4441
            val = "-"
4442
        elif field == "vcpus":
4443
          val = i_be[constants.BE_VCPUS]
4444
        elif field == "disk_template":
4445
          val = instance.disk_template
4446
        elif field == "ip":
4447
          if instance.nics:
4448
            val = instance.nics[0].ip
4449
          else:
4450
            val = None
4451
        elif field == "nic_mode":
4452
          if instance.nics:
4453
            val = i_nicp[0][constants.NIC_MODE]
4454
          else:
4455
            val = None
4456
        elif field == "nic_link":
4457
          if instance.nics:
4458
            val = i_nicp[0][constants.NIC_LINK]
4459
          else:
4460
            val = None
4461
        elif field == "bridge":
4462
          if (instance.nics and
4463
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
4464
            val = i_nicp[0][constants.NIC_LINK]
4465
          else:
4466
            val = None
4467
        elif field == "mac":
4468
          if instance.nics:
4469
            val = instance.nics[0].mac
4470
          else:
4471
            val = None
4472
        elif field == "sda_size" or field == "sdb_size":
4473
          idx = ord(field[2]) - ord('a')
4474
          try:
4475
            val = instance.FindDisk(idx).size
4476
          except errors.OpPrereqError:
4477
            val = None
4478
        elif field == "disk_usage": # total disk usage per node
4479
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
4480
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
4481
        elif field == "tags":
4482
          val = list(instance.GetTags())
4483
        elif field == "hvparams":
4484
          val = i_hv
4485
        elif (field.startswith(HVPREFIX) and
4486
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS and
4487
              field[len(HVPREFIX):] not in constants.HVC_GLOBALS):
4488
          val = i_hv.get(field[len(HVPREFIX):], None)
4489
        elif field == "beparams":
4490
          val = i_be
4491
        elif (field.startswith(BEPREFIX) and
4492
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
4493
          val = i_be.get(field[len(BEPREFIX):], None)
4494
        elif st_match and st_match.groups():
4495
          # matches a variable list
4496
          st_groups = st_match.groups()
4497
          if st_groups and st_groups[0] == "disk":
4498
            if st_groups[1] == "count":
4499
              val = len(instance.disks)
4500
            elif st_groups[1] == "sizes":
4501
              val = [disk.size for disk in instance.disks]
4502
            elif st_groups[1] == "size":
4503
              try:
4504
                val = instance.FindDisk(st_groups[2]).size
4505
              except errors.OpPrereqError:
4506
                val = None
4507
            else:
4508
              assert False, "Unhandled disk parameter"
4509
          elif st_groups[0] == "nic":
4510
            if st_groups[1] == "count":
4511
              val = len(instance.nics)
4512
            elif st_groups[1] == "macs":
4513
              val = [nic.mac for nic in instance.nics]
4514
            elif st_groups[1] == "ips":
4515
              val = [nic.ip for nic in instance.nics]
4516
            elif st_groups[1] == "modes":
4517
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
4518
            elif st_groups[1] == "links":
4519
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
4520
            elif st_groups[1] == "bridges":
4521
              val = []
4522
              for nicp in i_nicp:
4523
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
4524
                  val.append(nicp[constants.NIC_LINK])
4525
                else:
4526
                  val.append(None)
4527
            else:
4528
              # index-based item
4529
              nic_idx = int(st_groups[2])
4530
              if nic_idx >= len(instance.nics):
4531
                val = None
4532
              else:
4533
                if st_groups[1] == "mac":
4534
                  val = instance.nics[nic_idx].mac
4535
                elif st_groups[1] == "ip":
4536
                  val = instance.nics[nic_idx].ip
4537
                elif st_groups[1] == "mode":
4538
                  val = i_nicp[nic_idx][constants.NIC_MODE]
4539
                elif st_groups[1] == "link":
4540
                  val = i_nicp[nic_idx][constants.NIC_LINK]
4541
                elif st_groups[1] == "bridge":
4542
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
4543
                  if nic_mode == constants.NIC_MODE_BRIDGED:
4544
                    val = i_nicp[nic_idx][constants.NIC_LINK]
4545
                  else:
4546
                    val = None
4547
                else:
4548
                  assert False, "Unhandled NIC parameter"
4549
          else:
4550
            assert False, ("Declared but unhandled variable parameter '%s'" %
4551
                           field)
4552
        else:
4553
          assert False, "Declared but unhandled parameter '%s'" % field
4554
        iout.append(val)
4555
      output.append(iout)
4556

    
4557
    return output
4558

    
4559

    
4560
class LUFailoverInstance(LogicalUnit):
4561
  """Failover an instance.
4562

4563
  """
4564
  HPATH = "instance-failover"
4565
  HTYPE = constants.HTYPE_INSTANCE
4566
  _OP_REQP = ["instance_name", "ignore_consistency"]
4567
  REQ_BGL = False
4568

    
4569
  def CheckArguments(self):
4570
    """Check the arguments.
4571

4572
    """
4573
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4574
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4575

    
4576
  def ExpandNames(self):
4577
    self._ExpandAndLockInstance()
4578
    self.needed_locks[locking.LEVEL_NODE] = []
4579
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4580

    
4581
  def DeclareLocks(self, level):
4582
    if level == locking.LEVEL_NODE:
4583
      self._LockInstancesNodes()
4584

    
4585
  def BuildHooksEnv(self):
4586
    """Build hooks env.
4587

4588
    This runs on master, primary and secondary nodes of the instance.
4589

4590
    """
4591
    instance = self.instance
4592
    source_node = instance.primary_node
4593
    target_node = instance.secondary_nodes[0]
4594
    env = {
4595
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
4596
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
4597
      "OLD_PRIMARY": source_node,
4598
      "OLD_SECONDARY": target_node,
4599
      "NEW_PRIMARY": target_node,
4600
      "NEW_SECONDARY": source_node,
4601
      }
4602
    env.update(_BuildInstanceHookEnvByObject(self, instance))
4603
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
4604
    nl_post = list(nl)
4605
    nl_post.append(source_node)
4606
    return env, nl, nl_post
4607

    
4608
  def CheckPrereq(self):
4609
    """Check prerequisites.
4610

4611
    This checks that the instance is in the cluster.
4612

4613
    """
4614
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4615
    assert self.instance is not None, \
4616
      "Cannot retrieve locked instance %s" % self.op.instance_name
4617

    
4618
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4619
    if instance.disk_template not in constants.DTS_NET_MIRROR:
4620
      raise errors.OpPrereqError("Instance's disk layout is not"
4621
                                 " network mirrored, cannot failover.",
4622
                                 errors.ECODE_STATE)
4623

    
4624
    secondary_nodes = instance.secondary_nodes
4625
    if not secondary_nodes:
4626
      raise errors.ProgrammerError("no secondary node but using "
4627
                                   "a mirrored disk template")
4628

    
4629
    target_node = secondary_nodes[0]
4630
    _CheckNodeOnline(self, target_node)
4631
    _CheckNodeNotDrained(self, target_node)
4632
    if instance.admin_up:
4633
      # check memory requirements on the secondary node
4634
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
4635
                           instance.name, bep[constants.BE_MEMORY],
4636
                           instance.hypervisor)
4637
    else:
4638
      self.LogInfo("Not checking memory on the secondary node as"
4639
                   " instance will not be started")
4640

    
4641
    # check bridge existance
4642
    _CheckInstanceBridgesExist(self, instance, node=target_node)
4643

    
4644
  def Exec(self, feedback_fn):
4645
    """Failover an instance.
4646

4647
    The failover is done by shutting it down on its present node and
4648
    starting it on the secondary.
4649

4650
    """
4651
    instance = self.instance
4652

    
4653
    source_node = instance.primary_node
4654
    target_node = instance.secondary_nodes[0]
4655

    
4656
    if instance.admin_up:
4657
      feedback_fn("* checking disk consistency between source and target")
4658
      for dev in instance.disks:
4659
        # for drbd, these are drbd over lvm
4660
        if not _CheckDiskConsistency(self, dev, target_node, False):
4661
          if not self.op.ignore_consistency:
4662
            raise errors.OpExecError("Disk %s is degraded on target node,"
4663
                                     " aborting failover." % dev.iv_name)
4664
    else:
4665
      feedback_fn("* not checking disk consistency as instance is not running")
4666

    
4667
    feedback_fn("* shutting down instance on source node")
4668
    logging.info("Shutting down instance %s on node %s",
4669
                 instance.name, source_node)
4670

    
4671
    result = self.rpc.call_instance_shutdown(source_node, instance,
4672
                                             self.shutdown_timeout)
4673
    msg = result.fail_msg
4674
    if msg:
4675
      if self.op.ignore_consistency:
4676
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
4677
                             " Proceeding anyway. Please make sure node"
4678
                             " %s is down. Error details: %s",
4679
                             instance.name, source_node, source_node, msg)
4680
      else:
4681
        raise errors.OpExecError("Could not shutdown instance %s on"
4682
                                 " node %s: %s" %
4683
                                 (instance.name, source_node, msg))
4684

    
4685
    feedback_fn("* deactivating the instance's disks on source node")
4686
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
4687
      raise errors.OpExecError("Can't shut down the instance's disks.")
4688

    
4689
    instance.primary_node = target_node
4690
    # distribute new instance config to the other nodes
4691
    self.cfg.Update(instance, feedback_fn)
4692

    
4693
    # Only start the instance if it's marked as up
4694
    if instance.admin_up:
4695
      feedback_fn("* activating the instance's disks on target node")
4696
      logging.info("Starting instance %s on node %s",
4697
                   instance.name, target_node)
4698

    
4699
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
4700
                                               ignore_secondaries=True)
4701
      if not disks_ok:
4702
        _ShutdownInstanceDisks(self, instance)
4703
        raise errors.OpExecError("Can't activate the instance's disks")
4704

    
4705
      feedback_fn("* starting the instance on the target node")
4706
      result = self.rpc.call_instance_start(target_node, instance, None, None)
4707
      msg = result.fail_msg
4708
      if msg:
4709
        _ShutdownInstanceDisks(self, instance)
4710
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
4711
                                 (instance.name, target_node, msg))
4712

    
4713

    
4714
class LUMigrateInstance(LogicalUnit):
4715
  """Migrate an instance.
4716

4717
  This is migration without shutting down, compared to the failover,
4718
  which is done with shutdown.
4719

4720
  """
4721
  HPATH = "instance-migrate"
4722
  HTYPE = constants.HTYPE_INSTANCE
4723
  _OP_REQP = ["instance_name", "live", "cleanup"]
4724

    
4725
  REQ_BGL = False
4726

    
4727
  def ExpandNames(self):
4728
    self._ExpandAndLockInstance()
4729

    
4730
    self.needed_locks[locking.LEVEL_NODE] = []
4731
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4732

    
4733
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
4734
                                       self.op.live, self.op.cleanup)
4735
    self.tasklets = [self._migrater]
4736

    
4737
  def DeclareLocks(self, level):
4738
    if level == locking.LEVEL_NODE:
4739
      self._LockInstancesNodes()
4740

    
4741
  def BuildHooksEnv(self):
4742
    """Build hooks env.
4743

4744
    This runs on master, primary and secondary nodes of the instance.
4745

4746
    """
4747
    instance = self._migrater.instance
4748
    source_node = instance.primary_node
4749
    target_node = instance.secondary_nodes[0]
4750
    env = _BuildInstanceHookEnvByObject(self, instance)
4751
    env["MIGRATE_LIVE"] = self.op.live
4752
    env["MIGRATE_CLEANUP"] = self.op.cleanup
4753
    env.update({
4754
        "OLD_PRIMARY": source_node,
4755
        "OLD_SECONDARY": target_node,
4756
        "NEW_PRIMARY": target_node,
4757
        "NEW_SECONDARY": source_node,
4758
        })
4759
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
4760
    nl_post = list(nl)
4761
    nl_post.append(source_node)
4762
    return env, nl, nl_post
4763

    
4764

    
4765
class LUMoveInstance(LogicalUnit):
4766
  """Move an instance by data-copying.
4767

4768
  """
4769
  HPATH = "instance-move"
4770
  HTYPE = constants.HTYPE_INSTANCE
4771
  _OP_REQP = ["instance_name", "target_node"]
4772
  REQ_BGL = False
4773

    
4774
  def CheckArguments(self):
4775
    """Check the arguments.
4776

4777
    """
4778
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4779
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4780

    
4781
  def ExpandNames(self):
4782
    self._ExpandAndLockInstance()
4783
    target_node = self.cfg.ExpandNodeName(self.op.target_node)
4784
    if target_node is None:
4785
      raise errors.OpPrereqError("Node '%s' not known" %
4786
                                  self.op.target_node, errors.ECODE_NOENT)
4787
    self.op.target_node = target_node
4788
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
4789
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4790

    
4791
  def DeclareLocks(self, level):
4792
    if level == locking.LEVEL_NODE:
4793
      self._LockInstancesNodes(primary_only=True)
4794

    
4795
  def BuildHooksEnv(self):
4796
    """Build hooks env.
4797

4798
    This runs on master, primary and secondary nodes of the instance.
4799

4800
    """
4801
    env = {
4802
      "TARGET_NODE": self.op.target_node,
4803
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
4804
      }
4805
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4806
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
4807
                                       self.op.target_node]
4808
    return env, nl, nl
4809

    
4810
  def CheckPrereq(self):
4811
    """Check prerequisites.
4812

4813
    This checks that the instance is in the cluster.
4814

4815
    """
4816
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4817
    assert self.instance is not None, \
4818
      "Cannot retrieve locked instance %s" % self.op.instance_name
4819

    
4820
    node = self.cfg.GetNodeInfo(self.op.target_node)
4821
    assert node is not None, \
4822
      "Cannot retrieve locked node %s" % self.op.target_node
4823

    
4824
    self.target_node = target_node = node.name
4825

    
4826
    if target_node == instance.primary_node:
4827
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
4828
                                 (instance.name, target_node),
4829
                                 errors.ECODE_STATE)
4830

    
4831
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4832

    
4833
    for idx, dsk in enumerate(instance.disks):
4834
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
4835
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
4836
                                   " cannot copy" % idx, errors.ECODE_STATE)
4837

    
4838
    _CheckNodeOnline(self, target_node)
4839
    _CheckNodeNotDrained(self, target_node)
4840

    
4841
    if instance.admin_up:
4842
      # check memory requirements on the secondary node
4843
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
4844
                           instance.name, bep[constants.BE_MEMORY],
4845
                           instance.hypervisor)
4846
    else:
4847
      self.LogInfo("Not checking memory on the secondary node as"
4848
                   " instance will not be started")
4849

    
4850
    # check bridge existance
4851
    _CheckInstanceBridgesExist(self, instance, node=target_node)
4852

    
4853
  def Exec(self, feedback_fn):
4854
    """Move an instance.
4855

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

4859
    """
4860
    instance = self.instance
4861

    
4862
    source_node = instance.primary_node
4863
    target_node = self.target_node
4864

    
4865
    self.LogInfo("Shutting down instance %s on source node %s",
4866
                 instance.name, source_node)
4867

    
4868
    result = self.rpc.call_instance_shutdown(source_node, instance,
4869
                                             self.shutdown_timeout)
4870
    msg = result.fail_msg
4871
    if msg:
4872
      if self.op.ignore_consistency:
4873
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
4874
                             " Proceeding anyway. Please make sure node"
4875
                             " %s is down. Error details: %s",
4876
                             instance.name, source_node, source_node, msg)
4877
      else:
4878
        raise errors.OpExecError("Could not shutdown instance %s on"
4879
                                 " node %s: %s" %
4880
                                 (instance.name, source_node, msg))
4881

    
4882
    # create the target disks
4883
    try:
4884
      _CreateDisks(self, instance, target_node=target_node)
4885
    except errors.OpExecError:
4886
      self.LogWarning("Device creation failed, reverting...")
4887
      try:
4888
        _RemoveDisks(self, instance, target_node=target_node)
4889
      finally:
4890
        self.cfg.ReleaseDRBDMinors(instance.name)
4891
        raise
4892

    
4893
    cluster_name = self.cfg.GetClusterInfo().cluster_name
4894

    
4895
    errs = []
4896
    # activate, get path, copy the data over
4897
    for idx, disk in enumerate(instance.disks):
4898
      self.LogInfo("Copying data for disk %d", idx)
4899
      result = self.rpc.call_blockdev_assemble(target_node, disk,
4900
                                               instance.name, True)
4901
      if result.fail_msg:
4902
        self.LogWarning("Can't assemble newly created disk %d: %s",
4903
                        idx, result.fail_msg)
4904
        errs.append(result.fail_msg)
4905
        break
4906
      dev_path = result.payload
4907
      result = self.rpc.call_blockdev_export(source_node, disk,
4908
                                             target_node, dev_path,
4909
                                             cluster_name)
4910
      if result.fail_msg:
4911
        self.LogWarning("Can't copy data over for disk %d: %s",
4912
                        idx, result.fail_msg)
4913
        errs.append(result.fail_msg)
4914
        break
4915

    
4916
    if errs:
4917
      self.LogWarning("Some disks failed to copy, aborting")
4918
      try:
4919
        _RemoveDisks(self, instance, target_node=target_node)
4920
      finally:
4921
        self.cfg.ReleaseDRBDMinors(instance.name)
4922
        raise errors.OpExecError("Errors during disk copy: %s" %
4923
                                 (",".join(errs),))
4924

    
4925
    instance.primary_node = target_node
4926
    self.cfg.Update(instance, feedback_fn)
4927

    
4928
    self.LogInfo("Removing the disks on the original node")
4929
    _RemoveDisks(self, instance, target_node=source_node)
4930

    
4931
    # Only start the instance if it's marked as up
4932
    if instance.admin_up:
4933
      self.LogInfo("Starting instance %s on node %s",
4934
                   instance.name, target_node)
4935

    
4936
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
4937
                                           ignore_secondaries=True)
4938
      if not disks_ok:
4939
        _ShutdownInstanceDisks(self, instance)
4940
        raise errors.OpExecError("Can't activate the instance's disks")
4941

    
4942
      result = self.rpc.call_instance_start(target_node, instance, None, None)
4943
      msg = result.fail_msg
4944
      if msg:
4945
        _ShutdownInstanceDisks(self, instance)
4946
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
4947
                                 (instance.name, target_node, msg))
4948

    
4949

    
4950
class LUMigrateNode(LogicalUnit):
4951
  """Migrate all instances from a node.
4952

4953
  """
4954
  HPATH = "node-migrate"
4955
  HTYPE = constants.HTYPE_NODE
4956
  _OP_REQP = ["node_name", "live"]
4957
  REQ_BGL = False
4958

    
4959
  def ExpandNames(self):
4960
    self.op.node_name = self.cfg.ExpandNodeName(self.op.node_name)
4961
    if self.op.node_name is None:
4962
      raise errors.OpPrereqError("Node '%s' not known" % self.op.node_name,
4963
                                 errors.ECODE_NOENT)
4964

    
4965
    self.needed_locks = {
4966
      locking.LEVEL_NODE: [self.op.node_name],
4967
      }
4968

    
4969
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4970

    
4971
    # Create tasklets for migrating instances for all instances on this node
4972
    names = []
4973
    tasklets = []
4974

    
4975
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
4976
      logging.debug("Migrating instance %s", inst.name)
4977
      names.append(inst.name)
4978

    
4979
      tasklets.append(TLMigrateInstance(self, inst.name, self.op.live, False))
4980

    
4981
    self.tasklets = tasklets
4982

    
4983
    # Declare instance locks
4984
    self.needed_locks[locking.LEVEL_INSTANCE] = names
4985

    
4986
  def DeclareLocks(self, level):
4987
    if level == locking.LEVEL_NODE:
4988
      self._LockInstancesNodes()
4989

    
4990
  def BuildHooksEnv(self):
4991
    """Build hooks env.
4992

4993
    This runs on the master, the primary and all the secondaries.
4994

4995
    """
4996
    env = {
4997
      "NODE_NAME": self.op.node_name,
4998
      }
4999

    
5000
    nl = [self.cfg.GetMasterNode()]
5001

    
5002
    return (env, nl, nl)
5003

    
5004

    
5005
class TLMigrateInstance(Tasklet):
5006
  def __init__(self, lu, instance_name, live, cleanup):
5007
    """Initializes this class.
5008

5009
    """
5010
    Tasklet.__init__(self, lu)
5011

    
5012
    # Parameters
5013
    self.instance_name = instance_name
5014
    self.live = live
5015
    self.cleanup = cleanup
5016

    
5017
  def CheckPrereq(self):
5018
    """Check prerequisites.
5019

5020
    This checks that the instance is in the cluster.
5021

5022
    """
5023
    instance = self.cfg.GetInstanceInfo(
5024
      self.cfg.ExpandInstanceName(self.instance_name))
5025
    if instance is None:
5026
      raise errors.OpPrereqError("Instance '%s' not known" %
5027
                                 self.instance_name, errors.ECODE_NOENT)
5028

    
5029
    if instance.disk_template != constants.DT_DRBD8:
5030
      raise errors.OpPrereqError("Instance's disk layout is not"
5031
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5032

    
5033
    secondary_nodes = instance.secondary_nodes
5034
    if not secondary_nodes:
5035
      raise errors.ConfigurationError("No secondary node but using"
5036
                                      " drbd8 disk template")
5037

    
5038
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5039

    
5040
    target_node = secondary_nodes[0]
5041
    # check memory requirements on the secondary node
5042
    _CheckNodeFreeMemory(self, target_node, "migrating instance %s" %
5043
                         instance.name, i_be[constants.BE_MEMORY],
5044
                         instance.hypervisor)
5045

    
5046
    # check bridge existance
5047
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5048

    
5049
    if not self.cleanup:
5050
      _CheckNodeNotDrained(self, target_node)
5051
      result = self.rpc.call_instance_migratable(instance.primary_node,
5052
                                                 instance)
5053
      result.Raise("Can't migrate, please use failover",
5054
                   prereq=True, ecode=errors.ECODE_STATE)
5055

    
5056
    self.instance = instance
5057

    
5058
  def _WaitUntilSync(self):
5059
    """Poll with custom rpc for disk sync.
5060

5061
    This uses our own step-based rpc call.
5062

5063
    """
5064
    self.feedback_fn("* wait until resync is done")
5065
    all_done = False
5066
    while not all_done:
5067
      all_done = True
5068
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
5069
                                            self.nodes_ip,
5070
                                            self.instance.disks)
5071
      min_percent = 100
5072
      for node, nres in result.items():
5073
        nres.Raise("Cannot resync disks on node %s" % node)
5074
        node_done, node_percent = nres.payload
5075
        all_done = all_done and node_done
5076
        if node_percent is not None:
5077
          min_percent = min(min_percent, node_percent)
5078
      if not all_done:
5079
        if min_percent < 100:
5080
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
5081
        time.sleep(2)
5082

    
5083
  def _EnsureSecondary(self, node):
5084
    """Demote a node to secondary.
5085

5086
    """
5087
    self.feedback_fn("* switching node %s to secondary mode" % node)
5088

    
5089
    for dev in self.instance.disks:
5090
      self.cfg.SetDiskID(dev, node)
5091

    
5092
    result = self.rpc.call_blockdev_close(node, self.instance.name,
5093
                                          self.instance.disks)
5094
    result.Raise("Cannot change disk to secondary on node %s" % node)
5095

    
5096
  def _GoStandalone(self):
5097
    """Disconnect from the network.
5098

5099
    """
5100
    self.feedback_fn("* changing into standalone mode")
5101
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
5102
                                               self.instance.disks)
5103
    for node, nres in result.items():
5104
      nres.Raise("Cannot disconnect disks node %s" % node)
5105

    
5106
  def _GoReconnect(self, multimaster):
5107
    """Reconnect to the network.
5108

5109
    """
5110
    if multimaster:
5111
      msg = "dual-master"
5112
    else:
5113
      msg = "single-master"
5114
    self.feedback_fn("* changing disks into %s mode" % msg)
5115
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
5116
                                           self.instance.disks,
5117
                                           self.instance.name, multimaster)
5118
    for node, nres in result.items():
5119
      nres.Raise("Cannot change disks config on node %s" % node)
5120

    
5121
  def _ExecCleanup(self):
5122
    """Try to cleanup after a failed migration.
5123

5124
    The cleanup is done by:
5125
      - check that the instance is running only on one node
5126
        (and update the config if needed)
5127
      - change disks on its secondary node to secondary
5128
      - wait until disks are fully synchronized
5129
      - disconnect from the network
5130
      - change disks into single-master mode
5131
      - wait again until disks are fully synchronized
5132

5133
    """
5134
    instance = self.instance
5135
    target_node = self.target_node
5136
    source_node = self.source_node
5137

    
5138
    # check running on only one node
5139
    self.feedback_fn("* checking where the instance actually runs"
5140
                     " (if this hangs, the hypervisor might be in"
5141
                     " a bad state)")
5142
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
5143
    for node, result in ins_l.items():
5144
      result.Raise("Can't contact node %s" % node)
5145

    
5146
    runningon_source = instance.name in ins_l[source_node].payload
5147
    runningon_target = instance.name in ins_l[target_node].payload
5148

    
5149
    if runningon_source and runningon_target:
5150
      raise errors.OpExecError("Instance seems to be running on two nodes,"
5151
                               " or the hypervisor is confused. You will have"
5152
                               " to ensure manually that it runs only on one"
5153
                               " and restart this operation.")
5154

    
5155
    if not (runningon_source or runningon_target):
5156
      raise errors.OpExecError("Instance does not seem to be running at all."
5157
                               " In this case, it's safer to repair by"
5158
                               " running 'gnt-instance stop' to ensure disk"
5159
                               " shutdown, and then restarting it.")
5160

    
5161
    if runningon_target:
5162
      # the migration has actually succeeded, we need to update the config
5163
      self.feedback_fn("* instance running on secondary node (%s),"
5164
                       " updating config" % target_node)
5165
      instance.primary_node = target_node
5166
      self.cfg.Update(instance, self.feedback_fn)
5167
      demoted_node = source_node
5168
    else:
5169
      self.feedback_fn("* instance confirmed to be running on its"
5170
                       " primary node (%s)" % source_node)
5171
      demoted_node = target_node
5172

    
5173
    self._EnsureSecondary(demoted_node)
5174
    try:
5175
      self._WaitUntilSync()
5176
    except errors.OpExecError:
5177
      # we ignore here errors, since if the device is standalone, it
5178
      # won't be able to sync
5179
      pass
5180
    self._GoStandalone()
5181
    self._GoReconnect(False)
5182
    self._WaitUntilSync()
5183

    
5184
    self.feedback_fn("* done")
5185

    
5186
  def _RevertDiskStatus(self):
5187
    """Try to revert the disk status after a failed migration.
5188

5189
    """
5190
    target_node = self.target_node
5191
    try:
5192
      self._EnsureSecondary(target_node)
5193
      self._GoStandalone()
5194
      self._GoReconnect(False)
5195
      self._WaitUntilSync()
5196
    except errors.OpExecError, err:
5197
      self.lu.LogWarning("Migration failed and I can't reconnect the"
5198
                         " drives: error '%s'\n"
5199
                         "Please look and recover the instance status" %
5200
                         str(err))
5201

    
5202
  def _AbortMigration(self):
5203
    """Call the hypervisor code to abort a started migration.
5204

5205
    """
5206
    instance = self.instance
5207
    target_node = self.target_node
5208
    migration_info = self.migration_info
5209

    
5210
    abort_result = self.rpc.call_finalize_migration(target_node,
5211
                                                    instance,
5212
                                                    migration_info,
5213
                                                    False)
5214
    abort_msg = abort_result.fail_msg
5215
    if abort_msg:
5216
      logging.error("Aborting migration failed on target node %s: %s",
5217
                    target_node, abort_msg)
5218
      # Don't raise an exception here, as we stil have to try to revert the
5219
      # disk status, even if this step failed.
5220

    
5221
  def _ExecMigration(self):
5222
    """Migrate an instance.
5223

5224
    The migrate is done by:
5225
      - change the disks into dual-master mode
5226
      - wait until disks are fully synchronized again
5227
      - migrate the instance
5228
      - change disks on the new secondary node (the old primary) to secondary
5229
      - wait until disks are fully synchronized
5230
      - change disks into single-master mode
5231

5232
    """
5233
    instance = self.instance
5234
    target_node = self.target_node
5235
    source_node = self.source_node
5236

    
5237
    self.feedback_fn("* checking disk consistency between source and target")
5238
    for dev in instance.disks:
5239
      if not _CheckDiskConsistency(self, dev, target_node, False):
5240
        raise errors.OpExecError("Disk %s is degraded or not fully"
5241
                                 " synchronized on target node,"
5242
                                 " aborting migrate." % dev.iv_name)
5243

    
5244
    # First get the migration information from the remote node
5245
    result = self.rpc.call_migration_info(source_node, instance)
5246
    msg = result.fail_msg
5247
    if msg:
5248
      log_err = ("Failed fetching source migration information from %s: %s" %
5249
                 (source_node, msg))
5250
      logging.error(log_err)
5251
      raise errors.OpExecError(log_err)
5252

    
5253
    self.migration_info = migration_info = result.payload
5254

    
5255
    # Then switch the disks to master/master mode
5256
    self._EnsureSecondary(target_node)
5257
    self._GoStandalone()
5258
    self._GoReconnect(True)
5259
    self._WaitUntilSync()
5260

    
5261
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
5262
    result = self.rpc.call_accept_instance(target_node,
5263
                                           instance,
5264
                                           migration_info,
5265
                                           self.nodes_ip[target_node])
5266

    
5267
    msg = result.fail_msg
5268
    if msg:
5269
      logging.error("Instance pre-migration failed, trying to revert"
5270
                    " disk status: %s", msg)
5271
      self.feedback_fn("Pre-migration failed, aborting")
5272
      self._AbortMigration()
5273
      self._RevertDiskStatus()
5274
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
5275
                               (instance.name, msg))
5276

    
5277
    self.feedback_fn("* migrating instance to %s" % target_node)
5278
    time.sleep(10)
5279
    result = self.rpc.call_instance_migrate(source_node, instance,
5280
                                            self.nodes_ip[target_node],
5281
                                            self.live)
5282
    msg = result.fail_msg
5283
    if msg:
5284
      logging.error("Instance migration failed, trying to revert"
5285
                    " disk status: %s", msg)
5286
      self.feedback_fn("Migration failed, aborting")
5287
      self._AbortMigration()
5288
      self._RevertDiskStatus()
5289
      raise errors.OpExecError("Could not migrate instance %s: %s" %
5290
                               (instance.name, msg))
5291
    time.sleep(10)
5292

    
5293
    instance.primary_node = target_node
5294
    # distribute new instance config to the other nodes
5295
    self.cfg.Update(instance, self.feedback_fn)
5296

    
5297
    result = self.rpc.call_finalize_migration(target_node,
5298
                                              instance,
5299
                                              migration_info,
5300
                                              True)
5301
    msg = result.fail_msg
5302
    if msg:
5303
      logging.error("Instance migration succeeded, but finalization failed:"
5304
                    " %s", msg)
5305
      raise errors.OpExecError("Could not finalize instance migration: %s" %
5306
                               msg)
5307

    
5308
    self._EnsureSecondary(source_node)
5309
    self._WaitUntilSync()
5310
    self._GoStandalone()
5311
    self._GoReconnect(False)
5312
    self._WaitUntilSync()
5313

    
5314
    self.feedback_fn("* done")
5315

    
5316
  def Exec(self, feedback_fn):
5317
    """Perform the migration.
5318

5319
    """
5320
    feedback_fn("Migrating instance %s" % self.instance.name)
5321

    
5322
    self.feedback_fn = feedback_fn
5323

    
5324
    self.source_node = self.instance.primary_node
5325
    self.target_node = self.instance.secondary_nodes[0]
5326
    self.all_nodes = [self.source_node, self.target_node]
5327
    self.nodes_ip = {
5328
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
5329
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
5330
      }
5331

    
5332
    if self.cleanup:
5333
      return self._ExecCleanup()
5334
    else:
5335
      return self._ExecMigration()
5336

    
5337

    
5338
def _CreateBlockDev(lu, node, instance, device, force_create,
5339
                    info, force_open):
5340
  """Create a tree of block devices on a given node.
5341

5342
  If this device type has to be created on secondaries, create it and
5343
  all its children.
5344

5345
  If not, just recurse to children keeping the same 'force' value.
5346

5347
  @param lu: the lu on whose behalf we execute
5348
  @param node: the node on which to create the device
5349
  @type instance: L{objects.Instance}
5350
  @param instance: the instance which owns the device
5351
  @type device: L{objects.Disk}
5352
  @param device: the device to create
5353
  @type force_create: boolean
5354
  @param force_create: whether to force creation of this device; this
5355
      will be change to True whenever we find a device which has
5356
      CreateOnSecondary() attribute
5357
  @param info: the extra 'metadata' we should attach to the device
5358
      (this will be represented as a LVM tag)
5359
  @type force_open: boolean
5360
  @param force_open: this parameter will be passes to the
5361
      L{backend.BlockdevCreate} function where it specifies
5362
      whether we run on primary or not, and it affects both
5363
      the child assembly and the device own Open() execution
5364

5365
  """
5366
  if device.CreateOnSecondary():
5367
    force_create = True
5368

    
5369
  if device.children:
5370
    for child in device.children:
5371
      _CreateBlockDev(lu, node, instance, child, force_create,
5372
                      info, force_open)
5373

    
5374
  if not force_create:
5375
    return
5376

    
5377
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
5378

    
5379

    
5380
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
5381
  """Create a single block device on a given node.
5382

5383
  This will not recurse over children of the device, so they must be
5384
  created in advance.
5385

5386
  @param lu: the lu on whose behalf we execute
5387
  @param node: the node on which to create the device
5388
  @type instance: L{objects.Instance}
5389
  @param instance: the instance which owns the device
5390
  @type device: L{objects.Disk}
5391
  @param device: the device to create
5392
  @param info: the extra 'metadata' we should attach to the device
5393
      (this will be represented as a LVM tag)
5394
  @type force_open: boolean
5395
  @param force_open: this parameter will be passes to the
5396
      L{backend.BlockdevCreate} function where it specifies
5397
      whether we run on primary or not, and it affects both
5398
      the child assembly and the device own Open() execution
5399

5400
  """
5401
  lu.cfg.SetDiskID(device, node)
5402
  result = lu.rpc.call_blockdev_create(node, device, device.size,
5403
                                       instance.name, force_open, info)
5404
  result.Raise("Can't create block device %s on"
5405
               " node %s for instance %s" % (device, node, instance.name))
5406
  if device.physical_id is None:
5407
    device.physical_id = result.payload
5408

    
5409

    
5410
def _GenerateUniqueNames(lu, exts):
5411
  """Generate a suitable LV name.
5412

5413
  This will generate a logical volume name for the given instance.
5414

5415
  """
5416
  results = []
5417
  for val in exts:
5418
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
5419
    results.append("%s%s" % (new_id, val))
5420
  return results
5421

    
5422

    
5423
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
5424
                         p_minor, s_minor):
5425
  """Generate a drbd8 device complete with its children.
5426

5427
  """
5428
  port = lu.cfg.AllocatePort()
5429
  vgname = lu.cfg.GetVGName()
5430
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
5431
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
5432
                          logical_id=(vgname, names[0]))
5433
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
5434
                          logical_id=(vgname, names[1]))
5435
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
5436
                          logical_id=(primary, secondary, port,
5437
                                      p_minor, s_minor,
5438
                                      shared_secret),
5439
                          children=[dev_data, dev_meta],
5440
                          iv_name=iv_name)
5441
  return drbd_dev
5442

    
5443

    
5444
def _GenerateDiskTemplate(lu, template_name,
5445
                          instance_name, primary_node,
5446
                          secondary_nodes, disk_info,
5447
                          file_storage_dir, file_driver,
5448
                          base_index):
5449
  """Generate the entire disk layout for a given template type.
5450

5451
  """
5452
  #TODO: compute space requirements
5453

    
5454
  vgname = lu.cfg.GetVGName()
5455
  disk_count = len(disk_info)
5456
  disks = []
5457
  if template_name == constants.DT_DISKLESS:
5458
    pass
5459
  elif template_name == constants.DT_PLAIN:
5460
    if len(secondary_nodes) != 0:
5461
      raise errors.ProgrammerError("Wrong template configuration")
5462

    
5463
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5464
                                      for i in range(disk_count)])
5465
    for idx, disk in enumerate(disk_info):
5466
      disk_index = idx + base_index
5467
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
5468
                              logical_id=(vgname, names[idx]),
5469
                              iv_name="disk/%d" % disk_index,
5470
                              mode=disk["mode"])
5471
      disks.append(disk_dev)
5472
  elif template_name == constants.DT_DRBD8:
5473
    if len(secondary_nodes) != 1:
5474
      raise errors.ProgrammerError("Wrong template configuration")
5475
    remote_node = secondary_nodes[0]
5476
    minors = lu.cfg.AllocateDRBDMinor(
5477
      [primary_node, remote_node] * len(disk_info), instance_name)
5478

    
5479
    names = []
5480
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5481
                                               for i in range(disk_count)]):
5482
      names.append(lv_prefix + "_data")
5483
      names.append(lv_prefix + "_meta")
5484
    for idx, disk in enumerate(disk_info):
5485
      disk_index = idx + base_index
5486
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
5487
                                      disk["size"], names[idx*2:idx*2+2],
5488
                                      "disk/%d" % disk_index,
5489
                                      minors[idx*2], minors[idx*2+1])
5490
      disk_dev.mode = disk["mode"]
5491
      disks.append(disk_dev)
5492
  elif template_name == constants.DT_FILE:
5493
    if len(secondary_nodes) != 0:
5494
      raise errors.ProgrammerError("Wrong template configuration")
5495

    
5496
    for idx, disk in enumerate(disk_info):
5497
      disk_index = idx + base_index
5498
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
5499
                              iv_name="disk/%d" % disk_index,
5500
                              logical_id=(file_driver,
5501
                                          "%s/disk%d" % (file_storage_dir,
5502
                                                         disk_index)),
5503
                              mode=disk["mode"])
5504
      disks.append(disk_dev)
5505
  else:
5506
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
5507
  return disks
5508

    
5509

    
5510
def _GetInstanceInfoText(instance):
5511
  """Compute that text that should be added to the disk's metadata.
5512

5513
  """
5514
  return "originstname+%s" % instance.name
5515

    
5516

    
5517
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
5518
  """Create all disks for an instance.
5519

5520
  This abstracts away some work from AddInstance.
5521

5522
  @type lu: L{LogicalUnit}
5523
  @param lu: the logical unit on whose behalf we execute
5524
  @type instance: L{objects.Instance}
5525
  @param instance: the instance whose disks we should create
5526
  @type to_skip: list
5527
  @param to_skip: list of indices to skip
5528
  @type target_node: string
5529
  @param target_node: if passed, overrides the target node for creation
5530
  @rtype: boolean
5531
  @return: the success of the creation
5532

5533
  """
5534
  info = _GetInstanceInfoText(instance)
5535
  if target_node is None:
5536
    pnode = instance.primary_node
5537
    all_nodes = instance.all_nodes
5538
  else:
5539
    pnode = target_node
5540
    all_nodes = [pnode]
5541

    
5542
  if instance.disk_template == constants.DT_FILE:
5543
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
5544
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
5545

    
5546
    result.Raise("Failed to create directory '%s' on"
5547
                 " node %s" % (file_storage_dir, pnode))
5548

    
5549
  # Note: this needs to be kept in sync with adding of disks in
5550
  # LUSetInstanceParams
5551
  for idx, device in enumerate(instance.disks):
5552
    if to_skip and idx in to_skip:
5553
      continue
5554
    logging.info("Creating volume %s for instance %s",
5555
                 device.iv_name, instance.name)
5556
    #HARDCODE
5557
    for node in all_nodes:
5558
      f_create = node == pnode
5559
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
5560

    
5561

    
5562
def _RemoveDisks(lu, instance, target_node=None):
5563
  """Remove all disks for an instance.
5564

5565
  This abstracts away some work from `AddInstance()` and
5566
  `RemoveInstance()`. Note that in case some of the devices couldn't
5567
  be removed, the removal will continue with the other ones (compare
5568
  with `_CreateDisks()`).
5569

5570
  @type lu: L{LogicalUnit}
5571
  @param lu: the logical unit on whose behalf we execute
5572
  @type instance: L{objects.Instance}
5573
  @param instance: the instance whose disks we should remove
5574
  @type target_node: string
5575
  @param target_node: used to override the node on which to remove the disks
5576
  @rtype: boolean
5577
  @return: the success of the removal
5578

5579
  """
5580
  logging.info("Removing block devices for instance %s", instance.name)
5581

    
5582
  all_result = True
5583
  for device in instance.disks:
5584
    if target_node:
5585
      edata = [(target_node, device)]
5586
    else:
5587
      edata = device.ComputeNodeTree(instance.primary_node)
5588
    for node, disk in edata:
5589
      lu.cfg.SetDiskID(disk, node)
5590
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
5591
      if msg:
5592
        lu.LogWarning("Could not remove block device %s on node %s,"
5593
                      " continuing anyway: %s", device.iv_name, node, msg)
5594
        all_result = False
5595

    
5596
  if instance.disk_template == constants.DT_FILE:
5597
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
5598
    if target_node:
5599
      tgt = target_node
5600
    else:
5601
      tgt = instance.primary_node
5602
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
5603
    if result.fail_msg:
5604
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
5605
                    file_storage_dir, instance.primary_node, result.fail_msg)
5606
      all_result = False
5607

    
5608
  return all_result
5609

    
5610

    
5611
def _ComputeDiskSize(disk_template, disks):
5612
  """Compute disk size requirements in the volume group
5613

5614
  """
5615
  # Required free disk space as a function of disk and swap space
5616
  req_size_dict = {
5617
    constants.DT_DISKLESS: None,
5618
    constants.DT_PLAIN: sum(d["size"] for d in disks),
5619
    # 128 MB are added for drbd metadata for each disk
5620
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
5621
    constants.DT_FILE: None,
5622
  }
5623

    
5624
  if disk_template not in req_size_dict:
5625
    raise errors.ProgrammerError("Disk template '%s' size requirement"
5626
                                 " is unknown" %  disk_template)
5627

    
5628
  return req_size_dict[disk_template]
5629

    
5630

    
5631
def _CheckHVParams(lu, nodenames, hvname, hvparams):
5632
  """Hypervisor parameter validation.
5633

5634
  This function abstract the hypervisor parameter validation to be
5635
  used in both instance create and instance modify.
5636

5637
  @type lu: L{LogicalUnit}
5638
  @param lu: the logical unit for which we check
5639
  @type nodenames: list
5640
  @param nodenames: the list of nodes on which we should check
5641
  @type hvname: string
5642
  @param hvname: the name of the hypervisor we should use
5643
  @type hvparams: dict
5644
  @param hvparams: the parameters which we need to check
5645
  @raise errors.OpPrereqError: if the parameters are not valid
5646

5647
  """
5648
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
5649
                                                  hvname,
5650
                                                  hvparams)
5651
  for node in nodenames:
5652
    info = hvinfo[node]
5653
    if info.offline:
5654
      continue
5655
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
5656

    
5657

    
5658
class LUCreateInstance(LogicalUnit):
5659
  """Create an instance.
5660

5661
  """
5662
  HPATH = "instance-add"
5663
  HTYPE = constants.HTYPE_INSTANCE
5664
  _OP_REQP = ["instance_name", "disks", "disk_template",
5665
              "mode", "start",
5666
              "wait_for_sync", "ip_check", "nics",
5667
              "hvparams", "beparams"]
5668
  REQ_BGL = False
5669

    
5670
  def CheckArguments(self):
5671
    """Check arguments.
5672

5673
    """
5674
    # do not require name_check to ease forward/backward compatibility
5675
    # for tools
5676
    if not hasattr(self.op, "name_check"):
5677
      self.op.name_check = True
5678
    if self.op.ip_check and not self.op.name_check:
5679
      # TODO: make the ip check more flexible and not depend on the name check
5680
      raise errors.OpPrereqError("Cannot do ip checks without a name check",
5681
                                 errors.ECODE_INVAL)
5682

    
5683
  def _ExpandNode(self, node):
5684
    """Expands and checks one node name.
5685

5686
    """
5687
    node_full = self.cfg.ExpandNodeName(node)
5688
    if node_full is None:
5689
      raise errors.OpPrereqError("Unknown node %s" % node, errors.ECODE_NOENT)
5690
    return node_full
5691

    
5692
  def ExpandNames(self):
5693
    """ExpandNames for CreateInstance.
5694

5695
    Figure out the right locks for instance creation.
5696

5697
    """
5698
    self.needed_locks = {}
5699

    
5700
    # set optional parameters to none if they don't exist
5701
    for attr in ["pnode", "snode", "iallocator", "hypervisor"]:
5702
      if not hasattr(self.op, attr):
5703
        setattr(self.op, attr, None)
5704

    
5705
    # cheap checks, mostly valid constants given
5706

    
5707
    # verify creation mode
5708
    if self.op.mode not in (constants.INSTANCE_CREATE,
5709
                            constants.INSTANCE_IMPORT):
5710
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
5711
                                 self.op.mode, errors.ECODE_INVAL)
5712

    
5713
    # disk template and mirror node verification
5714
    if self.op.disk_template not in constants.DISK_TEMPLATES:
5715
      raise errors.OpPrereqError("Invalid disk template name",
5716
                                 errors.ECODE_INVAL)
5717

    
5718
    if self.op.hypervisor is None:
5719
      self.op.hypervisor = self.cfg.GetHypervisorType()
5720

    
5721
    cluster = self.cfg.GetClusterInfo()
5722
    enabled_hvs = cluster.enabled_hypervisors
5723
    if self.op.hypervisor not in enabled_hvs:
5724
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
5725
                                 " cluster (%s)" % (self.op.hypervisor,
5726
                                  ",".join(enabled_hvs)),
5727
                                 errors.ECODE_STATE)
5728

    
5729
    # check hypervisor parameter syntax (locally)
5730
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5731
    filled_hvp = objects.FillDict(cluster.hvparams[self.op.hypervisor],
5732
                                  self.op.hvparams)
5733
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
5734
    hv_type.CheckParameterSyntax(filled_hvp)
5735
    self.hv_full = filled_hvp
5736
    # check that we don't specify global parameters on an instance
5737
    _CheckGlobalHvParams(self.op.hvparams)
5738

    
5739
    # fill and remember the beparams dict
5740
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5741
    self.be_full = objects.FillDict(cluster.beparams[constants.PP_DEFAULT],
5742
                                    self.op.beparams)
5743

    
5744
    #### instance parameters check
5745

    
5746
    # instance name verification
5747
    if self.op.name_check:
5748
      hostname1 = utils.GetHostInfo(self.op.instance_name)
5749
      self.op.instance_name = instance_name = hostname1.name
5750
      # used in CheckPrereq for ip ping check
5751
      self.check_ip = hostname1.ip
5752
    else:
5753
      instance_name = self.op.instance_name
5754
      self.check_ip = None
5755

    
5756
    # this is just a preventive check, but someone might still add this
5757
    # instance in the meantime, and creation will fail at lock-add time
5758
    if instance_name in self.cfg.GetInstanceList():
5759
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5760
                                 instance_name, errors.ECODE_EXISTS)
5761

    
5762
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
5763

    
5764
    # NIC buildup
5765
    self.nics = []
5766
    for idx, nic in enumerate(self.op.nics):
5767
      nic_mode_req = nic.get("mode", None)
5768
      nic_mode = nic_mode_req
5769
      if nic_mode is None:
5770
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
5771

    
5772
      # in routed mode, for the first nic, the default ip is 'auto'
5773
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
5774
        default_ip_mode = constants.VALUE_AUTO
5775
      else:
5776
        default_ip_mode = constants.VALUE_NONE
5777

    
5778
      # ip validity checks
5779
      ip = nic.get("ip", default_ip_mode)
5780
      if ip is None or ip.lower() == constants.VALUE_NONE:
5781
        nic_ip = None
5782
      elif ip.lower() == constants.VALUE_AUTO:
5783
        if not self.op.name_check:
5784
          raise errors.OpPrereqError("IP address set to auto but name checks"
5785
                                     " have been skipped. Aborting.",
5786
                                     errors.ECODE_INVAL)
5787
        nic_ip = hostname1.ip
5788
      else:
5789
        if not utils.IsValidIP(ip):
5790
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
5791
                                     " like a valid IP" % ip,
5792
                                     errors.ECODE_INVAL)
5793
        nic_ip = ip
5794

    
5795
      # TODO: check the ip address for uniqueness
5796
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
5797
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
5798
                                   errors.ECODE_INVAL)
5799

    
5800
      # MAC address verification
5801
      mac = nic.get("mac", constants.VALUE_AUTO)
5802
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5803
        mac = utils.NormalizeAndValidateMac(mac)
5804

    
5805
        try:
5806
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
5807
        except errors.ReservationError:
5808
          raise errors.OpPrereqError("MAC address %s already in use"
5809
                                     " in cluster" % mac,
5810
                                     errors.ECODE_NOTUNIQUE)
5811

    
5812
      # bridge verification
5813
      bridge = nic.get("bridge", None)
5814
      link = nic.get("link", None)
5815
      if bridge and link:
5816
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
5817
                                   " at the same time", errors.ECODE_INVAL)
5818
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
5819
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
5820
                                   errors.ECODE_INVAL)
5821
      elif bridge:
5822
        link = bridge
5823

    
5824
      nicparams = {}
5825
      if nic_mode_req:
5826
        nicparams[constants.NIC_MODE] = nic_mode_req
5827
      if link:
5828
        nicparams[constants.NIC_LINK] = link
5829

    
5830
      check_params = objects.FillDict(cluster.nicparams[constants.PP_DEFAULT],
5831
                                      nicparams)
5832
      objects.NIC.CheckParameterSyntax(check_params)
5833
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
5834

    
5835
    # disk checks/pre-build
5836
    self.disks = []
5837
    for disk in self.op.disks:
5838
      mode = disk.get("mode", constants.DISK_RDWR)
5839
      if mode not in constants.DISK_ACCESS_SET:
5840
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
5841
                                   mode, errors.ECODE_INVAL)
5842
      size = disk.get("size", None)
5843
      if size is None:
5844
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
5845
      try:
5846
        size = int(size)
5847
      except (TypeError, ValueError):
5848
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
5849
                                   errors.ECODE_INVAL)
5850
      self.disks.append({"size": size, "mode": mode})
5851

    
5852
    # file storage checks
5853
    if (self.op.file_driver and
5854
        not self.op.file_driver in constants.FILE_DRIVER):
5855
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
5856
                                 self.op.file_driver, errors.ECODE_INVAL)
5857

    
5858
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
5859
      raise errors.OpPrereqError("File storage directory path not absolute",
5860
                                 errors.ECODE_INVAL)
5861

    
5862
    ### Node/iallocator related checks
5863
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
5864
      raise errors.OpPrereqError("One and only one of iallocator and primary"
5865
                                 " node must be given",
5866
                                 errors.ECODE_INVAL)
5867

    
5868
    if self.op.iallocator:
5869
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5870
    else:
5871
      self.op.pnode = self._ExpandNode(self.op.pnode)
5872
      nodelist = [self.op.pnode]
5873
      if self.op.snode is not None:
5874
        self.op.snode = self._ExpandNode(self.op.snode)
5875
        nodelist.append(self.op.snode)
5876
      self.needed_locks[locking.LEVEL_NODE] = nodelist
5877

    
5878
    # in case of import lock the source node too
5879
    if self.op.mode == constants.INSTANCE_IMPORT:
5880
      src_node = getattr(self.op, "src_node", None)
5881
      src_path = getattr(self.op, "src_path", None)
5882

    
5883
      if src_path is None:
5884
        self.op.src_path = src_path = self.op.instance_name
5885

    
5886
      if src_node is None:
5887
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5888
        self.op.src_node = None
5889
        if os.path.isabs(src_path):
5890
          raise errors.OpPrereqError("Importing an instance from an absolute"
5891
                                     " path requires a source node option.",
5892
                                     errors.ECODE_INVAL)
5893
      else:
5894
        self.op.src_node = src_node = self._ExpandNode(src_node)
5895
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
5896
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
5897
        if not os.path.isabs(src_path):
5898
          self.op.src_path = src_path = \
5899
            os.path.join(constants.EXPORT_DIR, src_path)
5900

    
5901
      # On import force_variant must be True, because if we forced it at
5902
      # initial install, our only chance when importing it back is that it
5903
      # works again!
5904
      self.op.force_variant = True
5905

    
5906
    else: # INSTANCE_CREATE
5907
      if getattr(self.op, "os_type", None) is None:
5908
        raise errors.OpPrereqError("No guest OS specified",
5909
                                   errors.ECODE_INVAL)
5910
      self.op.force_variant = getattr(self.op, "force_variant", False)
5911

    
5912
  def _RunAllocator(self):
5913
    """Run the allocator based on input opcode.
5914

5915
    """
5916
    nics = [n.ToDict() for n in self.nics]
5917
    ial = IAllocator(self.cfg, self.rpc,
5918
                     mode=constants.IALLOCATOR_MODE_ALLOC,
5919
                     name=self.op.instance_name,
5920
                     disk_template=self.op.disk_template,
5921
                     tags=[],
5922
                     os=self.op.os_type,
5923
                     vcpus=self.be_full[constants.BE_VCPUS],
5924
                     mem_size=self.be_full[constants.BE_MEMORY],
5925
                     disks=self.disks,
5926
                     nics=nics,
5927
                     hypervisor=self.op.hypervisor,
5928
                     )
5929

    
5930
    ial.Run(self.op.iallocator)
5931

    
5932
    if not ial.success:
5933
      raise errors.OpPrereqError("Can't compute nodes using"
5934
                                 " iallocator '%s': %s" %
5935
                                 (self.op.iallocator, ial.info),
5936
                                 errors.ECODE_NORES)
5937
    if len(ial.nodes) != ial.required_nodes:
5938
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
5939
                                 " of nodes (%s), required %s" %
5940
                                 (self.op.iallocator, len(ial.nodes),
5941
                                  ial.required_nodes), errors.ECODE_FAULT)
5942
    self.op.pnode = ial.nodes[0]
5943
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
5944
                 self.op.instance_name, self.op.iallocator,
5945
                 utils.CommaJoin(ial.nodes))
5946
    if ial.required_nodes == 2:
5947
      self.op.snode = ial.nodes[1]
5948

    
5949
  def BuildHooksEnv(self):
5950
    """Build hooks env.
5951

5952
    This runs on master, primary and secondary nodes of the instance.
5953

5954
    """
5955
    env = {
5956
      "ADD_MODE": self.op.mode,
5957
      }
5958
    if self.op.mode == constants.INSTANCE_IMPORT:
5959
      env["SRC_NODE"] = self.op.src_node
5960
      env["SRC_PATH"] = self.op.src_path
5961
      env["SRC_IMAGES"] = self.src_images
5962

    
5963
    env.update(_BuildInstanceHookEnv(
5964
      name=self.op.instance_name,
5965
      primary_node=self.op.pnode,
5966
      secondary_nodes=self.secondaries,
5967
      status=self.op.start,
5968
      os_type=self.op.os_type,
5969
      memory=self.be_full[constants.BE_MEMORY],
5970
      vcpus=self.be_full[constants.BE_VCPUS],
5971
      nics=_NICListToTuple(self, self.nics),
5972
      disk_template=self.op.disk_template,
5973
      disks=[(d["size"], d["mode"]) for d in self.disks],
5974
      bep=self.be_full,
5975
      hvp=self.hv_full,
5976
      hypervisor_name=self.op.hypervisor,
5977
    ))
5978

    
5979
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
5980
          self.secondaries)
5981
    return env, nl, nl
5982

    
5983

    
5984
  def CheckPrereq(self):
5985
    """Check prerequisites.
5986

5987
    """
5988
    if (not self.cfg.GetVGName() and
5989
        self.op.disk_template not in constants.DTS_NOT_LVM):
5990
      raise errors.OpPrereqError("Cluster does not support lvm-based"
5991
                                 " instances", errors.ECODE_STATE)
5992

    
5993
    if self.op.mode == constants.INSTANCE_IMPORT:
5994
      src_node = self.op.src_node
5995
      src_path = self.op.src_path
5996

    
5997
      if src_node is None:
5998
        locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
5999
        exp_list = self.rpc.call_export_list(locked_nodes)
6000
        found = False
6001
        for node in exp_list:
6002
          if exp_list[node].fail_msg:
6003
            continue
6004
          if src_path in exp_list[node].payload:
6005
            found = True
6006
            self.op.src_node = src_node = node
6007
            self.op.src_path = src_path = os.path.join(constants.EXPORT_DIR,
6008
                                                       src_path)
6009
            break
6010
        if not found:
6011
          raise errors.OpPrereqError("No export found for relative path %s" %
6012
                                      src_path, errors.ECODE_INVAL)
6013

    
6014
      _CheckNodeOnline(self, src_node)
6015
      result = self.rpc.call_export_info(src_node, src_path)
6016
      result.Raise("No export or invalid export found in dir %s" % src_path)
6017

    
6018
      export_info = objects.SerializableConfigParser.Loads(str(result.payload))
6019
      if not export_info.has_section(constants.INISECT_EXP):
6020
        raise errors.ProgrammerError("Corrupted export config",
6021
                                     errors.ECODE_ENVIRON)
6022

    
6023
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
6024
      if (int(ei_version) != constants.EXPORT_VERSION):
6025
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
6026
                                   (ei_version, constants.EXPORT_VERSION),
6027
                                   errors.ECODE_ENVIRON)
6028

    
6029
      # Check that the new instance doesn't have less disks than the export
6030
      instance_disks = len(self.disks)
6031
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
6032
      if instance_disks < export_disks:
6033
        raise errors.OpPrereqError("Not enough disks to import."
6034
                                   " (instance: %d, export: %d)" %
6035
                                   (instance_disks, export_disks),
6036
                                   errors.ECODE_INVAL)
6037

    
6038
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
6039
      disk_images = []
6040
      for idx in range(export_disks):
6041
        option = 'disk%d_dump' % idx
6042
        if export_info.has_option(constants.INISECT_INS, option):
6043
          # FIXME: are the old os-es, disk sizes, etc. useful?
6044
          export_name = export_info.get(constants.INISECT_INS, option)
6045
          image = os.path.join(src_path, export_name)
6046
          disk_images.append(image)
6047
        else:
6048
          disk_images.append(False)
6049

    
6050
      self.src_images = disk_images
6051

    
6052
      old_name = export_info.get(constants.INISECT_INS, 'name')
6053
      # FIXME: int() here could throw a ValueError on broken exports
6054
      exp_nic_count = int(export_info.get(constants.INISECT_INS, 'nic_count'))
6055
      if self.op.instance_name == old_name:
6056
        for idx, nic in enumerate(self.nics):
6057
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
6058
            nic_mac_ini = 'nic%d_mac' % idx
6059
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
6060

    
6061
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
6062

    
6063
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
6064
    if self.op.ip_check:
6065
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
6066
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
6067
                                   (self.check_ip, self.op.instance_name),
6068
                                   errors.ECODE_NOTUNIQUE)
6069

    
6070
    #### mac address generation
6071
    # By generating here the mac address both the allocator and the hooks get
6072
    # the real final mac address rather than the 'auto' or 'generate' value.
6073
    # There is a race condition between the generation and the instance object
6074
    # creation, which means that we know the mac is valid now, but we're not
6075
    # sure it will be when we actually add the instance. If things go bad
6076
    # adding the instance will abort because of a duplicate mac, and the
6077
    # creation job will fail.
6078
    for nic in self.nics:
6079
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
6080
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
6081

    
6082
    #### allocator run
6083

    
6084
    if self.op.iallocator is not None:
6085
      self._RunAllocator()
6086

    
6087
    #### node related checks
6088

    
6089
    # check primary node
6090
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
6091
    assert self.pnode is not None, \
6092
      "Cannot retrieve locked node %s" % self.op.pnode
6093
    if pnode.offline:
6094
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
6095
                                 pnode.name, errors.ECODE_STATE)
6096
    if pnode.drained:
6097
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
6098
                                 pnode.name, errors.ECODE_STATE)
6099

    
6100
    self.secondaries = []
6101

    
6102
    # mirror node verification
6103
    if self.op.disk_template in constants.DTS_NET_MIRROR:
6104
      if self.op.snode is None:
6105
        raise errors.OpPrereqError("The networked disk templates need"
6106
                                   " a mirror node", errors.ECODE_INVAL)
6107
      if self.op.snode == pnode.name:
6108
        raise errors.OpPrereqError("The secondary node cannot be the"
6109
                                   " primary node.", errors.ECODE_INVAL)
6110
      _CheckNodeOnline(self, self.op.snode)
6111
      _CheckNodeNotDrained(self, self.op.snode)
6112
      self.secondaries.append(self.op.snode)
6113

    
6114
    nodenames = [pnode.name] + self.secondaries
6115

    
6116
    req_size = _ComputeDiskSize(self.op.disk_template,
6117
                                self.disks)
6118

    
6119
    # Check lv size requirements
6120
    if req_size is not None:
6121
      nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
6122
                                         self.op.hypervisor)
6123
      for node in nodenames:
6124
        info = nodeinfo[node]
6125
        info.Raise("Cannot get current information from node %s" % node)
6126
        info = info.payload
6127
        vg_free = info.get('vg_free', None)
6128
        if not isinstance(vg_free, int):
6129
          raise errors.OpPrereqError("Can't compute free disk space on"
6130
                                     " node %s" % node, errors.ECODE_ENVIRON)
6131
        if req_size > vg_free:
6132
          raise errors.OpPrereqError("Not enough disk space on target node %s."
6133
                                     " %d MB available, %d MB required" %
6134
                                     (node, vg_free, req_size),
6135
                                     errors.ECODE_NORES)
6136

    
6137
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
6138

    
6139
    # os verification
6140
    result = self.rpc.call_os_get(pnode.name, self.op.os_type)
6141
    result.Raise("OS '%s' not in supported os list for primary node %s" %
6142
                 (self.op.os_type, pnode.name),
6143
                 prereq=True, ecode=errors.ECODE_INVAL)
6144
    if not self.op.force_variant:
6145
      _CheckOSVariant(result.payload, self.op.os_type)
6146

    
6147
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
6148

    
6149
    # memory check on primary node
6150
    if self.op.start:
6151
      _CheckNodeFreeMemory(self, self.pnode.name,
6152
                           "creating instance %s" % self.op.instance_name,
6153
                           self.be_full[constants.BE_MEMORY],
6154
                           self.op.hypervisor)
6155

    
6156
    self.dry_run_result = list(nodenames)
6157

    
6158
  def Exec(self, feedback_fn):
6159
    """Create and add the instance to the cluster.
6160

6161
    """
6162
    instance = self.op.instance_name
6163
    pnode_name = self.pnode.name
6164

    
6165
    ht_kind = self.op.hypervisor
6166
    if ht_kind in constants.HTS_REQ_PORT:
6167
      network_port = self.cfg.AllocatePort()
6168
    else:
6169
      network_port = None
6170

    
6171
    ##if self.op.vnc_bind_address is None:
6172
    ##  self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
6173

    
6174
    # this is needed because os.path.join does not accept None arguments
6175
    if self.op.file_storage_dir is None:
6176
      string_file_storage_dir = ""
6177
    else:
6178
      string_file_storage_dir = self.op.file_storage_dir
6179

    
6180
    # build the full file storage dir path
6181
    file_storage_dir = os.path.normpath(os.path.join(
6182
                                        self.cfg.GetFileStorageDir(),
6183
                                        string_file_storage_dir, instance))
6184

    
6185

    
6186
    disks = _GenerateDiskTemplate(self,
6187
                                  self.op.disk_template,
6188
                                  instance, pnode_name,
6189
                                  self.secondaries,
6190
                                  self.disks,
6191
                                  file_storage_dir,
6192
                                  self.op.file_driver,
6193
                                  0)
6194

    
6195
    iobj = objects.Instance(name=instance, os=self.op.os_type,
6196
                            primary_node=pnode_name,
6197
                            nics=self.nics, disks=disks,
6198
                            disk_template=self.op.disk_template,
6199
                            admin_up=False,
6200
                            network_port=network_port,
6201
                            beparams=self.op.beparams,
6202
                            hvparams=self.op.hvparams,
6203
                            hypervisor=self.op.hypervisor,
6204
                            )
6205

    
6206
    feedback_fn("* creating instance disks...")
6207
    try:
6208
      _CreateDisks(self, iobj)
6209
    except errors.OpExecError:
6210
      self.LogWarning("Device creation failed, reverting...")
6211
      try:
6212
        _RemoveDisks(self, iobj)
6213
      finally:
6214
        self.cfg.ReleaseDRBDMinors(instance)
6215
        raise
6216

    
6217
    feedback_fn("adding instance %s to cluster config" % instance)
6218

    
6219
    self.cfg.AddInstance(iobj, self.proc.GetECId())
6220

    
6221
    # Declare that we don't want to remove the instance lock anymore, as we've
6222
    # added the instance to the config
6223
    del self.remove_locks[locking.LEVEL_INSTANCE]
6224
    # Unlock all the nodes
6225
    if self.op.mode == constants.INSTANCE_IMPORT:
6226
      nodes_keep = [self.op.src_node]
6227
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
6228
                       if node != self.op.src_node]
6229
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
6230
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
6231
    else:
6232
      self.context.glm.release(locking.LEVEL_NODE)
6233
      del self.acquired_locks[locking.LEVEL_NODE]
6234

    
6235
    if self.op.wait_for_sync:
6236
      disk_abort = not _WaitForSync(self, iobj)
6237
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
6238
      # make sure the disks are not degraded (still sync-ing is ok)
6239
      time.sleep(15)
6240
      feedback_fn("* checking mirrors status")
6241
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
6242
    else:
6243
      disk_abort = False
6244

    
6245
    if disk_abort:
6246
      _RemoveDisks(self, iobj)
6247
      self.cfg.RemoveInstance(iobj.name)
6248
      # Make sure the instance lock gets removed
6249
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
6250
      raise errors.OpExecError("There are some degraded disks for"
6251
                               " this instance")
6252

    
6253
    feedback_fn("creating os for instance %s on node %s" %
6254
                (instance, pnode_name))
6255

    
6256
    if iobj.disk_template != constants.DT_DISKLESS:
6257
      if self.op.mode == constants.INSTANCE_CREATE:
6258
        feedback_fn("* running the instance OS create scripts...")
6259
        # FIXME: pass debug option from opcode to backend
6260
        result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
6261
                                               self.op.debug_level)
6262
        result.Raise("Could not add os for instance %s"
6263
                     " on node %s" % (instance, pnode_name))
6264

    
6265
      elif self.op.mode == constants.INSTANCE_IMPORT:
6266
        feedback_fn("* running the instance OS import scripts...")
6267
        src_node = self.op.src_node
6268
        src_images = self.src_images
6269
        cluster_name = self.cfg.GetClusterName()
6270
        # FIXME: pass debug option from opcode to backend
6271
        import_result = self.rpc.call_instance_os_import(pnode_name, iobj,
6272
                                                         src_node, src_images,
6273
                                                         cluster_name,
6274
                                                         self.op.debug_level)
6275
        msg = import_result.fail_msg
6276
        if msg:
6277
          self.LogWarning("Error while importing the disk images for instance"
6278
                          " %s on node %s: %s" % (instance, pnode_name, msg))
6279
      else:
6280
        # also checked in the prereq part
6281
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
6282
                                     % self.op.mode)
6283

    
6284
    if self.op.start:
6285
      iobj.admin_up = True
6286
      self.cfg.Update(iobj, feedback_fn)
6287
      logging.info("Starting instance %s on node %s", instance, pnode_name)
6288
      feedback_fn("* starting instance...")
6289
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
6290
      result.Raise("Could not start instance")
6291

    
6292
    return list(iobj.all_nodes)
6293

    
6294

    
6295
class LUConnectConsole(NoHooksLU):
6296
  """Connect to an instance's console.
6297

6298
  This is somewhat special in that it returns the command line that
6299
  you need to run on the master node in order to connect to the
6300
  console.
6301

6302
  """
6303
  _OP_REQP = ["instance_name"]
6304
  REQ_BGL = False
6305

    
6306
  def ExpandNames(self):
6307
    self._ExpandAndLockInstance()
6308

    
6309
  def CheckPrereq(self):
6310
    """Check prerequisites.
6311

6312
    This checks that the instance is in the cluster.
6313

6314
    """
6315
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6316
    assert self.instance is not None, \
6317
      "Cannot retrieve locked instance %s" % self.op.instance_name
6318
    _CheckNodeOnline(self, self.instance.primary_node)
6319

    
6320
  def Exec(self, feedback_fn):
6321
    """Connect to the console of an instance
6322

6323
    """
6324
    instance = self.instance
6325
    node = instance.primary_node
6326

    
6327
    node_insts = self.rpc.call_instance_list([node],
6328
                                             [instance.hypervisor])[node]
6329
    node_insts.Raise("Can't get node information from %s" % node)
6330

    
6331
    if instance.name not in node_insts.payload:
6332
      raise errors.OpExecError("Instance %s is not running." % instance.name)
6333

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

    
6336
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
6337
    cluster = self.cfg.GetClusterInfo()
6338
    # beparams and hvparams are passed separately, to avoid editing the
6339
    # instance and then saving the defaults in the instance itself.
6340
    hvparams = cluster.FillHV(instance)
6341
    beparams = cluster.FillBE(instance)
6342
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
6343

    
6344
    # build ssh cmdline
6345
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
6346

    
6347

    
6348
class LUReplaceDisks(LogicalUnit):
6349
  """Replace the disks of an instance.
6350

6351
  """
6352
  HPATH = "mirrors-replace"
6353
  HTYPE = constants.HTYPE_INSTANCE
6354
  _OP_REQP = ["instance_name", "mode", "disks"]
6355
  REQ_BGL = False
6356

    
6357
  def CheckArguments(self):
6358
    if not hasattr(self.op, "remote_node"):
6359
      self.op.remote_node = None
6360
    if not hasattr(self.op, "iallocator"):
6361
      self.op.iallocator = None
6362
    if not hasattr(self.op, "early_release"):
6363
      self.op.early_release = False
6364

    
6365
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
6366
                                  self.op.iallocator)
6367

    
6368
  def ExpandNames(self):
6369
    self._ExpandAndLockInstance()
6370

    
6371
    if self.op.iallocator is not None:
6372
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6373

    
6374
    elif self.op.remote_node is not None:
6375
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
6376
      if remote_node is None:
6377
        raise errors.OpPrereqError("Node '%s' not known" %
6378
                                   self.op.remote_node, errors.ECODE_NOENT)
6379

    
6380
      self.op.remote_node = remote_node
6381

    
6382
      # Warning: do not remove the locking of the new secondary here
6383
      # unless DRBD8.AddChildren is changed to work in parallel;
6384
      # currently it doesn't since parallel invocations of
6385
      # FindUnusedMinor will conflict
6386
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
6387
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6388

    
6389
    else:
6390
      self.needed_locks[locking.LEVEL_NODE] = []
6391
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6392

    
6393
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
6394
                                   self.op.iallocator, self.op.remote_node,
6395
                                   self.op.disks, False, self.op.early_release)
6396

    
6397
    self.tasklets = [self.replacer]
6398

    
6399
  def DeclareLocks(self, level):
6400
    # If we're not already locking all nodes in the set we have to declare the
6401
    # instance's primary/secondary nodes.
6402
    if (level == locking.LEVEL_NODE and
6403
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
6404
      self._LockInstancesNodes()
6405

    
6406
  def BuildHooksEnv(self):
6407
    """Build hooks env.
6408

6409
    This runs on the master, the primary and all the secondaries.
6410

6411
    """
6412
    instance = self.replacer.instance
6413
    env = {
6414
      "MODE": self.op.mode,
6415
      "NEW_SECONDARY": self.op.remote_node,
6416
      "OLD_SECONDARY": instance.secondary_nodes[0],
6417
      }
6418
    env.update(_BuildInstanceHookEnvByObject(self, instance))
6419
    nl = [
6420
      self.cfg.GetMasterNode(),
6421
      instance.primary_node,
6422
      ]
6423
    if self.op.remote_node is not None:
6424
      nl.append(self.op.remote_node)
6425
    return env, nl, nl
6426

    
6427

    
6428
class LUEvacuateNode(LogicalUnit):
6429
  """Relocate the secondary instances from a node.
6430

6431
  """
6432
  HPATH = "node-evacuate"
6433
  HTYPE = constants.HTYPE_NODE
6434
  _OP_REQP = ["node_name"]
6435
  REQ_BGL = False
6436

    
6437
  def CheckArguments(self):
6438
    if not hasattr(self.op, "remote_node"):
6439
      self.op.remote_node = None
6440
    if not hasattr(self.op, "iallocator"):
6441
      self.op.iallocator = None
6442
    if not hasattr(self.op, "early_release"):
6443
      self.op.early_release = False
6444

    
6445
    TLReplaceDisks.CheckArguments(constants.REPLACE_DISK_CHG,
6446
                                  self.op.remote_node,
6447
                                  self.op.iallocator)
6448

    
6449
  def ExpandNames(self):
6450
    self.op.node_name = self.cfg.ExpandNodeName(self.op.node_name)
6451
    if self.op.node_name is None:
6452
      raise errors.OpPrereqError("Node '%s' not known" % self.op.node_name,
6453
                                 errors.ECODE_NOENT)
6454

    
6455
    self.needed_locks = {}
6456

    
6457
    # Declare node locks
6458
    if self.op.iallocator is not None:
6459
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6460

    
6461
    elif self.op.remote_node is not None:
6462
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
6463
      if remote_node is None:
6464
        raise errors.OpPrereqError("Node '%s' not known" %
6465
                                   self.op.remote_node, errors.ECODE_NOENT)
6466

    
6467
      self.op.remote_node = remote_node
6468

    
6469
      # Warning: do not remove the locking of the new secondary here
6470
      # unless DRBD8.AddChildren is changed to work in parallel;
6471
      # currently it doesn't since parallel invocations of
6472
      # FindUnusedMinor will conflict
6473
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
6474
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6475

    
6476
    else:
6477
      raise errors.OpPrereqError("Invalid parameters", errors.ECODE_INVAL)
6478

    
6479
    # Create tasklets for replacing disks for all secondary instances on this
6480
    # node
6481
    names = []
6482
    tasklets = []
6483

    
6484
    for inst in _GetNodeSecondaryInstances(self.cfg, self.op.node_name):
6485
      logging.debug("Replacing disks for instance %s", inst.name)
6486
      names.append(inst.name)
6487

    
6488
      replacer = TLReplaceDisks(self, inst.name, constants.REPLACE_DISK_CHG,
6489
                                self.op.iallocator, self.op.remote_node, [],
6490
                                True, self.op.early_release)
6491
      tasklets.append(replacer)
6492

    
6493
    self.tasklets = tasklets
6494
    self.instance_names = names
6495

    
6496
    # Declare instance locks
6497
    self.needed_locks[locking.LEVEL_INSTANCE] = self.instance_names
6498

    
6499
  def DeclareLocks(self, level):
6500
    # If we're not already locking all nodes in the set we have to declare the
6501
    # instance's primary/secondary nodes.
6502
    if (level == locking.LEVEL_NODE and
6503
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
6504
      self._LockInstancesNodes()
6505

    
6506
  def BuildHooksEnv(self):
6507
    """Build hooks env.
6508

6509
    This runs on the master, the primary and all the secondaries.
6510

6511
    """
6512
    env = {
6513
      "NODE_NAME": self.op.node_name,
6514
      }
6515

    
6516
    nl = [self.cfg.GetMasterNode()]
6517

    
6518
    if self.op.remote_node is not None:
6519
      env["NEW_SECONDARY"] = self.op.remote_node
6520
      nl.append(self.op.remote_node)
6521

    
6522
    return (env, nl, nl)
6523

    
6524

    
6525
class TLReplaceDisks(Tasklet):
6526
  """Replaces disks for an instance.
6527

6528
  Note: Locking is not within the scope of this class.
6529

6530
  """
6531
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
6532
               disks, delay_iallocator, early_release):
6533
    """Initializes this class.
6534

6535
    """
6536
    Tasklet.__init__(self, lu)
6537

    
6538
    # Parameters
6539
    self.instance_name = instance_name
6540
    self.mode = mode
6541
    self.iallocator_name = iallocator_name
6542
    self.remote_node = remote_node
6543
    self.disks = disks
6544
    self.delay_iallocator = delay_iallocator
6545
    self.early_release = early_release
6546

    
6547
    # Runtime data
6548
    self.instance = None
6549
    self.new_node = None
6550
    self.target_node = None
6551
    self.other_node = None
6552
    self.remote_node_info = None
6553
    self.node_secondary_ip = None
6554

    
6555
  @staticmethod
6556
  def CheckArguments(mode, remote_node, iallocator):
6557
    """Helper function for users of this class.
6558

6559
    """
6560
    # check for valid parameter combination
6561
    if mode == constants.REPLACE_DISK_CHG:
6562
      if remote_node is None and iallocator is None:
6563
        raise errors.OpPrereqError("When changing the secondary either an"
6564
                                   " iallocator script must be used or the"
6565
                                   " new node given", errors.ECODE_INVAL)
6566

    
6567
      if remote_node is not None and iallocator is not None:
6568
        raise errors.OpPrereqError("Give either the iallocator or the new"
6569
                                   " secondary, not both", errors.ECODE_INVAL)
6570

    
6571
    elif remote_node is not None or iallocator is not None:
6572
      # Not replacing the secondary
6573
      raise errors.OpPrereqError("The iallocator and new node options can"
6574
                                 " only be used when changing the"
6575
                                 " secondary node", errors.ECODE_INVAL)
6576

    
6577
  @staticmethod
6578
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
6579
    """Compute a new secondary node using an IAllocator.
6580

6581
    """
6582
    ial = IAllocator(lu.cfg, lu.rpc,
6583
                     mode=constants.IALLOCATOR_MODE_RELOC,
6584
                     name=instance_name,
6585
                     relocate_from=relocate_from)
6586

    
6587
    ial.Run(iallocator_name)
6588

    
6589
    if not ial.success:
6590
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
6591
                                 " %s" % (iallocator_name, ial.info),
6592
                                 errors.ECODE_NORES)
6593

    
6594
    if len(ial.nodes) != ial.required_nodes:
6595
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6596
                                 " of nodes (%s), required %s" %
6597
                                 (iallocator_name,
6598
                                  len(ial.nodes), ial.required_nodes),
6599
                                 errors.ECODE_FAULT)
6600

    
6601
    remote_node_name = ial.nodes[0]
6602

    
6603
    lu.LogInfo("Selected new secondary for instance '%s': %s",
6604
               instance_name, remote_node_name)
6605

    
6606
    return remote_node_name
6607

    
6608
  def _FindFaultyDisks(self, node_name):
6609
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
6610
                                    node_name, True)
6611

    
6612
  def CheckPrereq(self):
6613
    """Check prerequisites.
6614

6615
    This checks that the instance is in the cluster.
6616

6617
    """
6618
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
6619
    assert instance is not None, \
6620
      "Cannot retrieve locked instance %s" % self.instance_name
6621

    
6622
    if instance.disk_template != constants.DT_DRBD8:
6623
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
6624
                                 " instances", errors.ECODE_INVAL)
6625

    
6626
    if len(instance.secondary_nodes) != 1:
6627
      raise errors.OpPrereqError("The instance has a strange layout,"
6628
                                 " expected one secondary but found %d" %
6629
                                 len(instance.secondary_nodes),
6630
                                 errors.ECODE_FAULT)
6631

    
6632
    if not self.delay_iallocator:
6633
      self._CheckPrereq2()
6634

    
6635
  def _CheckPrereq2(self):
6636
    """Check prerequisites, second part.
6637

6638
    This function should always be part of CheckPrereq. It was separated and is
6639
    now called from Exec because during node evacuation iallocator was only
6640
    called with an unmodified cluster model, not taking planned changes into
6641
    account.
6642

6643
    """
6644
    instance = self.instance
6645
    secondary_node = instance.secondary_nodes[0]
6646

    
6647
    if self.iallocator_name is None:
6648
      remote_node = self.remote_node
6649
    else:
6650
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
6651
                                       instance.name, instance.secondary_nodes)
6652

    
6653
    if remote_node is not None:
6654
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
6655
      assert self.remote_node_info is not None, \
6656
        "Cannot retrieve locked node %s" % remote_node
6657
    else:
6658
      self.remote_node_info = None
6659

    
6660
    if remote_node == self.instance.primary_node:
6661
      raise errors.OpPrereqError("The specified node is the primary node of"
6662
                                 " the instance.", errors.ECODE_INVAL)
6663

    
6664
    if remote_node == secondary_node:
6665
      raise errors.OpPrereqError("The specified node is already the"
6666
                                 " secondary node of the instance.",
6667
                                 errors.ECODE_INVAL)
6668

    
6669
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
6670
                                    constants.REPLACE_DISK_CHG):
6671
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
6672
                                 errors.ECODE_INVAL)
6673

    
6674
    if self.mode == constants.REPLACE_DISK_AUTO:
6675
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
6676
      faulty_secondary = self._FindFaultyDisks(secondary_node)
6677

    
6678
      if faulty_primary and faulty_secondary:
6679
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
6680
                                   " one node and can not be repaired"
6681
                                   " automatically" % self.instance_name,
6682
                                   errors.ECODE_STATE)
6683

    
6684
      if faulty_primary:
6685
        self.disks = faulty_primary
6686
        self.target_node = instance.primary_node
6687
        self.other_node = secondary_node
6688
        check_nodes = [self.target_node, self.other_node]
6689
      elif faulty_secondary:
6690
        self.disks = faulty_secondary
6691
        self.target_node = secondary_node
6692
        self.other_node = instance.primary_node
6693
        check_nodes = [self.target_node, self.other_node]
6694
      else:
6695
        self.disks = []
6696
        check_nodes = []
6697

    
6698
    else:
6699
      # Non-automatic modes
6700
      if self.mode == constants.REPLACE_DISK_PRI:
6701
        self.target_node = instance.primary_node
6702
        self.other_node = secondary_node
6703
        check_nodes = [self.target_node, self.other_node]
6704

    
6705
      elif self.mode == constants.REPLACE_DISK_SEC:
6706
        self.target_node = secondary_node
6707
        self.other_node = instance.primary_node
6708
        check_nodes = [self.target_node, self.other_node]
6709

    
6710
      elif self.mode == constants.REPLACE_DISK_CHG:
6711
        self.new_node = remote_node
6712
        self.other_node = instance.primary_node
6713
        self.target_node = secondary_node
6714
        check_nodes = [self.new_node, self.other_node]
6715

    
6716
        _CheckNodeNotDrained(self.lu, remote_node)
6717

    
6718
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
6719
        assert old_node_info is not None
6720
        if old_node_info.offline and not self.early_release:
6721
          # doesn't make sense to delay the release
6722
          self.early_release = True
6723
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
6724
                          " early-release mode", secondary_node)
6725

    
6726
      else:
6727
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
6728
                                     self.mode)
6729

    
6730
      # If not specified all disks should be replaced
6731
      if not self.disks:
6732
        self.disks = range(len(self.instance.disks))
6733

    
6734
    for node in check_nodes:
6735
      _CheckNodeOnline(self.lu, node)
6736

    
6737
    # Check whether disks are valid
6738
    for disk_idx in self.disks:
6739
      instance.FindDisk(disk_idx)
6740

    
6741
    # Get secondary node IP addresses
6742
    node_2nd_ip = {}
6743

    
6744
    for node_name in [self.target_node, self.other_node, self.new_node]:
6745
      if node_name is not None:
6746
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
6747

    
6748
    self.node_secondary_ip = node_2nd_ip
6749

    
6750
  def Exec(self, feedback_fn):
6751
    """Execute disk replacement.
6752

6753
    This dispatches the disk replacement to the appropriate handler.
6754

6755
    """
6756
    if self.delay_iallocator:
6757
      self._CheckPrereq2()
6758

    
6759
    if not self.disks:
6760
      feedback_fn("No disks need replacement")
6761
      return
6762

    
6763
    feedback_fn("Replacing disk(s) %s for %s" %
6764
                (utils.CommaJoin(self.disks), self.instance.name))
6765

    
6766
    activate_disks = (not self.instance.admin_up)
6767

    
6768
    # Activate the instance disks if we're replacing them on a down instance
6769
    if activate_disks:
6770
      _StartInstanceDisks(self.lu, self.instance, True)
6771

    
6772
    try:
6773
      # Should we replace the secondary node?
6774
      if self.new_node is not None:
6775
        fn = self._ExecDrbd8Secondary
6776
      else:
6777
        fn = self._ExecDrbd8DiskOnly
6778

    
6779
      return fn(feedback_fn)
6780

    
6781
    finally:
6782
      # Deactivate the instance disks if we're replacing them on a
6783
      # down instance
6784
      if activate_disks:
6785
        _SafeShutdownInstanceDisks(self.lu, self.instance)
6786

    
6787
  def _CheckVolumeGroup(self, nodes):
6788
    self.lu.LogInfo("Checking volume groups")
6789

    
6790
    vgname = self.cfg.GetVGName()
6791

    
6792
    # Make sure volume group exists on all involved nodes
6793
    results = self.rpc.call_vg_list(nodes)
6794
    if not results:
6795
      raise errors.OpExecError("Can't list volume groups on the nodes")
6796

    
6797
    for node in nodes:
6798
      res = results[node]
6799
      res.Raise("Error checking node %s" % node)
6800
      if vgname not in res.payload:
6801
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
6802
                                 (vgname, node))
6803

    
6804
  def _CheckDisksExistence(self, nodes):
6805
    # Check disk existence
6806
    for idx, dev in enumerate(self.instance.disks):
6807
      if idx not in self.disks:
6808
        continue
6809

    
6810
      for node in nodes:
6811
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
6812
        self.cfg.SetDiskID(dev, node)
6813

    
6814
        result = self.rpc.call_blockdev_find(node, dev)
6815

    
6816
        msg = result.fail_msg
6817
        if msg or not result.payload:
6818
          if not msg:
6819
            msg = "disk not found"
6820
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
6821
                                   (idx, node, msg))
6822

    
6823
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
6824
    for idx, dev in enumerate(self.instance.disks):
6825
      if idx not in self.disks:
6826
        continue
6827

    
6828
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
6829
                      (idx, node_name))
6830

    
6831
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
6832
                                   ldisk=ldisk):
6833
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
6834
                                 " replace disks for instance %s" %
6835
                                 (node_name, self.instance.name))
6836

    
6837
  def _CreateNewStorage(self, node_name):
6838
    vgname = self.cfg.GetVGName()
6839
    iv_names = {}
6840

    
6841
    for idx, dev in enumerate(self.instance.disks):
6842
      if idx not in self.disks:
6843
        continue
6844

    
6845
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
6846

    
6847
      self.cfg.SetDiskID(dev, node_name)
6848

    
6849
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
6850
      names = _GenerateUniqueNames(self.lu, lv_names)
6851

    
6852
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
6853
                             logical_id=(vgname, names[0]))
6854
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6855
                             logical_id=(vgname, names[1]))
6856

    
6857
      new_lvs = [lv_data, lv_meta]
6858
      old_lvs = dev.children
6859
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
6860

    
6861
      # we pass force_create=True to force the LVM creation
6862
      for new_lv in new_lvs:
6863
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
6864
                        _GetInstanceInfoText(self.instance), False)
6865

    
6866
    return iv_names
6867

    
6868
  def _CheckDevices(self, node_name, iv_names):
6869
    for name, (dev, _, _) in iv_names.iteritems():
6870
      self.cfg.SetDiskID(dev, node_name)
6871

    
6872
      result = self.rpc.call_blockdev_find(node_name, dev)
6873

    
6874
      msg = result.fail_msg
6875
      if msg or not result.payload:
6876
        if not msg:
6877
          msg = "disk not found"
6878
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
6879
                                 (name, msg))
6880

    
6881
      if result.payload.is_degraded:
6882
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
6883

    
6884
  def _RemoveOldStorage(self, node_name, iv_names):
6885
    for name, (_, old_lvs, _) in iv_names.iteritems():
6886
      self.lu.LogInfo("Remove logical volumes for %s" % name)
6887

    
6888
      for lv in old_lvs:
6889
        self.cfg.SetDiskID(lv, node_name)
6890

    
6891
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
6892
        if msg:
6893
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
6894
                             hint="remove unused LVs manually")
6895

    
6896
  def _ReleaseNodeLock(self, node_name):
6897
    """Releases the lock for a given node."""
6898
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
6899

    
6900
  def _ExecDrbd8DiskOnly(self, feedback_fn):
6901
    """Replace a disk on the primary or secondary for DRBD 8.
6902

6903
    The algorithm for replace is quite complicated:
6904

6905
      1. for each disk to be replaced:
6906

6907
        1. create new LVs on the target node with unique names
6908
        1. detach old LVs from the drbd device
6909
        1. rename old LVs to name_replaced.<time_t>
6910
        1. rename new LVs to old LVs
6911
        1. attach the new LVs (with the old names now) to the drbd device
6912

6913
      1. wait for sync across all devices
6914

6915
      1. for each modified disk:
6916

6917
        1. remove old LVs (which have the name name_replaces.<time_t>)
6918

6919
    Failures are not very well handled.
6920

6921
    """
6922
    steps_total = 6
6923

    
6924
    # Step: check device activation
6925
    self.lu.LogStep(1, steps_total, "Check device existence")
6926
    self._CheckDisksExistence([self.other_node, self.target_node])
6927
    self._CheckVolumeGroup([self.target_node, self.other_node])
6928

    
6929
    # Step: check other node consistency
6930
    self.lu.LogStep(2, steps_total, "Check peer consistency")
6931
    self._CheckDisksConsistency(self.other_node,
6932
                                self.other_node == self.instance.primary_node,
6933
                                False)
6934

    
6935
    # Step: create new storage
6936
    self.lu.LogStep(3, steps_total, "Allocate new storage")
6937
    iv_names = self._CreateNewStorage(self.target_node)
6938

    
6939
    # Step: for each lv, detach+rename*2+attach
6940
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
6941
    for dev, old_lvs, new_lvs in iv_names.itervalues():
6942
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
6943

    
6944
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
6945
                                                     old_lvs)
6946
      result.Raise("Can't detach drbd from local storage on node"
6947
                   " %s for device %s" % (self.target_node, dev.iv_name))
6948
      #dev.children = []
6949
      #cfg.Update(instance)
6950

    
6951
      # ok, we created the new LVs, so now we know we have the needed
6952
      # storage; as such, we proceed on the target node to rename
6953
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
6954
      # using the assumption that logical_id == physical_id (which in
6955
      # turn is the unique_id on that node)
6956

    
6957
      # FIXME(iustin): use a better name for the replaced LVs
6958
      temp_suffix = int(time.time())
6959
      ren_fn = lambda d, suff: (d.physical_id[0],
6960
                                d.physical_id[1] + "_replaced-%s" % suff)
6961

    
6962
      # Build the rename list based on what LVs exist on the node
6963
      rename_old_to_new = []
6964
      for to_ren in old_lvs:
6965
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
6966
        if not result.fail_msg and result.payload:
6967
          # device exists
6968
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
6969

    
6970
      self.lu.LogInfo("Renaming the old LVs on the target node")
6971
      result = self.rpc.call_blockdev_rename(self.target_node,
6972
                                             rename_old_to_new)
6973
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
6974

    
6975
      # Now we rename the new LVs to the old LVs
6976
      self.lu.LogInfo("Renaming the new LVs on the target node")
6977
      rename_new_to_old = [(new, old.physical_id)
6978
                           for old, new in zip(old_lvs, new_lvs)]
6979
      result = self.rpc.call_blockdev_rename(self.target_node,
6980
                                             rename_new_to_old)
6981
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
6982

    
6983
      for old, new in zip(old_lvs, new_lvs):
6984
        new.logical_id = old.logical_id
6985
        self.cfg.SetDiskID(new, self.target_node)
6986

    
6987
      for disk in old_lvs:
6988
        disk.logical_id = ren_fn(disk, temp_suffix)
6989
        self.cfg.SetDiskID(disk, self.target_node)
6990

    
6991
      # Now that the new lvs have the old name, we can add them to the device
6992
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
6993
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
6994
                                                  new_lvs)
6995
      msg = result.fail_msg
6996
      if msg:
6997
        for new_lv in new_lvs:
6998
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
6999
                                               new_lv).fail_msg
7000
          if msg2:
7001
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
7002
                               hint=("cleanup manually the unused logical"
7003
                                     "volumes"))
7004
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
7005

    
7006
      dev.children = new_lvs
7007

    
7008
      self.cfg.Update(self.instance, feedback_fn)
7009

    
7010
    cstep = 5
7011
    if self.early_release:
7012
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7013
      cstep += 1
7014
      self._RemoveOldStorage(self.target_node, iv_names)
7015
      # only release the lock if we're doing secondary replace, since
7016
      # we use the primary node later
7017
      if self.target_node != self.instance.primary_node:
7018
        self._ReleaseNodeLock(self.target_node)
7019

    
7020
    # Wait for sync
7021
    # This can fail as the old devices are degraded and _WaitForSync
7022
    # does a combined result over all disks, so we don't check its return value
7023
    self.lu.LogStep(cstep, steps_total, "Sync devices")
7024
    cstep += 1
7025
    _WaitForSync(self.lu, self.instance)
7026

    
7027
    # Check all devices manually
7028
    self._CheckDevices(self.instance.primary_node, iv_names)
7029

    
7030
    # Step: remove old storage
7031
    if not self.early_release:
7032
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7033
      cstep += 1
7034
      self._RemoveOldStorage(self.target_node, iv_names)
7035

    
7036
  def _ExecDrbd8Secondary(self, feedback_fn):
7037
    """Replace the secondary node for DRBD 8.
7038

7039
    The algorithm for replace is quite complicated:
7040
      - for all disks of the instance:
7041
        - create new LVs on the new node with same names
7042
        - shutdown the drbd device on the old secondary
7043
        - disconnect the drbd network on the primary
7044
        - create the drbd device on the new secondary
7045
        - network attach the drbd on the primary, using an artifice:
7046
          the drbd code for Attach() will connect to the network if it
7047
          finds a device which is connected to the good local disks but
7048
          not network enabled
7049
      - wait for sync across all devices
7050
      - remove all disks from the old secondary
7051

7052
    Failures are not very well handled.
7053

7054
    """
7055
    steps_total = 6
7056

    
7057
    # Step: check device activation
7058
    self.lu.LogStep(1, steps_total, "Check device existence")
7059
    self._CheckDisksExistence([self.instance.primary_node])
7060
    self._CheckVolumeGroup([self.instance.primary_node])
7061

    
7062
    # Step: check other node consistency
7063
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7064
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
7065

    
7066
    # Step: create new storage
7067
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7068
    for idx, dev in enumerate(self.instance.disks):
7069
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
7070
                      (self.new_node, idx))
7071
      # we pass force_create=True to force LVM creation
7072
      for new_lv in dev.children:
7073
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
7074
                        _GetInstanceInfoText(self.instance), False)
7075

    
7076
    # Step 4: dbrd minors and drbd setups changes
7077
    # after this, we must manually remove the drbd minors on both the
7078
    # error and the success paths
7079
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7080
    minors = self.cfg.AllocateDRBDMinor([self.new_node
7081
                                         for dev in self.instance.disks],
7082
                                        self.instance.name)
7083
    logging.debug("Allocated minors %r", minors)
7084

    
7085
    iv_names = {}
7086
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
7087
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
7088
                      (self.new_node, idx))
7089
      # create new devices on new_node; note that we create two IDs:
7090
      # one without port, so the drbd will be activated without
7091
      # networking information on the new node at this stage, and one
7092
      # with network, for the latter activation in step 4
7093
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
7094
      if self.instance.primary_node == o_node1:
7095
        p_minor = o_minor1
7096
      else:
7097
        assert self.instance.primary_node == o_node2, "Three-node instance?"
7098
        p_minor = o_minor2
7099

    
7100
      new_alone_id = (self.instance.primary_node, self.new_node, None,
7101
                      p_minor, new_minor, o_secret)
7102
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
7103
                    p_minor, new_minor, o_secret)
7104

    
7105
      iv_names[idx] = (dev, dev.children, new_net_id)
7106
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
7107
                    new_net_id)
7108
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
7109
                              logical_id=new_alone_id,
7110
                              children=dev.children,
7111
                              size=dev.size)
7112
      try:
7113
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
7114
                              _GetInstanceInfoText(self.instance), False)
7115
      except errors.GenericError:
7116
        self.cfg.ReleaseDRBDMinors(self.instance.name)
7117
        raise
7118

    
7119
    # We have new devices, shutdown the drbd on the old secondary
7120
    for idx, dev in enumerate(self.instance.disks):
7121
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
7122
      self.cfg.SetDiskID(dev, self.target_node)
7123
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
7124
      if msg:
7125
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
7126
                           "node: %s" % (idx, msg),
7127
                           hint=("Please cleanup this device manually as"
7128
                                 " soon as possible"))
7129

    
7130
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
7131
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
7132
                                               self.node_secondary_ip,
7133
                                               self.instance.disks)\
7134
                                              [self.instance.primary_node]
7135

    
7136
    msg = result.fail_msg
7137
    if msg:
7138
      # detaches didn't succeed (unlikely)
7139
      self.cfg.ReleaseDRBDMinors(self.instance.name)
7140
      raise errors.OpExecError("Can't detach the disks from the network on"
7141
                               " old node: %s" % (msg,))
7142

    
7143
    # if we managed to detach at least one, we update all the disks of
7144
    # the instance to point to the new secondary
7145
    self.lu.LogInfo("Updating instance configuration")
7146
    for dev, _, new_logical_id in iv_names.itervalues():
7147
      dev.logical_id = new_logical_id
7148
      self.cfg.SetDiskID(dev, self.instance.primary_node)
7149

    
7150
    self.cfg.Update(self.instance, feedback_fn)
7151

    
7152
    # and now perform the drbd attach
7153
    self.lu.LogInfo("Attaching primary drbds to new secondary"
7154
                    " (standalone => connected)")
7155
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
7156
                                            self.new_node],
7157
                                           self.node_secondary_ip,
7158
                                           self.instance.disks,
7159
                                           self.instance.name,
7160
                                           False)
7161
    for to_node, to_result in result.items():
7162
      msg = to_result.fail_msg
7163
      if msg:
7164
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
7165
                           to_node, msg,
7166
                           hint=("please do a gnt-instance info to see the"
7167
                                 " status of disks"))
7168
    cstep = 5
7169
    if self.early_release:
7170
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7171
      cstep += 1
7172
      self._RemoveOldStorage(self.target_node, iv_names)
7173
      self._ReleaseNodeLock([self.target_node, self.new_node])
7174

    
7175
    # Wait for sync
7176
    # This can fail as the old devices are degraded and _WaitForSync
7177
    # does a combined result over all disks, so we don't check its return value
7178
    self.lu.LogStep(cstep, steps_total, "Sync devices")
7179
    cstep += 1
7180
    _WaitForSync(self.lu, self.instance)
7181

    
7182
    # Check all devices manually
7183
    self._CheckDevices(self.instance.primary_node, iv_names)
7184

    
7185
    # Step: remove old storage
7186
    if not self.early_release:
7187
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7188
      self._RemoveOldStorage(self.target_node, iv_names)
7189

    
7190

    
7191
class LURepairNodeStorage(NoHooksLU):
7192
  """Repairs the volume group on a node.
7193

7194
  """
7195
  _OP_REQP = ["node_name"]
7196
  REQ_BGL = False
7197

    
7198
  def CheckArguments(self):
7199
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
7200
    if node_name is None:
7201
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name,
7202
                                 errors.ECODE_NOENT)
7203

    
7204
    self.op.node_name = node_name
7205

    
7206
  def ExpandNames(self):
7207
    self.needed_locks = {
7208
      locking.LEVEL_NODE: [self.op.node_name],
7209
      }
7210

    
7211
  def _CheckFaultyDisks(self, instance, node_name):
7212
    """Ensure faulty disks abort the opcode or at least warn."""
7213
    try:
7214
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
7215
                                  node_name, True):
7216
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
7217
                                   " node '%s'" % (instance.name, node_name),
7218
                                   errors.ECODE_STATE)
7219
    except errors.OpPrereqError, err:
7220
      if self.op.ignore_consistency:
7221
        self.proc.LogWarning(str(err.args[0]))
7222
      else:
7223
        raise
7224

    
7225
  def CheckPrereq(self):
7226
    """Check prerequisites.
7227

7228
    """
7229
    storage_type = self.op.storage_type
7230

    
7231
    if (constants.SO_FIX_CONSISTENCY not in
7232
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
7233
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
7234
                                 " repaired" % storage_type,
7235
                                 errors.ECODE_INVAL)
7236

    
7237
    # Check whether any instance on this node has faulty disks
7238
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
7239
      if not inst.admin_up:
7240
        continue
7241
      check_nodes = set(inst.all_nodes)
7242
      check_nodes.discard(self.op.node_name)
7243
      for inst_node_name in check_nodes:
7244
        self._CheckFaultyDisks(inst, inst_node_name)
7245

    
7246
  def Exec(self, feedback_fn):
7247
    feedback_fn("Repairing storage unit '%s' on %s ..." %
7248
                (self.op.name, self.op.node_name))
7249

    
7250
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
7251
    result = self.rpc.call_storage_execute(self.op.node_name,
7252
                                           self.op.storage_type, st_args,
7253
                                           self.op.name,
7254
                                           constants.SO_FIX_CONSISTENCY)
7255
    result.Raise("Failed to repair storage unit '%s' on %s" %
7256
                 (self.op.name, self.op.node_name))
7257

    
7258

    
7259
class LUGrowDisk(LogicalUnit):
7260
  """Grow a disk of an instance.
7261

7262
  """
7263
  HPATH = "disk-grow"
7264
  HTYPE = constants.HTYPE_INSTANCE
7265
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
7266
  REQ_BGL = False
7267

    
7268
  def ExpandNames(self):
7269
    self._ExpandAndLockInstance()
7270
    self.needed_locks[locking.LEVEL_NODE] = []
7271
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7272

    
7273
  def DeclareLocks(self, level):
7274
    if level == locking.LEVEL_NODE:
7275
      self._LockInstancesNodes()
7276

    
7277
  def BuildHooksEnv(self):
7278
    """Build hooks env.
7279

7280
    This runs on the master, the primary and all the secondaries.
7281

7282
    """
7283
    env = {
7284
      "DISK": self.op.disk,
7285
      "AMOUNT": self.op.amount,
7286
      }
7287
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
7288
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
7289
    return env, nl, nl
7290

    
7291
  def CheckPrereq(self):
7292
    """Check prerequisites.
7293

7294
    This checks that the instance is in the cluster.
7295

7296
    """
7297
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7298
    assert instance is not None, \
7299
      "Cannot retrieve locked instance %s" % self.op.instance_name
7300
    nodenames = list(instance.all_nodes)
7301
    for node in nodenames:
7302
      _CheckNodeOnline(self, node)
7303

    
7304

    
7305
    self.instance = instance
7306

    
7307
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
7308
      raise errors.OpPrereqError("Instance's disk layout does not support"
7309
                                 " growing.", errors.ECODE_INVAL)
7310

    
7311
    self.disk = instance.FindDisk(self.op.disk)
7312

    
7313
    nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
7314
                                       instance.hypervisor)
7315
    for node in nodenames:
7316
      info = nodeinfo[node]
7317
      info.Raise("Cannot get current information from node %s" % node)
7318
      vg_free = info.payload.get('vg_free', None)
7319
      if not isinstance(vg_free, int):
7320
        raise errors.OpPrereqError("Can't compute free disk space on"
7321
                                   " node %s" % node, errors.ECODE_ENVIRON)
7322
      if self.op.amount > vg_free:
7323
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
7324
                                   " %d MiB available, %d MiB required" %
7325
                                   (node, vg_free, self.op.amount),
7326
                                   errors.ECODE_NORES)
7327

    
7328
  def Exec(self, feedback_fn):
7329
    """Execute disk grow.
7330

7331
    """
7332
    instance = self.instance
7333
    disk = self.disk
7334
    for node in instance.all_nodes:
7335
      self.cfg.SetDiskID(disk, node)
7336
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
7337
      result.Raise("Grow request failed to node %s" % node)
7338

    
7339
      # TODO: Rewrite code to work properly
7340
      # DRBD goes into sync mode for a short amount of time after executing the
7341
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
7342
      # calling "resize" in sync mode fails. Sleeping for a short amount of
7343
      # time is a work-around.
7344
      time.sleep(5)
7345

    
7346
    disk.RecordGrow(self.op.amount)
7347
    self.cfg.Update(instance, feedback_fn)
7348
    if self.op.wait_for_sync:
7349
      disk_abort = not _WaitForSync(self, instance)
7350
      if disk_abort:
7351
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
7352
                             " status.\nPlease check the instance.")
7353

    
7354

    
7355
class LUQueryInstanceData(NoHooksLU):
7356
  """Query runtime instance data.
7357

7358
  """
7359
  _OP_REQP = ["instances", "static"]
7360
  REQ_BGL = False
7361

    
7362
  def ExpandNames(self):
7363
    self.needed_locks = {}
7364
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
7365

    
7366
    if not isinstance(self.op.instances, list):
7367
      raise errors.OpPrereqError("Invalid argument type 'instances'",
7368
                                 errors.ECODE_INVAL)
7369

    
7370
    if self.op.instances:
7371
      self.wanted_names = []
7372
      for name in self.op.instances:
7373
        full_name = self.cfg.ExpandInstanceName(name)
7374
        if full_name is None:
7375
          raise errors.OpPrereqError("Instance '%s' not known" % name,
7376
                                     errors.ECODE_NOENT)
7377
        self.wanted_names.append(full_name)
7378
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
7379
    else:
7380
      self.wanted_names = None
7381
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
7382

    
7383
    self.needed_locks[locking.LEVEL_NODE] = []
7384
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7385

    
7386
  def DeclareLocks(self, level):
7387
    if level == locking.LEVEL_NODE:
7388
      self._LockInstancesNodes()
7389

    
7390
  def CheckPrereq(self):
7391
    """Check prerequisites.
7392

7393
    This only checks the optional instance list against the existing names.
7394

7395
    """
7396
    if self.wanted_names is None:
7397
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
7398

    
7399
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
7400
                             in self.wanted_names]
7401
    return
7402

    
7403
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
7404
    """Returns the status of a block device
7405

7406
    """
7407
    if self.op.static or not node:
7408
      return None
7409

    
7410
    self.cfg.SetDiskID(dev, node)
7411

    
7412
    result = self.rpc.call_blockdev_find(node, dev)
7413
    if result.offline:
7414
      return None
7415

    
7416
    result.Raise("Can't compute disk status for %s" % instance_name)
7417

    
7418
    status = result.payload
7419
    if status is None:
7420
      return None
7421

    
7422
    return (status.dev_path, status.major, status.minor,
7423
            status.sync_percent, status.estimated_time,
7424
            status.is_degraded, status.ldisk_status)
7425

    
7426
  def _ComputeDiskStatus(self, instance, snode, dev):
7427
    """Compute block device status.
7428

7429
    """
7430
    if dev.dev_type in constants.LDS_DRBD:
7431
      # we change the snode then (otherwise we use the one passed in)
7432
      if dev.logical_id[0] == instance.primary_node:
7433
        snode = dev.logical_id[1]
7434
      else:
7435
        snode = dev.logical_id[0]
7436

    
7437
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
7438
                                              instance.name, dev)
7439
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
7440

    
7441
    if dev.children:
7442
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
7443
                      for child in dev.children]
7444
    else:
7445
      dev_children = []
7446

    
7447
    data = {
7448
      "iv_name": dev.iv_name,
7449
      "dev_type": dev.dev_type,
7450
      "logical_id": dev.logical_id,
7451
      "physical_id": dev.physical_id,
7452
      "pstatus": dev_pstatus,
7453
      "sstatus": dev_sstatus,
7454
      "children": dev_children,
7455
      "mode": dev.mode,
7456
      "size": dev.size,
7457
      }
7458

    
7459
    return data
7460

    
7461
  def Exec(self, feedback_fn):
7462
    """Gather and return data"""
7463
    result = {}
7464

    
7465
    cluster = self.cfg.GetClusterInfo()
7466

    
7467
    for instance in self.wanted_instances:
7468
      if not self.op.static:
7469
        remote_info = self.rpc.call_instance_info(instance.primary_node,
7470
                                                  instance.name,
7471
                                                  instance.hypervisor)
7472
        remote_info.Raise("Error checking node %s" % instance.primary_node)
7473
        remote_info = remote_info.payload
7474
        if remote_info and "state" in remote_info:
7475
          remote_state = "up"
7476
        else:
7477
          remote_state = "down"
7478
      else:
7479
        remote_state = None
7480
      if instance.admin_up:
7481
        config_state = "up"
7482
      else:
7483
        config_state = "down"
7484

    
7485
      disks = [self._ComputeDiskStatus(instance, None, device)
7486
               for device in instance.disks]
7487

    
7488
      idict = {
7489
        "name": instance.name,
7490
        "config_state": config_state,
7491
        "run_state": remote_state,
7492
        "pnode": instance.primary_node,
7493
        "snodes": instance.secondary_nodes,
7494
        "os": instance.os,
7495
        # this happens to be the same format used for hooks
7496
        "nics": _NICListToTuple(self, instance.nics),
7497
        "disks": disks,
7498
        "hypervisor": instance.hypervisor,
7499
        "network_port": instance.network_port,
7500
        "hv_instance": instance.hvparams,
7501
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
7502
        "be_instance": instance.beparams,
7503
        "be_actual": cluster.FillBE(instance),
7504
        "serial_no": instance.serial_no,
7505
        "mtime": instance.mtime,
7506
        "ctime": instance.ctime,
7507
        "uuid": instance.uuid,
7508
        }
7509

    
7510
      result[instance.name] = idict
7511

    
7512
    return result
7513

    
7514

    
7515
class LUSetInstanceParams(LogicalUnit):
7516
  """Modifies an instances's parameters.
7517

7518
  """
7519
  HPATH = "instance-modify"
7520
  HTYPE = constants.HTYPE_INSTANCE
7521
  _OP_REQP = ["instance_name"]
7522
  REQ_BGL = False
7523

    
7524
  def CheckArguments(self):
7525
    if not hasattr(self.op, 'nics'):
7526
      self.op.nics = []
7527
    if not hasattr(self.op, 'disks'):
7528
      self.op.disks = []
7529
    if not hasattr(self.op, 'beparams'):
7530
      self.op.beparams = {}
7531
    if not hasattr(self.op, 'hvparams'):
7532
      self.op.hvparams = {}
7533
    self.op.force = getattr(self.op, "force", False)
7534
    if not (self.op.nics or self.op.disks or
7535
            self.op.hvparams or self.op.beparams):
7536
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
7537

    
7538
    if self.op.hvparams:
7539
      _CheckGlobalHvParams(self.op.hvparams)
7540

    
7541
    # Disk validation
7542
    disk_addremove = 0
7543
    for disk_op, disk_dict in self.op.disks:
7544
      if disk_op == constants.DDM_REMOVE:
7545
        disk_addremove += 1
7546
        continue
7547
      elif disk_op == constants.DDM_ADD:
7548
        disk_addremove += 1
7549
      else:
7550
        if not isinstance(disk_op, int):
7551
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
7552
        if not isinstance(disk_dict, dict):
7553
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
7554
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
7555

    
7556
      if disk_op == constants.DDM_ADD:
7557
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
7558
        if mode not in constants.DISK_ACCESS_SET:
7559
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
7560
                                     errors.ECODE_INVAL)
7561
        size = disk_dict.get('size', None)
7562
        if size is None:
7563
          raise errors.OpPrereqError("Required disk parameter size missing",
7564
                                     errors.ECODE_INVAL)
7565
        try:
7566
          size = int(size)
7567
        except (TypeError, ValueError), err:
7568
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
7569
                                     str(err), errors.ECODE_INVAL)
7570
        disk_dict['size'] = size
7571
      else:
7572
        # modification of disk
7573
        if 'size' in disk_dict:
7574
          raise errors.OpPrereqError("Disk size change not possible, use"
7575
                                     " grow-disk", errors.ECODE_INVAL)
7576

    
7577
    if disk_addremove > 1:
7578
      raise errors.OpPrereqError("Only one disk add or remove operation"
7579
                                 " supported at a time", errors.ECODE_INVAL)
7580

    
7581
    # NIC validation
7582
    nic_addremove = 0
7583
    for nic_op, nic_dict in self.op.nics:
7584
      if nic_op == constants.DDM_REMOVE:
7585
        nic_addremove += 1
7586
        continue
7587
      elif nic_op == constants.DDM_ADD:
7588
        nic_addremove += 1
7589
      else:
7590
        if not isinstance(nic_op, int):
7591
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
7592
        if not isinstance(nic_dict, dict):
7593
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
7594
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
7595

    
7596
      # nic_dict should be a dict
7597
      nic_ip = nic_dict.get('ip', None)
7598
      if nic_ip is not None:
7599
        if nic_ip.lower() == constants.VALUE_NONE:
7600
          nic_dict['ip'] = None
7601
        else:
7602
          if not utils.IsValidIP(nic_ip):
7603
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
7604
                                       errors.ECODE_INVAL)
7605

    
7606
      nic_bridge = nic_dict.get('bridge', None)
7607
      nic_link = nic_dict.get('link', None)
7608
      if nic_bridge and nic_link:
7609
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7610
                                   " at the same time", errors.ECODE_INVAL)
7611
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
7612
        nic_dict['bridge'] = None
7613
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
7614
        nic_dict['link'] = None
7615

    
7616
      if nic_op == constants.DDM_ADD:
7617
        nic_mac = nic_dict.get('mac', None)
7618
        if nic_mac is None:
7619
          nic_dict['mac'] = constants.VALUE_AUTO
7620

    
7621
      if 'mac' in nic_dict:
7622
        nic_mac = nic_dict['mac']
7623
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7624
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
7625

    
7626
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
7627
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
7628
                                     " modifying an existing nic",
7629
                                     errors.ECODE_INVAL)
7630

    
7631
    if nic_addremove > 1:
7632
      raise errors.OpPrereqError("Only one NIC add or remove operation"
7633
                                 " supported at a time", errors.ECODE_INVAL)
7634

    
7635
  def ExpandNames(self):
7636
    self._ExpandAndLockInstance()
7637
    self.needed_locks[locking.LEVEL_NODE] = []
7638
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7639

    
7640
  def DeclareLocks(self, level):
7641
    if level == locking.LEVEL_NODE:
7642
      self._LockInstancesNodes()
7643

    
7644
  def BuildHooksEnv(self):
7645
    """Build hooks env.
7646

7647
    This runs on the master, primary and secondaries.
7648

7649
    """
7650
    args = dict()
7651
    if constants.BE_MEMORY in self.be_new:
7652
      args['memory'] = self.be_new[constants.BE_MEMORY]
7653
    if constants.BE_VCPUS in self.be_new:
7654
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
7655
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
7656
    # information at all.
7657
    if self.op.nics:
7658
      args['nics'] = []
7659
      nic_override = dict(self.op.nics)
7660
      c_nicparams = self.cluster.nicparams[constants.PP_DEFAULT]
7661
      for idx, nic in enumerate(self.instance.nics):
7662
        if idx in nic_override:
7663
          this_nic_override = nic_override[idx]
7664
        else:
7665
          this_nic_override = {}
7666
        if 'ip' in this_nic_override:
7667
          ip = this_nic_override['ip']
7668
        else:
7669
          ip = nic.ip
7670
        if 'mac' in this_nic_override:
7671
          mac = this_nic_override['mac']
7672
        else:
7673
          mac = nic.mac
7674
        if idx in self.nic_pnew:
7675
          nicparams = self.nic_pnew[idx]
7676
        else:
7677
          nicparams = objects.FillDict(c_nicparams, nic.nicparams)
7678
        mode = nicparams[constants.NIC_MODE]
7679
        link = nicparams[constants.NIC_LINK]
7680
        args['nics'].append((ip, mac, mode, link))
7681
      if constants.DDM_ADD in nic_override:
7682
        ip = nic_override[constants.DDM_ADD].get('ip', None)
7683
        mac = nic_override[constants.DDM_ADD]['mac']
7684
        nicparams = self.nic_pnew[constants.DDM_ADD]
7685
        mode = nicparams[constants.NIC_MODE]
7686
        link = nicparams[constants.NIC_LINK]
7687
        args['nics'].append((ip, mac, mode, link))
7688
      elif constants.DDM_REMOVE in nic_override:
7689
        del args['nics'][-1]
7690

    
7691
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
7692
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
7693
    return env, nl, nl
7694

    
7695
  @staticmethod
7696
  def _GetUpdatedParams(old_params, update_dict,
7697
                        default_values, parameter_types):
7698
    """Return the new params dict for the given params.
7699

7700
    @type old_params: dict
7701
    @param old_params: old parameters
7702
    @type update_dict: dict
7703
    @param update_dict: dict containing new parameter values,
7704
                        or constants.VALUE_DEFAULT to reset the
7705
                        parameter to its default value
7706
    @type default_values: dict
7707
    @param default_values: default values for the filled parameters
7708
    @type parameter_types: dict
7709
    @param parameter_types: dict mapping target dict keys to types
7710
                            in constants.ENFORCEABLE_TYPES
7711
    @rtype: (dict, dict)
7712
    @return: (new_parameters, filled_parameters)
7713

7714
    """
7715
    params_copy = copy.deepcopy(old_params)
7716
    for key, val in update_dict.iteritems():
7717
      if val == constants.VALUE_DEFAULT:
7718
        try:
7719
          del params_copy[key]
7720
        except KeyError:
7721
          pass
7722
      else:
7723
        params_copy[key] = val
7724
    utils.ForceDictType(params_copy, parameter_types)
7725
    params_filled = objects.FillDict(default_values, params_copy)
7726
    return (params_copy, params_filled)
7727

    
7728
  def CheckPrereq(self):
7729
    """Check prerequisites.
7730

7731
    This only checks the instance list against the existing names.
7732

7733
    """
7734
    self.force = self.op.force
7735

    
7736
    # checking the new params on the primary/secondary nodes
7737

    
7738
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7739
    cluster = self.cluster = self.cfg.GetClusterInfo()
7740
    assert self.instance is not None, \
7741
      "Cannot retrieve locked instance %s" % self.op.instance_name
7742
    pnode = instance.primary_node
7743
    nodelist = list(instance.all_nodes)
7744

    
7745
    # hvparams processing
7746
    if self.op.hvparams:
7747
      i_hvdict, hv_new = self._GetUpdatedParams(
7748
                             instance.hvparams, self.op.hvparams,
7749
                             cluster.hvparams[instance.hypervisor],
7750
                             constants.HVS_PARAMETER_TYPES)
7751
      # local check
7752
      hypervisor.GetHypervisor(
7753
        instance.hypervisor).CheckParameterSyntax(hv_new)
7754
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
7755
      self.hv_new = hv_new # the new actual values
7756
      self.hv_inst = i_hvdict # the new dict (without defaults)
7757
    else:
7758
      self.hv_new = self.hv_inst = {}
7759

    
7760
    # beparams processing
7761
    if self.op.beparams:
7762
      i_bedict, be_new = self._GetUpdatedParams(
7763
                             instance.beparams, self.op.beparams,
7764
                             cluster.beparams[constants.PP_DEFAULT],
7765
                             constants.BES_PARAMETER_TYPES)
7766
      self.be_new = be_new # the new actual values
7767
      self.be_inst = i_bedict # the new dict (without defaults)
7768
    else:
7769
      self.be_new = self.be_inst = {}
7770

    
7771
    self.warn = []
7772

    
7773
    if constants.BE_MEMORY in self.op.beparams and not self.force:
7774
      mem_check_list = [pnode]
7775
      if be_new[constants.BE_AUTO_BALANCE]:
7776
        # either we changed auto_balance to yes or it was from before
7777
        mem_check_list.extend(instance.secondary_nodes)
7778
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
7779
                                                  instance.hypervisor)
7780
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
7781
                                         instance.hypervisor)
7782
      pninfo = nodeinfo[pnode]
7783
      msg = pninfo.fail_msg
7784
      if msg:
7785
        # Assume the primary node is unreachable and go ahead
7786
        self.warn.append("Can't get info from primary node %s: %s" %
7787
                         (pnode,  msg))
7788
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
7789
        self.warn.append("Node data from primary node %s doesn't contain"
7790
                         " free memory information" % pnode)
7791
      elif instance_info.fail_msg:
7792
        self.warn.append("Can't get instance runtime information: %s" %
7793
                        instance_info.fail_msg)
7794
      else:
7795
        if instance_info.payload:
7796
          current_mem = int(instance_info.payload['memory'])
7797
        else:
7798
          # Assume instance not running
7799
          # (there is a slight race condition here, but it's not very probable,
7800
          # and we have no other way to check)
7801
          current_mem = 0
7802
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
7803
                    pninfo.payload['memory_free'])
7804
        if miss_mem > 0:
7805
          raise errors.OpPrereqError("This change will prevent the instance"
7806
                                     " from starting, due to %d MB of memory"
7807
                                     " missing on its primary node" % miss_mem,
7808
                                     errors.ECODE_NORES)
7809

    
7810
      if be_new[constants.BE_AUTO_BALANCE]:
7811
        for node, nres in nodeinfo.items():
7812
          if node not in instance.secondary_nodes:
7813
            continue
7814
          msg = nres.fail_msg
7815
          if msg:
7816
            self.warn.append("Can't get info from secondary node %s: %s" %
7817
                             (node, msg))
7818
          elif not isinstance(nres.payload.get('memory_free', None), int):
7819
            self.warn.append("Secondary node %s didn't return free"
7820
                             " memory information" % node)
7821
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
7822
            self.warn.append("Not enough memory to failover instance to"
7823
                             " secondary node %s" % node)
7824

    
7825
    # NIC processing
7826
    self.nic_pnew = {}
7827
    self.nic_pinst = {}
7828
    for nic_op, nic_dict in self.op.nics:
7829
      if nic_op == constants.DDM_REMOVE:
7830
        if not instance.nics:
7831
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
7832
                                     errors.ECODE_INVAL)
7833
        continue
7834
      if nic_op != constants.DDM_ADD:
7835
        # an existing nic
7836
        if not instance.nics:
7837
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
7838
                                     " no NICs" % nic_op,
7839
                                     errors.ECODE_INVAL)
7840
        if nic_op < 0 or nic_op >= len(instance.nics):
7841
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
7842
                                     " are 0 to %d" %
7843
                                     (nic_op, len(instance.nics) - 1),
7844
                                     errors.ECODE_INVAL)
7845
        old_nic_params = instance.nics[nic_op].nicparams
7846
        old_nic_ip = instance.nics[nic_op].ip
7847
      else:
7848
        old_nic_params = {}
7849
        old_nic_ip = None
7850

    
7851
      update_params_dict = dict([(key, nic_dict[key])
7852
                                 for key in constants.NICS_PARAMETERS
7853
                                 if key in nic_dict])
7854

    
7855
      if 'bridge' in nic_dict:
7856
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
7857

    
7858
      new_nic_params, new_filled_nic_params = \
7859
          self._GetUpdatedParams(old_nic_params, update_params_dict,
7860
                                 cluster.nicparams[constants.PP_DEFAULT],
7861
                                 constants.NICS_PARAMETER_TYPES)
7862
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
7863
      self.nic_pinst[nic_op] = new_nic_params
7864
      self.nic_pnew[nic_op] = new_filled_nic_params
7865
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
7866

    
7867
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
7868
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
7869
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
7870
        if msg:
7871
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
7872
          if self.force:
7873
            self.warn.append(msg)
7874
          else:
7875
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
7876
      if new_nic_mode == constants.NIC_MODE_ROUTED:
7877
        if 'ip' in nic_dict:
7878
          nic_ip = nic_dict['ip']
7879
        else:
7880
          nic_ip = old_nic_ip
7881
        if nic_ip is None:
7882
          raise errors.OpPrereqError('Cannot set the nic ip to None'
7883
                                     ' on a routed nic', errors.ECODE_INVAL)
7884
      if 'mac' in nic_dict:
7885
        nic_mac = nic_dict['mac']
7886
        if nic_mac is None:
7887
          raise errors.OpPrereqError('Cannot set the nic mac to None',
7888
                                     errors.ECODE_INVAL)
7889
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7890
          # otherwise generate the mac
7891
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
7892
        else:
7893
          # or validate/reserve the current one
7894
          try:
7895
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
7896
          except errors.ReservationError:
7897
            raise errors.OpPrereqError("MAC address %s already in use"
7898
                                       " in cluster" % nic_mac,
7899
                                       errors.ECODE_NOTUNIQUE)
7900

    
7901
    # DISK processing
7902
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
7903
      raise errors.OpPrereqError("Disk operations not supported for"
7904
                                 " diskless instances",
7905
                                 errors.ECODE_INVAL)
7906
    for disk_op, _ in self.op.disks:
7907
      if disk_op == constants.DDM_REMOVE:
7908
        if len(instance.disks) == 1:
7909
          raise errors.OpPrereqError("Cannot remove the last disk of"
7910
                                     " an instance",
7911
                                     errors.ECODE_INVAL)
7912
        ins_l = self.rpc.call_instance_list([pnode], [instance.hypervisor])
7913
        ins_l = ins_l[pnode]
7914
        msg = ins_l.fail_msg
7915
        if msg:
7916
          raise errors.OpPrereqError("Can't contact node %s: %s" %
7917
                                     (pnode, msg), errors.ECODE_ENVIRON)
7918
        if instance.name in ins_l.payload:
7919
          raise errors.OpPrereqError("Instance is running, can't remove"
7920
                                     " disks.", errors.ECODE_STATE)
7921

    
7922
      if (disk_op == constants.DDM_ADD and
7923
          len(instance.nics) >= constants.MAX_DISKS):
7924
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
7925
                                   " add more" % constants.MAX_DISKS,
7926
                                   errors.ECODE_STATE)
7927
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
7928
        # an existing disk
7929
        if disk_op < 0 or disk_op >= len(instance.disks):
7930
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
7931
                                     " are 0 to %d" %
7932
                                     (disk_op, len(instance.disks)),
7933
                                     errors.ECODE_INVAL)
7934

    
7935
    return
7936

    
7937
  def Exec(self, feedback_fn):
7938
    """Modifies an instance.
7939

7940
    All parameters take effect only at the next restart of the instance.
7941

7942
    """
7943
    # Process here the warnings from CheckPrereq, as we don't have a
7944
    # feedback_fn there.
7945
    for warn in self.warn:
7946
      feedback_fn("WARNING: %s" % warn)
7947

    
7948
    result = []
7949
    instance = self.instance
7950
    # disk changes
7951
    for disk_op, disk_dict in self.op.disks:
7952
      if disk_op == constants.DDM_REMOVE:
7953
        # remove the last disk
7954
        device = instance.disks.pop()
7955
        device_idx = len(instance.disks)
7956
        for node, disk in device.ComputeNodeTree(instance.primary_node):
7957
          self.cfg.SetDiskID(disk, node)
7958
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
7959
          if msg:
7960
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
7961
                            " continuing anyway", device_idx, node, msg)
7962
        result.append(("disk/%d" % device_idx, "remove"))
7963
      elif disk_op == constants.DDM_ADD:
7964
        # add a new disk
7965
        if instance.disk_template == constants.DT_FILE:
7966
          file_driver, file_path = instance.disks[0].logical_id
7967
          file_path = os.path.dirname(file_path)
7968
        else:
7969
          file_driver = file_path = None
7970
        disk_idx_base = len(instance.disks)
7971
        new_disk = _GenerateDiskTemplate(self,
7972
                                         instance.disk_template,
7973
                                         instance.name, instance.primary_node,
7974
                                         instance.secondary_nodes,
7975
                                         [disk_dict],
7976
                                         file_path,
7977
                                         file_driver,
7978
                                         disk_idx_base)[0]
7979
        instance.disks.append(new_disk)
7980
        info = _GetInstanceInfoText(instance)
7981

    
7982
        logging.info("Creating volume %s for instance %s",
7983
                     new_disk.iv_name, instance.name)
7984
        # Note: this needs to be kept in sync with _CreateDisks
7985
        #HARDCODE
7986
        for node in instance.all_nodes:
7987
          f_create = node == instance.primary_node
7988
          try:
7989
            _CreateBlockDev(self, node, instance, new_disk,
7990
                            f_create, info, f_create)
7991
          except errors.OpExecError, err:
7992
            self.LogWarning("Failed to create volume %s (%s) on"
7993
                            " node %s: %s",
7994
                            new_disk.iv_name, new_disk, node, err)
7995
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
7996
                       (new_disk.size, new_disk.mode)))
7997
      else:
7998
        # change a given disk
7999
        instance.disks[disk_op].mode = disk_dict['mode']
8000
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
8001
    # NIC changes
8002
    for nic_op, nic_dict in self.op.nics:
8003
      if nic_op == constants.DDM_REMOVE:
8004
        # remove the last nic
8005
        del instance.nics[-1]
8006
        result.append(("nic.%d" % len(instance.nics), "remove"))
8007
      elif nic_op == constants.DDM_ADD:
8008
        # mac and bridge should be set, by now
8009
        mac = nic_dict['mac']
8010
        ip = nic_dict.get('ip', None)
8011
        nicparams = self.nic_pinst[constants.DDM_ADD]
8012
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
8013
        instance.nics.append(new_nic)
8014
        result.append(("nic.%d" % (len(instance.nics) - 1),
8015
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
8016
                       (new_nic.mac, new_nic.ip,
8017
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
8018
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
8019
                       )))
8020
      else:
8021
        for key in 'mac', 'ip':
8022
          if key in nic_dict:
8023
            setattr(instance.nics[nic_op], key, nic_dict[key])
8024
        if nic_op in self.nic_pinst:
8025
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
8026
        for key, val in nic_dict.iteritems():
8027
          result.append(("nic.%s/%d" % (key, nic_op), val))
8028

    
8029
    # hvparams changes
8030
    if self.op.hvparams:
8031
      instance.hvparams = self.hv_inst
8032
      for key, val in self.op.hvparams.iteritems():
8033
        result.append(("hv/%s" % key, val))
8034

    
8035
    # beparams changes
8036
    if self.op.beparams:
8037
      instance.beparams = self.be_inst
8038
      for key, val in self.op.beparams.iteritems():
8039
        result.append(("be/%s" % key, val))
8040

    
8041
    self.cfg.Update(instance, feedback_fn)
8042

    
8043
    return result
8044

    
8045

    
8046
class LUQueryExports(NoHooksLU):
8047
  """Query the exports list
8048

8049
  """
8050
  _OP_REQP = ['nodes']
8051
  REQ_BGL = False
8052

    
8053
  def ExpandNames(self):
8054
    self.needed_locks = {}
8055
    self.share_locks[locking.LEVEL_NODE] = 1
8056
    if not self.op.nodes:
8057
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8058
    else:
8059
      self.needed_locks[locking.LEVEL_NODE] = \
8060
        _GetWantedNodes(self, self.op.nodes)
8061

    
8062
  def CheckPrereq(self):
8063
    """Check prerequisites.
8064

8065
    """
8066
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
8067

    
8068
  def Exec(self, feedback_fn):
8069
    """Compute the list of all the exported system images.
8070

8071
    @rtype: dict
8072
    @return: a dictionary with the structure node->(export-list)
8073
        where export-list is a list of the instances exported on
8074
        that node.
8075

8076
    """
8077
    rpcresult = self.rpc.call_export_list(self.nodes)
8078
    result = {}
8079
    for node in rpcresult:
8080
      if rpcresult[node].fail_msg:
8081
        result[node] = False
8082
      else:
8083
        result[node] = rpcresult[node].payload
8084

    
8085
    return result
8086

    
8087

    
8088
class LUExportInstance(LogicalUnit):
8089
  """Export an instance to an image in the cluster.
8090

8091
  """
8092
  HPATH = "instance-export"
8093
  HTYPE = constants.HTYPE_INSTANCE
8094
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
8095
  REQ_BGL = False
8096

    
8097
  def CheckArguments(self):
8098
    """Check the arguments.
8099

8100
    """
8101
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
8102
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
8103

    
8104
  def ExpandNames(self):
8105
    self._ExpandAndLockInstance()
8106
    # FIXME: lock only instance primary and destination node
8107
    #
8108
    # Sad but true, for now we have do lock all nodes, as we don't know where
8109
    # the previous export might be, and and in this LU we search for it and
8110
    # remove it from its current node. In the future we could fix this by:
8111
    #  - making a tasklet to search (share-lock all), then create the new one,
8112
    #    then one to remove, after
8113
    #  - removing the removal operation altogether
8114
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8115

    
8116
  def DeclareLocks(self, level):
8117
    """Last minute lock declaration."""
8118
    # All nodes are locked anyway, so nothing to do here.
8119

    
8120
  def BuildHooksEnv(self):
8121
    """Build hooks env.
8122

8123
    This will run on the master, primary node and target node.
8124

8125
    """
8126
    env = {
8127
      "EXPORT_NODE": self.op.target_node,
8128
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
8129
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
8130
      }
8131
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8132
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node,
8133
          self.op.target_node]
8134
    return env, nl, nl
8135

    
8136
  def CheckPrereq(self):
8137
    """Check prerequisites.
8138

8139
    This checks that the instance and node names are valid.
8140

8141
    """
8142
    instance_name = self.op.instance_name
8143
    self.instance = self.cfg.GetInstanceInfo(instance_name)
8144
    assert self.instance is not None, \
8145
          "Cannot retrieve locked instance %s" % self.op.instance_name
8146
    _CheckNodeOnline(self, self.instance.primary_node)
8147

    
8148
    self.dst_node = self.cfg.GetNodeInfo(
8149
      self.cfg.ExpandNodeName(self.op.target_node))
8150

    
8151
    if self.dst_node is None:
8152
      # This is wrong node name, not a non-locked node
8153
      raise errors.OpPrereqError("Wrong node name %s" % self.op.target_node,
8154
                                 errors.ECODE_NOENT)
8155
    _CheckNodeOnline(self, self.dst_node.name)
8156
    _CheckNodeNotDrained(self, self.dst_node.name)
8157

    
8158
    # instance disk type verification
8159
    for disk in self.instance.disks:
8160
      if disk.dev_type == constants.LD_FILE:
8161
        raise errors.OpPrereqError("Export not supported for instances with"
8162
                                   " file-based disks", errors.ECODE_INVAL)
8163

    
8164
  def Exec(self, feedback_fn):
8165
    """Export an instance to an image in the cluster.
8166

8167
    """
8168
    instance = self.instance
8169
    dst_node = self.dst_node
8170
    src_node = instance.primary_node
8171

    
8172
    if self.op.shutdown:
8173
      # shutdown the instance, but not the disks
8174
      feedback_fn("Shutting down instance %s" % instance.name)
8175
      result = self.rpc.call_instance_shutdown(src_node, instance,
8176
                                               self.shutdown_timeout)
8177
      result.Raise("Could not shutdown instance %s on"
8178
                   " node %s" % (instance.name, src_node))
8179

    
8180
    vgname = self.cfg.GetVGName()
8181

    
8182
    snap_disks = []
8183

    
8184
    # set the disks ID correctly since call_instance_start needs the
8185
    # correct drbd minor to create the symlinks
8186
    for disk in instance.disks:
8187
      self.cfg.SetDiskID(disk, src_node)
8188

    
8189
    activate_disks = (not instance.admin_up)
8190

    
8191
    if activate_disks:
8192
      # Activate the instance disks if we'exporting a stopped instance
8193
      feedback_fn("Activating disks for %s" % instance.name)
8194
      _StartInstanceDisks(self, instance, None)
8195

    
8196
    try:
8197
      # per-disk results
8198
      dresults = []
8199
      try:
8200
        for idx, disk in enumerate(instance.disks):
8201
          feedback_fn("Creating a snapshot of disk/%s on node %s" %
8202
                      (idx, src_node))
8203

    
8204
          # result.payload will be a snapshot of an lvm leaf of the one we
8205
          # passed
8206
          result = self.rpc.call_blockdev_snapshot(src_node, disk)
8207
          msg = result.fail_msg
8208
          if msg:
8209
            self.LogWarning("Could not snapshot disk/%s on node %s: %s",
8210
                            idx, src_node, msg)
8211
            snap_disks.append(False)
8212
          else:
8213
            disk_id = (vgname, result.payload)
8214
            new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
8215
                                   logical_id=disk_id, physical_id=disk_id,
8216
                                   iv_name=disk.iv_name)
8217
            snap_disks.append(new_dev)
8218

    
8219
      finally:
8220
        if self.op.shutdown and instance.admin_up:
8221
          feedback_fn("Starting instance %s" % instance.name)
8222
          result = self.rpc.call_instance_start(src_node, instance, None, None)
8223
          msg = result.fail_msg
8224
          if msg:
8225
            _ShutdownInstanceDisks(self, instance)
8226
            raise errors.OpExecError("Could not start instance: %s" % msg)
8227

    
8228
      # TODO: check for size
8229

    
8230
      cluster_name = self.cfg.GetClusterName()
8231
      for idx, dev in enumerate(snap_disks):
8232
        feedback_fn("Exporting snapshot %s from %s to %s" %
8233
                    (idx, src_node, dst_node.name))
8234
        if dev:
8235
          # FIXME: pass debug from opcode to backend
8236
          result = self.rpc.call_snapshot_export(src_node, dev, dst_node.name,
8237
                                                 instance, cluster_name,
8238
                                                 idx, self.op.debug_level)
8239
          msg = result.fail_msg
8240
          if msg:
8241
            self.LogWarning("Could not export disk/%s from node %s to"
8242
                            " node %s: %s", idx, src_node, dst_node.name, msg)
8243
            dresults.append(False)
8244
          else:
8245
            dresults.append(True)
8246
          msg = self.rpc.call_blockdev_remove(src_node, dev).fail_msg
8247
          if msg:
8248
            self.LogWarning("Could not remove snapshot for disk/%d from node"
8249
                            " %s: %s", idx, src_node, msg)
8250
        else:
8251
          dresults.append(False)
8252

    
8253
      feedback_fn("Finalizing export on %s" % dst_node.name)
8254
      result = self.rpc.call_finalize_export(dst_node.name, instance,
8255
                                             snap_disks)
8256
      fin_resu = True
8257
      msg = result.fail_msg
8258
      if msg:
8259
        self.LogWarning("Could not finalize export for instance %s"
8260
                        " on node %s: %s", instance.name, dst_node.name, msg)
8261
        fin_resu = False
8262

    
8263
    finally:
8264
      if activate_disks:
8265
        feedback_fn("Deactivating disks for %s" % instance.name)
8266
        _ShutdownInstanceDisks(self, instance)
8267

    
8268
    nodelist = self.cfg.GetNodeList()
8269
    nodelist.remove(dst_node.name)
8270

    
8271
    # on one-node clusters nodelist will be empty after the removal
8272
    # if we proceed the backup would be removed because OpQueryExports
8273
    # substitutes an empty list with the full cluster node list.
8274
    iname = instance.name
8275
    if nodelist:
8276
      feedback_fn("Removing old exports for instance %s" % iname)
8277
      exportlist = self.rpc.call_export_list(nodelist)
8278
      for node in exportlist:
8279
        if exportlist[node].fail_msg:
8280
          continue
8281
        if iname in exportlist[node].payload:
8282
          msg = self.rpc.call_export_remove(node, iname).fail_msg
8283
          if msg:
8284
            self.LogWarning("Could not remove older export for instance %s"
8285
                            " on node %s: %s", iname, node, msg)
8286
    return fin_resu, dresults
8287

    
8288

    
8289
class LURemoveExport(NoHooksLU):
8290
  """Remove exports related to the named instance.
8291

8292
  """
8293
  _OP_REQP = ["instance_name"]
8294
  REQ_BGL = False
8295

    
8296
  def ExpandNames(self):
8297
    self.needed_locks = {}
8298
    # We need all nodes to be locked in order for RemoveExport to work, but we
8299
    # don't need to lock the instance itself, as nothing will happen to it (and
8300
    # we can remove exports also for a removed instance)
8301
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8302

    
8303
  def CheckPrereq(self):
8304
    """Check prerequisites.
8305
    """
8306
    pass
8307

    
8308
  def Exec(self, feedback_fn):
8309
    """Remove any export.
8310

8311
    """
8312
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
8313
    # If the instance was not found we'll try with the name that was passed in.
8314
    # This will only work if it was an FQDN, though.
8315
    fqdn_warn = False
8316
    if not instance_name:
8317
      fqdn_warn = True
8318
      instance_name = self.op.instance_name
8319

    
8320
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
8321
    exportlist = self.rpc.call_export_list(locked_nodes)
8322
    found = False
8323
    for node in exportlist:
8324
      msg = exportlist[node].fail_msg
8325
      if msg:
8326
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
8327
        continue
8328
      if instance_name in exportlist[node].payload:
8329
        found = True
8330
        result = self.rpc.call_export_remove(node, instance_name)
8331
        msg = result.fail_msg
8332
        if msg:
8333
          logging.error("Could not remove export for instance %s"
8334
                        " on node %s: %s", instance_name, node, msg)
8335

    
8336
    if fqdn_warn and not found:
8337
      feedback_fn("Export not found. If trying to remove an export belonging"
8338
                  " to a deleted instance please use its Fully Qualified"
8339
                  " Domain Name.")
8340

    
8341

    
8342
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
8343
  """Generic tags LU.
8344

8345
  This is an abstract class which is the parent of all the other tags LUs.
8346

8347
  """
8348

    
8349
  def ExpandNames(self):
8350
    self.needed_locks = {}
8351
    if self.op.kind == constants.TAG_NODE:
8352
      name = self.cfg.ExpandNodeName(self.op.name)
8353
      if name is None:
8354
        raise errors.OpPrereqError("Invalid node name (%s)" %
8355
                                   (self.op.name,), errors.ECODE_NOENT)
8356
      self.op.name = name
8357
      self.needed_locks[locking.LEVEL_NODE] = name
8358
    elif self.op.kind == constants.TAG_INSTANCE:
8359
      name = self.cfg.ExpandInstanceName(self.op.name)
8360
      if name is None:
8361
        raise errors.OpPrereqError("Invalid instance name (%s)" %
8362
                                   (self.op.name,), errors.ECODE_NOENT)
8363
      self.op.name = name
8364
      self.needed_locks[locking.LEVEL_INSTANCE] = name
8365

    
8366
  def CheckPrereq(self):
8367
    """Check prerequisites.
8368

8369
    """
8370
    if self.op.kind == constants.TAG_CLUSTER:
8371
      self.target = self.cfg.GetClusterInfo()
8372
    elif self.op.kind == constants.TAG_NODE:
8373
      self.target = self.cfg.GetNodeInfo(self.op.name)
8374
    elif self.op.kind == constants.TAG_INSTANCE:
8375
      self.target = self.cfg.GetInstanceInfo(self.op.name)
8376
    else:
8377
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
8378
                                 str(self.op.kind), errors.ECODE_INVAL)
8379

    
8380

    
8381
class LUGetTags(TagsLU):
8382
  """Returns the tags of a given object.
8383

8384
  """
8385
  _OP_REQP = ["kind", "name"]
8386
  REQ_BGL = False
8387

    
8388
  def Exec(self, feedback_fn):
8389
    """Returns the tag list.
8390

8391
    """
8392
    return list(self.target.GetTags())
8393

    
8394

    
8395
class LUSearchTags(NoHooksLU):
8396
  """Searches the tags for a given pattern.
8397

8398
  """
8399
  _OP_REQP = ["pattern"]
8400
  REQ_BGL = False
8401

    
8402
  def ExpandNames(self):
8403
    self.needed_locks = {}
8404

    
8405
  def CheckPrereq(self):
8406
    """Check prerequisites.
8407

8408
    This checks the pattern passed for validity by compiling it.
8409

8410
    """
8411
    try:
8412
      self.re = re.compile(self.op.pattern)
8413
    except re.error, err:
8414
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
8415
                                 (self.op.pattern, err), errors.ECODE_INVAL)
8416

    
8417
  def Exec(self, feedback_fn):
8418
    """Returns the tag list.
8419

8420
    """
8421
    cfg = self.cfg
8422
    tgts = [("/cluster", cfg.GetClusterInfo())]
8423
    ilist = cfg.GetAllInstancesInfo().values()
8424
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
8425
    nlist = cfg.GetAllNodesInfo().values()
8426
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
8427
    results = []
8428
    for path, target in tgts:
8429
      for tag in target.GetTags():
8430
        if self.re.search(tag):
8431
          results.append((path, tag))
8432
    return results
8433

    
8434

    
8435
class LUAddTags(TagsLU):
8436
  """Sets a tag on a given object.
8437

8438
  """
8439
  _OP_REQP = ["kind", "name", "tags"]
8440
  REQ_BGL = False
8441

    
8442
  def CheckPrereq(self):
8443
    """Check prerequisites.
8444

8445
    This checks the type and length of the tag name and value.
8446

8447
    """
8448
    TagsLU.CheckPrereq(self)
8449
    for tag in self.op.tags:
8450
      objects.TaggableObject.ValidateTag(tag)
8451

    
8452
  def Exec(self, feedback_fn):
8453
    """Sets the tag.
8454

8455
    """
8456
    try:
8457
      for tag in self.op.tags:
8458
        self.target.AddTag(tag)
8459
    except errors.TagError, err:
8460
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
8461
    self.cfg.Update(self.target, feedback_fn)
8462

    
8463

    
8464
class LUDelTags(TagsLU):
8465
  """Delete a list of tags from a given object.
8466

8467
  """
8468
  _OP_REQP = ["kind", "name", "tags"]
8469
  REQ_BGL = False
8470

    
8471
  def CheckPrereq(self):
8472
    """Check prerequisites.
8473

8474
    This checks that we have the given tag.
8475

8476
    """
8477
    TagsLU.CheckPrereq(self)
8478
    for tag in self.op.tags:
8479
      objects.TaggableObject.ValidateTag(tag)
8480
    del_tags = frozenset(self.op.tags)
8481
    cur_tags = self.target.GetTags()
8482
    if not del_tags <= cur_tags:
8483
      diff_tags = del_tags - cur_tags
8484
      diff_names = ["'%s'" % tag for tag in diff_tags]
8485
      diff_names.sort()
8486
      raise errors.OpPrereqError("Tag(s) %s not found" %
8487
                                 (",".join(diff_names)), errors.ECODE_NOENT)
8488

    
8489
  def Exec(self, feedback_fn):
8490
    """Remove the tag from the object.
8491

8492
    """
8493
    for tag in self.op.tags:
8494
      self.target.RemoveTag(tag)
8495
    self.cfg.Update(self.target, feedback_fn)
8496

    
8497

    
8498
class LUTestDelay(NoHooksLU):
8499
  """Sleep for a specified amount of time.
8500

8501
  This LU sleeps on the master and/or nodes for a specified amount of
8502
  time.
8503

8504
  """
8505
  _OP_REQP = ["duration", "on_master", "on_nodes"]
8506
  REQ_BGL = False
8507

    
8508
  def ExpandNames(self):
8509
    """Expand names and set required locks.
8510

8511
    This expands the node list, if any.
8512

8513
    """
8514
    self.needed_locks = {}
8515
    if self.op.on_nodes:
8516
      # _GetWantedNodes can be used here, but is not always appropriate to use
8517
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
8518
      # more information.
8519
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
8520
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
8521

    
8522
  def CheckPrereq(self):
8523
    """Check prerequisites.
8524

8525
    """
8526

    
8527
  def Exec(self, feedback_fn):
8528
    """Do the actual sleep.
8529

8530
    """
8531
    if self.op.on_master:
8532
      if not utils.TestDelay(self.op.duration):
8533
        raise errors.OpExecError("Error during master delay test")
8534
    if self.op.on_nodes:
8535
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
8536
      for node, node_result in result.items():
8537
        node_result.Raise("Failure during rpc call to node %s" % node)
8538

    
8539

    
8540
class IAllocator(object):
8541
  """IAllocator framework.
8542

8543
  An IAllocator instance has three sets of attributes:
8544
    - cfg that is needed to query the cluster
8545
    - input data (all members of the _KEYS class attribute are required)
8546
    - four buffer attributes (in|out_data|text), that represent the
8547
      input (to the external script) in text and data structure format,
8548
      and the output from it, again in two formats
8549
    - the result variables from the script (success, info, nodes) for
8550
      easy usage
8551

8552
  """
8553
  # pylint: disable-msg=R0902
8554
  # lots of instance attributes
8555
  _ALLO_KEYS = [
8556
    "mem_size", "disks", "disk_template",
8557
    "os", "tags", "nics", "vcpus", "hypervisor",
8558
    ]
8559
  _RELO_KEYS = [
8560
    "relocate_from",
8561
    ]
8562

    
8563
  def __init__(self, cfg, rpc, mode, name, **kwargs):
8564
    self.cfg = cfg
8565
    self.rpc = rpc
8566
    # init buffer variables
8567
    self.in_text = self.out_text = self.in_data = self.out_data = None
8568
    # init all input fields so that pylint is happy
8569
    self.mode = mode
8570
    self.name = name
8571
    self.mem_size = self.disks = self.disk_template = None
8572
    self.os = self.tags = self.nics = self.vcpus = None
8573
    self.hypervisor = None
8574
    self.relocate_from = None
8575
    # computed fields
8576
    self.required_nodes = None
8577
    # init result fields
8578
    self.success = self.info = self.nodes = None
8579
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
8580
      keyset = self._ALLO_KEYS
8581
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
8582
      keyset = self._RELO_KEYS
8583
    else:
8584
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
8585
                                   " IAllocator" % self.mode)
8586
    for key in kwargs:
8587
      if key not in keyset:
8588
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
8589
                                     " IAllocator" % key)
8590
      setattr(self, key, kwargs[key])
8591
    for key in keyset:
8592
      if key not in kwargs:
8593
        raise errors.ProgrammerError("Missing input parameter '%s' to"
8594
                                     " IAllocator" % key)
8595
    self._BuildInputData()
8596

    
8597
  def _ComputeClusterData(self):
8598
    """Compute the generic allocator input data.
8599

8600
    This is the data that is independent of the actual operation.
8601

8602
    """
8603
    cfg = self.cfg
8604
    cluster_info = cfg.GetClusterInfo()
8605
    # cluster data
8606
    data = {
8607
      "version": constants.IALLOCATOR_VERSION,
8608
      "cluster_name": cfg.GetClusterName(),
8609
      "cluster_tags": list(cluster_info.GetTags()),
8610
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
8611
      # we don't have job IDs
8612
      }
8613
    iinfo = cfg.GetAllInstancesInfo().values()
8614
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
8615

    
8616
    # node data
8617
    node_results = {}
8618
    node_list = cfg.GetNodeList()
8619

    
8620
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
8621
      hypervisor_name = self.hypervisor
8622
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
8623
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
8624

    
8625
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
8626
                                        hypervisor_name)
8627
    node_iinfo = \
8628
      self.rpc.call_all_instances_info(node_list,
8629
                                       cluster_info.enabled_hypervisors)
8630
    for nname, nresult in node_data.items():
8631
      # first fill in static (config-based) values
8632
      ninfo = cfg.GetNodeInfo(nname)
8633
      pnr = {
8634
        "tags": list(ninfo.GetTags()),
8635
        "primary_ip": ninfo.primary_ip,
8636
        "secondary_ip": ninfo.secondary_ip,
8637
        "offline": ninfo.offline,
8638
        "drained": ninfo.drained,
8639
        "master_candidate": ninfo.master_candidate,
8640
        }
8641

    
8642
      if not (ninfo.offline or ninfo.drained):
8643
        nresult.Raise("Can't get data for node %s" % nname)
8644
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
8645
                                nname)
8646
        remote_info = nresult.payload
8647

    
8648
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
8649
                     'vg_size', 'vg_free', 'cpu_total']:
8650
          if attr not in remote_info:
8651
            raise errors.OpExecError("Node '%s' didn't return attribute"
8652
                                     " '%s'" % (nname, attr))
8653
          if not isinstance(remote_info[attr], int):
8654
            raise errors.OpExecError("Node '%s' returned invalid value"
8655
                                     " for '%s': %s" %
8656
                                     (nname, attr, remote_info[attr]))
8657
        # compute memory used by primary instances
8658
        i_p_mem = i_p_up_mem = 0
8659
        for iinfo, beinfo in i_list:
8660
          if iinfo.primary_node == nname:
8661
            i_p_mem += beinfo[constants.BE_MEMORY]
8662
            if iinfo.name not in node_iinfo[nname].payload:
8663
              i_used_mem = 0
8664
            else:
8665
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
8666
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
8667
            remote_info['memory_free'] -= max(0, i_mem_diff)
8668

    
8669
            if iinfo.admin_up:
8670
              i_p_up_mem += beinfo[constants.BE_MEMORY]
8671

    
8672
        # compute memory used by instances
8673
        pnr_dyn = {
8674
          "total_memory": remote_info['memory_total'],
8675
          "reserved_memory": remote_info['memory_dom0'],
8676
          "free_memory": remote_info['memory_free'],
8677
          "total_disk": remote_info['vg_size'],
8678
          "free_disk": remote_info['vg_free'],
8679
          "total_cpus": remote_info['cpu_total'],
8680
          "i_pri_memory": i_p_mem,
8681
          "i_pri_up_memory": i_p_up_mem,
8682
          }
8683
        pnr.update(pnr_dyn)
8684

    
8685
      node_results[nname] = pnr
8686
    data["nodes"] = node_results
8687

    
8688
    # instance data
8689
    instance_data = {}
8690
    for iinfo, beinfo in i_list:
8691
      nic_data = []
8692
      for nic in iinfo.nics:
8693
        filled_params = objects.FillDict(
8694
            cluster_info.nicparams[constants.PP_DEFAULT],
8695
            nic.nicparams)
8696
        nic_dict = {"mac": nic.mac,
8697
                    "ip": nic.ip,
8698
                    "mode": filled_params[constants.NIC_MODE],
8699
                    "link": filled_params[constants.NIC_LINK],
8700
                   }
8701
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
8702
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
8703
        nic_data.append(nic_dict)
8704
      pir = {
8705
        "tags": list(iinfo.GetTags()),
8706
        "admin_up": iinfo.admin_up,
8707
        "vcpus": beinfo[constants.BE_VCPUS],
8708
        "memory": beinfo[constants.BE_MEMORY],
8709
        "os": iinfo.os,
8710
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
8711
        "nics": nic_data,
8712
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
8713
        "disk_template": iinfo.disk_template,
8714
        "hypervisor": iinfo.hypervisor,
8715
        }
8716
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
8717
                                                 pir["disks"])
8718
      instance_data[iinfo.name] = pir
8719

    
8720
    data["instances"] = instance_data
8721

    
8722
    self.in_data = data
8723

    
8724
  def _AddNewInstance(self):
8725
    """Add new instance data to allocator structure.
8726

8727
    This in combination with _AllocatorGetClusterData will create the
8728
    correct structure needed as input for the allocator.
8729

8730
    The checks for the completeness of the opcode must have already been
8731
    done.
8732

8733
    """
8734
    data = self.in_data
8735

    
8736
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
8737

    
8738
    if self.disk_template in constants.DTS_NET_MIRROR:
8739
      self.required_nodes = 2
8740
    else:
8741
      self.required_nodes = 1
8742
    request = {
8743
      "type": "allocate",
8744
      "name": self.name,
8745
      "disk_template": self.disk_template,
8746
      "tags": self.tags,
8747
      "os": self.os,
8748
      "vcpus": self.vcpus,
8749
      "memory": self.mem_size,
8750
      "disks": self.disks,
8751
      "disk_space_total": disk_space,
8752
      "nics": self.nics,
8753
      "required_nodes": self.required_nodes,
8754
      }
8755
    data["request"] = request
8756

    
8757
  def _AddRelocateInstance(self):
8758
    """Add relocate instance data to allocator structure.
8759

8760
    This in combination with _IAllocatorGetClusterData will create the
8761
    correct structure needed as input for the allocator.
8762

8763
    The checks for the completeness of the opcode must have already been
8764
    done.
8765

8766
    """
8767
    instance = self.cfg.GetInstanceInfo(self.name)
8768
    if instance is None:
8769
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
8770
                                   " IAllocator" % self.name)
8771

    
8772
    if instance.disk_template not in constants.DTS_NET_MIRROR:
8773
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
8774
                                 errors.ECODE_INVAL)
8775

    
8776
    if len(instance.secondary_nodes) != 1:
8777
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
8778
                                 errors.ECODE_STATE)
8779

    
8780
    self.required_nodes = 1
8781
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
8782
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
8783

    
8784
    request = {
8785
      "type": "relocate",
8786
      "name": self.name,
8787
      "disk_space_total": disk_space,
8788
      "required_nodes": self.required_nodes,
8789
      "relocate_from": self.relocate_from,
8790
      }
8791
    self.in_data["request"] = request
8792

    
8793
  def _BuildInputData(self):
8794
    """Build input data structures.
8795

8796
    """
8797
    self._ComputeClusterData()
8798

    
8799
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
8800
      self._AddNewInstance()
8801
    else:
8802
      self._AddRelocateInstance()
8803

    
8804
    self.in_text = serializer.Dump(self.in_data)
8805

    
8806
  def Run(self, name, validate=True, call_fn=None):
8807
    """Run an instance allocator and return the results.
8808

8809
    """
8810
    if call_fn is None:
8811
      call_fn = self.rpc.call_iallocator_runner
8812

    
8813
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
8814
    result.Raise("Failure while running the iallocator script")
8815

    
8816
    self.out_text = result.payload
8817
    if validate:
8818
      self._ValidateResult()
8819

    
8820
  def _ValidateResult(self):
8821
    """Process the allocator results.
8822

8823
    This will process and if successful save the result in
8824
    self.out_data and the other parameters.
8825

8826
    """
8827
    try:
8828
      rdict = serializer.Load(self.out_text)
8829
    except Exception, err:
8830
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
8831

    
8832
    if not isinstance(rdict, dict):
8833
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
8834

    
8835
    for key in "success", "info", "nodes":
8836
      if key not in rdict:
8837
        raise errors.OpExecError("Can't parse iallocator results:"
8838
                                 " missing key '%s'" % key)
8839
      setattr(self, key, rdict[key])
8840

    
8841
    if not isinstance(rdict["nodes"], list):
8842
      raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
8843
                               " is not a list")
8844
    self.out_data = rdict
8845

    
8846

    
8847
class LUTestAllocator(NoHooksLU):
8848
  """Run allocator tests.
8849

8850
  This LU runs the allocator tests
8851

8852
  """
8853
  _OP_REQP = ["direction", "mode", "name"]
8854

    
8855
  def CheckPrereq(self):
8856
    """Check prerequisites.
8857

8858
    This checks the opcode parameters depending on the director and mode test.
8859

8860
    """
8861
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
8862
      for attr in ["name", "mem_size", "disks", "disk_template",
8863
                   "os", "tags", "nics", "vcpus"]:
8864
        if not hasattr(self.op, attr):
8865
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
8866
                                     attr, errors.ECODE_INVAL)
8867
      iname = self.cfg.ExpandInstanceName(self.op.name)
8868
      if iname is not None:
8869
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
8870
                                   iname, errors.ECODE_EXISTS)
8871
      if not isinstance(self.op.nics, list):
8872
        raise errors.OpPrereqError("Invalid parameter 'nics'",
8873
                                   errors.ECODE_INVAL)
8874
      for row in self.op.nics:
8875
        if (not isinstance(row, dict) or
8876
            "mac" not in row or
8877
            "ip" not in row or
8878
            "bridge" not in row):
8879
          raise errors.OpPrereqError("Invalid contents of the 'nics'"
8880
                                     " parameter", errors.ECODE_INVAL)
8881
      if not isinstance(self.op.disks, list):
8882
        raise errors.OpPrereqError("Invalid parameter 'disks'",
8883
                                   errors.ECODE_INVAL)
8884
      for row in self.op.disks:
8885
        if (not isinstance(row, dict) or
8886
            "size" not in row or
8887
            not isinstance(row["size"], int) or
8888
            "mode" not in row or
8889
            row["mode"] not in ['r', 'w']):
8890
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
8891
                                     " parameter", errors.ECODE_INVAL)
8892
      if not hasattr(self.op, "hypervisor") or self.op.hypervisor is None:
8893
        self.op.hypervisor = self.cfg.GetHypervisorType()
8894
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
8895
      if not hasattr(self.op, "name"):
8896
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input",
8897
                                   errors.ECODE_INVAL)
8898
      fname = self.cfg.ExpandInstanceName(self.op.name)
8899
      if fname is None:
8900
        raise errors.OpPrereqError("Instance '%s' not found for relocation" %
8901
                                   self.op.name, errors.ECODE_NOENT)
8902
      self.op.name = fname
8903
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
8904
    else:
8905
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
8906
                                 self.op.mode, errors.ECODE_INVAL)
8907

    
8908
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
8909
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
8910
        raise errors.OpPrereqError("Missing allocator name",
8911
                                   errors.ECODE_INVAL)
8912
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
8913
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
8914
                                 self.op.direction, errors.ECODE_INVAL)
8915

    
8916
  def Exec(self, feedback_fn):
8917
    """Run the allocator test.
8918

8919
    """
8920
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
8921
      ial = IAllocator(self.cfg, self.rpc,
8922
                       mode=self.op.mode,
8923
                       name=self.op.name,
8924
                       mem_size=self.op.mem_size,
8925
                       disks=self.op.disks,
8926
                       disk_template=self.op.disk_template,
8927
                       os=self.op.os,
8928
                       tags=self.op.tags,
8929
                       nics=self.op.nics,
8930
                       vcpus=self.op.vcpus,
8931
                       hypervisor=self.op.hypervisor,
8932
                       )
8933
    else:
8934
      ial = IAllocator(self.cfg, self.rpc,
8935
                       mode=self.op.mode,
8936
                       name=self.op.name,
8937
                       relocate_from=list(self.relocate_from),
8938
                       )
8939

    
8940
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
8941
      result = ial.in_text
8942
    else:
8943
      ial.Run(self.op.allocator, validate=False)
8944
      result = ial.out_text
8945
    return result