Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 2abc8f57

History | View | Annotate | Download (422.3 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 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,C0302
25

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

    
29
# C0302: since we have waaaay to many lines in this module
30

    
31
import os
32
import os.path
33
import time
34
import re
35
import platform
36
import logging
37
import copy
38
import OpenSSL
39
import socket
40
import tempfile
41
import shutil
42
import itertools
43

    
44
from ganeti import ssh
45
from ganeti import utils
46
from ganeti import errors
47
from ganeti import hypervisor
48
from ganeti import locking
49
from ganeti import constants
50
from ganeti import objects
51
from ganeti import serializer
52
from ganeti import ssconf
53
from ganeti import uidpool
54
from ganeti import compat
55
from ganeti import masterd
56
from ganeti import netutils
57
from ganeti import query
58
from ganeti import qlang
59
from ganeti import opcodes
60

    
61
import ganeti.masterd.instance # pylint: disable-msg=W0611
62

    
63

    
64
def _SupportsOob(cfg, node):
65
  """Tells if node supports OOB.
66

67
  @type cfg: L{config.ConfigWriter}
68
  @param cfg: The cluster configuration
69
  @type node: L{objects.Node}
70
  @param node: The node
71
  @return: The OOB script if supported or an empty string otherwise
72

73
  """
74
  return cfg.GetNdParams(node)[constants.ND_OOB_PROGRAM]
75

    
76

    
77
# End types
78
class LogicalUnit(object):
79
  """Logical Unit base class.
80

81
  Subclasses must follow these rules:
82
    - implement ExpandNames
83
    - implement CheckPrereq (except when tasklets are used)
84
    - implement Exec (except when tasklets are used)
85
    - implement BuildHooksEnv
86
    - redefine HPATH and HTYPE
87
    - optionally redefine their run requirements:
88
        REQ_BGL: the LU needs to hold the Big Ganeti Lock exclusively
89

90
  Note that all commands require root permissions.
91

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

95
  """
96
  HPATH = None
97
  HTYPE = None
98
  REQ_BGL = True
99

    
100
  def __init__(self, processor, op, context, rpc):
101
    """Constructor for LogicalUnit.
102

103
    This needs to be overridden in derived classes in order to check op
104
    validity.
105

106
    """
107
    self.proc = processor
108
    self.op = op
109
    self.cfg = context.cfg
110
    self.context = context
111
    self.rpc = rpc
112
    # Dicts used to declare locking needs to mcpu
113
    self.needed_locks = None
114
    self.acquired_locks = {}
115
    self.share_locks = dict.fromkeys(locking.LEVELS, 0)
116
    self.add_locks = {}
117
    self.remove_locks = {}
118
    # Used to force good behavior when calling helper functions
119
    self.recalculate_locks = {}
120
    self.__ssh = None
121
    # logging
122
    self.Log = processor.Log # pylint: disable-msg=C0103
123
    self.LogWarning = processor.LogWarning # pylint: disable-msg=C0103
124
    self.LogInfo = processor.LogInfo # pylint: disable-msg=C0103
125
    self.LogStep = processor.LogStep # pylint: disable-msg=C0103
126
    # support for dry-run
127
    self.dry_run_result = None
128
    # support for generic debug attribute
129
    if (not hasattr(self.op, "debug_level") or
130
        not isinstance(self.op.debug_level, int)):
131
      self.op.debug_level = 0
132

    
133
    # Tasklets
134
    self.tasklets = None
135

    
136
    # Validate opcode parameters and set defaults
137
    self.op.Validate(True)
138

    
139
    self.CheckArguments()
140

    
141
  def __GetSSH(self):
142
    """Returns the SshRunner object
143

144
    """
145
    if not self.__ssh:
146
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
147
    return self.__ssh
148

    
149
  ssh = property(fget=__GetSSH)
150

    
151
  def CheckArguments(self):
152
    """Check syntactic validity for the opcode arguments.
153

154
    This method is for doing a simple syntactic check and ensure
155
    validity of opcode parameters, without any cluster-related
156
    checks. While the same can be accomplished in ExpandNames and/or
157
    CheckPrereq, doing these separate is better because:
158

159
      - ExpandNames is left as as purely a lock-related function
160
      - CheckPrereq is run after we have acquired locks (and possible
161
        waited for them)
162

163
    The function is allowed to change the self.op attribute so that
164
    later methods can no longer worry about missing parameters.
165

166
    """
167
    pass
168

    
169
  def ExpandNames(self):
170
    """Expand names for this LU.
171

172
    This method is called before starting to execute the opcode, and it should
173
    update all the parameters of the opcode to their canonical form (e.g. a
174
    short node name must be fully expanded after this method has successfully
175
    completed). This way locking, hooks, logging, etc. can work correctly.
176

177
    LUs which implement this method must also populate the self.needed_locks
178
    member, as a dict with lock levels as keys, and a list of needed lock names
179
    as values. Rules:
180

181
      - use an empty dict if you don't need any lock
182
      - if you don't need any lock at a particular level omit that level
183
      - don't put anything for the BGL level
184
      - if you want all locks at a level use locking.ALL_SET as a value
185

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

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

194
    Examples::
195

196
      # Acquire all nodes and one instance
197
      self.needed_locks = {
198
        locking.LEVEL_NODE: locking.ALL_SET,
199
        locking.LEVEL_INSTANCE: ['instance1.example.com'],
200
      }
201
      # Acquire just two nodes
202
      self.needed_locks = {
203
        locking.LEVEL_NODE: ['node1.example.com', 'node2.example.com'],
204
      }
205
      # Acquire no locks
206
      self.needed_locks = {} # No, you can't leave it to the default value None
207

208
    """
209
    # The implementation of this method is mandatory only if the new LU is
210
    # concurrent, so that old LUs don't need to be changed all at the same
211
    # time.
212
    if self.REQ_BGL:
213
      self.needed_locks = {} # Exclusive LUs don't need locks.
214
    else:
215
      raise NotImplementedError
216

    
217
  def DeclareLocks(self, level):
218
    """Declare LU locking needs for a level
219

220
    While most LUs can just declare their locking needs at ExpandNames time,
221
    sometimes there's the need to calculate some locks after having acquired
222
    the ones before. This function is called just before acquiring locks at a
223
    particular level, but after acquiring the ones at lower levels, and permits
224
    such calculations. It can be used to modify self.needed_locks, and by
225
    default it does nothing.
226

227
    This function is only called if you have something already set in
228
    self.needed_locks for the level.
229

230
    @param level: Locking level which is going to be locked
231
    @type level: member of ganeti.locking.LEVELS
232

233
    """
234

    
235
  def CheckPrereq(self):
236
    """Check prerequisites for this LU.
237

238
    This method should check that the prerequisites for the execution
239
    of this LU are fulfilled. It can do internode communication, but
240
    it should be idempotent - no cluster or system changes are
241
    allowed.
242

243
    The method should raise errors.OpPrereqError in case something is
244
    not fulfilled. Its return value is ignored.
245

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

249
    """
250
    if self.tasklets is not None:
251
      for (idx, tl) in enumerate(self.tasklets):
252
        logging.debug("Checking prerequisites for tasklet %s/%s",
253
                      idx + 1, len(self.tasklets))
254
        tl.CheckPrereq()
255
    else:
256
      pass
257

    
258
  def Exec(self, feedback_fn):
259
    """Execute the LU.
260

261
    This method should implement the actual work. It should raise
262
    errors.OpExecError for failures that are somewhat dealt with in
263
    code, or expected.
264

265
    """
266
    if self.tasklets is not None:
267
      for (idx, tl) in enumerate(self.tasklets):
268
        logging.debug("Executing tasklet %s/%s", idx + 1, len(self.tasklets))
269
        tl.Exec(feedback_fn)
270
    else:
271
      raise NotImplementedError
272

    
273
  def BuildHooksEnv(self):
274
    """Build hooks environment for this LU.
275

276
    This method should return a three-node tuple consisting of: a dict
277
    containing the environment that will be used for running the
278
    specific hook for this LU, a list of node names on which the hook
279
    should run before the execution, and a list of node names on which
280
    the hook should run after the execution.
281

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

287
    No nodes should be returned as an empty list (and not None).
288

289
    Note that if the HPATH for a LU class is None, this function will
290
    not be called.
291

292
    """
293
    raise NotImplementedError
294

    
295
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
296
    """Notify the LU about the results of its hooks.
297

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

304
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
305
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
306
    @param hook_results: the results of the multi-node hooks rpc call
307
    @param feedback_fn: function used send feedback back to the caller
308
    @param lu_result: the previous Exec result this LU had, or None
309
        in the PRE phase
310
    @return: the new Exec result, based on the previous result
311
        and hook results
312

313
    """
314
    # API must be kept, thus we ignore the unused argument and could
315
    # be a function warnings
316
    # pylint: disable-msg=W0613,R0201
317
    return lu_result
318

    
319
  def _ExpandAndLockInstance(self):
320
    """Helper function to expand and lock an instance.
321

322
    Many LUs that work on an instance take its name in self.op.instance_name
323
    and need to expand it and then declare the expanded name for locking. This
324
    function does it, and then updates self.op.instance_name to the expanded
325
    name. It also initializes needed_locks as a dict, if this hasn't been done
326
    before.
327

328
    """
329
    if self.needed_locks is None:
330
      self.needed_locks = {}
331
    else:
332
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
333
        "_ExpandAndLockInstance called with instance-level locks set"
334
    self.op.instance_name = _ExpandInstanceName(self.cfg,
335
                                                self.op.instance_name)
336
    self.needed_locks[locking.LEVEL_INSTANCE] = self.op.instance_name
337

    
338
  def _LockInstancesNodes(self, primary_only=False):
339
    """Helper function to declare instances' nodes for locking.
340

341
    This function should be called after locking one or more instances to lock
342
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
343
    with all primary or secondary nodes for instances already locked and
344
    present in self.needed_locks[locking.LEVEL_INSTANCE].
345

346
    It should be called from DeclareLocks, and for safety only works if
347
    self.recalculate_locks[locking.LEVEL_NODE] is set.
348

349
    In the future it may grow parameters to just lock some instance's nodes, or
350
    to just lock primaries or secondary nodes, if needed.
351

352
    If should be called in DeclareLocks in a way similar to::
353

354
      if level == locking.LEVEL_NODE:
355
        self._LockInstancesNodes()
356

357
    @type primary_only: boolean
358
    @param primary_only: only lock primary nodes of locked instances
359

360
    """
361
    assert locking.LEVEL_NODE in self.recalculate_locks, \
362
      "_LockInstancesNodes helper function called with no nodes to recalculate"
363

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

    
366
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
367
    # future we might want to have different behaviors depending on the value
368
    # of self.recalculate_locks[locking.LEVEL_NODE]
369
    wanted_nodes = []
370
    for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
371
      instance = self.context.cfg.GetInstanceInfo(instance_name)
372
      wanted_nodes.append(instance.primary_node)
373
      if not primary_only:
374
        wanted_nodes.extend(instance.secondary_nodes)
375

    
376
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
377
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
378
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
379
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
380

    
381
    del self.recalculate_locks[locking.LEVEL_NODE]
382

    
383

    
384
class NoHooksLU(LogicalUnit): # pylint: disable-msg=W0223
385
  """Simple LU which runs no hooks.
386

387
  This LU is intended as a parent for other LogicalUnits which will
388
  run no hooks, in order to reduce duplicate code.
389

390
  """
391
  HPATH = None
392
  HTYPE = None
393

    
394
  def BuildHooksEnv(self):
395
    """Empty BuildHooksEnv for NoHooksLu.
396

397
    This just raises an error.
398

399
    """
400
    assert False, "BuildHooksEnv called for NoHooksLUs"
401

    
402

    
403
class Tasklet:
404
  """Tasklet base class.
405

406
  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
407
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
408
  tasklets know nothing about locks.
409

410
  Subclasses must follow these rules:
411
    - Implement CheckPrereq
412
    - Implement Exec
413

414
  """
415
  def __init__(self, lu):
416
    self.lu = lu
417

    
418
    # Shortcuts
419
    self.cfg = lu.cfg
420
    self.rpc = lu.rpc
421

    
422
  def CheckPrereq(self):
423
    """Check prerequisites for this tasklets.
424

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

429
    The method should raise errors.OpPrereqError in case something is not
430
    fulfilled. Its return value is ignored.
431

432
    This method should also update all parameters to their canonical form if it
433
    hasn't been done before.
434

435
    """
436
    pass
437

    
438
  def Exec(self, feedback_fn):
439
    """Execute the tasklet.
440

441
    This method should implement the actual work. It should raise
442
    errors.OpExecError for failures that are somewhat dealt with in code, or
443
    expected.
444

445
    """
446
    raise NotImplementedError
447

    
448

    
449
class _QueryBase:
450
  """Base for query utility classes.
451

452
  """
453
  #: Attribute holding field definitions
454
  FIELDS = None
455

    
456
  def __init__(self, names, fields, use_locking):
457
    """Initializes this class.
458

459
    """
460
    self.names = names
461
    self.use_locking = use_locking
462

    
463
    self.query = query.Query(self.FIELDS, fields)
464
    self.requested_data = self.query.RequestedData()
465

    
466
    self.do_locking = None
467
    self.wanted = None
468

    
469
  def _GetNames(self, lu, all_names, lock_level):
470
    """Helper function to determine names asked for in the query.
471

472
    """
473
    if self.do_locking:
474
      names = lu.acquired_locks[lock_level]
475
    else:
476
      names = all_names
477

    
478
    if self.wanted == locking.ALL_SET:
479
      assert not self.names
480
      # caller didn't specify names, so ordering is not important
481
      return utils.NiceSort(names)
482

    
483
    # caller specified names and we must keep the same order
484
    assert self.names
485
    assert not self.do_locking or lu.acquired_locks[lock_level]
486

    
487
    missing = set(self.wanted).difference(names)
488
    if missing:
489
      raise errors.OpExecError("Some items were removed before retrieving"
490
                               " their data: %s" % missing)
491

    
492
    # Return expanded names
493
    return self.wanted
494

    
495
  @classmethod
496
  def FieldsQuery(cls, fields):
497
    """Returns list of available fields.
498

499
    @return: List of L{objects.QueryFieldDefinition}
500

501
    """
502
    return query.QueryFields(cls.FIELDS, fields)
503

    
504
  def ExpandNames(self, lu):
505
    """Expand names for this query.
506

507
    See L{LogicalUnit.ExpandNames}.
508

509
    """
510
    raise NotImplementedError()
511

    
512
  def DeclareLocks(self, lu, level):
513
    """Declare locks for this query.
514

515
    See L{LogicalUnit.DeclareLocks}.
516

517
    """
518
    raise NotImplementedError()
519

    
520
  def _GetQueryData(self, lu):
521
    """Collects all data for this query.
522

523
    @return: Query data object
524

525
    """
526
    raise NotImplementedError()
527

    
528
  def NewStyleQuery(self, lu):
529
    """Collect data and execute query.
530

531
    """
532
    return query.GetQueryResponse(self.query, self._GetQueryData(lu))
533

    
534
  def OldStyleQuery(self, lu):
535
    """Collect data and execute query.
536

537
    """
538
    return self.query.OldStyleQuery(self._GetQueryData(lu))
539

    
540

    
541
def _GetWantedNodes(lu, nodes):
542
  """Returns list of checked and expanded node names.
543

544
  @type lu: L{LogicalUnit}
545
  @param lu: the logical unit on whose behalf we execute
546
  @type nodes: list
547
  @param nodes: list of node names or None for all nodes
548
  @rtype: list
549
  @return: the list of nodes, sorted
550
  @raise errors.ProgrammerError: if the nodes parameter is wrong type
551

552
  """
553
  if nodes:
554
    return [_ExpandNodeName(lu.cfg, name) for name in nodes]
555

    
556
  return utils.NiceSort(lu.cfg.GetNodeList())
557

    
558

    
559
def _GetWantedInstances(lu, instances):
560
  """Returns list of checked and expanded instance names.
561

562
  @type lu: L{LogicalUnit}
563
  @param lu: the logical unit on whose behalf we execute
564
  @type instances: list
565
  @param instances: list of instance names or None for all instances
566
  @rtype: list
567
  @return: the list of instances, sorted
568
  @raise errors.OpPrereqError: if the instances parameter is wrong type
569
  @raise errors.OpPrereqError: if any of the passed instances is not found
570

571
  """
572
  if instances:
573
    wanted = [_ExpandInstanceName(lu.cfg, name) for name in instances]
574
  else:
575
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
576
  return wanted
577

    
578

    
579
def _GetUpdatedParams(old_params, update_dict,
580
                      use_default=True, use_none=False):
581
  """Return the new version of a parameter dictionary.
582

583
  @type old_params: dict
584
  @param old_params: old parameters
585
  @type update_dict: dict
586
  @param update_dict: dict containing new parameter values, or
587
      constants.VALUE_DEFAULT to reset the parameter to its default
588
      value
589
  @param use_default: boolean
590
  @type use_default: whether to recognise L{constants.VALUE_DEFAULT}
591
      values as 'to be deleted' values
592
  @param use_none: boolean
593
  @type use_none: whether to recognise C{None} values as 'to be
594
      deleted' values
595
  @rtype: dict
596
  @return: the new parameter dictionary
597

598
  """
599
  params_copy = copy.deepcopy(old_params)
600
  for key, val in update_dict.iteritems():
601
    if ((use_default and val == constants.VALUE_DEFAULT) or
602
        (use_none and val is None)):
603
      try:
604
        del params_copy[key]
605
      except KeyError:
606
        pass
607
    else:
608
      params_copy[key] = val
609
  return params_copy
610

    
611

    
612
def _CheckOutputFields(static, dynamic, selected):
613
  """Checks whether all selected fields are valid.
614

615
  @type static: L{utils.FieldSet}
616
  @param static: static fields set
617
  @type dynamic: L{utils.FieldSet}
618
  @param dynamic: dynamic fields set
619

620
  """
621
  f = utils.FieldSet()
622
  f.Extend(static)
623
  f.Extend(dynamic)
624

    
625
  delta = f.NonMatching(selected)
626
  if delta:
627
    raise errors.OpPrereqError("Unknown output fields selected: %s"
628
                               % ",".join(delta), errors.ECODE_INVAL)
629

    
630

    
631
def _CheckGlobalHvParams(params):
632
  """Validates that given hypervisor params are not global ones.
633

634
  This will ensure that instances don't get customised versions of
635
  global params.
636

637
  """
638
  used_globals = constants.HVC_GLOBALS.intersection(params)
639
  if used_globals:
640
    msg = ("The following hypervisor parameters are global and cannot"
641
           " be customized at instance level, please modify them at"
642
           " cluster level: %s" % utils.CommaJoin(used_globals))
643
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
644

    
645

    
646
def _CheckNodeOnline(lu, node, msg=None):
647
  """Ensure that a given node is online.
648

649
  @param lu: the LU on behalf of which we make the check
650
  @param node: the node to check
651
  @param msg: if passed, should be a message to replace the default one
652
  @raise errors.OpPrereqError: if the node is offline
653

654
  """
655
  if msg is None:
656
    msg = "Can't use offline node"
657
  if lu.cfg.GetNodeInfo(node).offline:
658
    raise errors.OpPrereqError("%s: %s" % (msg, node), errors.ECODE_STATE)
659

    
660

    
661
def _CheckNodeNotDrained(lu, node):
662
  """Ensure that a given node is not drained.
663

664
  @param lu: the LU on behalf of which we make the check
665
  @param node: the node to check
666
  @raise errors.OpPrereqError: if the node is drained
667

668
  """
669
  if lu.cfg.GetNodeInfo(node).drained:
670
    raise errors.OpPrereqError("Can't use drained node %s" % node,
671
                               errors.ECODE_STATE)
672

    
673

    
674
def _CheckNodeVmCapable(lu, node):
675
  """Ensure that a given node is vm capable.
676

677
  @param lu: the LU on behalf of which we make the check
678
  @param node: the node to check
679
  @raise errors.OpPrereqError: if the node is not vm capable
680

681
  """
682
  if not lu.cfg.GetNodeInfo(node).vm_capable:
683
    raise errors.OpPrereqError("Can't use non-vm_capable node %s" % node,
684
                               errors.ECODE_STATE)
685

    
686

    
687
def _CheckNodeHasOS(lu, node, os_name, force_variant):
688
  """Ensure that a node supports a given OS.
689

690
  @param lu: the LU on behalf of which we make the check
691
  @param node: the node to check
692
  @param os_name: the OS to query about
693
  @param force_variant: whether to ignore variant errors
694
  @raise errors.OpPrereqError: if the node is not supporting the OS
695

696
  """
697
  result = lu.rpc.call_os_get(node, os_name)
698
  result.Raise("OS '%s' not in supported OS list for node %s" %
699
               (os_name, node),
700
               prereq=True, ecode=errors.ECODE_INVAL)
701
  if not force_variant:
702
    _CheckOSVariant(result.payload, os_name)
703

    
704

    
705
def _CheckNodeHasSecondaryIP(lu, node, secondary_ip, prereq):
706
  """Ensure that a node has the given secondary ip.
707

708
  @type lu: L{LogicalUnit}
709
  @param lu: the LU on behalf of which we make the check
710
  @type node: string
711
  @param node: the node to check
712
  @type secondary_ip: string
713
  @param secondary_ip: the ip to check
714
  @type prereq: boolean
715
  @param prereq: whether to throw a prerequisite or an execute error
716
  @raise errors.OpPrereqError: if the node doesn't have the ip, and prereq=True
717
  @raise errors.OpExecError: if the node doesn't have the ip, and prereq=False
718

719
  """
720
  result = lu.rpc.call_node_has_ip_address(node, secondary_ip)
721
  result.Raise("Failure checking secondary ip on node %s" % node,
722
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
723
  if not result.payload:
724
    msg = ("Node claims it doesn't have the secondary ip you gave (%s),"
725
           " please fix and re-run this command" % secondary_ip)
726
    if prereq:
727
      raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
728
    else:
729
      raise errors.OpExecError(msg)
730

    
731

    
732
def _GetClusterDomainSecret():
733
  """Reads the cluster domain secret.
734

735
  """
736
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
737
                               strict=True)
738

    
739

    
740
def _CheckInstanceDown(lu, instance, reason):
741
  """Ensure that an instance is not running."""
742
  if instance.admin_up:
743
    raise errors.OpPrereqError("Instance %s is marked to be up, %s" %
744
                               (instance.name, reason), errors.ECODE_STATE)
745

    
746
  pnode = instance.primary_node
747
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
748
  ins_l.Raise("Can't contact node %s for instance information" % pnode,
749
              prereq=True, ecode=errors.ECODE_ENVIRON)
750

    
751
  if instance.name in ins_l.payload:
752
    raise errors.OpPrereqError("Instance %s is running, %s" %
753
                               (instance.name, reason), errors.ECODE_STATE)
754

    
755

    
756
def _ExpandItemName(fn, name, kind):
757
  """Expand an item name.
758

759
  @param fn: the function to use for expansion
760
  @param name: requested item name
761
  @param kind: text description ('Node' or 'Instance')
762
  @return: the resolved (full) name
763
  @raise errors.OpPrereqError: if the item is not found
764

765
  """
766
  full_name = fn(name)
767
  if full_name is None:
768
    raise errors.OpPrereqError("%s '%s' not known" % (kind, name),
769
                               errors.ECODE_NOENT)
770
  return full_name
771

    
772

    
773
def _ExpandNodeName(cfg, name):
774
  """Wrapper over L{_ExpandItemName} for nodes."""
775
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
776

    
777

    
778
def _ExpandInstanceName(cfg, name):
779
  """Wrapper over L{_ExpandItemName} for instance."""
780
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
781

    
782

    
783
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
784
                          memory, vcpus, nics, disk_template, disks,
785
                          bep, hvp, hypervisor_name):
786
  """Builds instance related env variables for hooks
787

788
  This builds the hook environment from individual variables.
789

790
  @type name: string
791
  @param name: the name of the instance
792
  @type primary_node: string
793
  @param primary_node: the name of the instance's primary node
794
  @type secondary_nodes: list
795
  @param secondary_nodes: list of secondary nodes as strings
796
  @type os_type: string
797
  @param os_type: the name of the instance's OS
798
  @type status: boolean
799
  @param status: the should_run status of the instance
800
  @type memory: string
801
  @param memory: the memory size of the instance
802
  @type vcpus: string
803
  @param vcpus: the count of VCPUs the instance has
804
  @type nics: list
805
  @param nics: list of tuples (ip, mac, mode, link) representing
806
      the NICs the instance has
807
  @type disk_template: string
808
  @param disk_template: the disk template of the instance
809
  @type disks: list
810
  @param disks: the list of (size, mode) pairs
811
  @type bep: dict
812
  @param bep: the backend parameters for the instance
813
  @type hvp: dict
814
  @param hvp: the hypervisor parameters for the instance
815
  @type hypervisor_name: string
816
  @param hypervisor_name: the hypervisor for the instance
817
  @rtype: dict
818
  @return: the hook environment for this instance
819

820
  """
821
  if status:
822
    str_status = "up"
823
  else:
824
    str_status = "down"
825
  env = {
826
    "OP_TARGET": name,
827
    "INSTANCE_NAME": name,
828
    "INSTANCE_PRIMARY": primary_node,
829
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
830
    "INSTANCE_OS_TYPE": os_type,
831
    "INSTANCE_STATUS": str_status,
832
    "INSTANCE_MEMORY": memory,
833
    "INSTANCE_VCPUS": vcpus,
834
    "INSTANCE_DISK_TEMPLATE": disk_template,
835
    "INSTANCE_HYPERVISOR": hypervisor_name,
836
  }
837

    
838
  if nics:
839
    nic_count = len(nics)
840
    for idx, (ip, mac, mode, link) in enumerate(nics):
841
      if ip is None:
842
        ip = ""
843
      env["INSTANCE_NIC%d_IP" % idx] = ip
844
      env["INSTANCE_NIC%d_MAC" % idx] = mac
845
      env["INSTANCE_NIC%d_MODE" % idx] = mode
846
      env["INSTANCE_NIC%d_LINK" % idx] = link
847
      if mode == constants.NIC_MODE_BRIDGED:
848
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
849
  else:
850
    nic_count = 0
851

    
852
  env["INSTANCE_NIC_COUNT"] = nic_count
853

    
854
  if disks:
855
    disk_count = len(disks)
856
    for idx, (size, mode) in enumerate(disks):
857
      env["INSTANCE_DISK%d_SIZE" % idx] = size
858
      env["INSTANCE_DISK%d_MODE" % idx] = mode
859
  else:
860
    disk_count = 0
861

    
862
  env["INSTANCE_DISK_COUNT"] = disk_count
863

    
864
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
865
    for key, value in source.items():
866
      env["INSTANCE_%s_%s" % (kind, key)] = value
867

    
868
  return env
869

    
870

    
871
def _NICListToTuple(lu, nics):
872
  """Build a list of nic information tuples.
873

874
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
875
  value in LUInstanceQueryData.
876

877
  @type lu:  L{LogicalUnit}
878
  @param lu: the logical unit on whose behalf we execute
879
  @type nics: list of L{objects.NIC}
880
  @param nics: list of nics to convert to hooks tuples
881

882
  """
883
  hooks_nics = []
884
  cluster = lu.cfg.GetClusterInfo()
885
  for nic in nics:
886
    ip = nic.ip
887
    mac = nic.mac
888
    filled_params = cluster.SimpleFillNIC(nic.nicparams)
889
    mode = filled_params[constants.NIC_MODE]
890
    link = filled_params[constants.NIC_LINK]
891
    hooks_nics.append((ip, mac, mode, link))
892
  return hooks_nics
893

    
894

    
895
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
896
  """Builds instance related env variables for hooks from an object.
897

898
  @type lu: L{LogicalUnit}
899
  @param lu: the logical unit on whose behalf we execute
900
  @type instance: L{objects.Instance}
901
  @param instance: the instance for which we should build the
902
      environment
903
  @type override: dict
904
  @param override: dictionary with key/values that will override
905
      our values
906
  @rtype: dict
907
  @return: the hook environment dictionary
908

909
  """
910
  cluster = lu.cfg.GetClusterInfo()
911
  bep = cluster.FillBE(instance)
912
  hvp = cluster.FillHV(instance)
913
  args = {
914
    'name': instance.name,
915
    'primary_node': instance.primary_node,
916
    'secondary_nodes': instance.secondary_nodes,
917
    'os_type': instance.os,
918
    'status': instance.admin_up,
919
    'memory': bep[constants.BE_MEMORY],
920
    'vcpus': bep[constants.BE_VCPUS],
921
    'nics': _NICListToTuple(lu, instance.nics),
922
    'disk_template': instance.disk_template,
923
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
924
    'bep': bep,
925
    'hvp': hvp,
926
    'hypervisor_name': instance.hypervisor,
927
  }
928
  if override:
929
    args.update(override)
930
  return _BuildInstanceHookEnv(**args) # pylint: disable-msg=W0142
931

    
932

    
933
def _AdjustCandidatePool(lu, exceptions):
934
  """Adjust the candidate pool after node operations.
935

936
  """
937
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
938
  if mod_list:
939
    lu.LogInfo("Promoted nodes to master candidate role: %s",
940
               utils.CommaJoin(node.name for node in mod_list))
941
    for name in mod_list:
942
      lu.context.ReaddNode(name)
943
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
944
  if mc_now > mc_max:
945
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
946
               (mc_now, mc_max))
947

    
948

    
949
def _DecideSelfPromotion(lu, exceptions=None):
950
  """Decide whether I should promote myself as a master candidate.
951

952
  """
953
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
954
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
955
  # the new node will increase mc_max with one, so:
956
  mc_should = min(mc_should + 1, cp_size)
957
  return mc_now < mc_should
958

    
959

    
960
def _CheckNicsBridgesExist(lu, target_nics, target_node):
961
  """Check that the brigdes needed by a list of nics exist.
962

963
  """
964
  cluster = lu.cfg.GetClusterInfo()
965
  paramslist = [cluster.SimpleFillNIC(nic.nicparams) for nic in target_nics]
966
  brlist = [params[constants.NIC_LINK] for params in paramslist
967
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
968
  if brlist:
969
    result = lu.rpc.call_bridges_exist(target_node, brlist)
970
    result.Raise("Error checking bridges on destination node '%s'" %
971
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
972

    
973

    
974
def _CheckInstanceBridgesExist(lu, instance, node=None):
975
  """Check that the brigdes needed by an instance exist.
976

977
  """
978
  if node is None:
979
    node = instance.primary_node
980
  _CheckNicsBridgesExist(lu, instance.nics, node)
981

    
982

    
983
def _CheckOSVariant(os_obj, name):
984
  """Check whether an OS name conforms to the os variants specification.
985

986
  @type os_obj: L{objects.OS}
987
  @param os_obj: OS object to check
988
  @type name: string
989
  @param name: OS name passed by the user, to check for validity
990

991
  """
992
  if not os_obj.supported_variants:
993
    return
994
  variant = objects.OS.GetVariant(name)
995
  if not variant:
996
    raise errors.OpPrereqError("OS name must include a variant",
997
                               errors.ECODE_INVAL)
998

    
999
  if variant not in os_obj.supported_variants:
1000
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
1001

    
1002

    
1003
def _GetNodeInstancesInner(cfg, fn):
1004
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
1005

    
1006

    
1007
def _GetNodeInstances(cfg, node_name):
1008
  """Returns a list of all primary and secondary instances on a node.
1009

1010
  """
1011

    
1012
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
1013

    
1014

    
1015
def _GetNodePrimaryInstances(cfg, node_name):
1016
  """Returns primary instances on a node.
1017

1018
  """
1019
  return _GetNodeInstancesInner(cfg,
1020
                                lambda inst: node_name == inst.primary_node)
1021

    
1022

    
1023
def _GetNodeSecondaryInstances(cfg, node_name):
1024
  """Returns secondary instances on a node.
1025

1026
  """
1027
  return _GetNodeInstancesInner(cfg,
1028
                                lambda inst: node_name in inst.secondary_nodes)
1029

    
1030

    
1031
def _GetStorageTypeArgs(cfg, storage_type):
1032
  """Returns the arguments for a storage type.
1033

1034
  """
1035
  # Special case for file storage
1036
  if storage_type == constants.ST_FILE:
1037
    # storage.FileStorage wants a list of storage directories
1038
    return [[cfg.GetFileStorageDir(), cfg.GetSharedFileStorageDir()]]
1039

    
1040
  return []
1041

    
1042

    
1043
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
1044
  faulty = []
1045

    
1046
  for dev in instance.disks:
1047
    cfg.SetDiskID(dev, node_name)
1048

    
1049
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
1050
  result.Raise("Failed to get disk status from node %s" % node_name,
1051
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
1052

    
1053
  for idx, bdev_status in enumerate(result.payload):
1054
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
1055
      faulty.append(idx)
1056

    
1057
  return faulty
1058

    
1059

    
1060
def _CheckIAllocatorOrNode(lu, iallocator_slot, node_slot):
1061
  """Check the sanity of iallocator and node arguments and use the
1062
  cluster-wide iallocator if appropriate.
1063

1064
  Check that at most one of (iallocator, node) is specified. If none is
1065
  specified, then the LU's opcode's iallocator slot is filled with the
1066
  cluster-wide default iallocator.
1067

1068
  @type iallocator_slot: string
1069
  @param iallocator_slot: the name of the opcode iallocator slot
1070
  @type node_slot: string
1071
  @param node_slot: the name of the opcode target node slot
1072

1073
  """
1074
  node = getattr(lu.op, node_slot, None)
1075
  iallocator = getattr(lu.op, iallocator_slot, None)
1076

    
1077
  if node is not None and iallocator is not None:
1078
    raise errors.OpPrereqError("Do not specify both, iallocator and node.",
1079
                               errors.ECODE_INVAL)
1080
  elif node is None and iallocator is None:
1081
    default_iallocator = lu.cfg.GetDefaultIAllocator()
1082
    if default_iallocator:
1083
      setattr(lu.op, iallocator_slot, default_iallocator)
1084
    else:
1085
      raise errors.OpPrereqError("No iallocator or node given and no"
1086
                                 " cluster-wide default iallocator found."
1087
                                 " Please specify either an iallocator or a"
1088
                                 " node, or set a cluster-wide default"
1089
                                 " iallocator.")
1090

    
1091

    
1092
class LUClusterPostInit(LogicalUnit):
1093
  """Logical unit for running hooks after cluster initialization.
1094

1095
  """
1096
  HPATH = "cluster-init"
1097
  HTYPE = constants.HTYPE_CLUSTER
1098

    
1099
  def BuildHooksEnv(self):
1100
    """Build hooks env.
1101

1102
    """
1103
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1104
    mn = self.cfg.GetMasterNode()
1105
    return env, [], [mn]
1106

    
1107
  def Exec(self, feedback_fn):
1108
    """Nothing to do.
1109

1110
    """
1111
    return True
1112

    
1113

    
1114
class LUClusterDestroy(LogicalUnit):
1115
  """Logical unit for destroying the cluster.
1116

1117
  """
1118
  HPATH = "cluster-destroy"
1119
  HTYPE = constants.HTYPE_CLUSTER
1120

    
1121
  def BuildHooksEnv(self):
1122
    """Build hooks env.
1123

1124
    """
1125
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1126
    return env, [], []
1127

    
1128
  def CheckPrereq(self):
1129
    """Check prerequisites.
1130

1131
    This checks whether the cluster is empty.
1132

1133
    Any errors are signaled by raising errors.OpPrereqError.
1134

1135
    """
1136
    master = self.cfg.GetMasterNode()
1137

    
1138
    nodelist = self.cfg.GetNodeList()
1139
    if len(nodelist) != 1 or nodelist[0] != master:
1140
      raise errors.OpPrereqError("There are still %d node(s) in"
1141
                                 " this cluster." % (len(nodelist) - 1),
1142
                                 errors.ECODE_INVAL)
1143
    instancelist = self.cfg.GetInstanceList()
1144
    if instancelist:
1145
      raise errors.OpPrereqError("There are still %d instance(s) in"
1146
                                 " this cluster." % len(instancelist),
1147
                                 errors.ECODE_INVAL)
1148

    
1149
  def Exec(self, feedback_fn):
1150
    """Destroys the cluster.
1151

1152
    """
1153
    master = self.cfg.GetMasterNode()
1154

    
1155
    # Run post hooks on master node before it's removed
1156
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
1157
    try:
1158
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
1159
    except:
1160
      # pylint: disable-msg=W0702
1161
      self.LogWarning("Errors occurred running hooks on %s" % master)
1162

    
1163
    result = self.rpc.call_node_stop_master(master, False)
1164
    result.Raise("Could not disable the master role")
1165

    
1166
    return master
1167

    
1168

    
1169
def _VerifyCertificate(filename):
1170
  """Verifies a certificate for LUClusterVerify.
1171

1172
  @type filename: string
1173
  @param filename: Path to PEM file
1174

1175
  """
1176
  try:
1177
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1178
                                           utils.ReadFile(filename))
1179
  except Exception, err: # pylint: disable-msg=W0703
1180
    return (LUClusterVerify.ETYPE_ERROR,
1181
            "Failed to load X509 certificate %s: %s" % (filename, err))
1182

    
1183
  (errcode, msg) = \
1184
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1185
                                constants.SSL_CERT_EXPIRATION_ERROR)
1186

    
1187
  if msg:
1188
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1189
  else:
1190
    fnamemsg = None
1191

    
1192
  if errcode is None:
1193
    return (None, fnamemsg)
1194
  elif errcode == utils.CERT_WARNING:
1195
    return (LUClusterVerify.ETYPE_WARNING, fnamemsg)
1196
  elif errcode == utils.CERT_ERROR:
1197
    return (LUClusterVerify.ETYPE_ERROR, fnamemsg)
1198

    
1199
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1200

    
1201

    
1202
class LUClusterVerify(LogicalUnit):
1203
  """Verifies the cluster status.
1204

1205
  """
1206
  HPATH = "cluster-verify"
1207
  HTYPE = constants.HTYPE_CLUSTER
1208
  REQ_BGL = False
1209

    
1210
  TCLUSTER = "cluster"
1211
  TNODE = "node"
1212
  TINSTANCE = "instance"
1213

    
1214
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1215
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1216
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1217
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1218
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1219
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1220
  EINSTANCEFAULTYDISK = (TINSTANCE, "EINSTANCEFAULTYDISK")
1221
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1222
  EINSTANCESPLITGROUPS = (TINSTANCE, "EINSTANCESPLITGROUPS")
1223
  ENODEDRBD = (TNODE, "ENODEDRBD")
1224
  ENODEDRBDHELPER = (TNODE, "ENODEDRBDHELPER")
1225
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1226
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1227
  ENODEHV = (TNODE, "ENODEHV")
1228
  ENODELVM = (TNODE, "ENODELVM")
1229
  ENODEN1 = (TNODE, "ENODEN1")
1230
  ENODENET = (TNODE, "ENODENET")
1231
  ENODEOS = (TNODE, "ENODEOS")
1232
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1233
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1234
  ENODERPC = (TNODE, "ENODERPC")
1235
  ENODESSH = (TNODE, "ENODESSH")
1236
  ENODEVERSION = (TNODE, "ENODEVERSION")
1237
  ENODESETUP = (TNODE, "ENODESETUP")
1238
  ENODETIME = (TNODE, "ENODETIME")
1239
  ENODEOOBPATH = (TNODE, "ENODEOOBPATH")
1240

    
1241
  ETYPE_FIELD = "code"
1242
  ETYPE_ERROR = "ERROR"
1243
  ETYPE_WARNING = "WARNING"
1244

    
1245
  _HOOKS_INDENT_RE = re.compile("^", re.M)
1246

    
1247
  class NodeImage(object):
1248
    """A class representing the logical and physical status of a node.
1249

1250
    @type name: string
1251
    @ivar name: the node name to which this object refers
1252
    @ivar volumes: a structure as returned from
1253
        L{ganeti.backend.GetVolumeList} (runtime)
1254
    @ivar instances: a list of running instances (runtime)
1255
    @ivar pinst: list of configured primary instances (config)
1256
    @ivar sinst: list of configured secondary instances (config)
1257
    @ivar sbp: diction of {secondary-node: list of instances} of all peers
1258
        of this node (config)
1259
    @ivar mfree: free memory, as reported by hypervisor (runtime)
1260
    @ivar dfree: free disk, as reported by the node (runtime)
1261
    @ivar offline: the offline status (config)
1262
    @type rpc_fail: boolean
1263
    @ivar rpc_fail: whether the RPC verify call was successfull (overall,
1264
        not whether the individual keys were correct) (runtime)
1265
    @type lvm_fail: boolean
1266
    @ivar lvm_fail: whether the RPC call didn't return valid LVM data
1267
    @type hyp_fail: boolean
1268
    @ivar hyp_fail: whether the RPC call didn't return the instance list
1269
    @type ghost: boolean
1270
    @ivar ghost: whether this is a known node or not (config)
1271
    @type os_fail: boolean
1272
    @ivar os_fail: whether the RPC call didn't return valid OS data
1273
    @type oslist: list
1274
    @ivar oslist: list of OSes as diagnosed by DiagnoseOS
1275
    @type vm_capable: boolean
1276
    @ivar vm_capable: whether the node can host instances
1277

1278
    """
1279
    def __init__(self, offline=False, name=None, vm_capable=True):
1280
      self.name = name
1281
      self.volumes = {}
1282
      self.instances = []
1283
      self.pinst = []
1284
      self.sinst = []
1285
      self.sbp = {}
1286
      self.mfree = 0
1287
      self.dfree = 0
1288
      self.offline = offline
1289
      self.vm_capable = vm_capable
1290
      self.rpc_fail = False
1291
      self.lvm_fail = False
1292
      self.hyp_fail = False
1293
      self.ghost = False
1294
      self.os_fail = False
1295
      self.oslist = {}
1296

    
1297
  def ExpandNames(self):
1298
    self.needed_locks = {
1299
      locking.LEVEL_NODE: locking.ALL_SET,
1300
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1301
    }
1302
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1303

    
1304
  def _Error(self, ecode, item, msg, *args, **kwargs):
1305
    """Format an error message.
1306

1307
    Based on the opcode's error_codes parameter, either format a
1308
    parseable error code, or a simpler error string.
1309

1310
    This must be called only from Exec and functions called from Exec.
1311

1312
    """
1313
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1314
    itype, etxt = ecode
1315
    # first complete the msg
1316
    if args:
1317
      msg = msg % args
1318
    # then format the whole message
1319
    if self.op.error_codes:
1320
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1321
    else:
1322
      if item:
1323
        item = " " + item
1324
      else:
1325
        item = ""
1326
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1327
    # and finally report it via the feedback_fn
1328
    self._feedback_fn("  - %s" % msg)
1329

    
1330
  def _ErrorIf(self, cond, *args, **kwargs):
1331
    """Log an error message if the passed condition is True.
1332

1333
    """
1334
    cond = bool(cond) or self.op.debug_simulate_errors
1335
    if cond:
1336
      self._Error(*args, **kwargs)
1337
    # do not mark the operation as failed for WARN cases only
1338
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1339
      self.bad = self.bad or cond
1340

    
1341
  def _VerifyNode(self, ninfo, nresult):
1342
    """Perform some basic validation on data returned from a node.
1343

1344
      - check the result data structure is well formed and has all the
1345
        mandatory fields
1346
      - check ganeti version
1347

1348
    @type ninfo: L{objects.Node}
1349
    @param ninfo: the node to check
1350
    @param nresult: the results from the node
1351
    @rtype: boolean
1352
    @return: whether overall this call was successful (and we can expect
1353
         reasonable values in the respose)
1354

1355
    """
1356
    node = ninfo.name
1357
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1358

    
1359
    # main result, nresult should be a non-empty dict
1360
    test = not nresult or not isinstance(nresult, dict)
1361
    _ErrorIf(test, self.ENODERPC, node,
1362
                  "unable to verify node: no data returned")
1363
    if test:
1364
      return False
1365

    
1366
    # compares ganeti version
1367
    local_version = constants.PROTOCOL_VERSION
1368
    remote_version = nresult.get("version", None)
1369
    test = not (remote_version and
1370
                isinstance(remote_version, (list, tuple)) and
1371
                len(remote_version) == 2)
1372
    _ErrorIf(test, self.ENODERPC, node,
1373
             "connection to node returned invalid data")
1374
    if test:
1375
      return False
1376

    
1377
    test = local_version != remote_version[0]
1378
    _ErrorIf(test, self.ENODEVERSION, node,
1379
             "incompatible protocol versions: master %s,"
1380
             " node %s", local_version, remote_version[0])
1381
    if test:
1382
      return False
1383

    
1384
    # node seems compatible, we can actually try to look into its results
1385

    
1386
    # full package version
1387
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1388
                  self.ENODEVERSION, node,
1389
                  "software version mismatch: master %s, node %s",
1390
                  constants.RELEASE_VERSION, remote_version[1],
1391
                  code=self.ETYPE_WARNING)
1392

    
1393
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1394
    if ninfo.vm_capable and isinstance(hyp_result, dict):
1395
      for hv_name, hv_result in hyp_result.iteritems():
1396
        test = hv_result is not None
1397
        _ErrorIf(test, self.ENODEHV, node,
1398
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1399

    
1400
    hvp_result = nresult.get(constants.NV_HVPARAMS, None)
1401
    if ninfo.vm_capable and isinstance(hvp_result, list):
1402
      for item, hv_name, hv_result in hvp_result:
1403
        _ErrorIf(True, self.ENODEHV, node,
1404
                 "hypervisor %s parameter verify failure (source %s): %s",
1405
                 hv_name, item, hv_result)
1406

    
1407
    test = nresult.get(constants.NV_NODESETUP,
1408
                           ["Missing NODESETUP results"])
1409
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1410
             "; ".join(test))
1411

    
1412
    return True
1413

    
1414
  def _VerifyNodeTime(self, ninfo, nresult,
1415
                      nvinfo_starttime, nvinfo_endtime):
1416
    """Check the node time.
1417

1418
    @type ninfo: L{objects.Node}
1419
    @param ninfo: the node to check
1420
    @param nresult: the remote results for the node
1421
    @param nvinfo_starttime: the start time of the RPC call
1422
    @param nvinfo_endtime: the end time of the RPC call
1423

1424
    """
1425
    node = ninfo.name
1426
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1427

    
1428
    ntime = nresult.get(constants.NV_TIME, None)
1429
    try:
1430
      ntime_merged = utils.MergeTime(ntime)
1431
    except (ValueError, TypeError):
1432
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1433
      return
1434

    
1435
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1436
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1437
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1438
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1439
    else:
1440
      ntime_diff = None
1441

    
1442
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1443
             "Node time diverges by at least %s from master node time",
1444
             ntime_diff)
1445

    
1446
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1447
    """Check the node LVM results.
1448

1449
    @type ninfo: L{objects.Node}
1450
    @param ninfo: the node to check
1451
    @param nresult: the remote results for the node
1452
    @param vg_name: the configured VG name
1453

1454
    """
1455
    if vg_name is None:
1456
      return
1457

    
1458
    node = ninfo.name
1459
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1460

    
1461
    # checks vg existence and size > 20G
1462
    vglist = nresult.get(constants.NV_VGLIST, None)
1463
    test = not vglist
1464
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1465
    if not test:
1466
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1467
                                            constants.MIN_VG_SIZE)
1468
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1469

    
1470
    # check pv names
1471
    pvlist = nresult.get(constants.NV_PVLIST, None)
1472
    test = pvlist is None
1473
    _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1474
    if not test:
1475
      # check that ':' is not present in PV names, since it's a
1476
      # special character for lvcreate (denotes the range of PEs to
1477
      # use on the PV)
1478
      for _, pvname, owner_vg in pvlist:
1479
        test = ":" in pvname
1480
        _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1481
                 " '%s' of VG '%s'", pvname, owner_vg)
1482

    
1483
  def _VerifyNodeBridges(self, ninfo, nresult, bridges):
1484
    """Check the node bridges.
1485

1486
    @type ninfo: L{objects.Node}
1487
    @param ninfo: the node to check
1488
    @param nresult: the remote results for the node
1489
    @param bridges: the expected list of bridges
1490

1491
    """
1492
    if not bridges:
1493
      return
1494

    
1495
    node = ninfo.name
1496
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1497

    
1498
    missing = nresult.get(constants.NV_BRIDGES, None)
1499
    test = not isinstance(missing, list)
1500
    _ErrorIf(test, self.ENODENET, node,
1501
             "did not return valid bridge information")
1502
    if not test:
1503
      _ErrorIf(bool(missing), self.ENODENET, node, "missing bridges: %s" %
1504
               utils.CommaJoin(sorted(missing)))
1505

    
1506
  def _VerifyNodeNetwork(self, ninfo, nresult):
1507
    """Check the node network connectivity results.
1508

1509
    @type ninfo: L{objects.Node}
1510
    @param ninfo: the node to check
1511
    @param nresult: the remote results for the node
1512

1513
    """
1514
    node = ninfo.name
1515
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1516

    
1517
    test = constants.NV_NODELIST not in nresult
1518
    _ErrorIf(test, self.ENODESSH, node,
1519
             "node hasn't returned node ssh connectivity data")
1520
    if not test:
1521
      if nresult[constants.NV_NODELIST]:
1522
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1523
          _ErrorIf(True, self.ENODESSH, node,
1524
                   "ssh communication with node '%s': %s", a_node, a_msg)
1525

    
1526
    test = constants.NV_NODENETTEST not in nresult
1527
    _ErrorIf(test, self.ENODENET, node,
1528
             "node hasn't returned node tcp connectivity data")
1529
    if not test:
1530
      if nresult[constants.NV_NODENETTEST]:
1531
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1532
        for anode in nlist:
1533
          _ErrorIf(True, self.ENODENET, node,
1534
                   "tcp communication with node '%s': %s",
1535
                   anode, nresult[constants.NV_NODENETTEST][anode])
1536

    
1537
    test = constants.NV_MASTERIP not in nresult
1538
    _ErrorIf(test, self.ENODENET, node,
1539
             "node hasn't returned node master IP reachability data")
1540
    if not test:
1541
      if not nresult[constants.NV_MASTERIP]:
1542
        if node == self.master_node:
1543
          msg = "the master node cannot reach the master IP (not configured?)"
1544
        else:
1545
          msg = "cannot reach the master IP"
1546
        _ErrorIf(True, self.ENODENET, node, msg)
1547

    
1548
  def _VerifyInstance(self, instance, instanceconfig, node_image,
1549
                      diskstatus):
1550
    """Verify an instance.
1551

1552
    This function checks to see if the required block devices are
1553
    available on the instance's node.
1554

1555
    """
1556
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1557
    node_current = instanceconfig.primary_node
1558

    
1559
    node_vol_should = {}
1560
    instanceconfig.MapLVsByNode(node_vol_should)
1561

    
1562
    for node in node_vol_should:
1563
      n_img = node_image[node]
1564
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1565
        # ignore missing volumes on offline or broken nodes
1566
        continue
1567
      for volume in node_vol_should[node]:
1568
        test = volume not in n_img.volumes
1569
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1570
                 "volume %s missing on node %s", volume, node)
1571

    
1572
    if instanceconfig.admin_up:
1573
      pri_img = node_image[node_current]
1574
      test = instance not in pri_img.instances and not pri_img.offline
1575
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1576
               "instance not running on its primary node %s",
1577
               node_current)
1578

    
1579
    for node, n_img in node_image.items():
1580
      if node != node_current:
1581
        test = instance in n_img.instances
1582
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1583
                 "instance should not run on node %s", node)
1584

    
1585
    diskdata = [(nname, success, status, idx)
1586
                for (nname, disks) in diskstatus.items()
1587
                for idx, (success, status) in enumerate(disks)]
1588

    
1589
    for nname, success, bdev_status, idx in diskdata:
1590
      # the 'ghost node' construction in Exec() ensures that we have a
1591
      # node here
1592
      snode = node_image[nname]
1593
      bad_snode = snode.ghost or snode.offline
1594
      _ErrorIf(instanceconfig.admin_up and not success and not bad_snode,
1595
               self.EINSTANCEFAULTYDISK, instance,
1596
               "couldn't retrieve status for disk/%s on %s: %s",
1597
               idx, nname, bdev_status)
1598
      _ErrorIf((instanceconfig.admin_up and success and
1599
                bdev_status.ldisk_status == constants.LDS_FAULTY),
1600
               self.EINSTANCEFAULTYDISK, instance,
1601
               "disk/%s on %s is faulty", idx, nname)
1602

    
1603
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1604
    """Verify if there are any unknown volumes in the cluster.
1605

1606
    The .os, .swap and backup volumes are ignored. All other volumes are
1607
    reported as unknown.
1608

1609
    @type reserved: L{ganeti.utils.FieldSet}
1610
    @param reserved: a FieldSet of reserved volume names
1611

1612
    """
1613
    for node, n_img in node_image.items():
1614
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1615
        # skip non-healthy nodes
1616
        continue
1617
      for volume in n_img.volumes:
1618
        test = ((node not in node_vol_should or
1619
                volume not in node_vol_should[node]) and
1620
                not reserved.Matches(volume))
1621
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1622
                      "volume %s is unknown", volume)
1623

    
1624
  def _VerifyOrphanInstances(self, instancelist, node_image):
1625
    """Verify the list of running instances.
1626

1627
    This checks what instances are running but unknown to the cluster.
1628

1629
    """
1630
    for node, n_img in node_image.items():
1631
      for o_inst in n_img.instances:
1632
        test = o_inst not in instancelist
1633
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1634
                      "instance %s on node %s should not exist", o_inst, node)
1635

    
1636
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1637
    """Verify N+1 Memory Resilience.
1638

1639
    Check that if one single node dies we can still start all the
1640
    instances it was primary for.
1641

1642
    """
1643
    for node, n_img in node_image.items():
1644
      # This code checks that every node which is now listed as
1645
      # secondary has enough memory to host all instances it is
1646
      # supposed to should a single other node in the cluster fail.
1647
      # FIXME: not ready for failover to an arbitrary node
1648
      # FIXME: does not support file-backed instances
1649
      # WARNING: we currently take into account down instances as well
1650
      # as up ones, considering that even if they're down someone
1651
      # might want to start them even in the event of a node failure.
1652
      if n_img.offline:
1653
        # we're skipping offline nodes from the N+1 warning, since
1654
        # most likely we don't have good memory infromation from them;
1655
        # we already list instances living on such nodes, and that's
1656
        # enough warning
1657
        continue
1658
      for prinode, instances in n_img.sbp.items():
1659
        needed_mem = 0
1660
        for instance in instances:
1661
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1662
          if bep[constants.BE_AUTO_BALANCE]:
1663
            needed_mem += bep[constants.BE_MEMORY]
1664
        test = n_img.mfree < needed_mem
1665
        self._ErrorIf(test, self.ENODEN1, node,
1666
                      "not enough memory to accomodate instance failovers"
1667
                      " should node %s fail (%dMiB needed, %dMiB available)",
1668
                      prinode, needed_mem, n_img.mfree)
1669

    
1670
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1671
                       master_files):
1672
    """Verifies and computes the node required file checksums.
1673

1674
    @type ninfo: L{objects.Node}
1675
    @param ninfo: the node to check
1676
    @param nresult: the remote results for the node
1677
    @param file_list: required list of files
1678
    @param local_cksum: dictionary of local files and their checksums
1679
    @param master_files: list of files that only masters should have
1680

1681
    """
1682
    node = ninfo.name
1683
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1684

    
1685
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1686
    test = not isinstance(remote_cksum, dict)
1687
    _ErrorIf(test, self.ENODEFILECHECK, node,
1688
             "node hasn't returned file checksum data")
1689
    if test:
1690
      return
1691

    
1692
    for file_name in file_list:
1693
      node_is_mc = ninfo.master_candidate
1694
      must_have = (file_name not in master_files) or node_is_mc
1695
      # missing
1696
      test1 = file_name not in remote_cksum
1697
      # invalid checksum
1698
      test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1699
      # existing and good
1700
      test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1701
      _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1702
               "file '%s' missing", file_name)
1703
      _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1704
               "file '%s' has wrong checksum", file_name)
1705
      # not candidate and this is not a must-have file
1706
      _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1707
               "file '%s' should not exist on non master"
1708
               " candidates (and the file is outdated)", file_name)
1709
      # all good, except non-master/non-must have combination
1710
      _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1711
               "file '%s' should not exist"
1712
               " on non master candidates", file_name)
1713

    
1714
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1715
                      drbd_map):
1716
    """Verifies and the node DRBD status.
1717

1718
    @type ninfo: L{objects.Node}
1719
    @param ninfo: the node to check
1720
    @param nresult: the remote results for the node
1721
    @param instanceinfo: the dict of instances
1722
    @param drbd_helper: the configured DRBD usermode helper
1723
    @param drbd_map: the DRBD map as returned by
1724
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1725

1726
    """
1727
    node = ninfo.name
1728
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1729

    
1730
    if drbd_helper:
1731
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1732
      test = (helper_result == None)
1733
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1734
               "no drbd usermode helper returned")
1735
      if helper_result:
1736
        status, payload = helper_result
1737
        test = not status
1738
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1739
                 "drbd usermode helper check unsuccessful: %s", payload)
1740
        test = status and (payload != drbd_helper)
1741
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1742
                 "wrong drbd usermode helper: %s", payload)
1743

    
1744
    # compute the DRBD minors
1745
    node_drbd = {}
1746
    for minor, instance in drbd_map[node].items():
1747
      test = instance not in instanceinfo
1748
      _ErrorIf(test, self.ECLUSTERCFG, None,
1749
               "ghost instance '%s' in temporary DRBD map", instance)
1750
        # ghost instance should not be running, but otherwise we
1751
        # don't give double warnings (both ghost instance and
1752
        # unallocated minor in use)
1753
      if test:
1754
        node_drbd[minor] = (instance, False)
1755
      else:
1756
        instance = instanceinfo[instance]
1757
        node_drbd[minor] = (instance.name, instance.admin_up)
1758

    
1759
    # and now check them
1760
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1761
    test = not isinstance(used_minors, (tuple, list))
1762
    _ErrorIf(test, self.ENODEDRBD, node,
1763
             "cannot parse drbd status file: %s", str(used_minors))
1764
    if test:
1765
      # we cannot check drbd status
1766
      return
1767

    
1768
    for minor, (iname, must_exist) in node_drbd.items():
1769
      test = minor not in used_minors and must_exist
1770
      _ErrorIf(test, self.ENODEDRBD, node,
1771
               "drbd minor %d of instance %s is not active", minor, iname)
1772
    for minor in used_minors:
1773
      test = minor not in node_drbd
1774
      _ErrorIf(test, self.ENODEDRBD, node,
1775
               "unallocated drbd minor %d is in use", minor)
1776

    
1777
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1778
    """Builds the node OS structures.
1779

1780
    @type ninfo: L{objects.Node}
1781
    @param ninfo: the node to check
1782
    @param nresult: the remote results for the node
1783
    @param nimg: the node image object
1784

1785
    """
1786
    node = ninfo.name
1787
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1788

    
1789
    remote_os = nresult.get(constants.NV_OSLIST, None)
1790
    test = (not isinstance(remote_os, list) or
1791
            not compat.all(isinstance(v, list) and len(v) == 7
1792
                           for v in remote_os))
1793

    
1794
    _ErrorIf(test, self.ENODEOS, node,
1795
             "node hasn't returned valid OS data")
1796

    
1797
    nimg.os_fail = test
1798

    
1799
    if test:
1800
      return
1801

    
1802
    os_dict = {}
1803

    
1804
    for (name, os_path, status, diagnose,
1805
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1806

    
1807
      if name not in os_dict:
1808
        os_dict[name] = []
1809

    
1810
      # parameters is a list of lists instead of list of tuples due to
1811
      # JSON lacking a real tuple type, fix it:
1812
      parameters = [tuple(v) for v in parameters]
1813
      os_dict[name].append((os_path, status, diagnose,
1814
                            set(variants), set(parameters), set(api_ver)))
1815

    
1816
    nimg.oslist = os_dict
1817

    
1818
  def _VerifyNodeOS(self, ninfo, nimg, base):
1819
    """Verifies the node OS list.
1820

1821
    @type ninfo: L{objects.Node}
1822
    @param ninfo: the node to check
1823
    @param nimg: the node image object
1824
    @param base: the 'template' node we match against (e.g. from the master)
1825

1826
    """
1827
    node = ninfo.name
1828
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1829

    
1830
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1831

    
1832
    beautify_params = lambda l: ["%s: %s" % (k, v) for (k, v) in l]
1833
    for os_name, os_data in nimg.oslist.items():
1834
      assert os_data, "Empty OS status for OS %s?!" % os_name
1835
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
1836
      _ErrorIf(not f_status, self.ENODEOS, node,
1837
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
1838
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
1839
               "OS '%s' has multiple entries (first one shadows the rest): %s",
1840
               os_name, utils.CommaJoin([v[0] for v in os_data]))
1841
      # this will catched in backend too
1842
      _ErrorIf(compat.any(v >= constants.OS_API_V15 for v in f_api)
1843
               and not f_var, self.ENODEOS, node,
1844
               "OS %s with API at least %d does not declare any variant",
1845
               os_name, constants.OS_API_V15)
1846
      # comparisons with the 'base' image
1847
      test = os_name not in base.oslist
1848
      _ErrorIf(test, self.ENODEOS, node,
1849
               "Extra OS %s not present on reference node (%s)",
1850
               os_name, base.name)
1851
      if test:
1852
        continue
1853
      assert base.oslist[os_name], "Base node has empty OS status?"
1854
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
1855
      if not b_status:
1856
        # base OS is invalid, skipping
1857
        continue
1858
      for kind, a, b in [("API version", f_api, b_api),
1859
                         ("variants list", f_var, b_var),
1860
                         ("parameters", beautify_params(f_param),
1861
                          beautify_params(b_param))]:
1862
        _ErrorIf(a != b, self.ENODEOS, node,
1863
                 "OS %s for %s differs from reference node %s: [%s] vs. [%s]",
1864
                 kind, os_name, base.name,
1865
                 utils.CommaJoin(sorted(a)), utils.CommaJoin(sorted(b)))
1866

    
1867
    # check any missing OSes
1868
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
1869
    _ErrorIf(missing, self.ENODEOS, node,
1870
             "OSes present on reference node %s but missing on this node: %s",
1871
             base.name, utils.CommaJoin(missing))
1872

    
1873
  def _VerifyOob(self, ninfo, nresult):
1874
    """Verifies out of band functionality of a node.
1875

1876
    @type ninfo: L{objects.Node}
1877
    @param ninfo: the node to check
1878
    @param nresult: the remote results for the node
1879

1880
    """
1881
    node = ninfo.name
1882
    # We just have to verify the paths on master and/or master candidates
1883
    # as the oob helper is invoked on the master
1884
    if ((ninfo.master_candidate or ninfo.master_capable) and
1885
        constants.NV_OOB_PATHS in nresult):
1886
      for path_result in nresult[constants.NV_OOB_PATHS]:
1887
        self._ErrorIf(path_result, self.ENODEOOBPATH, node, path_result)
1888

    
1889
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1890
    """Verifies and updates the node volume data.
1891

1892
    This function will update a L{NodeImage}'s internal structures
1893
    with data from the remote call.
1894

1895
    @type ninfo: L{objects.Node}
1896
    @param ninfo: the node to check
1897
    @param nresult: the remote results for the node
1898
    @param nimg: the node image object
1899
    @param vg_name: the configured VG name
1900

1901
    """
1902
    node = ninfo.name
1903
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1904

    
1905
    nimg.lvm_fail = True
1906
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1907
    if vg_name is None:
1908
      pass
1909
    elif isinstance(lvdata, basestring):
1910
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1911
               utils.SafeEncode(lvdata))
1912
    elif not isinstance(lvdata, dict):
1913
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1914
    else:
1915
      nimg.volumes = lvdata
1916
      nimg.lvm_fail = False
1917

    
1918
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1919
    """Verifies and updates the node instance list.
1920

1921
    If the listing was successful, then updates this node's instance
1922
    list. Otherwise, it marks the RPC call as failed for the instance
1923
    list key.
1924

1925
    @type ninfo: L{objects.Node}
1926
    @param ninfo: the node to check
1927
    @param nresult: the remote results for the node
1928
    @param nimg: the node image object
1929

1930
    """
1931
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1932
    test = not isinstance(idata, list)
1933
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1934
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1935
    if test:
1936
      nimg.hyp_fail = True
1937
    else:
1938
      nimg.instances = idata
1939

    
1940
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1941
    """Verifies and computes a node information map
1942

1943
    @type ninfo: L{objects.Node}
1944
    @param ninfo: the node to check
1945
    @param nresult: the remote results for the node
1946
    @param nimg: the node image object
1947
    @param vg_name: the configured VG name
1948

1949
    """
1950
    node = ninfo.name
1951
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1952

    
1953
    # try to read free memory (from the hypervisor)
1954
    hv_info = nresult.get(constants.NV_HVINFO, None)
1955
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
1956
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1957
    if not test:
1958
      try:
1959
        nimg.mfree = int(hv_info["memory_free"])
1960
      except (ValueError, TypeError):
1961
        _ErrorIf(True, self.ENODERPC, node,
1962
                 "node returned invalid nodeinfo, check hypervisor")
1963

    
1964
    # FIXME: devise a free space model for file based instances as well
1965
    if vg_name is not None:
1966
      test = (constants.NV_VGLIST not in nresult or
1967
              vg_name not in nresult[constants.NV_VGLIST])
1968
      _ErrorIf(test, self.ENODELVM, node,
1969
               "node didn't return data for the volume group '%s'"
1970
               " - it is either missing or broken", vg_name)
1971
      if not test:
1972
        try:
1973
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
1974
        except (ValueError, TypeError):
1975
          _ErrorIf(True, self.ENODERPC, node,
1976
                   "node returned invalid LVM info, check LVM status")
1977

    
1978
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
1979
    """Gets per-disk status information for all instances.
1980

1981
    @type nodelist: list of strings
1982
    @param nodelist: Node names
1983
    @type node_image: dict of (name, L{objects.Node})
1984
    @param node_image: Node objects
1985
    @type instanceinfo: dict of (name, L{objects.Instance})
1986
    @param instanceinfo: Instance objects
1987
    @rtype: {instance: {node: [(succes, payload)]}}
1988
    @return: a dictionary of per-instance dictionaries with nodes as
1989
        keys and disk information as values; the disk information is a
1990
        list of tuples (success, payload)
1991

1992
    """
1993
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1994

    
1995
    node_disks = {}
1996
    node_disks_devonly = {}
1997
    diskless_instances = set()
1998
    diskless = constants.DT_DISKLESS
1999

    
2000
    for nname in nodelist:
2001
      node_instances = list(itertools.chain(node_image[nname].pinst,
2002
                                            node_image[nname].sinst))
2003
      diskless_instances.update(inst for inst in node_instances
2004
                                if instanceinfo[inst].disk_template == diskless)
2005
      disks = [(inst, disk)
2006
               for inst in node_instances
2007
               for disk in instanceinfo[inst].disks]
2008

    
2009
      if not disks:
2010
        # No need to collect data
2011
        continue
2012

    
2013
      node_disks[nname] = disks
2014

    
2015
      # Creating copies as SetDiskID below will modify the objects and that can
2016
      # lead to incorrect data returned from nodes
2017
      devonly = [dev.Copy() for (_, dev) in disks]
2018

    
2019
      for dev in devonly:
2020
        self.cfg.SetDiskID(dev, nname)
2021

    
2022
      node_disks_devonly[nname] = devonly
2023

    
2024
    assert len(node_disks) == len(node_disks_devonly)
2025

    
2026
    # Collect data from all nodes with disks
2027
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
2028
                                                          node_disks_devonly)
2029

    
2030
    assert len(result) == len(node_disks)
2031

    
2032
    instdisk = {}
2033

    
2034
    for (nname, nres) in result.items():
2035
      disks = node_disks[nname]
2036

    
2037
      if nres.offline:
2038
        # No data from this node
2039
        data = len(disks) * [(False, "node offline")]
2040
      else:
2041
        msg = nres.fail_msg
2042
        _ErrorIf(msg, self.ENODERPC, nname,
2043
                 "while getting disk information: %s", msg)
2044
        if msg:
2045
          # No data from this node
2046
          data = len(disks) * [(False, msg)]
2047
        else:
2048
          data = []
2049
          for idx, i in enumerate(nres.payload):
2050
            if isinstance(i, (tuple, list)) and len(i) == 2:
2051
              data.append(i)
2052
            else:
2053
              logging.warning("Invalid result from node %s, entry %d: %s",
2054
                              nname, idx, i)
2055
              data.append((False, "Invalid result from the remote node"))
2056

    
2057
      for ((inst, _), status) in zip(disks, data):
2058
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
2059

    
2060
    # Add empty entries for diskless instances.
2061
    for inst in diskless_instances:
2062
      assert inst not in instdisk
2063
      instdisk[inst] = {}
2064

    
2065
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
2066
                      len(nnames) <= len(instanceinfo[inst].all_nodes) and
2067
                      compat.all(isinstance(s, (tuple, list)) and
2068
                                 len(s) == 2 for s in statuses)
2069
                      for inst, nnames in instdisk.items()
2070
                      for nname, statuses in nnames.items())
2071
    assert set(instdisk) == set(instanceinfo), "instdisk consistency failure"
2072

    
2073
    return instdisk
2074

    
2075
  def _VerifyHVP(self, hvp_data):
2076
    """Verifies locally the syntax of the hypervisor parameters.
2077

2078
    """
2079
    for item, hv_name, hv_params in hvp_data:
2080
      msg = ("hypervisor %s parameters syntax check (source %s): %%s" %
2081
             (item, hv_name))
2082
      try:
2083
        hv_class = hypervisor.GetHypervisor(hv_name)
2084
        utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2085
        hv_class.CheckParameterSyntax(hv_params)
2086
      except errors.GenericError, err:
2087
        self._ErrorIf(True, self.ECLUSTERCFG, None, msg % str(err))
2088

    
2089

    
2090
  def BuildHooksEnv(self):
2091
    """Build hooks env.
2092

2093
    Cluster-Verify hooks just ran in the post phase and their failure makes
2094
    the output be logged in the verify output and the verification to fail.
2095

2096
    """
2097
    all_nodes = self.cfg.GetNodeList()
2098
    env = {
2099
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2100
      }
2101
    for node in self.cfg.GetAllNodesInfo().values():
2102
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
2103

    
2104
    return env, [], all_nodes
2105

    
2106
  def Exec(self, feedback_fn):
2107
    """Verify integrity of cluster, performing various test on nodes.
2108

2109
    """
2110
    # This method has too many local variables. pylint: disable-msg=R0914
2111
    self.bad = False
2112
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2113
    verbose = self.op.verbose
2114
    self._feedback_fn = feedback_fn
2115
    feedback_fn("* Verifying global settings")
2116
    for msg in self.cfg.VerifyConfig():
2117
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
2118

    
2119
    # Check the cluster certificates
2120
    for cert_filename in constants.ALL_CERT_FILES:
2121
      (errcode, msg) = _VerifyCertificate(cert_filename)
2122
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
2123

    
2124
    vg_name = self.cfg.GetVGName()
2125
    drbd_helper = self.cfg.GetDRBDHelper()
2126
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
2127
    cluster = self.cfg.GetClusterInfo()
2128
    nodeinfo_byname = self.cfg.GetAllNodesInfo()
2129
    nodelist = utils.NiceSort(nodeinfo_byname.keys())
2130
    nodeinfo = [nodeinfo_byname[nname] for nname in nodelist]
2131
    instanceinfo = self.cfg.GetAllInstancesInfo()
2132
    instancelist = utils.NiceSort(instanceinfo.keys())
2133
    groupinfo = self.cfg.GetAllNodeGroupsInfo()
2134
    i_non_redundant = [] # Non redundant instances
2135
    i_non_a_balanced = [] # Non auto-balanced instances
2136
    n_offline = 0 # Count of offline nodes
2137
    n_drained = 0 # Count of nodes being drained
2138
    node_vol_should = {}
2139

    
2140
    # FIXME: verify OS list
2141
    # do local checksums
2142
    master_files = [constants.CLUSTER_CONF_FILE]
2143
    master_node = self.master_node = self.cfg.GetMasterNode()
2144
    master_ip = self.cfg.GetMasterIP()
2145

    
2146
    file_names = ssconf.SimpleStore().GetFileList()
2147
    file_names.extend(constants.ALL_CERT_FILES)
2148
    file_names.extend(master_files)
2149
    if cluster.modify_etc_hosts:
2150
      file_names.append(constants.ETC_HOSTS)
2151

    
2152
    local_checksums = utils.FingerprintFiles(file_names)
2153

    
2154
    # Compute the set of hypervisor parameters
2155
    hvp_data = []
2156
    for hv_name in hypervisors:
2157
      hvp_data.append(("cluster", hv_name, cluster.GetHVDefaults(hv_name)))
2158
    for os_name, os_hvp in cluster.os_hvp.items():
2159
      for hv_name, hv_params in os_hvp.items():
2160
        if not hv_params:
2161
          continue
2162
        full_params = cluster.GetHVDefaults(hv_name, os_name=os_name)
2163
        hvp_data.append(("os %s" % os_name, hv_name, full_params))
2164
    # TODO: collapse identical parameter values in a single one
2165
    for instance in instanceinfo.values():
2166
      if not instance.hvparams:
2167
        continue
2168
      hvp_data.append(("instance %s" % instance.name, instance.hypervisor,
2169
                       cluster.FillHV(instance)))
2170
    # and verify them locally
2171
    self._VerifyHVP(hvp_data)
2172

    
2173
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
2174
    node_verify_param = {
2175
      constants.NV_FILELIST: file_names,
2176
      constants.NV_NODELIST: [node.name for node in nodeinfo
2177
                              if not node.offline],
2178
      constants.NV_HYPERVISOR: hypervisors,
2179
      constants.NV_HVPARAMS: hvp_data,
2180
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
2181
                                  node.secondary_ip) for node in nodeinfo
2182
                                 if not node.offline],
2183
      constants.NV_INSTANCELIST: hypervisors,
2184
      constants.NV_VERSION: None,
2185
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2186
      constants.NV_NODESETUP: None,
2187
      constants.NV_TIME: None,
2188
      constants.NV_MASTERIP: (master_node, master_ip),
2189
      constants.NV_OSLIST: None,
2190
      constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2191
      }
2192

    
2193
    if vg_name is not None:
2194
      node_verify_param[constants.NV_VGLIST] = None
2195
      node_verify_param[constants.NV_LVLIST] = vg_name
2196
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2197
      node_verify_param[constants.NV_DRBDLIST] = None
2198

    
2199
    if drbd_helper:
2200
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2201

    
2202
    # bridge checks
2203
    # FIXME: this needs to be changed per node-group, not cluster-wide
2204
    bridges = set()
2205
    default_nicpp = cluster.nicparams[constants.PP_DEFAULT]
2206
    if default_nicpp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2207
      bridges.add(default_nicpp[constants.NIC_LINK])
2208
    for instance in instanceinfo.values():
2209
      for nic in instance.nics:
2210
        full_nic = cluster.SimpleFillNIC(nic.nicparams)
2211
        if full_nic[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2212
          bridges.add(full_nic[constants.NIC_LINK])
2213

    
2214
    if bridges:
2215
      node_verify_param[constants.NV_BRIDGES] = list(bridges)
2216

    
2217
    # Build our expected cluster state
2218
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2219
                                                 name=node.name,
2220
                                                 vm_capable=node.vm_capable))
2221
                      for node in nodeinfo)
2222

    
2223
    # Gather OOB paths
2224
    oob_paths = []
2225
    for node in nodeinfo:
2226
      path = _SupportsOob(self.cfg, node)
2227
      if path and path not in oob_paths:
2228
        oob_paths.append(path)
2229

    
2230
    if oob_paths:
2231
      node_verify_param[constants.NV_OOB_PATHS] = oob_paths
2232

    
2233
    for instance in instancelist:
2234
      inst_config = instanceinfo[instance]
2235

    
2236
      for nname in inst_config.all_nodes:
2237
        if nname not in node_image:
2238
          # ghost node
2239
          gnode = self.NodeImage(name=nname)
2240
          gnode.ghost = True
2241
          node_image[nname] = gnode
2242

    
2243
      inst_config.MapLVsByNode(node_vol_should)
2244

    
2245
      pnode = inst_config.primary_node
2246
      node_image[pnode].pinst.append(instance)
2247

    
2248
      for snode in inst_config.secondary_nodes:
2249
        nimg = node_image[snode]
2250
        nimg.sinst.append(instance)
2251
        if pnode not in nimg.sbp:
2252
          nimg.sbp[pnode] = []
2253
        nimg.sbp[pnode].append(instance)
2254

    
2255
    # At this point, we have the in-memory data structures complete,
2256
    # except for the runtime information, which we'll gather next
2257

    
2258
    # Due to the way our RPC system works, exact response times cannot be
2259
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2260
    # time before and after executing the request, we can at least have a time
2261
    # window.
2262
    nvinfo_starttime = time.time()
2263
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
2264
                                           self.cfg.GetClusterName())
2265
    nvinfo_endtime = time.time()
2266

    
2267
    all_drbd_map = self.cfg.ComputeDRBDMap()
2268

    
2269
    feedback_fn("* Gathering disk information (%s nodes)" % len(nodelist))
2270
    instdisk = self._CollectDiskInfo(nodelist, node_image, instanceinfo)
2271

    
2272
    feedback_fn("* Verifying node status")
2273

    
2274
    refos_img = None
2275

    
2276
    for node_i in nodeinfo:
2277
      node = node_i.name
2278
      nimg = node_image[node]
2279

    
2280
      if node_i.offline:
2281
        if verbose:
2282
          feedback_fn("* Skipping offline node %s" % (node,))
2283
        n_offline += 1
2284
        continue
2285

    
2286
      if node == master_node:
2287
        ntype = "master"
2288
      elif node_i.master_candidate:
2289
        ntype = "master candidate"
2290
      elif node_i.drained:
2291
        ntype = "drained"
2292
        n_drained += 1
2293
      else:
2294
        ntype = "regular"
2295
      if verbose:
2296
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2297

    
2298
      msg = all_nvinfo[node].fail_msg
2299
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2300
      if msg:
2301
        nimg.rpc_fail = True
2302
        continue
2303

    
2304
      nresult = all_nvinfo[node].payload
2305

    
2306
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2307
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2308
      self._VerifyNodeNetwork(node_i, nresult)
2309
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2310
                            master_files)
2311

    
2312
      self._VerifyOob(node_i, nresult)
2313

    
2314
      if nimg.vm_capable:
2315
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2316
        self._VerifyNodeDrbd(node_i, nresult, instanceinfo, drbd_helper,
2317
                             all_drbd_map)
2318

    
2319
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2320
        self._UpdateNodeInstances(node_i, nresult, nimg)
2321
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2322
        self._UpdateNodeOS(node_i, nresult, nimg)
2323
        if not nimg.os_fail:
2324
          if refos_img is None:
2325
            refos_img = nimg
2326
          self._VerifyNodeOS(node_i, nimg, refos_img)
2327
        self._VerifyNodeBridges(node_i, nresult, bridges)
2328

    
2329
    feedback_fn("* Verifying instance status")
2330
    for instance in instancelist:
2331
      if verbose:
2332
        feedback_fn("* Verifying instance %s" % instance)
2333
      inst_config = instanceinfo[instance]
2334
      self._VerifyInstance(instance, inst_config, node_image,
2335
                           instdisk[instance])
2336
      inst_nodes_offline = []
2337

    
2338
      pnode = inst_config.primary_node
2339
      pnode_img = node_image[pnode]
2340
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2341
               self.ENODERPC, pnode, "instance %s, connection to"
2342
               " primary node failed", instance)
2343

    
2344
      _ErrorIf(pnode_img.offline, self.EINSTANCEBADNODE, instance,
2345
               "instance lives on offline node %s", inst_config.primary_node)
2346

    
2347
      # If the instance is non-redundant we cannot survive losing its primary
2348
      # node, so we are not N+1 compliant. On the other hand we have no disk
2349
      # templates with more than one secondary so that situation is not well
2350
      # supported either.
2351
      # FIXME: does not support file-backed instances
2352
      if not inst_config.secondary_nodes:
2353
        i_non_redundant.append(instance)
2354

    
2355
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2356
               instance, "instance has multiple secondary nodes: %s",
2357
               utils.CommaJoin(inst_config.secondary_nodes),
2358
               code=self.ETYPE_WARNING)
2359

    
2360
      if inst_config.disk_template in constants.DTS_INT_MIRROR:
2361
        pnode = inst_config.primary_node
2362
        instance_nodes = utils.NiceSort(inst_config.all_nodes)
2363
        instance_groups = {}
2364

    
2365
        for node in instance_nodes:
2366
          instance_groups.setdefault(nodeinfo_byname[node].group,
2367
                                     []).append(node)
2368

    
2369
        pretty_list = [
2370
          "%s (group %s)" % (utils.CommaJoin(nodes), groupinfo[group].name)
2371
          # Sort so that we always list the primary node first.
2372
          for group, nodes in sorted(instance_groups.items(),
2373
                                     key=lambda (_, nodes): pnode in nodes,
2374
                                     reverse=True)]
2375

    
2376
        self._ErrorIf(len(instance_groups) > 1, self.EINSTANCESPLITGROUPS,
2377
                      instance, "instance has primary and secondary nodes in"
2378
                      " different groups: %s", utils.CommaJoin(pretty_list),
2379
                      code=self.ETYPE_WARNING)
2380

    
2381
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2382
        i_non_a_balanced.append(instance)
2383

    
2384
      for snode in inst_config.secondary_nodes:
2385
        s_img = node_image[snode]
2386
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2387
                 "instance %s, connection to secondary node failed", instance)
2388

    
2389
        if s_img.offline:
2390
          inst_nodes_offline.append(snode)
2391

    
2392
      # warn that the instance lives on offline nodes
2393
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2394
               "instance has offline secondary node(s) %s",
2395
               utils.CommaJoin(inst_nodes_offline))
2396
      # ... or ghost/non-vm_capable nodes
2397
      for node in inst_config.all_nodes:
2398
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2399
                 "instance lives on ghost node %s", node)
2400
        _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2401
                 instance, "instance lives on non-vm_capable node %s", node)
2402

    
2403
    feedback_fn("* Verifying orphan volumes")
2404
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2405
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2406

    
2407
    feedback_fn("* Verifying orphan instances")
2408
    self._VerifyOrphanInstances(instancelist, node_image)
2409

    
2410
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2411
      feedback_fn("* Verifying N+1 Memory redundancy")
2412
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2413

    
2414
    feedback_fn("* Other Notes")
2415
    if i_non_redundant:
2416
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2417
                  % len(i_non_redundant))
2418

    
2419
    if i_non_a_balanced:
2420
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2421
                  % len(i_non_a_balanced))
2422

    
2423
    if n_offline:
2424
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2425

    
2426
    if n_drained:
2427
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2428

    
2429
    return not self.bad
2430

    
2431
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2432
    """Analyze the post-hooks' result
2433

2434
    This method analyses the hook result, handles it, and sends some
2435
    nicely-formatted feedback back to the user.
2436

2437
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2438
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2439
    @param hooks_results: the results of the multi-node hooks rpc call
2440
    @param feedback_fn: function used send feedback back to the caller
2441
    @param lu_result: previous Exec result
2442
    @return: the new Exec result, based on the previous result
2443
        and hook results
2444

2445
    """
2446
    # We only really run POST phase hooks, and are only interested in
2447
    # their results
2448
    if phase == constants.HOOKS_PHASE_POST:
2449
      # Used to change hooks' output to proper indentation
2450
      feedback_fn("* Hooks Results")
2451
      assert hooks_results, "invalid result from hooks"
2452

    
2453
      for node_name in hooks_results:
2454
        res = hooks_results[node_name]
2455
        msg = res.fail_msg
2456
        test = msg and not res.offline
2457
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2458
                      "Communication failure in hooks execution: %s", msg)
2459
        if res.offline or msg:
2460
          # No need to investigate payload if node is offline or gave an error.
2461
          # override manually lu_result here as _ErrorIf only
2462
          # overrides self.bad
2463
          lu_result = 1
2464
          continue
2465
        for script, hkr, output in res.payload:
2466
          test = hkr == constants.HKR_FAIL
2467
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2468
                        "Script %s failed, output:", script)
2469
          if test:
2470
            output = self._HOOKS_INDENT_RE.sub('      ', output)
2471
            feedback_fn("%s" % output)
2472
            lu_result = 0
2473

    
2474
      return lu_result
2475

    
2476

    
2477
class LUClusterVerifyDisks(NoHooksLU):
2478
  """Verifies the cluster disks status.
2479

2480
  """
2481
  REQ_BGL = False
2482

    
2483
  def ExpandNames(self):
2484
    self.needed_locks = {
2485
      locking.LEVEL_NODE: locking.ALL_SET,
2486
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2487
    }
2488
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2489

    
2490
  def Exec(self, feedback_fn):
2491
    """Verify integrity of cluster disks.
2492

2493
    @rtype: tuple of three items
2494
    @return: a tuple of (dict of node-to-node_error, list of instances
2495
        which need activate-disks, dict of instance: (node, volume) for
2496
        missing volumes
2497

2498
    """
2499
    result = res_nodes, res_instances, res_missing = {}, [], {}
2500

    
2501
    nodes = utils.NiceSort(self.cfg.GetVmCapableNodeList())
2502
    instances = self.cfg.GetAllInstancesInfo().values()
2503

    
2504
    nv_dict = {}
2505
    for inst in instances:
2506
      inst_lvs = {}
2507
      if not inst.admin_up:
2508
        continue
2509
      inst.MapLVsByNode(inst_lvs)
2510
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2511
      for node, vol_list in inst_lvs.iteritems():
2512
        for vol in vol_list:
2513
          nv_dict[(node, vol)] = inst
2514

    
2515
    if not nv_dict:
2516
      return result
2517

    
2518
    node_lvs = self.rpc.call_lv_list(nodes, [])
2519
    for node, node_res in node_lvs.items():
2520
      if node_res.offline:
2521
        continue
2522
      msg = node_res.fail_msg
2523
      if msg:
2524
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2525
        res_nodes[node] = msg
2526
        continue
2527

    
2528
      lvs = node_res.payload
2529
      for lv_name, (_, _, lv_online) in lvs.items():
2530
        inst = nv_dict.pop((node, lv_name), None)
2531
        if (not lv_online and inst is not None
2532
            and inst.name not in res_instances):
2533
          res_instances.append(inst.name)
2534

    
2535
    # any leftover items in nv_dict are missing LVs, let's arrange the
2536
    # data better
2537
    for key, inst in nv_dict.iteritems():
2538
      if inst.name not in res_missing:
2539
        res_missing[inst.name] = []
2540
      res_missing[inst.name].append(key)
2541

    
2542
    return result
2543

    
2544

    
2545
class LUClusterRepairDiskSizes(NoHooksLU):
2546
  """Verifies the cluster disks sizes.
2547

2548
  """
2549
  REQ_BGL = False
2550

    
2551
  def ExpandNames(self):
2552
    if self.op.instances:
2553
      self.wanted_names = []
2554
      for name in self.op.instances:
2555
        full_name = _ExpandInstanceName(self.cfg, name)
2556
        self.wanted_names.append(full_name)
2557
      self.needed_locks = {
2558
        locking.LEVEL_NODE: [],
2559
        locking.LEVEL_INSTANCE: self.wanted_names,
2560
        }
2561
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2562
    else:
2563
      self.wanted_names = None
2564
      self.needed_locks = {
2565
        locking.LEVEL_NODE: locking.ALL_SET,
2566
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2567
        }
2568
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2569

    
2570
  def DeclareLocks(self, level):
2571
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2572
      self._LockInstancesNodes(primary_only=True)
2573

    
2574
  def CheckPrereq(self):
2575
    """Check prerequisites.
2576

2577
    This only checks the optional instance list against the existing names.
2578

2579
    """
2580
    if self.wanted_names is None:
2581
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2582

    
2583
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2584
                             in self.wanted_names]
2585

    
2586
  def _EnsureChildSizes(self, disk):
2587
    """Ensure children of the disk have the needed disk size.
2588

2589
    This is valid mainly for DRBD8 and fixes an issue where the
2590
    children have smaller disk size.
2591

2592
    @param disk: an L{ganeti.objects.Disk} object
2593

2594
    """
2595
    if disk.dev_type == constants.LD_DRBD8:
2596
      assert disk.children, "Empty children for DRBD8?"
2597
      fchild = disk.children[0]
2598
      mismatch = fchild.size < disk.size
2599
      if mismatch:
2600
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2601
                     fchild.size, disk.size)
2602
        fchild.size = disk.size
2603

    
2604
      # and we recurse on this child only, not on the metadev
2605
      return self._EnsureChildSizes(fchild) or mismatch
2606
    else:
2607
      return False
2608

    
2609
  def Exec(self, feedback_fn):
2610
    """Verify the size of cluster disks.
2611

2612
    """
2613
    # TODO: check child disks too
2614
    # TODO: check differences in size between primary/secondary nodes
2615
    per_node_disks = {}
2616
    for instance in self.wanted_instances:
2617
      pnode = instance.primary_node
2618
      if pnode not in per_node_disks:
2619
        per_node_disks[pnode] = []
2620
      for idx, disk in enumerate(instance.disks):
2621
        per_node_disks[pnode].append((instance, idx, disk))
2622

    
2623
    changed = []
2624
    for node, dskl in per_node_disks.items():
2625
      newl = [v[2].Copy() for v in dskl]
2626
      for dsk in newl:
2627
        self.cfg.SetDiskID(dsk, node)
2628
      result = self.rpc.call_blockdev_getsize(node, newl)
2629
      if result.fail_msg:
2630
        self.LogWarning("Failure in blockdev_getsize call to node"
2631
                        " %s, ignoring", node)
2632
        continue
2633
      if len(result.payload) != len(dskl):
2634
        logging.warning("Invalid result from node %s: len(dksl)=%d,"
2635
                        " result.payload=%s", node, len(dskl), result.payload)
2636
        self.LogWarning("Invalid result from node %s, ignoring node results",
2637
                        node)
2638
        continue
2639
      for ((instance, idx, disk), size) in zip(dskl, result.payload):
2640
        if size is None:
2641
          self.LogWarning("Disk %d of instance %s did not return size"
2642
                          " information, ignoring", idx, instance.name)
2643
          continue
2644
        if not isinstance(size, (int, long)):
2645
          self.LogWarning("Disk %d of instance %s did not return valid"
2646
                          " size information, ignoring", idx, instance.name)
2647
          continue
2648
        size = size >> 20
2649
        if size != disk.size:
2650
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2651
                       " correcting: recorded %d, actual %d", idx,
2652
                       instance.name, disk.size, size)
2653
          disk.size = size
2654
          self.cfg.Update(instance, feedback_fn)
2655
          changed.append((instance.name, idx, size))
2656
        if self._EnsureChildSizes(disk):
2657
          self.cfg.Update(instance, feedback_fn)
2658
          changed.append((instance.name, idx, disk.size))
2659
    return changed
2660

    
2661

    
2662
class LUClusterRename(LogicalUnit):
2663
  """Rename the cluster.
2664

2665
  """
2666
  HPATH = "cluster-rename"
2667
  HTYPE = constants.HTYPE_CLUSTER
2668

    
2669
  def BuildHooksEnv(self):
2670
    """Build hooks env.
2671

2672
    """
2673
    env = {
2674
      "OP_TARGET": self.cfg.GetClusterName(),
2675
      "NEW_NAME": self.op.name,
2676
      }
2677
    mn = self.cfg.GetMasterNode()
2678
    all_nodes = self.cfg.GetNodeList()
2679
    return env, [mn], all_nodes
2680

    
2681
  def CheckPrereq(self):
2682
    """Verify that the passed name is a valid one.
2683

2684
    """
2685
    hostname = netutils.GetHostname(name=self.op.name,
2686
                                    family=self.cfg.GetPrimaryIPFamily())
2687

    
2688
    new_name = hostname.name
2689
    self.ip = new_ip = hostname.ip
2690
    old_name = self.cfg.GetClusterName()
2691
    old_ip = self.cfg.GetMasterIP()
2692
    if new_name == old_name and new_ip == old_ip:
2693
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2694
                                 " cluster has changed",
2695
                                 errors.ECODE_INVAL)
2696
    if new_ip != old_ip:
2697
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2698
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2699
                                   " reachable on the network" %
2700
                                   new_ip, errors.ECODE_NOTUNIQUE)
2701

    
2702
    self.op.name = new_name
2703

    
2704
  def Exec(self, feedback_fn):
2705
    """Rename the cluster.
2706

2707
    """
2708
    clustername = self.op.name
2709
    ip = self.ip
2710

    
2711
    # shutdown the master IP
2712
    master = self.cfg.GetMasterNode()
2713
    result = self.rpc.call_node_stop_master(master, False)
2714
    result.Raise("Could not disable the master role")
2715

    
2716
    try:
2717
      cluster = self.cfg.GetClusterInfo()
2718
      cluster.cluster_name = clustername
2719
      cluster.master_ip = ip
2720
      self.cfg.Update(cluster, feedback_fn)
2721

    
2722
      # update the known hosts file
2723
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2724
      node_list = self.cfg.GetOnlineNodeList()
2725
      try:
2726
        node_list.remove(master)
2727
      except ValueError:
2728
        pass
2729
      _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
2730
    finally:
2731
      result = self.rpc.call_node_start_master(master, False, False)
2732
      msg = result.fail_msg
2733
      if msg:
2734
        self.LogWarning("Could not re-enable the master role on"
2735
                        " the master, please restart manually: %s", msg)
2736

    
2737
    return clustername
2738

    
2739

    
2740
class LUClusterSetParams(LogicalUnit):
2741
  """Change the parameters of the cluster.
2742

2743
  """
2744
  HPATH = "cluster-modify"
2745
  HTYPE = constants.HTYPE_CLUSTER
2746
  REQ_BGL = False
2747

    
2748
  def CheckArguments(self):
2749
    """Check parameters
2750

2751
    """
2752
    if self.op.uid_pool:
2753
      uidpool.CheckUidPool(self.op.uid_pool)
2754

    
2755
    if self.op.add_uids:
2756
      uidpool.CheckUidPool(self.op.add_uids)
2757

    
2758
    if self.op.remove_uids:
2759
      uidpool.CheckUidPool(self.op.remove_uids)
2760

    
2761
  def ExpandNames(self):
2762
    # FIXME: in the future maybe other cluster params won't require checking on
2763
    # all nodes to be modified.
2764
    self.needed_locks = {
2765
      locking.LEVEL_NODE: locking.ALL_SET,
2766
    }
2767
    self.share_locks[locking.LEVEL_NODE] = 1
2768

    
2769
  def BuildHooksEnv(self):
2770
    """Build hooks env.
2771

2772
    """
2773
    env = {
2774
      "OP_TARGET": self.cfg.GetClusterName(),
2775
      "NEW_VG_NAME": self.op.vg_name,
2776
      }
2777
    mn = self.cfg.GetMasterNode()
2778
    return env, [mn], [mn]
2779

    
2780
  def CheckPrereq(self):
2781
    """Check prerequisites.
2782

2783
    This checks whether the given params don't conflict and
2784
    if the given volume group is valid.
2785

2786
    """
2787
    if self.op.vg_name is not None and not self.op.vg_name:
2788
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2789
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2790
                                   " instances exist", errors.ECODE_INVAL)
2791

    
2792
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
2793
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
2794
        raise errors.OpPrereqError("Cannot disable drbd helper while"
2795
                                   " drbd-based instances exist",
2796
                                   errors.ECODE_INVAL)
2797

    
2798
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2799

    
2800
    # if vg_name not None, checks given volume group on all nodes
2801
    if self.op.vg_name:
2802
      vglist = self.rpc.call_vg_list(node_list)
2803
      for node in node_list:
2804
        msg = vglist[node].fail_msg
2805
        if msg:
2806
          # ignoring down node
2807
          self.LogWarning("Error while gathering data on node %s"
2808
                          " (ignoring node): %s", node, msg)
2809
          continue
2810
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2811
                                              self.op.vg_name,
2812
                                              constants.MIN_VG_SIZE)
2813
        if vgstatus:
2814
          raise errors.OpPrereqError("Error on node '%s': %s" %
2815
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2816

    
2817
    if self.op.drbd_helper:
2818
      # checks given drbd helper on all nodes
2819
      helpers = self.rpc.call_drbd_helper(node_list)
2820
      for node in node_list:
2821
        ninfo = self.cfg.GetNodeInfo(node)
2822
        if ninfo.offline:
2823
          self.LogInfo("Not checking drbd helper on offline node %s", node)
2824
          continue
2825
        msg = helpers[node].fail_msg
2826
        if msg:
2827
          raise errors.OpPrereqError("Error checking drbd helper on node"
2828
                                     " '%s': %s" % (node, msg),
2829
                                     errors.ECODE_ENVIRON)
2830
        node_helper = helpers[node].payload
2831
        if node_helper != self.op.drbd_helper:
2832
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
2833
                                     (node, node_helper), errors.ECODE_ENVIRON)
2834

    
2835
    self.cluster = cluster = self.cfg.GetClusterInfo()
2836
    # validate params changes
2837
    if self.op.beparams:
2838
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2839
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2840

    
2841
    if self.op.ndparams:
2842
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
2843
      self.new_ndparams = cluster.SimpleFillND(self.op.ndparams)
2844

    
2845
      # TODO: we need a more general way to handle resetting
2846
      # cluster-level parameters to default values
2847
      if self.new_ndparams["oob_program"] == "":
2848
        self.new_ndparams["oob_program"] = \
2849
            constants.NDC_DEFAULTS[constants.ND_OOB_PROGRAM]
2850

    
2851
    if self.op.nicparams:
2852
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2853
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2854
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2855
      nic_errors = []
2856

    
2857
      # check all instances for consistency
2858
      for instance in self.cfg.GetAllInstancesInfo().values():
2859
        for nic_idx, nic in enumerate(instance.nics):
2860
          params_copy = copy.deepcopy(nic.nicparams)
2861
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2862

    
2863
          # check parameter syntax
2864
          try:
2865
            objects.NIC.CheckParameterSyntax(params_filled)
2866
          except errors.ConfigurationError, err:
2867
            nic_errors.append("Instance %s, nic/%d: %s" %
2868
                              (instance.name, nic_idx, err))
2869

    
2870
          # if we're moving instances to routed, check that they have an ip
2871
          target_mode = params_filled[constants.NIC_MODE]
2872
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2873
            nic_errors.append("Instance %s, nic/%d: routed NIC with no ip"
2874
                              " address" % (instance.name, nic_idx))
2875
      if nic_errors:
2876
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2877
                                   "\n".join(nic_errors))
2878

    
2879
    # hypervisor list/parameters
2880
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2881
    if self.op.hvparams:
2882
      for hv_name, hv_dict in self.op.hvparams.items():
2883
        if hv_name not in self.new_hvparams:
2884
          self.new_hvparams[hv_name] = hv_dict
2885
        else:
2886
          self.new_hvparams[hv_name].update(hv_dict)
2887

    
2888
    # os hypervisor parameters
2889
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2890
    if self.op.os_hvp:
2891
      for os_name, hvs in self.op.os_hvp.items():
2892
        if os_name not in self.new_os_hvp:
2893
          self.new_os_hvp[os_name] = hvs
2894
        else:
2895
          for hv_name, hv_dict in hvs.items():
2896
            if hv_name not in self.new_os_hvp[os_name]:
2897
              self.new_os_hvp[os_name][hv_name] = hv_dict
2898
            else:
2899
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2900

    
2901
    # os parameters
2902
    self.new_osp = objects.FillDict(cluster.osparams, {})
2903
    if self.op.osparams:
2904
      for os_name, osp in self.op.osparams.items():
2905
        if os_name not in self.new_osp:
2906
          self.new_osp[os_name] = {}
2907

    
2908
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2909
                                                  use_none=True)
2910

    
2911
        if not self.new_osp[os_name]:
2912
          # we removed all parameters
2913
          del self.new_osp[os_name]
2914
        else:
2915
          # check the parameter validity (remote check)
2916
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
2917
                         os_name, self.new_osp[os_name])
2918

    
2919
    # changes to the hypervisor list
2920
    if self.op.enabled_hypervisors is not None:
2921
      self.hv_list = self.op.enabled_hypervisors
2922
      for hv in self.hv_list:
2923
        # if the hypervisor doesn't already exist in the cluster
2924
        # hvparams, we initialize it to empty, and then (in both
2925
        # cases) we make sure to fill the defaults, as we might not
2926
        # have a complete defaults list if the hypervisor wasn't
2927
        # enabled before
2928
        if hv not in new_hvp:
2929
          new_hvp[hv] = {}
2930
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2931
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2932
    else:
2933
      self.hv_list = cluster.enabled_hypervisors
2934

    
2935
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2936
      # either the enabled list has changed, or the parameters have, validate
2937
      for hv_name, hv_params in self.new_hvparams.items():
2938
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2939
            (self.op.enabled_hypervisors and
2940
             hv_name in self.op.enabled_hypervisors)):
2941
          # either this is a new hypervisor, or its parameters have changed
2942
          hv_class = hypervisor.GetHypervisor(hv_name)
2943
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2944
          hv_class.CheckParameterSyntax(hv_params)
2945
          _CheckHVParams(self, node_list, hv_name, hv_params)
2946

    
2947
    if self.op.os_hvp:
2948
      # no need to check any newly-enabled hypervisors, since the
2949
      # defaults have already been checked in the above code-block
2950
      for os_name, os_hvp in self.new_os_hvp.items():
2951
        for hv_name, hv_params in os_hvp.items():
2952
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2953
          # we need to fill in the new os_hvp on top of the actual hv_p
2954
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2955
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2956
          hv_class = hypervisor.GetHypervisor(hv_name)
2957
          hv_class.CheckParameterSyntax(new_osp)
2958
          _CheckHVParams(self, node_list, hv_name, new_osp)
2959

    
2960
    if self.op.default_iallocator:
2961
      alloc_script = utils.FindFile(self.op.default_iallocator,
2962
                                    constants.IALLOCATOR_SEARCH_PATH,
2963
                                    os.path.isfile)
2964
      if alloc_script is None:
2965
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
2966
                                   " specified" % self.op.default_iallocator,
2967
                                   errors.ECODE_INVAL)
2968

    
2969
  def Exec(self, feedback_fn):
2970
    """Change the parameters of the cluster.
2971

2972
    """
2973
    if self.op.vg_name is not None:
2974
      new_volume = self.op.vg_name
2975
      if not new_volume:
2976
        new_volume = None
2977
      if new_volume != self.cfg.GetVGName():
2978
        self.cfg.SetVGName(new_volume)
2979
      else:
2980
        feedback_fn("Cluster LVM configuration already in desired"
2981
                    " state, not changing")
2982
    if self.op.drbd_helper is not None:
2983
      new_helper = self.op.drbd_helper
2984
      if not new_helper:
2985
        new_helper = None
2986
      if new_helper != self.cfg.GetDRBDHelper():
2987
        self.cfg.SetDRBDHelper(new_helper)
2988
      else:
2989
        feedback_fn("Cluster DRBD helper already in desired state,"
2990
                    " not changing")
2991
    if self.op.hvparams:
2992
      self.cluster.hvparams = self.new_hvparams
2993
    if self.op.os_hvp:
2994
      self.cluster.os_hvp = self.new_os_hvp
2995
    if self.op.enabled_hypervisors is not None:
2996
      self.cluster.hvparams = self.new_hvparams
2997
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2998
    if self.op.beparams:
2999
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
3000
    if self.op.nicparams:
3001
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
3002
    if self.op.osparams:
3003
      self.cluster.osparams = self.new_osp
3004
    if self.op.ndparams:
3005
      self.cluster.ndparams = self.new_ndparams
3006

    
3007
    if self.op.candidate_pool_size is not None:
3008
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
3009
      # we need to update the pool size here, otherwise the save will fail
3010
      _AdjustCandidatePool(self, [])
3011

    
3012
    if self.op.maintain_node_health is not None:
3013
      self.cluster.maintain_node_health = self.op.maintain_node_health
3014

    
3015
    if self.op.prealloc_wipe_disks is not None:
3016
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
3017

    
3018
    if self.op.add_uids is not None:
3019
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
3020

    
3021
    if self.op.remove_uids is not None:
3022
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
3023

    
3024
    if self.op.uid_pool is not None:
3025
      self.cluster.uid_pool = self.op.uid_pool
3026

    
3027
    if self.op.default_iallocator is not None:
3028
      self.cluster.default_iallocator = self.op.default_iallocator
3029

    
3030
    if self.op.reserved_lvs is not None:
3031
      self.cluster.reserved_lvs = self.op.reserved_lvs
3032

    
3033
    def helper_os(aname, mods, desc):
3034
      desc += " OS list"
3035
      lst = getattr(self.cluster, aname)
3036
      for key, val in mods:
3037
        if key == constants.DDM_ADD:
3038
          if val in lst:
3039
            feedback_fn("OS %s already in %s, ignoring" % (val, desc))
3040
          else:
3041
            lst.append(val)
3042
        elif key == constants.DDM_REMOVE:
3043
          if val in lst:
3044
            lst.remove(val)
3045
          else:
3046
            feedback_fn("OS %s not found in %s, ignoring" % (val, desc))
3047
        else:
3048
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
3049

    
3050
    if self.op.hidden_os:
3051
      helper_os("hidden_os", self.op.hidden_os, "hidden")
3052

    
3053
    if self.op.blacklisted_os:
3054
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
3055

    
3056
    if self.op.master_netdev:
3057
      master = self.cfg.GetMasterNode()
3058
      feedback_fn("Shutting down master ip on the current netdev (%s)" %
3059
                  self.cluster.master_netdev)
3060
      result = self.rpc.call_node_stop_master(master, False)
3061
      result.Raise("Could not disable the master ip")
3062
      feedback_fn("Changing master_netdev from %s to %s" %
3063
                  (self.cluster.master_netdev, self.op.master_netdev))
3064
      self.cluster.master_netdev = self.op.master_netdev
3065

    
3066
    self.cfg.Update(self.cluster, feedback_fn)
3067

    
3068
    if self.op.master_netdev:
3069
      feedback_fn("Starting the master ip on the new master netdev (%s)" %
3070
                  self.op.master_netdev)
3071
      result = self.rpc.call_node_start_master(master, False, False)
3072
      if result.fail_msg:
3073
        self.LogWarning("Could not re-enable the master ip on"
3074
                        " the master, please restart manually: %s",
3075
                        result.fail_msg)
3076

    
3077

    
3078
def _UploadHelper(lu, nodes, fname):
3079
  """Helper for uploading a file and showing warnings.
3080

3081
  """
3082
  if os.path.exists(fname):
3083
    result = lu.rpc.call_upload_file(nodes, fname)
3084
    for to_node, to_result in result.items():
3085
      msg = to_result.fail_msg
3086
      if msg:
3087
        msg = ("Copy of file %s to node %s failed: %s" %
3088
               (fname, to_node, msg))
3089
        lu.proc.LogWarning(msg)
3090

    
3091

    
3092
def _RedistributeAncillaryFiles(lu, additional_nodes=None, additional_vm=True):
3093
  """Distribute additional files which are part of the cluster configuration.
3094

3095
  ConfigWriter takes care of distributing the config and ssconf files, but
3096
  there are more files which should be distributed to all nodes. This function
3097
  makes sure those are copied.
3098

3099
  @param lu: calling logical unit
3100
  @param additional_nodes: list of nodes not in the config to distribute to
3101
  @type additional_vm: boolean
3102
  @param additional_vm: whether the additional nodes are vm-capable or not
3103

3104
  """
3105
  # 1. Gather target nodes
3106
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
3107
  dist_nodes = lu.cfg.GetOnlineNodeList()
3108
  nvm_nodes = lu.cfg.GetNonVmCapableNodeList()
3109
  vm_nodes = [name for name in dist_nodes if name not in nvm_nodes]
3110
  if additional_nodes is not None:
3111
    dist_nodes.extend(additional_nodes)
3112
    if additional_vm:
3113
      vm_nodes.extend(additional_nodes)
3114
  if myself.name in dist_nodes:
3115
    dist_nodes.remove(myself.name)
3116
  if myself.name in vm_nodes:
3117
    vm_nodes.remove(myself.name)
3118

    
3119
  # 2. Gather files to distribute
3120
  dist_files = set([constants.ETC_HOSTS,
3121
                    constants.SSH_KNOWN_HOSTS_FILE,
3122
                    constants.RAPI_CERT_FILE,
3123
                    constants.RAPI_USERS_FILE,
3124
                    constants.CONFD_HMAC_KEY,
3125
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
3126
                   ])
3127

    
3128
  vm_files = set()
3129
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
3130
  for hv_name in enabled_hypervisors:
3131
    hv_class = hypervisor.GetHypervisor(hv_name)
3132
    vm_files.update(hv_class.GetAncillaryFiles())
3133

    
3134
  # 3. Perform the files upload
3135
  for fname in dist_files:
3136
    _UploadHelper(lu, dist_nodes, fname)
3137
  for fname in vm_files:
3138
    _UploadHelper(lu, vm_nodes, fname)
3139

    
3140

    
3141
class LUClusterRedistConf(NoHooksLU):
3142
  """Force the redistribution of cluster configuration.
3143

3144
  This is a very simple LU.
3145

3146
  """
3147
  REQ_BGL = False
3148

    
3149
  def ExpandNames(self):
3150
    self.needed_locks = {
3151
      locking.LEVEL_NODE: locking.ALL_SET,
3152
    }
3153
    self.share_locks[locking.LEVEL_NODE] = 1
3154

    
3155
  def Exec(self, feedback_fn):
3156
    """Redistribute the configuration.
3157

3158
    """
3159
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
3160
    _RedistributeAncillaryFiles(self)
3161

    
3162

    
3163
def _WaitForSync(lu, instance, disks=None, oneshot=False):
3164
  """Sleep and poll for an instance's disk to sync.
3165

3166
  """
3167
  if not instance.disks or disks is not None and not disks:
3168
    return True
3169

    
3170
  disks = _ExpandCheckDisks(instance, disks)
3171

    
3172
  if not oneshot:
3173
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
3174

    
3175
  node = instance.primary_node
3176

    
3177
  for dev in disks:
3178
    lu.cfg.SetDiskID(dev, node)
3179

    
3180
  # TODO: Convert to utils.Retry
3181

    
3182
  retries = 0
3183
  degr_retries = 10 # in seconds, as we sleep 1 second each time
3184
  while True:
3185
    max_time = 0
3186
    done = True
3187
    cumul_degraded = False
3188
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
3189
    msg = rstats.fail_msg
3190
    if msg:
3191
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
3192
      retries += 1
3193
      if retries >= 10:
3194
        raise errors.RemoteError("Can't contact node %s for mirror data,"
3195
                                 " aborting." % node)
3196
      time.sleep(6)
3197
      continue
3198
    rstats = rstats.payload
3199
    retries = 0
3200
    for i, mstat in enumerate(rstats):
3201
      if mstat is None:
3202
        lu.LogWarning("Can't compute data for node %s/%s",
3203
                           node, disks[i].iv_name)
3204
        continue
3205

    
3206
      cumul_degraded = (cumul_degraded or
3207
                        (mstat.is_degraded and mstat.sync_percent is None))
3208
      if mstat.sync_percent is not None:
3209
        done = False
3210
        if mstat.estimated_time is not None:
3211
          rem_time = ("%s remaining (estimated)" %
3212
                      utils.FormatSeconds(mstat.estimated_time))
3213
          max_time = mstat.estimated_time
3214
        else:
3215
          rem_time = "no time estimate"
3216
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3217
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3218

    
3219
    # if we're done but degraded, let's do a few small retries, to
3220
    # make sure we see a stable and not transient situation; therefore
3221
    # we force restart of the loop
3222
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3223
      logging.info("Degraded disks found, %d retries left", degr_retries)
3224
      degr_retries -= 1
3225
      time.sleep(1)
3226
      continue
3227

    
3228
    if done or oneshot:
3229
      break
3230

    
3231
    time.sleep(min(60, max_time))
3232

    
3233
  if done:
3234
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3235
  return not cumul_degraded
3236

    
3237

    
3238
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3239
  """Check that mirrors are not degraded.
3240

3241
  The ldisk parameter, if True, will change the test from the
3242
  is_degraded attribute (which represents overall non-ok status for
3243
  the device(s)) to the ldisk (representing the local storage status).
3244

3245
  """
3246
  lu.cfg.SetDiskID(dev, node)
3247

    
3248
  result = True
3249

    
3250
  if on_primary or dev.AssembleOnSecondary():
3251
    rstats = lu.rpc.call_blockdev_find(node, dev)
3252
    msg = rstats.fail_msg
3253
    if msg:
3254
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3255
      result = False
3256
    elif not rstats.payload:
3257
      lu.LogWarning("Can't find disk on node %s", node)
3258
      result = False
3259
    else:
3260
      if ldisk:
3261
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3262
      else:
3263
        result = result and not rstats.payload.is_degraded
3264

    
3265
  if dev.children:
3266
    for child in dev.children:
3267
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3268

    
3269
  return result
3270

    
3271

    
3272
class LUOobCommand(NoHooksLU):
3273
  """Logical unit for OOB handling.
3274

3275
  """
3276
  REG_BGL = False
3277

    
3278
  def CheckPrereq(self):
3279
    """Check prerequisites.
3280

3281
    This checks:
3282
     - the node exists in the configuration
3283
     - OOB is supported
3284

3285
    Any errors are signaled by raising errors.OpPrereqError.
3286

3287
    """
3288
    self.nodes = []
3289
    for node_name in self.op.node_names:
3290
      node = self.cfg.GetNodeInfo(node_name)
3291

    
3292
      if node is None:
3293
        raise errors.OpPrereqError("Node %s not found" % node_name,
3294
                                   errors.ECODE_NOENT)
3295
      else:
3296
        self.nodes.append(node)
3297

    
3298
      if (self.op.command == constants.OOB_POWER_OFF and not node.offline):
3299
        raise errors.OpPrereqError(("Cannot power off node %s because it is"
3300
                                    " not marked offline") % node_name,
3301
                                   errors.ECODE_STATE)
3302

    
3303
  def ExpandNames(self):
3304
    """Gather locks we need.
3305

3306
    """
3307
    if self.op.node_names:
3308
      self.op.node_names = [_ExpandNodeName(self.cfg, name)
3309
                            for name in self.op.node_names]
3310
    else:
3311
      self.op.node_names = self.cfg.GetNodeList()
3312

    
3313
    self.needed_locks = {
3314
      locking.LEVEL_NODE: self.op.node_names,
3315
      }
3316

    
3317
  def Exec(self, feedback_fn):
3318
    """Execute OOB and return result if we expect any.
3319

3320
    """
3321
    master_node = self.cfg.GetMasterNode()
3322
    ret = []
3323

    
3324
    for node in self.nodes:
3325
      node_entry = [(constants.RS_NORMAL, node.name)]
3326
      ret.append(node_entry)
3327

    
3328
      oob_program = _SupportsOob(self.cfg, node)
3329

    
3330
      if not oob_program:
3331
        node_entry.append((constants.RS_UNAVAIL, None))
3332
        continue
3333

    
3334
      logging.info("Executing out-of-band command '%s' using '%s' on %s",
3335
                   self.op.command, oob_program, node.name)
3336
      result = self.rpc.call_run_oob(master_node, oob_program,
3337
                                     self.op.command, node.name,
3338
                                     self.op.timeout)
3339

    
3340
      if result.fail_msg:
3341
        self.LogWarning("On node '%s' out-of-band RPC failed with: %s",
3342
                        node.name, result.fail_msg)
3343
        node_entry.append((constants.RS_NODATA, None))
3344
      else:
3345
        try:
3346
          self._CheckPayload(result)
3347
        except errors.OpExecError, err:
3348
          self.LogWarning("The payload returned by '%s' is not valid: %s",
3349
                          node.name, err)
3350
          node_entry.append((constants.RS_NODATA, None))
3351
        else:
3352
          if self.op.command == constants.OOB_HEALTH:
3353
            # For health we should log important events
3354
            for item, status in result.payload:
3355
              if status in [constants.OOB_STATUS_WARNING,
3356
                            constants.OOB_STATUS_CRITICAL]:
3357
                self.LogWarning("On node '%s' item '%s' has status '%s'",
3358
                                node.name, item, status)
3359

    
3360
          if self.op.command == constants.OOB_POWER_ON:
3361
            node.powered = True
3362
          elif self.op.command == constants.OOB_POWER_OFF:
3363
            node.powered = False
3364
          elif self.op.command == constants.OOB_POWER_STATUS:
3365
            powered = result.payload[constants.OOB_POWER_STATUS_POWERED]
3366
            if powered != node.powered:
3367
              logging.warning(("Recorded power state (%s) of node '%s' does not"
3368
                               " match actual power state (%s)"), node.powered,
3369
                              node.name, powered)
3370

    
3371
          # For configuration changing commands we should update the node
3372
          if self.op.command in (constants.OOB_POWER_ON,
3373
                                 constants.OOB_POWER_OFF):
3374
            self.cfg.Update(node, feedback_fn)
3375

    
3376
          node_entry.append((constants.RS_NORMAL, result.payload))
3377

    
3378
    return ret
3379

    
3380
  def _CheckPayload(self, result):
3381
    """Checks if the payload is valid.
3382

3383
    @param result: RPC result
3384
    @raises errors.OpExecError: If payload is not valid
3385

3386
    """
3387
    errs = []
3388
    if self.op.command == constants.OOB_HEALTH:
3389
      if not isinstance(result.payload, list):
3390
        errs.append("command 'health' is expected to return a list but got %s" %
3391
                    type(result.payload))
3392
      else:
3393
        for item, status in result.payload:
3394
          if status not in constants.OOB_STATUSES:
3395
            errs.append("health item '%s' has invalid status '%s'" %
3396
                        (item, status))
3397

    
3398
    if self.op.command == constants.OOB_POWER_STATUS:
3399
      if not isinstance(result.payload, dict):
3400
        errs.append("power-status is expected to return a dict but got %s" %
3401
                    type(result.payload))
3402

    
3403
    if self.op.command in [
3404
        constants.OOB_POWER_ON,
3405
        constants.OOB_POWER_OFF,
3406
        constants.OOB_POWER_CYCLE,
3407
        ]:
3408
      if result.payload is not None:
3409
        errs.append("%s is expected to not return payload but got '%s'" %
3410
                    (self.op.command, result.payload))
3411

    
3412
    if errs:
3413
      raise errors.OpExecError("Check of out-of-band payload failed due to %s" %
3414
                               utils.CommaJoin(errs))
3415

    
3416

    
3417

    
3418
class LUOsDiagnose(NoHooksLU):
3419
  """Logical unit for OS diagnose/query.
3420

3421
  """
3422
  REQ_BGL = False
3423
  _HID = "hidden"
3424
  _BLK = "blacklisted"
3425
  _VLD = "valid"
3426
  _FIELDS_STATIC = utils.FieldSet()
3427
  _FIELDS_DYNAMIC = utils.FieldSet("name", _VLD, "node_status", "variants",
3428
                                   "parameters", "api_versions", _HID, _BLK)
3429

    
3430
  def CheckArguments(self):
3431
    if self.op.names:
3432
      raise errors.OpPrereqError("Selective OS query not supported",
3433
                                 errors.ECODE_INVAL)
3434

    
3435
    _CheckOutputFields(static=self._FIELDS_STATIC,
3436
                       dynamic=self._FIELDS_DYNAMIC,
3437
                       selected=self.op.output_fields)
3438

    
3439
  def ExpandNames(self):
3440
    # Lock all nodes, in shared mode
3441
    # Temporary removal of locks, should be reverted later
3442
    # TODO: reintroduce locks when they are lighter-weight
3443
    self.needed_locks = {}
3444
    #self.share_locks[locking.LEVEL_NODE] = 1
3445
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3446

    
3447
  @staticmethod
3448
  def _DiagnoseByOS(rlist):
3449
    """Remaps a per-node return list into an a per-os per-node dictionary
3450

3451
    @param rlist: a map with node names as keys and OS objects as values
3452

3453
    @rtype: dict
3454
    @return: a dictionary with osnames as keys and as value another
3455
        map, with nodes as keys and tuples of (path, status, diagnose,
3456
        variants, parameters, api_versions) as values, eg::
3457

3458
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3459
                                     (/srv/..., False, "invalid api")],
3460
                           "node2": [(/srv/..., True, "", [], [])]}
3461
          }
3462

3463
    """
3464
    all_os = {}
3465
    # we build here the list of nodes that didn't fail the RPC (at RPC
3466
    # level), so that nodes with a non-responding node daemon don't
3467
    # make all OSes invalid
3468
    good_nodes = [node_name for node_name in rlist
3469
                  if not rlist[node_name].fail_msg]
3470
    for node_name, nr in rlist.items():
3471
      if nr.fail_msg or not nr.payload:
3472
        continue
3473
      for (name, path, status, diagnose, variants,
3474
           params, api_versions) in nr.payload:
3475
        if name not in all_os:
3476
          # build a list of nodes for this os containing empty lists
3477
          # for each node in node_list
3478
          all_os[name] = {}
3479
          for nname in good_nodes:
3480
            all_os[name][nname] = []
3481
        # convert params from [name, help] to (name, help)
3482
        params = [tuple(v) for v in params]
3483
        all_os[name][node_name].append((path, status, diagnose,
3484
                                        variants, params, api_versions))
3485
    return all_os
3486

    
3487
  def Exec(self, feedback_fn):
3488
    """Compute the list of OSes.
3489

3490
    """
3491
    valid_nodes = [node.name
3492
                   for node in self.cfg.GetAllNodesInfo().values()
3493
                   if not node.offline and node.vm_capable]
3494
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3495
    pol = self._DiagnoseByOS(node_data)
3496
    output = []
3497
    cluster = self.cfg.GetClusterInfo()
3498

    
3499
    for os_name in utils.NiceSort(pol.keys()):
3500
      os_data = pol[os_name]
3501
      row = []
3502
      valid = True
3503
      (variants, params, api_versions) = null_state = (set(), set(), set())
3504
      for idx, osl in enumerate(os_data.values()):
3505
        valid = bool(valid and osl and osl[0][1])
3506
        if not valid:
3507
          (variants, params, api_versions) = null_state
3508
          break
3509
        node_variants, node_params, node_api = osl[0][3:6]
3510
        if idx == 0: # first entry
3511
          variants = set(node_variants)
3512
          params = set(node_params)
3513
          api_versions = set(node_api)
3514
        else: # keep consistency
3515
          variants.intersection_update(node_variants)
3516
          params.intersection_update(node_params)
3517
          api_versions.intersection_update(node_api)
3518

    
3519
      is_hid = os_name in cluster.hidden_os
3520
      is_blk = os_name in cluster.blacklisted_os
3521
      if ((self._HID not in self.op.output_fields and is_hid) or
3522
          (self._BLK not in self.op.output_fields and is_blk) or
3523
          (self._VLD not in self.op.output_fields and not valid)):
3524
        continue
3525

    
3526
      for field in self.op.output_fields:
3527
        if field == "name":
3528
          val = os_name
3529
        elif field == self._VLD:
3530
          val = valid
3531
        elif field == "node_status":
3532
          # this is just a copy of the dict
3533
          val = {}
3534
          for node_name, nos_list in os_data.items():
3535
            val[node_name] = nos_list
3536
        elif field == "variants":
3537
          val = utils.NiceSort(list(variants))
3538
        elif field == "parameters":
3539
          val = list(params)
3540
        elif field == "api_versions":
3541
          val = list(api_versions)
3542
        elif field == self._HID:
3543
          val = is_hid
3544
        elif field == self._BLK:
3545
          val = is_blk
3546
        else:
3547
          raise errors.ParameterError(field)
3548
        row.append(val)
3549
      output.append(row)
3550

    
3551
    return output
3552

    
3553

    
3554
class LUNodeRemove(LogicalUnit):
3555
  """Logical unit for removing a node.
3556

3557
  """
3558
  HPATH = "node-remove"
3559
  HTYPE = constants.HTYPE_NODE
3560

    
3561
  def BuildHooksEnv(self):
3562
    """Build hooks env.
3563

3564
    This doesn't run on the target node in the pre phase as a failed
3565
    node would then be impossible to remove.
3566

3567
    """
3568
    env = {
3569
      "OP_TARGET": self.op.node_name,
3570
      "NODE_NAME": self.op.node_name,
3571
      }
3572
    all_nodes = self.cfg.GetNodeList()
3573
    try:
3574
      all_nodes.remove(self.op.node_name)
3575
    except ValueError:
3576
      logging.warning("Node %s which is about to be removed not found"
3577
                      " in the all nodes list", self.op.node_name)
3578
    return env, all_nodes, all_nodes
3579

    
3580
  def CheckPrereq(self):
3581
    """Check prerequisites.
3582

3583
    This checks:
3584
     - the node exists in the configuration
3585
     - it does not have primary or secondary instances
3586
     - it's not the master
3587

3588
    Any errors are signaled by raising errors.OpPrereqError.
3589

3590
    """
3591
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3592
    node = self.cfg.GetNodeInfo(self.op.node_name)
3593
    assert node is not None
3594

    
3595
    instance_list = self.cfg.GetInstanceList()
3596

    
3597
    masternode = self.cfg.GetMasterNode()
3598
    if node.name == masternode:
3599
      raise errors.OpPrereqError("Node is the master node,"
3600
                                 " you need to failover first.",
3601
                                 errors.ECODE_INVAL)
3602

    
3603
    for instance_name in instance_list:
3604
      instance = self.cfg.GetInstanceInfo(instance_name)
3605
      if node.name in instance.all_nodes:
3606
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3607
                                   " please remove first." % instance_name,
3608
                                   errors.ECODE_INVAL)
3609
    self.op.node_name = node.name
3610
    self.node = node
3611

    
3612
  def Exec(self, feedback_fn):
3613
    """Removes the node from the cluster.
3614

3615
    """
3616
    node = self.node
3617
    logging.info("Stopping the node daemon and removing configs from node %s",
3618
                 node.name)
3619

    
3620
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3621

    
3622
    # Promote nodes to master candidate as needed
3623
    _AdjustCandidatePool(self, exceptions=[node.name])
3624
    self.context.RemoveNode(node.name)
3625

    
3626
    # Run post hooks on the node before it's removed
3627
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3628
    try:
3629
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3630
    except:
3631
      # pylint: disable-msg=W0702
3632
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3633

    
3634
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3635
    msg = result.fail_msg
3636
    if msg:
3637
      self.LogWarning("Errors encountered on the remote node while leaving"
3638
                      " the cluster: %s", msg)
3639

    
3640
    # Remove node from our /etc/hosts
3641
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3642
      master_node = self.cfg.GetMasterNode()
3643
      result = self.rpc.call_etc_hosts_modify(master_node,
3644
                                              constants.ETC_HOSTS_REMOVE,
3645
                                              node.name, None)
3646
      result.Raise("Can't update hosts file with new host data")
3647
      _RedistributeAncillaryFiles(self)
3648

    
3649

    
3650
class _NodeQuery(_QueryBase):
3651
  FIELDS = query.NODE_FIELDS
3652

    
3653
  def ExpandNames(self, lu):
3654
    lu.needed_locks = {}
3655
    lu.share_locks[locking.LEVEL_NODE] = 1
3656

    
3657
    if self.names:
3658
      self.wanted = _GetWantedNodes(lu, self.names)
3659
    else:
3660
      self.wanted = locking.ALL_SET
3661

    
3662
    self.do_locking = (self.use_locking and
3663
                       query.NQ_LIVE in self.requested_data)
3664

    
3665
    if self.do_locking:
3666
      # if we don't request only static fields, we need to lock the nodes
3667
      lu.needed_locks[locking.LEVEL_NODE] = self.wanted
3668

    
3669
  def DeclareLocks(self, lu, level):
3670
    pass
3671

    
3672
  def _GetQueryData(self, lu):
3673
    """Computes the list of nodes and their attributes.
3674

3675
    """
3676
    all_info = lu.cfg.GetAllNodesInfo()
3677

    
3678
    nodenames = self._GetNames(lu, all_info.keys(), locking.LEVEL_NODE)
3679

    
3680
    # Gather data as requested
3681
    if query.NQ_LIVE in self.requested_data:
3682
      # filter out non-vm_capable nodes
3683
      toquery_nodes = [name for name in nodenames if all_info[name].vm_capable]
3684

    
3685
      node_data = lu.rpc.call_node_info(toquery_nodes, lu.cfg.GetVGName(),
3686
                                        lu.cfg.GetHypervisorType())
3687
      live_data = dict((name, nresult.payload)
3688
                       for (name, nresult) in node_data.items()
3689
                       if not nresult.fail_msg and nresult.payload)
3690
    else:
3691
      live_data = None
3692

    
3693
    if query.NQ_INST in self.requested_data:
3694
      node_to_primary = dict([(name, set()) for name in nodenames])
3695
      node_to_secondary = dict([(name, set()) for name in nodenames])
3696

    
3697
      inst_data = lu.cfg.GetAllInstancesInfo()
3698

    
3699
      for inst in inst_data.values():
3700
        if inst.primary_node in node_to_primary:
3701
          node_to_primary[inst.primary_node].add(inst.name)
3702
        for secnode in inst.secondary_nodes:
3703
          if secnode in node_to_secondary:
3704
            node_to_secondary[secnode].add(inst.name)
3705
    else:
3706
      node_to_primary = None
3707
      node_to_secondary = None
3708

    
3709
    if query.NQ_OOB in self.requested_data:
3710
      oob_support = dict((name, bool(_SupportsOob(lu.cfg, node)))
3711
                         for name, node in all_info.iteritems())
3712
    else:
3713
      oob_support = None
3714

    
3715
    if query.NQ_GROUP in self.requested_data:
3716
      groups = lu.cfg.GetAllNodeGroupsInfo()
3717
    else:
3718
      groups = {}
3719

    
3720
    return query.NodeQueryData([all_info[name] for name in nodenames],
3721
                               live_data, lu.cfg.GetMasterNode(),
3722
                               node_to_primary, node_to_secondary, groups,
3723
                               oob_support, lu.cfg.GetClusterInfo())
3724

    
3725

    
3726
class LUNodeQuery(NoHooksLU):
3727
  """Logical unit for querying nodes.
3728

3729
  """
3730
  # pylint: disable-msg=W0142
3731
  REQ_BGL = False
3732

    
3733
  def CheckArguments(self):
3734
    self.nq = _NodeQuery(self.op.names, self.op.output_fields,
3735
                         self.op.use_locking)
3736

    
3737
  def ExpandNames(self):
3738
    self.nq.ExpandNames(self)
3739

    
3740
  def Exec(self, feedback_fn):
3741
    return self.nq.OldStyleQuery(self)
3742

    
3743

    
3744
class LUNodeQueryvols(NoHooksLU):
3745
  """Logical unit for getting volumes on node(s).
3746

3747
  """
3748
  REQ_BGL = False
3749
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3750
  _FIELDS_STATIC = utils.FieldSet("node")
3751

    
3752
  def CheckArguments(self):
3753
    _CheckOutputFields(static=self._FIELDS_STATIC,
3754
                       dynamic=self._FIELDS_DYNAMIC,
3755
                       selected=self.op.output_fields)
3756

    
3757
  def ExpandNames(self):
3758
    self.needed_locks = {}
3759
    self.share_locks[locking.LEVEL_NODE] = 1
3760
    if not self.op.nodes:
3761
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3762
    else:
3763
      self.needed_locks[locking.LEVEL_NODE] = \
3764
        _GetWantedNodes(self, self.op.nodes)
3765

    
3766
  def Exec(self, feedback_fn):
3767
    """Computes the list of nodes and their attributes.
3768

3769
    """
3770
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3771
    volumes = self.rpc.call_node_volumes(nodenames)
3772

    
3773
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3774
             in self.cfg.GetInstanceList()]
3775

    
3776
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3777

    
3778
    output = []
3779
    for node in nodenames:
3780
      nresult = volumes[node]
3781
      if nresult.offline:
3782
        continue
3783
      msg = nresult.fail_msg
3784
      if msg:
3785
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3786
        continue
3787

    
3788
      node_vols = nresult.payload[:]
3789
      node_vols.sort(key=lambda vol: vol['dev'])
3790

    
3791
      for vol in node_vols:
3792
        node_output = []
3793
        for field in self.op.output_fields:
3794
          if field == "node":
3795
            val = node
3796
          elif field == "phys":
3797
            val = vol['dev']
3798
          elif field == "vg":
3799
            val = vol['vg']
3800
          elif field == "name":
3801
            val = vol['name']
3802
          elif field == "size":
3803
            val = int(float(vol['size']))
3804
          elif field == "instance":
3805
            for inst in ilist:
3806
              if node not in lv_by_node[inst]:
3807
                continue
3808
              if vol['name'] in lv_by_node[inst][node]:
3809
                val = inst.name
3810
                break
3811
            else:
3812
              val = '-'
3813
          else:
3814
            raise errors.ParameterError(field)
3815
          node_output.append(str(val))
3816

    
3817
        output.append(node_output)
3818

    
3819
    return output
3820

    
3821

    
3822
class LUNodeQueryStorage(NoHooksLU):
3823
  """Logical unit for getting information on storage units on node(s).
3824

3825
  """
3826
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3827
  REQ_BGL = False
3828

    
3829
  def CheckArguments(self):
3830
    _CheckOutputFields(static=self._FIELDS_STATIC,
3831
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3832
                       selected=self.op.output_fields)
3833

    
3834
  def ExpandNames(self):
3835
    self.needed_locks = {}
3836
    self.share_locks[locking.LEVEL_NODE] = 1
3837

    
3838
    if self.op.nodes:
3839
      self.needed_locks[locking.LEVEL_NODE] = \
3840
        _GetWantedNodes(self, self.op.nodes)
3841
    else:
3842
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3843

    
3844
  def Exec(self, feedback_fn):
3845
    """Computes the list of nodes and their attributes.
3846

3847
    """
3848
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3849

    
3850
    # Always get name to sort by
3851
    if constants.SF_NAME in self.op.output_fields:
3852
      fields = self.op.output_fields[:]
3853
    else:
3854
      fields = [constants.SF_NAME] + self.op.output_fields
3855

    
3856
    # Never ask for node or type as it's only known to the LU
3857
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3858
      while extra in fields:
3859
        fields.remove(extra)
3860

    
3861
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3862
    name_idx = field_idx[constants.SF_NAME]
3863

    
3864
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3865
    data = self.rpc.call_storage_list(self.nodes,
3866
                                      self.op.storage_type, st_args,
3867
                                      self.op.name, fields)
3868

    
3869
    result = []
3870

    
3871
    for node in utils.NiceSort(self.nodes):
3872
      nresult = data[node]
3873
      if nresult.offline:
3874
        continue
3875

    
3876
      msg = nresult.fail_msg
3877
      if msg:
3878
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3879
        continue
3880

    
3881
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3882

    
3883
      for name in utils.NiceSort(rows.keys()):
3884
        row = rows[name]
3885

    
3886
        out = []
3887

    
3888
        for field in self.op.output_fields:
3889
          if field == constants.SF_NODE:
3890
            val = node
3891
          elif field == constants.SF_TYPE:
3892
            val = self.op.storage_type
3893
          elif field in field_idx:
3894
            val = row[field_idx[field]]
3895
          else:
3896
            raise errors.ParameterError(field)
3897

    
3898
          out.append(val)
3899

    
3900
        result.append(out)
3901

    
3902
    return result
3903

    
3904

    
3905
class _InstanceQuery(_QueryBase):
3906
  FIELDS = query.INSTANCE_FIELDS
3907

    
3908
  def ExpandNames(self, lu):
3909
    lu.needed_locks = {}
3910
    lu.share_locks[locking.LEVEL_INSTANCE] = 1
3911
    lu.share_locks[locking.LEVEL_NODE] = 1
3912

    
3913
    if self.names:
3914
      self.wanted = _GetWantedInstances(lu, self.names)
3915
    else:
3916
      self.wanted = locking.ALL_SET
3917

    
3918
    self.do_locking = (self.use_locking and
3919
                       query.IQ_LIVE in self.requested_data)
3920
    if self.do_locking:
3921
      lu.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
3922
      lu.needed_locks[locking.LEVEL_NODE] = []
3923
      lu.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3924

    
3925
  def DeclareLocks(self, lu, level):
3926
    if level == locking.LEVEL_NODE and self.do_locking:
3927
      lu._LockInstancesNodes() # pylint: disable-msg=W0212
3928

    
3929
  def _GetQueryData(self, lu):
3930
    """Computes the list of instances and their attributes.
3931

3932
    """
3933
    cluster = lu.cfg.GetClusterInfo()
3934
    all_info = lu.cfg.GetAllInstancesInfo()
3935

    
3936
    instance_names = self._GetNames(lu, all_info.keys(), locking.LEVEL_INSTANCE)
3937

    
3938
    instance_list = [all_info[name] for name in instance_names]
3939
    nodes = frozenset(itertools.chain(*(inst.all_nodes
3940
                                        for inst in instance_list)))
3941
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
3942
    bad_nodes = []
3943
    offline_nodes = []
3944
    wrongnode_inst = set()
3945

    
3946
    # Gather data as requested
3947
    if self.requested_data & set([query.IQ_LIVE, query.IQ_CONSOLE]):
3948
      live_data = {}
3949
      node_data = lu.rpc.call_all_instances_info(nodes, hv_list)
3950
      for name in nodes:
3951
        result = node_data[name]
3952
        if result.offline:
3953
          # offline nodes will be in both lists
3954
          assert result.fail_msg
3955
          offline_nodes.append(name)
3956
        if result.fail_msg:
3957
          bad_nodes.append(name)
3958
        elif result.payload:
3959
          for inst in result.payload:
3960
            if inst in all_info:
3961
              if all_info[inst].primary_node == name:
3962
                live_data.update(result.payload)
3963
              else:
3964
                wrongnode_inst.add(inst)
3965
            else:
3966
              # orphan instance; we don't list it here as we don't
3967
              # handle this case yet in the output of instance listing
3968
              logging.warning("Orphan instance '%s' found on node %s",
3969
                              inst, name)
3970
        # else no instance is alive
3971
    else:
3972
      live_data = {}
3973

    
3974
    if query.IQ_DISKUSAGE in self.requested_data:
3975
      disk_usage = dict((inst.name,
3976
                         _ComputeDiskSize(inst.disk_template,
3977
                                          [{"size": disk.size}
3978
                                           for disk in inst.disks]))
3979
                        for inst in instance_list)
3980
    else:
3981
      disk_usage = None
3982

    
3983
    if query.IQ_CONSOLE in self.requested_data:
3984
      consinfo = {}
3985
      for inst in instance_list:
3986
        if inst.name in live_data:
3987
          # Instance is running
3988
          consinfo[inst.name] = _GetInstanceConsole(cluster, inst)
3989
        else:
3990
          consinfo[inst.name] = None
3991
      assert set(consinfo.keys()) == set(instance_names)
3992
    else:
3993
      consinfo = None
3994

    
3995
    return query.InstanceQueryData(instance_list, lu.cfg.GetClusterInfo(),
3996
                                   disk_usage, offline_nodes, bad_nodes,
3997
                                   live_data, wrongnode_inst, consinfo)
3998

    
3999

    
4000
class LUQuery(NoHooksLU):
4001
  """Query for resources/items of a certain kind.
4002

4003
  """
4004
  # pylint: disable-msg=W0142
4005
  REQ_BGL = False
4006

    
4007
  def CheckArguments(self):
4008
    qcls = _GetQueryImplementation(self.op.what)
4009
    names = qlang.ReadSimpleFilter("name", self.op.filter)
4010

    
4011
    self.impl = qcls(names, self.op.fields, False)
4012

    
4013
  def ExpandNames(self):
4014
    self.impl.ExpandNames(self)
4015

    
4016
  def DeclareLocks(self, level):
4017
    self.impl.DeclareLocks(self, level)
4018

    
4019
  def Exec(self, feedback_fn):
4020
    return self.impl.NewStyleQuery(self)
4021

    
4022

    
4023
class LUQueryFields(NoHooksLU):
4024
  """Query for resources/items of a certain kind.
4025

4026
  """
4027
  # pylint: disable-msg=W0142
4028
  REQ_BGL = False
4029

    
4030
  def CheckArguments(self):
4031
    self.qcls = _GetQueryImplementation(self.op.what)
4032

    
4033
  def ExpandNames(self):
4034
    self.needed_locks = {}
4035

    
4036
  def Exec(self, feedback_fn):
4037
    return self.qcls.FieldsQuery(self.op.fields)
4038

    
4039

    
4040
class LUNodeModifyStorage(NoHooksLU):
4041
  """Logical unit for modifying a storage volume on a node.
4042

4043
  """
4044
  REQ_BGL = False
4045

    
4046
  def CheckArguments(self):
4047
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4048

    
4049
    storage_type = self.op.storage_type
4050

    
4051
    try:
4052
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
4053
    except KeyError:
4054
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
4055
                                 " modified" % storage_type,
4056
                                 errors.ECODE_INVAL)
4057

    
4058
    diff = set(self.op.changes.keys()) - modifiable
4059
    if diff:
4060
      raise errors.OpPrereqError("The following fields can not be modified for"
4061
                                 " storage units of type '%s': %r" %
4062
                                 (storage_type, list(diff)),
4063
                                 errors.ECODE_INVAL)
4064

    
4065
  def ExpandNames(self):
4066
    self.needed_locks = {
4067
      locking.LEVEL_NODE: self.op.node_name,
4068
      }
4069

    
4070
  def Exec(self, feedback_fn):
4071
    """Computes the list of nodes and their attributes.
4072

4073
    """
4074
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4075
    result = self.rpc.call_storage_modify(self.op.node_name,
4076
                                          self.op.storage_type, st_args,
4077
                                          self.op.name, self.op.changes)
4078
    result.Raise("Failed to modify storage unit '%s' on %s" %
4079
                 (self.op.name, self.op.node_name))
4080

    
4081

    
4082
class LUNodeAdd(LogicalUnit):
4083
  """Logical unit for adding node to the cluster.
4084

4085
  """
4086
  HPATH = "node-add"
4087
  HTYPE = constants.HTYPE_NODE
4088
  _NFLAGS = ["master_capable", "vm_capable"]
4089

    
4090
  def CheckArguments(self):
4091
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
4092
    # validate/normalize the node name
4093
    self.hostname = netutils.GetHostname(name=self.op.node_name,
4094
                                         family=self.primary_ip_family)
4095
    self.op.node_name = self.hostname.name
4096

    
4097
    if self.op.readd and self.op.node_name == self.cfg.GetMasterNode():
4098
      raise errors.OpPrereqError("Cannot readd the master node",
4099
                                 errors.ECODE_STATE)
4100

    
4101
    if self.op.readd and self.op.group:
4102
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
4103
                                 " being readded", errors.ECODE_INVAL)
4104

    
4105
  def BuildHooksEnv(self):
4106
    """Build hooks env.
4107

4108
    This will run on all nodes before, and on all nodes + the new node after.
4109

4110
    """
4111
    env = {
4112
      "OP_TARGET": self.op.node_name,
4113
      "NODE_NAME": self.op.node_name,
4114
      "NODE_PIP": self.op.primary_ip,
4115
      "NODE_SIP": self.op.secondary_ip,
4116
      "MASTER_CAPABLE": str(self.op.master_capable),
4117
      "VM_CAPABLE": str(self.op.vm_capable),
4118
      }
4119
    nodes_0 = self.cfg.GetNodeList()
4120
    nodes_1 = nodes_0 + [self.op.node_name, ]
4121
    return env, nodes_0, nodes_1
4122

    
4123
  def CheckPrereq(self):
4124
    """Check prerequisites.
4125

4126
    This checks:
4127
     - the new node is not already in the config
4128
     - it is resolvable
4129
     - its parameters (single/dual homed) matches the cluster
4130

4131
    Any errors are signaled by raising errors.OpPrereqError.
4132

4133
    """
4134
    cfg = self.cfg
4135
    hostname = self.hostname
4136
    node = hostname.name
4137
    primary_ip = self.op.primary_ip = hostname.ip
4138
    if self.op.secondary_ip is None:
4139
      if self.primary_ip_family == netutils.IP6Address.family:
4140
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
4141
                                   " IPv4 address must be given as secondary",
4142
                                   errors.ECODE_INVAL)
4143
      self.op.secondary_ip = primary_ip
4144

    
4145
    secondary_ip = self.op.secondary_ip
4146
    if not netutils.IP4Address.IsValid(secondary_ip):
4147
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4148
                                 " address" % secondary_ip, errors.ECODE_INVAL)
4149

    
4150
    node_list = cfg.GetNodeList()
4151
    if not self.op.readd and node in node_list:
4152
      raise errors.OpPrereqError("Node %s is already in the configuration" %
4153
                                 node, errors.ECODE_EXISTS)
4154
    elif self.op.readd and node not in node_list:
4155
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
4156
                                 errors.ECODE_NOENT)
4157

    
4158
    self.changed_primary_ip = False
4159

    
4160
    for existing_node_name in node_list:
4161
      existing_node = cfg.GetNodeInfo(existing_node_name)
4162

    
4163
      if self.op.readd and node == existing_node_name:
4164
        if existing_node.secondary_ip != secondary_ip:
4165
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
4166
                                     " address configuration as before",
4167
                                     errors.ECODE_INVAL)
4168
        if existing_node.primary_ip != primary_ip:
4169
          self.changed_primary_ip = True
4170

    
4171
        continue
4172

    
4173
      if (existing_node.primary_ip == primary_ip or
4174
          existing_node.secondary_ip == primary_ip or
4175
          existing_node.primary_ip == secondary_ip or
4176
          existing_node.secondary_ip == secondary_ip):
4177
        raise errors.OpPrereqError("New node ip address(es) conflict with"
4178
                                   " existing node %s" % existing_node.name,
4179
                                   errors.ECODE_NOTUNIQUE)
4180

    
4181
    # After this 'if' block, None is no longer a valid value for the
4182
    # _capable op attributes
4183
    if self.op.readd:
4184
      old_node = self.cfg.GetNodeInfo(node)
4185
      assert old_node is not None, "Can't retrieve locked node %s" % node
4186
      for attr in self._NFLAGS:
4187
        if getattr(self.op, attr) is None:
4188
          setattr(self.op, attr, getattr(old_node, attr))
4189
    else:
4190
      for attr in self._NFLAGS:
4191
        if getattr(self.op, attr) is None:
4192
          setattr(self.op, attr, True)
4193

    
4194
    if self.op.readd and not self.op.vm_capable:
4195
      pri, sec = cfg.GetNodeInstances(node)
4196
      if pri or sec:
4197
        raise errors.OpPrereqError("Node %s being re-added with vm_capable"
4198
                                   " flag set to false, but it already holds"
4199
                                   " instances" % node,
4200
                                   errors.ECODE_STATE)
4201

    
4202
    # check that the type of the node (single versus dual homed) is the
4203
    # same as for the master
4204
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
4205
    master_singlehomed = myself.secondary_ip == myself.primary_ip
4206
    newbie_singlehomed = secondary_ip == primary_ip
4207
    if master_singlehomed != newbie_singlehomed:
4208
      if master_singlehomed:
4209
        raise errors.OpPrereqError("The master has no secondary ip but the"
4210
                                   " new node has one",
4211
                                   errors.ECODE_INVAL)
4212
      else:
4213
        raise errors.OpPrereqError("The master has a secondary ip but the"
4214
                                   " new node doesn't have one",
4215
                                   errors.ECODE_INVAL)
4216

    
4217
    # checks reachability
4218
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
4219
      raise errors.OpPrereqError("Node not reachable by ping",
4220
                                 errors.ECODE_ENVIRON)
4221

    
4222
    if not newbie_singlehomed:
4223
      # check reachability from my secondary ip to newbie's secondary ip
4224
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
4225
                           source=myself.secondary_ip):
4226
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4227
                                   " based ping to node daemon port",
4228
                                   errors.ECODE_ENVIRON)
4229

    
4230
    if self.op.readd:
4231
      exceptions = [node]
4232
    else:
4233
      exceptions = []
4234

    
4235
    if self.op.master_capable:
4236
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
4237
    else:
4238
      self.master_candidate = False
4239

    
4240
    if self.op.readd:
4241
      self.new_node = old_node
4242
    else:
4243
      node_group = cfg.LookupNodeGroup(self.op.group)
4244
      self.new_node = objects.Node(name=node,
4245
                                   primary_ip=primary_ip,
4246
                                   secondary_ip=secondary_ip,
4247
                                   master_candidate=self.master_candidate,
4248
                                   offline=False, drained=False,
4249
                                   group=node_group)
4250

    
4251
    if self.op.ndparams:
4252
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
4253

    
4254
  def Exec(self, feedback_fn):
4255
    """Adds the new node to the cluster.
4256

4257
    """
4258
    new_node = self.new_node
4259
    node = new_node.name
4260

    
4261
    # We adding a new node so we assume it's powered
4262
    new_node.powered = True
4263

    
4264
    # for re-adds, reset the offline/drained/master-candidate flags;
4265
    # we need to reset here, otherwise offline would prevent RPC calls
4266
    # later in the procedure; this also means that if the re-add
4267
    # fails, we are left with a non-offlined, broken node
4268
    if self.op.readd:
4269
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
4270
      self.LogInfo("Readding a node, the offline/drained flags were reset")
4271
      # if we demote the node, we do cleanup later in the procedure
4272
      new_node.master_candidate = self.master_candidate
4273
      if self.changed_primary_ip:
4274
        new_node.primary_ip = self.op.primary_ip
4275

    
4276
    # copy the master/vm_capable flags
4277
    for attr in self._NFLAGS:
4278
      setattr(new_node, attr, getattr(self.op, attr))
4279

    
4280
    # notify the user about any possible mc promotion
4281
    if new_node.master_candidate:
4282
      self.LogInfo("Node will be a master candidate")
4283

    
4284
    if self.op.ndparams:
4285
      new_node.ndparams = self.op.ndparams
4286
    else:
4287
      new_node.ndparams = {}
4288

    
4289
    # check connectivity
4290
    result = self.rpc.call_version([node])[node]
4291
    result.Raise("Can't get version information from node %s" % node)
4292
    if constants.PROTOCOL_VERSION == result.payload:
4293
      logging.info("Communication to node %s fine, sw version %s match",
4294
                   node, result.payload)
4295
    else:
4296
      raise errors.OpExecError("Version mismatch master version %s,"
4297
                               " node version %s" %
4298
                               (constants.PROTOCOL_VERSION, result.payload))
4299

    
4300
    # Add node to our /etc/hosts, and add key to known_hosts
4301
    if self.cfg.GetClusterInfo().modify_etc_hosts:
4302
      master_node = self.cfg.GetMasterNode()
4303
      result = self.rpc.call_etc_hosts_modify(master_node,
4304
                                              constants.ETC_HOSTS_ADD,
4305
                                              self.hostname.name,
4306
                                              self.hostname.ip)
4307
      result.Raise("Can't update hosts file with new host data")
4308

    
4309
    if new_node.secondary_ip != new_node.primary_ip:
4310
      _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
4311
                               False)
4312

    
4313
    node_verify_list = [self.cfg.GetMasterNode()]
4314
    node_verify_param = {
4315
      constants.NV_NODELIST: [node],
4316
      # TODO: do a node-net-test as well?
4317
    }
4318

    
4319
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
4320
                                       self.cfg.GetClusterName())
4321
    for verifier in node_verify_list:
4322
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
4323
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
4324
      if nl_payload:
4325
        for failed in nl_payload:
4326
          feedback_fn("ssh/hostname verification failed"
4327
                      " (checking from %s): %s" %
4328
                      (verifier, nl_payload[failed]))
4329
        raise errors.OpExecError("ssh/hostname verification failed")
4330

    
4331
    if self.op.readd:
4332
      _RedistributeAncillaryFiles(self)
4333
      self.context.ReaddNode(new_node)
4334
      # make sure we redistribute the config
4335
      self.cfg.Update(new_node, feedback_fn)
4336
      # and make sure the new node will not have old files around
4337
      if not new_node.master_candidate:
4338
        result = self.rpc.call_node_demote_from_mc(new_node.name)
4339
        msg = result.fail_msg
4340
        if msg:
4341
          self.LogWarning("Node failed to demote itself from master"
4342
                          " candidate status: %s" % msg)
4343
    else:
4344
      _RedistributeAncillaryFiles(self, additional_nodes=[node],
4345
                                  additional_vm=self.op.vm_capable)
4346
      self.context.AddNode(new_node, self.proc.GetECId())
4347

    
4348

    
4349
class LUNodeSetParams(LogicalUnit):
4350
  """Modifies the parameters of a node.
4351

4352
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
4353
      to the node role (as _ROLE_*)
4354
  @cvar _R2F: a dictionary from node role to tuples of flags
4355
  @cvar _FLAGS: a list of attribute names corresponding to the flags
4356

4357
  """
4358
  HPATH = "node-modify"
4359
  HTYPE = constants.HTYPE_NODE
4360
  REQ_BGL = False
4361
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
4362
  _F2R = {
4363
    (True, False, False): _ROLE_CANDIDATE,
4364
    (False, True, False): _ROLE_DRAINED,
4365
    (False, False, True): _ROLE_OFFLINE,
4366
    (False, False, False): _ROLE_REGULAR,
4367
    }
4368
  _R2F = dict((v, k) for k, v in _F2R.items())
4369
  _FLAGS = ["master_candidate", "drained", "offline"]
4370

    
4371
  def CheckArguments(self):
4372
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4373
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
4374
                self.op.master_capable, self.op.vm_capable,
4375
                self.op.secondary_ip, self.op.ndparams]
4376
    if all_mods.count(None) == len(all_mods):
4377
      raise errors.OpPrereqError("Please pass at least one modification",
4378
                                 errors.ECODE_INVAL)
4379
    if all_mods.count(True) > 1:
4380
      raise errors.OpPrereqError("Can't set the node into more than one"
4381
                                 " state at the same time",
4382
                                 errors.ECODE_INVAL)
4383

    
4384
    # Boolean value that tells us whether we might be demoting from MC
4385
    self.might_demote = (self.op.master_candidate == False or
4386
                         self.op.offline == True or
4387
                         self.op.drained == True or
4388
                         self.op.master_capable == False)
4389

    
4390
    if self.op.secondary_ip:
4391
      if not netutils.IP4Address.IsValid(self.op.secondary_ip):
4392
        raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4393
                                   " address" % self.op.secondary_ip,
4394
                                   errors.ECODE_INVAL)
4395

    
4396
    self.lock_all = self.op.auto_promote and self.might_demote
4397
    self.lock_instances = self.op.secondary_ip is not None
4398

    
4399
  def ExpandNames(self):
4400
    if self.lock_all:
4401
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
4402
    else:
4403
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
4404

    
4405
    if self.lock_instances:
4406
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4407

    
4408
  def DeclareLocks(self, level):
4409
    # If we have locked all instances, before waiting to lock nodes, release
4410
    # all the ones living on nodes unrelated to the current operation.
4411
    if level == locking.LEVEL_NODE and self.lock_instances:
4412
      instances_release = []
4413
      instances_keep = []
4414
      self.affected_instances = []
4415
      if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4416
        for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
4417
          instance = self.context.cfg.GetInstanceInfo(instance_name)
4418
          i_mirrored = instance.disk_template in constants.DTS_INT_MIRROR
4419
          if i_mirrored and self.op.node_name in instance.all_nodes:
4420
            instances_keep.append(instance_name)
4421
            self.affected_instances.append(instance)
4422
          else:
4423
            instances_release.append(instance_name)
4424
        if instances_release:
4425
          self.context.glm.release(locking.LEVEL_INSTANCE, instances_release)
4426
          self.acquired_locks[locking.LEVEL_INSTANCE] = instances_keep
4427

    
4428
  def BuildHooksEnv(self):
4429
    """Build hooks env.
4430

4431
    This runs on the master node.
4432

4433
    """
4434
    env = {
4435
      "OP_TARGET": self.op.node_name,
4436
      "MASTER_CANDIDATE": str(self.op.master_candidate),
4437
      "OFFLINE": str(self.op.offline),
4438
      "DRAINED": str(self.op.drained),
4439
      "MASTER_CAPABLE": str(self.op.master_capable),
4440
      "VM_CAPABLE": str(self.op.vm_capable),
4441
      }
4442
    nl = [self.cfg.GetMasterNode(),
4443
          self.op.node_name]
4444
    return env, nl, nl
4445

    
4446
  def CheckPrereq(self):
4447
    """Check prerequisites.
4448

4449
    This only checks the instance list against the existing names.
4450

4451
    """
4452
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
4453

    
4454
    if (self.op.master_candidate is not None or
4455
        self.op.drained is not None or
4456
        self.op.offline is not None):
4457
      # we can't change the master's node flags
4458
      if self.op.node_name == self.cfg.GetMasterNode():
4459
        raise errors.OpPrereqError("The master role can be changed"
4460
                                   " only via master-failover",
4461
                                   errors.ECODE_INVAL)
4462

    
4463
    if self.op.master_candidate and not node.master_capable:
4464
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4465
                                 " it a master candidate" % node.name,
4466
                                 errors.ECODE_STATE)
4467

    
4468
    if self.op.vm_capable == False:
4469
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
4470
      if ipri or isec:
4471
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
4472
                                   " the vm_capable flag" % node.name,
4473
                                   errors.ECODE_STATE)
4474

    
4475
    if node.master_candidate and self.might_demote and not self.lock_all:
4476
      assert not self.op.auto_promote, "auto_promote set but lock_all not"
4477
      # check if after removing the current node, we're missing master
4478
      # candidates
4479
      (mc_remaining, mc_should, _) = \
4480
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
4481
      if mc_remaining < mc_should:
4482
        raise errors.OpPrereqError("Not enough master candidates, please"
4483
                                   " pass auto promote option to allow"
4484
                                   " promotion", errors.ECODE_STATE)
4485

    
4486
    self.old_flags = old_flags = (node.master_candidate,
4487
                                  node.drained, node.offline)
4488
    assert old_flags in self._F2R, "Un-handled old flags  %s" % str(old_flags)
4489
    self.old_role = old_role = self._F2R[old_flags]
4490

    
4491
    # Check for ineffective changes
4492
    for attr in self._FLAGS:
4493
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
4494
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
4495
        setattr(self.op, attr, None)
4496

    
4497
    # Past this point, any flag change to False means a transition
4498
    # away from the respective state, as only real changes are kept
4499

    
4500
    # TODO: We might query the real power state if it supports OOB
4501
    if _SupportsOob(self.cfg, node):
4502
      if self.op.offline is False and not (node.powered or
4503
                                           self.op.powered == True):
4504
        raise errors.OpPrereqError(("Please power on node %s first before you"
4505
                                    " can reset offline state") %
4506
                                   self.op.node_name)
4507
    elif self.op.powered is not None:
4508
      raise errors.OpPrereqError(("Unable to change powered state for node %s"
4509
                                  " which does not support out-of-band"
4510
                                  " handling") % self.op.node_name)
4511

    
4512
    # If we're being deofflined/drained, we'll MC ourself if needed
4513
    if (self.op.drained == False or self.op.offline == False or
4514
        (self.op.master_capable and not node.master_capable)):
4515
      if _DecideSelfPromotion(self):
4516
        self.op.master_candidate = True
4517
        self.LogInfo("Auto-promoting node to master candidate")
4518

    
4519
    # If we're no longer master capable, we'll demote ourselves from MC
4520
    if self.op.master_capable == False and node.master_candidate:
4521
      self.LogInfo("Demoting from master candidate")
4522
      self.op.master_candidate = False
4523

    
4524
    # Compute new role
4525
    assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
4526
    if self.op.master_candidate:
4527
      new_role = self._ROLE_CANDIDATE
4528
    elif self.op.drained:
4529
      new_role = self._ROLE_DRAINED
4530
    elif self.op.offline:
4531
      new_role = self._ROLE_OFFLINE
4532
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
4533
      # False is still in new flags, which means we're un-setting (the
4534
      # only) True flag
4535
      new_role = self._ROLE_REGULAR
4536
    else: # no new flags, nothing, keep old role
4537
      new_role = old_role
4538

    
4539
    self.new_role = new_role
4540

    
4541
    if old_role == self._ROLE_OFFLINE and new_role != old_role:
4542
      # Trying to transition out of offline status
4543
      result = self.rpc.call_version([node.name])[node.name]
4544
      if result.fail_msg:
4545
        raise errors.OpPrereqError("Node %s is being de-offlined but fails"
4546
                                   " to report its version: %s" %
4547
                                   (node.name, result.fail_msg),
4548
                                   errors.ECODE_STATE)
4549
      else:
4550
        self.LogWarning("Transitioning node from offline to online state"
4551
                        " without using re-add. Please make sure the node"
4552
                        " is healthy!")
4553

    
4554
    if self.op.secondary_ip:
4555
      # Ok even without locking, because this can't be changed by any LU
4556
      master = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
4557
      master_singlehomed = master.secondary_ip == master.primary_ip
4558
      if master_singlehomed and self.op.secondary_ip:
4559
        raise errors.OpPrereqError("Cannot change the secondary ip on a single"
4560
                                   " homed cluster", errors.ECODE_INVAL)
4561

    
4562
      if node.offline:
4563
        if self.affected_instances:
4564
          raise errors.OpPrereqError("Cannot change secondary ip: offline"
4565
                                     " node has instances (%s) configured"
4566
                                     " to use it" % self.affected_instances)
4567
      else:
4568
        # On online nodes, check that no instances are running, and that
4569
        # the node has the new ip and we can reach it.
4570
        for instance in self.affected_instances:
4571
          _CheckInstanceDown(self, instance, "cannot change secondary ip")
4572

    
4573
        _CheckNodeHasSecondaryIP(self, node.name, self.op.secondary_ip, True)
4574
        if master.name != node.name:
4575
          # check reachability from master secondary ip to new secondary ip
4576
          if not netutils.TcpPing(self.op.secondary_ip,
4577
                                  constants.DEFAULT_NODED_PORT,
4578
                                  source=master.secondary_ip):
4579
            raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4580
                                       " based ping to node daemon port",
4581
                                       errors.ECODE_ENVIRON)
4582

    
4583
    if self.op.ndparams:
4584
      new_ndparams = _GetUpdatedParams(self.node.ndparams, self.op.ndparams)
4585
      utils.ForceDictType(new_ndparams, constants.NDS_PARAMETER_TYPES)
4586
      self.new_ndparams = new_ndparams
4587

    
4588
  def Exec(self, feedback_fn):
4589
    """Modifies a node.
4590

4591
    """
4592
    node = self.node
4593
    old_role = self.old_role
4594
    new_role = self.new_role
4595

    
4596
    result = []
4597

    
4598
    if self.op.ndparams:
4599
      node.ndparams = self.new_ndparams
4600

    
4601
    if self.op.powered is not None:
4602
      node.powered = self.op.powered
4603

    
4604
    for attr in ["master_capable", "vm_capable"]:
4605
      val = getattr(self.op, attr)
4606
      if val is not None:
4607
        setattr(node, attr, val)
4608
        result.append((attr, str(val)))
4609

    
4610
    if new_role != old_role:
4611
      # Tell the node to demote itself, if no longer MC and not offline
4612
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
4613
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
4614
        if msg:
4615
          self.LogWarning("Node failed to demote itself: %s", msg)
4616

    
4617
      new_flags = self._R2F[new_role]
4618
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
4619
        if of != nf:
4620
          result.append((desc, str(nf)))
4621
      (node.master_candidate, node.drained, node.offline) = new_flags
4622

    
4623
      # we locked all nodes, we adjust the CP before updating this node
4624
      if self.lock_all:
4625
        _AdjustCandidatePool(self, [node.name])
4626

    
4627
    if self.op.secondary_ip:
4628
      node.secondary_ip = self.op.secondary_ip
4629
      result.append(("secondary_ip", self.op.secondary_ip))
4630

    
4631
    # this will trigger configuration file update, if needed
4632
    self.cfg.Update(node, feedback_fn)
4633

    
4634
    # this will trigger job queue propagation or cleanup if the mc
4635
    # flag changed
4636
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
4637
      self.context.ReaddNode(node)
4638

    
4639
    return result
4640

    
4641

    
4642
class LUNodePowercycle(NoHooksLU):
4643
  """Powercycles a node.
4644

4645
  """
4646
  REQ_BGL = False
4647

    
4648
  def CheckArguments(self):
4649
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4650
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4651
      raise errors.OpPrereqError("The node is the master and the force"
4652
                                 " parameter was not set",
4653
                                 errors.ECODE_INVAL)
4654

    
4655
  def ExpandNames(self):
4656
    """Locking for PowercycleNode.
4657

4658
    This is a last-resort option and shouldn't block on other
4659
    jobs. Therefore, we grab no locks.
4660

4661
    """
4662
    self.needed_locks = {}
4663

    
4664
  def Exec(self, feedback_fn):
4665
    """Reboots a node.
4666

4667
    """
4668
    result = self.rpc.call_node_powercycle(self.op.node_name,
4669
                                           self.cfg.GetHypervisorType())
4670
    result.Raise("Failed to schedule the reboot")
4671
    return result.payload
4672

    
4673

    
4674
class LUClusterQuery(NoHooksLU):
4675
  """Query cluster configuration.
4676

4677
  """
4678
  REQ_BGL = False
4679

    
4680
  def ExpandNames(self):
4681
    self.needed_locks = {}
4682

    
4683
  def Exec(self, feedback_fn):
4684
    """Return cluster config.
4685

4686
    """
4687
    cluster = self.cfg.GetClusterInfo()
4688
    os_hvp = {}
4689

    
4690
    # Filter just for enabled hypervisors
4691
    for os_name, hv_dict in cluster.os_hvp.items():
4692
      os_hvp[os_name] = {}
4693
      for hv_name, hv_params in hv_dict.items():
4694
        if hv_name in cluster.enabled_hypervisors:
4695
          os_hvp[os_name][hv_name] = hv_params
4696

    
4697
    # Convert ip_family to ip_version
4698
    primary_ip_version = constants.IP4_VERSION
4699
    if cluster.primary_ip_family == netutils.IP6Address.family:
4700
      primary_ip_version = constants.IP6_VERSION
4701

    
4702
    result = {
4703
      "software_version": constants.RELEASE_VERSION,
4704
      "protocol_version": constants.PROTOCOL_VERSION,
4705
      "config_version": constants.CONFIG_VERSION,
4706
      "os_api_version": max(constants.OS_API_VERSIONS),
4707
      "export_version": constants.EXPORT_VERSION,
4708
      "architecture": (platform.architecture()[0], platform.machine()),
4709
      "name": cluster.cluster_name,
4710
      "master": cluster.master_node,
4711
      "default_hypervisor": cluster.enabled_hypervisors[0],
4712
      "enabled_hypervisors": cluster.enabled_hypervisors,
4713
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4714
                        for hypervisor_name in cluster.enabled_hypervisors]),
4715
      "os_hvp": os_hvp,
4716
      "beparams": cluster.beparams,
4717
      "osparams": cluster.osparams,
4718
      "nicparams": cluster.nicparams,
4719
      "ndparams": cluster.ndparams,
4720
      "candidate_pool_size": cluster.candidate_pool_size,
4721
      "master_netdev": cluster.master_netdev,
4722
      "volume_group_name": cluster.volume_group_name,
4723
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
4724
      "file_storage_dir": cluster.file_storage_dir,
4725
      "shared_file_storage_dir": cluster.shared_file_storage_dir,
4726
      "maintain_node_health": cluster.maintain_node_health,
4727
      "ctime": cluster.ctime,
4728
      "mtime": cluster.mtime,
4729
      "uuid": cluster.uuid,
4730
      "tags": list(cluster.GetTags()),
4731
      "uid_pool": cluster.uid_pool,
4732
      "default_iallocator": cluster.default_iallocator,
4733
      "reserved_lvs": cluster.reserved_lvs,
4734
      "primary_ip_version": primary_ip_version,
4735
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
4736
      "hidden_os": cluster.hidden_os,
4737
      "blacklisted_os": cluster.blacklisted_os,
4738
      }
4739

    
4740
    return result
4741

    
4742

    
4743
class LUClusterConfigQuery(NoHooksLU):
4744
  """Return configuration values.
4745

4746
  """
4747
  REQ_BGL = False
4748
  _FIELDS_DYNAMIC = utils.FieldSet()
4749
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4750
                                  "watcher_pause", "volume_group_name")
4751

    
4752
  def CheckArguments(self):
4753
    _CheckOutputFields(static=self._FIELDS_STATIC,
4754
                       dynamic=self._FIELDS_DYNAMIC,
4755
                       selected=self.op.output_fields)
4756

    
4757
  def ExpandNames(self):
4758
    self.needed_locks = {}
4759

    
4760
  def Exec(self, feedback_fn):
4761
    """Dump a representation of the cluster config to the standard output.
4762

4763
    """
4764
    values = []
4765
    for field in self.op.output_fields:
4766
      if field == "cluster_name":
4767
        entry = self.cfg.GetClusterName()
4768
      elif field == "master_node":
4769
        entry = self.cfg.GetMasterNode()
4770
      elif field == "drain_flag":
4771
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4772
      elif field == "watcher_pause":
4773
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4774
      elif field == "volume_group_name":
4775
        entry = self.cfg.GetVGName()
4776
      else:
4777
        raise errors.ParameterError(field)
4778
      values.append(entry)
4779
    return values
4780

    
4781

    
4782
class LUInstanceActivateDisks(NoHooksLU):
4783
  """Bring up an instance's disks.
4784

4785
  """
4786
  REQ_BGL = False
4787

    
4788
  def ExpandNames(self):
4789
    self._ExpandAndLockInstance()
4790
    self.needed_locks[locking.LEVEL_NODE] = []
4791
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4792

    
4793
  def DeclareLocks(self, level):
4794
    if level == locking.LEVEL_NODE:
4795
      self._LockInstancesNodes()
4796

    
4797
  def CheckPrereq(self):
4798
    """Check prerequisites.
4799

4800
    This checks that the instance is in the cluster.
4801

4802
    """
4803
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4804
    assert self.instance is not None, \
4805
      "Cannot retrieve locked instance %s" % self.op.instance_name
4806
    _CheckNodeOnline(self, self.instance.primary_node)
4807

    
4808
  def Exec(self, feedback_fn):
4809
    """Activate the disks.
4810

4811
    """
4812
    disks_ok, disks_info = \
4813
              _AssembleInstanceDisks(self, self.instance,
4814
                                     ignore_size=self.op.ignore_size)
4815
    if not disks_ok:
4816
      raise errors.OpExecError("Cannot activate block devices")
4817

    
4818
    return disks_info
4819

    
4820

    
4821
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4822
                           ignore_size=False):
4823
  """Prepare the block devices for an instance.
4824

4825
  This sets up the block devices on all nodes.
4826

4827
  @type lu: L{LogicalUnit}
4828
  @param lu: the logical unit on whose behalf we execute
4829
  @type instance: L{objects.Instance}
4830
  @param instance: the instance for whose disks we assemble
4831
  @type disks: list of L{objects.Disk} or None
4832
  @param disks: which disks to assemble (or all, if None)
4833
  @type ignore_secondaries: boolean
4834
  @param ignore_secondaries: if true, errors on secondary nodes
4835
      won't result in an error return from the function
4836
  @type ignore_size: boolean
4837
  @param ignore_size: if true, the current known size of the disk
4838
      will not be used during the disk activation, useful for cases
4839
      when the size is wrong
4840
  @return: False if the operation failed, otherwise a list of
4841
      (host, instance_visible_name, node_visible_name)
4842
      with the mapping from node devices to instance devices
4843

4844
  """
4845
  device_info = []
4846
  disks_ok = True
4847
  iname = instance.name
4848
  disks = _ExpandCheckDisks(instance, disks)
4849

    
4850
  # With the two passes mechanism we try to reduce the window of
4851
  # opportunity for the race condition of switching DRBD to primary
4852
  # before handshaking occured, but we do not eliminate it
4853

    
4854
  # The proper fix would be to wait (with some limits) until the
4855
  # connection has been made and drbd transitions from WFConnection
4856
  # into any other network-connected state (Connected, SyncTarget,
4857
  # SyncSource, etc.)
4858

    
4859
  # 1st pass, assemble on all nodes in secondary mode
4860
  for idx, inst_disk in enumerate(disks):
4861
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4862
      if ignore_size:
4863
        node_disk = node_disk.Copy()
4864
        node_disk.UnsetSize()
4865
      lu.cfg.SetDiskID(node_disk, node)
4866
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False, idx)
4867
      msg = result.fail_msg
4868
      if msg:
4869
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4870
                           " (is_primary=False, pass=1): %s",
4871
                           inst_disk.iv_name, node, msg)
4872
        if not ignore_secondaries:
4873
          disks_ok = False
4874

    
4875
  # FIXME: race condition on drbd migration to primary
4876

    
4877
  # 2nd pass, do only the primary node
4878
  for idx, inst_disk in enumerate(disks):
4879
    dev_path = None
4880

    
4881
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4882
      if node != instance.primary_node:
4883
        continue
4884
      if ignore_size:
4885
        node_disk = node_disk.Copy()
4886
        node_disk.UnsetSize()
4887
      lu.cfg.SetDiskID(node_disk, node)
4888
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True, idx)
4889
      msg = result.fail_msg
4890
      if msg:
4891
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4892
                           " (is_primary=True, pass=2): %s",
4893
                           inst_disk.iv_name, node, msg)
4894
        disks_ok = False
4895
      else:
4896
        dev_path = result.payload
4897

    
4898
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4899

    
4900
  # leave the disks configured for the primary node
4901
  # this is a workaround that would be fixed better by
4902
  # improving the logical/physical id handling
4903
  for disk in disks:
4904
    lu.cfg.SetDiskID(disk, instance.primary_node)
4905

    
4906
  return disks_ok, device_info
4907

    
4908

    
4909
def _StartInstanceDisks(lu, instance, force):
4910
  """Start the disks of an instance.
4911

4912
  """
4913
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4914
                                           ignore_secondaries=force)
4915
  if not disks_ok:
4916
    _ShutdownInstanceDisks(lu, instance)
4917
    if force is not None and not force:
4918
      lu.proc.LogWarning("", hint="If the message above refers to a"
4919
                         " secondary node,"
4920
                         " you can retry the operation using '--force'.")
4921
    raise errors.OpExecError("Disk consistency error")
4922

    
4923

    
4924
class LUInstanceDeactivateDisks(NoHooksLU):
4925
  """Shutdown an instance's disks.
4926

4927
  """
4928
  REQ_BGL = False
4929

    
4930
  def ExpandNames(self):
4931
    self._ExpandAndLockInstance()
4932
    self.needed_locks[locking.LEVEL_NODE] = []
4933
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4934

    
4935
  def DeclareLocks(self, level):
4936
    if level == locking.LEVEL_NODE:
4937
      self._LockInstancesNodes()
4938

    
4939
  def CheckPrereq(self):
4940
    """Check prerequisites.
4941

4942
    This checks that the instance is in the cluster.
4943

4944
    """
4945
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4946
    assert self.instance is not None, \
4947
      "Cannot retrieve locked instance %s" % self.op.instance_name
4948

    
4949
  def Exec(self, feedback_fn):
4950
    """Deactivate the disks
4951

4952
    """
4953
    instance = self.instance
4954
    if self.op.force:
4955
      _ShutdownInstanceDisks(self, instance)
4956
    else:
4957
      _SafeShutdownInstanceDisks(self, instance)
4958

    
4959

    
4960
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4961
  """Shutdown block devices of an instance.
4962

4963
  This function checks if an instance is running, before calling
4964
  _ShutdownInstanceDisks.
4965

4966
  """
4967
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4968
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4969

    
4970

    
4971
def _ExpandCheckDisks(instance, disks):
4972
  """Return the instance disks selected by the disks list
4973

4974
  @type disks: list of L{objects.Disk} or None
4975
  @param disks: selected disks
4976
  @rtype: list of L{objects.Disk}
4977
  @return: selected instance disks to act on
4978

4979
  """
4980
  if disks is None:
4981
    return instance.disks
4982
  else:
4983
    if not set(disks).issubset(instance.disks):
4984
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4985
                                   " target instance")
4986
    return disks
4987

    
4988

    
4989
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4990
  """Shutdown block devices of an instance.
4991

4992
  This does the shutdown on all nodes of the instance.
4993

4994
  If the ignore_primary is false, errors on the primary node are
4995
  ignored.
4996

4997
  """
4998
  all_result = True
4999
  disks = _ExpandCheckDisks(instance, disks)
5000

    
5001
  for disk in disks:
5002
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
5003
      lu.cfg.SetDiskID(top_disk, node)
5004
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
5005
      msg = result.fail_msg
5006
      if msg:
5007
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
5008
                      disk.iv_name, node, msg)
5009
        if ((node == instance.primary_node and not ignore_primary) or
5010
            (node != instance.primary_node and not result.offline)):
5011
          all_result = False
5012
  return all_result
5013

    
5014

    
5015
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
5016
  """Checks if a node has enough free memory.
5017

5018
  This function check if a given node has the needed amount of free
5019
  memory. In case the node has less memory or we cannot get the
5020
  information from the node, this function raise an OpPrereqError
5021
  exception.
5022

5023
  @type lu: C{LogicalUnit}
5024
  @param lu: a logical unit from which we get configuration data
5025
  @type node: C{str}
5026
  @param node: the node to check
5027
  @type reason: C{str}
5028
  @param reason: string to use in the error message
5029
  @type requested: C{int}
5030
  @param requested: the amount of memory in MiB to check for
5031
  @type hypervisor_name: C{str}
5032
  @param hypervisor_name: the hypervisor to ask for memory stats
5033
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
5034
      we cannot check the node
5035

5036
  """
5037
  nodeinfo = lu.rpc.call_node_info([node], None, hypervisor_name)
5038
  nodeinfo[node].Raise("Can't get data from node %s" % node,
5039
                       prereq=True, ecode=errors.ECODE_ENVIRON)
5040
  free_mem = nodeinfo[node].payload.get('memory_free', None)
5041
  if not isinstance(free_mem, int):
5042
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
5043
                               " was '%s'" % (node, free_mem),
5044
                               errors.ECODE_ENVIRON)
5045
  if requested > free_mem:
5046
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
5047
                               " needed %s MiB, available %s MiB" %
5048
                               (node, reason, requested, free_mem),
5049
                               errors.ECODE_NORES)
5050

    
5051

    
5052
def _CheckNodesFreeDiskPerVG(lu, nodenames, req_sizes):
5053
  """Checks if nodes have enough free disk space in the all VGs.
5054

5055
  This function check if all given nodes have the needed amount of
5056
  free disk. In case any node has less disk or we cannot get the
5057
  information from the node, this function raise an OpPrereqError
5058
  exception.
5059

5060
  @type lu: C{LogicalUnit}
5061
  @param lu: a logical unit from which we get configuration data
5062
  @type nodenames: C{list}
5063
  @param nodenames: the list of node names to check
5064
  @type req_sizes: C{dict}
5065
  @param req_sizes: the hash of vg and corresponding amount of disk in
5066
      MiB to check for
5067
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5068
      or we cannot check the node
5069

5070
  """
5071
  for vg, req_size in req_sizes.items():
5072
    _CheckNodesFreeDiskOnVG(lu, nodenames, vg, req_size)
5073

    
5074

    
5075
def _CheckNodesFreeDiskOnVG(lu, nodenames, vg, requested):
5076
  """Checks if nodes have enough free disk space in the specified VG.
5077

5078
  This function check if all given nodes have the needed amount of
5079
  free disk. In case any node has less disk or we cannot get the
5080
  information from the node, this function raise an OpPrereqError
5081
  exception.
5082

5083
  @type lu: C{LogicalUnit}
5084
  @param lu: a logical unit from which we get configuration data
5085
  @type nodenames: C{list}
5086
  @param nodenames: the list of node names to check
5087
  @type vg: C{str}
5088
  @param vg: the volume group to check
5089
  @type requested: C{int}
5090
  @param requested: the amount of disk in MiB to check for
5091
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5092
      or we cannot check the node
5093

5094
  """
5095
  nodeinfo = lu.rpc.call_node_info(nodenames, vg, None)
5096
  for node in nodenames:
5097
    info = nodeinfo[node]
5098
    info.Raise("Cannot get current information from node %s" % node,
5099
               prereq=True, ecode=errors.ECODE_ENVIRON)
5100
    vg_free = info.payload.get("vg_free", None)
5101
    if not isinstance(vg_free, int):
5102
      raise errors.OpPrereqError("Can't compute free disk space on node"
5103
                                 " %s for vg %s, result was '%s'" %
5104
                                 (node, vg, vg_free), errors.ECODE_ENVIRON)
5105
    if requested > vg_free:
5106
      raise errors.OpPrereqError("Not enough disk space on target node %s"
5107
                                 " vg %s: required %d MiB, available %d MiB" %
5108
                                 (node, vg, requested, vg_free),
5109
                                 errors.ECODE_NORES)
5110

    
5111

    
5112
class LUInstanceStartup(LogicalUnit):
5113
  """Starts an instance.
5114

5115
  """
5116
  HPATH = "instance-start"
5117
  HTYPE = constants.HTYPE_INSTANCE
5118
  REQ_BGL = False
5119

    
5120
  def CheckArguments(self):
5121
    # extra beparams
5122
    if self.op.beparams:
5123
      # fill the beparams dict
5124
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5125

    
5126
  def ExpandNames(self):
5127
    self._ExpandAndLockInstance()
5128

    
5129
  def BuildHooksEnv(self):
5130
    """Build hooks env.
5131

5132
    This runs on master, primary and secondary nodes of the instance.
5133

5134
    """
5135
    env = {
5136
      "FORCE": self.op.force,
5137
      }
5138
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5139
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5140
    return env, nl, nl
5141

    
5142
  def CheckPrereq(self):
5143
    """Check prerequisites.
5144

5145
    This checks that the instance is in the cluster.
5146

5147
    """
5148
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5149
    assert self.instance is not None, \
5150
      "Cannot retrieve locked instance %s" % self.op.instance_name
5151

    
5152
    # extra hvparams
5153
    if self.op.hvparams:
5154
      # check hypervisor parameter syntax (locally)
5155
      cluster = self.cfg.GetClusterInfo()
5156
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5157
      filled_hvp = cluster.FillHV(instance)
5158
      filled_hvp.update(self.op.hvparams)
5159
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
5160
      hv_type.CheckParameterSyntax(filled_hvp)
5161
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
5162

    
5163
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
5164

    
5165
    if self.primary_offline and self.op.ignore_offline_nodes:
5166
      self.proc.LogWarning("Ignoring offline primary node")
5167

    
5168
      if self.op.hvparams or self.op.beparams:
5169
        self.proc.LogWarning("Overridden parameters are ignored")
5170
    else:
5171
      _CheckNodeOnline(self, instance.primary_node)
5172

    
5173
      bep = self.cfg.GetClusterInfo().FillBE(instance)
5174

    
5175
      # check bridges existence
5176
      _CheckInstanceBridgesExist(self, instance)
5177

    
5178
      remote_info = self.rpc.call_instance_info(instance.primary_node,
5179
                                                instance.name,
5180
                                                instance.hypervisor)
5181
      remote_info.Raise("Error checking node %s" % instance.primary_node,
5182
                        prereq=True, ecode=errors.ECODE_ENVIRON)
5183
      if not remote_info.payload: # not running already
5184
        _CheckNodeFreeMemory(self, instance.primary_node,
5185
                             "starting instance %s" % instance.name,
5186
                             bep[constants.BE_MEMORY], instance.hypervisor)
5187

    
5188
  def Exec(self, feedback_fn):
5189
    """Start the instance.
5190

5191
    """
5192
    instance = self.instance
5193
    force = self.op.force
5194

    
5195
    self.cfg.MarkInstanceUp(instance.name)
5196

    
5197
    if self.primary_offline:
5198
      assert self.op.ignore_offline_nodes
5199
      self.proc.LogInfo("Primary node offline, marked instance as started")
5200
    else:
5201
      node_current = instance.primary_node
5202

    
5203
      _StartInstanceDisks(self, instance, force)
5204

    
5205
      result = self.rpc.call_instance_start(node_current, instance,
5206
                                            self.op.hvparams, self.op.beparams)
5207
      msg = result.fail_msg
5208
      if msg:
5209
        _ShutdownInstanceDisks(self, instance)
5210
        raise errors.OpExecError("Could not start instance: %s" % msg)
5211

    
5212

    
5213
class LUInstanceReboot(LogicalUnit):
5214
  """Reboot an instance.
5215

5216
  """
5217
  HPATH = "instance-reboot"
5218
  HTYPE = constants.HTYPE_INSTANCE
5219
  REQ_BGL = False
5220

    
5221
  def ExpandNames(self):
5222
    self._ExpandAndLockInstance()
5223

    
5224
  def BuildHooksEnv(self):
5225
    """Build hooks env.
5226

5227
    This runs on master, primary and secondary nodes of the instance.
5228

5229
    """
5230
    env = {
5231
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
5232
      "REBOOT_TYPE": self.op.reboot_type,
5233
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5234
      }
5235
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5236
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5237
    return env, nl, nl
5238

    
5239
  def CheckPrereq(self):
5240
    """Check prerequisites.
5241

5242
    This checks that the instance is in the cluster.
5243

5244
    """
5245
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5246
    assert self.instance is not None, \
5247
      "Cannot retrieve locked instance %s" % self.op.instance_name
5248

    
5249
    _CheckNodeOnline(self, instance.primary_node)
5250

    
5251
    # check bridges existence
5252
    _CheckInstanceBridgesExist(self, instance)
5253

    
5254
  def Exec(self, feedback_fn):
5255
    """Reboot the instance.
5256

5257
    """
5258
    instance = self.instance
5259
    ignore_secondaries = self.op.ignore_secondaries
5260
    reboot_type = self.op.reboot_type
5261

    
5262
    node_current = instance.primary_node
5263

    
5264
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
5265
                       constants.INSTANCE_REBOOT_HARD]:
5266
      for disk in instance.disks:
5267
        self.cfg.SetDiskID(disk, node_current)
5268
      result = self.rpc.call_instance_reboot(node_current, instance,
5269
                                             reboot_type,
5270
                                             self.op.shutdown_timeout)
5271
      result.Raise("Could not reboot instance")
5272
    else:
5273
      result = self.rpc.call_instance_shutdown(node_current, instance,
5274
                                               self.op.shutdown_timeout)
5275
      result.Raise("Could not shutdown instance for full reboot")
5276
      _ShutdownInstanceDisks(self, instance)
5277
      _StartInstanceDisks(self, instance, ignore_secondaries)
5278
      result = self.rpc.call_instance_start(node_current, instance, None, None)
5279
      msg = result.fail_msg
5280
      if msg:
5281
        _ShutdownInstanceDisks(self, instance)
5282
        raise errors.OpExecError("Could not start instance for"
5283
                                 " full reboot: %s" % msg)
5284

    
5285
    self.cfg.MarkInstanceUp(instance.name)
5286

    
5287

    
5288
class LUInstanceShutdown(LogicalUnit):
5289
  """Shutdown an instance.
5290

5291
  """
5292
  HPATH = "instance-stop"
5293
  HTYPE = constants.HTYPE_INSTANCE
5294
  REQ_BGL = False
5295

    
5296
  def ExpandNames(self):
5297
    self._ExpandAndLockInstance()
5298

    
5299
  def BuildHooksEnv(self):
5300
    """Build hooks env.
5301

5302
    This runs on master, primary and secondary nodes of the instance.
5303

5304
    """
5305
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5306
    env["TIMEOUT"] = self.op.timeout
5307
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5308
    return env, nl, nl
5309

    
5310
  def CheckPrereq(self):
5311
    """Check prerequisites.
5312

5313
    This checks that the instance is in the cluster.
5314

5315
    """
5316
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5317
    assert self.instance is not None, \
5318
      "Cannot retrieve locked instance %s" % self.op.instance_name
5319

    
5320
    self.primary_offline = \
5321
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
5322

    
5323
    if self.primary_offline and self.op.ignore_offline_nodes:
5324
      self.proc.LogWarning("Ignoring offline primary node")
5325
    else:
5326
      _CheckNodeOnline(self, self.instance.primary_node)
5327

    
5328
  def Exec(self, feedback_fn):
5329
    """Shutdown the instance.
5330

5331
    """
5332
    instance = self.instance
5333
    node_current = instance.primary_node
5334
    timeout = self.op.timeout
5335

    
5336
    self.cfg.MarkInstanceDown(instance.name)
5337

    
5338
    if self.primary_offline:
5339
      assert self.op.ignore_offline_nodes
5340
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
5341
    else:
5342
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
5343
      msg = result.fail_msg
5344
      if msg:
5345
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
5346

    
5347
      _ShutdownInstanceDisks(self, instance)
5348

    
5349

    
5350
class LUInstanceReinstall(LogicalUnit):
5351
  """Reinstall an instance.
5352

5353
  """
5354
  HPATH = "instance-reinstall"
5355
  HTYPE = constants.HTYPE_INSTANCE
5356
  REQ_BGL = False
5357

    
5358
  def ExpandNames(self):
5359
    self._ExpandAndLockInstance()
5360

    
5361
  def BuildHooksEnv(self):
5362
    """Build hooks env.
5363

5364
    This runs on master, primary and secondary nodes of the instance.
5365

5366
    """
5367
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5368
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5369
    return env, nl, nl
5370

    
5371
  def CheckPrereq(self):
5372
    """Check prerequisites.
5373

5374
    This checks that the instance is in the cluster and is not running.
5375

5376
    """
5377
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5378
    assert instance is not None, \
5379
      "Cannot retrieve locked instance %s" % self.op.instance_name
5380
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
5381
                     " offline, cannot reinstall")
5382
    for node in instance.secondary_nodes:
5383
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
5384
                       " cannot reinstall")
5385

    
5386
    if instance.disk_template == constants.DT_DISKLESS:
5387
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5388
                                 self.op.instance_name,
5389
                                 errors.ECODE_INVAL)
5390
    _CheckInstanceDown(self, instance, "cannot reinstall")
5391

    
5392
    if self.op.os_type is not None:
5393
      # OS verification
5394
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
5395
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
5396
      instance_os = self.op.os_type
5397
    else:
5398
      instance_os = instance.os
5399

    
5400
    nodelist = list(instance.all_nodes)
5401

    
5402
    if self.op.osparams:
5403
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
5404
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
5405
      self.os_inst = i_osdict # the new dict (without defaults)
5406
    else:
5407
      self.os_inst = None
5408

    
5409
    self.instance = instance
5410

    
5411
  def Exec(self, feedback_fn):
5412
    """Reinstall the instance.
5413

5414
    """
5415
    inst = self.instance
5416

    
5417
    if self.op.os_type is not None:
5418
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
5419
      inst.os = self.op.os_type
5420
      # Write to configuration
5421
      self.cfg.Update(inst, feedback_fn)
5422

    
5423
    _StartInstanceDisks(self, inst, None)
5424
    try:
5425
      feedback_fn("Running the instance OS create scripts...")
5426
      # FIXME: pass debug option from opcode to backend
5427
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
5428
                                             self.op.debug_level,
5429
                                             osparams=self.os_inst)
5430
      result.Raise("Could not install OS for instance %s on node %s" %
5431
                   (inst.name, inst.primary_node))
5432
    finally:
5433
      _ShutdownInstanceDisks(self, inst)
5434

    
5435

    
5436
class LUInstanceRecreateDisks(LogicalUnit):
5437
  """Recreate an instance's missing disks.
5438

5439
  """
5440
  HPATH = "instance-recreate-disks"
5441
  HTYPE = constants.HTYPE_INSTANCE
5442
  REQ_BGL = False
5443

    
5444
  def CheckArguments(self):
5445
    # normalise the disk list
5446
    self.op.disks = sorted(frozenset(self.op.disks))
5447

    
5448
  def ExpandNames(self):
5449
    self._ExpandAndLockInstance()
5450
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5451
    if self.op.nodes:
5452
      self.op.nodes = [_ExpandNodeName(self.cfg, n) for n in self.op.nodes]
5453
      self.needed_locks[locking.LEVEL_NODE] = list(self.op.nodes)
5454
    else:
5455
      self.needed_locks[locking.LEVEL_NODE] = []
5456

    
5457
  def DeclareLocks(self, level):
5458
    if level == locking.LEVEL_NODE:
5459
      # if we replace the nodes, we only need to lock the old primary,
5460
      # otherwise we need to lock all nodes for disk re-creation
5461
      primary_only = bool(self.op.nodes)
5462
      self._LockInstancesNodes(primary_only=primary_only)
5463

    
5464
  def BuildHooksEnv(self):
5465
    """Build hooks env.
5466

5467
    This runs on master, primary and secondary nodes of the instance.
5468

5469
    """
5470
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5471
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5472
    return env, nl, nl
5473

    
5474
  def CheckPrereq(self):
5475
    """Check prerequisites.
5476

5477
    This checks that the instance is in the cluster and is not running.
5478

5479
    """
5480
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5481
    assert instance is not None, \
5482
      "Cannot retrieve locked instance %s" % self.op.instance_name
5483
    if self.op.nodes:
5484
      if len(self.op.nodes) != len(instance.all_nodes):
5485
        raise errors.OpPrereqError("Instance %s currently has %d nodes, but"
5486
                                   " %d replacement nodes were specified" %
5487
                                   (instance.name, len(instance.all_nodes),
5488
                                    len(self.op.nodes)),
5489
                                   errors.ECODE_INVAL)
5490
      assert instance.disk_template != constants.DT_DRBD8 or \
5491
          len(self.op.nodes) == 2
5492
      assert instance.disk_template != constants.DT_PLAIN or \
5493
          len(self.op.nodes) == 1
5494
      primary_node = self.op.nodes[0]
5495
    else:
5496
      primary_node = instance.primary_node
5497
    _CheckNodeOnline(self, primary_node)
5498

    
5499
    if instance.disk_template == constants.DT_DISKLESS:
5500
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5501
                                 self.op.instance_name, errors.ECODE_INVAL)
5502
    # if we replace nodes *and* the old primary is offline, we don't
5503
    # check
5504
    assert instance.primary_node in self.needed_locks[locking.LEVEL_NODE]
5505
    old_pnode = self.cfg.GetNodeInfo(instance.primary_node)
5506
    if not (self.op.nodes and old_pnode.offline):
5507
      _CheckInstanceDown(self, instance, "cannot recreate disks")
5508

    
5509
    if not self.op.disks:
5510
      self.op.disks = range(len(instance.disks))
5511
    else:
5512
      for idx in self.op.disks:
5513
        if idx >= len(instance.disks):
5514
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
5515
                                     errors.ECODE_INVAL)
5516
    if self.op.disks != range(len(instance.disks)) and self.op.nodes:
5517
      raise errors.OpPrereqError("Can't recreate disks partially and"
5518
                                 " change the nodes at the same time",
5519
                                 errors.ECODE_INVAL)
5520
    self.instance = instance
5521

    
5522
  def Exec(self, feedback_fn):
5523
    """Recreate the disks.
5524

5525
    """
5526
    # change primary node, if needed
5527
    if self.op.nodes:
5528
      self.instance.primary_node = self.op.nodes[0]
5529
      self.LogWarning("Changing the instance's nodes, you will have to"
5530
                      " remove any disks left on the older nodes manually")
5531

    
5532
    to_skip = []
5533
    for idx, disk in enumerate(self.instance.disks):
5534
      if idx not in self.op.disks: # disk idx has not been passed in
5535
        to_skip.append(idx)
5536
        continue
5537
      # update secondaries for disks, if needed
5538
      if self.op.nodes:
5539
        if disk.dev_type == constants.LD_DRBD8:
5540
          # need to update the nodes
5541
          assert len(self.op.nodes) == 2
5542
          logical_id = list(disk.logical_id)
5543
          logical_id[0] = self.op.nodes[0]
5544
          logical_id[1] = self.op.nodes[1]
5545
          disk.logical_id = tuple(logical_id)
5546

    
5547
    if self.op.nodes:
5548
      self.cfg.Update(self.instance, feedback_fn)
5549

    
5550
    _CreateDisks(self, self.instance, to_skip=to_skip)
5551

    
5552

    
5553
class LUInstanceRename(LogicalUnit):
5554
  """Rename an instance.
5555

5556
  """
5557
  HPATH = "instance-rename"
5558
  HTYPE = constants.HTYPE_INSTANCE
5559

    
5560
  def CheckArguments(self):
5561
    """Check arguments.
5562

5563
    """
5564
    if self.op.ip_check and not self.op.name_check:
5565
      # TODO: make the ip check more flexible and not depend on the name check
5566
      raise errors.OpPrereqError("Cannot do ip check without a name check",
5567
                                 errors.ECODE_INVAL)
5568

    
5569
  def BuildHooksEnv(self):
5570
    """Build hooks env.
5571

5572
    This runs on master, primary and secondary nodes of the instance.
5573

5574
    """
5575
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5576
    env["INSTANCE_NEW_NAME"] = self.op.new_name
5577
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5578
    return env, nl, nl
5579

    
5580
  def CheckPrereq(self):
5581
    """Check prerequisites.
5582

5583
    This checks that the instance is in the cluster and is not running.
5584

5585
    """
5586
    self.op.instance_name = _ExpandInstanceName(self.cfg,
5587
                                                self.op.instance_name)
5588
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5589
    assert instance is not None
5590
    _CheckNodeOnline(self, instance.primary_node)
5591
    _CheckInstanceDown(self, instance, "cannot rename")
5592
    self.instance = instance
5593

    
5594
    new_name = self.op.new_name
5595
    if self.op.name_check:
5596
      hostname = netutils.GetHostname(name=new_name)
5597
      if hostname != new_name:
5598
        self.LogInfo("Resolved given name '%s' to '%s'", new_name,
5599
                     hostname.name)
5600
      new_name = self.op.new_name = hostname.name
5601
      if (self.op.ip_check and
5602
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
5603
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
5604
                                   (hostname.ip, new_name),
5605
                                   errors.ECODE_NOTUNIQUE)
5606

    
5607
    instance_list = self.cfg.GetInstanceList()
5608
    if new_name in instance_list and new_name != instance.name:
5609
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5610
                                 new_name, errors.ECODE_EXISTS)
5611

    
5612
  def Exec(self, feedback_fn):
5613
    """Rename the instance.
5614

5615
    """
5616
    inst = self.instance
5617
    old_name = inst.name
5618

    
5619
    rename_file_storage = False
5620
    if (inst.disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE) and
5621
        self.op.new_name != inst.name):
5622
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5623
      rename_file_storage = True
5624

    
5625
    self.cfg.RenameInstance(inst.name, self.op.new_name)
5626
    # Change the instance lock. This is definitely safe while we hold the BGL
5627
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
5628
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
5629

    
5630
    # re-read the instance from the configuration after rename
5631
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
5632

    
5633
    if rename_file_storage:
5634
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5635
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
5636
                                                     old_file_storage_dir,
5637
                                                     new_file_storage_dir)
5638
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
5639
                   " (but the instance has been renamed in Ganeti)" %
5640
                   (inst.primary_node, old_file_storage_dir,
5641
                    new_file_storage_dir))
5642

    
5643
    _StartInstanceDisks(self, inst, None)
5644
    try:
5645
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
5646
                                                 old_name, self.op.debug_level)
5647
      msg = result.fail_msg
5648
      if msg:
5649
        msg = ("Could not run OS rename script for instance %s on node %s"
5650
               " (but the instance has been renamed in Ganeti): %s" %
5651
               (inst.name, inst.primary_node, msg))
5652
        self.proc.LogWarning(msg)
5653
    finally:
5654
      _ShutdownInstanceDisks(self, inst)
5655

    
5656
    return inst.name
5657

    
5658

    
5659
class LUInstanceRemove(LogicalUnit):
5660
  """Remove an instance.
5661

5662
  """
5663
  HPATH = "instance-remove"
5664
  HTYPE = constants.HTYPE_INSTANCE
5665
  REQ_BGL = False
5666

    
5667
  def ExpandNames(self):
5668
    self._ExpandAndLockInstance()
5669
    self.needed_locks[locking.LEVEL_NODE] = []
5670
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5671

    
5672
  def DeclareLocks(self, level):
5673
    if level == locking.LEVEL_NODE:
5674
      self._LockInstancesNodes()
5675

    
5676
  def BuildHooksEnv(self):
5677
    """Build hooks env.
5678

5679
    This runs on master, primary and secondary nodes of the instance.
5680

5681
    """
5682
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5683
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
5684
    nl = [self.cfg.GetMasterNode()]
5685
    nl_post = list(self.instance.all_nodes) + nl
5686
    return env, nl, nl_post
5687

    
5688
  def CheckPrereq(self):
5689
    """Check prerequisites.
5690

5691
    This checks that the instance is in the cluster.
5692

5693
    """
5694
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5695
    assert self.instance is not None, \
5696
      "Cannot retrieve locked instance %s" % self.op.instance_name
5697

    
5698
  def Exec(self, feedback_fn):
5699
    """Remove the instance.
5700

5701
    """
5702
    instance = self.instance
5703
    logging.info("Shutting down instance %s on node %s",
5704
                 instance.name, instance.primary_node)
5705

    
5706
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5707
                                             self.op.shutdown_timeout)
5708
    msg = result.fail_msg
5709
    if msg:
5710
      if self.op.ignore_failures:
5711
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5712
      else:
5713
        raise errors.OpExecError("Could not shutdown instance %s on"
5714
                                 " node %s: %s" %
5715
                                 (instance.name, instance.primary_node, msg))
5716

    
5717
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5718

    
5719

    
5720
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5721
  """Utility function to remove an instance.
5722

5723
  """
5724
  logging.info("Removing block devices for instance %s", instance.name)
5725

    
5726
  if not _RemoveDisks(lu, instance):
5727
    if not ignore_failures:
5728
      raise errors.OpExecError("Can't remove instance's disks")
5729
    feedback_fn("Warning: can't remove instance's disks")
5730

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

    
5733
  lu.cfg.RemoveInstance(instance.name)
5734

    
5735
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5736
    "Instance lock removal conflict"
5737

    
5738
  # Remove lock for the instance
5739
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5740

    
5741

    
5742
class LUInstanceQuery(NoHooksLU):
5743
  """Logical unit for querying instances.
5744

5745
  """
5746
  # pylint: disable-msg=W0142
5747
  REQ_BGL = False
5748

    
5749
  def CheckArguments(self):
5750
    self.iq = _InstanceQuery(self.op.names, self.op.output_fields,
5751
                             self.op.use_locking)
5752

    
5753
  def ExpandNames(self):
5754
    self.iq.ExpandNames(self)
5755

    
5756
  def DeclareLocks(self, level):
5757
    self.iq.DeclareLocks(self, level)
5758

    
5759
  def Exec(self, feedback_fn):
5760
    return self.iq.OldStyleQuery(self)
5761

    
5762

    
5763
class LUInstanceFailover(LogicalUnit):
5764
  """Failover an instance.
5765

5766
  """
5767
  HPATH = "instance-failover"
5768
  HTYPE = constants.HTYPE_INSTANCE
5769
  REQ_BGL = False
5770

    
5771
  def CheckArguments(self):
5772
    """Check the arguments.
5773

5774
    """
5775
    self.iallocator = getattr(self.op, "iallocator", None)
5776
    self.target_node = getattr(self.op, "target_node", None)
5777

    
5778
  def ExpandNames(self):
5779
    self._ExpandAndLockInstance()
5780

    
5781
    if self.op.target_node is not None:
5782
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5783

    
5784
    self.needed_locks[locking.LEVEL_NODE] = []
5785
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5786

    
5787
  def DeclareLocks(self, level):
5788
    if level == locking.LEVEL_NODE:
5789
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
5790
      if instance.disk_template in constants.DTS_EXT_MIRROR:
5791
        if self.op.target_node is None:
5792
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5793
        else:
5794
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
5795
                                                   self.op.target_node]
5796
        del self.recalculate_locks[locking.LEVEL_NODE]
5797
      else:
5798
        self._LockInstancesNodes()
5799

    
5800
  def BuildHooksEnv(self):
5801
    """Build hooks env.
5802

5803
    This runs on master, primary and secondary nodes of the instance.
5804

5805
    """
5806
    instance = self.instance
5807
    source_node = instance.primary_node
5808
    env = {
5809
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5810
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5811
      "OLD_PRIMARY": source_node,
5812
      "NEW_PRIMARY": self.op.target_node,
5813
      }
5814

    
5815
    if instance.disk_template in constants.DTS_INT_MIRROR:
5816
      env["OLD_SECONDARY"] = instance.secondary_nodes[0]
5817
      env["NEW_SECONDARY"] = source_node
5818
    else:
5819
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = ""
5820

    
5821
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5822
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5823
    nl_post = list(nl)
5824
    nl_post.append(source_node)
5825
    return env, nl, nl_post
5826

    
5827
  def CheckPrereq(self):
5828
    """Check prerequisites.
5829

5830
    This checks that the instance is in the cluster.
5831

5832
    """
5833
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5834
    assert self.instance is not None, \
5835
      "Cannot retrieve locked instance %s" % self.op.instance_name
5836

    
5837
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5838
    if instance.disk_template not in constants.DTS_MIRRORED:
5839
      raise errors.OpPrereqError("Instance's disk layout is not"
5840
                                 " mirrored, cannot failover.",
5841
                                 errors.ECODE_STATE)
5842

    
5843
    if instance.disk_template in constants.DTS_EXT_MIRROR:
5844
      _CheckIAllocatorOrNode(self, "iallocator", "target_node")
5845
      if self.op.iallocator:
5846
        self._RunAllocator()
5847
        # Release all unnecessary node locks
5848
        nodes_keep = [instance.primary_node, self.op.target_node]
5849
        nodes_rel = [node for node in self.acquired_locks[locking.LEVEL_NODE]
5850
                     if node not in nodes_keep]
5851
        self.context.glm.release(locking.LEVEL_NODE, nodes_rel)
5852
        self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
5853

    
5854
      # self.op.target_node is already populated, either directly or by the
5855
      # iallocator run
5856
      target_node = self.op.target_node
5857

    
5858
    else:
5859
      secondary_nodes = instance.secondary_nodes
5860
      if not secondary_nodes:
5861
        raise errors.ConfigurationError("No secondary node but using"
5862
                                        " %s disk template" %
5863
                                        instance.disk_template)
5864
      target_node = secondary_nodes[0]
5865

    
5866
      if self.op.iallocator or (self.op.target_node and
5867
                                self.op.target_node != target_node):
5868
        raise errors.OpPrereqError("Instances with disk template %s cannot"
5869
                                   " be failed over to arbitrary nodes"
5870
                                   " (neither an iallocator nor a target"
5871
                                   " node can be passed)" %
5872
                                   instance.disk_template, errors.ECODE_INVAL)
5873
    _CheckNodeOnline(self, target_node)
5874
    _CheckNodeNotDrained(self, target_node)
5875

    
5876
    # Save target_node so that we can use it in BuildHooksEnv
5877
    self.op.target_node = target_node
5878

    
5879
    if instance.admin_up:
5880
      # check memory requirements on the secondary node
5881
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5882
                           instance.name, bep[constants.BE_MEMORY],
5883
                           instance.hypervisor)
5884
    else:
5885
      self.LogInfo("Not checking memory on the secondary node as"
5886
                   " instance will not be started")
5887

    
5888
    # check bridge existance
5889
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5890

    
5891
  def Exec(self, feedback_fn):
5892
    """Failover an instance.
5893

5894
    The failover is done by shutting it down on its present node and
5895
    starting it on the secondary.
5896

5897
    """
5898
    instance = self.instance
5899
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
5900

    
5901
    source_node = instance.primary_node
5902
    target_node = self.op.target_node
5903

    
5904
    if instance.admin_up:
5905
      feedback_fn("* checking disk consistency between source and target")
5906
      for dev in instance.disks:
5907
        # for drbd, these are drbd over lvm
5908
        if not _CheckDiskConsistency(self, dev, target_node, False):
5909
          if not self.op.ignore_consistency:
5910
            raise errors.OpExecError("Disk %s is degraded on target node,"
5911
                                     " aborting failover." % dev.iv_name)
5912
    else:
5913
      feedback_fn("* not checking disk consistency as instance is not running")
5914

    
5915
    feedback_fn("* shutting down instance on source node")
5916
    logging.info("Shutting down instance %s on node %s",
5917
                 instance.name, source_node)
5918

    
5919
    result = self.rpc.call_instance_shutdown(source_node, instance,
5920
                                             self.op.shutdown_timeout)
5921
    msg = result.fail_msg
5922
    if msg:
5923
      if self.op.ignore_consistency or primary_node.offline:
5924
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5925
                             " Proceeding anyway. Please make sure node"
5926
                             " %s is down. Error details: %s",
5927
                             instance.name, source_node, source_node, msg)
5928
      else:
5929
        raise errors.OpExecError("Could not shutdown instance %s on"
5930
                                 " node %s: %s" %
5931
                                 (instance.name, source_node, msg))
5932

    
5933
    feedback_fn("* deactivating the instance's disks on source node")
5934
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5935
      raise errors.OpExecError("Can't shut down the instance's disks.")
5936

    
5937
    instance.primary_node = target_node
5938
    # distribute new instance config to the other nodes
5939
    self.cfg.Update(instance, feedback_fn)
5940

    
5941
    # Only start the instance if it's marked as up
5942
    if instance.admin_up:
5943
      feedback_fn("* activating the instance's disks on target node")
5944
      logging.info("Starting instance %s on node %s",
5945
                   instance.name, target_node)
5946

    
5947
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5948
                                           ignore_secondaries=True)
5949
      if not disks_ok:
5950
        _ShutdownInstanceDisks(self, instance)
5951
        raise errors.OpExecError("Can't activate the instance's disks")
5952

    
5953
      feedback_fn("* starting the instance on the target node")
5954
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5955
      msg = result.fail_msg
5956
      if msg:
5957
        _ShutdownInstanceDisks(self, instance)
5958
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5959
                                 (instance.name, target_node, msg))
5960

    
5961
  def _RunAllocator(self):
5962
    """Run the allocator based on input opcode.
5963

5964
    """
5965
    ial = IAllocator(self.cfg, self.rpc,
5966
                     mode=constants.IALLOCATOR_MODE_RELOC,
5967
                     name=self.instance.name,
5968
                     # TODO See why hail breaks with a single node below
5969
                     relocate_from=[self.instance.primary_node,
5970
                                    self.instance.primary_node],
5971
                     )
5972

    
5973
    ial.Run(self.op.iallocator)
5974

    
5975
    if not ial.success:
5976
      raise errors.OpPrereqError("Can't compute nodes using"
5977
                                 " iallocator '%s': %s" %
5978
                                 (self.op.iallocator, ial.info),
5979
                                 errors.ECODE_NORES)
5980
    if len(ial.result) != ial.required_nodes:
5981
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
5982
                                 " of nodes (%s), required %s" %
5983
                                 (self.op.iallocator, len(ial.result),
5984
                                  ial.required_nodes), errors.ECODE_FAULT)
5985
    self.op.target_node = ial.result[0]
5986
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
5987
                 self.instance.name, self.op.iallocator,
5988
                 utils.CommaJoin(ial.result))
5989

    
5990

    
5991
class LUInstanceMigrate(LogicalUnit):
5992
  """Migrate an instance.
5993

5994
  This is migration without shutting down, compared to the failover,
5995
  which is done with shutdown.
5996

5997
  """
5998
  HPATH = "instance-migrate"
5999
  HTYPE = constants.HTYPE_INSTANCE
6000
  REQ_BGL = False
6001

    
6002
  def ExpandNames(self):
6003
    self._ExpandAndLockInstance()
6004

    
6005
    if self.op.target_node is not None:
6006
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6007

    
6008
    self.needed_locks[locking.LEVEL_NODE] = []
6009
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6010

    
6011
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
6012
                                       self.op.cleanup)
6013
    self.tasklets = [self._migrater]
6014

    
6015
  def DeclareLocks(self, level):
6016
    if level == locking.LEVEL_NODE:
6017
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6018
      if instance.disk_template in constants.DTS_EXT_MIRROR:
6019
        if self.op.target_node is None:
6020
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6021
        else:
6022
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6023
                                                   self.op.target_node]
6024
        del self.recalculate_locks[locking.LEVEL_NODE]
6025
      else:
6026
        self._LockInstancesNodes()
6027

    
6028
  def BuildHooksEnv(self):
6029
    """Build hooks env.
6030

6031
    This runs on master, primary and secondary nodes of the instance.
6032

6033
    """
6034
    instance = self._migrater.instance
6035
    source_node = instance.primary_node
6036
    target_node = self.op.target_node
6037
    env = _BuildInstanceHookEnvByObject(self, instance)
6038
    env["MIGRATE_LIVE"] = self._migrater.live
6039
    env["MIGRATE_CLEANUP"] = self.op.cleanup
6040
    env.update({
6041
        "OLD_PRIMARY": source_node,
6042
        "NEW_PRIMARY": target_node,
6043
        })
6044

    
6045
    if instance.disk_template in constants.DTS_INT_MIRROR:
6046
      env["OLD_SECONDARY"] = target_node
6047
      env["NEW_SECONDARY"] = source_node
6048
    else:
6049
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = None
6050

    
6051
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6052
    nl_post = list(nl)
6053
    nl_post.append(source_node)
6054
    return env, nl, nl_post
6055

    
6056

    
6057
class LUInstanceMove(LogicalUnit):
6058
  """Move an instance by data-copying.
6059

6060
  """
6061
  HPATH = "instance-move"
6062
  HTYPE = constants.HTYPE_INSTANCE
6063
  REQ_BGL = False
6064

    
6065
  def ExpandNames(self):
6066
    self._ExpandAndLockInstance()
6067
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6068
    self.op.target_node = target_node
6069
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
6070
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6071

    
6072
  def DeclareLocks(self, level):
6073
    if level == locking.LEVEL_NODE:
6074
      self._LockInstancesNodes(primary_only=True)
6075

    
6076
  def BuildHooksEnv(self):
6077
    """Build hooks env.
6078

6079
    This runs on master, primary and secondary nodes of the instance.
6080

6081
    """
6082
    env = {
6083
      "TARGET_NODE": self.op.target_node,
6084
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6085
      }
6086
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6087
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
6088
                                       self.op.target_node]
6089
    return env, nl, nl
6090

    
6091
  def CheckPrereq(self):
6092
    """Check prerequisites.
6093

6094
    This checks that the instance is in the cluster.
6095

6096
    """
6097
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6098
    assert self.instance is not None, \
6099
      "Cannot retrieve locked instance %s" % self.op.instance_name
6100

    
6101
    node = self.cfg.GetNodeInfo(self.op.target_node)
6102
    assert node is not None, \
6103
      "Cannot retrieve locked node %s" % self.op.target_node
6104

    
6105
    self.target_node = target_node = node.name
6106

    
6107
    if target_node == instance.primary_node:
6108
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
6109
                                 (instance.name, target_node),
6110
                                 errors.ECODE_STATE)
6111

    
6112
    bep = self.cfg.GetClusterInfo().FillBE(instance)
6113

    
6114
    for idx, dsk in enumerate(instance.disks):
6115
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
6116
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
6117
                                   " cannot copy" % idx, errors.ECODE_STATE)
6118

    
6119
    _CheckNodeOnline(self, target_node)
6120
    _CheckNodeNotDrained(self, target_node)
6121
    _CheckNodeVmCapable(self, target_node)
6122

    
6123
    if instance.admin_up:
6124
      # check memory requirements on the secondary node
6125
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
6126
                           instance.name, bep[constants.BE_MEMORY],
6127
                           instance.hypervisor)
6128
    else:
6129
      self.LogInfo("Not checking memory on the secondary node as"
6130
                   " instance will not be started")
6131

    
6132
    # check bridge existance
6133
    _CheckInstanceBridgesExist(self, instance, node=target_node)
6134

    
6135
  def Exec(self, feedback_fn):
6136
    """Move an instance.
6137

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

6141
    """
6142
    instance = self.instance
6143

    
6144
    source_node = instance.primary_node
6145
    target_node = self.target_node
6146

    
6147
    self.LogInfo("Shutting down instance %s on source node %s",
6148
                 instance.name, source_node)
6149

    
6150
    result = self.rpc.call_instance_shutdown(source_node, instance,
6151
                                             self.op.shutdown_timeout)
6152
    msg = result.fail_msg
6153
    if msg:
6154
      if self.op.ignore_consistency:
6155
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
6156
                             " Proceeding anyway. Please make sure node"
6157
                             " %s is down. Error details: %s",
6158
                             instance.name, source_node, source_node, msg)
6159
      else:
6160
        raise errors.OpExecError("Could not shutdown instance %s on"
6161
                                 " node %s: %s" %
6162
                                 (instance.name, source_node, msg))
6163

    
6164
    # create the target disks
6165
    try:
6166
      _CreateDisks(self, instance, target_node=target_node)
6167
    except errors.OpExecError:
6168
      self.LogWarning("Device creation failed, reverting...")
6169
      try:
6170
        _RemoveDisks(self, instance, target_node=target_node)
6171
      finally:
6172
        self.cfg.ReleaseDRBDMinors(instance.name)
6173
        raise
6174

    
6175
    cluster_name = self.cfg.GetClusterInfo().cluster_name
6176

    
6177
    errs = []
6178
    # activate, get path, copy the data over
6179
    for idx, disk in enumerate(instance.disks):
6180
      self.LogInfo("Copying data for disk %d", idx)
6181
      result = self.rpc.call_blockdev_assemble(target_node, disk,
6182
                                               instance.name, True, idx)
6183
      if result.fail_msg:
6184
        self.LogWarning("Can't assemble newly created disk %d: %s",
6185
                        idx, result.fail_msg)
6186
        errs.append(result.fail_msg)
6187
        break
6188
      dev_path = result.payload
6189
      result = self.rpc.call_blockdev_export(source_node, disk,
6190
                                             target_node, dev_path,
6191
                                             cluster_name)
6192
      if result.fail_msg:
6193
        self.LogWarning("Can't copy data over for disk %d: %s",
6194
                        idx, result.fail_msg)
6195
        errs.append(result.fail_msg)
6196
        break
6197

    
6198
    if errs:
6199
      self.LogWarning("Some disks failed to copy, aborting")
6200
      try:
6201
        _RemoveDisks(self, instance, target_node=target_node)
6202
      finally:
6203
        self.cfg.ReleaseDRBDMinors(instance.name)
6204
        raise errors.OpExecError("Errors during disk copy: %s" %
6205
                                 (",".join(errs),))
6206

    
6207
    instance.primary_node = target_node
6208
    self.cfg.Update(instance, feedback_fn)
6209

    
6210
    self.LogInfo("Removing the disks on the original node")
6211
    _RemoveDisks(self, instance, target_node=source_node)
6212

    
6213
    # Only start the instance if it's marked as up
6214
    if instance.admin_up:
6215
      self.LogInfo("Starting instance %s on node %s",
6216
                   instance.name, target_node)
6217

    
6218
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
6219
                                           ignore_secondaries=True)
6220
      if not disks_ok:
6221
        _ShutdownInstanceDisks(self, instance)
6222
        raise errors.OpExecError("Can't activate the instance's disks")
6223

    
6224
      result = self.rpc.call_instance_start(target_node, instance, None, None)
6225
      msg = result.fail_msg
6226
      if msg:
6227
        _ShutdownInstanceDisks(self, instance)
6228
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
6229
                                 (instance.name, target_node, msg))
6230

    
6231

    
6232
class LUNodeMigrate(LogicalUnit):
6233
  """Migrate all instances from a node.
6234

6235
  """
6236
  HPATH = "node-migrate"
6237
  HTYPE = constants.HTYPE_NODE
6238
  REQ_BGL = False
6239

    
6240
  def CheckArguments(self):
6241
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
6242

    
6243
  def ExpandNames(self):
6244
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6245

    
6246
    self.needed_locks = {}
6247

    
6248
    # Create tasklets for migrating instances for all instances on this node
6249
    names = []
6250
    tasklets = []
6251

    
6252
    self.lock_all_nodes = False
6253

    
6254
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
6255
      logging.debug("Migrating instance %s", inst.name)
6256
      names.append(inst.name)
6257

    
6258
      tasklets.append(TLMigrateInstance(self, inst.name, False))
6259

    
6260
      if inst.disk_template in constants.DTS_EXT_MIRROR:
6261
        # We need to lock all nodes, as the iallocator will choose the
6262
        # destination nodes afterwards
6263
        self.lock_all_nodes = True
6264

    
6265
    self.tasklets = tasklets
6266

    
6267
    # Declare node locks
6268
    if self.lock_all_nodes:
6269
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6270
    else:
6271
      self.needed_locks[locking.LEVEL_NODE] = [self.op.node_name]
6272
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6273

    
6274
    # Declare instance locks
6275
    self.needed_locks[locking.LEVEL_INSTANCE] = names
6276

    
6277
  def DeclareLocks(self, level):
6278
    if level == locking.LEVEL_NODE and not self.lock_all_nodes:
6279
      self._LockInstancesNodes()
6280

    
6281
  def BuildHooksEnv(self):
6282
    """Build hooks env.
6283

6284
    This runs on the master, the primary and all the secondaries.
6285

6286
    """
6287
    env = {
6288
      "NODE_NAME": self.op.node_name,
6289
      }
6290

    
6291
    nl = [self.cfg.GetMasterNode()]
6292

    
6293
    return (env, nl, nl)
6294

    
6295

    
6296
class TLMigrateInstance(Tasklet):
6297
  """Tasklet class for instance migration.
6298

6299
  @type live: boolean
6300
  @ivar live: whether the migration will be done live or non-live;
6301
      this variable is initalized only after CheckPrereq has run
6302

6303
  """
6304
  def __init__(self, lu, instance_name, cleanup):
6305
    """Initializes this class.
6306

6307
    """
6308
    Tasklet.__init__(self, lu)
6309

    
6310
    # Parameters
6311
    self.instance_name = instance_name
6312
    self.cleanup = cleanup
6313
    self.live = False # will be overridden later
6314

    
6315
  def CheckPrereq(self):
6316
    """Check prerequisites.
6317

6318
    This checks that the instance is in the cluster.
6319

6320
    """
6321
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
6322
    instance = self.cfg.GetInstanceInfo(instance_name)
6323
    assert instance is not None
6324
    self.instance = instance
6325

    
6326
    if instance.disk_template not in constants.DTS_MIRRORED:
6327
      raise errors.OpPrereqError("Instance's disk layout '%s' does not allow"
6328
                                 " migrations" % instance.disk_template,
6329
                                 errors.ECODE_STATE)
6330

    
6331
    if instance.disk_template in constants.DTS_EXT_MIRROR:
6332
      _CheckIAllocatorOrNode(self.lu, "iallocator", "target_node")
6333

    
6334
      if self.lu.op.iallocator:
6335
        self._RunAllocator()
6336
      else:
6337
        # We set set self.target_node as it is required by
6338
        # BuildHooksEnv
6339
        self.target_node = self.lu.op.target_node
6340

    
6341
      target_node = self.target_node
6342
      if self.target_node == instance.primary_node:
6343
        raise errors.OpPrereqError("Cannot migrate instance %s"
6344
                                   " to its primary (%s)" %
6345
                                   (instance.name, instance.primary_node))
6346

    
6347
      if len(self.lu.tasklets) == 1:
6348
        # It is safe to remove locks only when we're the only tasklet in the LU
6349
        nodes_keep = [instance.primary_node, target_node]
6350
        nodes_rel = [node for node in self.lu.acquired_locks[locking.LEVEL_NODE]
6351
                     if node not in nodes_keep]
6352
        self.lu.context.glm.release(locking.LEVEL_NODE, nodes_rel)
6353
        self.lu.acquired_locks[locking.LEVEL_NODE] = nodes_keep
6354

    
6355
    else:
6356
      secondary_nodes = instance.secondary_nodes
6357
      if not secondary_nodes:
6358
        raise errors.ConfigurationError("No secondary node but using"
6359
                                        " %s disk template" %
6360
                                        instance.disk_template)
6361
      target_node = secondary_nodes[0]
6362
      if self.lu.op.iallocator or (self.lu.op.target_node and
6363
                                   self.lu.op.target_node != target_node):
6364
        raise errors.OpPrereqError("Instances with disk template %s cannot"
6365
                                   " be migrated over to arbitrary nodes"
6366
                                   " (neither an iallocator nor a target"
6367
                                   " node can be passed)" %
6368
                                   instance.disk_template, errors.ECODE_INVAL)
6369

    
6370
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
6371

    
6372
    # check memory requirements on the secondary node
6373
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
6374
                         instance.name, i_be[constants.BE_MEMORY],
6375
                         instance.hypervisor)
6376

    
6377
    # check bridge existance
6378
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
6379

    
6380
    if not self.cleanup:
6381
      _CheckNodeNotDrained(self.lu, target_node)
6382
      result = self.rpc.call_instance_migratable(instance.primary_node,
6383
                                                 instance)
6384
      result.Raise("Can't migrate, please use failover",
6385
                   prereq=True, ecode=errors.ECODE_STATE)
6386

    
6387

    
6388
    if self.lu.op.live is not None and self.lu.op.mode is not None:
6389
      raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
6390
                                 " parameters are accepted",
6391
                                 errors.ECODE_INVAL)
6392
    if self.lu.op.live is not None:
6393
      if self.lu.op.live:
6394
        self.lu.op.mode = constants.HT_MIGRATION_LIVE
6395
      else:
6396
        self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6397
      # reset the 'live' parameter to None so that repeated
6398
      # invocations of CheckPrereq do not raise an exception
6399
      self.lu.op.live = None
6400
    elif self.lu.op.mode is None:
6401
      # read the default value from the hypervisor
6402
      i_hv = self.cfg.GetClusterInfo().FillHV(self.instance, skip_globals=False)
6403
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6404

    
6405
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6406

    
6407
  def _RunAllocator(self):
6408
    """Run the allocator based on input opcode.
6409

6410
    """
6411
    ial = IAllocator(self.cfg, self.rpc,
6412
                     mode=constants.IALLOCATOR_MODE_RELOC,
6413
                     name=self.instance_name,
6414
                     # TODO See why hail breaks with a single node below
6415
                     relocate_from=[self.instance.primary_node,
6416
                                    self.instance.primary_node],
6417
                     )
6418

    
6419
    ial.Run(self.lu.op.iallocator)
6420

    
6421
    if not ial.success:
6422
      raise errors.OpPrereqError("Can't compute nodes using"
6423
                                 " iallocator '%s': %s" %
6424
                                 (self.lu.op.iallocator, ial.info),
6425
                                 errors.ECODE_NORES)
6426
    if len(ial.result) != ial.required_nodes:
6427
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6428
                                 " of nodes (%s), required %s" %
6429
                                 (self.lu.op.iallocator, len(ial.result),
6430
                                  ial.required_nodes), errors.ECODE_FAULT)
6431
    self.target_node = ial.result[0]
6432
    self.lu.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6433
                 self.instance_name, self.lu.op.iallocator,
6434
                 utils.CommaJoin(ial.result))
6435

    
6436
  def _WaitUntilSync(self):
6437
    """Poll with custom rpc for disk sync.
6438

6439
    This uses our own step-based rpc call.
6440

6441
    """
6442
    self.feedback_fn("* wait until resync is done")
6443
    all_done = False
6444
    while not all_done:
6445
      all_done = True
6446
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6447
                                            self.nodes_ip,
6448
                                            self.instance.disks)
6449
      min_percent = 100
6450
      for node, nres in result.items():
6451
        nres.Raise("Cannot resync disks on node %s" % node)
6452
        node_done, node_percent = nres.payload
6453
        all_done = all_done and node_done
6454
        if node_percent is not None:
6455
          min_percent = min(min_percent, node_percent)
6456
      if not all_done:
6457
        if min_percent < 100:
6458
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6459
        time.sleep(2)
6460

    
6461
  def _EnsureSecondary(self, node):
6462
    """Demote a node to secondary.
6463

6464
    """
6465
    self.feedback_fn("* switching node %s to secondary mode" % node)
6466

    
6467
    for dev in self.instance.disks:
6468
      self.cfg.SetDiskID(dev, node)
6469

    
6470
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6471
                                          self.instance.disks)
6472
    result.Raise("Cannot change disk to secondary on node %s" % node)
6473

    
6474
  def _GoStandalone(self):
6475
    """Disconnect from the network.
6476

6477
    """
6478
    self.feedback_fn("* changing into standalone mode")
6479
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6480
                                               self.instance.disks)
6481
    for node, nres in result.items():
6482
      nres.Raise("Cannot disconnect disks node %s" % node)
6483

    
6484
  def _GoReconnect(self, multimaster):
6485
    """Reconnect to the network.
6486

6487
    """
6488
    if multimaster:
6489
      msg = "dual-master"
6490
    else:
6491
      msg = "single-master"
6492
    self.feedback_fn("* changing disks into %s mode" % msg)
6493
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6494
                                           self.instance.disks,
6495
                                           self.instance.name, multimaster)
6496
    for node, nres in result.items():
6497
      nres.Raise("Cannot change disks config on node %s" % node)
6498

    
6499
  def _ExecCleanup(self):
6500
    """Try to cleanup after a failed migration.
6501

6502
    The cleanup is done by:
6503
      - check that the instance is running only on one node
6504
        (and update the config if needed)
6505
      - change disks on its secondary node to secondary
6506
      - wait until disks are fully synchronized
6507
      - disconnect from the network
6508
      - change disks into single-master mode
6509
      - wait again until disks are fully synchronized
6510

6511
    """
6512
    instance = self.instance
6513
    target_node = self.target_node
6514
    source_node = self.source_node
6515

    
6516
    # check running on only one node
6517
    self.feedback_fn("* checking where the instance actually runs"
6518
                     " (if this hangs, the hypervisor might be in"
6519
                     " a bad state)")
6520
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
6521
    for node, result in ins_l.items():
6522
      result.Raise("Can't contact node %s" % node)
6523

    
6524
    runningon_source = instance.name in ins_l[source_node].payload
6525
    runningon_target = instance.name in ins_l[target_node].payload
6526

    
6527
    if runningon_source and runningon_target:
6528
      raise errors.OpExecError("Instance seems to be running on two nodes,"
6529
                               " or the hypervisor is confused. You will have"
6530
                               " to ensure manually that it runs only on one"
6531
                               " and restart this operation.")
6532

    
6533
    if not (runningon_source or runningon_target):
6534
      raise errors.OpExecError("Instance does not seem to be running at all."
6535
                               " In this case, it's safer to repair by"
6536
                               " running 'gnt-instance stop' to ensure disk"
6537
                               " shutdown, and then restarting it.")
6538

    
6539
    if runningon_target:
6540
      # the migration has actually succeeded, we need to update the config
6541
      self.feedback_fn("* instance running on secondary node (%s),"
6542
                       " updating config" % target_node)
6543
      instance.primary_node = target_node
6544
      self.cfg.Update(instance, self.feedback_fn)
6545
      demoted_node = source_node
6546
    else:
6547
      self.feedback_fn("* instance confirmed to be running on its"
6548
                       " primary node (%s)" % source_node)
6549
      demoted_node = target_node
6550

    
6551
    if instance.disk_template in constants.DTS_INT_MIRROR:
6552
      self._EnsureSecondary(demoted_node)
6553
      try:
6554
        self._WaitUntilSync()
6555
      except errors.OpExecError:
6556
        # we ignore here errors, since if the device is standalone, it
6557
        # won't be able to sync
6558
        pass
6559
      self._GoStandalone()
6560
      self._GoReconnect(False)
6561
      self._WaitUntilSync()
6562

    
6563
    self.feedback_fn("* done")
6564

    
6565
  def _RevertDiskStatus(self):
6566
    """Try to revert the disk status after a failed migration.
6567

6568
    """
6569
    target_node = self.target_node
6570
    if self.instance.disk_template in constants.DTS_EXT_MIRROR:
6571
      return
6572

    
6573
    try:
6574
      self._EnsureSecondary(target_node)
6575
      self._GoStandalone()
6576
      self._GoReconnect(False)
6577
      self._WaitUntilSync()
6578
    except errors.OpExecError, err:
6579
      self.lu.LogWarning("Migration failed and I can't reconnect the"
6580
                         " drives: error '%s'\n"
6581
                         "Please look and recover the instance status" %
6582
                         str(err))
6583

    
6584
  def _AbortMigration(self):
6585
    """Call the hypervisor code to abort a started migration.
6586

6587
    """
6588
    instance = self.instance
6589
    target_node = self.target_node
6590
    migration_info = self.migration_info
6591

    
6592
    abort_result = self.rpc.call_finalize_migration(target_node,
6593
                                                    instance,
6594
                                                    migration_info,
6595
                                                    False)
6596
    abort_msg = abort_result.fail_msg
6597
    if abort_msg:
6598
      logging.error("Aborting migration failed on target node %s: %s",
6599
                    target_node, abort_msg)
6600
      # Don't raise an exception here, as we stil have to try to revert the
6601
      # disk status, even if this step failed.
6602

    
6603
  def _ExecMigration(self):
6604
    """Migrate an instance.
6605

6606
    The migrate is done by:
6607
      - change the disks into dual-master mode
6608
      - wait until disks are fully synchronized again
6609
      - migrate the instance
6610
      - change disks on the new secondary node (the old primary) to secondary
6611
      - wait until disks are fully synchronized
6612
      - change disks into single-master mode
6613

6614
    """
6615
    instance = self.instance
6616
    target_node = self.target_node
6617
    source_node = self.source_node
6618

    
6619
    self.feedback_fn("* checking disk consistency between source and target")
6620
    for dev in instance.disks:
6621
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6622
        raise errors.OpExecError("Disk %s is degraded or not fully"
6623
                                 " synchronized on target node,"
6624
                                 " aborting migrate." % dev.iv_name)
6625

    
6626
    # First get the migration information from the remote node
6627
    result = self.rpc.call_migration_info(source_node, instance)
6628
    msg = result.fail_msg
6629
    if msg:
6630
      log_err = ("Failed fetching source migration information from %s: %s" %
6631
                 (source_node, msg))
6632
      logging.error(log_err)
6633
      raise errors.OpExecError(log_err)
6634

    
6635
    self.migration_info = migration_info = result.payload
6636

    
6637
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
6638
      # Then switch the disks to master/master mode
6639
      self._EnsureSecondary(target_node)
6640
      self._GoStandalone()
6641
      self._GoReconnect(True)
6642
      self._WaitUntilSync()
6643

    
6644
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6645
    result = self.rpc.call_accept_instance(target_node,
6646
                                           instance,
6647
                                           migration_info,
6648
                                           self.nodes_ip[target_node])
6649

    
6650
    msg = result.fail_msg
6651
    if msg:
6652
      logging.error("Instance pre-migration failed, trying to revert"
6653
                    " disk status: %s", msg)
6654
      self.feedback_fn("Pre-migration failed, aborting")
6655
      self._AbortMigration()
6656
      self._RevertDiskStatus()
6657
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6658
                               (instance.name, msg))
6659

    
6660
    self.feedback_fn("* migrating instance to %s" % target_node)
6661
    result = self.rpc.call_instance_migrate(source_node, instance,
6662
                                            self.nodes_ip[target_node],
6663
                                            self.live)
6664
    msg = result.fail_msg
6665
    if msg:
6666
      logging.error("Instance migration failed, trying to revert"
6667
                    " disk status: %s", msg)
6668
      self.feedback_fn("Migration failed, aborting")
6669
      self._AbortMigration()
6670
      self._RevertDiskStatus()
6671
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6672
                               (instance.name, msg))
6673

    
6674
    instance.primary_node = target_node
6675
    # distribute new instance config to the other nodes
6676
    self.cfg.Update(instance, self.feedback_fn)
6677

    
6678
    result = self.rpc.call_finalize_migration(target_node,
6679
                                              instance,
6680
                                              migration_info,
6681
                                              True)
6682
    msg = result.fail_msg
6683
    if msg:
6684
      logging.error("Instance migration succeeded, but finalization failed:"
6685
                    " %s", msg)
6686
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6687
                               msg)
6688

    
6689
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
6690
      self._EnsureSecondary(source_node)
6691
      self._WaitUntilSync()
6692
      self._GoStandalone()
6693
      self._GoReconnect(False)
6694
      self._WaitUntilSync()
6695

    
6696
    self.feedback_fn("* done")
6697

    
6698
  def Exec(self, feedback_fn):
6699
    """Perform the migration.
6700

6701
    """
6702
    feedback_fn("Migrating instance %s" % self.instance.name)
6703

    
6704
    self.feedback_fn = feedback_fn
6705

    
6706
    self.source_node = self.instance.primary_node
6707

    
6708
    # FIXME: if we implement migrate-to-any in DRBD, this needs fixing
6709
    if self.instance.disk_template in constants.DTS_INT_MIRROR:
6710
      self.target_node = self.instance.secondary_nodes[0]
6711
      # Otherwise self.target_node has been populated either
6712
      # directly, or through an iallocator.
6713

    
6714
    self.all_nodes = [self.source_node, self.target_node]
6715
    self.nodes_ip = {
6716
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6717
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6718
      }
6719

    
6720
    if self.cleanup:
6721
      return self._ExecCleanup()
6722
    else:
6723
      return self._ExecMigration()
6724

    
6725

    
6726
def _CreateBlockDev(lu, node, instance, device, force_create,
6727
                    info, force_open):
6728
  """Create a tree of block devices on a given node.
6729

6730
  If this device type has to be created on secondaries, create it and
6731
  all its children.
6732

6733
  If not, just recurse to children keeping the same 'force' value.
6734

6735
  @param lu: the lu on whose behalf we execute
6736
  @param node: the node on which to create the device
6737
  @type instance: L{objects.Instance}
6738
  @param instance: the instance which owns the device
6739
  @type device: L{objects.Disk}
6740
  @param device: the device to create
6741
  @type force_create: boolean
6742
  @param force_create: whether to force creation of this device; this
6743
      will be change to True whenever we find a device which has
6744
      CreateOnSecondary() attribute
6745
  @param info: the extra 'metadata' we should attach to the device
6746
      (this will be represented as a LVM tag)
6747
  @type force_open: boolean
6748
  @param force_open: this parameter will be passes to the
6749
      L{backend.BlockdevCreate} function where it specifies
6750
      whether we run on primary or not, and it affects both
6751
      the child assembly and the device own Open() execution
6752

6753
  """
6754
  if device.CreateOnSecondary():
6755
    force_create = True
6756

    
6757
  if device.children:
6758
    for child in device.children:
6759
      _CreateBlockDev(lu, node, instance, child, force_create,
6760
                      info, force_open)
6761

    
6762
  if not force_create:
6763
    return
6764

    
6765
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6766

    
6767

    
6768
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6769
  """Create a single block device on a given node.
6770

6771
  This will not recurse over children of the device, so they must be
6772
  created in advance.
6773

6774
  @param lu: the lu on whose behalf we execute
6775
  @param node: the node on which to create the device
6776
  @type instance: L{objects.Instance}
6777
  @param instance: the instance which owns the device
6778
  @type device: L{objects.Disk}
6779
  @param device: the device to create
6780
  @param info: the extra 'metadata' we should attach to the device
6781
      (this will be represented as a LVM tag)
6782
  @type force_open: boolean
6783
  @param force_open: this parameter will be passes to the
6784
      L{backend.BlockdevCreate} function where it specifies
6785
      whether we run on primary or not, and it affects both
6786
      the child assembly and the device own Open() execution
6787

6788
  """
6789
  lu.cfg.SetDiskID(device, node)
6790
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6791
                                       instance.name, force_open, info)
6792
  result.Raise("Can't create block device %s on"
6793
               " node %s for instance %s" % (device, node, instance.name))
6794
  if device.physical_id is None:
6795
    device.physical_id = result.payload
6796

    
6797

    
6798
def _GenerateUniqueNames(lu, exts):
6799
  """Generate a suitable LV name.
6800

6801
  This will generate a logical volume name for the given instance.
6802

6803
  """
6804
  results = []
6805
  for val in exts:
6806
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6807
    results.append("%s%s" % (new_id, val))
6808
  return results
6809

    
6810

    
6811
def _GenerateDRBD8Branch(lu, primary, secondary, size, vgnames, names,
6812
                         iv_name, p_minor, s_minor):
6813
  """Generate a drbd8 device complete with its children.
6814

6815
  """
6816
  assert len(vgnames) == len(names) == 2
6817
  port = lu.cfg.AllocatePort()
6818
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6819
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6820
                          logical_id=(vgnames[0], names[0]))
6821
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6822
                          logical_id=(vgnames[1], names[1]))
6823
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6824
                          logical_id=(primary, secondary, port,
6825
                                      p_minor, s_minor,
6826
                                      shared_secret),
6827
                          children=[dev_data, dev_meta],
6828
                          iv_name=iv_name)
6829
  return drbd_dev
6830

    
6831

    
6832
def _GenerateDiskTemplate(lu, template_name,
6833
                          instance_name, primary_node,
6834
                          secondary_nodes, disk_info,
6835
                          file_storage_dir, file_driver,
6836
                          base_index, feedback_fn):
6837
  """Generate the entire disk layout for a given template type.
6838

6839
  """
6840
  #TODO: compute space requirements
6841

    
6842
  vgname = lu.cfg.GetVGName()
6843
  disk_count = len(disk_info)
6844
  disks = []
6845
  if template_name == constants.DT_DISKLESS:
6846
    pass
6847
  elif template_name == constants.DT_PLAIN:
6848
    if len(secondary_nodes) != 0:
6849
      raise errors.ProgrammerError("Wrong template configuration")
6850

    
6851
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6852
                                      for i in range(disk_count)])
6853
    for idx, disk in enumerate(disk_info):
6854
      disk_index = idx + base_index
6855
      vg = disk.get("vg", vgname)
6856
      feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
6857
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6858
                              logical_id=(vg, names[idx]),
6859
                              iv_name="disk/%d" % disk_index,
6860
                              mode=disk["mode"])
6861
      disks.append(disk_dev)
6862
  elif template_name == constants.DT_DRBD8:
6863
    if len(secondary_nodes) != 1:
6864
      raise errors.ProgrammerError("Wrong template configuration")
6865
    remote_node = secondary_nodes[0]
6866
    minors = lu.cfg.AllocateDRBDMinor(
6867
      [primary_node, remote_node] * len(disk_info), instance_name)
6868

    
6869
    names = []
6870
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6871
                                               for i in range(disk_count)]):
6872
      names.append(lv_prefix + "_data")
6873
      names.append(lv_prefix + "_meta")
6874
    for idx, disk in enumerate(disk_info):
6875
      disk_index = idx + base_index
6876
      data_vg = disk.get("vg", vgname)
6877
      meta_vg = disk.get("metavg", data_vg)
6878
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6879
                                      disk["size"], [data_vg, meta_vg],
6880
                                      names[idx*2:idx*2+2],
6881
                                      "disk/%d" % disk_index,
6882
                                      minors[idx*2], minors[idx*2+1])
6883
      disk_dev.mode = disk["mode"]
6884
      disks.append(disk_dev)
6885
  elif template_name == constants.DT_FILE:
6886
    if len(secondary_nodes) != 0:
6887
      raise errors.ProgrammerError("Wrong template configuration")
6888

    
6889
    opcodes.RequireFileStorage()
6890

    
6891
    for idx, disk in enumerate(disk_info):
6892
      disk_index = idx + base_index
6893
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6894
                              iv_name="disk/%d" % disk_index,
6895
                              logical_id=(file_driver,
6896
                                          "%s/disk%d" % (file_storage_dir,
6897
                                                         disk_index)),
6898
                              mode=disk["mode"])
6899
      disks.append(disk_dev)
6900
  elif template_name == constants.DT_SHARED_FILE:
6901
    if len(secondary_nodes) != 0:
6902
      raise errors.ProgrammerError("Wrong template configuration")
6903

    
6904
    opcodes.RequireSharedFileStorage()
6905

    
6906
    for idx, disk in enumerate(disk_info):
6907
      disk_index = idx + base_index
6908
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6909
                              iv_name="disk/%d" % disk_index,
6910
                              logical_id=(file_driver,
6911
                                          "%s/disk%d" % (file_storage_dir,
6912
                                                         disk_index)),
6913
                              mode=disk["mode"])
6914
      disks.append(disk_dev)
6915
  elif template_name == constants.DT_BLOCK:
6916
    if len(secondary_nodes) != 0:
6917
      raise errors.ProgrammerError("Wrong template configuration")
6918

    
6919
    for idx, disk in enumerate(disk_info):
6920
      disk_index = idx + base_index
6921
      disk_dev = objects.Disk(dev_type=constants.LD_BLOCKDEV, size=disk["size"],
6922
                              logical_id=(constants.BLOCKDEV_DRIVER_MANUAL,
6923
                                          disk["adopt"]),
6924
                              iv_name="disk/%d" % disk_index,
6925
                              mode=disk["mode"])
6926
      disks.append(disk_dev)
6927

    
6928
  else:
6929
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6930
  return disks
6931

    
6932

    
6933
def _GetInstanceInfoText(instance):
6934
  """Compute that text that should be added to the disk's metadata.
6935

6936
  """
6937
  return "originstname+%s" % instance.name
6938

    
6939

    
6940
def _CalcEta(time_taken, written, total_size):
6941
  """Calculates the ETA based on size written and total size.
6942

6943
  @param time_taken: The time taken so far
6944
  @param written: amount written so far
6945
  @param total_size: The total size of data to be written
6946
  @return: The remaining time in seconds
6947

6948
  """
6949
  avg_time = time_taken / float(written)
6950
  return (total_size - written) * avg_time
6951

    
6952

    
6953
def _WipeDisks(lu, instance):
6954
  """Wipes instance disks.
6955

6956
  @type lu: L{LogicalUnit}
6957
  @param lu: the logical unit on whose behalf we execute
6958
  @type instance: L{objects.Instance}
6959
  @param instance: the instance whose disks we should create
6960
  @return: the success of the wipe
6961

6962
  """
6963
  node = instance.primary_node
6964

    
6965
  for device in instance.disks:
6966
    lu.cfg.SetDiskID(device, node)
6967

    
6968
  logging.info("Pause sync of instance %s disks", instance.name)
6969
  result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, True)
6970

    
6971
  for idx, success in enumerate(result.payload):
6972
    if not success:
6973
      logging.warn("pause-sync of instance %s for disks %d failed",
6974
                   instance.name, idx)
6975

    
6976
  try:
6977
    for idx, device in enumerate(instance.disks):
6978
      # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
6979
      # MAX_WIPE_CHUNK at max
6980
      wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
6981
                            constants.MIN_WIPE_CHUNK_PERCENT)
6982
      # we _must_ make this an int, otherwise rounding errors will
6983
      # occur
6984
      wipe_chunk_size = int(wipe_chunk_size)
6985

    
6986
      lu.LogInfo("* Wiping disk %d", idx)
6987
      logging.info("Wiping disk %d for instance %s, node %s using"
6988
                   " chunk size %s", idx, instance.name, node, wipe_chunk_size)
6989

    
6990
      offset = 0
6991
      size = device.size
6992
      last_output = 0
6993
      start_time = time.time()
6994

    
6995
      while offset < size:
6996
        wipe_size = min(wipe_chunk_size, size - offset)
6997
        logging.debug("Wiping disk %d, offset %s, chunk %s",
6998
                      idx, offset, wipe_size)
6999
        result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
7000
        result.Raise("Could not wipe disk %d at offset %d for size %d" %
7001
                     (idx, offset, wipe_size))
7002
        now = time.time()
7003
        offset += wipe_size
7004
        if now - last_output >= 60:
7005
          eta = _CalcEta(now - start_time, offset, size)
7006
          lu.LogInfo(" - done: %.1f%% ETA: %s" %
7007
                     (offset / float(size) * 100, utils.FormatSeconds(eta)))
7008
          last_output = now
7009
  finally:
7010
    logging.info("Resume sync of instance %s disks", instance.name)
7011

    
7012
    result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, False)
7013

    
7014
    for idx, success in enumerate(result.payload):
7015
      if not success:
7016
        lu.LogWarning("Warning: Resume sync of disk %d failed. Please have a"
7017
                      " look at the status and troubleshoot the issue.", idx)
7018
        logging.warn("resume-sync of instance %s for disks %d failed",
7019
                     instance.name, idx)
7020

    
7021

    
7022
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
7023
  """Create all disks for an instance.
7024

7025
  This abstracts away some work from AddInstance.
7026

7027
  @type lu: L{LogicalUnit}
7028
  @param lu: the logical unit on whose behalf we execute
7029
  @type instance: L{objects.Instance}
7030
  @param instance: the instance whose disks we should create
7031
  @type to_skip: list
7032
  @param to_skip: list of indices to skip
7033
  @type target_node: string
7034
  @param target_node: if passed, overrides the target node for creation
7035
  @rtype: boolean
7036
  @return: the success of the creation
7037

7038
  """
7039
  info = _GetInstanceInfoText(instance)
7040
  if target_node is None:
7041
    pnode = instance.primary_node
7042
    all_nodes = instance.all_nodes
7043
  else:
7044
    pnode = target_node
7045
    all_nodes = [pnode]
7046

    
7047
  if instance.disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE):
7048
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7049
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
7050

    
7051
    result.Raise("Failed to create directory '%s' on"
7052
                 " node %s" % (file_storage_dir, pnode))
7053

    
7054
  # Note: this needs to be kept in sync with adding of disks in
7055
  # LUInstanceSetParams
7056
  for idx, device in enumerate(instance.disks):
7057
    if to_skip and idx in to_skip:
7058
      continue
7059
    logging.info("Creating volume %s for instance %s",
7060
                 device.iv_name, instance.name)
7061
    #HARDCODE
7062
    for node in all_nodes:
7063
      f_create = node == pnode
7064
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
7065

    
7066

    
7067
def _RemoveDisks(lu, instance, target_node=None):
7068
  """Remove all disks for an instance.
7069

7070
  This abstracts away some work from `AddInstance()` and
7071
  `RemoveInstance()`. Note that in case some of the devices couldn't
7072
  be removed, the removal will continue with the other ones (compare
7073
  with `_CreateDisks()`).
7074

7075
  @type lu: L{LogicalUnit}
7076
  @param lu: the logical unit on whose behalf we execute
7077
  @type instance: L{objects.Instance}
7078
  @param instance: the instance whose disks we should remove
7079
  @type target_node: string
7080
  @param target_node: used to override the node on which to remove the disks
7081
  @rtype: boolean
7082
  @return: the success of the removal
7083

7084
  """
7085
  logging.info("Removing block devices for instance %s", instance.name)
7086

    
7087
  all_result = True
7088
  for device in instance.disks:
7089
    if target_node:
7090
      edata = [(target_node, device)]
7091
    else:
7092
      edata = device.ComputeNodeTree(instance.primary_node)
7093
    for node, disk in edata:
7094
      lu.cfg.SetDiskID(disk, node)
7095
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
7096
      if msg:
7097
        lu.LogWarning("Could not remove block device %s on node %s,"
7098
                      " continuing anyway: %s", device.iv_name, node, msg)
7099
        all_result = False
7100

    
7101
  if instance.disk_template == constants.DT_FILE:
7102
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7103
    if target_node:
7104
      tgt = target_node
7105
    else:
7106
      tgt = instance.primary_node
7107
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
7108
    if result.fail_msg:
7109
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
7110
                    file_storage_dir, instance.primary_node, result.fail_msg)
7111
      all_result = False
7112

    
7113
  return all_result
7114

    
7115

    
7116
def _ComputeDiskSizePerVG(disk_template, disks):
7117
  """Compute disk size requirements in the volume group
7118

7119
  """
7120
  def _compute(disks, payload):
7121
    """Universal algorithm
7122

7123
    """
7124
    vgs = {}
7125
    for disk in disks:
7126
      vgs[disk["vg"]] = vgs.get("vg", 0) + disk["size"] + payload
7127

    
7128
    return vgs
7129

    
7130
  # Required free disk space as a function of disk and swap space
7131
  req_size_dict = {
7132
    constants.DT_DISKLESS: {},
7133
    constants.DT_PLAIN: _compute(disks, 0),
7134
    # 128 MB are added for drbd metadata for each disk
7135
    constants.DT_DRBD8: _compute(disks, 128),
7136
    constants.DT_FILE: {},
7137
    constants.DT_SHARED_FILE: {},
7138
  }
7139

    
7140
  if disk_template not in req_size_dict:
7141
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7142
                                 " is unknown" %  disk_template)
7143

    
7144
  return req_size_dict[disk_template]
7145

    
7146

    
7147
def _ComputeDiskSize(disk_template, disks):
7148
  """Compute disk size requirements in the volume group
7149

7150
  """
7151
  # Required free disk space as a function of disk and swap space
7152
  req_size_dict = {
7153
    constants.DT_DISKLESS: None,
7154
    constants.DT_PLAIN: sum(d["size"] for d in disks),
7155
    # 128 MB are added for drbd metadata for each disk
7156
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
7157
    constants.DT_FILE: None,
7158
    constants.DT_SHARED_FILE: 0,
7159
    constants.DT_BLOCK: 0,
7160
  }
7161

    
7162
  if disk_template not in req_size_dict:
7163
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7164
                                 " is unknown" %  disk_template)
7165

    
7166
  return req_size_dict[disk_template]
7167

    
7168

    
7169
def _FilterVmNodes(lu, nodenames):
7170
  """Filters out non-vm_capable nodes from a list.
7171

7172
  @type lu: L{LogicalUnit}
7173
  @param lu: the logical unit for which we check
7174
  @type nodenames: list
7175
  @param nodenames: the list of nodes on which we should check
7176
  @rtype: list
7177
  @return: the list of vm-capable nodes
7178

7179
  """
7180
  vm_nodes = frozenset(lu.cfg.GetNonVmCapableNodeList())
7181
  return [name for name in nodenames if name not in vm_nodes]
7182

    
7183

    
7184
def _CheckHVParams(lu, nodenames, hvname, hvparams):
7185
  """Hypervisor parameter validation.
7186

7187
  This function abstract the hypervisor parameter validation to be
7188
  used in both instance create and instance modify.
7189

7190
  @type lu: L{LogicalUnit}
7191
  @param lu: the logical unit for which we check
7192
  @type nodenames: list
7193
  @param nodenames: the list of nodes on which we should check
7194
  @type hvname: string
7195
  @param hvname: the name of the hypervisor we should use
7196
  @type hvparams: dict
7197
  @param hvparams: the parameters which we need to check
7198
  @raise errors.OpPrereqError: if the parameters are not valid
7199

7200
  """
7201
  nodenames = _FilterVmNodes(lu, nodenames)
7202
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
7203
                                                  hvname,
7204
                                                  hvparams)
7205
  for node in nodenames:
7206
    info = hvinfo[node]
7207
    if info.offline:
7208
      continue
7209
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
7210

    
7211

    
7212
def _CheckOSParams(lu, required, nodenames, osname, osparams):
7213
  """OS parameters validation.
7214

7215
  @type lu: L{LogicalUnit}
7216
  @param lu: the logical unit for which we check
7217
  @type required: boolean
7218
  @param required: whether the validation should fail if the OS is not
7219
      found
7220
  @type nodenames: list
7221
  @param nodenames: the list of nodes on which we should check
7222
  @type osname: string
7223
  @param osname: the name of the hypervisor we should use
7224
  @type osparams: dict
7225
  @param osparams: the parameters which we need to check
7226
  @raise errors.OpPrereqError: if the parameters are not valid
7227

7228
  """
7229
  nodenames = _FilterVmNodes(lu, nodenames)
7230
  result = lu.rpc.call_os_validate(required, nodenames, osname,
7231
                                   [constants.OS_VALIDATE_PARAMETERS],
7232
                                   osparams)
7233
  for node, nres in result.items():
7234
    # we don't check for offline cases since this should be run only
7235
    # against the master node and/or an instance's nodes
7236
    nres.Raise("OS Parameters validation failed on node %s" % node)
7237
    if not nres.payload:
7238
      lu.LogInfo("OS %s not found on node %s, validation skipped",
7239
                 osname, node)
7240

    
7241

    
7242
class LUInstanceCreate(LogicalUnit):
7243
  """Create an instance.
7244

7245
  """
7246
  HPATH = "instance-add"
7247
  HTYPE = constants.HTYPE_INSTANCE
7248
  REQ_BGL = False
7249

    
7250
  def CheckArguments(self):
7251
    """Check arguments.
7252

7253
    """
7254
    # do not require name_check to ease forward/backward compatibility
7255
    # for tools
7256
    if self.op.no_install and self.op.start:
7257
      self.LogInfo("No-installation mode selected, disabling startup")
7258
      self.op.start = False
7259
    # validate/normalize the instance name
7260
    self.op.instance_name = \
7261
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
7262

    
7263
    if self.op.ip_check and not self.op.name_check:
7264
      # TODO: make the ip check more flexible and not depend on the name check
7265
      raise errors.OpPrereqError("Cannot do ip check without a name check",
7266
                                 errors.ECODE_INVAL)
7267

    
7268
    # check nics' parameter names
7269
    for nic in self.op.nics:
7270
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
7271

    
7272
    # check disks. parameter names and consistent adopt/no-adopt strategy
7273
    has_adopt = has_no_adopt = False
7274
    for disk in self.op.disks:
7275
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
7276
      if "adopt" in disk:
7277
        has_adopt = True
7278
      else:
7279
        has_no_adopt = True
7280
    if has_adopt and has_no_adopt:
7281
      raise errors.OpPrereqError("Either all disks are adopted or none is",
7282
                                 errors.ECODE_INVAL)
7283
    if has_adopt:
7284
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
7285
        raise errors.OpPrereqError("Disk adoption is not supported for the"
7286
                                   " '%s' disk template" %
7287
                                   self.op.disk_template,
7288
                                   errors.ECODE_INVAL)
7289
      if self.op.iallocator is not None:
7290
        raise errors.OpPrereqError("Disk adoption not allowed with an"
7291
                                   " iallocator script", errors.ECODE_INVAL)
7292
      if self.op.mode == constants.INSTANCE_IMPORT:
7293
        raise errors.OpPrereqError("Disk adoption not allowed for"
7294
                                   " instance import", errors.ECODE_INVAL)
7295
    else:
7296
      if self.op.disk_template in constants.DTS_MUST_ADOPT:
7297
        raise errors.OpPrereqError("Disk template %s requires disk adoption,"
7298
                                   " but no 'adopt' parameter given" %
7299
                                   self.op.disk_template,
7300
                                   errors.ECODE_INVAL)
7301

    
7302
    self.adopt_disks = has_adopt
7303

    
7304
    # instance name verification
7305
    if self.op.name_check:
7306
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
7307
      self.op.instance_name = self.hostname1.name
7308
      # used in CheckPrereq for ip ping check
7309
      self.check_ip = self.hostname1.ip
7310
    else:
7311
      self.check_ip = None
7312

    
7313
    # file storage checks
7314
    if (self.op.file_driver and
7315
        not self.op.file_driver in constants.FILE_DRIVER):
7316
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
7317
                                 self.op.file_driver, errors.ECODE_INVAL)
7318

    
7319
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
7320
      raise errors.OpPrereqError("File storage directory path not absolute",
7321
                                 errors.ECODE_INVAL)
7322

    
7323
    ### Node/iallocator related checks
7324
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
7325

    
7326
    if self.op.pnode is not None:
7327
      if self.op.disk_template in constants.DTS_INT_MIRROR:
7328
        if self.op.snode is None:
7329
          raise errors.OpPrereqError("The networked disk templates need"
7330
                                     " a mirror node", errors.ECODE_INVAL)
7331
      elif self.op.snode:
7332
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
7333
                        " template")
7334
        self.op.snode = None
7335

    
7336
    self._cds = _GetClusterDomainSecret()
7337

    
7338
    if self.op.mode == constants.INSTANCE_IMPORT:
7339
      # On import force_variant must be True, because if we forced it at
7340
      # initial install, our only chance when importing it back is that it
7341
      # works again!
7342
      self.op.force_variant = True
7343

    
7344
      if self.op.no_install:
7345
        self.LogInfo("No-installation mode has no effect during import")
7346

    
7347
    elif self.op.mode == constants.INSTANCE_CREATE:
7348
      if self.op.os_type is None:
7349
        raise errors.OpPrereqError("No guest OS specified",
7350
                                   errors.ECODE_INVAL)
7351
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
7352
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
7353
                                   " installation" % self.op.os_type,
7354
                                   errors.ECODE_STATE)
7355
      if self.op.disk_template is None:
7356
        raise errors.OpPrereqError("No disk template specified",
7357
                                   errors.ECODE_INVAL)
7358

    
7359
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7360
      # Check handshake to ensure both clusters have the same domain secret
7361
      src_handshake = self.op.source_handshake
7362
      if not src_handshake:
7363
        raise errors.OpPrereqError("Missing source handshake",
7364
                                   errors.ECODE_INVAL)
7365

    
7366
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
7367
                                                           src_handshake)
7368
      if errmsg:
7369
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
7370
                                   errors.ECODE_INVAL)
7371

    
7372
      # Load and check source CA
7373
      self.source_x509_ca_pem = self.op.source_x509_ca
7374
      if not self.source_x509_ca_pem:
7375
        raise errors.OpPrereqError("Missing source X509 CA",
7376
                                   errors.ECODE_INVAL)
7377

    
7378
      try:
7379
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
7380
                                                    self._cds)
7381
      except OpenSSL.crypto.Error, err:
7382
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
7383
                                   (err, ), errors.ECODE_INVAL)
7384

    
7385
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
7386
      if errcode is not None:
7387
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
7388
                                   errors.ECODE_INVAL)
7389

    
7390
      self.source_x509_ca = cert
7391

    
7392
      src_instance_name = self.op.source_instance_name
7393
      if not src_instance_name:
7394
        raise errors.OpPrereqError("Missing source instance name",
7395
                                   errors.ECODE_INVAL)
7396

    
7397
      self.source_instance_name = \
7398
          netutils.GetHostname(name=src_instance_name).name
7399

    
7400
    else:
7401
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
7402
                                 self.op.mode, errors.ECODE_INVAL)
7403

    
7404
  def ExpandNames(self):
7405
    """ExpandNames for CreateInstance.
7406

7407
    Figure out the right locks for instance creation.
7408

7409
    """
7410
    self.needed_locks = {}
7411

    
7412
    instance_name = self.op.instance_name
7413
    # this is just a preventive check, but someone might still add this
7414
    # instance in the meantime, and creation will fail at lock-add time
7415
    if instance_name in self.cfg.GetInstanceList():
7416
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
7417
                                 instance_name, errors.ECODE_EXISTS)
7418

    
7419
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
7420

    
7421
    if self.op.iallocator:
7422
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7423
    else:
7424
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
7425
      nodelist = [self.op.pnode]
7426
      if self.op.snode is not None:
7427
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
7428
        nodelist.append(self.op.snode)
7429
      self.needed_locks[locking.LEVEL_NODE] = nodelist
7430

    
7431
    # in case of import lock the source node too
7432
    if self.op.mode == constants.INSTANCE_IMPORT:
7433
      src_node = self.op.src_node
7434
      src_path = self.op.src_path
7435

    
7436
      if src_path is None:
7437
        self.op.src_path = src_path = self.op.instance_name
7438

    
7439
      if src_node is None:
7440
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7441
        self.op.src_node = None
7442
        if os.path.isabs(src_path):
7443
          raise errors.OpPrereqError("Importing an instance from an absolute"
7444
                                     " path requires a source node option.",
7445
                                     errors.ECODE_INVAL)
7446
      else:
7447
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
7448
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
7449
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
7450
        if not os.path.isabs(src_path):
7451
          self.op.src_path = src_path = \
7452
            utils.PathJoin(constants.EXPORT_DIR, src_path)
7453

    
7454
  def _RunAllocator(self):
7455
    """Run the allocator based on input opcode.
7456

7457
    """
7458
    nics = [n.ToDict() for n in self.nics]
7459
    ial = IAllocator(self.cfg, self.rpc,
7460
                     mode=constants.IALLOCATOR_MODE_ALLOC,
7461
                     name=self.op.instance_name,
7462
                     disk_template=self.op.disk_template,
7463
                     tags=[],
7464
                     os=self.op.os_type,
7465
                     vcpus=self.be_full[constants.BE_VCPUS],
7466
                     mem_size=self.be_full[constants.BE_MEMORY],
7467
                     disks=self.disks,
7468
                     nics=nics,
7469
                     hypervisor=self.op.hypervisor,
7470
                     )
7471

    
7472
    ial.Run(self.op.iallocator)
7473

    
7474
    if not ial.success:
7475
      raise errors.OpPrereqError("Can't compute nodes using"
7476
                                 " iallocator '%s': %s" %
7477
                                 (self.op.iallocator, ial.info),
7478
                                 errors.ECODE_NORES)
7479
    if len(ial.result) != ial.required_nodes:
7480
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7481
                                 " of nodes (%s), required %s" %
7482
                                 (self.op.iallocator, len(ial.result),
7483
                                  ial.required_nodes), errors.ECODE_FAULT)
7484
    self.op.pnode = ial.result[0]
7485
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
7486
                 self.op.instance_name, self.op.iallocator,
7487
                 utils.CommaJoin(ial.result))
7488
    if ial.required_nodes == 2:
7489
      self.op.snode = ial.result[1]
7490

    
7491
  def BuildHooksEnv(self):
7492
    """Build hooks env.
7493

7494
    This runs on master, primary and secondary nodes of the instance.
7495

7496
    """
7497
    env = {
7498
      "ADD_MODE": self.op.mode,
7499
      }
7500
    if self.op.mode == constants.INSTANCE_IMPORT:
7501
      env["SRC_NODE"] = self.op.src_node
7502
      env["SRC_PATH"] = self.op.src_path
7503
      env["SRC_IMAGES"] = self.src_images
7504

    
7505
    env.update(_BuildInstanceHookEnv(
7506
      name=self.op.instance_name,
7507
      primary_node=self.op.pnode,
7508
      secondary_nodes=self.secondaries,
7509
      status=self.op.start,
7510
      os_type=self.op.os_type,
7511
      memory=self.be_full[constants.BE_MEMORY],
7512
      vcpus=self.be_full[constants.BE_VCPUS],
7513
      nics=_NICListToTuple(self, self.nics),
7514
      disk_template=self.op.disk_template,
7515
      disks=[(d["size"], d["mode"]) for d in self.disks],
7516
      bep=self.be_full,
7517
      hvp=self.hv_full,
7518
      hypervisor_name=self.op.hypervisor,
7519
    ))
7520

    
7521
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
7522
          self.secondaries)
7523
    return env, nl, nl
7524

    
7525
  def _ReadExportInfo(self):
7526
    """Reads the export information from disk.
7527

7528
    It will override the opcode source node and path with the actual
7529
    information, if these two were not specified before.
7530

7531
    @return: the export information
7532

7533
    """
7534
    assert self.op.mode == constants.INSTANCE_IMPORT
7535

    
7536
    src_node = self.op.src_node
7537
    src_path = self.op.src_path
7538

    
7539
    if src_node is None:
7540
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
7541
      exp_list = self.rpc.call_export_list(locked_nodes)
7542
      found = False
7543
      for node in exp_list:
7544
        if exp_list[node].fail_msg:
7545
          continue
7546
        if src_path in exp_list[node].payload:
7547
          found = True
7548
          self.op.src_node = src_node = node
7549
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
7550
                                                       src_path)
7551
          break
7552
      if not found:
7553
        raise errors.OpPrereqError("No export found for relative path %s" %
7554
                                    src_path, errors.ECODE_INVAL)
7555

    
7556
    _CheckNodeOnline(self, src_node)
7557
    result = self.rpc.call_export_info(src_node, src_path)
7558
    result.Raise("No export or invalid export found in dir %s" % src_path)
7559

    
7560
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
7561
    if not export_info.has_section(constants.INISECT_EXP):
7562
      raise errors.ProgrammerError("Corrupted export config",
7563
                                   errors.ECODE_ENVIRON)
7564

    
7565
    ei_version = export_info.get(constants.INISECT_EXP, "version")
7566
    if (int(ei_version) != constants.EXPORT_VERSION):
7567
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
7568
                                 (ei_version, constants.EXPORT_VERSION),
7569
                                 errors.ECODE_ENVIRON)
7570
    return export_info
7571

    
7572
  def _ReadExportParams(self, einfo):
7573
    """Use export parameters as defaults.
7574

7575
    In case the opcode doesn't specify (as in override) some instance
7576
    parameters, then try to use them from the export information, if
7577
    that declares them.
7578

7579
    """
7580
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
7581

    
7582
    if self.op.disk_template is None:
7583
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
7584
        self.op.disk_template = einfo.get(constants.INISECT_INS,
7585
                                          "disk_template")
7586
      else:
7587
        raise errors.OpPrereqError("No disk template specified and the export"
7588
                                   " is missing the disk_template information",
7589
                                   errors.ECODE_INVAL)
7590

    
7591
    if not self.op.disks:
7592
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
7593
        disks = []
7594
        # TODO: import the disk iv_name too
7595
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
7596
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
7597
          disks.append({"size": disk_sz})
7598
        self.op.disks = disks
7599
      else:
7600
        raise errors.OpPrereqError("No disk info specified and the export"
7601
                                   " is missing the disk information",
7602
                                   errors.ECODE_INVAL)
7603

    
7604
    if (not self.op.nics and
7605
        einfo.has_option(constants.INISECT_INS, "nic_count")):
7606
      nics = []
7607
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
7608
        ndict = {}
7609
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
7610
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
7611
          ndict[name] = v
7612
        nics.append(ndict)
7613
      self.op.nics = nics
7614

    
7615
    if (self.op.hypervisor is None and
7616
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
7617
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
7618
    if einfo.has_section(constants.INISECT_HYP):
7619
      # use the export parameters but do not override the ones
7620
      # specified by the user
7621
      for name, value in einfo.items(constants.INISECT_HYP):
7622
        if name not in self.op.hvparams:
7623
          self.op.hvparams[name] = value
7624

    
7625
    if einfo.has_section(constants.INISECT_BEP):
7626
      # use the parameters, without overriding
7627
      for name, value in einfo.items(constants.INISECT_BEP):
7628
        if name not in self.op.beparams:
7629
          self.op.beparams[name] = value
7630
    else:
7631
      # try to read the parameters old style, from the main section
7632
      for name in constants.BES_PARAMETERS:
7633
        if (name not in self.op.beparams and
7634
            einfo.has_option(constants.INISECT_INS, name)):
7635
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
7636

    
7637
    if einfo.has_section(constants.INISECT_OSP):
7638
      # use the parameters, without overriding
7639
      for name, value in einfo.items(constants.INISECT_OSP):
7640
        if name not in self.op.osparams:
7641
          self.op.osparams[name] = value
7642

    
7643
  def _RevertToDefaults(self, cluster):
7644
    """Revert the instance parameters to the default values.
7645

7646
    """
7647
    # hvparams
7648
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
7649
    for name in self.op.hvparams.keys():
7650
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
7651
        del self.op.hvparams[name]
7652
    # beparams
7653
    be_defs = cluster.SimpleFillBE({})
7654
    for name in self.op.beparams.keys():
7655
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
7656
        del self.op.beparams[name]
7657
    # nic params
7658
    nic_defs = cluster.SimpleFillNIC({})
7659
    for nic in self.op.nics:
7660
      for name in constants.NICS_PARAMETERS:
7661
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
7662
          del nic[name]
7663
    # osparams
7664
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
7665
    for name in self.op.osparams.keys():
7666
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
7667
        del self.op.osparams[name]
7668

    
7669
  def CheckPrereq(self):
7670
    """Check prerequisites.
7671

7672
    """
7673
    if self.op.mode == constants.INSTANCE_IMPORT:
7674
      export_info = self._ReadExportInfo()
7675
      self._ReadExportParams(export_info)
7676

    
7677
    if (not self.cfg.GetVGName() and
7678
        self.op.disk_template not in constants.DTS_NOT_LVM):
7679
      raise errors.OpPrereqError("Cluster does not support lvm-based"
7680
                                 " instances", errors.ECODE_STATE)
7681

    
7682
    if self.op.hypervisor is None:
7683
      self.op.hypervisor = self.cfg.GetHypervisorType()
7684

    
7685
    cluster = self.cfg.GetClusterInfo()
7686
    enabled_hvs = cluster.enabled_hypervisors
7687
    if self.op.hypervisor not in enabled_hvs:
7688
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
7689
                                 " cluster (%s)" % (self.op.hypervisor,
7690
                                  ",".join(enabled_hvs)),
7691
                                 errors.ECODE_STATE)
7692

    
7693
    # check hypervisor parameter syntax (locally)
7694
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
7695
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
7696
                                      self.op.hvparams)
7697
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
7698
    hv_type.CheckParameterSyntax(filled_hvp)
7699
    self.hv_full = filled_hvp
7700
    # check that we don't specify global parameters on an instance
7701
    _CheckGlobalHvParams(self.op.hvparams)
7702

    
7703
    # fill and remember the beparams dict
7704
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
7705
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
7706

    
7707
    # build os parameters
7708
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
7709

    
7710
    # now that hvp/bep are in final format, let's reset to defaults,
7711
    # if told to do so
7712
    if self.op.identify_defaults:
7713
      self._RevertToDefaults(cluster)
7714

    
7715
    # NIC buildup
7716
    self.nics = []
7717
    for idx, nic in enumerate(self.op.nics):
7718
      nic_mode_req = nic.get("mode", None)
7719
      nic_mode = nic_mode_req
7720
      if nic_mode is None:
7721
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
7722

    
7723
      # bridge verification
7724
      bridge = nic.get("bridge", None)
7725
      link = nic.get("link", None)
7726
      if bridge and link:
7727
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7728
                                   " at the same time", errors.ECODE_INVAL)
7729
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7730
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7731
                                   errors.ECODE_INVAL)
7732
      elif bridge:
7733
        link = bridge
7734

    
7735
      nicparams = {}
7736
      if nic_mode_req:
7737
        nicparams[constants.NIC_MODE] = nic_mode_req
7738
      if link:
7739
        nicparams[constants.NIC_LINK] = link
7740

    
7741
      # in routed mode, for the first nic, the default ip is 'auto'
7742
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
7743
        default_ip_mode = constants.VALUE_AUTO
7744
      else:
7745
        default_ip_mode = constants.VALUE_NONE
7746

    
7747
      # ip validity checks
7748
      ip = nic.get("ip", default_ip_mode)
7749
      if ip is None or ip.lower() == constants.VALUE_NONE:
7750
        nic_ip = None
7751
      elif ip.lower() == constants.VALUE_AUTO:
7752
        if not self.op.name_check:
7753
          raise errors.OpPrereqError("IP address set to auto but name checks"
7754
                                     " have been skipped",
7755
                                     errors.ECODE_INVAL)
7756
        nic_ip = self.hostname1.ip
7757
        try:
7758
          self.cfg.ReserveIp(link, nic_ip, self.proc.GetECId())
7759
        except errors.ReservationError:
7760
          raise errors.OpPrereqError("IP address %s already in use"
7761
                                     " in cluster" % nic_ip,
7762
                                     errors.ECODE_NOTUNIQUE)
7763
      elif ip.lower() == constants.NIC_IP_POOL:
7764
        nic_ip = self.cfg.GenerateIp(link, self.proc.GetECId())
7765
        logging.info("Chose ip %s from pool %s" % (nic_ip, link))
7766
      else:
7767
        if not netutils.IPAddress.IsValid(ip):
7768
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
7769
                                     errors.ECODE_INVAL)
7770
        nic_ip = ip
7771
        try:
7772
          self.cfg.ReserveIp(link, nic_ip, self.proc.GetECId())
7773
        except errors.ReservationError:
7774
          raise errors.OpPrereqError("IP address %s already in use"
7775
                                     " in cluster" % nic_ip,
7776
                                     errors.ECODE_NOTUNIQUE)
7777

    
7778
      # TODO: check the ip address for uniqueness
7779
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7780
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7781
                                   errors.ECODE_INVAL)
7782

    
7783
      # MAC address verification
7784
      mac = nic.get("mac", constants.VALUE_AUTO)
7785
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7786
        mac = utils.NormalizeAndValidateMac(mac)
7787

    
7788
        try:
7789
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7790
        except errors.ReservationError:
7791
          raise errors.OpPrereqError("MAC address %s already in use"
7792
                                     " in cluster" % mac,
7793
                                     errors.ECODE_NOTUNIQUE)
7794

    
7795
      check_params = cluster.SimpleFillNIC(nicparams)
7796
      objects.NIC.CheckParameterSyntax(check_params)
7797
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7798

    
7799
    # disk checks/pre-build
7800
    self.disks = []
7801
    for disk in self.op.disks:
7802
      mode = disk.get("mode", constants.DISK_RDWR)
7803
      if mode not in constants.DISK_ACCESS_SET:
7804
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7805
                                   mode, errors.ECODE_INVAL)
7806
      size = disk.get("size", None)
7807
      if size is None:
7808
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7809
      try:
7810
        size = int(size)
7811
      except (TypeError, ValueError):
7812
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7813
                                   errors.ECODE_INVAL)
7814
      data_vg = disk.get("vg", self.cfg.GetVGName())
7815
      meta_vg = disk.get("metavg", data_vg)
7816
      new_disk = {"size": size, "mode": mode, "vg": data_vg, "metavg": meta_vg}
7817
      if "adopt" in disk:
7818
        new_disk["adopt"] = disk["adopt"]
7819
      self.disks.append(new_disk)
7820

    
7821
    if self.op.mode == constants.INSTANCE_IMPORT:
7822

    
7823
      # Check that the new instance doesn't have less disks than the export
7824
      instance_disks = len(self.disks)
7825
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7826
      if instance_disks < export_disks:
7827
        raise errors.OpPrereqError("Not enough disks to import."
7828
                                   " (instance: %d, export: %d)" %
7829
                                   (instance_disks, export_disks),
7830
                                   errors.ECODE_INVAL)
7831

    
7832
      disk_images = []
7833
      for idx in range(export_disks):
7834
        option = 'disk%d_dump' % idx
7835
        if export_info.has_option(constants.INISECT_INS, option):
7836
          # FIXME: are the old os-es, disk sizes, etc. useful?
7837
          export_name = export_info.get(constants.INISECT_INS, option)
7838
          image = utils.PathJoin(self.op.src_path, export_name)
7839
          disk_images.append(image)
7840
        else:
7841
          disk_images.append(False)
7842

    
7843
      self.src_images = disk_images
7844

    
7845
      old_name = export_info.get(constants.INISECT_INS, 'name')
7846
      try:
7847
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7848
      except (TypeError, ValueError), err:
7849
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7850
                                   " an integer: %s" % str(err),
7851
                                   errors.ECODE_STATE)
7852
      if self.op.instance_name == old_name:
7853
        for idx, nic in enumerate(self.nics):
7854
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7855
            nic_mac_ini = 'nic%d_mac' % idx
7856
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7857

    
7858
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7859

    
7860
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7861
    if self.op.ip_check:
7862
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7863
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7864
                                   (self.check_ip, self.op.instance_name),
7865
                                   errors.ECODE_NOTUNIQUE)
7866

    
7867
    #### mac address generation
7868
    # By generating here the mac address both the allocator and the hooks get
7869
    # the real final mac address rather than the 'auto' or 'generate' value.
7870
    # There is a race condition between the generation and the instance object
7871
    # creation, which means that we know the mac is valid now, but we're not
7872
    # sure it will be when we actually add the instance. If things go bad
7873
    # adding the instance will abort because of a duplicate mac, and the
7874
    # creation job will fail.
7875
    for nic in self.nics:
7876
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7877
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7878

    
7879
    #### allocator run
7880

    
7881
    if self.op.iallocator is not None:
7882
      self._RunAllocator()
7883

    
7884
    #### node related checks
7885

    
7886
    # check primary node
7887
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7888
    assert self.pnode is not None, \
7889
      "Cannot retrieve locked node %s" % self.op.pnode
7890
    if pnode.offline:
7891
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7892
                                 pnode.name, errors.ECODE_STATE)
7893
    if pnode.drained:
7894
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7895
                                 pnode.name, errors.ECODE_STATE)
7896
    if not pnode.vm_capable:
7897
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
7898
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
7899

    
7900
    self.secondaries = []
7901

    
7902
    # mirror node verification
7903
    if self.op.disk_template in constants.DTS_INT_MIRROR:
7904
      if self.op.snode == pnode.name:
7905
        raise errors.OpPrereqError("The secondary node cannot be the"
7906
                                   " primary node.", errors.ECODE_INVAL)
7907
      _CheckNodeOnline(self, self.op.snode)
7908
      _CheckNodeNotDrained(self, self.op.snode)
7909
      _CheckNodeVmCapable(self, self.op.snode)
7910
      self.secondaries.append(self.op.snode)
7911

    
7912
    nodenames = [pnode.name] + self.secondaries
7913

    
7914
    if not self.adopt_disks:
7915
      # Check lv size requirements, if not adopting
7916
      req_sizes = _ComputeDiskSizePerVG(self.op.disk_template, self.disks)
7917
      _CheckNodesFreeDiskPerVG(self, nodenames, req_sizes)
7918

    
7919
    elif self.op.disk_template == constants.DT_PLAIN: # Check the adoption data
7920
      all_lvs = set([i["vg"] + "/" + i["adopt"] for i in self.disks])
7921
      if len(all_lvs) != len(self.disks):
7922
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7923
                                   errors.ECODE_INVAL)
7924
      for lv_name in all_lvs:
7925
        try:
7926
          # FIXME: lv_name here is "vg/lv" need to ensure that other calls
7927
          # to ReserveLV uses the same syntax
7928
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7929
        except errors.ReservationError:
7930
          raise errors.OpPrereqError("LV named %s used by another instance" %
7931
                                     lv_name, errors.ECODE_NOTUNIQUE)
7932

    
7933
      vg_names = self.rpc.call_vg_list([pnode.name])[pnode.name]
7934
      vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
7935

    
7936
      node_lvs = self.rpc.call_lv_list([pnode.name],
7937
                                       vg_names.payload.keys())[pnode.name]
7938
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7939
      node_lvs = node_lvs.payload
7940

    
7941
      delta = all_lvs.difference(node_lvs.keys())
7942
      if delta:
7943
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7944
                                   utils.CommaJoin(delta),
7945
                                   errors.ECODE_INVAL)
7946
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7947
      if online_lvs:
7948
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7949
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7950
                                   errors.ECODE_STATE)
7951
      # update the size of disk based on what is found
7952
      for dsk in self.disks:
7953
        dsk["size"] = int(float(node_lvs[dsk["vg"] + "/" + dsk["adopt"]][0]))
7954

    
7955
    elif self.op.disk_template == constants.DT_BLOCK:
7956
      # Normalize and de-duplicate device paths
7957
      all_disks = set([os.path.abspath(i["adopt"]) for i in self.disks])
7958
      if len(all_disks) != len(self.disks):
7959
        raise errors.OpPrereqError("Duplicate disk names given for adoption",
7960
                                   errors.ECODE_INVAL)
7961
      baddisks = [d for d in all_disks
7962
                  if not d.startswith(constants.ADOPTABLE_BLOCKDEV_ROOT)]
7963
      if baddisks:
7964
        raise errors.OpPrereqError("Device node(s) %s lie outside %s and"
7965
                                   " cannot be adopted" %
7966
                                   (", ".join(baddisks),
7967
                                    constants.ADOPTABLE_BLOCKDEV_ROOT),
7968
                                   errors.ECODE_INVAL)
7969

    
7970
      node_disks = self.rpc.call_bdev_sizes([pnode.name],
7971
                                            list(all_disks))[pnode.name]
7972
      node_disks.Raise("Cannot get block device information from node %s" %
7973
                       pnode.name)
7974
      node_disks = node_disks.payload
7975
      delta = all_disks.difference(node_disks.keys())
7976
      if delta:
7977
        raise errors.OpPrereqError("Missing block device(s): %s" %
7978
                                   utils.CommaJoin(delta),
7979
                                   errors.ECODE_INVAL)
7980
      for dsk in self.disks:
7981
        dsk["size"] = int(float(node_disks[dsk["adopt"]]))
7982

    
7983
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7984

    
7985
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7986
    # check OS parameters (remotely)
7987
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7988

    
7989
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7990

    
7991
    # memory check on primary node
7992
    if self.op.start:
7993
      _CheckNodeFreeMemory(self, self.pnode.name,
7994
                           "creating instance %s" % self.op.instance_name,
7995
                           self.be_full[constants.BE_MEMORY],
7996
                           self.op.hypervisor)
7997

    
7998
    self.dry_run_result = list(nodenames)
7999

    
8000
  def Exec(self, feedback_fn):
8001
    """Create and add the instance to the cluster.
8002

8003
    """
8004
    instance = self.op.instance_name
8005
    pnode_name = self.pnode.name
8006

    
8007
    ht_kind = self.op.hypervisor
8008
    if ht_kind in constants.HTS_REQ_PORT:
8009
      network_port = self.cfg.AllocatePort()
8010
    else:
8011
      network_port = None
8012

    
8013
    if constants.ENABLE_FILE_STORAGE or constants.ENABLE_SHARED_FILE_STORAGE:
8014
      # this is needed because os.path.join does not accept None arguments
8015
      if self.op.file_storage_dir is None:
8016
        string_file_storage_dir = ""
8017
      else:
8018
        string_file_storage_dir = self.op.file_storage_dir
8019

    
8020
      # build the full file storage dir path
8021
      if self.op.disk_template == constants.DT_SHARED_FILE:
8022
        get_fsd_fn = self.cfg.GetSharedFileStorageDir
8023
      else:
8024
        get_fsd_fn = self.cfg.GetFileStorageDir
8025

    
8026
      file_storage_dir = utils.PathJoin(get_fsd_fn(),
8027
                                        string_file_storage_dir, instance)
8028
    else:
8029
      file_storage_dir = ""
8030

    
8031
    disks = _GenerateDiskTemplate(self,
8032
                                  self.op.disk_template,
8033
                                  instance, pnode_name,
8034
                                  self.secondaries,
8035
                                  self.disks,
8036
                                  file_storage_dir,
8037
                                  self.op.file_driver,
8038
                                  0,
8039
                                  feedback_fn)
8040

    
8041
    iobj = objects.Instance(name=instance, os=self.op.os_type,
8042
                            primary_node=pnode_name,
8043
                            nics=self.nics, disks=disks,
8044
                            disk_template=self.op.disk_template,
8045
                            admin_up=False,
8046
                            network_port=network_port,
8047
                            beparams=self.op.beparams,
8048
                            hvparams=self.op.hvparams,
8049
                            hypervisor=self.op.hypervisor,
8050
                            osparams=self.op.osparams,
8051
                            )
8052

    
8053
    if self.adopt_disks:
8054
      if self.op.disk_template == constants.DT_PLAIN:
8055
        # rename LVs to the newly-generated names; we need to construct
8056
        # 'fake' LV disks with the old data, plus the new unique_id
8057
        tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
8058
        rename_to = []
8059
        for t_dsk, a_dsk in zip (tmp_disks, self.disks):
8060
          rename_to.append(t_dsk.logical_id)
8061
          t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
8062
          self.cfg.SetDiskID(t_dsk, pnode_name)
8063
        result = self.rpc.call_blockdev_rename(pnode_name,
8064
                                               zip(tmp_disks, rename_to))
8065
        result.Raise("Failed to rename adoped LVs")
8066
    else:
8067
      feedback_fn("* creating instance disks...")
8068
      try:
8069
        _CreateDisks(self, iobj)
8070
      except errors.OpExecError:
8071
        self.LogWarning("Device creation failed, reverting...")
8072
        try:
8073
          _RemoveDisks(self, iobj)
8074
        finally:
8075
          self.cfg.ReleaseDRBDMinors(instance)
8076
          raise
8077

    
8078
    feedback_fn("adding instance %s to cluster config" % instance)
8079

    
8080
    self.cfg.AddInstance(iobj, self.proc.GetECId())
8081

    
8082
    # Declare that we don't want to remove the instance lock anymore, as we've
8083
    # added the instance to the config
8084
    del self.remove_locks[locking.LEVEL_INSTANCE]
8085
    # Unlock all the nodes
8086
    if self.op.mode == constants.INSTANCE_IMPORT:
8087
      nodes_keep = [self.op.src_node]
8088
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
8089
                       if node != self.op.src_node]
8090
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
8091
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
8092
    else:
8093
      self.context.glm.release(locking.LEVEL_NODE)
8094
      del self.acquired_locks[locking.LEVEL_NODE]
8095

    
8096
    disk_abort = False
8097
    if not self.adopt_disks and self.cfg.GetClusterInfo().prealloc_wipe_disks:
8098
      feedback_fn("* wiping instance disks...")
8099
      try:
8100
        _WipeDisks(self, iobj)
8101
      except errors.OpExecError, err:
8102
        logging.exception("Wiping disks failed")
8103
        self.LogWarning("Wiping instance disks failed (%s)", err)
8104
        disk_abort = True
8105

    
8106
    if disk_abort:
8107
      # Something is already wrong with the disks, don't do anything else
8108
      pass
8109
    elif self.op.wait_for_sync:
8110
      disk_abort = not _WaitForSync(self, iobj)
8111
    elif iobj.disk_template in constants.DTS_INT_MIRROR:
8112
      # make sure the disks are not degraded (still sync-ing is ok)
8113
      time.sleep(15)
8114
      feedback_fn("* checking mirrors status")
8115
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
8116
    else:
8117
      disk_abort = False
8118

    
8119
    if disk_abort:
8120
      _RemoveDisks(self, iobj)
8121
      self.cfg.RemoveInstance(iobj.name)
8122
      # Make sure the instance lock gets removed
8123
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
8124
      raise errors.OpExecError("There are some degraded disks for"
8125
                               " this instance")
8126

    
8127
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
8128
      if self.op.mode == constants.INSTANCE_CREATE:
8129
        if not self.op.no_install:
8130
          feedback_fn("* running the instance OS create scripts...")
8131
          # FIXME: pass debug option from opcode to backend
8132
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
8133
                                                 self.op.debug_level)
8134
          result.Raise("Could not add os for instance %s"
8135
                       " on node %s" % (instance, pnode_name))
8136

    
8137
      elif self.op.mode == constants.INSTANCE_IMPORT:
8138
        feedback_fn("* running the instance OS import scripts...")
8139

    
8140
        transfers = []
8141

    
8142
        for idx, image in enumerate(self.src_images):
8143
          if not image:
8144
            continue
8145

    
8146
          # FIXME: pass debug option from opcode to backend
8147
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
8148
                                             constants.IEIO_FILE, (image, ),
8149
                                             constants.IEIO_SCRIPT,
8150
                                             (iobj.disks[idx], idx),
8151
                                             None)
8152
          transfers.append(dt)
8153

    
8154
        import_result = \
8155
          masterd.instance.TransferInstanceData(self, feedback_fn,
8156
                                                self.op.src_node, pnode_name,
8157
                                                self.pnode.secondary_ip,
8158
                                                iobj, transfers)
8159
        if not compat.all(import_result):
8160
          self.LogWarning("Some disks for instance %s on node %s were not"
8161
                          " imported successfully" % (instance, pnode_name))
8162

    
8163
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
8164
        feedback_fn("* preparing remote import...")
8165
        # The source cluster will stop the instance before attempting to make a
8166
        # connection. In some cases stopping an instance can take a long time,
8167
        # hence the shutdown timeout is added to the connection timeout.
8168
        connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
8169
                           self.op.source_shutdown_timeout)
8170
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
8171

    
8172
        assert iobj.primary_node == self.pnode.name
8173
        disk_results = \
8174
          masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
8175
                                        self.source_x509_ca,
8176
                                        self._cds, timeouts)
8177
        if not compat.all(disk_results):
8178
          # TODO: Should the instance still be started, even if some disks
8179
          # failed to import (valid for local imports, too)?
8180
          self.LogWarning("Some disks for instance %s on node %s were not"
8181
                          " imported successfully" % (instance, pnode_name))
8182

    
8183
        # Run rename script on newly imported instance
8184
        assert iobj.name == instance
8185
        feedback_fn("Running rename script for %s" % instance)
8186
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
8187
                                                   self.source_instance_name,
8188
                                                   self.op.debug_level)
8189
        if result.fail_msg:
8190
          self.LogWarning("Failed to run rename script for %s on node"
8191
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
8192

    
8193
      else:
8194
        # also checked in the prereq part
8195
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
8196
                                     % self.op.mode)
8197

    
8198
    if self.op.start:
8199
      iobj.admin_up = True
8200
      self.cfg.Update(iobj, feedback_fn)
8201
      logging.info("Starting instance %s on node %s", instance, pnode_name)
8202
      feedback_fn("* starting instance...")
8203
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
8204
      result.Raise("Could not start instance")
8205

    
8206
    return list(iobj.all_nodes)
8207

    
8208

    
8209
class LUInstanceConsole(NoHooksLU):
8210
  """Connect to an instance's console.
8211

8212
  This is somewhat special in that it returns the command line that
8213
  you need to run on the master node in order to connect to the
8214
  console.
8215

8216
  """
8217
  REQ_BGL = False
8218

    
8219
  def ExpandNames(self):
8220
    self._ExpandAndLockInstance()
8221

    
8222
  def CheckPrereq(self):
8223
    """Check prerequisites.
8224

8225
    This checks that the instance is in the cluster.
8226

8227
    """
8228
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8229
    assert self.instance is not None, \
8230
      "Cannot retrieve locked instance %s" % self.op.instance_name
8231
    _CheckNodeOnline(self, self.instance.primary_node)
8232

    
8233
  def Exec(self, feedback_fn):
8234
    """Connect to the console of an instance
8235

8236
    """
8237
    instance = self.instance
8238
    node = instance.primary_node
8239

    
8240
    node_insts = self.rpc.call_instance_list([node],
8241
                                             [instance.hypervisor])[node]
8242
    node_insts.Raise("Can't get node information from %s" % node)
8243

    
8244
    if instance.name not in node_insts.payload:
8245
      if instance.admin_up:
8246
        state = "ERROR_down"
8247
      else:
8248
        state = "ADMIN_down"
8249
      raise errors.OpExecError("Instance %s is not running (state %s)" %
8250
                               (instance.name, state))
8251

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

    
8254
    return _GetInstanceConsole(self.cfg.GetClusterInfo(), instance)
8255

    
8256

    
8257
def _GetInstanceConsole(cluster, instance):
8258
  """Returns console information for an instance.
8259

8260
  @type cluster: L{objects.Cluster}
8261
  @type instance: L{objects.Instance}
8262
  @rtype: dict
8263

8264
  """
8265
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
8266
  # beparams and hvparams are passed separately, to avoid editing the
8267
  # instance and then saving the defaults in the instance itself.
8268
  hvparams = cluster.FillHV(instance)
8269
  beparams = cluster.FillBE(instance)
8270
  console = hyper.GetInstanceConsole(instance, hvparams, beparams)
8271

    
8272
  assert console.instance == instance.name
8273
  assert console.Validate()
8274

    
8275
  return console.ToDict()
8276

    
8277

    
8278
class LUInstanceReplaceDisks(LogicalUnit):
8279
  """Replace the disks of an instance.
8280

8281
  """
8282
  HPATH = "mirrors-replace"
8283
  HTYPE = constants.HTYPE_INSTANCE
8284
  REQ_BGL = False
8285

    
8286
  def CheckArguments(self):
8287
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
8288
                                  self.op.iallocator)
8289

    
8290
  def ExpandNames(self):
8291
    self._ExpandAndLockInstance()
8292

    
8293
    if self.op.iallocator is not None:
8294
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8295

    
8296
    elif self.op.remote_node is not None:
8297
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8298
      self.op.remote_node = remote_node
8299

    
8300
      # Warning: do not remove the locking of the new secondary here
8301
      # unless DRBD8.AddChildren is changed to work in parallel;
8302
      # currently it doesn't since parallel invocations of
8303
      # FindUnusedMinor will conflict
8304
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
8305
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
8306

    
8307
    else:
8308
      self.needed_locks[locking.LEVEL_NODE] = []
8309
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8310

    
8311
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
8312
                                   self.op.iallocator, self.op.remote_node,
8313
                                   self.op.disks, False, self.op.early_release)
8314

    
8315
    self.tasklets = [self.replacer]
8316

    
8317
  def DeclareLocks(self, level):
8318
    # If we're not already locking all nodes in the set we have to declare the
8319
    # instance's primary/secondary nodes.
8320
    if (level == locking.LEVEL_NODE and
8321
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
8322
      self._LockInstancesNodes()
8323

    
8324
  def BuildHooksEnv(self):
8325
    """Build hooks env.
8326

8327
    This runs on the master, the primary and all the secondaries.
8328

8329
    """
8330
    instance = self.replacer.instance
8331
    env = {
8332
      "MODE": self.op.mode,
8333
      "NEW_SECONDARY": self.op.remote_node,
8334
      "OLD_SECONDARY": instance.secondary_nodes[0],
8335
      }
8336
    env.update(_BuildInstanceHookEnvByObject(self, instance))
8337
    nl = [
8338
      self.cfg.GetMasterNode(),
8339
      instance.primary_node,
8340
      ]
8341
    if self.op.remote_node is not None:
8342
      nl.append(self.op.remote_node)
8343
    return env, nl, nl
8344

    
8345

    
8346
class TLReplaceDisks(Tasklet):
8347
  """Replaces disks for an instance.
8348

8349
  Note: Locking is not within the scope of this class.
8350

8351
  """
8352
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
8353
               disks, delay_iallocator, early_release):
8354
    """Initializes this class.
8355

8356
    """
8357
    Tasklet.__init__(self, lu)
8358

    
8359
    # Parameters
8360
    self.instance_name = instance_name
8361
    self.mode = mode
8362
    self.iallocator_name = iallocator_name
8363
    self.remote_node = remote_node
8364
    self.disks = disks
8365
    self.delay_iallocator = delay_iallocator
8366
    self.early_release = early_release
8367

    
8368
    # Runtime data
8369
    self.instance = None
8370
    self.new_node = None
8371
    self.target_node = None
8372
    self.other_node = None
8373
    self.remote_node_info = None
8374
    self.node_secondary_ip = None
8375

    
8376
  @staticmethod
8377
  def CheckArguments(mode, remote_node, iallocator):
8378
    """Helper function for users of this class.
8379

8380
    """
8381
    # check for valid parameter combination
8382
    if mode == constants.REPLACE_DISK_CHG:
8383
      if remote_node is None and iallocator is None:
8384
        raise errors.OpPrereqError("When changing the secondary either an"
8385
                                   " iallocator script must be used or the"
8386
                                   " new node given", errors.ECODE_INVAL)
8387

    
8388
      if remote_node is not None and iallocator is not None:
8389
        raise errors.OpPrereqError("Give either the iallocator or the new"
8390
                                   " secondary, not both", errors.ECODE_INVAL)
8391

    
8392
    elif remote_node is not None or iallocator is not None:
8393
      # Not replacing the secondary
8394
      raise errors.OpPrereqError("The iallocator and new node options can"
8395
                                 " only be used when changing the"
8396
                                 " secondary node", errors.ECODE_INVAL)
8397

    
8398
  @staticmethod
8399
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
8400
    """Compute a new secondary node using an IAllocator.
8401

8402
    """
8403
    ial = IAllocator(lu.cfg, lu.rpc,
8404
                     mode=constants.IALLOCATOR_MODE_RELOC,
8405
                     name=instance_name,
8406
                     relocate_from=relocate_from)
8407

    
8408
    ial.Run(iallocator_name)
8409

    
8410
    if not ial.success:
8411
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
8412
                                 " %s" % (iallocator_name, ial.info),
8413
                                 errors.ECODE_NORES)
8414

    
8415
    if len(ial.result) != ial.required_nodes:
8416
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
8417
                                 " of nodes (%s), required %s" %
8418
                                 (iallocator_name,
8419
                                  len(ial.result), ial.required_nodes),
8420
                                 errors.ECODE_FAULT)
8421

    
8422
    remote_node_name = ial.result[0]
8423

    
8424
    lu.LogInfo("Selected new secondary for instance '%s': %s",
8425
               instance_name, remote_node_name)
8426

    
8427
    return remote_node_name
8428

    
8429
  def _FindFaultyDisks(self, node_name):
8430
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
8431
                                    node_name, True)
8432

    
8433
  def CheckPrereq(self):
8434
    """Check prerequisites.
8435

8436
    This checks that the instance is in the cluster.
8437

8438
    """
8439
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
8440
    assert instance is not None, \
8441
      "Cannot retrieve locked instance %s" % self.instance_name
8442

    
8443
    if instance.disk_template != constants.DT_DRBD8:
8444
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
8445
                                 " instances", errors.ECODE_INVAL)
8446

    
8447
    if len(instance.secondary_nodes) != 1:
8448
      raise errors.OpPrereqError("The instance has a strange layout,"
8449
                                 " expected one secondary but found %d" %
8450
                                 len(instance.secondary_nodes),
8451
                                 errors.ECODE_FAULT)
8452

    
8453
    if not self.delay_iallocator:
8454
      self._CheckPrereq2()
8455

    
8456
  def _CheckPrereq2(self):
8457
    """Check prerequisites, second part.
8458

8459
    This function should always be part of CheckPrereq. It was separated and is
8460
    now called from Exec because during node evacuation iallocator was only
8461
    called with an unmodified cluster model, not taking planned changes into
8462
    account.
8463

8464
    """
8465
    instance = self.instance
8466
    secondary_node = instance.secondary_nodes[0]
8467

    
8468
    if self.iallocator_name is None:
8469
      remote_node = self.remote_node
8470
    else:
8471
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
8472
                                       instance.name, instance.secondary_nodes)
8473

    
8474
    if remote_node is not None:
8475
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
8476
      assert self.remote_node_info is not None, \
8477
        "Cannot retrieve locked node %s" % remote_node
8478
    else:
8479
      self.remote_node_info = None
8480

    
8481
    if remote_node == self.instance.primary_node:
8482
      raise errors.OpPrereqError("The specified node is the primary node of"
8483
                                 " the instance.", errors.ECODE_INVAL)
8484

    
8485
    if remote_node == secondary_node:
8486
      raise errors.OpPrereqError("The specified node is already the"
8487
                                 " secondary node of the instance.",
8488
                                 errors.ECODE_INVAL)
8489

    
8490
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
8491
                                    constants.REPLACE_DISK_CHG):
8492
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
8493
                                 errors.ECODE_INVAL)
8494

    
8495
    if self.mode == constants.REPLACE_DISK_AUTO:
8496
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
8497
      faulty_secondary = self._FindFaultyDisks(secondary_node)
8498

    
8499
      if faulty_primary and faulty_secondary:
8500
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
8501
                                   " one node and can not be repaired"
8502
                                   " automatically" % self.instance_name,
8503
                                   errors.ECODE_STATE)
8504

    
8505
      if faulty_primary:
8506
        self.disks = faulty_primary
8507
        self.target_node = instance.primary_node
8508
        self.other_node = secondary_node
8509
        check_nodes = [self.target_node, self.other_node]
8510
      elif faulty_secondary:
8511
        self.disks = faulty_secondary
8512
        self.target_node = secondary_node
8513
        self.other_node = instance.primary_node
8514
        check_nodes = [self.target_node, self.other_node]
8515
      else:
8516
        self.disks = []
8517
        check_nodes = []
8518

    
8519
    else:
8520
      # Non-automatic modes
8521
      if self.mode == constants.REPLACE_DISK_PRI:
8522
        self.target_node = instance.primary_node
8523
        self.other_node = secondary_node
8524
        check_nodes = [self.target_node, self.other_node]
8525

    
8526
      elif self.mode == constants.REPLACE_DISK_SEC:
8527
        self.target_node = secondary_node
8528
        self.other_node = instance.primary_node
8529
        check_nodes = [self.target_node, self.other_node]
8530

    
8531
      elif self.mode == constants.REPLACE_DISK_CHG:
8532
        self.new_node = remote_node
8533
        self.other_node = instance.primary_node
8534
        self.target_node = secondary_node
8535
        check_nodes = [self.new_node, self.other_node]
8536

    
8537
        _CheckNodeNotDrained(self.lu, remote_node)
8538
        _CheckNodeVmCapable(self.lu, remote_node)
8539

    
8540
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
8541
        assert old_node_info is not None
8542
        if old_node_info.offline and not self.early_release:
8543
          # doesn't make sense to delay the release
8544
          self.early_release = True
8545
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
8546
                          " early-release mode", secondary_node)
8547

    
8548
      else:
8549
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
8550
                                     self.mode)
8551

    
8552
      # If not specified all disks should be replaced
8553
      if not self.disks:
8554
        self.disks = range(len(self.instance.disks))
8555

    
8556
    for node in check_nodes:
8557
      _CheckNodeOnline(self.lu, node)
8558

    
8559
    touched_nodes = frozenset([self.new_node, self.other_node,
8560
                               self.target_node])
8561

    
8562
    if self.lu.needed_locks[locking.LEVEL_NODE] == locking.ALL_SET:
8563
      # Release unneeded node locks
8564
      for name in self.lu.acquired_locks[locking.LEVEL_NODE]:
8565
        if name not in touched_nodes:
8566
          self._ReleaseNodeLock(name)
8567

    
8568
    # Check whether disks are valid
8569
    for disk_idx in self.disks:
8570
      instance.FindDisk(disk_idx)
8571

    
8572
    # Get secondary node IP addresses
8573
    self.node_secondary_ip = \
8574
      dict((node_name, self.cfg.GetNodeInfo(node_name).secondary_ip)
8575
           for node_name in touched_nodes
8576
           if node_name is not None)
8577

    
8578
  def Exec(self, feedback_fn):
8579
    """Execute disk replacement.
8580

8581
    This dispatches the disk replacement to the appropriate handler.
8582

8583
    """
8584
    if self.delay_iallocator:
8585
      self._CheckPrereq2()
8586

    
8587
    if (self.lu.needed_locks[locking.LEVEL_NODE] == locking.ALL_SET and
8588
        __debug__):
8589
      # Verify owned locks before starting operation
8590
      owned_locks = self.lu.context.glm.list_owned(locking.LEVEL_NODE)
8591
      assert set(owned_locks) == set(self.node_secondary_ip), \
8592
          "Not owning the correct locks: %s" % (owned_locks, )
8593

    
8594
    if not self.disks:
8595
      feedback_fn("No disks need replacement")
8596
      return
8597

    
8598
    feedback_fn("Replacing disk(s) %s for %s" %
8599
                (utils.CommaJoin(self.disks), self.instance.name))
8600

    
8601
    activate_disks = (not self.instance.admin_up)
8602

    
8603
    # Activate the instance disks if we're replacing them on a down instance
8604
    if activate_disks:
8605
      _StartInstanceDisks(self.lu, self.instance, True)
8606

    
8607
    try:
8608
      # Should we replace the secondary node?
8609
      if self.new_node is not None:
8610
        fn = self._ExecDrbd8Secondary
8611
      else:
8612
        fn = self._ExecDrbd8DiskOnly
8613

    
8614
      return fn(feedback_fn)
8615

    
8616
    finally:
8617
      # Deactivate the instance disks if we're replacing them on a
8618
      # down instance
8619
      if activate_disks:
8620
        _SafeShutdownInstanceDisks(self.lu, self.instance)
8621

    
8622
      if __debug__:
8623
        # Verify owned locks
8624
        owned_locks = self.lu.context.glm.list_owned(locking.LEVEL_NODE)
8625
        assert ((self.early_release and not owned_locks) or
8626
                (not self.early_release and
8627
                 set(owned_locks) == set(self.node_secondary_ip))), \
8628
          ("Not owning the correct locks, early_release=%s, owned=%r" %
8629
           (self.early_release, owned_locks))
8630

    
8631
  def _CheckVolumeGroup(self, nodes):
8632
    self.lu.LogInfo("Checking volume groups")
8633

    
8634
    vgname = self.cfg.GetVGName()
8635

    
8636
    # Make sure volume group exists on all involved nodes
8637
    results = self.rpc.call_vg_list(nodes)
8638
    if not results:
8639
      raise errors.OpExecError("Can't list volume groups on the nodes")
8640

    
8641
    for node in nodes:
8642
      res = results[node]
8643
      res.Raise("Error checking node %s" % node)
8644
      if vgname not in res.payload:
8645
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
8646
                                 (vgname, node))
8647

    
8648
  def _CheckDisksExistence(self, nodes):
8649
    # Check disk existence
8650
    for idx, dev in enumerate(self.instance.disks):
8651
      if idx not in self.disks:
8652
        continue
8653

    
8654
      for node in nodes:
8655
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
8656
        self.cfg.SetDiskID(dev, node)
8657

    
8658
        result = self.rpc.call_blockdev_find(node, dev)
8659

    
8660
        msg = result.fail_msg
8661
        if msg or not result.payload:
8662
          if not msg:
8663
            msg = "disk not found"
8664
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
8665
                                   (idx, node, msg))
8666

    
8667
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
8668
    for idx, dev in enumerate(self.instance.disks):
8669
      if idx not in self.disks:
8670
        continue
8671

    
8672
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
8673
                      (idx, node_name))
8674

    
8675
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
8676
                                   ldisk=ldisk):
8677
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
8678
                                 " replace disks for instance %s" %
8679
                                 (node_name, self.instance.name))
8680

    
8681
  def _CreateNewStorage(self, node_name):
8682
    iv_names = {}
8683

    
8684
    for idx, dev in enumerate(self.instance.disks):
8685
      if idx not in self.disks:
8686
        continue
8687

    
8688
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
8689

    
8690
      self.cfg.SetDiskID(dev, node_name)
8691

    
8692
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
8693
      names = _GenerateUniqueNames(self.lu, lv_names)
8694

    
8695
      vg_data = dev.children[0].logical_id[0]
8696
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
8697
                             logical_id=(vg_data, names[0]))
8698
      vg_meta = dev.children[1].logical_id[0]
8699
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
8700
                             logical_id=(vg_meta, names[1]))
8701

    
8702
      new_lvs = [lv_data, lv_meta]
8703
      old_lvs = dev.children
8704
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
8705

    
8706
      # we pass force_create=True to force the LVM creation
8707
      for new_lv in new_lvs:
8708
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
8709
                        _GetInstanceInfoText(self.instance), False)
8710

    
8711
    return iv_names
8712

    
8713
  def _CheckDevices(self, node_name, iv_names):
8714
    for name, (dev, _, _) in iv_names.iteritems():
8715
      self.cfg.SetDiskID(dev, node_name)
8716

    
8717
      result = self.rpc.call_blockdev_find(node_name, dev)
8718

    
8719
      msg = result.fail_msg
8720
      if msg or not result.payload:
8721
        if not msg:
8722
          msg = "disk not found"
8723
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
8724
                                 (name, msg))
8725

    
8726
      if result.payload.is_degraded:
8727
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
8728

    
8729
  def _RemoveOldStorage(self, node_name, iv_names):
8730
    for name, (_, old_lvs, _) in iv_names.iteritems():
8731
      self.lu.LogInfo("Remove logical volumes for %s" % name)
8732

    
8733
      for lv in old_lvs:
8734
        self.cfg.SetDiskID(lv, node_name)
8735

    
8736
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
8737
        if msg:
8738
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
8739
                             hint="remove unused LVs manually")
8740

    
8741
  def _ReleaseNodeLock(self, node_name):
8742
    """Releases the lock for a given node."""
8743
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
8744

    
8745
  def _ExecDrbd8DiskOnly(self, feedback_fn):
8746
    """Replace a disk on the primary or secondary for DRBD 8.
8747

8748
    The algorithm for replace is quite complicated:
8749

8750
      1. for each disk to be replaced:
8751

8752
        1. create new LVs on the target node with unique names
8753
        1. detach old LVs from the drbd device
8754
        1. rename old LVs to name_replaced.<time_t>
8755
        1. rename new LVs to old LVs
8756
        1. attach the new LVs (with the old names now) to the drbd device
8757

8758
      1. wait for sync across all devices
8759

8760
      1. for each modified disk:
8761

8762
        1. remove old LVs (which have the name name_replaces.<time_t>)
8763

8764
    Failures are not very well handled.
8765

8766
    """
8767
    steps_total = 6
8768

    
8769
    # Step: check device activation
8770
    self.lu.LogStep(1, steps_total, "Check device existence")
8771
    self._CheckDisksExistence([self.other_node, self.target_node])
8772
    self._CheckVolumeGroup([self.target_node, self.other_node])
8773

    
8774
    # Step: check other node consistency
8775
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8776
    self._CheckDisksConsistency(self.other_node,
8777
                                self.other_node == self.instance.primary_node,
8778
                                False)
8779

    
8780
    # Step: create new storage
8781
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8782
    iv_names = self._CreateNewStorage(self.target_node)
8783

    
8784
    # Step: for each lv, detach+rename*2+attach
8785
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8786
    for dev, old_lvs, new_lvs in iv_names.itervalues():
8787
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
8788

    
8789
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
8790
                                                     old_lvs)
8791
      result.Raise("Can't detach drbd from local storage on node"
8792
                   " %s for device %s" % (self.target_node, dev.iv_name))
8793
      #dev.children = []
8794
      #cfg.Update(instance)
8795

    
8796
      # ok, we created the new LVs, so now we know we have the needed
8797
      # storage; as such, we proceed on the target node to rename
8798
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
8799
      # using the assumption that logical_id == physical_id (which in
8800
      # turn is the unique_id on that node)
8801

    
8802
      # FIXME(iustin): use a better name for the replaced LVs
8803
      temp_suffix = int(time.time())
8804
      ren_fn = lambda d, suff: (d.physical_id[0],
8805
                                d.physical_id[1] + "_replaced-%s" % suff)
8806

    
8807
      # Build the rename list based on what LVs exist on the node
8808
      rename_old_to_new = []
8809
      for to_ren in old_lvs:
8810
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
8811
        if not result.fail_msg and result.payload:
8812
          # device exists
8813
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
8814

    
8815
      self.lu.LogInfo("Renaming the old LVs on the target node")
8816
      result = self.rpc.call_blockdev_rename(self.target_node,
8817
                                             rename_old_to_new)
8818
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
8819

    
8820
      # Now we rename the new LVs to the old LVs
8821
      self.lu.LogInfo("Renaming the new LVs on the target node")
8822
      rename_new_to_old = [(new, old.physical_id)
8823
                           for old, new in zip(old_lvs, new_lvs)]
8824
      result = self.rpc.call_blockdev_rename(self.target_node,
8825
                                             rename_new_to_old)
8826
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
8827

    
8828
      for old, new in zip(old_lvs, new_lvs):
8829
        new.logical_id = old.logical_id
8830
        self.cfg.SetDiskID(new, self.target_node)
8831

    
8832
      for disk in old_lvs:
8833
        disk.logical_id = ren_fn(disk, temp_suffix)
8834
        self.cfg.SetDiskID(disk, self.target_node)
8835

    
8836
      # Now that the new lvs have the old name, we can add them to the device
8837
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
8838
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
8839
                                                  new_lvs)
8840
      msg = result.fail_msg
8841
      if msg:
8842
        for new_lv in new_lvs:
8843
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
8844
                                               new_lv).fail_msg
8845
          if msg2:
8846
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
8847
                               hint=("cleanup manually the unused logical"
8848
                                     "volumes"))
8849
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8850

    
8851
      dev.children = new_lvs
8852

    
8853
      self.cfg.Update(self.instance, feedback_fn)
8854

    
8855
    cstep = 5
8856
    if self.early_release:
8857
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8858
      cstep += 1
8859
      self._RemoveOldStorage(self.target_node, iv_names)
8860
      # WARNING: we release both node locks here, do not do other RPCs
8861
      # than WaitForSync to the primary node
8862
      self._ReleaseNodeLock([self.target_node, self.other_node])
8863

    
8864
    # Wait for sync
8865
    # This can fail as the old devices are degraded and _WaitForSync
8866
    # does a combined result over all disks, so we don't check its return value
8867
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8868
    cstep += 1
8869
    _WaitForSync(self.lu, self.instance)
8870

    
8871
    # Check all devices manually
8872
    self._CheckDevices(self.instance.primary_node, iv_names)
8873

    
8874
    # Step: remove old storage
8875
    if not self.early_release:
8876
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8877
      cstep += 1
8878
      self._RemoveOldStorage(self.target_node, iv_names)
8879

    
8880
  def _ExecDrbd8Secondary(self, feedback_fn):
8881
    """Replace the secondary node for DRBD 8.
8882

8883
    The algorithm for replace is quite complicated:
8884
      - for all disks of the instance:
8885
        - create new LVs on the new node with same names
8886
        - shutdown the drbd device on the old secondary
8887
        - disconnect the drbd network on the primary
8888
        - create the drbd device on the new secondary
8889
        - network attach the drbd on the primary, using an artifice:
8890
          the drbd code for Attach() will connect to the network if it
8891
          finds a device which is connected to the good local disks but
8892
          not network enabled
8893
      - wait for sync across all devices
8894
      - remove all disks from the old secondary
8895

8896
    Failures are not very well handled.
8897

8898
    """
8899
    steps_total = 6
8900

    
8901
    # Step: check device activation
8902
    self.lu.LogStep(1, steps_total, "Check device existence")
8903
    self._CheckDisksExistence([self.instance.primary_node])
8904
    self._CheckVolumeGroup([self.instance.primary_node])
8905

    
8906
    # Step: check other node consistency
8907
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8908
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8909

    
8910
    # Step: create new storage
8911
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8912
    for idx, dev in enumerate(self.instance.disks):
8913
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8914
                      (self.new_node, idx))
8915
      # we pass force_create=True to force LVM creation
8916
      for new_lv in dev.children:
8917
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8918
                        _GetInstanceInfoText(self.instance), False)
8919

    
8920
    # Step 4: dbrd minors and drbd setups changes
8921
    # after this, we must manually remove the drbd minors on both the
8922
    # error and the success paths
8923
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8924
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8925
                                         for dev in self.instance.disks],
8926
                                        self.instance.name)
8927
    logging.debug("Allocated minors %r", minors)
8928

    
8929
    iv_names = {}
8930
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8931
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8932
                      (self.new_node, idx))
8933
      # create new devices on new_node; note that we create two IDs:
8934
      # one without port, so the drbd will be activated without
8935
      # networking information on the new node at this stage, and one
8936
      # with network, for the latter activation in step 4
8937
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8938
      if self.instance.primary_node == o_node1:
8939
        p_minor = o_minor1
8940
      else:
8941
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8942
        p_minor = o_minor2
8943

    
8944
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8945
                      p_minor, new_minor, o_secret)
8946
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8947
                    p_minor, new_minor, o_secret)
8948

    
8949
      iv_names[idx] = (dev, dev.children, new_net_id)
8950
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8951
                    new_net_id)
8952
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8953
                              logical_id=new_alone_id,
8954
                              children=dev.children,
8955
                              size=dev.size)
8956
      try:
8957
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8958
                              _GetInstanceInfoText(self.instance), False)
8959
      except errors.GenericError:
8960
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8961
        raise
8962

    
8963
    # We have new devices, shutdown the drbd on the old secondary
8964
    for idx, dev in enumerate(self.instance.disks):
8965
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8966
      self.cfg.SetDiskID(dev, self.target_node)
8967
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8968
      if msg:
8969
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8970
                           "node: %s" % (idx, msg),
8971
                           hint=("Please cleanup this device manually as"
8972
                                 " soon as possible"))
8973

    
8974
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8975
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8976
                                               self.node_secondary_ip,
8977
                                               self.instance.disks)\
8978
                                              [self.instance.primary_node]
8979

    
8980
    msg = result.fail_msg
8981
    if msg:
8982
      # detaches didn't succeed (unlikely)
8983
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8984
      raise errors.OpExecError("Can't detach the disks from the network on"
8985
                               " old node: %s" % (msg,))
8986

    
8987
    # if we managed to detach at least one, we update all the disks of
8988
    # the instance to point to the new secondary
8989
    self.lu.LogInfo("Updating instance configuration")
8990
    for dev, _, new_logical_id in iv_names.itervalues():
8991
      dev.logical_id = new_logical_id
8992
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8993

    
8994
    self.cfg.Update(self.instance, feedback_fn)
8995

    
8996
    # and now perform the drbd attach
8997
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8998
                    " (standalone => connected)")
8999
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
9000
                                            self.new_node],
9001
                                           self.node_secondary_ip,
9002
                                           self.instance.disks,
9003
                                           self.instance.name,
9004
                                           False)
9005
    for to_node, to_result in result.items():
9006
      msg = to_result.fail_msg
9007
      if msg:
9008
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
9009
                           to_node, msg,
9010
                           hint=("please do a gnt-instance info to see the"
9011
                                 " status of disks"))
9012
    cstep = 5
9013
    if self.early_release:
9014
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9015
      cstep += 1
9016
      self._RemoveOldStorage(self.target_node, iv_names)
9017
      # WARNING: we release all node locks here, do not do other RPCs
9018
      # than WaitForSync to the primary node
9019
      self._ReleaseNodeLock([self.instance.primary_node,
9020
                             self.target_node,
9021
                             self.new_node])
9022

    
9023
    # Wait for sync
9024
    # This can fail as the old devices are degraded and _WaitForSync
9025
    # does a combined result over all disks, so we don't check its return value
9026
    self.lu.LogStep(cstep, steps_total, "Sync devices")
9027
    cstep += 1
9028
    _WaitForSync(self.lu, self.instance)
9029

    
9030
    # Check all devices manually
9031
    self._CheckDevices(self.instance.primary_node, iv_names)
9032

    
9033
    # Step: remove old storage
9034
    if not self.early_release:
9035
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9036
      self._RemoveOldStorage(self.target_node, iv_names)
9037

    
9038

    
9039
class LURepairNodeStorage(NoHooksLU):
9040
  """Repairs the volume group on a node.
9041

9042
  """
9043
  REQ_BGL = False
9044

    
9045
  def CheckArguments(self):
9046
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
9047

    
9048
    storage_type = self.op.storage_type
9049

    
9050
    if (constants.SO_FIX_CONSISTENCY not in
9051
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
9052
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
9053
                                 " repaired" % storage_type,
9054
                                 errors.ECODE_INVAL)
9055

    
9056
  def ExpandNames(self):
9057
    self.needed_locks = {
9058
      locking.LEVEL_NODE: [self.op.node_name],
9059
      }
9060

    
9061
  def _CheckFaultyDisks(self, instance, node_name):
9062
    """Ensure faulty disks abort the opcode or at least warn."""
9063
    try:
9064
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
9065
                                  node_name, True):
9066
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
9067
                                   " node '%s'" % (instance.name, node_name),
9068
                                   errors.ECODE_STATE)
9069
    except errors.OpPrereqError, err:
9070
      if self.op.ignore_consistency:
9071
        self.proc.LogWarning(str(err.args[0]))
9072
      else:
9073
        raise
9074

    
9075
  def CheckPrereq(self):
9076
    """Check prerequisites.
9077

9078
    """
9079
    # Check whether any instance on this node has faulty disks
9080
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
9081
      if not inst.admin_up:
9082
        continue
9083
      check_nodes = set(inst.all_nodes)
9084
      check_nodes.discard(self.op.node_name)
9085
      for inst_node_name in check_nodes:
9086
        self._CheckFaultyDisks(inst, inst_node_name)
9087

    
9088
  def Exec(self, feedback_fn):
9089
    feedback_fn("Repairing storage unit '%s' on %s ..." %
9090
                (self.op.name, self.op.node_name))
9091

    
9092
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
9093
    result = self.rpc.call_storage_execute(self.op.node_name,
9094
                                           self.op.storage_type, st_args,
9095
                                           self.op.name,
9096
                                           constants.SO_FIX_CONSISTENCY)
9097
    result.Raise("Failed to repair storage unit '%s' on %s" %
9098
                 (self.op.name, self.op.node_name))
9099

    
9100

    
9101
class LUNodeEvacStrategy(NoHooksLU):
9102
  """Computes the node evacuation strategy.
9103

9104
  """
9105
  REQ_BGL = False
9106

    
9107
  def CheckArguments(self):
9108
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
9109

    
9110
  def ExpandNames(self):
9111
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
9112
    self.needed_locks = locks = {}
9113
    if self.op.remote_node is None:
9114
      locks[locking.LEVEL_NODE] = locking.ALL_SET
9115
    else:
9116
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9117
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
9118

    
9119
  def Exec(self, feedback_fn):
9120
    if self.op.remote_node is not None:
9121
      instances = []
9122
      for node in self.op.nodes:
9123
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
9124
      result = []
9125
      for i in instances:
9126
        if i.primary_node == self.op.remote_node:
9127
          raise errors.OpPrereqError("Node %s is the primary node of"
9128
                                     " instance %s, cannot use it as"
9129
                                     " secondary" %
9130
                                     (self.op.remote_node, i.name),
9131
                                     errors.ECODE_INVAL)
9132
        result.append([i.name, self.op.remote_node])
9133
    else:
9134
      ial = IAllocator(self.cfg, self.rpc,
9135
                       mode=constants.IALLOCATOR_MODE_MEVAC,
9136
                       evac_nodes=self.op.nodes)
9137
      ial.Run(self.op.iallocator, validate=True)
9138
      if not ial.success:
9139
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
9140
                                 errors.ECODE_NORES)
9141
      result = ial.result
9142
    return result
9143

    
9144

    
9145
class LUInstanceGrowDisk(LogicalUnit):
9146
  """Grow a disk of an instance.
9147

9148
  """
9149
  HPATH = "disk-grow"
9150
  HTYPE = constants.HTYPE_INSTANCE
9151
  REQ_BGL = False
9152

    
9153
  def ExpandNames(self):
9154
    self._ExpandAndLockInstance()
9155
    self.needed_locks[locking.LEVEL_NODE] = []
9156
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9157

    
9158
  def DeclareLocks(self, level):
9159
    if level == locking.LEVEL_NODE:
9160
      self._LockInstancesNodes()
9161

    
9162
  def BuildHooksEnv(self):
9163
    """Build hooks env.
9164

9165
    This runs on the master, the primary and all the secondaries.
9166

9167
    """
9168
    env = {
9169
      "DISK": self.op.disk,
9170
      "AMOUNT": self.op.amount,
9171
      }
9172
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9173
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9174
    return env, nl, nl
9175

    
9176
  def CheckPrereq(self):
9177
    """Check prerequisites.
9178

9179
    This checks that the instance is in the cluster.
9180

9181
    """
9182
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9183
    assert instance is not None, \
9184
      "Cannot retrieve locked instance %s" % self.op.instance_name
9185
    nodenames = list(instance.all_nodes)
9186
    for node in nodenames:
9187
      _CheckNodeOnline(self, node)
9188

    
9189
    self.instance = instance
9190

    
9191
    if instance.disk_template not in constants.DTS_GROWABLE:
9192
      raise errors.OpPrereqError("Instance's disk layout does not support"
9193
                                 " growing.", errors.ECODE_INVAL)
9194

    
9195
    self.disk = instance.FindDisk(self.op.disk)
9196

    
9197
    if instance.disk_template not in (constants.DT_FILE,
9198
                                      constants.DT_SHARED_FILE):
9199
      # TODO: check the free disk space for file, when that feature will be
9200
      # supported
9201
      _CheckNodesFreeDiskPerVG(self, nodenames,
9202
                               self.disk.ComputeGrowth(self.op.amount))
9203

    
9204
  def Exec(self, feedback_fn):
9205
    """Execute disk grow.
9206

9207
    """
9208
    instance = self.instance
9209
    disk = self.disk
9210

    
9211
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
9212
    if not disks_ok:
9213
      raise errors.OpExecError("Cannot activate block device to grow")
9214

    
9215
    for node in instance.all_nodes:
9216
      self.cfg.SetDiskID(disk, node)
9217
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
9218
      result.Raise("Grow request failed to node %s" % node)
9219

    
9220
      # TODO: Rewrite code to work properly
9221
      # DRBD goes into sync mode for a short amount of time after executing the
9222
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
9223
      # calling "resize" in sync mode fails. Sleeping for a short amount of
9224
      # time is a work-around.
9225
      time.sleep(5)
9226

    
9227
    disk.RecordGrow(self.op.amount)
9228
    self.cfg.Update(instance, feedback_fn)
9229
    if self.op.wait_for_sync:
9230
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
9231
      if disk_abort:
9232
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
9233
                             " status.\nPlease check the instance.")
9234
      if not instance.admin_up:
9235
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
9236
    elif not instance.admin_up:
9237
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
9238
                           " not supposed to be running because no wait for"
9239
                           " sync mode was requested.")
9240

    
9241

    
9242
class LUInstanceQueryData(NoHooksLU):
9243
  """Query runtime instance data.
9244

9245
  """
9246
  REQ_BGL = False
9247

    
9248
  def ExpandNames(self):
9249
    self.needed_locks = {}
9250

    
9251
    # Use locking if requested or when non-static information is wanted
9252
    if not (self.op.static or self.op.use_locking):
9253
      self.LogWarning("Non-static data requested, locks need to be acquired")
9254
      self.op.use_locking = True
9255

    
9256
    if self.op.instances or not self.op.use_locking:
9257
      # Expand instance names right here
9258
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
9259
    else:
9260
      # Will use acquired locks
9261
      self.wanted_names = None
9262

    
9263
    if self.op.use_locking:
9264
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9265

    
9266
      if self.wanted_names is None:
9267
        self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
9268
      else:
9269
        self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
9270

    
9271
      self.needed_locks[locking.LEVEL_NODE] = []
9272
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9273
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9274

    
9275
  def DeclareLocks(self, level):
9276
    if self.op.use_locking and level == locking.LEVEL_NODE:
9277
      self._LockInstancesNodes()
9278

    
9279
  def CheckPrereq(self):
9280
    """Check prerequisites.
9281

9282
    This only checks the optional instance list against the existing names.
9283

9284
    """
9285
    if self.wanted_names is None:
9286
      assert self.op.use_locking, "Locking was not used"
9287
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
9288

    
9289
    self.wanted_instances = [self.cfg.GetInstanceInfo(name)
9290
                             for name in self.wanted_names]
9291

    
9292
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
9293
    """Returns the status of a block device
9294

9295
    """
9296
    if self.op.static or not node:
9297
      return None
9298

    
9299
    self.cfg.SetDiskID(dev, node)
9300

    
9301
    result = self.rpc.call_blockdev_find(node, dev)
9302
    if result.offline:
9303
      return None
9304

    
9305
    result.Raise("Can't compute disk status for %s" % instance_name)
9306

    
9307
    status = result.payload
9308
    if status is None:
9309
      return None
9310

    
9311
    return (status.dev_path, status.major, status.minor,
9312
            status.sync_percent, status.estimated_time,
9313
            status.is_degraded, status.ldisk_status)
9314

    
9315
  def _ComputeDiskStatus(self, instance, snode, dev):
9316
    """Compute block device status.
9317

9318
    """
9319
    if dev.dev_type in constants.LDS_DRBD:
9320
      # we change the snode then (otherwise we use the one passed in)
9321
      if dev.logical_id[0] == instance.primary_node:
9322
        snode = dev.logical_id[1]
9323
      else:
9324
        snode = dev.logical_id[0]
9325

    
9326
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
9327
                                              instance.name, dev)
9328
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
9329

    
9330
    if dev.children:
9331
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
9332
                      for child in dev.children]
9333
    else:
9334
      dev_children = []
9335

    
9336
    return {
9337
      "iv_name": dev.iv_name,
9338
      "dev_type": dev.dev_type,
9339
      "logical_id": dev.logical_id,
9340
      "physical_id": dev.physical_id,
9341
      "pstatus": dev_pstatus,
9342
      "sstatus": dev_sstatus,
9343
      "children": dev_children,
9344
      "mode": dev.mode,
9345
      "size": dev.size,
9346
      }
9347

    
9348
  def Exec(self, feedback_fn):
9349
    """Gather and return data"""
9350
    result = {}
9351

    
9352
    cluster = self.cfg.GetClusterInfo()
9353

    
9354
    for instance in self.wanted_instances:
9355
      if not self.op.static:
9356
        remote_info = self.rpc.call_instance_info(instance.primary_node,
9357
                                                  instance.name,
9358
                                                  instance.hypervisor)
9359
        remote_info.Raise("Error checking node %s" % instance.primary_node)
9360
        remote_info = remote_info.payload
9361
        if remote_info and "state" in remote_info:
9362
          remote_state = "up"
9363
        else:
9364
          remote_state = "down"
9365
      else:
9366
        remote_state = None
9367
      if instance.admin_up:
9368
        config_state = "up"
9369
      else:
9370
        config_state = "down"
9371

    
9372
      disks = [self._ComputeDiskStatus(instance, None, device)
9373
               for device in instance.disks]
9374

    
9375
      result[instance.name] = {
9376
        "name": instance.name,
9377
        "config_state": config_state,
9378
        "run_state": remote_state,
9379
        "pnode": instance.primary_node,
9380
        "snodes": instance.secondary_nodes,
9381
        "os": instance.os,
9382
        # this happens to be the same format used for hooks
9383
        "nics": _NICListToTuple(self, instance.nics),
9384
        "disk_template": instance.disk_template,
9385
        "disks": disks,
9386
        "hypervisor": instance.hypervisor,
9387
        "network_port": instance.network_port,
9388
        "hv_instance": instance.hvparams,
9389
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
9390
        "be_instance": instance.beparams,
9391
        "be_actual": cluster.FillBE(instance),
9392
        "os_instance": instance.osparams,
9393
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
9394
        "serial_no": instance.serial_no,
9395
        "mtime": instance.mtime,
9396
        "ctime": instance.ctime,
9397
        "uuid": instance.uuid,
9398
        }
9399

    
9400
    return result
9401

    
9402

    
9403
class LUInstanceSetParams(LogicalUnit):
9404
  """Modifies an instances's parameters.
9405

9406
  """
9407
  HPATH = "instance-modify"
9408
  HTYPE = constants.HTYPE_INSTANCE
9409
  REQ_BGL = False
9410

    
9411
  def CheckArguments(self):
9412
    if not (self.op.nics or self.op.disks or self.op.disk_template or
9413
            self.op.hvparams or self.op.beparams or self.op.os_name):
9414
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
9415

    
9416
    if self.op.hvparams:
9417
      _CheckGlobalHvParams(self.op.hvparams)
9418

    
9419
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9420

    
9421
    # Disk validation
9422
    disk_addremove = 0
9423
    for disk_op, disk_dict in self.op.disks:
9424
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
9425
      if disk_op == constants.DDM_REMOVE:
9426
        disk_addremove += 1
9427
        continue
9428
      elif disk_op == constants.DDM_ADD:
9429
        disk_addremove += 1
9430
      else:
9431
        if not isinstance(disk_op, int):
9432
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
9433
        if not isinstance(disk_dict, dict):
9434
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
9435
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9436

    
9437
      if disk_op == constants.DDM_ADD:
9438
        if "adopt" in disk_dict:
9439
          has_adopt = True
9440
        else:
9441
          has_adopt = False
9442

    
9443
        if has_adopt:
9444
          if instance.disk_template not in constants.DTS_MAY_ADOPT:
9445
            raise errors.OpPrereqError("Disk adoption is not supported for the"
9446
                                       " '%s' disk template" %
9447
                                       instance.disk_template,
9448
                                       errors.ECODE_INVAL)
9449
        self.adopt_disks = has_adopt
9450

    
9451
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
9452
        if mode not in constants.DISK_ACCESS_SET:
9453
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
9454
                                     errors.ECODE_INVAL)
9455
        if not has_adopt:
9456
          size = disk_dict.get('size', None)
9457
          if size is None:
9458
            raise errors.OpPrereqError("Required disk parameter size missing",
9459
                                       errors.ECODE_INVAL)
9460
          try:
9461
            size = int(size)
9462
          except (TypeError, ValueError), err:
9463
            raise errors.OpPrereqError("Invalid disk size parameter: %s" %
9464
                                       str(err), errors.ECODE_INVAL)
9465
          disk_dict['size'] = size
9466
      else:
9467
        # modification of disk
9468
        if 'size' in disk_dict:
9469
          raise errors.OpPrereqError("Disk size change not possible, use"
9470
                                     " grow-disk", errors.ECODE_INVAL)
9471

    
9472
    if disk_addremove > 1:
9473
      raise errors.OpPrereqError("Only one disk add or remove operation"
9474
                                 " supported at a time", errors.ECODE_INVAL)
9475

    
9476
    if self.op.disks and self.op.disk_template is not None:
9477
      raise errors.OpPrereqError("Disk template conversion and other disk"
9478
                                 " changes not supported at the same time",
9479
                                 errors.ECODE_INVAL)
9480

    
9481
    if (self.op.disk_template and
9482
        self.op.disk_template in constants.DTS_INT_MIRROR and
9483
        self.op.remote_node is None):
9484
      raise errors.OpPrereqError("Changing the disk template to a mirrored"
9485
                                 " one requires specifying a secondary node",
9486
                                 errors.ECODE_INVAL)
9487

    
9488
    # NIC validation
9489
    nic_addremove = 0
9490
    for nic_op, nic_dict in self.op.nics:
9491
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
9492
      if nic_op == constants.DDM_REMOVE:
9493
        nic_addremove += 1
9494
        continue
9495
      elif nic_op == constants.DDM_ADD:
9496
        nic_addremove += 1
9497
      else:
9498
        if not isinstance(nic_op, int):
9499
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
9500
        if not isinstance(nic_dict, dict):
9501
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
9502
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9503

    
9504
      # nic_dict should be a dict
9505
      nic_ip = nic_dict.get('ip', None)
9506
      if nic_ip is not None:
9507
        if nic_ip.lower() == constants.VALUE_NONE:
9508
          nic_dict['ip'] = None
9509
        else:
9510
          if not netutils.IPAddress.IsValid(nic_ip):
9511
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
9512
                                       errors.ECODE_INVAL)
9513

    
9514
      nic_bridge = nic_dict.get('bridge', None)
9515
      nic_link = nic_dict.get('link', None)
9516
      if nic_bridge and nic_link:
9517
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
9518
                                   " at the same time", errors.ECODE_INVAL)
9519
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
9520
        nic_dict['bridge'] = None
9521
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
9522
        nic_dict['link'] = None
9523

    
9524
      if nic_op == constants.DDM_ADD:
9525
        nic_mac = nic_dict.get('mac', None)
9526
        if nic_mac is None:
9527
          nic_dict['mac'] = constants.VALUE_AUTO
9528

    
9529
      if 'mac' in nic_dict:
9530
        nic_mac = nic_dict['mac']
9531
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9532
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
9533

    
9534
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
9535
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
9536
                                     " modifying an existing nic",
9537
                                     errors.ECODE_INVAL)
9538

    
9539
    if nic_addremove > 1:
9540
      raise errors.OpPrereqError("Only one NIC add or remove operation"
9541
                                 " supported at a time", errors.ECODE_INVAL)
9542

    
9543
  def ExpandNames(self):
9544
    self._ExpandAndLockInstance()
9545
    self.needed_locks[locking.LEVEL_NODE] = []
9546
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9547

    
9548
  def DeclareLocks(self, level):
9549
    if level == locking.LEVEL_NODE:
9550
      self._LockInstancesNodes()
9551
      if self.op.disk_template and self.op.remote_node:
9552
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9553
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
9554

    
9555
  def BuildHooksEnv(self):
9556
    """Build hooks env.
9557

9558
    This runs on the master, primary and secondaries.
9559

9560
    """
9561
    args = dict()
9562
    if constants.BE_MEMORY in self.be_new:
9563
      args['memory'] = self.be_new[constants.BE_MEMORY]
9564
    if constants.BE_VCPUS in self.be_new:
9565
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
9566
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
9567
    # information at all.
9568
    if self.op.nics:
9569
      args['nics'] = []
9570
      nic_override = dict(self.op.nics)
9571
      for idx, nic in enumerate(self.instance.nics):
9572
        if idx in nic_override:
9573
          this_nic_override = nic_override[idx]
9574
        else:
9575
          this_nic_override = {}
9576
        if 'ip' in this_nic_override:
9577
          ip = this_nic_override['ip']
9578
        else:
9579
          ip = nic.ip
9580
        if 'mac' in this_nic_override:
9581
          mac = this_nic_override['mac']
9582
        else:
9583
          mac = nic.mac
9584
        if idx in self.nic_pnew:
9585
          nicparams = self.nic_pnew[idx]
9586
        else:
9587
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
9588
        mode = nicparams[constants.NIC_MODE]
9589
        link = nicparams[constants.NIC_LINK]
9590
        args['nics'].append((ip, mac, mode, link))
9591
      if constants.DDM_ADD in nic_override:
9592
        ip = nic_override[constants.DDM_ADD].get('ip', None)
9593
        mac = nic_override[constants.DDM_ADD]['mac']
9594
        nicparams = self.nic_pnew[constants.DDM_ADD]
9595
        mode = nicparams[constants.NIC_MODE]
9596
        link = nicparams[constants.NIC_LINK]
9597
        args['nics'].append((ip, mac, mode, link))
9598
      elif constants.DDM_REMOVE in nic_override:
9599
        del args['nics'][-1]
9600

    
9601
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
9602
    if self.op.disk_template:
9603
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
9604
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9605
    return env, nl, nl
9606

    
9607
  def CheckPrereq(self):
9608
    """Check prerequisites.
9609

9610
    This only checks the instance list against the existing names.
9611

9612
    """
9613
    # checking the new params on the primary/secondary nodes
9614

    
9615
    instance = self.instance
9616
    cluster = self.cluster = self.cfg.GetClusterInfo()
9617
    assert self.instance is not None, \
9618
      "Cannot retrieve locked instance %s" % self.op.instance_name
9619
    pnode = instance.primary_node
9620
    nodelist = list(instance.all_nodes)
9621

    
9622
    # OS change
9623
    if self.op.os_name and not self.op.force:
9624
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
9625
                      self.op.force_variant)
9626
      instance_os = self.op.os_name
9627
    else:
9628
      instance_os = instance.os
9629

    
9630
    if self.op.disk_template:
9631
      if instance.disk_template == self.op.disk_template:
9632
        raise errors.OpPrereqError("Instance already has disk template %s" %
9633
                                   instance.disk_template, errors.ECODE_INVAL)
9634

    
9635
      if (instance.disk_template,
9636
          self.op.disk_template) not in self._DISK_CONVERSIONS:
9637
        raise errors.OpPrereqError("Unsupported disk template conversion from"
9638
                                   " %s to %s" % (instance.disk_template,
9639
                                                  self.op.disk_template),
9640
                                   errors.ECODE_INVAL)
9641
      _CheckInstanceDown(self, instance, "cannot change disk template")
9642
      if self.op.disk_template in constants.DTS_INT_MIRROR:
9643
        if self.op.remote_node == pnode:
9644
          raise errors.OpPrereqError("Given new secondary node %s is the same"
9645
                                     " as the primary node of the instance" %
9646
                                     self.op.remote_node, errors.ECODE_STATE)
9647
        _CheckNodeOnline(self, self.op.remote_node)
9648
        _CheckNodeNotDrained(self, self.op.remote_node)
9649
        # FIXME: here we assume that the old instance type is DT_PLAIN
9650
        assert instance.disk_template == constants.DT_PLAIN
9651
        disks = [{"size": d.size, "vg": d.logical_id[0]}
9652
                 for d in instance.disks]
9653
        required = _ComputeDiskSizePerVG(self.op.disk_template, disks)
9654
        _CheckNodesFreeDiskPerVG(self, [self.op.remote_node], required)
9655

    
9656
    # hvparams processing
9657
    if self.op.hvparams:
9658
      hv_type = instance.hypervisor
9659
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
9660
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
9661
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
9662

    
9663
      # local check
9664
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
9665
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
9666
      self.hv_new = hv_new # the new actual values
9667
      self.hv_inst = i_hvdict # the new dict (without defaults)
9668
    else:
9669
      self.hv_new = self.hv_inst = {}
9670

    
9671
    # beparams processing
9672
    if self.op.beparams:
9673
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
9674
                                   use_none=True)
9675
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
9676
      be_new = cluster.SimpleFillBE(i_bedict)
9677
      self.be_new = be_new # the new actual values
9678
      self.be_inst = i_bedict # the new dict (without defaults)
9679
    else:
9680
      self.be_new = self.be_inst = {}
9681
    be_old = cluster.FillBE(instance)
9682

    
9683
    # osparams processing
9684
    if self.op.osparams:
9685
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
9686
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
9687
      self.os_inst = i_osdict # the new dict (without defaults)
9688
    else:
9689
      self.os_inst = {}
9690

    
9691
    self.warn = []
9692

    
9693
    if (constants.BE_MEMORY in self.op.beparams and not self.op.force and
9694
        be_new[constants.BE_MEMORY] > be_old[constants.BE_MEMORY]):
9695
      mem_check_list = [pnode]
9696
      if be_new[constants.BE_AUTO_BALANCE]:
9697
        # either we changed auto_balance to yes or it was from before
9698
        mem_check_list.extend(instance.secondary_nodes)
9699
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
9700
                                                  instance.hypervisor)
9701
      nodeinfo = self.rpc.call_node_info(mem_check_list, None,
9702
                                         instance.hypervisor)
9703
      pninfo = nodeinfo[pnode]
9704
      msg = pninfo.fail_msg
9705
      if msg:
9706
        # Assume the primary node is unreachable and go ahead
9707
        self.warn.append("Can't get info from primary node %s: %s" %
9708
                         (pnode,  msg))
9709
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
9710
        self.warn.append("Node data from primary node %s doesn't contain"
9711
                         " free memory information" % pnode)
9712
      elif instance_info.fail_msg:
9713
        self.warn.append("Can't get instance runtime information: %s" %
9714
                        instance_info.fail_msg)
9715
      else:
9716
        if instance_info.payload:
9717
          current_mem = int(instance_info.payload['memory'])
9718
        else:
9719
          # Assume instance not running
9720
          # (there is a slight race condition here, but it's not very probable,
9721
          # and we have no other way to check)
9722
          current_mem = 0
9723
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
9724
                    pninfo.payload['memory_free'])
9725
        if miss_mem > 0:
9726
          raise errors.OpPrereqError("This change will prevent the instance"
9727
                                     " from starting, due to %d MB of memory"
9728
                                     " missing on its primary node" % miss_mem,
9729
                                     errors.ECODE_NORES)
9730

    
9731
      if be_new[constants.BE_AUTO_BALANCE]:
9732
        for node, nres in nodeinfo.items():
9733
          if node not in instance.secondary_nodes:
9734
            continue
9735
          nres.Raise("Can't get info from secondary node %s" % node,
9736
                     prereq=True, ecode=errors.ECODE_STATE)
9737
          if not isinstance(nres.payload.get('memory_free', None), int):
9738
            raise errors.OpPrereqError("Secondary node %s didn't return free"
9739
                                       " memory information" % node,
9740
                                       errors.ECODE_STATE)
9741
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
9742
            raise errors.OpPrereqError("This change will prevent the instance"
9743
                                       " from failover to its secondary node"
9744
                                       " %s, due to not enough memory" % node,
9745
                                       errors.ECODE_STATE)
9746

    
9747
    # NIC processing
9748
    self.nic_pnew = {}
9749
    self.nic_pinst = {}
9750
    for nic_op, nic_dict in self.op.nics:
9751
      if nic_op == constants.DDM_REMOVE:
9752
        if not instance.nics:
9753
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
9754
                                     errors.ECODE_INVAL)
9755
        continue
9756
      if nic_op != constants.DDM_ADD:
9757
        # an existing nic
9758
        if not instance.nics:
9759
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
9760
                                     " no NICs" % nic_op,
9761
                                     errors.ECODE_INVAL)
9762
        if nic_op < 0 or nic_op >= len(instance.nics):
9763
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
9764
                                     " are 0 to %d" %
9765
                                     (nic_op, len(instance.nics) - 1),
9766
                                     errors.ECODE_INVAL)
9767
        old_nic_params = instance.nics[nic_op].nicparams
9768
        old_nic_ip = instance.nics[nic_op].ip
9769
      else:
9770
        old_nic_params = {}
9771
        old_nic_ip = None
9772

    
9773
      update_params_dict = dict([(key, nic_dict[key])
9774
                                 for key in constants.NICS_PARAMETERS
9775
                                 if key in nic_dict])
9776

    
9777
      if 'bridge' in nic_dict:
9778
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
9779

    
9780
      new_nic_params = _GetUpdatedParams(old_nic_params,
9781
                                         update_params_dict)
9782
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
9783
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
9784
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
9785
      self.nic_pinst[nic_op] = new_nic_params
9786
      self.nic_pnew[nic_op] = new_filled_nic_params
9787
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
9788

    
9789
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
9790
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
9791
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
9792
        if msg:
9793
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
9794
          if self.op.force:
9795
            self.warn.append(msg)
9796
          else:
9797
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
9798
      if new_nic_mode == constants.NIC_MODE_ROUTED:
9799
        if 'ip' in nic_dict:
9800
          nic_ip = nic_dict['ip']
9801
        else:
9802
          nic_ip = old_nic_ip
9803
        if nic_ip is None:
9804
          raise errors.OpPrereqError('Cannot set the nic ip to None'
9805
                                     ' on a routed nic', errors.ECODE_INVAL)
9806
      if 'mac' in nic_dict:
9807
        nic_mac = nic_dict['mac']
9808
        if nic_mac is None:
9809
          raise errors.OpPrereqError('Cannot set the nic mac to None',
9810
                                     errors.ECODE_INVAL)
9811
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9812
          # otherwise generate the mac
9813
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
9814
        else:
9815
          # or validate/reserve the current one
9816
          try:
9817
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
9818
          except errors.ReservationError:
9819
            raise errors.OpPrereqError("MAC address %s already in use"
9820
                                       " in cluster" % nic_mac,
9821
                                       errors.ECODE_NOTUNIQUE)
9822

    
9823
    # DISK processing
9824
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
9825
      raise errors.OpPrereqError("Disk operations not supported for"
9826
                                 " diskless instances",
9827
                                 errors.ECODE_INVAL)
9828
    for disk_op, disk_dict in self.op.disks:
9829
      if disk_op == constants.DDM_REMOVE:
9830
        if len(instance.disks) == 1:
9831
          raise errors.OpPrereqError("Cannot remove the last disk of"
9832
                                     " an instance", errors.ECODE_INVAL)
9833
        _CheckInstanceDown(self, instance, "cannot remove disks")
9834

    
9835
      if (disk_op == constants.DDM_ADD and
9836
          len(instance.disks) >= constants.MAX_DISKS):
9837
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
9838
                                   " add more" % constants.MAX_DISKS,
9839
                                   errors.ECODE_STATE)
9840
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
9841
        # an existing disk
9842
        if disk_op < 0 or disk_op >= len(instance.disks):
9843
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9844
                                     " are 0 to %d" %
9845
                                     (disk_op, len(instance.disks)),
9846
                                     errors.ECODE_INVAL)
9847

    
9848
      if disk_op == constants.DDM_ADD and self.adopt_disks:
9849
        if instance.disk_template == constants.DT_PLAIN:
9850
          # Check the adoption data
9851
          vg = disk_dict.get("vg", self.cfg.GetVGName())
9852
          lv_name = vg + "/" + disk_dict["adopt"]
9853
          try:
9854
            # FIXME: lv_name here is "vg/lv" need to ensure that other calls
9855
            # to ReserveLV uses the same syntax
9856
            self.cfg.ReserveLV(lv_name, self.proc.GetECId())
9857
          except errors.ReservationError:
9858
            raise errors.OpPrereqError("LV named %s used by another instance" %
9859
                                       lv_name, errors.ECODE_NOTUNIQUE)
9860

    
9861
          vg_names = self.rpc.call_vg_list([instance.primary_node])
9862
          vg_names = vg_names[instance.primary_node]
9863
          vg_names.Raise("Cannot get VG information from node %s" %
9864
                         instance.primary_node)
9865

    
9866
          node_lvs = self.rpc.call_lv_list([instance.primary_node],
9867
                                           vg_names.payload.keys()
9868
                                          )[instance.primary_node]
9869
          node_lvs.Raise("Cannot get LV information from node %s" %
9870
                         instance.primary_node)
9871
          node_lvs = node_lvs.payload
9872

    
9873
          if lv_name not in node_lvs:
9874
            raise errors.OpPrereqError("Logical volume: %s not present "
9875
                                       " on node %s" %
9876
                                       (lv_name, instance.primary_node),
9877
                                       errors.ECODE_INVAL)
9878
          if node_lvs[lv_name][2]:
9879
            raise errors.OpPrereqError("Logical volume %s is online, cannot"
9880
                                       " adopt." % lv_name,
9881
                                       errors.ECODE_STATE)
9882
          # update the size of disk based on what is found
9883
          disk_dict["size"] = int(float(node_lvs[lv_name][0]))
9884

    
9885
        elif instance.disk_template == constants.DT_BLOCK:
9886
          disk = disk_dict["adopt"]
9887
          node_disks = self.rpc.call_bdev_sizes([instance.primary_node],
9888
                                                [disk])[instance.primary_node]
9889
          node_disks = node_disks.payload
9890
          if disk not in node_disks:
9891
            raise errors.OpPrereqError("Missing block device %s" % disk,
9892
                                       errors.ECODE_INVAL)
9893
          disk_dict["size"] = int(float(node_disks[disk]))
9894

    
9895
    return
9896

    
9897
  def _ConvertPlainToDrbd(self, feedback_fn):
9898
    """Converts an instance from plain to drbd.
9899

9900
    """
9901
    feedback_fn("Converting template to drbd")
9902
    instance = self.instance
9903
    pnode = instance.primary_node
9904
    snode = self.op.remote_node
9905

    
9906
    # create a fake disk info for _GenerateDiskTemplate
9907
    disk_info = [{"size": d.size, "mode": d.mode,
9908
                  "vg": d.logical_id[0]} for d in instance.disks]
9909
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9910
                                      instance.name, pnode, [snode],
9911
                                      disk_info, None, None, 0, feedback_fn)
9912
    info = _GetInstanceInfoText(instance)
9913
    feedback_fn("Creating aditional volumes...")
9914
    # first, create the missing data and meta devices
9915
    for disk in new_disks:
9916
      # unfortunately this is... not too nice
9917
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9918
                            info, True)
9919
      for child in disk.children:
9920
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9921
    # at this stage, all new LVs have been created, we can rename the
9922
    # old ones
9923
    feedback_fn("Renaming original volumes...")
9924
    rename_list = [(o, n.children[0].logical_id)
9925
                   for (o, n) in zip(instance.disks, new_disks)]
9926
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9927
    result.Raise("Failed to rename original LVs")
9928

    
9929
    feedback_fn("Initializing DRBD devices...")
9930
    # all child devices are in place, we can now create the DRBD devices
9931
    for disk in new_disks:
9932
      for node in [pnode, snode]:
9933
        f_create = node == pnode
9934
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9935

    
9936
    # at this point, the instance has been modified
9937
    instance.disk_template = constants.DT_DRBD8
9938
    instance.disks = new_disks
9939
    self.cfg.Update(instance, feedback_fn)
9940

    
9941
    # disks are created, waiting for sync
9942
    disk_abort = not _WaitForSync(self, instance,
9943
                                  oneshot=not self.op.wait_for_sync)
9944
    if disk_abort:
9945
      raise errors.OpExecError("There are some degraded disks for"
9946
                               " this instance, please cleanup manually")
9947

    
9948
  def _ConvertDrbdToPlain(self, feedback_fn):
9949
    """Converts an instance from drbd to plain.
9950

9951
    """
9952
    instance = self.instance
9953
    assert len(instance.secondary_nodes) == 1
9954
    pnode = instance.primary_node
9955
    snode = instance.secondary_nodes[0]
9956
    feedback_fn("Converting template to plain")
9957

    
9958
    old_disks = instance.disks
9959
    new_disks = [d.children[0] for d in old_disks]
9960

    
9961
    # copy over size and mode
9962
    for parent, child in zip(old_disks, new_disks):
9963
      child.size = parent.size
9964
      child.mode = parent.mode
9965

    
9966
    # update instance structure
9967
    instance.disks = new_disks
9968
    instance.disk_template = constants.DT_PLAIN
9969
    self.cfg.Update(instance, feedback_fn)
9970

    
9971
    feedback_fn("Removing volumes on the secondary node...")
9972
    for disk in old_disks:
9973
      self.cfg.SetDiskID(disk, snode)
9974
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9975
      if msg:
9976
        self.LogWarning("Could not remove block device %s on node %s,"
9977
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9978

    
9979
    feedback_fn("Removing unneeded volumes on the primary node...")
9980
    for idx, disk in enumerate(old_disks):
9981
      meta = disk.children[1]
9982
      self.cfg.SetDiskID(meta, pnode)
9983
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9984
      if msg:
9985
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9986
                        " continuing anyway: %s", idx, pnode, msg)
9987

    
9988
  def Exec(self, feedback_fn):
9989
    """Modifies an instance.
9990

9991
    All parameters take effect only at the next restart of the instance.
9992

9993
    """
9994
    # Process here the warnings from CheckPrereq, as we don't have a
9995
    # feedback_fn there.
9996
    for warn in self.warn:
9997
      feedback_fn("WARNING: %s" % warn)
9998

    
9999
    result = []
10000
    instance = self.instance
10001
    # disk changes
10002
    for disk_op, disk_dict in self.op.disks:
10003
      if disk_op == constants.DDM_REMOVE:
10004
        # remove the last disk
10005
        device = instance.disks.pop()
10006
        device_idx = len(instance.disks)
10007
        for node, disk in device.ComputeNodeTree(instance.primary_node):
10008
          self.cfg.SetDiskID(disk, node)
10009
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
10010
          if msg:
10011
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
10012
                            " continuing anyway", device_idx, node, msg)
10013
        result.append(("disk/%d" % device_idx, "remove"))
10014
      elif disk_op == constants.DDM_ADD:
10015
        # add a new disk
10016
        if instance.disk_template in (constants.DT_FILE,
10017
                                        constants.DT_SHARED_FILE):
10018
          file_driver, file_path = instance.disks[0].logical_id
10019
          file_path = os.path.dirname(file_path)
10020
        else:
10021
          file_driver = file_path = None
10022
        disk_idx_base = len(instance.disks)
10023
        new_disk = _GenerateDiskTemplate(self,
10024
                                         instance.disk_template,
10025
                                         instance.name, instance.primary_node,
10026
                                         instance.secondary_nodes,
10027
                                         [disk_dict],
10028
                                         file_path,
10029
                                         file_driver,
10030
                                         disk_idx_base, feedback_fn)[0]
10031
        instance.disks.append(new_disk)
10032
        info = _GetInstanceInfoText(instance)
10033

    
10034
        if self.adopt_disks:
10035
          if instance.disk_template == constants.DT_PLAIN:
10036
            # rename LV to the a newly-generated name; we need to construct
10037
            # 'fake' LV disk with the old data, plus the new unique_id
10038
            tmp_disk = objects.Disk.FromDict(disk_dict)
10039
            rename_to = tmp_disk.logical_id
10040
            tmp_disk.logical_id = (tmp_disk.logical_id[0], disk_dict["adopt"])
10041
            self.cfg.SetDiskID(tmp_disk, instance.primary_node)
10042
            result = self.rpc.call_blockdev_rename(instance.primary_node,
10043
                                                   [(tmp_disk, rename_to)])
10044
            result.Raise("Failed to rename adopted LV")
10045
          result.append(("disk/%d" % disk_idx_base, "add:adopt=%s,mode=%s" %
10046
                         (disk_dict["adopt"], new_disk.mode)))
10047
        else:
10048
          logging.info("Creating volume %s for instance %s",
10049
                       new_disk.iv_name, instance.name)
10050
          # Note: this needs to be kept in sync with _CreateDisks
10051
          #HARDCODE
10052
          for node in instance.all_nodes:
10053
            f_create = node == instance.primary_node
10054
            try:
10055
              _CreateBlockDev(self, node, instance, new_disk,
10056
                              f_create, info, f_create)
10057
            except errors.OpExecError, err:
10058
              self.LogWarning("Failed to create volume %s (%s) on"
10059
                              " node %s: %s",
10060
                              new_disk.iv_name, new_disk, node, err)
10061
          result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
10062
                         (new_disk.size, new_disk.mode)))
10063
      else:
10064
        # change a given disk
10065
        instance.disks[disk_op].mode = disk_dict['mode']
10066
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
10067

    
10068
    if self.op.disk_template:
10069
      r_shut = _ShutdownInstanceDisks(self, instance)
10070
      if not r_shut:
10071
        raise errors.OpExecError("Cannot shutdown instance disks, unable to"
10072
                                 " proceed with disk template conversion")
10073
      mode = (instance.disk_template, self.op.disk_template)
10074
      try:
10075
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
10076
      except:
10077
        self.cfg.ReleaseDRBDMinors(instance.name)
10078
        raise
10079
      result.append(("disk_template", self.op.disk_template))
10080

    
10081
    # NIC changes
10082
    for nic_op, nic_dict in self.op.nics:
10083
      if nic_op == constants.DDM_REMOVE:
10084
        # remove the last nic
10085
        del instance.nics[-1]
10086
        result.append(("nic.%d" % len(instance.nics), "remove"))
10087
      elif nic_op == constants.DDM_ADD:
10088
        # mac and bridge should be set, by now
10089
        mac = nic_dict['mac']
10090
        ip = nic_dict.get('ip', None)
10091
        nicparams = self.nic_pinst[constants.DDM_ADD]
10092
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
10093
        instance.nics.append(new_nic)
10094
        result.append(("nic.%d" % (len(instance.nics) - 1),
10095
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
10096
                       (new_nic.mac, new_nic.ip,
10097
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
10098
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
10099
                       )))
10100
      else:
10101
        for key in 'mac', 'ip':
10102
          if key in nic_dict:
10103
            setattr(instance.nics[nic_op], key, nic_dict[key])
10104
        if nic_op in self.nic_pinst:
10105
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
10106
        for key, val in nic_dict.iteritems():
10107
          result.append(("nic.%s/%d" % (key, nic_op), val))
10108

    
10109
    # hvparams changes
10110
    if self.op.hvparams:
10111
      instance.hvparams = self.hv_inst
10112
      for key, val in self.op.hvparams.iteritems():
10113
        result.append(("hv/%s" % key, val))
10114

    
10115
    # beparams changes
10116
    if self.op.beparams:
10117
      instance.beparams = self.be_inst
10118
      for key, val in self.op.beparams.iteritems():
10119
        result.append(("be/%s" % key, val))
10120

    
10121
    # OS change
10122
    if self.op.os_name:
10123
      instance.os = self.op.os_name
10124

    
10125
    # osparams changes
10126
    if self.op.osparams:
10127
      instance.osparams = self.os_inst
10128
      for key, val in self.op.osparams.iteritems():
10129
        result.append(("os/%s" % key, val))
10130

    
10131
    self.cfg.Update(instance, feedback_fn)
10132

    
10133
    return result
10134

    
10135
  _DISK_CONVERSIONS = {
10136
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
10137
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
10138
    }
10139

    
10140

    
10141
class LUBackupQuery(NoHooksLU):
10142
  """Query the exports list
10143

10144
  """
10145
  REQ_BGL = False
10146

    
10147
  def ExpandNames(self):
10148
    self.needed_locks = {}
10149
    self.share_locks[locking.LEVEL_NODE] = 1
10150
    if not self.op.nodes:
10151
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10152
    else:
10153
      self.needed_locks[locking.LEVEL_NODE] = \
10154
        _GetWantedNodes(self, self.op.nodes)
10155

    
10156
  def Exec(self, feedback_fn):
10157
    """Compute the list of all the exported system images.
10158

10159
    @rtype: dict
10160
    @return: a dictionary with the structure node->(export-list)
10161
        where export-list is a list of the instances exported on
10162
        that node.
10163

10164
    """
10165
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
10166
    rpcresult = self.rpc.call_export_list(self.nodes)
10167
    result = {}
10168
    for node in rpcresult:
10169
      if rpcresult[node].fail_msg:
10170
        result[node] = False
10171
      else:
10172
        result[node] = rpcresult[node].payload
10173

    
10174
    return result
10175

    
10176

    
10177
class LUBackupPrepare(NoHooksLU):
10178
  """Prepares an instance for an export and returns useful information.
10179

10180
  """
10181
  REQ_BGL = False
10182

    
10183
  def ExpandNames(self):
10184
    self._ExpandAndLockInstance()
10185

    
10186
  def CheckPrereq(self):
10187
    """Check prerequisites.
10188

10189
    """
10190
    instance_name = self.op.instance_name
10191

    
10192
    self.instance = self.cfg.GetInstanceInfo(instance_name)
10193
    assert self.instance is not None, \
10194
          "Cannot retrieve locked instance %s" % self.op.instance_name
10195
    _CheckNodeOnline(self, self.instance.primary_node)
10196

    
10197
    self._cds = _GetClusterDomainSecret()
10198

    
10199
  def Exec(self, feedback_fn):
10200
    """Prepares an instance for an export.
10201

10202
    """
10203
    instance = self.instance
10204

    
10205
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
10206
      salt = utils.GenerateSecret(8)
10207

    
10208
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
10209
      result = self.rpc.call_x509_cert_create(instance.primary_node,
10210
                                              constants.RIE_CERT_VALIDITY)
10211
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
10212

    
10213
      (name, cert_pem) = result.payload
10214

    
10215
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
10216
                                             cert_pem)
10217

    
10218
      return {
10219
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
10220
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
10221
                          salt),
10222
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
10223
        }
10224

    
10225
    return None
10226

    
10227

    
10228
class LUBackupExport(LogicalUnit):
10229
  """Export an instance to an image in the cluster.
10230

10231
  """
10232
  HPATH = "instance-export"
10233
  HTYPE = constants.HTYPE_INSTANCE
10234
  REQ_BGL = False
10235

    
10236
  def CheckArguments(self):
10237
    """Check the arguments.
10238

10239
    """
10240
    self.x509_key_name = self.op.x509_key_name
10241
    self.dest_x509_ca_pem = self.op.destination_x509_ca
10242

    
10243
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
10244
      if not self.x509_key_name:
10245
        raise errors.OpPrereqError("Missing X509 key name for encryption",
10246
                                   errors.ECODE_INVAL)
10247

    
10248
      if not self.dest_x509_ca_pem:
10249
        raise errors.OpPrereqError("Missing destination X509 CA",
10250
                                   errors.ECODE_INVAL)
10251

    
10252
  def ExpandNames(self):
10253
    self._ExpandAndLockInstance()
10254

    
10255
    # Lock all nodes for local exports
10256
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10257
      # FIXME: lock only instance primary and destination node
10258
      #
10259
      # Sad but true, for now we have do lock all nodes, as we don't know where
10260
      # the previous export might be, and in this LU we search for it and
10261
      # remove it from its current node. In the future we could fix this by:
10262
      #  - making a tasklet to search (share-lock all), then create the
10263
      #    new one, then one to remove, after
10264
      #  - removing the removal operation altogether
10265
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10266

    
10267
  def DeclareLocks(self, level):
10268
    """Last minute lock declaration."""
10269
    # All nodes are locked anyway, so nothing to do here.
10270

    
10271
  def BuildHooksEnv(self):
10272
    """Build hooks env.
10273

10274
    This will run on the master, primary node and target node.
10275

10276
    """
10277
    env = {
10278
      "EXPORT_MODE": self.op.mode,
10279
      "EXPORT_NODE": self.op.target_node,
10280
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
10281
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
10282
      # TODO: Generic function for boolean env variables
10283
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
10284
      }
10285

    
10286
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
10287

    
10288
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
10289

    
10290
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10291
      nl.append(self.op.target_node)
10292

    
10293
    return env, nl, nl
10294

    
10295
  def CheckPrereq(self):
10296
    """Check prerequisites.
10297

10298
    This checks that the instance and node names are valid.
10299

10300
    """
10301
    instance_name = self.op.instance_name
10302

    
10303
    self.instance = self.cfg.GetInstanceInfo(instance_name)
10304
    assert self.instance is not None, \
10305
          "Cannot retrieve locked instance %s" % self.op.instance_name
10306
    _CheckNodeOnline(self, self.instance.primary_node)
10307

    
10308
    if (self.op.remove_instance and self.instance.admin_up and
10309
        not self.op.shutdown):
10310
      raise errors.OpPrereqError("Can not remove instance without shutting it"
10311
                                 " down before")
10312

    
10313
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10314
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
10315
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
10316
      assert self.dst_node is not None
10317

    
10318
      _CheckNodeOnline(self, self.dst_node.name)
10319
      _CheckNodeNotDrained(self, self.dst_node.name)
10320

    
10321
      self._cds = None
10322
      self.dest_disk_info = None
10323
      self.dest_x509_ca = None
10324

    
10325
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
10326
      self.dst_node = None
10327

    
10328
      if len(self.op.target_node) != len(self.instance.disks):
10329
        raise errors.OpPrereqError(("Received destination information for %s"
10330
                                    " disks, but instance %s has %s disks") %
10331
                                   (len(self.op.target_node), instance_name,
10332
                                    len(self.instance.disks)),
10333
                                   errors.ECODE_INVAL)
10334

    
10335
      cds = _GetClusterDomainSecret()
10336

    
10337
      # Check X509 key name
10338
      try:
10339
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
10340
      except (TypeError, ValueError), err:
10341
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
10342

    
10343
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
10344
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
10345
                                   errors.ECODE_INVAL)
10346

    
10347
      # Load and verify CA
10348
      try:
10349
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
10350
      except OpenSSL.crypto.Error, err:
10351
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
10352
                                   (err, ), errors.ECODE_INVAL)
10353

    
10354
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
10355
      if errcode is not None:
10356
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
10357
                                   (msg, ), errors.ECODE_INVAL)
10358

    
10359
      self.dest_x509_ca = cert
10360

    
10361
      # Verify target information
10362
      disk_info = []
10363
      for idx, disk_data in enumerate(self.op.target_node):
10364
        try:
10365
          (host, port, magic) = \
10366
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
10367
        except errors.GenericError, err:
10368
          raise errors.OpPrereqError("Target info for disk %s: %s" %
10369
                                     (idx, err), errors.ECODE_INVAL)
10370

    
10371
        disk_info.append((host, port, magic))
10372

    
10373
      assert len(disk_info) == len(self.op.target_node)
10374
      self.dest_disk_info = disk_info
10375

    
10376
    else:
10377
      raise errors.ProgrammerError("Unhandled export mode %r" %
10378
                                   self.op.mode)
10379

    
10380
    # instance disk type verification
10381
    # TODO: Implement export support for file-based disks
10382
    for disk in self.instance.disks:
10383
      if disk.dev_type == constants.LD_FILE:
10384
        raise errors.OpPrereqError("Export not supported for instances with"
10385
                                   " file-based disks", errors.ECODE_INVAL)
10386

    
10387
  def _CleanupExports(self, feedback_fn):
10388
    """Removes exports of current instance from all other nodes.
10389

10390
    If an instance in a cluster with nodes A..D was exported to node C, its
10391
    exports will be removed from the nodes A, B and D.
10392

10393
    """
10394
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
10395

    
10396
    nodelist = self.cfg.GetNodeList()
10397
    nodelist.remove(self.dst_node.name)
10398

    
10399
    # on one-node clusters nodelist will be empty after the removal
10400
    # if we proceed the backup would be removed because OpBackupQuery
10401
    # substitutes an empty list with the full cluster node list.
10402
    iname = self.instance.name
10403
    if nodelist:
10404
      feedback_fn("Removing old exports for instance %s" % iname)
10405
      exportlist = self.rpc.call_export_list(nodelist)
10406
      for node in exportlist:
10407
        if exportlist[node].fail_msg:
10408
          continue
10409
        if iname in exportlist[node].payload:
10410
          msg = self.rpc.call_export_remove(node, iname).fail_msg
10411
          if msg:
10412
            self.LogWarning("Could not remove older export for instance %s"
10413
                            " on node %s: %s", iname, node, msg)
10414

    
10415
  def Exec(self, feedback_fn):
10416
    """Export an instance to an image in the cluster.
10417

10418
    """
10419
    assert self.op.mode in constants.EXPORT_MODES
10420

    
10421
    instance = self.instance
10422
    src_node = instance.primary_node
10423

    
10424
    if self.op.shutdown:
10425
      # shutdown the instance, but not the disks
10426
      feedback_fn("Shutting down instance %s" % instance.name)
10427
      result = self.rpc.call_instance_shutdown(src_node, instance,
10428
                                               self.op.shutdown_timeout)
10429
      # TODO: Maybe ignore failures if ignore_remove_failures is set
10430
      result.Raise("Could not shutdown instance %s on"
10431
                   " node %s" % (instance.name, src_node))
10432

    
10433
    # set the disks ID correctly since call_instance_start needs the
10434
    # correct drbd minor to create the symlinks
10435
    for disk in instance.disks:
10436
      self.cfg.SetDiskID(disk, src_node)
10437

    
10438
    activate_disks = (not instance.admin_up)
10439

    
10440
    if activate_disks:
10441
      # Activate the instance disks if we'exporting a stopped instance
10442
      feedback_fn("Activating disks for %s" % instance.name)
10443
      _StartInstanceDisks(self, instance, None)
10444

    
10445
    try:
10446
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
10447
                                                     instance)
10448

    
10449
      helper.CreateSnapshots()
10450
      try:
10451
        if (self.op.shutdown and instance.admin_up and
10452
            not self.op.remove_instance):
10453
          assert not activate_disks
10454
          feedback_fn("Starting instance %s" % instance.name)
10455
          result = self.rpc.call_instance_start(src_node, instance, None, None)
10456
          msg = result.fail_msg
10457
          if msg:
10458
            feedback_fn("Failed to start instance: %s" % msg)
10459
            _ShutdownInstanceDisks(self, instance)
10460
            raise errors.OpExecError("Could not start instance: %s" % msg)
10461

    
10462
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
10463
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
10464
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
10465
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
10466
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
10467

    
10468
          (key_name, _, _) = self.x509_key_name
10469

    
10470
          dest_ca_pem = \
10471
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
10472
                                            self.dest_x509_ca)
10473

    
10474
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
10475
                                                     key_name, dest_ca_pem,
10476
                                                     timeouts)
10477
      finally:
10478
        helper.Cleanup()
10479

    
10480
      # Check for backwards compatibility
10481
      assert len(dresults) == len(instance.disks)
10482
      assert compat.all(isinstance(i, bool) for i in dresults), \
10483
             "Not all results are boolean: %r" % dresults
10484

    
10485
    finally:
10486
      if activate_disks:
10487
        feedback_fn("Deactivating disks for %s" % instance.name)
10488
        _ShutdownInstanceDisks(self, instance)
10489

    
10490
    if not (compat.all(dresults) and fin_resu):
10491
      failures = []
10492
      if not fin_resu:
10493
        failures.append("export finalization")
10494
      if not compat.all(dresults):
10495
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
10496
                               if not dsk)
10497
        failures.append("disk export: disk(s) %s" % fdsk)
10498

    
10499
      raise errors.OpExecError("Export failed, errors in %s" %
10500
                               utils.CommaJoin(failures))
10501

    
10502
    # At this point, the export was successful, we can cleanup/finish
10503

    
10504
    # Remove instance if requested
10505
    if self.op.remove_instance:
10506
      feedback_fn("Removing instance %s" % instance.name)
10507
      _RemoveInstance(self, feedback_fn, instance,
10508
                      self.op.ignore_remove_failures)
10509

    
10510
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10511
      self._CleanupExports(feedback_fn)
10512

    
10513
    return fin_resu, dresults
10514

    
10515

    
10516
class LUBackupRemove(NoHooksLU):
10517
  """Remove exports related to the named instance.
10518

10519
  """
10520
  REQ_BGL = False
10521

    
10522
  def ExpandNames(self):
10523
    self.needed_locks = {}
10524
    # We need all nodes to be locked in order for RemoveExport to work, but we
10525
    # don't need to lock the instance itself, as nothing will happen to it (and
10526
    # we can remove exports also for a removed instance)
10527
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10528

    
10529
  def Exec(self, feedback_fn):
10530
    """Remove any export.
10531

10532
    """
10533
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
10534
    # If the instance was not found we'll try with the name that was passed in.
10535
    # This will only work if it was an FQDN, though.
10536
    fqdn_warn = False
10537
    if not instance_name:
10538
      fqdn_warn = True
10539
      instance_name = self.op.instance_name
10540

    
10541
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
10542
    exportlist = self.rpc.call_export_list(locked_nodes)
10543
    found = False
10544
    for node in exportlist:
10545
      msg = exportlist[node].fail_msg
10546
      if msg:
10547
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
10548
        continue
10549
      if instance_name in exportlist[node].payload:
10550
        found = True
10551
        result = self.rpc.call_export_remove(node, instance_name)
10552
        msg = result.fail_msg
10553
        if msg:
10554
          logging.error("Could not remove export for instance %s"
10555
                        " on node %s: %s", instance_name, node, msg)
10556

    
10557
    if fqdn_warn and not found:
10558
      feedback_fn("Export not found. If trying to remove an export belonging"
10559
                  " to a deleted instance please use its Fully Qualified"
10560
                  " Domain Name.")
10561

    
10562

    
10563
class LUGroupAdd(LogicalUnit):
10564
  """Logical unit for creating node groups.
10565

10566
  """
10567
  HPATH = "group-add"
10568
  HTYPE = constants.HTYPE_GROUP
10569
  REQ_BGL = False
10570

    
10571
  def ExpandNames(self):
10572
    # We need the new group's UUID here so that we can create and acquire the
10573
    # corresponding lock. Later, in Exec(), we'll indicate to cfg.AddNodeGroup
10574
    # that it should not check whether the UUID exists in the configuration.
10575
    self.group_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
10576
    self.needed_locks = {}
10577
    self.add_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
10578

    
10579
  def CheckPrereq(self):
10580
    """Check prerequisites.
10581

10582
    This checks that the given group name is not an existing node group
10583
    already.
10584

10585
    """
10586
    try:
10587
      existing_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10588
    except errors.OpPrereqError:
10589
      pass
10590
    else:
10591
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
10592
                                 " node group (UUID: %s)" %
10593
                                 (self.op.group_name, existing_uuid),
10594
                                 errors.ECODE_EXISTS)
10595

    
10596
    if self.op.ndparams:
10597
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
10598

    
10599
  def BuildHooksEnv(self):
10600
    """Build hooks env.
10601

10602
    """
10603
    env = {
10604
      "GROUP_NAME": self.op.group_name,
10605
      }
10606
    mn = self.cfg.GetMasterNode()
10607
    return env, [mn], [mn]
10608

    
10609
  def Exec(self, feedback_fn):
10610
    """Add the node group to the cluster.
10611

10612
    """
10613
    group_obj = objects.NodeGroup(name=self.op.group_name, members=[],
10614
                                  uuid=self.group_uuid,
10615
                                  alloc_policy=self.op.alloc_policy,
10616
                                  ndparams=self.op.ndparams)
10617

    
10618
    self.cfg.AddNodeGroup(group_obj, self.proc.GetECId(), check_uuid=False)
10619
    del self.remove_locks[locking.LEVEL_NODEGROUP]
10620

    
10621

    
10622
class LUGroupAssignNodes(NoHooksLU):
10623
  """Logical unit for assigning nodes to groups.
10624

10625
  """
10626
  REQ_BGL = False
10627

    
10628
  def ExpandNames(self):
10629
    # These raise errors.OpPrereqError on their own:
10630
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10631
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
10632

    
10633
    # We want to lock all the affected nodes and groups. We have readily
10634
    # available the list of nodes, and the *destination* group. To gather the
10635
    # list of "source" groups, we need to fetch node information later on.
10636
    self.needed_locks = {
10637
      locking.LEVEL_NODEGROUP: set([self.group_uuid]),
10638
      locking.LEVEL_NODE: self.op.nodes,
10639
      }
10640

    
10641
  def DeclareLocks(self, level):
10642
    if level == locking.LEVEL_NODEGROUP:
10643
      assert len(self.needed_locks[locking.LEVEL_NODEGROUP]) == 1
10644

    
10645
      # Try to get all affected nodes' groups without having the group or node
10646
      # lock yet. Needs verification later in the code flow.
10647
      groups = self.cfg.GetNodeGroupsFromNodes(self.op.nodes)
10648

    
10649
      self.needed_locks[locking.LEVEL_NODEGROUP].update(groups)
10650

    
10651
  def CheckPrereq(self):
10652
    """Check prerequisites.
10653

10654
    """
10655
    assert self.needed_locks[locking.LEVEL_NODEGROUP]
10656
    assert (frozenset(self.acquired_locks[locking.LEVEL_NODE]) ==
10657
            frozenset(self.op.nodes))
10658

    
10659
    expected_locks = (set([self.group_uuid]) |
10660
                      self.cfg.GetNodeGroupsFromNodes(self.op.nodes))
10661
    actual_locks = self.acquired_locks[locking.LEVEL_NODEGROUP]
10662
    if actual_locks != expected_locks:
10663
      raise errors.OpExecError("Nodes changed groups since locks were acquired,"
10664
                               " current groups are '%s', used to be '%s'" %
10665
                               (utils.CommaJoin(expected_locks),
10666
                                utils.CommaJoin(actual_locks)))
10667

    
10668
    self.node_data = self.cfg.GetAllNodesInfo()
10669
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
10670
    instance_data = self.cfg.GetAllInstancesInfo()
10671

    
10672
    if self.group is None:
10673
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10674
                               (self.op.group_name, self.group_uuid))
10675

    
10676
    (new_splits, previous_splits) = \
10677
      self.CheckAssignmentForSplitInstances([(node, self.group_uuid)
10678
                                             for node in self.op.nodes],
10679
                                            self.node_data, instance_data)
10680

    
10681
    if new_splits:
10682
      fmt_new_splits = utils.CommaJoin(utils.NiceSort(new_splits))
10683

    
10684
      if not self.op.force:
10685
        raise errors.OpExecError("The following instances get split by this"
10686
                                 " change and --force was not given: %s" %
10687
                                 fmt_new_splits)
10688
      else:
10689
        self.LogWarning("This operation will split the following instances: %s",
10690
                        fmt_new_splits)
10691

    
10692
        if previous_splits:
10693
          self.LogWarning("In addition, these already-split instances continue"
10694
                          " to be split across groups: %s",
10695
                          utils.CommaJoin(utils.NiceSort(previous_splits)))
10696

    
10697
  def Exec(self, feedback_fn):
10698
    """Assign nodes to a new group.
10699

10700
    """
10701
    for node in self.op.nodes:
10702
      self.node_data[node].group = self.group_uuid
10703

    
10704
    # FIXME: Depends on side-effects of modifying the result of
10705
    # C{cfg.GetAllNodesInfo}
10706

    
10707
    self.cfg.Update(self.group, feedback_fn) # Saves all modified nodes.
10708

    
10709
  @staticmethod
10710
  def CheckAssignmentForSplitInstances(changes, node_data, instance_data):
10711
    """Check for split instances after a node assignment.
10712

10713
    This method considers a series of node assignments as an atomic operation,
10714
    and returns information about split instances after applying the set of
10715
    changes.
10716

10717
    In particular, it returns information about newly split instances, and
10718
    instances that were already split, and remain so after the change.
10719

10720
    Only instances whose disk template is listed in constants.DTS_INT_MIRROR are
10721
    considered.
10722

10723
    @type changes: list of (node_name, new_group_uuid) pairs.
10724
    @param changes: list of node assignments to consider.
10725
    @param node_data: a dict with data for all nodes
10726
    @param instance_data: a dict with all instances to consider
10727
    @rtype: a two-tuple
10728
    @return: a list of instances that were previously okay and result split as a
10729
      consequence of this change, and a list of instances that were previously
10730
      split and this change does not fix.
10731

10732
    """
10733
    changed_nodes = dict((node, group) for node, group in changes
10734
                         if node_data[node].group != group)
10735

    
10736
    all_split_instances = set()
10737
    previously_split_instances = set()
10738

    
10739
    def InstanceNodes(instance):
10740
      return [instance.primary_node] + list(instance.secondary_nodes)
10741

    
10742
    for inst in instance_data.values():
10743
      if inst.disk_template not in constants.DTS_INT_MIRROR:
10744
        continue
10745

    
10746
      instance_nodes = InstanceNodes(inst)
10747

    
10748
      if len(set(node_data[node].group for node in instance_nodes)) > 1:
10749
        previously_split_instances.add(inst.name)
10750

    
10751
      if len(set(changed_nodes.get(node, node_data[node].group)
10752
                 for node in instance_nodes)) > 1:
10753
        all_split_instances.add(inst.name)
10754

    
10755
    return (list(all_split_instances - previously_split_instances),
10756
            list(previously_split_instances & all_split_instances))
10757

    
10758

    
10759
class _GroupQuery(_QueryBase):
10760

    
10761
  FIELDS = query.GROUP_FIELDS
10762

    
10763
  def ExpandNames(self, lu):
10764
    lu.needed_locks = {}
10765

    
10766
    self._all_groups = lu.cfg.GetAllNodeGroupsInfo()
10767
    name_to_uuid = dict((g.name, g.uuid) for g in self._all_groups.values())
10768

    
10769
    if not self.names:
10770
      self.wanted = [name_to_uuid[name]
10771
                     for name in utils.NiceSort(name_to_uuid.keys())]
10772
    else:
10773
      # Accept names to be either names or UUIDs.
10774
      missing = []
10775
      self.wanted = []
10776
      all_uuid = frozenset(self._all_groups.keys())
10777

    
10778
      for name in self.names:
10779
        if name in all_uuid:
10780
          self.wanted.append(name)
10781
        elif name in name_to_uuid:
10782
          self.wanted.append(name_to_uuid[name])
10783
        else:
10784
          missing.append(name)
10785

    
10786
      if missing:
10787
        raise errors.OpPrereqError("Some groups do not exist: %s" %
10788
                                   utils.CommaJoin(missing),
10789
                                   errors.ECODE_NOENT)
10790

    
10791
  def DeclareLocks(self, lu, level):
10792
    pass
10793

    
10794
  def _GetQueryData(self, lu):
10795
    """Computes the list of node groups and their attributes.
10796

10797
    """
10798
    do_nodes = query.GQ_NODE in self.requested_data
10799
    do_instances = query.GQ_INST in self.requested_data
10800

    
10801
    group_to_nodes = None
10802
    group_to_instances = None
10803

    
10804
    # For GQ_NODE, we need to map group->[nodes], and group->[instances] for
10805
    # GQ_INST. The former is attainable with just GetAllNodesInfo(), but for the
10806
    # latter GetAllInstancesInfo() is not enough, for we have to go through
10807
    # instance->node. Hence, we will need to process nodes even if we only need
10808
    # instance information.
10809
    if do_nodes or do_instances:
10810
      all_nodes = lu.cfg.GetAllNodesInfo()
10811
      group_to_nodes = dict((uuid, []) for uuid in self.wanted)
10812
      node_to_group = {}
10813

    
10814
      for node in all_nodes.values():
10815
        if node.group in group_to_nodes:
10816
          group_to_nodes[node.group].append(node.name)
10817
          node_to_group[node.name] = node.group
10818

    
10819
      if do_instances:
10820
        all_instances = lu.cfg.GetAllInstancesInfo()
10821
        group_to_instances = dict((uuid, []) for uuid in self.wanted)
10822

    
10823
        for instance in all_instances.values():
10824
          node = instance.primary_node
10825
          if node in node_to_group:
10826
            group_to_instances[node_to_group[node]].append(instance.name)
10827

    
10828
        if not do_nodes:
10829
          # Do not pass on node information if it was not requested.
10830
          group_to_nodes = None
10831

    
10832
    return query.GroupQueryData([self._all_groups[uuid]
10833
                                 for uuid in self.wanted],
10834
                                group_to_nodes, group_to_instances)
10835

    
10836

    
10837
class LUGroupQuery(NoHooksLU):
10838
  """Logical unit for querying node groups.
10839

10840
  """
10841
  REQ_BGL = False
10842

    
10843
  def CheckArguments(self):
10844
    self.gq = _GroupQuery(self.op.names, self.op.output_fields, False)
10845

    
10846
  def ExpandNames(self):
10847
    self.gq.ExpandNames(self)
10848

    
10849
  def Exec(self, feedback_fn):
10850
    return self.gq.OldStyleQuery(self)
10851

    
10852

    
10853
class LUGroupSetParams(LogicalUnit):
10854
  """Modifies the parameters of a node group.
10855

10856
  """
10857
  HPATH = "group-modify"
10858
  HTYPE = constants.HTYPE_GROUP
10859
  REQ_BGL = False
10860

    
10861
  def CheckArguments(self):
10862
    all_changes = [
10863
      self.op.ndparams,
10864
      self.op.alloc_policy,
10865
      ]
10866

    
10867
    if all_changes.count(None) == len(all_changes):
10868
      raise errors.OpPrereqError("Please pass at least one modification",
10869
                                 errors.ECODE_INVAL)
10870

    
10871
  def ExpandNames(self):
10872
    # This raises errors.OpPrereqError on its own:
10873
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10874

    
10875
    self.needed_locks = {
10876
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10877
      }
10878

    
10879
  def CheckPrereq(self):
10880
    """Check prerequisites.
10881

10882
    """
10883
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
10884

    
10885
    if self.group is None:
10886
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10887
                               (self.op.group_name, self.group_uuid))
10888

    
10889
    if self.op.ndparams:
10890
      new_ndparams = _GetUpdatedParams(self.group.ndparams, self.op.ndparams)
10891
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
10892
      self.new_ndparams = new_ndparams
10893

    
10894
  def BuildHooksEnv(self):
10895
    """Build hooks env.
10896

10897
    """
10898
    env = {
10899
      "GROUP_NAME": self.op.group_name,
10900
      "NEW_ALLOC_POLICY": self.op.alloc_policy,
10901
      }
10902
    mn = self.cfg.GetMasterNode()
10903
    return env, [mn], [mn]
10904

    
10905
  def Exec(self, feedback_fn):
10906
    """Modifies the node group.
10907

10908
    """
10909
    result = []
10910

    
10911
    if self.op.ndparams:
10912
      self.group.ndparams = self.new_ndparams
10913
      result.append(("ndparams", str(self.group.ndparams)))
10914

    
10915
    if self.op.alloc_policy:
10916
      self.group.alloc_policy = self.op.alloc_policy
10917

    
10918
    self.cfg.Update(self.group, feedback_fn)
10919
    return result
10920

    
10921

    
10922

    
10923
class LUGroupRemove(LogicalUnit):
10924
  HPATH = "group-remove"
10925
  HTYPE = constants.HTYPE_GROUP
10926
  REQ_BGL = False
10927

    
10928
  def ExpandNames(self):
10929
    # This will raises errors.OpPrereqError on its own:
10930
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10931
    self.needed_locks = {
10932
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10933
      }
10934

    
10935
  def CheckPrereq(self):
10936
    """Check prerequisites.
10937

10938
    This checks that the given group name exists as a node group, that is
10939
    empty (i.e., contains no nodes), and that is not the last group of the
10940
    cluster.
10941

10942
    """
10943
    # Verify that the group is empty.
10944
    group_nodes = [node.name
10945
                   for node in self.cfg.GetAllNodesInfo().values()
10946
                   if node.group == self.group_uuid]
10947

    
10948
    if group_nodes:
10949
      raise errors.OpPrereqError("Group '%s' not empty, has the following"
10950
                                 " nodes: %s" %
10951
                                 (self.op.group_name,
10952
                                  utils.CommaJoin(utils.NiceSort(group_nodes))),
10953
                                 errors.ECODE_STATE)
10954

    
10955
    # Verify the cluster would not be left group-less.
10956
    if len(self.cfg.GetNodeGroupList()) == 1:
10957
      raise errors.OpPrereqError("Group '%s' is the only group,"
10958
                                 " cannot be removed" %
10959
                                 self.op.group_name,
10960
                                 errors.ECODE_STATE)
10961

    
10962
  def BuildHooksEnv(self):
10963
    """Build hooks env.
10964

10965
    """
10966
    env = {
10967
      "GROUP_NAME": self.op.group_name,
10968
      }
10969
    mn = self.cfg.GetMasterNode()
10970
    return env, [mn], [mn]
10971

    
10972
  def Exec(self, feedback_fn):
10973
    """Remove the node group.
10974

10975
    """
10976
    try:
10977
      self.cfg.RemoveNodeGroup(self.group_uuid)
10978
    except errors.ConfigurationError:
10979
      raise errors.OpExecError("Group '%s' with UUID %s disappeared" %
10980
                               (self.op.group_name, self.group_uuid))
10981

    
10982
    self.remove_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
10983

    
10984

    
10985
class LUGroupRename(LogicalUnit):
10986
  HPATH = "group-rename"
10987
  HTYPE = constants.HTYPE_GROUP
10988
  REQ_BGL = False
10989

    
10990
  def ExpandNames(self):
10991
    # This raises errors.OpPrereqError on its own:
10992
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.old_name)
10993

    
10994
    self.needed_locks = {
10995
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10996
      }
10997

    
10998
  def CheckPrereq(self):
10999
    """Check prerequisites.
11000

11001
    This checks that the given old_name exists as a node group, and that
11002
    new_name doesn't.
11003

11004
    """
11005
    try:
11006
      new_name_uuid = self.cfg.LookupNodeGroup(self.op.new_name)
11007
    except errors.OpPrereqError:
11008
      pass
11009
    else:
11010
      raise errors.OpPrereqError("Desired new name '%s' clashes with existing"
11011
                                 " node group (UUID: %s)" %
11012
                                 (self.op.new_name, new_name_uuid),
11013
                                 errors.ECODE_EXISTS)
11014

    
11015
  def BuildHooksEnv(self):
11016
    """Build hooks env.
11017

11018
    """
11019
    env = {
11020
      "OLD_NAME": self.op.old_name,
11021
      "NEW_NAME": self.op.new_name,
11022
      }
11023

    
11024
    mn = self.cfg.GetMasterNode()
11025
    all_nodes = self.cfg.GetAllNodesInfo()
11026
    run_nodes = [mn]
11027
    all_nodes.pop(mn, None)
11028

    
11029
    for node in all_nodes.values():
11030
      if node.group == self.group_uuid:
11031
        run_nodes.append(node.name)
11032

    
11033
    return env, run_nodes, run_nodes
11034

    
11035
  def Exec(self, feedback_fn):
11036
    """Rename the node group.
11037

11038
    """
11039
    group = self.cfg.GetNodeGroup(self.group_uuid)
11040

    
11041
    if group is None:
11042
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11043
                               (self.op.old_name, self.group_uuid))
11044

    
11045
    group.name = self.op.new_name
11046
    self.cfg.Update(group, feedback_fn)
11047

    
11048
    return self.op.new_name
11049

    
11050

    
11051
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
11052
  """Generic tags LU.
11053

11054
  This is an abstract class which is the parent of all the other tags LUs.
11055

11056
  """
11057

    
11058
  def ExpandNames(self):
11059
    self.needed_locks = {}
11060
    if self.op.kind == constants.TAG_NODE:
11061
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
11062
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
11063
    elif self.op.kind == constants.TAG_INSTANCE:
11064
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
11065
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
11066

    
11067
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
11068
    # not possible to acquire the BGL based on opcode parameters)
11069

    
11070
  def CheckPrereq(self):
11071
    """Check prerequisites.
11072

11073
    """
11074
    if self.op.kind == constants.TAG_CLUSTER:
11075
      self.target = self.cfg.GetClusterInfo()
11076
    elif self.op.kind == constants.TAG_NODE:
11077
      self.target = self.cfg.GetNodeInfo(self.op.name)
11078
    elif self.op.kind == constants.TAG_INSTANCE:
11079
      self.target = self.cfg.GetInstanceInfo(self.op.name)
11080
    else:
11081
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
11082
                                 str(self.op.kind), errors.ECODE_INVAL)
11083

    
11084

    
11085
class LUTagsGet(TagsLU):
11086
  """Returns the tags of a given object.
11087

11088
  """
11089
  REQ_BGL = False
11090

    
11091
  def ExpandNames(self):
11092
    TagsLU.ExpandNames(self)
11093

    
11094
    # Share locks as this is only a read operation
11095
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
11096

    
11097
  def Exec(self, feedback_fn):
11098
    """Returns the tag list.
11099

11100
    """
11101
    return list(self.target.GetTags())
11102

    
11103

    
11104
class LUTagsSearch(NoHooksLU):
11105
  """Searches the tags for a given pattern.
11106

11107
  """
11108
  REQ_BGL = False
11109

    
11110
  def ExpandNames(self):
11111
    self.needed_locks = {}
11112

    
11113
  def CheckPrereq(self):
11114
    """Check prerequisites.
11115

11116
    This checks the pattern passed for validity by compiling it.
11117

11118
    """
11119
    try:
11120
      self.re = re.compile(self.op.pattern)
11121
    except re.error, err:
11122
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
11123
                                 (self.op.pattern, err), errors.ECODE_INVAL)
11124

    
11125
  def Exec(self, feedback_fn):
11126
    """Returns the tag list.
11127

11128
    """
11129
    cfg = self.cfg
11130
    tgts = [("/cluster", cfg.GetClusterInfo())]
11131
    ilist = cfg.GetAllInstancesInfo().values()
11132
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
11133
    nlist = cfg.GetAllNodesInfo().values()
11134
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
11135
    results = []
11136
    for path, target in tgts:
11137
      for tag in target.GetTags():
11138
        if self.re.search(tag):
11139
          results.append((path, tag))
11140
    return results
11141

    
11142

    
11143
class LUTagsSet(TagsLU):
11144
  """Sets a tag on a given object.
11145

11146
  """
11147
  REQ_BGL = False
11148

    
11149
  def CheckPrereq(self):
11150
    """Check prerequisites.
11151

11152
    This checks the type and length of the tag name and value.
11153

11154
    """
11155
    TagsLU.CheckPrereq(self)
11156
    for tag in self.op.tags:
11157
      objects.TaggableObject.ValidateTag(tag)
11158

    
11159
  def Exec(self, feedback_fn):
11160
    """Sets the tag.
11161

11162
    """
11163
    try:
11164
      for tag in self.op.tags:
11165
        self.target.AddTag(tag)
11166
    except errors.TagError, err:
11167
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
11168
    self.cfg.Update(self.target, feedback_fn)
11169

    
11170

    
11171
class LUTagsDel(TagsLU):
11172
  """Delete a list of tags from a given object.
11173

11174
  """
11175
  REQ_BGL = False
11176

    
11177
  def CheckPrereq(self):
11178
    """Check prerequisites.
11179

11180
    This checks that we have the given tag.
11181

11182
    """
11183
    TagsLU.CheckPrereq(self)
11184
    for tag in self.op.tags:
11185
      objects.TaggableObject.ValidateTag(tag)
11186
    del_tags = frozenset(self.op.tags)
11187
    cur_tags = self.target.GetTags()
11188

    
11189
    diff_tags = del_tags - cur_tags
11190
    if diff_tags:
11191
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
11192
      raise errors.OpPrereqError("Tag(s) %s not found" %
11193
                                 (utils.CommaJoin(diff_names), ),
11194
                                 errors.ECODE_NOENT)
11195

    
11196
  def Exec(self, feedback_fn):
11197
    """Remove the tag from the object.
11198

11199
    """
11200
    for tag in self.op.tags:
11201
      self.target.RemoveTag(tag)
11202
    self.cfg.Update(self.target, feedback_fn)
11203

    
11204

    
11205
class LUTestDelay(NoHooksLU):
11206
  """Sleep for a specified amount of time.
11207

11208
  This LU sleeps on the master and/or nodes for a specified amount of
11209
  time.
11210

11211
  """
11212
  REQ_BGL = False
11213

    
11214
  def ExpandNames(self):
11215
    """Expand names and set required locks.
11216

11217
    This expands the node list, if any.
11218

11219
    """
11220
    self.needed_locks = {}
11221
    if self.op.on_nodes:
11222
      # _GetWantedNodes can be used here, but is not always appropriate to use
11223
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
11224
      # more information.
11225
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
11226
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
11227

    
11228
  def _TestDelay(self):
11229
    """Do the actual sleep.
11230

11231
    """
11232
    if self.op.on_master:
11233
      if not utils.TestDelay(self.op.duration):
11234
        raise errors.OpExecError("Error during master delay test")
11235
    if self.op.on_nodes:
11236
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
11237
      for node, node_result in result.items():
11238
        node_result.Raise("Failure during rpc call to node %s" % node)
11239

    
11240
  def Exec(self, feedback_fn):
11241
    """Execute the test delay opcode, with the wanted repetitions.
11242

11243
    """
11244
    if self.op.repeat == 0:
11245
      self._TestDelay()
11246
    else:
11247
      top_value = self.op.repeat - 1
11248
      for i in range(self.op.repeat):
11249
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
11250
        self._TestDelay()
11251

    
11252

    
11253
class LUTestJqueue(NoHooksLU):
11254
  """Utility LU to test some aspects of the job queue.
11255

11256
  """
11257
  REQ_BGL = False
11258

    
11259
  # Must be lower than default timeout for WaitForJobChange to see whether it
11260
  # notices changed jobs
11261
  _CLIENT_CONNECT_TIMEOUT = 20.0
11262
  _CLIENT_CONFIRM_TIMEOUT = 60.0
11263

    
11264
  @classmethod
11265
  def _NotifyUsingSocket(cls, cb, errcls):
11266
    """Opens a Unix socket and waits for another program to connect.
11267

11268
    @type cb: callable
11269
    @param cb: Callback to send socket name to client
11270
    @type errcls: class
11271
    @param errcls: Exception class to use for errors
11272

11273
    """
11274
    # Using a temporary directory as there's no easy way to create temporary
11275
    # sockets without writing a custom loop around tempfile.mktemp and
11276
    # socket.bind
11277
    tmpdir = tempfile.mkdtemp()
11278
    try:
11279
      tmpsock = utils.PathJoin(tmpdir, "sock")
11280

    
11281
      logging.debug("Creating temporary socket at %s", tmpsock)
11282
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
11283
      try:
11284
        sock.bind(tmpsock)
11285
        sock.listen(1)
11286

    
11287
        # Send details to client
11288
        cb(tmpsock)
11289

    
11290
        # Wait for client to connect before continuing
11291
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
11292
        try:
11293
          (conn, _) = sock.accept()
11294
        except socket.error, err:
11295
          raise errcls("Client didn't connect in time (%s)" % err)
11296
      finally:
11297
        sock.close()
11298
    finally:
11299
      # Remove as soon as client is connected
11300
      shutil.rmtree(tmpdir)
11301

    
11302
    # Wait for client to close
11303
    try:
11304
      try:
11305
        # pylint: disable-msg=E1101
11306
        # Instance of '_socketobject' has no ... member
11307
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
11308
        conn.recv(1)
11309
      except socket.error, err:
11310
        raise errcls("Client failed to confirm notification (%s)" % err)
11311
    finally:
11312
      conn.close()
11313

    
11314
  def _SendNotification(self, test, arg, sockname):
11315
    """Sends a notification to the client.
11316

11317
    @type test: string
11318
    @param test: Test name
11319
    @param arg: Test argument (depends on test)
11320
    @type sockname: string
11321
    @param sockname: Socket path
11322

11323
    """
11324
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
11325

    
11326
  def _Notify(self, prereq, test, arg):
11327
    """Notifies the client of a test.
11328

11329
    @type prereq: bool
11330
    @param prereq: Whether this is a prereq-phase test
11331
    @type test: string
11332
    @param test: Test name
11333
    @param arg: Test argument (depends on test)
11334

11335
    """
11336
    if prereq:
11337
      errcls = errors.OpPrereqError
11338
    else:
11339
      errcls = errors.OpExecError
11340

    
11341
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
11342
                                                  test, arg),
11343
                                   errcls)
11344

    
11345
  def CheckArguments(self):
11346
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
11347
    self.expandnames_calls = 0
11348

    
11349
  def ExpandNames(self):
11350
    checkargs_calls = getattr(self, "checkargs_calls", 0)
11351
    if checkargs_calls < 1:
11352
      raise errors.ProgrammerError("CheckArguments was not called")
11353

    
11354
    self.expandnames_calls += 1
11355

    
11356
    if self.op.notify_waitlock:
11357
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
11358

    
11359
    self.LogInfo("Expanding names")
11360

    
11361
    # Get lock on master node (just to get a lock, not for a particular reason)
11362
    self.needed_locks = {
11363
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
11364
      }
11365

    
11366
  def Exec(self, feedback_fn):
11367
    if self.expandnames_calls < 1:
11368
      raise errors.ProgrammerError("ExpandNames was not called")
11369

    
11370
    if self.op.notify_exec:
11371
      self._Notify(False, constants.JQT_EXEC, None)
11372

    
11373
    self.LogInfo("Executing")
11374

    
11375
    if self.op.log_messages:
11376
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
11377
      for idx, msg in enumerate(self.op.log_messages):
11378
        self.LogInfo("Sending log message %s", idx + 1)
11379
        feedback_fn(constants.JQT_MSGPREFIX + msg)
11380
        # Report how many test messages have been sent
11381
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
11382

    
11383
    if self.op.fail:
11384
      raise errors.OpExecError("Opcode failure was requested")
11385

    
11386
    return True
11387

    
11388

    
11389
class IAllocator(object):
11390
  """IAllocator framework.
11391

11392
  An IAllocator instance has three sets of attributes:
11393
    - cfg that is needed to query the cluster
11394
    - input data (all members of the _KEYS class attribute are required)
11395
    - four buffer attributes (in|out_data|text), that represent the
11396
      input (to the external script) in text and data structure format,
11397
      and the output from it, again in two formats
11398
    - the result variables from the script (success, info, nodes) for
11399
      easy usage
11400

11401
  """
11402
  # pylint: disable-msg=R0902
11403
  # lots of instance attributes
11404
  _ALLO_KEYS = [
11405
    "name", "mem_size", "disks", "disk_template",
11406
    "os", "tags", "nics", "vcpus", "hypervisor",
11407
    ]
11408
  _RELO_KEYS = [
11409
    "name", "relocate_from",
11410
    ]
11411
  _EVAC_KEYS = [
11412
    "evac_nodes",
11413
    ]
11414

    
11415
  def __init__(self, cfg, rpc, mode, **kwargs):
11416
    self.cfg = cfg
11417
    self.rpc = rpc
11418
    # init buffer variables
11419
    self.in_text = self.out_text = self.in_data = self.out_data = None
11420
    # init all input fields so that pylint is happy
11421
    self.mode = mode
11422
    self.mem_size = self.disks = self.disk_template = None
11423
    self.os = self.tags = self.nics = self.vcpus = None
11424
    self.hypervisor = None
11425
    self.relocate_from = None
11426
    self.name = None
11427
    self.evac_nodes = None
11428
    # computed fields
11429
    self.required_nodes = None
11430
    # init result fields
11431
    self.success = self.info = self.result = None
11432
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
11433
      keyset = self._ALLO_KEYS
11434
      fn = self._AddNewInstance
11435
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
11436
      keyset = self._RELO_KEYS
11437
      fn = self._AddRelocateInstance
11438
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
11439
      keyset = self._EVAC_KEYS
11440
      fn = self._AddEvacuateNodes
11441
    else:
11442
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
11443
                                   " IAllocator" % self.mode)
11444
    for key in kwargs:
11445
      if key not in keyset:
11446
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
11447
                                     " IAllocator" % key)
11448
      setattr(self, key, kwargs[key])
11449

    
11450
    for key in keyset:
11451
      if key not in kwargs:
11452
        raise errors.ProgrammerError("Missing input parameter '%s' to"
11453
                                     " IAllocator" % key)
11454
    self._BuildInputData(fn)
11455

    
11456
  def _ComputeClusterData(self):
11457
    """Compute the generic allocator input data.
11458

11459
    This is the data that is independent of the actual operation.
11460

11461
    """
11462
    cfg = self.cfg
11463
    cluster_info = cfg.GetClusterInfo()
11464
    # cluster data
11465
    data = {
11466
      "version": constants.IALLOCATOR_VERSION,
11467
      "cluster_name": cfg.GetClusterName(),
11468
      "cluster_tags": list(cluster_info.GetTags()),
11469
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
11470
      # we don't have job IDs
11471
      }
11472
    ninfo = cfg.GetAllNodesInfo()
11473
    iinfo = cfg.GetAllInstancesInfo().values()
11474
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
11475

    
11476
    # node data
11477
    node_list = [n.name for n in ninfo.values() if n.vm_capable]
11478

    
11479
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
11480
      hypervisor_name = self.hypervisor
11481
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
11482
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
11483
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
11484
      hypervisor_name = cluster_info.enabled_hypervisors[0]
11485

    
11486
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
11487
                                        hypervisor_name)
11488
    node_iinfo = \
11489
      self.rpc.call_all_instances_info(node_list,
11490
                                       cluster_info.enabled_hypervisors)
11491

    
11492
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
11493

    
11494
    config_ndata = self._ComputeBasicNodeData(ninfo)
11495
    data["nodes"] = self._ComputeDynamicNodeData(ninfo, node_data, node_iinfo,
11496
                                                 i_list, config_ndata)
11497
    assert len(data["nodes"]) == len(ninfo), \
11498
        "Incomplete node data computed"
11499

    
11500
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
11501

    
11502
    self.in_data = data
11503

    
11504
  @staticmethod
11505
  def _ComputeNodeGroupData(cfg):
11506
    """Compute node groups data.
11507

11508
    """
11509
    ng = {}
11510
    for guuid, gdata in cfg.GetAllNodeGroupsInfo().items():
11511
      ng[guuid] = {
11512
        "name": gdata.name,
11513
        "alloc_policy": gdata.alloc_policy,
11514
        }
11515
    return ng
11516

    
11517
  @staticmethod
11518
  def _ComputeBasicNodeData(node_cfg):
11519
    """Compute global node data.
11520

11521
    @rtype: dict
11522
    @returns: a dict of name: (node dict, node config)
11523

11524
    """
11525
    node_results = {}
11526
    for ninfo in node_cfg.values():
11527
      # fill in static (config-based) values
11528
      pnr = {
11529
        "tags": list(ninfo.GetTags()),
11530
        "primary_ip": ninfo.primary_ip,
11531
        "secondary_ip": ninfo.secondary_ip,
11532
        "offline": ninfo.offline,
11533
        "drained": ninfo.drained,
11534
        "master_candidate": ninfo.master_candidate,
11535
        "group": ninfo.group,
11536
        "master_capable": ninfo.master_capable,
11537
        "vm_capable": ninfo.vm_capable,
11538
        }
11539

    
11540
      node_results[ninfo.name] = pnr
11541

    
11542
    return node_results
11543

    
11544
  @staticmethod
11545
  def _ComputeDynamicNodeData(node_cfg, node_data, node_iinfo, i_list,
11546
                              node_results):
11547
    """Compute global node data.
11548

11549
    @param node_results: the basic node structures as filled from the config
11550

11551
    """
11552
    # make a copy of the current dict
11553
    node_results = dict(node_results)
11554
    for nname, nresult in node_data.items():
11555
      assert nname in node_results, "Missing basic data for node %s" % nname
11556
      ninfo = node_cfg[nname]
11557

    
11558
      if not (ninfo.offline or ninfo.drained):
11559
        nresult.Raise("Can't get data for node %s" % nname)
11560
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
11561
                                nname)
11562
        remote_info = nresult.payload
11563

    
11564
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
11565
                     'vg_size', 'vg_free', 'cpu_total']:
11566
          if attr not in remote_info:
11567
            raise errors.OpExecError("Node '%s' didn't return attribute"
11568
                                     " '%s'" % (nname, attr))
11569
          if not isinstance(remote_info[attr], int):
11570
            raise errors.OpExecError("Node '%s' returned invalid value"
11571
                                     " for '%s': %s" %
11572
                                     (nname, attr, remote_info[attr]))
11573
        # compute memory used by primary instances
11574
        i_p_mem = i_p_up_mem = 0
11575
        for iinfo, beinfo in i_list:
11576
          if iinfo.primary_node == nname:
11577
            i_p_mem += beinfo[constants.BE_MEMORY]
11578
            if iinfo.name not in node_iinfo[nname].payload:
11579
              i_used_mem = 0
11580
            else:
11581
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
11582
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
11583
            remote_info['memory_free'] -= max(0, i_mem_diff)
11584

    
11585
            if iinfo.admin_up:
11586
              i_p_up_mem += beinfo[constants.BE_MEMORY]
11587

    
11588
        # compute memory used by instances
11589
        pnr_dyn = {
11590
          "total_memory": remote_info['memory_total'],
11591
          "reserved_memory": remote_info['memory_dom0'],
11592
          "free_memory": remote_info['memory_free'],
11593
          "total_disk": remote_info['vg_size'],
11594
          "free_disk": remote_info['vg_free'],
11595
          "total_cpus": remote_info['cpu_total'],
11596
          "i_pri_memory": i_p_mem,
11597
          "i_pri_up_memory": i_p_up_mem,
11598
          }
11599
        pnr_dyn.update(node_results[nname])
11600
        node_results[nname] = pnr_dyn
11601

    
11602
    return node_results
11603

    
11604
  @staticmethod
11605
  def _ComputeInstanceData(cluster_info, i_list):
11606
    """Compute global instance data.
11607

11608
    """
11609
    instance_data = {}
11610
    for iinfo, beinfo in i_list:
11611
      nic_data = []
11612
      for nic in iinfo.nics:
11613
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
11614
        nic_dict = {"mac": nic.mac,
11615
                    "ip": nic.ip,
11616
                    "mode": filled_params[constants.NIC_MODE],
11617
                    "link": filled_params[constants.NIC_LINK],
11618
                   }
11619
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
11620
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
11621
        nic_data.append(nic_dict)
11622
      pir = {
11623
        "tags": list(iinfo.GetTags()),
11624
        "admin_up": iinfo.admin_up,
11625
        "vcpus": beinfo[constants.BE_VCPUS],
11626
        "memory": beinfo[constants.BE_MEMORY],
11627
        "os": iinfo.os,
11628
        "nics": nic_data,
11629
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
11630
        "disk_template": iinfo.disk_template,
11631
        "hypervisor": iinfo.hypervisor,
11632
        }
11633
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
11634
                                                 pir["disks"])
11635
      # hail's relocation mode does not work without secondaries,
11636
      # as it exclusively tries replace-secondary moves. So, let's trick hail
11637
      # by specifying our primary and secondary node to be the same.
11638
      if iinfo.disk_template in constants.DTS_EXT_MIRROR:
11639
        pir["nodes"] = [iinfo.primary_node, iinfo.primary_node]
11640
      else:
11641
        pir["nodes"] = [iinfo.primary_node] + list(iinfo.secondary_nodes)
11642
      instance_data[iinfo.name] = pir
11643

    
11644
    return instance_data
11645

    
11646
  def _AddNewInstance(self):
11647
    """Add new instance data to allocator structure.
11648

11649
    This in combination with _AllocatorGetClusterData will create the
11650
    correct structure needed as input for the allocator.
11651

11652
    The checks for the completeness of the opcode must have already been
11653
    done.
11654

11655
    """
11656
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
11657

    
11658
    if self.disk_template in constants.DTS_INT_MIRROR:
11659
      self.required_nodes = 2
11660
    else:
11661
      self.required_nodes = 1
11662
    request = {
11663
      "name": self.name,
11664
      "disk_template": self.disk_template,
11665
      "tags": self.tags,
11666
      "os": self.os,
11667
      "vcpus": self.vcpus,
11668
      "memory": self.mem_size,
11669
      "disks": self.disks,
11670
      "disk_space_total": disk_space,
11671
      "nics": self.nics,
11672
      "required_nodes": self.required_nodes,
11673
      }
11674
    return request
11675

    
11676
  def _AddRelocateInstance(self):
11677
    """Add relocate instance data to allocator structure.
11678

11679
    This in combination with _IAllocatorGetClusterData will create the
11680
    correct structure needed as input for the allocator.
11681

11682
    The checks for the completeness of the opcode must have already been
11683
    done.
11684

11685
    """
11686
    instance = self.cfg.GetInstanceInfo(self.name)
11687
    if instance is None:
11688
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
11689
                                   " IAllocator" % self.name)
11690

    
11691
    if instance.disk_template not in constants.DTS_MIRRORED:
11692
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
11693
                                 errors.ECODE_INVAL)
11694

    
11695
    if instance.disk_template in constants.DTS_INT_MIRROR and \
11696
        len(instance.secondary_nodes) != 1:
11697
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
11698
                                 errors.ECODE_STATE)
11699

    
11700
    self.required_nodes = 1
11701
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
11702
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
11703

    
11704
    request = {
11705
      "name": self.name,
11706
      "disk_space_total": disk_space,
11707
      "required_nodes": self.required_nodes,
11708
      "relocate_from": self.relocate_from,
11709
      }
11710
    return request
11711

    
11712
  def _AddEvacuateNodes(self):
11713
    """Add evacuate nodes data to allocator structure.
11714

11715
    """
11716
    request = {
11717
      "evac_nodes": self.evac_nodes
11718
      }
11719
    return request
11720

    
11721
  def _BuildInputData(self, fn):
11722
    """Build input data structures.
11723

11724
    """
11725
    self._ComputeClusterData()
11726

    
11727
    request = fn()
11728
    request["type"] = self.mode
11729
    self.in_data["request"] = request
11730

    
11731
    self.in_text = serializer.Dump(self.in_data)
11732

    
11733
  def Run(self, name, validate=True, call_fn=None):
11734
    """Run an instance allocator and return the results.
11735

11736
    """
11737
    if call_fn is None:
11738
      call_fn = self.rpc.call_iallocator_runner
11739

    
11740
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
11741
    result.Raise("Failure while running the iallocator script")
11742

    
11743
    self.out_text = result.payload
11744
    if validate:
11745
      self._ValidateResult()
11746

    
11747
  def _ValidateResult(self):
11748
    """Process the allocator results.
11749

11750
    This will process and if successful save the result in
11751
    self.out_data and the other parameters.
11752

11753
    """
11754
    try:
11755
      rdict = serializer.Load(self.out_text)
11756
    except Exception, err:
11757
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
11758

    
11759
    if not isinstance(rdict, dict):
11760
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
11761

    
11762
    # TODO: remove backwards compatiblity in later versions
11763
    if "nodes" in rdict and "result" not in rdict:
11764
      rdict["result"] = rdict["nodes"]
11765
      del rdict["nodes"]
11766

    
11767
    for key in "success", "info", "result":
11768
      if key not in rdict:
11769
        raise errors.OpExecError("Can't parse iallocator results:"
11770
                                 " missing key '%s'" % key)
11771
      setattr(self, key, rdict[key])
11772

    
11773
    if not isinstance(rdict["result"], list):
11774
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
11775
                               " is not a list")
11776
    self.out_data = rdict
11777

    
11778

    
11779
class LUTestAllocator(NoHooksLU):
11780
  """Run allocator tests.
11781

11782
  This LU runs the allocator tests
11783

11784
  """
11785
  def CheckPrereq(self):
11786
    """Check prerequisites.
11787

11788
    This checks the opcode parameters depending on the director and mode test.
11789

11790
    """
11791
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
11792
      for attr in ["mem_size", "disks", "disk_template",
11793
                   "os", "tags", "nics", "vcpus"]:
11794
        if not hasattr(self.op, attr):
11795
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
11796
                                     attr, errors.ECODE_INVAL)
11797
      iname = self.cfg.ExpandInstanceName(self.op.name)
11798
      if iname is not None:
11799
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
11800
                                   iname, errors.ECODE_EXISTS)
11801
      if not isinstance(self.op.nics, list):
11802
        raise errors.OpPrereqError("Invalid parameter 'nics'",
11803
                                   errors.ECODE_INVAL)
11804
      if not isinstance(self.op.disks, list):
11805
        raise errors.OpPrereqError("Invalid parameter 'disks'",
11806
                                   errors.ECODE_INVAL)
11807
      for row in self.op.disks:
11808
        if (not isinstance(row, dict) or
11809
            "size" not in row or
11810
            not isinstance(row["size"], int) or
11811
            "mode" not in row or
11812
            row["mode"] not in ['r', 'w']):
11813
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
11814
                                     " parameter", errors.ECODE_INVAL)
11815
      if self.op.hypervisor is None:
11816
        self.op.hypervisor = self.cfg.GetHypervisorType()
11817
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
11818
      fname = _ExpandInstanceName(self.cfg, self.op.name)
11819
      self.op.name = fname
11820
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
11821
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
11822
      if not hasattr(self.op, "evac_nodes"):
11823
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
11824
                                   " opcode input", errors.ECODE_INVAL)
11825
    else:
11826
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
11827
                                 self.op.mode, errors.ECODE_INVAL)
11828

    
11829
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
11830
      if self.op.allocator is None:
11831
        raise errors.OpPrereqError("Missing allocator name",
11832
                                   errors.ECODE_INVAL)
11833
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
11834
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
11835
                                 self.op.direction, errors.ECODE_INVAL)
11836

    
11837
  def Exec(self, feedback_fn):
11838
    """Run the allocator test.
11839

11840
    """
11841
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
11842
      ial = IAllocator(self.cfg, self.rpc,
11843
                       mode=self.op.mode,
11844
                       name=self.op.name,
11845
                       mem_size=self.op.mem_size,
11846
                       disks=self.op.disks,
11847
                       disk_template=self.op.disk_template,
11848
                       os=self.op.os,
11849
                       tags=self.op.tags,
11850
                       nics=self.op.nics,
11851
                       vcpus=self.op.vcpus,
11852
                       hypervisor=self.op.hypervisor,
11853
                       )
11854
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
11855
      ial = IAllocator(self.cfg, self.rpc,
11856
                       mode=self.op.mode,
11857
                       name=self.op.name,
11858
                       relocate_from=list(self.relocate_from),
11859
                       )
11860
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
11861
      ial = IAllocator(self.cfg, self.rpc,
11862
                       mode=self.op.mode,
11863
                       evac_nodes=self.op.evac_nodes)
11864
    else:
11865
      raise errors.ProgrammerError("Uncatched mode %s in"
11866
                                   " LUTestAllocator.Exec", self.op.mode)
11867

    
11868
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
11869
      result = ial.in_text
11870
    else:
11871
      ial.Run(self.op.allocator, validate=False)
11872
      result = ial.out_text
11873
    return result
11874

    
11875

    
11876
#: Query type implementations
11877
_QUERY_IMPL = {
11878
  constants.QR_INSTANCE: _InstanceQuery,
11879
  constants.QR_NODE: _NodeQuery,
11880
  constants.QR_GROUP: _GroupQuery,
11881
  }
11882

    
11883

    
11884
def _GetQueryImplementation(name):
11885
  """Returns the implemtnation for a query type.
11886

11887
  @param name: Query type, must be one of L{constants.QR_OP_QUERY}
11888

11889
  """
11890
  try:
11891
    return _QUERY_IMPL[name]
11892
  except KeyError:
11893
    raise errors.OpPrereqError("Unknown query resource '%s'" % name,
11894
                               errors.ECODE_INVAL)