Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ b94590c6

History | View | Annotate | Download (409.5 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 time.
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 _VerifyNodeNetwork(self, ninfo, nresult):
1484
    """Check the node time.
1485

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

1490
    """
1491
    node = ninfo.name
1492
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1493

    
1494
    test = constants.NV_NODELIST not in nresult
1495
    _ErrorIf(test, self.ENODESSH, node,
1496
             "node hasn't returned node ssh connectivity data")
1497
    if not test:
1498
      if nresult[constants.NV_NODELIST]:
1499
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1500
          _ErrorIf(True, self.ENODESSH, node,
1501
                   "ssh communication with node '%s': %s", a_node, a_msg)
1502

    
1503
    test = constants.NV_NODENETTEST not in nresult
1504
    _ErrorIf(test, self.ENODENET, node,
1505
             "node hasn't returned node tcp connectivity data")
1506
    if not test:
1507
      if nresult[constants.NV_NODENETTEST]:
1508
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1509
        for anode in nlist:
1510
          _ErrorIf(True, self.ENODENET, node,
1511
                   "tcp communication with node '%s': %s",
1512
                   anode, nresult[constants.NV_NODENETTEST][anode])
1513

    
1514
    test = constants.NV_MASTERIP not in nresult
1515
    _ErrorIf(test, self.ENODENET, node,
1516
             "node hasn't returned node master IP reachability data")
1517
    if not test:
1518
      if not nresult[constants.NV_MASTERIP]:
1519
        if node == self.master_node:
1520
          msg = "the master node cannot reach the master IP (not configured?)"
1521
        else:
1522
          msg = "cannot reach the master IP"
1523
        _ErrorIf(True, self.ENODENET, node, msg)
1524

    
1525
  def _VerifyInstance(self, instance, instanceconfig, node_image,
1526
                      diskstatus):
1527
    """Verify an instance.
1528

1529
    This function checks to see if the required block devices are
1530
    available on the instance's node.
1531

1532
    """
1533
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1534
    node_current = instanceconfig.primary_node
1535

    
1536
    node_vol_should = {}
1537
    instanceconfig.MapLVsByNode(node_vol_should)
1538

    
1539
    for node in node_vol_should:
1540
      n_img = node_image[node]
1541
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1542
        # ignore missing volumes on offline or broken nodes
1543
        continue
1544
      for volume in node_vol_should[node]:
1545
        test = volume not in n_img.volumes
1546
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1547
                 "volume %s missing on node %s", volume, node)
1548

    
1549
    if instanceconfig.admin_up:
1550
      pri_img = node_image[node_current]
1551
      test = instance not in pri_img.instances and not pri_img.offline
1552
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1553
               "instance not running on its primary node %s",
1554
               node_current)
1555

    
1556
    for node, n_img in node_image.items():
1557
      if node != node_current:
1558
        test = instance in n_img.instances
1559
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1560
                 "instance should not run on node %s", node)
1561

    
1562
    diskdata = [(nname, success, status, idx)
1563
                for (nname, disks) in diskstatus.items()
1564
                for idx, (success, status) in enumerate(disks)]
1565

    
1566
    for nname, success, bdev_status, idx in diskdata:
1567
      # the 'ghost node' construction in Exec() ensures that we have a
1568
      # node here
1569
      snode = node_image[nname]
1570
      bad_snode = snode.ghost or snode.offline
1571
      _ErrorIf(instanceconfig.admin_up and not success and not bad_snode,
1572
               self.EINSTANCEFAULTYDISK, instance,
1573
               "couldn't retrieve status for disk/%s on %s: %s",
1574
               idx, nname, bdev_status)
1575
      _ErrorIf((instanceconfig.admin_up and success and
1576
                bdev_status.ldisk_status == constants.LDS_FAULTY),
1577
               self.EINSTANCEFAULTYDISK, instance,
1578
               "disk/%s on %s is faulty", idx, nname)
1579

    
1580
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1581
    """Verify if there are any unknown volumes in the cluster.
1582

1583
    The .os, .swap and backup volumes are ignored. All other volumes are
1584
    reported as unknown.
1585

1586
    @type reserved: L{ganeti.utils.FieldSet}
1587
    @param reserved: a FieldSet of reserved volume names
1588

1589
    """
1590
    for node, n_img in node_image.items():
1591
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1592
        # skip non-healthy nodes
1593
        continue
1594
      for volume in n_img.volumes:
1595
        test = ((node not in node_vol_should or
1596
                volume not in node_vol_should[node]) and
1597
                not reserved.Matches(volume))
1598
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1599
                      "volume %s is unknown", volume)
1600

    
1601
  def _VerifyOrphanInstances(self, instancelist, node_image):
1602
    """Verify the list of running instances.
1603

1604
    This checks what instances are running but unknown to the cluster.
1605

1606
    """
1607
    for node, n_img in node_image.items():
1608
      for o_inst in n_img.instances:
1609
        test = o_inst not in instancelist
1610
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1611
                      "instance %s on node %s should not exist", o_inst, node)
1612

    
1613
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1614
    """Verify N+1 Memory Resilience.
1615

1616
    Check that if one single node dies we can still start all the
1617
    instances it was primary for.
1618

1619
    """
1620
    for node, n_img in node_image.items():
1621
      # This code checks that every node which is now listed as
1622
      # secondary has enough memory to host all instances it is
1623
      # supposed to should a single other node in the cluster fail.
1624
      # FIXME: not ready for failover to an arbitrary node
1625
      # FIXME: does not support file-backed instances
1626
      # WARNING: we currently take into account down instances as well
1627
      # as up ones, considering that even if they're down someone
1628
      # might want to start them even in the event of a node failure.
1629
      if n_img.offline:
1630
        # we're skipping offline nodes from the N+1 warning, since
1631
        # most likely we don't have good memory infromation from them;
1632
        # we already list instances living on such nodes, and that's
1633
        # enough warning
1634
        continue
1635
      for prinode, instances in n_img.sbp.items():
1636
        needed_mem = 0
1637
        for instance in instances:
1638
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1639
          if bep[constants.BE_AUTO_BALANCE]:
1640
            needed_mem += bep[constants.BE_MEMORY]
1641
        test = n_img.mfree < needed_mem
1642
        self._ErrorIf(test, self.ENODEN1, node,
1643
                      "not enough memory to accomodate instance failovers"
1644
                      " should node %s fail", prinode)
1645

    
1646
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1647
                       master_files):
1648
    """Verifies and computes the node required file checksums.
1649

1650
    @type ninfo: L{objects.Node}
1651
    @param ninfo: the node to check
1652
    @param nresult: the remote results for the node
1653
    @param file_list: required list of files
1654
    @param local_cksum: dictionary of local files and their checksums
1655
    @param master_files: list of files that only masters should have
1656

1657
    """
1658
    node = ninfo.name
1659
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1660

    
1661
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1662
    test = not isinstance(remote_cksum, dict)
1663
    _ErrorIf(test, self.ENODEFILECHECK, node,
1664
             "node hasn't returned file checksum data")
1665
    if test:
1666
      return
1667

    
1668
    for file_name in file_list:
1669
      node_is_mc = ninfo.master_candidate
1670
      must_have = (file_name not in master_files) or node_is_mc
1671
      # missing
1672
      test1 = file_name not in remote_cksum
1673
      # invalid checksum
1674
      test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1675
      # existing and good
1676
      test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1677
      _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1678
               "file '%s' missing", file_name)
1679
      _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1680
               "file '%s' has wrong checksum", file_name)
1681
      # not candidate and this is not a must-have file
1682
      _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1683
               "file '%s' should not exist on non master"
1684
               " candidates (and the file is outdated)", file_name)
1685
      # all good, except non-master/non-must have combination
1686
      _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1687
               "file '%s' should not exist"
1688
               " on non master candidates", file_name)
1689

    
1690
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1691
                      drbd_map):
1692
    """Verifies and the node DRBD status.
1693

1694
    @type ninfo: L{objects.Node}
1695
    @param ninfo: the node to check
1696
    @param nresult: the remote results for the node
1697
    @param instanceinfo: the dict of instances
1698
    @param drbd_helper: the configured DRBD usermode helper
1699
    @param drbd_map: the DRBD map as returned by
1700
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1701

1702
    """
1703
    node = ninfo.name
1704
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1705

    
1706
    if drbd_helper:
1707
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1708
      test = (helper_result == None)
1709
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1710
               "no drbd usermode helper returned")
1711
      if helper_result:
1712
        status, payload = helper_result
1713
        test = not status
1714
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1715
                 "drbd usermode helper check unsuccessful: %s", payload)
1716
        test = status and (payload != drbd_helper)
1717
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1718
                 "wrong drbd usermode helper: %s", payload)
1719

    
1720
    # compute the DRBD minors
1721
    node_drbd = {}
1722
    for minor, instance in drbd_map[node].items():
1723
      test = instance not in instanceinfo
1724
      _ErrorIf(test, self.ECLUSTERCFG, None,
1725
               "ghost instance '%s' in temporary DRBD map", instance)
1726
        # ghost instance should not be running, but otherwise we
1727
        # don't give double warnings (both ghost instance and
1728
        # unallocated minor in use)
1729
      if test:
1730
        node_drbd[minor] = (instance, False)
1731
      else:
1732
        instance = instanceinfo[instance]
1733
        node_drbd[minor] = (instance.name, instance.admin_up)
1734

    
1735
    # and now check them
1736
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1737
    test = not isinstance(used_minors, (tuple, list))
1738
    _ErrorIf(test, self.ENODEDRBD, node,
1739
             "cannot parse drbd status file: %s", str(used_minors))
1740
    if test:
1741
      # we cannot check drbd status
1742
      return
1743

    
1744
    for minor, (iname, must_exist) in node_drbd.items():
1745
      test = minor not in used_minors and must_exist
1746
      _ErrorIf(test, self.ENODEDRBD, node,
1747
               "drbd minor %d of instance %s is not active", minor, iname)
1748
    for minor in used_minors:
1749
      test = minor not in node_drbd
1750
      _ErrorIf(test, self.ENODEDRBD, node,
1751
               "unallocated drbd minor %d is in use", minor)
1752

    
1753
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1754
    """Builds the node OS structures.
1755

1756
    @type ninfo: L{objects.Node}
1757
    @param ninfo: the node to check
1758
    @param nresult: the remote results for the node
1759
    @param nimg: the node image object
1760

1761
    """
1762
    node = ninfo.name
1763
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1764

    
1765
    remote_os = nresult.get(constants.NV_OSLIST, None)
1766
    test = (not isinstance(remote_os, list) or
1767
            not compat.all(isinstance(v, list) and len(v) == 7
1768
                           for v in remote_os))
1769

    
1770
    _ErrorIf(test, self.ENODEOS, node,
1771
             "node hasn't returned valid OS data")
1772

    
1773
    nimg.os_fail = test
1774

    
1775
    if test:
1776
      return
1777

    
1778
    os_dict = {}
1779

    
1780
    for (name, os_path, status, diagnose,
1781
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1782

    
1783
      if name not in os_dict:
1784
        os_dict[name] = []
1785

    
1786
      # parameters is a list of lists instead of list of tuples due to
1787
      # JSON lacking a real tuple type, fix it:
1788
      parameters = [tuple(v) for v in parameters]
1789
      os_dict[name].append((os_path, status, diagnose,
1790
                            set(variants), set(parameters), set(api_ver)))
1791

    
1792
    nimg.oslist = os_dict
1793

    
1794
  def _VerifyNodeOS(self, ninfo, nimg, base):
1795
    """Verifies the node OS list.
1796

1797
    @type ninfo: L{objects.Node}
1798
    @param ninfo: the node to check
1799
    @param nimg: the node image object
1800
    @param base: the 'template' node we match against (e.g. from the master)
1801

1802
    """
1803
    node = ninfo.name
1804
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1805

    
1806
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1807

    
1808
    for os_name, os_data in nimg.oslist.items():
1809
      assert os_data, "Empty OS status for OS %s?!" % os_name
1810
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
1811
      _ErrorIf(not f_status, self.ENODEOS, node,
1812
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
1813
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
1814
               "OS '%s' has multiple entries (first one shadows the rest): %s",
1815
               os_name, utils.CommaJoin([v[0] for v in os_data]))
1816
      # this will catched in backend too
1817
      _ErrorIf(compat.any(v >= constants.OS_API_V15 for v in f_api)
1818
               and not f_var, self.ENODEOS, node,
1819
               "OS %s with API at least %d does not declare any variant",
1820
               os_name, constants.OS_API_V15)
1821
      # comparisons with the 'base' image
1822
      test = os_name not in base.oslist
1823
      _ErrorIf(test, self.ENODEOS, node,
1824
               "Extra OS %s not present on reference node (%s)",
1825
               os_name, base.name)
1826
      if test:
1827
        continue
1828
      assert base.oslist[os_name], "Base node has empty OS status?"
1829
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
1830
      if not b_status:
1831
        # base OS is invalid, skipping
1832
        continue
1833
      for kind, a, b in [("API version", f_api, b_api),
1834
                         ("variants list", f_var, b_var),
1835
                         ("parameters", f_param, b_param)]:
1836
        _ErrorIf(a != b, self.ENODEOS, node,
1837
                 "OS %s %s differs from reference node %s: %s vs. %s",
1838
                 kind, os_name, base.name,
1839
                 utils.CommaJoin(a), utils.CommaJoin(b))
1840

    
1841
    # check any missing OSes
1842
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
1843
    _ErrorIf(missing, self.ENODEOS, node,
1844
             "OSes present on reference node %s but missing on this node: %s",
1845
             base.name, utils.CommaJoin(missing))
1846

    
1847
  def _VerifyOob(self, ninfo, nresult):
1848
    """Verifies out of band functionality of a node.
1849

1850
    @type ninfo: L{objects.Node}
1851
    @param ninfo: the node to check
1852
    @param nresult: the remote results for the node
1853

1854
    """
1855
    node = ninfo.name
1856
    # We just have to verify the paths on master and/or master candidates
1857
    # as the oob helper is invoked on the master
1858
    if ((ninfo.master_candidate or ninfo.master_capable) and
1859
        constants.NV_OOB_PATHS in nresult):
1860
      for path_result in nresult[constants.NV_OOB_PATHS]:
1861
        self._ErrorIf(path_result, self.ENODEOOBPATH, node, path_result)
1862

    
1863
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1864
    """Verifies and updates the node volume data.
1865

1866
    This function will update a L{NodeImage}'s internal structures
1867
    with data from the remote call.
1868

1869
    @type ninfo: L{objects.Node}
1870
    @param ninfo: the node to check
1871
    @param nresult: the remote results for the node
1872
    @param nimg: the node image object
1873
    @param vg_name: the configured VG name
1874

1875
    """
1876
    node = ninfo.name
1877
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1878

    
1879
    nimg.lvm_fail = True
1880
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1881
    if vg_name is None:
1882
      pass
1883
    elif isinstance(lvdata, basestring):
1884
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1885
               utils.SafeEncode(lvdata))
1886
    elif not isinstance(lvdata, dict):
1887
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1888
    else:
1889
      nimg.volumes = lvdata
1890
      nimg.lvm_fail = False
1891

    
1892
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1893
    """Verifies and updates the node instance list.
1894

1895
    If the listing was successful, then updates this node's instance
1896
    list. Otherwise, it marks the RPC call as failed for the instance
1897
    list key.
1898

1899
    @type ninfo: L{objects.Node}
1900
    @param ninfo: the node to check
1901
    @param nresult: the remote results for the node
1902
    @param nimg: the node image object
1903

1904
    """
1905
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1906
    test = not isinstance(idata, list)
1907
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1908
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1909
    if test:
1910
      nimg.hyp_fail = True
1911
    else:
1912
      nimg.instances = idata
1913

    
1914
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1915
    """Verifies and computes a node information map
1916

1917
    @type ninfo: L{objects.Node}
1918
    @param ninfo: the node to check
1919
    @param nresult: the remote results for the node
1920
    @param nimg: the node image object
1921
    @param vg_name: the configured VG name
1922

1923
    """
1924
    node = ninfo.name
1925
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1926

    
1927
    # try to read free memory (from the hypervisor)
1928
    hv_info = nresult.get(constants.NV_HVINFO, None)
1929
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
1930
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1931
    if not test:
1932
      try:
1933
        nimg.mfree = int(hv_info["memory_free"])
1934
      except (ValueError, TypeError):
1935
        _ErrorIf(True, self.ENODERPC, node,
1936
                 "node returned invalid nodeinfo, check hypervisor")
1937

    
1938
    # FIXME: devise a free space model for file based instances as well
1939
    if vg_name is not None:
1940
      test = (constants.NV_VGLIST not in nresult or
1941
              vg_name not in nresult[constants.NV_VGLIST])
1942
      _ErrorIf(test, self.ENODELVM, node,
1943
               "node didn't return data for the volume group '%s'"
1944
               " - it is either missing or broken", vg_name)
1945
      if not test:
1946
        try:
1947
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
1948
        except (ValueError, TypeError):
1949
          _ErrorIf(True, self.ENODERPC, node,
1950
                   "node returned invalid LVM info, check LVM status")
1951

    
1952
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
1953
    """Gets per-disk status information for all instances.
1954

1955
    @type nodelist: list of strings
1956
    @param nodelist: Node names
1957
    @type node_image: dict of (name, L{objects.Node})
1958
    @param node_image: Node objects
1959
    @type instanceinfo: dict of (name, L{objects.Instance})
1960
    @param instanceinfo: Instance objects
1961
    @rtype: {instance: {node: [(succes, payload)]}}
1962
    @return: a dictionary of per-instance dictionaries with nodes as
1963
        keys and disk information as values; the disk information is a
1964
        list of tuples (success, payload)
1965

1966
    """
1967
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1968

    
1969
    node_disks = {}
1970
    node_disks_devonly = {}
1971
    diskless_instances = set()
1972
    diskless = constants.DT_DISKLESS
1973

    
1974
    for nname in nodelist:
1975
      node_instances = list(itertools.chain(node_image[nname].pinst,
1976
                                            node_image[nname].sinst))
1977
      diskless_instances.update(inst for inst in node_instances
1978
                                if instanceinfo[inst].disk_template == diskless)
1979
      disks = [(inst, disk)
1980
               for inst in node_instances
1981
               for disk in instanceinfo[inst].disks]
1982

    
1983
      if not disks:
1984
        # No need to collect data
1985
        continue
1986

    
1987
      node_disks[nname] = disks
1988

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

    
1993
      for dev in devonly:
1994
        self.cfg.SetDiskID(dev, nname)
1995

    
1996
      node_disks_devonly[nname] = devonly
1997

    
1998
    assert len(node_disks) == len(node_disks_devonly)
1999

    
2000
    # Collect data from all nodes with disks
2001
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
2002
                                                          node_disks_devonly)
2003

    
2004
    assert len(result) == len(node_disks)
2005

    
2006
    instdisk = {}
2007

    
2008
    for (nname, nres) in result.items():
2009
      disks = node_disks[nname]
2010

    
2011
      if nres.offline:
2012
        # No data from this node
2013
        data = len(disks) * [(False, "node offline")]
2014
      else:
2015
        msg = nres.fail_msg
2016
        _ErrorIf(msg, self.ENODERPC, nname,
2017
                 "while getting disk information: %s", msg)
2018
        if msg:
2019
          # No data from this node
2020
          data = len(disks) * [(False, msg)]
2021
        else:
2022
          data = []
2023
          for idx, i in enumerate(nres.payload):
2024
            if isinstance(i, (tuple, list)) and len(i) == 2:
2025
              data.append(i)
2026
            else:
2027
              logging.warning("Invalid result from node %s, entry %d: %s",
2028
                              nname, idx, i)
2029
              data.append((False, "Invalid result from the remote node"))
2030

    
2031
      for ((inst, _), status) in zip(disks, data):
2032
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
2033

    
2034
    # Add empty entries for diskless instances.
2035
    for inst in diskless_instances:
2036
      assert inst not in instdisk
2037
      instdisk[inst] = {}
2038

    
2039
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
2040
                      len(nnames) <= len(instanceinfo[inst].all_nodes) and
2041
                      compat.all(isinstance(s, (tuple, list)) and
2042
                                 len(s) == 2 for s in statuses)
2043
                      for inst, nnames in instdisk.items()
2044
                      for nname, statuses in nnames.items())
2045
    assert set(instdisk) == set(instanceinfo), "instdisk consistency failure"
2046

    
2047
    return instdisk
2048

    
2049
  def _VerifyHVP(self, hvp_data):
2050
    """Verifies locally the syntax of the hypervisor parameters.
2051

2052
    """
2053
    for item, hv_name, hv_params in hvp_data:
2054
      msg = ("hypervisor %s parameters syntax check (source %s): %%s" %
2055
             (item, hv_name))
2056
      try:
2057
        hv_class = hypervisor.GetHypervisor(hv_name)
2058
        utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2059
        hv_class.CheckParameterSyntax(hv_params)
2060
      except errors.GenericError, err:
2061
        self._ErrorIf(True, self.ECLUSTERCFG, None, msg % str(err))
2062

    
2063

    
2064
  def BuildHooksEnv(self):
2065
    """Build hooks env.
2066

2067
    Cluster-Verify hooks just ran in the post phase and their failure makes
2068
    the output be logged in the verify output and the verification to fail.
2069

2070
    """
2071
    all_nodes = self.cfg.GetNodeList()
2072
    env = {
2073
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2074
      }
2075
    for node in self.cfg.GetAllNodesInfo().values():
2076
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
2077

    
2078
    return env, [], all_nodes
2079

    
2080
  def Exec(self, feedback_fn):
2081
    """Verify integrity of cluster, performing various test on nodes.
2082

2083
    """
2084
    # This method has too many local variables. pylint: disable-msg=R0914
2085
    self.bad = False
2086
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2087
    verbose = self.op.verbose
2088
    self._feedback_fn = feedback_fn
2089
    feedback_fn("* Verifying global settings")
2090
    for msg in self.cfg.VerifyConfig():
2091
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
2092

    
2093
    # Check the cluster certificates
2094
    for cert_filename in constants.ALL_CERT_FILES:
2095
      (errcode, msg) = _VerifyCertificate(cert_filename)
2096
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
2097

    
2098
    vg_name = self.cfg.GetVGName()
2099
    drbd_helper = self.cfg.GetDRBDHelper()
2100
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
2101
    cluster = self.cfg.GetClusterInfo()
2102
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
2103
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
2104
    nodeinfo_byname = dict(zip(nodelist, nodeinfo))
2105
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
2106
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
2107
                        for iname in instancelist)
2108
    groupinfo = self.cfg.GetAllNodeGroupsInfo()
2109
    i_non_redundant = [] # Non redundant instances
2110
    i_non_a_balanced = [] # Non auto-balanced instances
2111
    n_offline = 0 # Count of offline nodes
2112
    n_drained = 0 # Count of nodes being drained
2113
    node_vol_should = {}
2114

    
2115
    # FIXME: verify OS list
2116
    # do local checksums
2117
    master_files = [constants.CLUSTER_CONF_FILE]
2118
    master_node = self.master_node = self.cfg.GetMasterNode()
2119
    master_ip = self.cfg.GetMasterIP()
2120

    
2121
    file_names = ssconf.SimpleStore().GetFileList()
2122
    file_names.extend(constants.ALL_CERT_FILES)
2123
    file_names.extend(master_files)
2124
    if cluster.modify_etc_hosts:
2125
      file_names.append(constants.ETC_HOSTS)
2126

    
2127
    local_checksums = utils.FingerprintFiles(file_names)
2128

    
2129
    # Compute the set of hypervisor parameters
2130
    hvp_data = []
2131
    for hv_name in hypervisors:
2132
      hvp_data.append(("cluster", hv_name, cluster.GetHVDefaults(hv_name)))
2133
    for os_name, os_hvp in cluster.os_hvp.items():
2134
      for hv_name, hv_params in os_hvp.items():
2135
        if not hv_params:
2136
          continue
2137
        full_params = cluster.GetHVDefaults(hv_name, os_name=os_name)
2138
        hvp_data.append(("os %s" % os_name, hv_name, full_params))
2139
    # TODO: collapse identical parameter values in a single one
2140
    for instance in instanceinfo.values():
2141
      if not instance.hvparams:
2142
        continue
2143
      hvp_data.append(("instance %s" % instance.name, instance.hypervisor,
2144
                       cluster.FillHV(instance)))
2145
    # and verify them locally
2146
    self._VerifyHVP(hvp_data)
2147

    
2148
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
2149
    node_verify_param = {
2150
      constants.NV_FILELIST: file_names,
2151
      constants.NV_NODELIST: [node.name for node in nodeinfo
2152
                              if not node.offline],
2153
      constants.NV_HYPERVISOR: hypervisors,
2154
      constants.NV_HVPARAMS: hvp_data,
2155
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
2156
                                  node.secondary_ip) for node in nodeinfo
2157
                                 if not node.offline],
2158
      constants.NV_INSTANCELIST: hypervisors,
2159
      constants.NV_VERSION: None,
2160
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2161
      constants.NV_NODESETUP: None,
2162
      constants.NV_TIME: None,
2163
      constants.NV_MASTERIP: (master_node, master_ip),
2164
      constants.NV_OSLIST: None,
2165
      constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2166
      }
2167

    
2168
    if vg_name is not None:
2169
      node_verify_param[constants.NV_VGLIST] = None
2170
      node_verify_param[constants.NV_LVLIST] = vg_name
2171
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2172
      node_verify_param[constants.NV_DRBDLIST] = None
2173

    
2174
    if drbd_helper:
2175
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2176

    
2177
    # Build our expected cluster state
2178
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2179
                                                 name=node.name,
2180
                                                 vm_capable=node.vm_capable))
2181
                      for node in nodeinfo)
2182

    
2183
    # Gather OOB paths
2184
    oob_paths = []
2185
    for node in nodeinfo:
2186
      path = _SupportsOob(self.cfg, node)
2187
      if path and path not in oob_paths:
2188
        oob_paths.append(path)
2189

    
2190
    if oob_paths:
2191
      node_verify_param[constants.NV_OOB_PATHS] = oob_paths
2192

    
2193
    for instance in instancelist:
2194
      inst_config = instanceinfo[instance]
2195

    
2196
      for nname in inst_config.all_nodes:
2197
        if nname not in node_image:
2198
          # ghost node
2199
          gnode = self.NodeImage(name=nname)
2200
          gnode.ghost = True
2201
          node_image[nname] = gnode
2202

    
2203
      inst_config.MapLVsByNode(node_vol_should)
2204

    
2205
      pnode = inst_config.primary_node
2206
      node_image[pnode].pinst.append(instance)
2207

    
2208
      for snode in inst_config.secondary_nodes:
2209
        nimg = node_image[snode]
2210
        nimg.sinst.append(instance)
2211
        if pnode not in nimg.sbp:
2212
          nimg.sbp[pnode] = []
2213
        nimg.sbp[pnode].append(instance)
2214

    
2215
    # At this point, we have the in-memory data structures complete,
2216
    # except for the runtime information, which we'll gather next
2217

    
2218
    # Due to the way our RPC system works, exact response times cannot be
2219
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2220
    # time before and after executing the request, we can at least have a time
2221
    # window.
2222
    nvinfo_starttime = time.time()
2223
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
2224
                                           self.cfg.GetClusterName())
2225
    nvinfo_endtime = time.time()
2226

    
2227
    all_drbd_map = self.cfg.ComputeDRBDMap()
2228

    
2229
    feedback_fn("* Gathering disk information (%s nodes)" % len(nodelist))
2230
    instdisk = self._CollectDiskInfo(nodelist, node_image, instanceinfo)
2231

    
2232
    feedback_fn("* Verifying node status")
2233

    
2234
    refos_img = None
2235

    
2236
    for node_i in nodeinfo:
2237
      node = node_i.name
2238
      nimg = node_image[node]
2239

    
2240
      if node_i.offline:
2241
        if verbose:
2242
          feedback_fn("* Skipping offline node %s" % (node,))
2243
        n_offline += 1
2244
        continue
2245

    
2246
      if node == master_node:
2247
        ntype = "master"
2248
      elif node_i.master_candidate:
2249
        ntype = "master candidate"
2250
      elif node_i.drained:
2251
        ntype = "drained"
2252
        n_drained += 1
2253
      else:
2254
        ntype = "regular"
2255
      if verbose:
2256
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2257

    
2258
      msg = all_nvinfo[node].fail_msg
2259
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2260
      if msg:
2261
        nimg.rpc_fail = True
2262
        continue
2263

    
2264
      nresult = all_nvinfo[node].payload
2265

    
2266
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2267
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2268
      self._VerifyNodeNetwork(node_i, nresult)
2269
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2270
                            master_files)
2271

    
2272
      self._VerifyOob(node_i, nresult)
2273

    
2274
      if nimg.vm_capable:
2275
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2276
        self._VerifyNodeDrbd(node_i, nresult, instanceinfo, drbd_helper,
2277
                             all_drbd_map)
2278

    
2279
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2280
        self._UpdateNodeInstances(node_i, nresult, nimg)
2281
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2282
        self._UpdateNodeOS(node_i, nresult, nimg)
2283
        if not nimg.os_fail:
2284
          if refos_img is None:
2285
            refos_img = nimg
2286
          self._VerifyNodeOS(node_i, nimg, refos_img)
2287

    
2288
    feedback_fn("* Verifying instance status")
2289
    for instance in instancelist:
2290
      if verbose:
2291
        feedback_fn("* Verifying instance %s" % instance)
2292
      inst_config = instanceinfo[instance]
2293
      self._VerifyInstance(instance, inst_config, node_image,
2294
                           instdisk[instance])
2295
      inst_nodes_offline = []
2296

    
2297
      pnode = inst_config.primary_node
2298
      pnode_img = node_image[pnode]
2299
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2300
               self.ENODERPC, pnode, "instance %s, connection to"
2301
               " primary node failed", instance)
2302

    
2303
      _ErrorIf(pnode_img.offline, self.EINSTANCEBADNODE, instance,
2304
               "instance lives on offline node %s", inst_config.primary_node)
2305

    
2306
      # If the instance is non-redundant we cannot survive losing its primary
2307
      # node, so we are not N+1 compliant. On the other hand we have no disk
2308
      # templates with more than one secondary so that situation is not well
2309
      # supported either.
2310
      # FIXME: does not support file-backed instances
2311
      if not inst_config.secondary_nodes:
2312
        i_non_redundant.append(instance)
2313

    
2314
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2315
               instance, "instance has multiple secondary nodes: %s",
2316
               utils.CommaJoin(inst_config.secondary_nodes),
2317
               code=self.ETYPE_WARNING)
2318

    
2319
      if inst_config.disk_template in constants.DTS_INT_MIRROR:
2320
        pnode = inst_config.primary_node
2321
        instance_nodes = utils.NiceSort(inst_config.all_nodes)
2322
        instance_groups = {}
2323

    
2324
        for node in instance_nodes:
2325
          instance_groups.setdefault(nodeinfo_byname[node].group,
2326
                                     []).append(node)
2327

    
2328
        pretty_list = [
2329
          "%s (group %s)" % (utils.CommaJoin(nodes), groupinfo[group].name)
2330
          # Sort so that we always list the primary node first.
2331
          for group, nodes in sorted(instance_groups.items(),
2332
                                     key=lambda (_, nodes): pnode in nodes,
2333
                                     reverse=True)]
2334

    
2335
        self._ErrorIf(len(instance_groups) > 1, self.EINSTANCESPLITGROUPS,
2336
                      instance, "instance has primary and secondary nodes in"
2337
                      " different groups: %s", utils.CommaJoin(pretty_list),
2338
                      code=self.ETYPE_WARNING)
2339

    
2340
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2341
        i_non_a_balanced.append(instance)
2342

    
2343
      for snode in inst_config.secondary_nodes:
2344
        s_img = node_image[snode]
2345
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2346
                 "instance %s, connection to secondary node failed", instance)
2347

    
2348
        if s_img.offline:
2349
          inst_nodes_offline.append(snode)
2350

    
2351
      # warn that the instance lives on offline nodes
2352
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2353
               "instance has offline secondary node(s) %s",
2354
               utils.CommaJoin(inst_nodes_offline))
2355
      # ... or ghost/non-vm_capable nodes
2356
      for node in inst_config.all_nodes:
2357
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2358
                 "instance lives on ghost node %s", node)
2359
        _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2360
                 instance, "instance lives on non-vm_capable node %s", node)
2361

    
2362
    feedback_fn("* Verifying orphan volumes")
2363
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2364
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2365

    
2366
    feedback_fn("* Verifying orphan instances")
2367
    self._VerifyOrphanInstances(instancelist, node_image)
2368

    
2369
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2370
      feedback_fn("* Verifying N+1 Memory redundancy")
2371
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2372

    
2373
    feedback_fn("* Other Notes")
2374
    if i_non_redundant:
2375
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2376
                  % len(i_non_redundant))
2377

    
2378
    if i_non_a_balanced:
2379
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2380
                  % len(i_non_a_balanced))
2381

    
2382
    if n_offline:
2383
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2384

    
2385
    if n_drained:
2386
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2387

    
2388
    return not self.bad
2389

    
2390
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2391
    """Analyze the post-hooks' result
2392

2393
    This method analyses the hook result, handles it, and sends some
2394
    nicely-formatted feedback back to the user.
2395

2396
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2397
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2398
    @param hooks_results: the results of the multi-node hooks rpc call
2399
    @param feedback_fn: function used send feedback back to the caller
2400
    @param lu_result: previous Exec result
2401
    @return: the new Exec result, based on the previous result
2402
        and hook results
2403

2404
    """
2405
    # We only really run POST phase hooks, and are only interested in
2406
    # their results
2407
    if phase == constants.HOOKS_PHASE_POST:
2408
      # Used to change hooks' output to proper indentation
2409
      feedback_fn("* Hooks Results")
2410
      assert hooks_results, "invalid result from hooks"
2411

    
2412
      for node_name in hooks_results:
2413
        res = hooks_results[node_name]
2414
        msg = res.fail_msg
2415
        test = msg and not res.offline
2416
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2417
                      "Communication failure in hooks execution: %s", msg)
2418
        if res.offline or msg:
2419
          # No need to investigate payload if node is offline or gave an error.
2420
          # override manually lu_result here as _ErrorIf only
2421
          # overrides self.bad
2422
          lu_result = 1
2423
          continue
2424
        for script, hkr, output in res.payload:
2425
          test = hkr == constants.HKR_FAIL
2426
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2427
                        "Script %s failed, output:", script)
2428
          if test:
2429
            output = self._HOOKS_INDENT_RE.sub('      ', output)
2430
            feedback_fn("%s" % output)
2431
            lu_result = 0
2432

    
2433
      return lu_result
2434

    
2435

    
2436
class LUClusterVerifyDisks(NoHooksLU):
2437
  """Verifies the cluster disks status.
2438

2439
  """
2440
  REQ_BGL = False
2441

    
2442
  def ExpandNames(self):
2443
    self.needed_locks = {
2444
      locking.LEVEL_NODE: locking.ALL_SET,
2445
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2446
    }
2447
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2448

    
2449
  def Exec(self, feedback_fn):
2450
    """Verify integrity of cluster disks.
2451

2452
    @rtype: tuple of three items
2453
    @return: a tuple of (dict of node-to-node_error, list of instances
2454
        which need activate-disks, dict of instance: (node, volume) for
2455
        missing volumes
2456

2457
    """
2458
    result = res_nodes, res_instances, res_missing = {}, [], {}
2459

    
2460
    nodes = utils.NiceSort(self.cfg.GetVmCapableNodeList())
2461
    instances = self.cfg.GetAllInstancesInfo().values()
2462

    
2463
    nv_dict = {}
2464
    for inst in instances:
2465
      inst_lvs = {}
2466
      if not inst.admin_up:
2467
        continue
2468
      inst.MapLVsByNode(inst_lvs)
2469
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2470
      for node, vol_list in inst_lvs.iteritems():
2471
        for vol in vol_list:
2472
          nv_dict[(node, vol)] = inst
2473

    
2474
    if not nv_dict:
2475
      return result
2476

    
2477
    node_lvs = self.rpc.call_lv_list(nodes, [])
2478
    for node, node_res in node_lvs.items():
2479
      if node_res.offline:
2480
        continue
2481
      msg = node_res.fail_msg
2482
      if msg:
2483
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2484
        res_nodes[node] = msg
2485
        continue
2486

    
2487
      lvs = node_res.payload
2488
      for lv_name, (_, _, lv_online) in lvs.items():
2489
        inst = nv_dict.pop((node, lv_name), None)
2490
        if (not lv_online and inst is not None
2491
            and inst.name not in res_instances):
2492
          res_instances.append(inst.name)
2493

    
2494
    # any leftover items in nv_dict are missing LVs, let's arrange the
2495
    # data better
2496
    for key, inst in nv_dict.iteritems():
2497
      if inst.name not in res_missing:
2498
        res_missing[inst.name] = []
2499
      res_missing[inst.name].append(key)
2500

    
2501
    return result
2502

    
2503

    
2504
class LUClusterRepairDiskSizes(NoHooksLU):
2505
  """Verifies the cluster disks sizes.
2506

2507
  """
2508
  REQ_BGL = False
2509

    
2510
  def ExpandNames(self):
2511
    if self.op.instances:
2512
      self.wanted_names = []
2513
      for name in self.op.instances:
2514
        full_name = _ExpandInstanceName(self.cfg, name)
2515
        self.wanted_names.append(full_name)
2516
      self.needed_locks = {
2517
        locking.LEVEL_NODE: [],
2518
        locking.LEVEL_INSTANCE: self.wanted_names,
2519
        }
2520
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2521
    else:
2522
      self.wanted_names = None
2523
      self.needed_locks = {
2524
        locking.LEVEL_NODE: locking.ALL_SET,
2525
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2526
        }
2527
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2528

    
2529
  def DeclareLocks(self, level):
2530
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2531
      self._LockInstancesNodes(primary_only=True)
2532

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

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

2538
    """
2539
    if self.wanted_names is None:
2540
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2541

    
2542
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2543
                             in self.wanted_names]
2544

    
2545
  def _EnsureChildSizes(self, disk):
2546
    """Ensure children of the disk have the needed disk size.
2547

2548
    This is valid mainly for DRBD8 and fixes an issue where the
2549
    children have smaller disk size.
2550

2551
    @param disk: an L{ganeti.objects.Disk} object
2552

2553
    """
2554
    if disk.dev_type == constants.LD_DRBD8:
2555
      assert disk.children, "Empty children for DRBD8?"
2556
      fchild = disk.children[0]
2557
      mismatch = fchild.size < disk.size
2558
      if mismatch:
2559
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2560
                     fchild.size, disk.size)
2561
        fchild.size = disk.size
2562

    
2563
      # and we recurse on this child only, not on the metadev
2564
      return self._EnsureChildSizes(fchild) or mismatch
2565
    else:
2566
      return False
2567

    
2568
  def Exec(self, feedback_fn):
2569
    """Verify the size of cluster disks.
2570

2571
    """
2572
    # TODO: check child disks too
2573
    # TODO: check differences in size between primary/secondary nodes
2574
    per_node_disks = {}
2575
    for instance in self.wanted_instances:
2576
      pnode = instance.primary_node
2577
      if pnode not in per_node_disks:
2578
        per_node_disks[pnode] = []
2579
      for idx, disk in enumerate(instance.disks):
2580
        per_node_disks[pnode].append((instance, idx, disk))
2581

    
2582
    changed = []
2583
    for node, dskl in per_node_disks.items():
2584
      newl = [v[2].Copy() for v in dskl]
2585
      for dsk in newl:
2586
        self.cfg.SetDiskID(dsk, node)
2587
      result = self.rpc.call_blockdev_getsize(node, newl)
2588
      if result.fail_msg:
2589
        self.LogWarning("Failure in blockdev_getsize call to node"
2590
                        " %s, ignoring", node)
2591
        continue
2592
      if len(result.payload) != len(dskl):
2593
        logging.warning("Invalid result from node %s: len(dksl)=%d,"
2594
                        " result.payload=%s", node, len(dskl), result.payload)
2595
        self.LogWarning("Invalid result from node %s, ignoring node results",
2596
                        node)
2597
        continue
2598
      for ((instance, idx, disk), size) in zip(dskl, result.payload):
2599
        if size is None:
2600
          self.LogWarning("Disk %d of instance %s did not return size"
2601
                          " information, ignoring", idx, instance.name)
2602
          continue
2603
        if not isinstance(size, (int, long)):
2604
          self.LogWarning("Disk %d of instance %s did not return valid"
2605
                          " size information, ignoring", idx, instance.name)
2606
          continue
2607
        size = size >> 20
2608
        if size != disk.size:
2609
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2610
                       " correcting: recorded %d, actual %d", idx,
2611
                       instance.name, disk.size, size)
2612
          disk.size = size
2613
          self.cfg.Update(instance, feedback_fn)
2614
          changed.append((instance.name, idx, size))
2615
        if self._EnsureChildSizes(disk):
2616
          self.cfg.Update(instance, feedback_fn)
2617
          changed.append((instance.name, idx, disk.size))
2618
    return changed
2619

    
2620

    
2621
class LUClusterRename(LogicalUnit):
2622
  """Rename the cluster.
2623

2624
  """
2625
  HPATH = "cluster-rename"
2626
  HTYPE = constants.HTYPE_CLUSTER
2627

    
2628
  def BuildHooksEnv(self):
2629
    """Build hooks env.
2630

2631
    """
2632
    env = {
2633
      "OP_TARGET": self.cfg.GetClusterName(),
2634
      "NEW_NAME": self.op.name,
2635
      }
2636
    mn = self.cfg.GetMasterNode()
2637
    all_nodes = self.cfg.GetNodeList()
2638
    return env, [mn], all_nodes
2639

    
2640
  def CheckPrereq(self):
2641
    """Verify that the passed name is a valid one.
2642

2643
    """
2644
    hostname = netutils.GetHostname(name=self.op.name,
2645
                                    family=self.cfg.GetPrimaryIPFamily())
2646

    
2647
    new_name = hostname.name
2648
    self.ip = new_ip = hostname.ip
2649
    old_name = self.cfg.GetClusterName()
2650
    old_ip = self.cfg.GetMasterIP()
2651
    if new_name == old_name and new_ip == old_ip:
2652
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2653
                                 " cluster has changed",
2654
                                 errors.ECODE_INVAL)
2655
    if new_ip != old_ip:
2656
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2657
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2658
                                   " reachable on the network" %
2659
                                   new_ip, errors.ECODE_NOTUNIQUE)
2660

    
2661
    self.op.name = new_name
2662

    
2663
  def Exec(self, feedback_fn):
2664
    """Rename the cluster.
2665

2666
    """
2667
    clustername = self.op.name
2668
    ip = self.ip
2669

    
2670
    # shutdown the master IP
2671
    master = self.cfg.GetMasterNode()
2672
    result = self.rpc.call_node_stop_master(master, False)
2673
    result.Raise("Could not disable the master role")
2674

    
2675
    try:
2676
      cluster = self.cfg.GetClusterInfo()
2677
      cluster.cluster_name = clustername
2678
      cluster.master_ip = ip
2679
      self.cfg.Update(cluster, feedback_fn)
2680

    
2681
      # update the known hosts file
2682
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2683
      node_list = self.cfg.GetOnlineNodeList()
2684
      try:
2685
        node_list.remove(master)
2686
      except ValueError:
2687
        pass
2688
      _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
2689
    finally:
2690
      result = self.rpc.call_node_start_master(master, False, False)
2691
      msg = result.fail_msg
2692
      if msg:
2693
        self.LogWarning("Could not re-enable the master role on"
2694
                        " the master, please restart manually: %s", msg)
2695

    
2696
    return clustername
2697

    
2698

    
2699
class LUClusterSetParams(LogicalUnit):
2700
  """Change the parameters of the cluster.
2701

2702
  """
2703
  HPATH = "cluster-modify"
2704
  HTYPE = constants.HTYPE_CLUSTER
2705
  REQ_BGL = False
2706

    
2707
  def CheckArguments(self):
2708
    """Check parameters
2709

2710
    """
2711
    if self.op.uid_pool:
2712
      uidpool.CheckUidPool(self.op.uid_pool)
2713

    
2714
    if self.op.add_uids:
2715
      uidpool.CheckUidPool(self.op.add_uids)
2716

    
2717
    if self.op.remove_uids:
2718
      uidpool.CheckUidPool(self.op.remove_uids)
2719

    
2720
  def ExpandNames(self):
2721
    # FIXME: in the future maybe other cluster params won't require checking on
2722
    # all nodes to be modified.
2723
    self.needed_locks = {
2724
      locking.LEVEL_NODE: locking.ALL_SET,
2725
    }
2726
    self.share_locks[locking.LEVEL_NODE] = 1
2727

    
2728
  def BuildHooksEnv(self):
2729
    """Build hooks env.
2730

2731
    """
2732
    env = {
2733
      "OP_TARGET": self.cfg.GetClusterName(),
2734
      "NEW_VG_NAME": self.op.vg_name,
2735
      }
2736
    mn = self.cfg.GetMasterNode()
2737
    return env, [mn], [mn]
2738

    
2739
  def CheckPrereq(self):
2740
    """Check prerequisites.
2741

2742
    This checks whether the given params don't conflict and
2743
    if the given volume group is valid.
2744

2745
    """
2746
    if self.op.vg_name is not None and not self.op.vg_name:
2747
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2748
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2749
                                   " instances exist", errors.ECODE_INVAL)
2750

    
2751
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
2752
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
2753
        raise errors.OpPrereqError("Cannot disable drbd helper while"
2754
                                   " drbd-based instances exist",
2755
                                   errors.ECODE_INVAL)
2756

    
2757
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2758

    
2759
    # if vg_name not None, checks given volume group on all nodes
2760
    if self.op.vg_name:
2761
      vglist = self.rpc.call_vg_list(node_list)
2762
      for node in node_list:
2763
        msg = vglist[node].fail_msg
2764
        if msg:
2765
          # ignoring down node
2766
          self.LogWarning("Error while gathering data on node %s"
2767
                          " (ignoring node): %s", node, msg)
2768
          continue
2769
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2770
                                              self.op.vg_name,
2771
                                              constants.MIN_VG_SIZE)
2772
        if vgstatus:
2773
          raise errors.OpPrereqError("Error on node '%s': %s" %
2774
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2775

    
2776
    if self.op.drbd_helper:
2777
      # checks given drbd helper on all nodes
2778
      helpers = self.rpc.call_drbd_helper(node_list)
2779
      for node in node_list:
2780
        ninfo = self.cfg.GetNodeInfo(node)
2781
        if ninfo.offline:
2782
          self.LogInfo("Not checking drbd helper on offline node %s", node)
2783
          continue
2784
        msg = helpers[node].fail_msg
2785
        if msg:
2786
          raise errors.OpPrereqError("Error checking drbd helper on node"
2787
                                     " '%s': %s" % (node, msg),
2788
                                     errors.ECODE_ENVIRON)
2789
        node_helper = helpers[node].payload
2790
        if node_helper != self.op.drbd_helper:
2791
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
2792
                                     (node, node_helper), errors.ECODE_ENVIRON)
2793

    
2794
    self.cluster = cluster = self.cfg.GetClusterInfo()
2795
    # validate params changes
2796
    if self.op.beparams:
2797
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2798
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2799

    
2800
    if self.op.ndparams:
2801
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
2802
      self.new_ndparams = cluster.SimpleFillND(self.op.ndparams)
2803

    
2804
      # TODO: we need a more general way to handle resetting
2805
      # cluster-level parameters to default values
2806
      if self.new_ndparams["oob_program"] == "":
2807
        self.new_ndparams["oob_program"] = \
2808
            constants.NDC_DEFAULTS[constants.ND_OOB_PROGRAM]
2809

    
2810
    if self.op.nicparams:
2811
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2812
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2813
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2814
      nic_errors = []
2815

    
2816
      # check all instances for consistency
2817
      for instance in self.cfg.GetAllInstancesInfo().values():
2818
        for nic_idx, nic in enumerate(instance.nics):
2819
          params_copy = copy.deepcopy(nic.nicparams)
2820
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2821

    
2822
          # check parameter syntax
2823
          try:
2824
            objects.NIC.CheckParameterSyntax(params_filled)
2825
          except errors.ConfigurationError, err:
2826
            nic_errors.append("Instance %s, nic/%d: %s" %
2827
                              (instance.name, nic_idx, err))
2828

    
2829
          # if we're moving instances to routed, check that they have an ip
2830
          target_mode = params_filled[constants.NIC_MODE]
2831
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2832
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2833
                              (instance.name, nic_idx))
2834
      if nic_errors:
2835
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2836
                                   "\n".join(nic_errors))
2837

    
2838
    # hypervisor list/parameters
2839
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2840
    if self.op.hvparams:
2841
      for hv_name, hv_dict in self.op.hvparams.items():
2842
        if hv_name not in self.new_hvparams:
2843
          self.new_hvparams[hv_name] = hv_dict
2844
        else:
2845
          self.new_hvparams[hv_name].update(hv_dict)
2846

    
2847
    # os hypervisor parameters
2848
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2849
    if self.op.os_hvp:
2850
      for os_name, hvs in self.op.os_hvp.items():
2851
        if os_name not in self.new_os_hvp:
2852
          self.new_os_hvp[os_name] = hvs
2853
        else:
2854
          for hv_name, hv_dict in hvs.items():
2855
            if hv_name not in self.new_os_hvp[os_name]:
2856
              self.new_os_hvp[os_name][hv_name] = hv_dict
2857
            else:
2858
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2859

    
2860
    # os parameters
2861
    self.new_osp = objects.FillDict(cluster.osparams, {})
2862
    if self.op.osparams:
2863
      for os_name, osp in self.op.osparams.items():
2864
        if os_name not in self.new_osp:
2865
          self.new_osp[os_name] = {}
2866

    
2867
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2868
                                                  use_none=True)
2869

    
2870
        if not self.new_osp[os_name]:
2871
          # we removed all parameters
2872
          del self.new_osp[os_name]
2873
        else:
2874
          # check the parameter validity (remote check)
2875
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
2876
                         os_name, self.new_osp[os_name])
2877

    
2878
    # changes to the hypervisor list
2879
    if self.op.enabled_hypervisors is not None:
2880
      self.hv_list = self.op.enabled_hypervisors
2881
      for hv in self.hv_list:
2882
        # if the hypervisor doesn't already exist in the cluster
2883
        # hvparams, we initialize it to empty, and then (in both
2884
        # cases) we make sure to fill the defaults, as we might not
2885
        # have a complete defaults list if the hypervisor wasn't
2886
        # enabled before
2887
        if hv not in new_hvp:
2888
          new_hvp[hv] = {}
2889
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2890
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2891
    else:
2892
      self.hv_list = cluster.enabled_hypervisors
2893

    
2894
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2895
      # either the enabled list has changed, or the parameters have, validate
2896
      for hv_name, hv_params in self.new_hvparams.items():
2897
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2898
            (self.op.enabled_hypervisors and
2899
             hv_name in self.op.enabled_hypervisors)):
2900
          # either this is a new hypervisor, or its parameters have changed
2901
          hv_class = hypervisor.GetHypervisor(hv_name)
2902
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2903
          hv_class.CheckParameterSyntax(hv_params)
2904
          _CheckHVParams(self, node_list, hv_name, hv_params)
2905

    
2906
    if self.op.os_hvp:
2907
      # no need to check any newly-enabled hypervisors, since the
2908
      # defaults have already been checked in the above code-block
2909
      for os_name, os_hvp in self.new_os_hvp.items():
2910
        for hv_name, hv_params in os_hvp.items():
2911
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2912
          # we need to fill in the new os_hvp on top of the actual hv_p
2913
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2914
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2915
          hv_class = hypervisor.GetHypervisor(hv_name)
2916
          hv_class.CheckParameterSyntax(new_osp)
2917
          _CheckHVParams(self, node_list, hv_name, new_osp)
2918

    
2919
    if self.op.default_iallocator:
2920
      alloc_script = utils.FindFile(self.op.default_iallocator,
2921
                                    constants.IALLOCATOR_SEARCH_PATH,
2922
                                    os.path.isfile)
2923
      if alloc_script is None:
2924
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
2925
                                   " specified" % self.op.default_iallocator,
2926
                                   errors.ECODE_INVAL)
2927

    
2928
  def Exec(self, feedback_fn):
2929
    """Change the parameters of the cluster.
2930

2931
    """
2932
    if self.op.vg_name is not None:
2933
      new_volume = self.op.vg_name
2934
      if not new_volume:
2935
        new_volume = None
2936
      if new_volume != self.cfg.GetVGName():
2937
        self.cfg.SetVGName(new_volume)
2938
      else:
2939
        feedback_fn("Cluster LVM configuration already in desired"
2940
                    " state, not changing")
2941
    if self.op.drbd_helper is not None:
2942
      new_helper = self.op.drbd_helper
2943
      if not new_helper:
2944
        new_helper = None
2945
      if new_helper != self.cfg.GetDRBDHelper():
2946
        self.cfg.SetDRBDHelper(new_helper)
2947
      else:
2948
        feedback_fn("Cluster DRBD helper already in desired state,"
2949
                    " not changing")
2950
    if self.op.hvparams:
2951
      self.cluster.hvparams = self.new_hvparams
2952
    if self.op.os_hvp:
2953
      self.cluster.os_hvp = self.new_os_hvp
2954
    if self.op.enabled_hypervisors is not None:
2955
      self.cluster.hvparams = self.new_hvparams
2956
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2957
    if self.op.beparams:
2958
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2959
    if self.op.nicparams:
2960
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2961
    if self.op.osparams:
2962
      self.cluster.osparams = self.new_osp
2963
    if self.op.ndparams:
2964
      self.cluster.ndparams = self.new_ndparams
2965

    
2966
    if self.op.candidate_pool_size is not None:
2967
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2968
      # we need to update the pool size here, otherwise the save will fail
2969
      _AdjustCandidatePool(self, [])
2970

    
2971
    if self.op.maintain_node_health is not None:
2972
      self.cluster.maintain_node_health = self.op.maintain_node_health
2973

    
2974
    if self.op.prealloc_wipe_disks is not None:
2975
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
2976

    
2977
    if self.op.add_uids is not None:
2978
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2979

    
2980
    if self.op.remove_uids is not None:
2981
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2982

    
2983
    if self.op.uid_pool is not None:
2984
      self.cluster.uid_pool = self.op.uid_pool
2985

    
2986
    if self.op.default_iallocator is not None:
2987
      self.cluster.default_iallocator = self.op.default_iallocator
2988

    
2989
    if self.op.reserved_lvs is not None:
2990
      self.cluster.reserved_lvs = self.op.reserved_lvs
2991

    
2992
    def helper_os(aname, mods, desc):
2993
      desc += " OS list"
2994
      lst = getattr(self.cluster, aname)
2995
      for key, val in mods:
2996
        if key == constants.DDM_ADD:
2997
          if val in lst:
2998
            feedback_fn("OS %s already in %s, ignoring" % (val, desc))
2999
          else:
3000
            lst.append(val)
3001
        elif key == constants.DDM_REMOVE:
3002
          if val in lst:
3003
            lst.remove(val)
3004
          else:
3005
            feedback_fn("OS %s not found in %s, ignoring" % (val, desc))
3006
        else:
3007
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
3008

    
3009
    if self.op.hidden_os:
3010
      helper_os("hidden_os", self.op.hidden_os, "hidden")
3011

    
3012
    if self.op.blacklisted_os:
3013
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
3014

    
3015
    if self.op.master_netdev:
3016
      master = self.cfg.GetMasterNode()
3017
      feedback_fn("Shutting down master ip on the current netdev (%s)" %
3018
                  self.cluster.master_netdev)
3019
      result = self.rpc.call_node_stop_master(master, False)
3020
      result.Raise("Could not disable the master ip")
3021
      feedback_fn("Changing master_netdev from %s to %s" %
3022
                  (self.cluster.master_netdev, self.op.master_netdev))
3023
      self.cluster.master_netdev = self.op.master_netdev
3024

    
3025
    self.cfg.Update(self.cluster, feedback_fn)
3026

    
3027
    if self.op.master_netdev:
3028
      feedback_fn("Starting the master ip on the new master netdev (%s)" %
3029
                  self.op.master_netdev)
3030
      result = self.rpc.call_node_start_master(master, False, False)
3031
      if result.fail_msg:
3032
        self.LogWarning("Could not re-enable the master ip on"
3033
                        " the master, please restart manually: %s",
3034
                        result.fail_msg)
3035

    
3036

    
3037
def _UploadHelper(lu, nodes, fname):
3038
  """Helper for uploading a file and showing warnings.
3039

3040
  """
3041
  if os.path.exists(fname):
3042
    result = lu.rpc.call_upload_file(nodes, fname)
3043
    for to_node, to_result in result.items():
3044
      msg = to_result.fail_msg
3045
      if msg:
3046
        msg = ("Copy of file %s to node %s failed: %s" %
3047
               (fname, to_node, msg))
3048
        lu.proc.LogWarning(msg)
3049

    
3050

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

3054
  ConfigWriter takes care of distributing the config and ssconf files, but
3055
  there are more files which should be distributed to all nodes. This function
3056
  makes sure those are copied.
3057

3058
  @param lu: calling logical unit
3059
  @param additional_nodes: list of nodes not in the config to distribute to
3060
  @type additional_vm: boolean
3061
  @param additional_vm: whether the additional nodes are vm-capable or not
3062

3063
  """
3064
  # 1. Gather target nodes
3065
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
3066
  dist_nodes = lu.cfg.GetOnlineNodeList()
3067
  nvm_nodes = lu.cfg.GetNonVmCapableNodeList()
3068
  vm_nodes = [name for name in dist_nodes if name not in nvm_nodes]
3069
  if additional_nodes is not None:
3070
    dist_nodes.extend(additional_nodes)
3071
    if additional_vm:
3072
      vm_nodes.extend(additional_nodes)
3073
  if myself.name in dist_nodes:
3074
    dist_nodes.remove(myself.name)
3075
  if myself.name in vm_nodes:
3076
    vm_nodes.remove(myself.name)
3077

    
3078
  # 2. Gather files to distribute
3079
  dist_files = set([constants.ETC_HOSTS,
3080
                    constants.SSH_KNOWN_HOSTS_FILE,
3081
                    constants.RAPI_CERT_FILE,
3082
                    constants.RAPI_USERS_FILE,
3083
                    constants.CONFD_HMAC_KEY,
3084
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
3085
                   ])
3086

    
3087
  vm_files = set()
3088
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
3089
  for hv_name in enabled_hypervisors:
3090
    hv_class = hypervisor.GetHypervisor(hv_name)
3091
    vm_files.update(hv_class.GetAncillaryFiles())
3092

    
3093
  # 3. Perform the files upload
3094
  for fname in dist_files:
3095
    _UploadHelper(lu, dist_nodes, fname)
3096
  for fname in vm_files:
3097
    _UploadHelper(lu, vm_nodes, fname)
3098

    
3099

    
3100
class LUClusterRedistConf(NoHooksLU):
3101
  """Force the redistribution of cluster configuration.
3102

3103
  This is a very simple LU.
3104

3105
  """
3106
  REQ_BGL = False
3107

    
3108
  def ExpandNames(self):
3109
    self.needed_locks = {
3110
      locking.LEVEL_NODE: locking.ALL_SET,
3111
    }
3112
    self.share_locks[locking.LEVEL_NODE] = 1
3113

    
3114
  def Exec(self, feedback_fn):
3115
    """Redistribute the configuration.
3116

3117
    """
3118
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
3119
    _RedistributeAncillaryFiles(self)
3120

    
3121

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

3125
  """
3126
  if not instance.disks or disks is not None and not disks:
3127
    return True
3128

    
3129
  disks = _ExpandCheckDisks(instance, disks)
3130

    
3131
  if not oneshot:
3132
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
3133

    
3134
  node = instance.primary_node
3135

    
3136
  for dev in disks:
3137
    lu.cfg.SetDiskID(dev, node)
3138

    
3139
  # TODO: Convert to utils.Retry
3140

    
3141
  retries = 0
3142
  degr_retries = 10 # in seconds, as we sleep 1 second each time
3143
  while True:
3144
    max_time = 0
3145
    done = True
3146
    cumul_degraded = False
3147
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
3148
    msg = rstats.fail_msg
3149
    if msg:
3150
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
3151
      retries += 1
3152
      if retries >= 10:
3153
        raise errors.RemoteError("Can't contact node %s for mirror data,"
3154
                                 " aborting." % node)
3155
      time.sleep(6)
3156
      continue
3157
    rstats = rstats.payload
3158
    retries = 0
3159
    for i, mstat in enumerate(rstats):
3160
      if mstat is None:
3161
        lu.LogWarning("Can't compute data for node %s/%s",
3162
                           node, disks[i].iv_name)
3163
        continue
3164

    
3165
      cumul_degraded = (cumul_degraded or
3166
                        (mstat.is_degraded and mstat.sync_percent is None))
3167
      if mstat.sync_percent is not None:
3168
        done = False
3169
        if mstat.estimated_time is not None:
3170
          rem_time = ("%s remaining (estimated)" %
3171
                      utils.FormatSeconds(mstat.estimated_time))
3172
          max_time = mstat.estimated_time
3173
        else:
3174
          rem_time = "no time estimate"
3175
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3176
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3177

    
3178
    # if we're done but degraded, let's do a few small retries, to
3179
    # make sure we see a stable and not transient situation; therefore
3180
    # we force restart of the loop
3181
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3182
      logging.info("Degraded disks found, %d retries left", degr_retries)
3183
      degr_retries -= 1
3184
      time.sleep(1)
3185
      continue
3186

    
3187
    if done or oneshot:
3188
      break
3189

    
3190
    time.sleep(min(60, max_time))
3191

    
3192
  if done:
3193
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3194
  return not cumul_degraded
3195

    
3196

    
3197
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3198
  """Check that mirrors are not degraded.
3199

3200
  The ldisk parameter, if True, will change the test from the
3201
  is_degraded attribute (which represents overall non-ok status for
3202
  the device(s)) to the ldisk (representing the local storage status).
3203

3204
  """
3205
  lu.cfg.SetDiskID(dev, node)
3206

    
3207
  result = True
3208

    
3209
  if on_primary or dev.AssembleOnSecondary():
3210
    rstats = lu.rpc.call_blockdev_find(node, dev)
3211
    msg = rstats.fail_msg
3212
    if msg:
3213
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3214
      result = False
3215
    elif not rstats.payload:
3216
      lu.LogWarning("Can't find disk on node %s", node)
3217
      result = False
3218
    else:
3219
      if ldisk:
3220
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3221
      else:
3222
        result = result and not rstats.payload.is_degraded
3223

    
3224
  if dev.children:
3225
    for child in dev.children:
3226
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3227

    
3228
  return result
3229

    
3230

    
3231
class LUOobCommand(NoHooksLU):
3232
  """Logical unit for OOB handling.
3233

3234
  """
3235
  REG_BGL = False
3236

    
3237
  def CheckPrereq(self):
3238
    """Check prerequisites.
3239

3240
    This checks:
3241
     - the node exists in the configuration
3242
     - OOB is supported
3243

3244
    Any errors are signaled by raising errors.OpPrereqError.
3245

3246
    """
3247
    self.nodes = []
3248
    for node_name in self.op.node_names:
3249
      node = self.cfg.GetNodeInfo(node_name)
3250

    
3251
      if node is None:
3252
        raise errors.OpPrereqError("Node %s not found" % node_name,
3253
                                   errors.ECODE_NOENT)
3254
      else:
3255
        self.nodes.append(node)
3256

    
3257
      if (self.op.command == constants.OOB_POWER_OFF and not node.offline):
3258
        raise errors.OpPrereqError(("Cannot power off node %s because it is"
3259
                                    " not marked offline") % node_name,
3260
                                   errors.ECODE_STATE)
3261

    
3262
  def ExpandNames(self):
3263
    """Gather locks we need.
3264

3265
    """
3266
    if self.op.node_names:
3267
      self.op.node_names = [_ExpandNodeName(self.cfg, name)
3268
                            for name in self.op.node_names]
3269
    else:
3270
      self.op.node_names = self.cfg.GetNodeList()
3271

    
3272
    self.needed_locks = {
3273
      locking.LEVEL_NODE: self.op.node_names,
3274
      }
3275

    
3276
  def Exec(self, feedback_fn):
3277
    """Execute OOB and return result if we expect any.
3278

3279
    """
3280
    master_node = self.cfg.GetMasterNode()
3281
    ret = []
3282

    
3283
    for node in self.nodes:
3284
      node_entry = [(constants.RS_NORMAL, node.name)]
3285
      ret.append(node_entry)
3286

    
3287
      oob_program = _SupportsOob(self.cfg, node)
3288

    
3289
      if not oob_program:
3290
        node_entry.append((constants.RS_UNAVAIL, None))
3291
        continue
3292

    
3293
      logging.info("Executing out-of-band command '%s' using '%s' on %s",
3294
                   self.op.command, oob_program, node.name)
3295
      result = self.rpc.call_run_oob(master_node, oob_program,
3296
                                     self.op.command, node.name,
3297
                                     self.op.timeout)
3298

    
3299
      if result.fail_msg:
3300
        self.LogWarning("On node '%s' out-of-band RPC failed with: %s",
3301
                        node.name, result.fail_msg)
3302
        node_entry.append((constants.RS_NODATA, None))
3303
      else:
3304
        try:
3305
          self._CheckPayload(result)
3306
        except errors.OpExecError, err:
3307
          self.LogWarning("The payload returned by '%s' is not valid: %s",
3308
                          node.name, err)
3309
          node_entry.append((constants.RS_NODATA, None))
3310
        else:
3311
          if self.op.command == constants.OOB_HEALTH:
3312
            # For health we should log important events
3313
            for item, status in result.payload:
3314
              if status in [constants.OOB_STATUS_WARNING,
3315
                            constants.OOB_STATUS_CRITICAL]:
3316
                self.LogWarning("On node '%s' item '%s' has status '%s'",
3317
                                node.name, item, status)
3318

    
3319
          if self.op.command == constants.OOB_POWER_ON:
3320
            node.powered = True
3321
          elif self.op.command == constants.OOB_POWER_OFF:
3322
            node.powered = False
3323
          elif self.op.command == constants.OOB_POWER_STATUS:
3324
            powered = result.payload[constants.OOB_POWER_STATUS_POWERED]
3325
            if powered != node.powered:
3326
              logging.warning(("Recorded power state (%s) of node '%s' does not"
3327
                               " match actual power state (%s)"), node.powered,
3328
                              node.name, powered)
3329

    
3330
          # For configuration changing commands we should update the node
3331
          if self.op.command in (constants.OOB_POWER_ON,
3332
                                 constants.OOB_POWER_OFF):
3333
            self.cfg.Update(node, feedback_fn)
3334

    
3335
          node_entry.append((constants.RS_NORMAL, result.payload))
3336

    
3337
    return ret
3338

    
3339
  def _CheckPayload(self, result):
3340
    """Checks if the payload is valid.
3341

3342
    @param result: RPC result
3343
    @raises errors.OpExecError: If payload is not valid
3344

3345
    """
3346
    errs = []
3347
    if self.op.command == constants.OOB_HEALTH:
3348
      if not isinstance(result.payload, list):
3349
        errs.append("command 'health' is expected to return a list but got %s" %
3350
                    type(result.payload))
3351
      else:
3352
        for item, status in result.payload:
3353
          if status not in constants.OOB_STATUSES:
3354
            errs.append("health item '%s' has invalid status '%s'" %
3355
                        (item, status))
3356

    
3357
    if self.op.command == constants.OOB_POWER_STATUS:
3358
      if not isinstance(result.payload, dict):
3359
        errs.append("power-status is expected to return a dict but got %s" %
3360
                    type(result.payload))
3361

    
3362
    if self.op.command in [
3363
        constants.OOB_POWER_ON,
3364
        constants.OOB_POWER_OFF,
3365
        constants.OOB_POWER_CYCLE,
3366
        ]:
3367
      if result.payload is not None:
3368
        errs.append("%s is expected to not return payload but got '%s'" %
3369
                    (self.op.command, result.payload))
3370

    
3371
    if errs:
3372
      raise errors.OpExecError("Check of out-of-band payload failed due to %s" %
3373
                               utils.CommaJoin(errs))
3374

    
3375

    
3376

    
3377
class LUOsDiagnose(NoHooksLU):
3378
  """Logical unit for OS diagnose/query.
3379

3380
  """
3381
  REQ_BGL = False
3382
  _HID = "hidden"
3383
  _BLK = "blacklisted"
3384
  _VLD = "valid"
3385
  _FIELDS_STATIC = utils.FieldSet()
3386
  _FIELDS_DYNAMIC = utils.FieldSet("name", _VLD, "node_status", "variants",
3387
                                   "parameters", "api_versions", _HID, _BLK)
3388

    
3389
  def CheckArguments(self):
3390
    if self.op.names:
3391
      raise errors.OpPrereqError("Selective OS query not supported",
3392
                                 errors.ECODE_INVAL)
3393

    
3394
    _CheckOutputFields(static=self._FIELDS_STATIC,
3395
                       dynamic=self._FIELDS_DYNAMIC,
3396
                       selected=self.op.output_fields)
3397

    
3398
  def ExpandNames(self):
3399
    # Lock all nodes, in shared mode
3400
    # Temporary removal of locks, should be reverted later
3401
    # TODO: reintroduce locks when they are lighter-weight
3402
    self.needed_locks = {}
3403
    #self.share_locks[locking.LEVEL_NODE] = 1
3404
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3405

    
3406
  @staticmethod
3407
  def _DiagnoseByOS(rlist):
3408
    """Remaps a per-node return list into an a per-os per-node dictionary
3409

3410
    @param rlist: a map with node names as keys and OS objects as values
3411

3412
    @rtype: dict
3413
    @return: a dictionary with osnames as keys and as value another
3414
        map, with nodes as keys and tuples of (path, status, diagnose,
3415
        variants, parameters, api_versions) as values, eg::
3416

3417
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3418
                                     (/srv/..., False, "invalid api")],
3419
                           "node2": [(/srv/..., True, "", [], [])]}
3420
          }
3421

3422
    """
3423
    all_os = {}
3424
    # we build here the list of nodes that didn't fail the RPC (at RPC
3425
    # level), so that nodes with a non-responding node daemon don't
3426
    # make all OSes invalid
3427
    good_nodes = [node_name for node_name in rlist
3428
                  if not rlist[node_name].fail_msg]
3429
    for node_name, nr in rlist.items():
3430
      if nr.fail_msg or not nr.payload:
3431
        continue
3432
      for (name, path, status, diagnose, variants,
3433
           params, api_versions) in nr.payload:
3434
        if name not in all_os:
3435
          # build a list of nodes for this os containing empty lists
3436
          # for each node in node_list
3437
          all_os[name] = {}
3438
          for nname in good_nodes:
3439
            all_os[name][nname] = []
3440
        # convert params from [name, help] to (name, help)
3441
        params = [tuple(v) for v in params]
3442
        all_os[name][node_name].append((path, status, diagnose,
3443
                                        variants, params, api_versions))
3444
    return all_os
3445

    
3446
  def Exec(self, feedback_fn):
3447
    """Compute the list of OSes.
3448

3449
    """
3450
    valid_nodes = [node.name
3451
                   for node in self.cfg.GetAllNodesInfo().values()
3452
                   if not node.offline and node.vm_capable]
3453
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3454
    pol = self._DiagnoseByOS(node_data)
3455
    output = []
3456
    cluster = self.cfg.GetClusterInfo()
3457

    
3458
    for os_name in utils.NiceSort(pol.keys()):
3459
      os_data = pol[os_name]
3460
      row = []
3461
      valid = True
3462
      (variants, params, api_versions) = null_state = (set(), set(), set())
3463
      for idx, osl in enumerate(os_data.values()):
3464
        valid = bool(valid and osl and osl[0][1])
3465
        if not valid:
3466
          (variants, params, api_versions) = null_state
3467
          break
3468
        node_variants, node_params, node_api = osl[0][3:6]
3469
        if idx == 0: # first entry
3470
          variants = set(node_variants)
3471
          params = set(node_params)
3472
          api_versions = set(node_api)
3473
        else: # keep consistency
3474
          variants.intersection_update(node_variants)
3475
          params.intersection_update(node_params)
3476
          api_versions.intersection_update(node_api)
3477

    
3478
      is_hid = os_name in cluster.hidden_os
3479
      is_blk = os_name in cluster.blacklisted_os
3480
      if ((self._HID not in self.op.output_fields and is_hid) or
3481
          (self._BLK not in self.op.output_fields and is_blk) or
3482
          (self._VLD not in self.op.output_fields and not valid)):
3483
        continue
3484

    
3485
      for field in self.op.output_fields:
3486
        if field == "name":
3487
          val = os_name
3488
        elif field == self._VLD:
3489
          val = valid
3490
        elif field == "node_status":
3491
          # this is just a copy of the dict
3492
          val = {}
3493
          for node_name, nos_list in os_data.items():
3494
            val[node_name] = nos_list
3495
        elif field == "variants":
3496
          val = utils.NiceSort(list(variants))
3497
        elif field == "parameters":
3498
          val = list(params)
3499
        elif field == "api_versions":
3500
          val = list(api_versions)
3501
        elif field == self._HID:
3502
          val = is_hid
3503
        elif field == self._BLK:
3504
          val = is_blk
3505
        else:
3506
          raise errors.ParameterError(field)
3507
        row.append(val)
3508
      output.append(row)
3509

    
3510
    return output
3511

    
3512

    
3513
class LUNodeRemove(LogicalUnit):
3514
  """Logical unit for removing a node.
3515

3516
  """
3517
  HPATH = "node-remove"
3518
  HTYPE = constants.HTYPE_NODE
3519

    
3520
  def BuildHooksEnv(self):
3521
    """Build hooks env.
3522

3523
    This doesn't run on the target node in the pre phase as a failed
3524
    node would then be impossible to remove.
3525

3526
    """
3527
    env = {
3528
      "OP_TARGET": self.op.node_name,
3529
      "NODE_NAME": self.op.node_name,
3530
      }
3531
    all_nodes = self.cfg.GetNodeList()
3532
    try:
3533
      all_nodes.remove(self.op.node_name)
3534
    except ValueError:
3535
      logging.warning("Node %s which is about to be removed not found"
3536
                      " in the all nodes list", self.op.node_name)
3537
    return env, all_nodes, all_nodes
3538

    
3539
  def CheckPrereq(self):
3540
    """Check prerequisites.
3541

3542
    This checks:
3543
     - the node exists in the configuration
3544
     - it does not have primary or secondary instances
3545
     - it's not the master
3546

3547
    Any errors are signaled by raising errors.OpPrereqError.
3548

3549
    """
3550
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3551
    node = self.cfg.GetNodeInfo(self.op.node_name)
3552
    assert node is not None
3553

    
3554
    instance_list = self.cfg.GetInstanceList()
3555

    
3556
    masternode = self.cfg.GetMasterNode()
3557
    if node.name == masternode:
3558
      raise errors.OpPrereqError("Node is the master node,"
3559
                                 " you need to failover first.",
3560
                                 errors.ECODE_INVAL)
3561

    
3562
    for instance_name in instance_list:
3563
      instance = self.cfg.GetInstanceInfo(instance_name)
3564
      if node.name in instance.all_nodes:
3565
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3566
                                   " please remove first." % instance_name,
3567
                                   errors.ECODE_INVAL)
3568
    self.op.node_name = node.name
3569
    self.node = node
3570

    
3571
  def Exec(self, feedback_fn):
3572
    """Removes the node from the cluster.
3573

3574
    """
3575
    node = self.node
3576
    logging.info("Stopping the node daemon and removing configs from node %s",
3577
                 node.name)
3578

    
3579
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3580

    
3581
    # Promote nodes to master candidate as needed
3582
    _AdjustCandidatePool(self, exceptions=[node.name])
3583
    self.context.RemoveNode(node.name)
3584

    
3585
    # Run post hooks on the node before it's removed
3586
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3587
    try:
3588
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3589
    except:
3590
      # pylint: disable-msg=W0702
3591
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3592

    
3593
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3594
    msg = result.fail_msg
3595
    if msg:
3596
      self.LogWarning("Errors encountered on the remote node while leaving"
3597
                      " the cluster: %s", msg)
3598

    
3599
    # Remove node from our /etc/hosts
3600
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3601
      master_node = self.cfg.GetMasterNode()
3602
      result = self.rpc.call_etc_hosts_modify(master_node,
3603
                                              constants.ETC_HOSTS_REMOVE,
3604
                                              node.name, None)
3605
      result.Raise("Can't update hosts file with new host data")
3606
      _RedistributeAncillaryFiles(self)
3607

    
3608

    
3609
class _NodeQuery(_QueryBase):
3610
  FIELDS = query.NODE_FIELDS
3611

    
3612
  def ExpandNames(self, lu):
3613
    lu.needed_locks = {}
3614
    lu.share_locks[locking.LEVEL_NODE] = 1
3615

    
3616
    if self.names:
3617
      self.wanted = _GetWantedNodes(lu, self.names)
3618
    else:
3619
      self.wanted = locking.ALL_SET
3620

    
3621
    self.do_locking = (self.use_locking and
3622
                       query.NQ_LIVE in self.requested_data)
3623

    
3624
    if self.do_locking:
3625
      # if we don't request only static fields, we need to lock the nodes
3626
      lu.needed_locks[locking.LEVEL_NODE] = self.wanted
3627

    
3628
  def DeclareLocks(self, lu, level):
3629
    pass
3630

    
3631
  def _GetQueryData(self, lu):
3632
    """Computes the list of nodes and their attributes.
3633

3634
    """
3635
    all_info = lu.cfg.GetAllNodesInfo()
3636

    
3637
    nodenames = self._GetNames(lu, all_info.keys(), locking.LEVEL_NODE)
3638

    
3639
    # Gather data as requested
3640
    if query.NQ_LIVE in self.requested_data:
3641
      # filter out non-vm_capable nodes
3642
      toquery_nodes = [name for name in nodenames if all_info[name].vm_capable]
3643

    
3644
      node_data = lu.rpc.call_node_info(toquery_nodes, lu.cfg.GetVGName(),
3645
                                        lu.cfg.GetHypervisorType())
3646
      live_data = dict((name, nresult.payload)
3647
                       for (name, nresult) in node_data.items()
3648
                       if not nresult.fail_msg and nresult.payload)
3649
    else:
3650
      live_data = None
3651

    
3652
    if query.NQ_INST in self.requested_data:
3653
      node_to_primary = dict([(name, set()) for name in nodenames])
3654
      node_to_secondary = dict([(name, set()) for name in nodenames])
3655

    
3656
      inst_data = lu.cfg.GetAllInstancesInfo()
3657

    
3658
      for inst in inst_data.values():
3659
        if inst.primary_node in node_to_primary:
3660
          node_to_primary[inst.primary_node].add(inst.name)
3661
        for secnode in inst.secondary_nodes:
3662
          if secnode in node_to_secondary:
3663
            node_to_secondary[secnode].add(inst.name)
3664
    else:
3665
      node_to_primary = None
3666
      node_to_secondary = None
3667

    
3668
    if query.NQ_OOB in self.requested_data:
3669
      oob_support = dict((name, bool(_SupportsOob(lu.cfg, node)))
3670
                         for name, node in all_info.iteritems())
3671
    else:
3672
      oob_support = None
3673

    
3674
    if query.NQ_GROUP in self.requested_data:
3675
      groups = lu.cfg.GetAllNodeGroupsInfo()
3676
    else:
3677
      groups = {}
3678

    
3679
    return query.NodeQueryData([all_info[name] for name in nodenames],
3680
                               live_data, lu.cfg.GetMasterNode(),
3681
                               node_to_primary, node_to_secondary, groups,
3682
                               oob_support, lu.cfg.GetClusterInfo())
3683

    
3684

    
3685
class LUNodeQuery(NoHooksLU):
3686
  """Logical unit for querying nodes.
3687

3688
  """
3689
  # pylint: disable-msg=W0142
3690
  REQ_BGL = False
3691

    
3692
  def CheckArguments(self):
3693
    self.nq = _NodeQuery(self.op.names, self.op.output_fields,
3694
                         self.op.use_locking)
3695

    
3696
  def ExpandNames(self):
3697
    self.nq.ExpandNames(self)
3698

    
3699
  def Exec(self, feedback_fn):
3700
    return self.nq.OldStyleQuery(self)
3701

    
3702

    
3703
class LUNodeQueryvols(NoHooksLU):
3704
  """Logical unit for getting volumes on node(s).
3705

3706
  """
3707
  REQ_BGL = False
3708
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3709
  _FIELDS_STATIC = utils.FieldSet("node")
3710

    
3711
  def CheckArguments(self):
3712
    _CheckOutputFields(static=self._FIELDS_STATIC,
3713
                       dynamic=self._FIELDS_DYNAMIC,
3714
                       selected=self.op.output_fields)
3715

    
3716
  def ExpandNames(self):
3717
    self.needed_locks = {}
3718
    self.share_locks[locking.LEVEL_NODE] = 1
3719
    if not self.op.nodes:
3720
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3721
    else:
3722
      self.needed_locks[locking.LEVEL_NODE] = \
3723
        _GetWantedNodes(self, self.op.nodes)
3724

    
3725
  def Exec(self, feedback_fn):
3726
    """Computes the list of nodes and their attributes.
3727

3728
    """
3729
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3730
    volumes = self.rpc.call_node_volumes(nodenames)
3731

    
3732
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3733
             in self.cfg.GetInstanceList()]
3734

    
3735
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3736

    
3737
    output = []
3738
    for node in nodenames:
3739
      nresult = volumes[node]
3740
      if nresult.offline:
3741
        continue
3742
      msg = nresult.fail_msg
3743
      if msg:
3744
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3745
        continue
3746

    
3747
      node_vols = nresult.payload[:]
3748
      node_vols.sort(key=lambda vol: vol['dev'])
3749

    
3750
      for vol in node_vols:
3751
        node_output = []
3752
        for field in self.op.output_fields:
3753
          if field == "node":
3754
            val = node
3755
          elif field == "phys":
3756
            val = vol['dev']
3757
          elif field == "vg":
3758
            val = vol['vg']
3759
          elif field == "name":
3760
            val = vol['name']
3761
          elif field == "size":
3762
            val = int(float(vol['size']))
3763
          elif field == "instance":
3764
            for inst in ilist:
3765
              if node not in lv_by_node[inst]:
3766
                continue
3767
              if vol['name'] in lv_by_node[inst][node]:
3768
                val = inst.name
3769
                break
3770
            else:
3771
              val = '-'
3772
          else:
3773
            raise errors.ParameterError(field)
3774
          node_output.append(str(val))
3775

    
3776
        output.append(node_output)
3777

    
3778
    return output
3779

    
3780

    
3781
class LUNodeQueryStorage(NoHooksLU):
3782
  """Logical unit for getting information on storage units on node(s).
3783

3784
  """
3785
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3786
  REQ_BGL = False
3787

    
3788
  def CheckArguments(self):
3789
    _CheckOutputFields(static=self._FIELDS_STATIC,
3790
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3791
                       selected=self.op.output_fields)
3792

    
3793
  def ExpandNames(self):
3794
    self.needed_locks = {}
3795
    self.share_locks[locking.LEVEL_NODE] = 1
3796

    
3797
    if self.op.nodes:
3798
      self.needed_locks[locking.LEVEL_NODE] = \
3799
        _GetWantedNodes(self, self.op.nodes)
3800
    else:
3801
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3802

    
3803
  def Exec(self, feedback_fn):
3804
    """Computes the list of nodes and their attributes.
3805

3806
    """
3807
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3808

    
3809
    # Always get name to sort by
3810
    if constants.SF_NAME in self.op.output_fields:
3811
      fields = self.op.output_fields[:]
3812
    else:
3813
      fields = [constants.SF_NAME] + self.op.output_fields
3814

    
3815
    # Never ask for node or type as it's only known to the LU
3816
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3817
      while extra in fields:
3818
        fields.remove(extra)
3819

    
3820
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3821
    name_idx = field_idx[constants.SF_NAME]
3822

    
3823
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3824
    data = self.rpc.call_storage_list(self.nodes,
3825
                                      self.op.storage_type, st_args,
3826
                                      self.op.name, fields)
3827

    
3828
    result = []
3829

    
3830
    for node in utils.NiceSort(self.nodes):
3831
      nresult = data[node]
3832
      if nresult.offline:
3833
        continue
3834

    
3835
      msg = nresult.fail_msg
3836
      if msg:
3837
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3838
        continue
3839

    
3840
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3841

    
3842
      for name in utils.NiceSort(rows.keys()):
3843
        row = rows[name]
3844

    
3845
        out = []
3846

    
3847
        for field in self.op.output_fields:
3848
          if field == constants.SF_NODE:
3849
            val = node
3850
          elif field == constants.SF_TYPE:
3851
            val = self.op.storage_type
3852
          elif field in field_idx:
3853
            val = row[field_idx[field]]
3854
          else:
3855
            raise errors.ParameterError(field)
3856

    
3857
          out.append(val)
3858

    
3859
        result.append(out)
3860

    
3861
    return result
3862

    
3863

    
3864
class _InstanceQuery(_QueryBase):
3865
  FIELDS = query.INSTANCE_FIELDS
3866

    
3867
  def ExpandNames(self, lu):
3868
    lu.needed_locks = {}
3869
    lu.share_locks[locking.LEVEL_INSTANCE] = 1
3870
    lu.share_locks[locking.LEVEL_NODE] = 1
3871

    
3872
    if self.names:
3873
      self.wanted = _GetWantedInstances(lu, self.names)
3874
    else:
3875
      self.wanted = locking.ALL_SET
3876

    
3877
    self.do_locking = (self.use_locking and
3878
                       query.IQ_LIVE in self.requested_data)
3879
    if self.do_locking:
3880
      lu.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
3881
      lu.needed_locks[locking.LEVEL_NODE] = []
3882
      lu.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3883

    
3884
  def DeclareLocks(self, lu, level):
3885
    if level == locking.LEVEL_NODE and self.do_locking:
3886
      lu._LockInstancesNodes() # pylint: disable-msg=W0212
3887

    
3888
  def _GetQueryData(self, lu):
3889
    """Computes the list of instances and their attributes.
3890

3891
    """
3892
    cluster = lu.cfg.GetClusterInfo()
3893
    all_info = lu.cfg.GetAllInstancesInfo()
3894

    
3895
    instance_names = self._GetNames(lu, all_info.keys(), locking.LEVEL_INSTANCE)
3896

    
3897
    instance_list = [all_info[name] for name in instance_names]
3898
    nodes = frozenset(itertools.chain(*(inst.all_nodes
3899
                                        for inst in instance_list)))
3900
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
3901
    bad_nodes = []
3902
    offline_nodes = []
3903
    wrongnode_inst = set()
3904

    
3905
    # Gather data as requested
3906
    if self.requested_data & set([query.IQ_LIVE, query.IQ_CONSOLE]):
3907
      live_data = {}
3908
      node_data = lu.rpc.call_all_instances_info(nodes, hv_list)
3909
      for name in nodes:
3910
        result = node_data[name]
3911
        if result.offline:
3912
          # offline nodes will be in both lists
3913
          assert result.fail_msg
3914
          offline_nodes.append(name)
3915
        if result.fail_msg:
3916
          bad_nodes.append(name)
3917
        elif result.payload:
3918
          for inst in result.payload:
3919
            if inst in all_info:
3920
              if all_info[inst].primary_node == name:
3921
                live_data.update(result.payload)
3922
              else:
3923
                wrongnode_inst.add(inst)
3924
            else:
3925
              # orphan instance; we don't list it here as we don't
3926
              # handle this case yet in the output of instance listing
3927
              logging.warning("Orphan instance '%s' found on node %s",
3928
                              inst, name)
3929
        # else no instance is alive
3930
    else:
3931
      live_data = {}
3932

    
3933
    if query.IQ_DISKUSAGE in self.requested_data:
3934
      disk_usage = dict((inst.name,
3935
                         _ComputeDiskSize(inst.disk_template,
3936
                                          [{"size": disk.size}
3937
                                           for disk in inst.disks]))
3938
                        for inst in instance_list)
3939
    else:
3940
      disk_usage = None
3941

    
3942
    if query.IQ_CONSOLE in self.requested_data:
3943
      consinfo = {}
3944
      for inst in instance_list:
3945
        if inst.name in live_data:
3946
          # Instance is running
3947
          consinfo[inst.name] = _GetInstanceConsole(cluster, inst)
3948
        else:
3949
          consinfo[inst.name] = None
3950
      assert set(consinfo.keys()) == set(instance_names)
3951
    else:
3952
      consinfo = None
3953

    
3954
    return query.InstanceQueryData(instance_list, lu.cfg.GetClusterInfo(),
3955
                                   disk_usage, offline_nodes, bad_nodes,
3956
                                   live_data, wrongnode_inst, consinfo)
3957

    
3958

    
3959
class LUQuery(NoHooksLU):
3960
  """Query for resources/items of a certain kind.
3961

3962
  """
3963
  # pylint: disable-msg=W0142
3964
  REQ_BGL = False
3965

    
3966
  def CheckArguments(self):
3967
    qcls = _GetQueryImplementation(self.op.what)
3968
    names = qlang.ReadSimpleFilter("name", self.op.filter)
3969

    
3970
    self.impl = qcls(names, self.op.fields, False)
3971

    
3972
  def ExpandNames(self):
3973
    self.impl.ExpandNames(self)
3974

    
3975
  def DeclareLocks(self, level):
3976
    self.impl.DeclareLocks(self, level)
3977

    
3978
  def Exec(self, feedback_fn):
3979
    return self.impl.NewStyleQuery(self)
3980

    
3981

    
3982
class LUQueryFields(NoHooksLU):
3983
  """Query for resources/items of a certain kind.
3984

3985
  """
3986
  # pylint: disable-msg=W0142
3987
  REQ_BGL = False
3988

    
3989
  def CheckArguments(self):
3990
    self.qcls = _GetQueryImplementation(self.op.what)
3991

    
3992
  def ExpandNames(self):
3993
    self.needed_locks = {}
3994

    
3995
  def Exec(self, feedback_fn):
3996
    return self.qcls.FieldsQuery(self.op.fields)
3997

    
3998

    
3999
class LUNodeModifyStorage(NoHooksLU):
4000
  """Logical unit for modifying a storage volume on a node.
4001

4002
  """
4003
  REQ_BGL = False
4004

    
4005
  def CheckArguments(self):
4006
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4007

    
4008
    storage_type = self.op.storage_type
4009

    
4010
    try:
4011
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
4012
    except KeyError:
4013
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
4014
                                 " modified" % storage_type,
4015
                                 errors.ECODE_INVAL)
4016

    
4017
    diff = set(self.op.changes.keys()) - modifiable
4018
    if diff:
4019
      raise errors.OpPrereqError("The following fields can not be modified for"
4020
                                 " storage units of type '%s': %r" %
4021
                                 (storage_type, list(diff)),
4022
                                 errors.ECODE_INVAL)
4023

    
4024
  def ExpandNames(self):
4025
    self.needed_locks = {
4026
      locking.LEVEL_NODE: self.op.node_name,
4027
      }
4028

    
4029
  def Exec(self, feedback_fn):
4030
    """Computes the list of nodes and their attributes.
4031

4032
    """
4033
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4034
    result = self.rpc.call_storage_modify(self.op.node_name,
4035
                                          self.op.storage_type, st_args,
4036
                                          self.op.name, self.op.changes)
4037
    result.Raise("Failed to modify storage unit '%s' on %s" %
4038
                 (self.op.name, self.op.node_name))
4039

    
4040

    
4041
class LUNodeAdd(LogicalUnit):
4042
  """Logical unit for adding node to the cluster.
4043

4044
  """
4045
  HPATH = "node-add"
4046
  HTYPE = constants.HTYPE_NODE
4047
  _NFLAGS = ["master_capable", "vm_capable"]
4048

    
4049
  def CheckArguments(self):
4050
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
4051
    # validate/normalize the node name
4052
    self.hostname = netutils.GetHostname(name=self.op.node_name,
4053
                                         family=self.primary_ip_family)
4054
    self.op.node_name = self.hostname.name
4055
    if self.op.readd and self.op.group:
4056
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
4057
                                 " being readded", errors.ECODE_INVAL)
4058

    
4059
  def BuildHooksEnv(self):
4060
    """Build hooks env.
4061

4062
    This will run on all nodes before, and on all nodes + the new node after.
4063

4064
    """
4065
    env = {
4066
      "OP_TARGET": self.op.node_name,
4067
      "NODE_NAME": self.op.node_name,
4068
      "NODE_PIP": self.op.primary_ip,
4069
      "NODE_SIP": self.op.secondary_ip,
4070
      "MASTER_CAPABLE": str(self.op.master_capable),
4071
      "VM_CAPABLE": str(self.op.vm_capable),
4072
      }
4073
    nodes_0 = self.cfg.GetNodeList()
4074
    nodes_1 = nodes_0 + [self.op.node_name, ]
4075
    return env, nodes_0, nodes_1
4076

    
4077
  def CheckPrereq(self):
4078
    """Check prerequisites.
4079

4080
    This checks:
4081
     - the new node is not already in the config
4082
     - it is resolvable
4083
     - its parameters (single/dual homed) matches the cluster
4084

4085
    Any errors are signaled by raising errors.OpPrereqError.
4086

4087
    """
4088
    cfg = self.cfg
4089
    hostname = self.hostname
4090
    node = hostname.name
4091
    primary_ip = self.op.primary_ip = hostname.ip
4092
    if self.op.secondary_ip is None:
4093
      if self.primary_ip_family == netutils.IP6Address.family:
4094
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
4095
                                   " IPv4 address must be given as secondary",
4096
                                   errors.ECODE_INVAL)
4097
      self.op.secondary_ip = primary_ip
4098

    
4099
    secondary_ip = self.op.secondary_ip
4100
    if not netutils.IP4Address.IsValid(secondary_ip):
4101
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4102
                                 " address" % secondary_ip, errors.ECODE_INVAL)
4103

    
4104
    node_list = cfg.GetNodeList()
4105
    if not self.op.readd and node in node_list:
4106
      raise errors.OpPrereqError("Node %s is already in the configuration" %
4107
                                 node, errors.ECODE_EXISTS)
4108
    elif self.op.readd and node not in node_list:
4109
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
4110
                                 errors.ECODE_NOENT)
4111

    
4112
    self.changed_primary_ip = False
4113

    
4114
    for existing_node_name in node_list:
4115
      existing_node = cfg.GetNodeInfo(existing_node_name)
4116

    
4117
      if self.op.readd and node == existing_node_name:
4118
        if existing_node.secondary_ip != secondary_ip:
4119
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
4120
                                     " address configuration as before",
4121
                                     errors.ECODE_INVAL)
4122
        if existing_node.primary_ip != primary_ip:
4123
          self.changed_primary_ip = True
4124

    
4125
        continue
4126

    
4127
      if (existing_node.primary_ip == primary_ip or
4128
          existing_node.secondary_ip == primary_ip or
4129
          existing_node.primary_ip == secondary_ip or
4130
          existing_node.secondary_ip == secondary_ip):
4131
        raise errors.OpPrereqError("New node ip address(es) conflict with"
4132
                                   " existing node %s" % existing_node.name,
4133
                                   errors.ECODE_NOTUNIQUE)
4134

    
4135
    # After this 'if' block, None is no longer a valid value for the
4136
    # _capable op attributes
4137
    if self.op.readd:
4138
      old_node = self.cfg.GetNodeInfo(node)
4139
      assert old_node is not None, "Can't retrieve locked node %s" % node
4140
      for attr in self._NFLAGS:
4141
        if getattr(self.op, attr) is None:
4142
          setattr(self.op, attr, getattr(old_node, attr))
4143
    else:
4144
      for attr in self._NFLAGS:
4145
        if getattr(self.op, attr) is None:
4146
          setattr(self.op, attr, True)
4147

    
4148
    if self.op.readd and not self.op.vm_capable:
4149
      pri, sec = cfg.GetNodeInstances(node)
4150
      if pri or sec:
4151
        raise errors.OpPrereqError("Node %s being re-added with vm_capable"
4152
                                   " flag set to false, but it already holds"
4153
                                   " instances" % node,
4154
                                   errors.ECODE_STATE)
4155

    
4156
    # check that the type of the node (single versus dual homed) is the
4157
    # same as for the master
4158
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
4159
    master_singlehomed = myself.secondary_ip == myself.primary_ip
4160
    newbie_singlehomed = secondary_ip == primary_ip
4161
    if master_singlehomed != newbie_singlehomed:
4162
      if master_singlehomed:
4163
        raise errors.OpPrereqError("The master has no secondary ip but the"
4164
                                   " new node has one",
4165
                                   errors.ECODE_INVAL)
4166
      else:
4167
        raise errors.OpPrereqError("The master has a secondary ip but the"
4168
                                   " new node doesn't have one",
4169
                                   errors.ECODE_INVAL)
4170

    
4171
    # checks reachability
4172
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
4173
      raise errors.OpPrereqError("Node not reachable by ping",
4174
                                 errors.ECODE_ENVIRON)
4175

    
4176
    if not newbie_singlehomed:
4177
      # check reachability from my secondary ip to newbie's secondary ip
4178
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
4179
                           source=myself.secondary_ip):
4180
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4181
                                   " based ping to node daemon port",
4182
                                   errors.ECODE_ENVIRON)
4183

    
4184
    if self.op.readd:
4185
      exceptions = [node]
4186
    else:
4187
      exceptions = []
4188

    
4189
    if self.op.master_capable:
4190
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
4191
    else:
4192
      self.master_candidate = False
4193

    
4194
    if self.op.readd:
4195
      self.new_node = old_node
4196
    else:
4197
      node_group = cfg.LookupNodeGroup(self.op.group)
4198
      self.new_node = objects.Node(name=node,
4199
                                   primary_ip=primary_ip,
4200
                                   secondary_ip=secondary_ip,
4201
                                   master_candidate=self.master_candidate,
4202
                                   offline=False, drained=False,
4203
                                   group=node_group)
4204

    
4205
    if self.op.ndparams:
4206
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
4207

    
4208
  def Exec(self, feedback_fn):
4209
    """Adds the new node to the cluster.
4210

4211
    """
4212
    new_node = self.new_node
4213
    node = new_node.name
4214

    
4215
    # We adding a new node so we assume it's powered
4216
    new_node.powered = True
4217

    
4218
    # for re-adds, reset the offline/drained/master-candidate flags;
4219
    # we need to reset here, otherwise offline would prevent RPC calls
4220
    # later in the procedure; this also means that if the re-add
4221
    # fails, we are left with a non-offlined, broken node
4222
    if self.op.readd:
4223
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
4224
      self.LogInfo("Readding a node, the offline/drained flags were reset")
4225
      # if we demote the node, we do cleanup later in the procedure
4226
      new_node.master_candidate = self.master_candidate
4227
      if self.changed_primary_ip:
4228
        new_node.primary_ip = self.op.primary_ip
4229

    
4230
    # copy the master/vm_capable flags
4231
    for attr in self._NFLAGS:
4232
      setattr(new_node, attr, getattr(self.op, attr))
4233

    
4234
    # notify the user about any possible mc promotion
4235
    if new_node.master_candidate:
4236
      self.LogInfo("Node will be a master candidate")
4237

    
4238
    if self.op.ndparams:
4239
      new_node.ndparams = self.op.ndparams
4240
    else:
4241
      new_node.ndparams = {}
4242

    
4243
    # check connectivity
4244
    result = self.rpc.call_version([node])[node]
4245
    result.Raise("Can't get version information from node %s" % node)
4246
    if constants.PROTOCOL_VERSION == result.payload:
4247
      logging.info("Communication to node %s fine, sw version %s match",
4248
                   node, result.payload)
4249
    else:
4250
      raise errors.OpExecError("Version mismatch master version %s,"
4251
                               " node version %s" %
4252
                               (constants.PROTOCOL_VERSION, result.payload))
4253

    
4254
    # Add node to our /etc/hosts, and add key to known_hosts
4255
    if self.cfg.GetClusterInfo().modify_etc_hosts:
4256
      master_node = self.cfg.GetMasterNode()
4257
      result = self.rpc.call_etc_hosts_modify(master_node,
4258
                                              constants.ETC_HOSTS_ADD,
4259
                                              self.hostname.name,
4260
                                              self.hostname.ip)
4261
      result.Raise("Can't update hosts file with new host data")
4262

    
4263
    if new_node.secondary_ip != new_node.primary_ip:
4264
      _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
4265
                               False)
4266

    
4267
    node_verify_list = [self.cfg.GetMasterNode()]
4268
    node_verify_param = {
4269
      constants.NV_NODELIST: [node],
4270
      # TODO: do a node-net-test as well?
4271
    }
4272

    
4273
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
4274
                                       self.cfg.GetClusterName())
4275
    for verifier in node_verify_list:
4276
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
4277
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
4278
      if nl_payload:
4279
        for failed in nl_payload:
4280
          feedback_fn("ssh/hostname verification failed"
4281
                      " (checking from %s): %s" %
4282
                      (verifier, nl_payload[failed]))
4283
        raise errors.OpExecError("ssh/hostname verification failed.")
4284

    
4285
    if self.op.readd:
4286
      _RedistributeAncillaryFiles(self)
4287
      self.context.ReaddNode(new_node)
4288
      # make sure we redistribute the config
4289
      self.cfg.Update(new_node, feedback_fn)
4290
      # and make sure the new node will not have old files around
4291
      if not new_node.master_candidate:
4292
        result = self.rpc.call_node_demote_from_mc(new_node.name)
4293
        msg = result.fail_msg
4294
        if msg:
4295
          self.LogWarning("Node failed to demote itself from master"
4296
                          " candidate status: %s" % msg)
4297
    else:
4298
      _RedistributeAncillaryFiles(self, additional_nodes=[node],
4299
                                  additional_vm=self.op.vm_capable)
4300
      self.context.AddNode(new_node, self.proc.GetECId())
4301

    
4302

    
4303
class LUNodeSetParams(LogicalUnit):
4304
  """Modifies the parameters of a node.
4305

4306
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
4307
      to the node role (as _ROLE_*)
4308
  @cvar _R2F: a dictionary from node role to tuples of flags
4309
  @cvar _FLAGS: a list of attribute names corresponding to the flags
4310

4311
  """
4312
  HPATH = "node-modify"
4313
  HTYPE = constants.HTYPE_NODE
4314
  REQ_BGL = False
4315
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
4316
  _F2R = {
4317
    (True, False, False): _ROLE_CANDIDATE,
4318
    (False, True, False): _ROLE_DRAINED,
4319
    (False, False, True): _ROLE_OFFLINE,
4320
    (False, False, False): _ROLE_REGULAR,
4321
    }
4322
  _R2F = dict((v, k) for k, v in _F2R.items())
4323
  _FLAGS = ["master_candidate", "drained", "offline"]
4324

    
4325
  def CheckArguments(self):
4326
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4327
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
4328
                self.op.master_capable, self.op.vm_capable,
4329
                self.op.secondary_ip, self.op.ndparams]
4330
    if all_mods.count(None) == len(all_mods):
4331
      raise errors.OpPrereqError("Please pass at least one modification",
4332
                                 errors.ECODE_INVAL)
4333
    if all_mods.count(True) > 1:
4334
      raise errors.OpPrereqError("Can't set the node into more than one"
4335
                                 " state at the same time",
4336
                                 errors.ECODE_INVAL)
4337

    
4338
    # Boolean value that tells us whether we might be demoting from MC
4339
    self.might_demote = (self.op.master_candidate == False or
4340
                         self.op.offline == True or
4341
                         self.op.drained == True or
4342
                         self.op.master_capable == False)
4343

    
4344
    if self.op.secondary_ip:
4345
      if not netutils.IP4Address.IsValid(self.op.secondary_ip):
4346
        raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4347
                                   " address" % self.op.secondary_ip,
4348
                                   errors.ECODE_INVAL)
4349

    
4350
    self.lock_all = self.op.auto_promote and self.might_demote
4351
    self.lock_instances = self.op.secondary_ip is not None
4352

    
4353
  def ExpandNames(self):
4354
    if self.lock_all:
4355
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
4356
    else:
4357
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
4358

    
4359
    if self.lock_instances:
4360
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4361

    
4362
  def DeclareLocks(self, level):
4363
    # If we have locked all instances, before waiting to lock nodes, release
4364
    # all the ones living on nodes unrelated to the current operation.
4365
    if level == locking.LEVEL_NODE and self.lock_instances:
4366
      instances_release = []
4367
      instances_keep = []
4368
      self.affected_instances = []
4369
      if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4370
        for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
4371
          instance = self.context.cfg.GetInstanceInfo(instance_name)
4372
          i_mirrored = instance.disk_template in constants.DTS_INT_MIRROR
4373
          if i_mirrored and self.op.node_name in instance.all_nodes:
4374
            instances_keep.append(instance_name)
4375
            self.affected_instances.append(instance)
4376
          else:
4377
            instances_release.append(instance_name)
4378
        if instances_release:
4379
          self.context.glm.release(locking.LEVEL_INSTANCE, instances_release)
4380
          self.acquired_locks[locking.LEVEL_INSTANCE] = instances_keep
4381

    
4382
  def BuildHooksEnv(self):
4383
    """Build hooks env.
4384

4385
    This runs on the master node.
4386

4387
    """
4388
    env = {
4389
      "OP_TARGET": self.op.node_name,
4390
      "MASTER_CANDIDATE": str(self.op.master_candidate),
4391
      "OFFLINE": str(self.op.offline),
4392
      "DRAINED": str(self.op.drained),
4393
      "MASTER_CAPABLE": str(self.op.master_capable),
4394
      "VM_CAPABLE": str(self.op.vm_capable),
4395
      }
4396
    nl = [self.cfg.GetMasterNode(),
4397
          self.op.node_name]
4398
    return env, nl, nl
4399

    
4400
  def CheckPrereq(self):
4401
    """Check prerequisites.
4402

4403
    This only checks the instance list against the existing names.
4404

4405
    """
4406
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
4407

    
4408
    if (self.op.master_candidate is not None or
4409
        self.op.drained is not None or
4410
        self.op.offline is not None):
4411
      # we can't change the master's node flags
4412
      if self.op.node_name == self.cfg.GetMasterNode():
4413
        raise errors.OpPrereqError("The master role can be changed"
4414
                                   " only via master-failover",
4415
                                   errors.ECODE_INVAL)
4416

    
4417
    if self.op.master_candidate and not node.master_capable:
4418
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4419
                                 " it a master candidate" % node.name,
4420
                                 errors.ECODE_STATE)
4421

    
4422
    if self.op.vm_capable == False:
4423
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
4424
      if ipri or isec:
4425
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
4426
                                   " the vm_capable flag" % node.name,
4427
                                   errors.ECODE_STATE)
4428

    
4429
    if node.master_candidate and self.might_demote and not self.lock_all:
4430
      assert not self.op.auto_promote, "auto_promote set but lock_all not"
4431
      # check if after removing the current node, we're missing master
4432
      # candidates
4433
      (mc_remaining, mc_should, _) = \
4434
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
4435
      if mc_remaining < mc_should:
4436
        raise errors.OpPrereqError("Not enough master candidates, please"
4437
                                   " pass auto promote option to allow"
4438
                                   " promotion", errors.ECODE_STATE)
4439

    
4440
    self.old_flags = old_flags = (node.master_candidate,
4441
                                  node.drained, node.offline)
4442
    assert old_flags in self._F2R, "Un-handled old flags  %s" % str(old_flags)
4443
    self.old_role = old_role = self._F2R[old_flags]
4444

    
4445
    # Check for ineffective changes
4446
    for attr in self._FLAGS:
4447
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
4448
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
4449
        setattr(self.op, attr, None)
4450

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

    
4454
    # TODO: We might query the real power state if it supports OOB
4455
    if _SupportsOob(self.cfg, node):
4456
      if self.op.offline is False and not (node.powered or
4457
                                           self.op.powered == True):
4458
        raise errors.OpPrereqError(("Please power on node %s first before you"
4459
                                    " can reset offline state") %
4460
                                   self.op.node_name)
4461
    elif self.op.powered is not None:
4462
      raise errors.OpPrereqError(("Unable to change powered state for node %s"
4463
                                  " which does not support out-of-band"
4464
                                  " handling") % self.op.node_name)
4465

    
4466
    # If we're being deofflined/drained, we'll MC ourself if needed
4467
    if (self.op.drained == False or self.op.offline == False or
4468
        (self.op.master_capable and not node.master_capable)):
4469
      if _DecideSelfPromotion(self):
4470
        self.op.master_candidate = True
4471
        self.LogInfo("Auto-promoting node to master candidate")
4472

    
4473
    # If we're no longer master capable, we'll demote ourselves from MC
4474
    if self.op.master_capable == False and node.master_candidate:
4475
      self.LogInfo("Demoting from master candidate")
4476
      self.op.master_candidate = False
4477

    
4478
    # Compute new role
4479
    assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
4480
    if self.op.master_candidate:
4481
      new_role = self._ROLE_CANDIDATE
4482
    elif self.op.drained:
4483
      new_role = self._ROLE_DRAINED
4484
    elif self.op.offline:
4485
      new_role = self._ROLE_OFFLINE
4486
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
4487
      # False is still in new flags, which means we're un-setting (the
4488
      # only) True flag
4489
      new_role = self._ROLE_REGULAR
4490
    else: # no new flags, nothing, keep old role
4491
      new_role = old_role
4492

    
4493
    self.new_role = new_role
4494

    
4495
    if old_role == self._ROLE_OFFLINE and new_role != old_role:
4496
      # Trying to transition out of offline status
4497
      result = self.rpc.call_version([node.name])[node.name]
4498
      if result.fail_msg:
4499
        raise errors.OpPrereqError("Node %s is being de-offlined but fails"
4500
                                   " to report its version: %s" %
4501
                                   (node.name, result.fail_msg),
4502
                                   errors.ECODE_STATE)
4503
      else:
4504
        self.LogWarning("Transitioning node from offline to online state"
4505
                        " without using re-add. Please make sure the node"
4506
                        " is healthy!")
4507

    
4508
    if self.op.secondary_ip:
4509
      # Ok even without locking, because this can't be changed by any LU
4510
      master = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
4511
      master_singlehomed = master.secondary_ip == master.primary_ip
4512
      if master_singlehomed and self.op.secondary_ip:
4513
        raise errors.OpPrereqError("Cannot change the secondary ip on a single"
4514
                                   " homed cluster", errors.ECODE_INVAL)
4515

    
4516
      if node.offline:
4517
        if self.affected_instances:
4518
          raise errors.OpPrereqError("Cannot change secondary ip: offline"
4519
                                     " node has instances (%s) configured"
4520
                                     " to use it" % self.affected_instances)
4521
      else:
4522
        # On online nodes, check that no instances are running, and that
4523
        # the node has the new ip and we can reach it.
4524
        for instance in self.affected_instances:
4525
          _CheckInstanceDown(self, instance, "cannot change secondary ip")
4526

    
4527
        _CheckNodeHasSecondaryIP(self, node.name, self.op.secondary_ip, True)
4528
        if master.name != node.name:
4529
          # check reachability from master secondary ip to new secondary ip
4530
          if not netutils.TcpPing(self.op.secondary_ip,
4531
                                  constants.DEFAULT_NODED_PORT,
4532
                                  source=master.secondary_ip):
4533
            raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4534
                                       " based ping to node daemon port",
4535
                                       errors.ECODE_ENVIRON)
4536

    
4537
    if self.op.ndparams:
4538
      new_ndparams = _GetUpdatedParams(self.node.ndparams, self.op.ndparams)
4539
      utils.ForceDictType(new_ndparams, constants.NDS_PARAMETER_TYPES)
4540
      self.new_ndparams = new_ndparams
4541

    
4542
  def Exec(self, feedback_fn):
4543
    """Modifies a node.
4544

4545
    """
4546
    node = self.node
4547
    old_role = self.old_role
4548
    new_role = self.new_role
4549

    
4550
    result = []
4551

    
4552
    if self.op.ndparams:
4553
      node.ndparams = self.new_ndparams
4554

    
4555
    if self.op.powered is not None:
4556
      node.powered = self.op.powered
4557

    
4558
    for attr in ["master_capable", "vm_capable"]:
4559
      val = getattr(self.op, attr)
4560
      if val is not None:
4561
        setattr(node, attr, val)
4562
        result.append((attr, str(val)))
4563

    
4564
    if new_role != old_role:
4565
      # Tell the node to demote itself, if no longer MC and not offline
4566
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
4567
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
4568
        if msg:
4569
          self.LogWarning("Node failed to demote itself: %s", msg)
4570

    
4571
      new_flags = self._R2F[new_role]
4572
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
4573
        if of != nf:
4574
          result.append((desc, str(nf)))
4575
      (node.master_candidate, node.drained, node.offline) = new_flags
4576

    
4577
      # we locked all nodes, we adjust the CP before updating this node
4578
      if self.lock_all:
4579
        _AdjustCandidatePool(self, [node.name])
4580

    
4581
    if self.op.secondary_ip:
4582
      node.secondary_ip = self.op.secondary_ip
4583
      result.append(("secondary_ip", self.op.secondary_ip))
4584

    
4585
    # this will trigger configuration file update, if needed
4586
    self.cfg.Update(node, feedback_fn)
4587

    
4588
    # this will trigger job queue propagation or cleanup if the mc
4589
    # flag changed
4590
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
4591
      self.context.ReaddNode(node)
4592

    
4593
    return result
4594

    
4595

    
4596
class LUNodePowercycle(NoHooksLU):
4597
  """Powercycles a node.
4598

4599
  """
4600
  REQ_BGL = False
4601

    
4602
  def CheckArguments(self):
4603
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4604
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4605
      raise errors.OpPrereqError("The node is the master and the force"
4606
                                 " parameter was not set",
4607
                                 errors.ECODE_INVAL)
4608

    
4609
  def ExpandNames(self):
4610
    """Locking for PowercycleNode.
4611

4612
    This is a last-resort option and shouldn't block on other
4613
    jobs. Therefore, we grab no locks.
4614

4615
    """
4616
    self.needed_locks = {}
4617

    
4618
  def Exec(self, feedback_fn):
4619
    """Reboots a node.
4620

4621
    """
4622
    result = self.rpc.call_node_powercycle(self.op.node_name,
4623
                                           self.cfg.GetHypervisorType())
4624
    result.Raise("Failed to schedule the reboot")
4625
    return result.payload
4626

    
4627

    
4628
class LUClusterQuery(NoHooksLU):
4629
  """Query cluster configuration.
4630

4631
  """
4632
  REQ_BGL = False
4633

    
4634
  def ExpandNames(self):
4635
    self.needed_locks = {}
4636

    
4637
  def Exec(self, feedback_fn):
4638
    """Return cluster config.
4639

4640
    """
4641
    cluster = self.cfg.GetClusterInfo()
4642
    os_hvp = {}
4643

    
4644
    # Filter just for enabled hypervisors
4645
    for os_name, hv_dict in cluster.os_hvp.items():
4646
      os_hvp[os_name] = {}
4647
      for hv_name, hv_params in hv_dict.items():
4648
        if hv_name in cluster.enabled_hypervisors:
4649
          os_hvp[os_name][hv_name] = hv_params
4650

    
4651
    # Convert ip_family to ip_version
4652
    primary_ip_version = constants.IP4_VERSION
4653
    if cluster.primary_ip_family == netutils.IP6Address.family:
4654
      primary_ip_version = constants.IP6_VERSION
4655

    
4656
    result = {
4657
      "software_version": constants.RELEASE_VERSION,
4658
      "protocol_version": constants.PROTOCOL_VERSION,
4659
      "config_version": constants.CONFIG_VERSION,
4660
      "os_api_version": max(constants.OS_API_VERSIONS),
4661
      "export_version": constants.EXPORT_VERSION,
4662
      "architecture": (platform.architecture()[0], platform.machine()),
4663
      "name": cluster.cluster_name,
4664
      "master": cluster.master_node,
4665
      "default_hypervisor": cluster.enabled_hypervisors[0],
4666
      "enabled_hypervisors": cluster.enabled_hypervisors,
4667
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4668
                        for hypervisor_name in cluster.enabled_hypervisors]),
4669
      "os_hvp": os_hvp,
4670
      "beparams": cluster.beparams,
4671
      "osparams": cluster.osparams,
4672
      "nicparams": cluster.nicparams,
4673
      "ndparams": cluster.ndparams,
4674
      "candidate_pool_size": cluster.candidate_pool_size,
4675
      "master_netdev": cluster.master_netdev,
4676
      "volume_group_name": cluster.volume_group_name,
4677
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
4678
      "file_storage_dir": cluster.file_storage_dir,
4679
      "shared_file_storage_dir": cluster.shared_file_storage_dir,
4680
      "maintain_node_health": cluster.maintain_node_health,
4681
      "ctime": cluster.ctime,
4682
      "mtime": cluster.mtime,
4683
      "uuid": cluster.uuid,
4684
      "tags": list(cluster.GetTags()),
4685
      "uid_pool": cluster.uid_pool,
4686
      "default_iallocator": cluster.default_iallocator,
4687
      "reserved_lvs": cluster.reserved_lvs,
4688
      "primary_ip_version": primary_ip_version,
4689
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
4690
      "hidden_os": cluster.hidden_os,
4691
      "blacklisted_os": cluster.blacklisted_os,
4692
      }
4693

    
4694
    return result
4695

    
4696

    
4697
class LUClusterConfigQuery(NoHooksLU):
4698
  """Return configuration values.
4699

4700
  """
4701
  REQ_BGL = False
4702
  _FIELDS_DYNAMIC = utils.FieldSet()
4703
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4704
                                  "watcher_pause", "volume_group_name")
4705

    
4706
  def CheckArguments(self):
4707
    _CheckOutputFields(static=self._FIELDS_STATIC,
4708
                       dynamic=self._FIELDS_DYNAMIC,
4709
                       selected=self.op.output_fields)
4710

    
4711
  def ExpandNames(self):
4712
    self.needed_locks = {}
4713

    
4714
  def Exec(self, feedback_fn):
4715
    """Dump a representation of the cluster config to the standard output.
4716

4717
    """
4718
    values = []
4719
    for field in self.op.output_fields:
4720
      if field == "cluster_name":
4721
        entry = self.cfg.GetClusterName()
4722
      elif field == "master_node":
4723
        entry = self.cfg.GetMasterNode()
4724
      elif field == "drain_flag":
4725
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4726
      elif field == "watcher_pause":
4727
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4728
      elif field == "volume_group_name":
4729
        entry = self.cfg.GetVGName()
4730
      else:
4731
        raise errors.ParameterError(field)
4732
      values.append(entry)
4733
    return values
4734

    
4735

    
4736
class LUInstanceActivateDisks(NoHooksLU):
4737
  """Bring up an instance's disks.
4738

4739
  """
4740
  REQ_BGL = False
4741

    
4742
  def ExpandNames(self):
4743
    self._ExpandAndLockInstance()
4744
    self.needed_locks[locking.LEVEL_NODE] = []
4745
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4746

    
4747
  def DeclareLocks(self, level):
4748
    if level == locking.LEVEL_NODE:
4749
      self._LockInstancesNodes()
4750

    
4751
  def CheckPrereq(self):
4752
    """Check prerequisites.
4753

4754
    This checks that the instance is in the cluster.
4755

4756
    """
4757
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4758
    assert self.instance is not None, \
4759
      "Cannot retrieve locked instance %s" % self.op.instance_name
4760
    _CheckNodeOnline(self, self.instance.primary_node)
4761

    
4762
  def Exec(self, feedback_fn):
4763
    """Activate the disks.
4764

4765
    """
4766
    disks_ok, disks_info = \
4767
              _AssembleInstanceDisks(self, self.instance,
4768
                                     ignore_size=self.op.ignore_size)
4769
    if not disks_ok:
4770
      raise errors.OpExecError("Cannot activate block devices")
4771

    
4772
    return disks_info
4773

    
4774

    
4775
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4776
                           ignore_size=False):
4777
  """Prepare the block devices for an instance.
4778

4779
  This sets up the block devices on all nodes.
4780

4781
  @type lu: L{LogicalUnit}
4782
  @param lu: the logical unit on whose behalf we execute
4783
  @type instance: L{objects.Instance}
4784
  @param instance: the instance for whose disks we assemble
4785
  @type disks: list of L{objects.Disk} or None
4786
  @param disks: which disks to assemble (or all, if None)
4787
  @type ignore_secondaries: boolean
4788
  @param ignore_secondaries: if true, errors on secondary nodes
4789
      won't result in an error return from the function
4790
  @type ignore_size: boolean
4791
  @param ignore_size: if true, the current known size of the disk
4792
      will not be used during the disk activation, useful for cases
4793
      when the size is wrong
4794
  @return: False if the operation failed, otherwise a list of
4795
      (host, instance_visible_name, node_visible_name)
4796
      with the mapping from node devices to instance devices
4797

4798
  """
4799
  device_info = []
4800
  disks_ok = True
4801
  iname = instance.name
4802
  disks = _ExpandCheckDisks(instance, disks)
4803

    
4804
  # With the two passes mechanism we try to reduce the window of
4805
  # opportunity for the race condition of switching DRBD to primary
4806
  # before handshaking occured, but we do not eliminate it
4807

    
4808
  # The proper fix would be to wait (with some limits) until the
4809
  # connection has been made and drbd transitions from WFConnection
4810
  # into any other network-connected state (Connected, SyncTarget,
4811
  # SyncSource, etc.)
4812

    
4813
  # 1st pass, assemble on all nodes in secondary mode
4814
  for idx, inst_disk in enumerate(disks):
4815
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4816
      if ignore_size:
4817
        node_disk = node_disk.Copy()
4818
        node_disk.UnsetSize()
4819
      lu.cfg.SetDiskID(node_disk, node)
4820
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False, idx)
4821
      msg = result.fail_msg
4822
      if msg:
4823
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4824
                           " (is_primary=False, pass=1): %s",
4825
                           inst_disk.iv_name, node, msg)
4826
        if not ignore_secondaries:
4827
          disks_ok = False
4828

    
4829
  # FIXME: race condition on drbd migration to primary
4830

    
4831
  # 2nd pass, do only the primary node
4832
  for idx, inst_disk in enumerate(disks):
4833
    dev_path = None
4834

    
4835
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4836
      if node != instance.primary_node:
4837
        continue
4838
      if ignore_size:
4839
        node_disk = node_disk.Copy()
4840
        node_disk.UnsetSize()
4841
      lu.cfg.SetDiskID(node_disk, node)
4842
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True, idx)
4843
      msg = result.fail_msg
4844
      if msg:
4845
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4846
                           " (is_primary=True, pass=2): %s",
4847
                           inst_disk.iv_name, node, msg)
4848
        disks_ok = False
4849
      else:
4850
        dev_path = result.payload
4851

    
4852
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4853

    
4854
  # leave the disks configured for the primary node
4855
  # this is a workaround that would be fixed better by
4856
  # improving the logical/physical id handling
4857
  for disk in disks:
4858
    lu.cfg.SetDiskID(disk, instance.primary_node)
4859

    
4860
  return disks_ok, device_info
4861

    
4862

    
4863
def _StartInstanceDisks(lu, instance, force):
4864
  """Start the disks of an instance.
4865

4866
  """
4867
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4868
                                           ignore_secondaries=force)
4869
  if not disks_ok:
4870
    _ShutdownInstanceDisks(lu, instance)
4871
    if force is not None and not force:
4872
      lu.proc.LogWarning("", hint="If the message above refers to a"
4873
                         " secondary node,"
4874
                         " you can retry the operation using '--force'.")
4875
    raise errors.OpExecError("Disk consistency error")
4876

    
4877

    
4878
class LUInstanceDeactivateDisks(NoHooksLU):
4879
  """Shutdown an instance's disks.
4880

4881
  """
4882
  REQ_BGL = False
4883

    
4884
  def ExpandNames(self):
4885
    self._ExpandAndLockInstance()
4886
    self.needed_locks[locking.LEVEL_NODE] = []
4887
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4888

    
4889
  def DeclareLocks(self, level):
4890
    if level == locking.LEVEL_NODE:
4891
      self._LockInstancesNodes()
4892

    
4893
  def CheckPrereq(self):
4894
    """Check prerequisites.
4895

4896
    This checks that the instance is in the cluster.
4897

4898
    """
4899
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4900
    assert self.instance is not None, \
4901
      "Cannot retrieve locked instance %s" % self.op.instance_name
4902

    
4903
  def Exec(self, feedback_fn):
4904
    """Deactivate the disks
4905

4906
    """
4907
    instance = self.instance
4908
    if self.op.force:
4909
      _ShutdownInstanceDisks(self, instance)
4910
    else:
4911
      _SafeShutdownInstanceDisks(self, instance)
4912

    
4913

    
4914
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4915
  """Shutdown block devices of an instance.
4916

4917
  This function checks if an instance is running, before calling
4918
  _ShutdownInstanceDisks.
4919

4920
  """
4921
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4922
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4923

    
4924

    
4925
def _ExpandCheckDisks(instance, disks):
4926
  """Return the instance disks selected by the disks list
4927

4928
  @type disks: list of L{objects.Disk} or None
4929
  @param disks: selected disks
4930
  @rtype: list of L{objects.Disk}
4931
  @return: selected instance disks to act on
4932

4933
  """
4934
  if disks is None:
4935
    return instance.disks
4936
  else:
4937
    if not set(disks).issubset(instance.disks):
4938
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4939
                                   " target instance")
4940
    return disks
4941

    
4942

    
4943
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4944
  """Shutdown block devices of an instance.
4945

4946
  This does the shutdown on all nodes of the instance.
4947

4948
  If the ignore_primary is false, errors on the primary node are
4949
  ignored.
4950

4951
  """
4952
  all_result = True
4953
  disks = _ExpandCheckDisks(instance, disks)
4954

    
4955
  for disk in disks:
4956
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4957
      lu.cfg.SetDiskID(top_disk, node)
4958
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4959
      msg = result.fail_msg
4960
      if msg:
4961
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4962
                      disk.iv_name, node, msg)
4963
        if ((node == instance.primary_node and not ignore_primary) or
4964
            (node != instance.primary_node and not result.offline)):
4965
          all_result = False
4966
  return all_result
4967

    
4968

    
4969
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4970
  """Checks if a node has enough free memory.
4971

4972
  This function check if a given node has the needed amount of free
4973
  memory. In case the node has less memory or we cannot get the
4974
  information from the node, this function raise an OpPrereqError
4975
  exception.
4976

4977
  @type lu: C{LogicalUnit}
4978
  @param lu: a logical unit from which we get configuration data
4979
  @type node: C{str}
4980
  @param node: the node to check
4981
  @type reason: C{str}
4982
  @param reason: string to use in the error message
4983
  @type requested: C{int}
4984
  @param requested: the amount of memory in MiB to check for
4985
  @type hypervisor_name: C{str}
4986
  @param hypervisor_name: the hypervisor to ask for memory stats
4987
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4988
      we cannot check the node
4989

4990
  """
4991
  nodeinfo = lu.rpc.call_node_info([node], None, hypervisor_name)
4992
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4993
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4994
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4995
  if not isinstance(free_mem, int):
4996
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4997
                               " was '%s'" % (node, free_mem),
4998
                               errors.ECODE_ENVIRON)
4999
  if requested > free_mem:
5000
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
5001
                               " needed %s MiB, available %s MiB" %
5002
                               (node, reason, requested, free_mem),
5003
                               errors.ECODE_NORES)
5004

    
5005

    
5006
def _CheckNodesFreeDiskPerVG(lu, nodenames, req_sizes):
5007
  """Checks if nodes have enough free disk space in the all VGs.
5008

5009
  This function check if all given nodes have the needed amount of
5010
  free disk. In case any node has less disk or we cannot get the
5011
  information from the node, this function raise an OpPrereqError
5012
  exception.
5013

5014
  @type lu: C{LogicalUnit}
5015
  @param lu: a logical unit from which we get configuration data
5016
  @type nodenames: C{list}
5017
  @param nodenames: the list of node names to check
5018
  @type req_sizes: C{dict}
5019
  @param req_sizes: the hash of vg and corresponding amount of disk in
5020
      MiB to check for
5021
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5022
      or we cannot check the node
5023

5024
  """
5025
  for vg, req_size in req_sizes.items():
5026
    _CheckNodesFreeDiskOnVG(lu, nodenames, vg, req_size)
5027

    
5028

    
5029
def _CheckNodesFreeDiskOnVG(lu, nodenames, vg, requested):
5030
  """Checks if nodes have enough free disk space in the specified VG.
5031

5032
  This function check if all given nodes have the needed amount of
5033
  free disk. In case any node has less disk or we cannot get the
5034
  information from the node, this function raise an OpPrereqError
5035
  exception.
5036

5037
  @type lu: C{LogicalUnit}
5038
  @param lu: a logical unit from which we get configuration data
5039
  @type nodenames: C{list}
5040
  @param nodenames: the list of node names to check
5041
  @type vg: C{str}
5042
  @param vg: the volume group to check
5043
  @type requested: C{int}
5044
  @param requested: the amount of disk in MiB to check for
5045
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5046
      or we cannot check the node
5047

5048
  """
5049
  nodeinfo = lu.rpc.call_node_info(nodenames, vg, None)
5050
  for node in nodenames:
5051
    info = nodeinfo[node]
5052
    info.Raise("Cannot get current information from node %s" % node,
5053
               prereq=True, ecode=errors.ECODE_ENVIRON)
5054
    vg_free = info.payload.get("vg_free", None)
5055
    if not isinstance(vg_free, int):
5056
      raise errors.OpPrereqError("Can't compute free disk space on node"
5057
                                 " %s for vg %s, result was '%s'" %
5058
                                 (node, vg, vg_free), errors.ECODE_ENVIRON)
5059
    if requested > vg_free:
5060
      raise errors.OpPrereqError("Not enough disk space on target node %s"
5061
                                 " vg %s: required %d MiB, available %d MiB" %
5062
                                 (node, vg, requested, vg_free),
5063
                                 errors.ECODE_NORES)
5064

    
5065

    
5066
class LUInstanceStartup(LogicalUnit):
5067
  """Starts an instance.
5068

5069
  """
5070
  HPATH = "instance-start"
5071
  HTYPE = constants.HTYPE_INSTANCE
5072
  REQ_BGL = False
5073

    
5074
  def CheckArguments(self):
5075
    # extra beparams
5076
    if self.op.beparams:
5077
      # fill the beparams dict
5078
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5079

    
5080
  def ExpandNames(self):
5081
    self._ExpandAndLockInstance()
5082

    
5083
  def BuildHooksEnv(self):
5084
    """Build hooks env.
5085

5086
    This runs on master, primary and secondary nodes of the instance.
5087

5088
    """
5089
    env = {
5090
      "FORCE": self.op.force,
5091
      }
5092
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5093
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5094
    return env, nl, nl
5095

    
5096
  def CheckPrereq(self):
5097
    """Check prerequisites.
5098

5099
    This checks that the instance is in the cluster.
5100

5101
    """
5102
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5103
    assert self.instance is not None, \
5104
      "Cannot retrieve locked instance %s" % self.op.instance_name
5105

    
5106
    # extra hvparams
5107
    if self.op.hvparams:
5108
      # check hypervisor parameter syntax (locally)
5109
      cluster = self.cfg.GetClusterInfo()
5110
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5111
      filled_hvp = cluster.FillHV(instance)
5112
      filled_hvp.update(self.op.hvparams)
5113
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
5114
      hv_type.CheckParameterSyntax(filled_hvp)
5115
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
5116

    
5117
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
5118

    
5119
    if self.primary_offline and self.op.ignore_offline_nodes:
5120
      self.proc.LogWarning("Ignoring offline primary node")
5121

    
5122
      if self.op.hvparams or self.op.beparams:
5123
        self.proc.LogWarning("Overridden parameters are ignored")
5124
    else:
5125
      _CheckNodeOnline(self, instance.primary_node)
5126

    
5127
      bep = self.cfg.GetClusterInfo().FillBE(instance)
5128

    
5129
      # check bridges existence
5130
      _CheckInstanceBridgesExist(self, instance)
5131

    
5132
      remote_info = self.rpc.call_instance_info(instance.primary_node,
5133
                                                instance.name,
5134
                                                instance.hypervisor)
5135
      remote_info.Raise("Error checking node %s" % instance.primary_node,
5136
                        prereq=True, ecode=errors.ECODE_ENVIRON)
5137
      if not remote_info.payload: # not running already
5138
        _CheckNodeFreeMemory(self, instance.primary_node,
5139
                             "starting instance %s" % instance.name,
5140
                             bep[constants.BE_MEMORY], instance.hypervisor)
5141

    
5142
  def Exec(self, feedback_fn):
5143
    """Start the instance.
5144

5145
    """
5146
    instance = self.instance
5147
    force = self.op.force
5148

    
5149
    self.cfg.MarkInstanceUp(instance.name)
5150

    
5151
    if self.primary_offline:
5152
      assert self.op.ignore_offline_nodes
5153
      self.proc.LogInfo("Primary node offline, marked instance as started")
5154
    else:
5155
      node_current = instance.primary_node
5156

    
5157
      _StartInstanceDisks(self, instance, force)
5158

    
5159
      result = self.rpc.call_instance_start(node_current, instance,
5160
                                            self.op.hvparams, self.op.beparams)
5161
      msg = result.fail_msg
5162
      if msg:
5163
        _ShutdownInstanceDisks(self, instance)
5164
        raise errors.OpExecError("Could not start instance: %s" % msg)
5165

    
5166

    
5167
class LUInstanceReboot(LogicalUnit):
5168
  """Reboot an instance.
5169

5170
  """
5171
  HPATH = "instance-reboot"
5172
  HTYPE = constants.HTYPE_INSTANCE
5173
  REQ_BGL = False
5174

    
5175
  def ExpandNames(self):
5176
    self._ExpandAndLockInstance()
5177

    
5178
  def BuildHooksEnv(self):
5179
    """Build hooks env.
5180

5181
    This runs on master, primary and secondary nodes of the instance.
5182

5183
    """
5184
    env = {
5185
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
5186
      "REBOOT_TYPE": self.op.reboot_type,
5187
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5188
      }
5189
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5190
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5191
    return env, nl, nl
5192

    
5193
  def CheckPrereq(self):
5194
    """Check prerequisites.
5195

5196
    This checks that the instance is in the cluster.
5197

5198
    """
5199
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5200
    assert self.instance is not None, \
5201
      "Cannot retrieve locked instance %s" % self.op.instance_name
5202

    
5203
    _CheckNodeOnline(self, instance.primary_node)
5204

    
5205
    # check bridges existence
5206
    _CheckInstanceBridgesExist(self, instance)
5207

    
5208
  def Exec(self, feedback_fn):
5209
    """Reboot the instance.
5210

5211
    """
5212
    instance = self.instance
5213
    ignore_secondaries = self.op.ignore_secondaries
5214
    reboot_type = self.op.reboot_type
5215

    
5216
    node_current = instance.primary_node
5217

    
5218
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
5219
                       constants.INSTANCE_REBOOT_HARD]:
5220
      for disk in instance.disks:
5221
        self.cfg.SetDiskID(disk, node_current)
5222
      result = self.rpc.call_instance_reboot(node_current, instance,
5223
                                             reboot_type,
5224
                                             self.op.shutdown_timeout)
5225
      result.Raise("Could not reboot instance")
5226
    else:
5227
      result = self.rpc.call_instance_shutdown(node_current, instance,
5228
                                               self.op.shutdown_timeout)
5229
      result.Raise("Could not shutdown instance for full reboot")
5230
      _ShutdownInstanceDisks(self, instance)
5231
      _StartInstanceDisks(self, instance, ignore_secondaries)
5232
      result = self.rpc.call_instance_start(node_current, instance, None, None)
5233
      msg = result.fail_msg
5234
      if msg:
5235
        _ShutdownInstanceDisks(self, instance)
5236
        raise errors.OpExecError("Could not start instance for"
5237
                                 " full reboot: %s" % msg)
5238

    
5239
    self.cfg.MarkInstanceUp(instance.name)
5240

    
5241

    
5242
class LUInstanceShutdown(LogicalUnit):
5243
  """Shutdown an instance.
5244

5245
  """
5246
  HPATH = "instance-stop"
5247
  HTYPE = constants.HTYPE_INSTANCE
5248
  REQ_BGL = False
5249

    
5250
  def ExpandNames(self):
5251
    self._ExpandAndLockInstance()
5252

    
5253
  def BuildHooksEnv(self):
5254
    """Build hooks env.
5255

5256
    This runs on master, primary and secondary nodes of the instance.
5257

5258
    """
5259
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5260
    env["TIMEOUT"] = self.op.timeout
5261
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5262
    return env, nl, nl
5263

    
5264
  def CheckPrereq(self):
5265
    """Check prerequisites.
5266

5267
    This checks that the instance is in the cluster.
5268

5269
    """
5270
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5271
    assert self.instance is not None, \
5272
      "Cannot retrieve locked instance %s" % self.op.instance_name
5273

    
5274
    self.primary_offline = \
5275
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
5276

    
5277
    if self.primary_offline and self.op.ignore_offline_nodes:
5278
      self.proc.LogWarning("Ignoring offline primary node")
5279
    else:
5280
      _CheckNodeOnline(self, self.instance.primary_node)
5281

    
5282
  def Exec(self, feedback_fn):
5283
    """Shutdown the instance.
5284

5285
    """
5286
    instance = self.instance
5287
    node_current = instance.primary_node
5288
    timeout = self.op.timeout
5289

    
5290
    self.cfg.MarkInstanceDown(instance.name)
5291

    
5292
    if self.primary_offline:
5293
      assert self.op.ignore_offline_nodes
5294
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
5295
    else:
5296
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
5297
      msg = result.fail_msg
5298
      if msg:
5299
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
5300

    
5301
      _ShutdownInstanceDisks(self, instance)
5302

    
5303

    
5304
class LUInstanceReinstall(LogicalUnit):
5305
  """Reinstall an instance.
5306

5307
  """
5308
  HPATH = "instance-reinstall"
5309
  HTYPE = constants.HTYPE_INSTANCE
5310
  REQ_BGL = False
5311

    
5312
  def ExpandNames(self):
5313
    self._ExpandAndLockInstance()
5314

    
5315
  def BuildHooksEnv(self):
5316
    """Build hooks env.
5317

5318
    This runs on master, primary and secondary nodes of the instance.
5319

5320
    """
5321
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5322
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5323
    return env, nl, nl
5324

    
5325
  def CheckPrereq(self):
5326
    """Check prerequisites.
5327

5328
    This checks that the instance is in the cluster and is not running.
5329

5330
    """
5331
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5332
    assert instance is not None, \
5333
      "Cannot retrieve locked instance %s" % self.op.instance_name
5334
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
5335
                     " offline, cannot reinstall")
5336
    for node in instance.secondary_nodes:
5337
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
5338
                       " cannot reinstall")
5339

    
5340
    if instance.disk_template == constants.DT_DISKLESS:
5341
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5342
                                 self.op.instance_name,
5343
                                 errors.ECODE_INVAL)
5344
    _CheckInstanceDown(self, instance, "cannot reinstall")
5345

    
5346
    if self.op.os_type is not None:
5347
      # OS verification
5348
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
5349
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
5350
      instance_os = self.op.os_type
5351
    else:
5352
      instance_os = instance.os
5353

    
5354
    nodelist = list(instance.all_nodes)
5355

    
5356
    if self.op.osparams:
5357
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
5358
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
5359
      self.os_inst = i_osdict # the new dict (without defaults)
5360
    else:
5361
      self.os_inst = None
5362

    
5363
    self.instance = instance
5364

    
5365
  def Exec(self, feedback_fn):
5366
    """Reinstall the instance.
5367

5368
    """
5369
    inst = self.instance
5370

    
5371
    if self.op.os_type is not None:
5372
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
5373
      inst.os = self.op.os_type
5374
      # Write to configuration
5375
      self.cfg.Update(inst, feedback_fn)
5376

    
5377
    _StartInstanceDisks(self, inst, None)
5378
    try:
5379
      feedback_fn("Running the instance OS create scripts...")
5380
      # FIXME: pass debug option from opcode to backend
5381
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
5382
                                             self.op.debug_level,
5383
                                             osparams=self.os_inst)
5384
      result.Raise("Could not install OS for instance %s on node %s" %
5385
                   (inst.name, inst.primary_node))
5386
    finally:
5387
      _ShutdownInstanceDisks(self, inst)
5388

    
5389

    
5390
class LUInstanceRecreateDisks(LogicalUnit):
5391
  """Recreate an instance's missing disks.
5392

5393
  """
5394
  HPATH = "instance-recreate-disks"
5395
  HTYPE = constants.HTYPE_INSTANCE
5396
  REQ_BGL = False
5397

    
5398
  def ExpandNames(self):
5399
    self._ExpandAndLockInstance()
5400

    
5401
  def BuildHooksEnv(self):
5402
    """Build hooks env.
5403

5404
    This runs on master, primary and secondary nodes of the instance.
5405

5406
    """
5407
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5408
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5409
    return env, nl, nl
5410

    
5411
  def CheckPrereq(self):
5412
    """Check prerequisites.
5413

5414
    This checks that the instance is in the cluster and is not running.
5415

5416
    """
5417
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5418
    assert instance is not None, \
5419
      "Cannot retrieve locked instance %s" % self.op.instance_name
5420
    _CheckNodeOnline(self, instance.primary_node)
5421

    
5422
    if instance.disk_template == constants.DT_DISKLESS:
5423
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5424
                                 self.op.instance_name, errors.ECODE_INVAL)
5425
    _CheckInstanceDown(self, instance, "cannot recreate disks")
5426

    
5427
    if not self.op.disks:
5428
      self.op.disks = range(len(instance.disks))
5429
    else:
5430
      for idx in self.op.disks:
5431
        if idx >= len(instance.disks):
5432
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
5433
                                     errors.ECODE_INVAL)
5434

    
5435
    self.instance = instance
5436

    
5437
  def Exec(self, feedback_fn):
5438
    """Recreate the disks.
5439

5440
    """
5441
    to_skip = []
5442
    for idx, _ in enumerate(self.instance.disks):
5443
      if idx not in self.op.disks: # disk idx has not been passed in
5444
        to_skip.append(idx)
5445
        continue
5446

    
5447
    _CreateDisks(self, self.instance, to_skip=to_skip)
5448

    
5449

    
5450
class LUInstanceRename(LogicalUnit):
5451
  """Rename an instance.
5452

5453
  """
5454
  HPATH = "instance-rename"
5455
  HTYPE = constants.HTYPE_INSTANCE
5456

    
5457
  def CheckArguments(self):
5458
    """Check arguments.
5459

5460
    """
5461
    if self.op.ip_check and not self.op.name_check:
5462
      # TODO: make the ip check more flexible and not depend on the name check
5463
      raise errors.OpPrereqError("Cannot do ip check without a name check",
5464
                                 errors.ECODE_INVAL)
5465

    
5466
  def BuildHooksEnv(self):
5467
    """Build hooks env.
5468

5469
    This runs on master, primary and secondary nodes of the instance.
5470

5471
    """
5472
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5473
    env["INSTANCE_NEW_NAME"] = self.op.new_name
5474
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5475
    return env, nl, nl
5476

    
5477
  def CheckPrereq(self):
5478
    """Check prerequisites.
5479

5480
    This checks that the instance is in the cluster and is not running.
5481

5482
    """
5483
    self.op.instance_name = _ExpandInstanceName(self.cfg,
5484
                                                self.op.instance_name)
5485
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5486
    assert instance is not None
5487
    _CheckNodeOnline(self, instance.primary_node)
5488
    _CheckInstanceDown(self, instance, "cannot rename")
5489
    self.instance = instance
5490

    
5491
    new_name = self.op.new_name
5492
    if self.op.name_check:
5493
      hostname = netutils.GetHostname(name=new_name)
5494
      self.LogInfo("Resolved given name '%s' to '%s'", new_name,
5495
                   hostname.name)
5496
      new_name = self.op.new_name = hostname.name
5497
      if (self.op.ip_check and
5498
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
5499
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
5500
                                   (hostname.ip, new_name),
5501
                                   errors.ECODE_NOTUNIQUE)
5502

    
5503
    instance_list = self.cfg.GetInstanceList()
5504
    if new_name in instance_list and new_name != instance.name:
5505
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5506
                                 new_name, errors.ECODE_EXISTS)
5507

    
5508
  def Exec(self, feedback_fn):
5509
    """Rename the instance.
5510

5511
    """
5512
    inst = self.instance
5513
    old_name = inst.name
5514

    
5515
    rename_file_storage = False
5516
    if (inst.disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE) and
5517
        self.op.new_name != inst.name):
5518
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5519
      rename_file_storage = True
5520

    
5521
    self.cfg.RenameInstance(inst.name, self.op.new_name)
5522
    # Change the instance lock. This is definitely safe while we hold the BGL
5523
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
5524
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
5525

    
5526
    # re-read the instance from the configuration after rename
5527
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
5528

    
5529
    if rename_file_storage:
5530
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5531
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
5532
                                                     old_file_storage_dir,
5533
                                                     new_file_storage_dir)
5534
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
5535
                   " (but the instance has been renamed in Ganeti)" %
5536
                   (inst.primary_node, old_file_storage_dir,
5537
                    new_file_storage_dir))
5538

    
5539
    _StartInstanceDisks(self, inst, None)
5540
    try:
5541
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
5542
                                                 old_name, self.op.debug_level)
5543
      msg = result.fail_msg
5544
      if msg:
5545
        msg = ("Could not run OS rename script for instance %s on node %s"
5546
               " (but the instance has been renamed in Ganeti): %s" %
5547
               (inst.name, inst.primary_node, msg))
5548
        self.proc.LogWarning(msg)
5549
    finally:
5550
      _ShutdownInstanceDisks(self, inst)
5551

    
5552
    return inst.name
5553

    
5554

    
5555
class LUInstanceRemove(LogicalUnit):
5556
  """Remove an instance.
5557

5558
  """
5559
  HPATH = "instance-remove"
5560
  HTYPE = constants.HTYPE_INSTANCE
5561
  REQ_BGL = False
5562

    
5563
  def ExpandNames(self):
5564
    self._ExpandAndLockInstance()
5565
    self.needed_locks[locking.LEVEL_NODE] = []
5566
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5567

    
5568
  def DeclareLocks(self, level):
5569
    if level == locking.LEVEL_NODE:
5570
      self._LockInstancesNodes()
5571

    
5572
  def BuildHooksEnv(self):
5573
    """Build hooks env.
5574

5575
    This runs on master, primary and secondary nodes of the instance.
5576

5577
    """
5578
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5579
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
5580
    nl = [self.cfg.GetMasterNode()]
5581
    nl_post = list(self.instance.all_nodes) + nl
5582
    return env, nl, nl_post
5583

    
5584
  def CheckPrereq(self):
5585
    """Check prerequisites.
5586

5587
    This checks that the instance is in the cluster.
5588

5589
    """
5590
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5591
    assert self.instance is not None, \
5592
      "Cannot retrieve locked instance %s" % self.op.instance_name
5593

    
5594
  def Exec(self, feedback_fn):
5595
    """Remove the instance.
5596

5597
    """
5598
    instance = self.instance
5599
    logging.info("Shutting down instance %s on node %s",
5600
                 instance.name, instance.primary_node)
5601

    
5602
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5603
                                             self.op.shutdown_timeout)
5604
    msg = result.fail_msg
5605
    if msg:
5606
      if self.op.ignore_failures:
5607
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5608
      else:
5609
        raise errors.OpExecError("Could not shutdown instance %s on"
5610
                                 " node %s: %s" %
5611
                                 (instance.name, instance.primary_node, msg))
5612

    
5613
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5614

    
5615

    
5616
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5617
  """Utility function to remove an instance.
5618

5619
  """
5620
  logging.info("Removing block devices for instance %s", instance.name)
5621

    
5622
  if not _RemoveDisks(lu, instance):
5623
    if not ignore_failures:
5624
      raise errors.OpExecError("Can't remove instance's disks")
5625
    feedback_fn("Warning: can't remove instance's disks")
5626

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

    
5629
  lu.cfg.RemoveInstance(instance.name)
5630

    
5631
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5632
    "Instance lock removal conflict"
5633

    
5634
  # Remove lock for the instance
5635
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5636

    
5637

    
5638
class LUInstanceQuery(NoHooksLU):
5639
  """Logical unit for querying instances.
5640

5641
  """
5642
  # pylint: disable-msg=W0142
5643
  REQ_BGL = False
5644

    
5645
  def CheckArguments(self):
5646
    self.iq = _InstanceQuery(self.op.names, self.op.output_fields,
5647
                             self.op.use_locking)
5648

    
5649
  def ExpandNames(self):
5650
    self.iq.ExpandNames(self)
5651

    
5652
  def DeclareLocks(self, level):
5653
    self.iq.DeclareLocks(self, level)
5654

    
5655
  def Exec(self, feedback_fn):
5656
    return self.iq.OldStyleQuery(self)
5657

    
5658

    
5659
class LUInstanceFailover(LogicalUnit):
5660
  """Failover an instance.
5661

5662
  """
5663
  HPATH = "instance-failover"
5664
  HTYPE = constants.HTYPE_INSTANCE
5665
  REQ_BGL = False
5666

    
5667
  def CheckArguments(self):
5668
    """Check the arguments.
5669

5670
    """
5671
    self.iallocator = getattr(self.op, "iallocator", None)
5672
    self.target_node = getattr(self.op, "target_node", None)
5673

    
5674
  def ExpandNames(self):
5675
    self._ExpandAndLockInstance()
5676

    
5677
    if self.op.target_node is not None:
5678
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5679

    
5680
    self.needed_locks[locking.LEVEL_NODE] = []
5681
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5682

    
5683
  def DeclareLocks(self, level):
5684
    if level == locking.LEVEL_NODE:
5685
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
5686
      if instance.disk_template in constants.DTS_EXT_MIRROR:
5687
        if self.op.target_node is None:
5688
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5689
        else:
5690
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
5691
                                                   self.op.target_node]
5692
        del self.recalculate_locks[locking.LEVEL_NODE]
5693
      else:
5694
        self._LockInstancesNodes()
5695

    
5696
  def BuildHooksEnv(self):
5697
    """Build hooks env.
5698

5699
    This runs on master, primary and secondary nodes of the instance.
5700

5701
    """
5702
    instance = self.instance
5703
    source_node = instance.primary_node
5704
    env = {
5705
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5706
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5707
      "OLD_PRIMARY": source_node,
5708
      "NEW_PRIMARY": self.op.target_node,
5709
      }
5710

    
5711
    if instance.disk_template in constants.DTS_INT_MIRROR:
5712
      env["OLD_SECONDARY"] = instance.secondary_nodes[0]
5713
      env["NEW_SECONDARY"] = source_node
5714
    else:
5715
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = ""
5716

    
5717
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5718
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5719
    nl_post = list(nl)
5720
    nl_post.append(source_node)
5721
    return env, nl, nl_post
5722

    
5723
  def CheckPrereq(self):
5724
    """Check prerequisites.
5725

5726
    This checks that the instance is in the cluster.
5727

5728
    """
5729
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5730
    assert self.instance is not None, \
5731
      "Cannot retrieve locked instance %s" % self.op.instance_name
5732

    
5733
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5734
    if instance.disk_template not in constants.DTS_MIRRORED:
5735
      raise errors.OpPrereqError("Instance's disk layout is not"
5736
                                 " mirrored, cannot failover.",
5737
                                 errors.ECODE_STATE)
5738

    
5739
    if instance.disk_template in constants.DTS_EXT_MIRROR:
5740
      _CheckIAllocatorOrNode(self, "iallocator", "target_node")
5741
      if self.op.iallocator:
5742
        self._RunAllocator()
5743
        # Release all unnecessary node locks
5744
        nodes_keep = [instance.primary_node, self.op.target_node]
5745
        nodes_rel = [node for node in self.acquired_locks[locking.LEVEL_NODE]
5746
                     if node not in nodes_keep]
5747
        self.context.glm.release(locking.LEVEL_NODE, nodes_rel)
5748
        self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
5749

    
5750
      # self.op.target_node is already populated, either directly or by the
5751
      # iallocator run
5752
      target_node = self.op.target_node
5753

    
5754
    else:
5755
      secondary_nodes = instance.secondary_nodes
5756
      if not secondary_nodes:
5757
        raise errors.ConfigurationError("No secondary node but using"
5758
                                        " %s disk template" %
5759
                                        instance.disk_template)
5760
      target_node = secondary_nodes[0]
5761

    
5762
      if self.op.iallocator or (self.op.target_node and
5763
                                self.op.target_node != target_node):
5764
        raise errors.OpPrereqError("Instances with disk template %s cannot"
5765
                                   " be failed over to arbitrary nodes"
5766
                                   " (neither an iallocator nor a target"
5767
                                   " node can be passed)" %
5768
                                   instance.disk_template, errors.ECODE_INVAL)
5769
    _CheckNodeOnline(self, target_node)
5770
    _CheckNodeNotDrained(self, target_node)
5771

    
5772
    # Save target_node so that we can use it in BuildHooksEnv
5773
    self.op.target_node = target_node
5774

    
5775
    if instance.admin_up:
5776
      # check memory requirements on the secondary node
5777
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5778
                           instance.name, bep[constants.BE_MEMORY],
5779
                           instance.hypervisor)
5780
    else:
5781
      self.LogInfo("Not checking memory on the secondary node as"
5782
                   " instance will not be started")
5783

    
5784
    # check bridge existance
5785
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5786

    
5787
  def Exec(self, feedback_fn):
5788
    """Failover an instance.
5789

5790
    The failover is done by shutting it down on its present node and
5791
    starting it on the secondary.
5792

5793
    """
5794
    instance = self.instance
5795
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
5796

    
5797
    source_node = instance.primary_node
5798
    target_node = self.op.target_node
5799

    
5800
    if instance.admin_up:
5801
      feedback_fn("* checking disk consistency between source and target")
5802
      for dev in instance.disks:
5803
        # for drbd, these are drbd over lvm
5804
        if not _CheckDiskConsistency(self, dev, target_node, False):
5805
          if not self.op.ignore_consistency:
5806
            raise errors.OpExecError("Disk %s is degraded on target node,"
5807
                                     " aborting failover." % dev.iv_name)
5808
    else:
5809
      feedback_fn("* not checking disk consistency as instance is not running")
5810

    
5811
    feedback_fn("* shutting down instance on source node")
5812
    logging.info("Shutting down instance %s on node %s",
5813
                 instance.name, source_node)
5814

    
5815
    result = self.rpc.call_instance_shutdown(source_node, instance,
5816
                                             self.op.shutdown_timeout)
5817
    msg = result.fail_msg
5818
    if msg:
5819
      if self.op.ignore_consistency or primary_node.offline:
5820
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5821
                             " Proceeding anyway. Please make sure node"
5822
                             " %s is down. Error details: %s",
5823
                             instance.name, source_node, source_node, msg)
5824
      else:
5825
        raise errors.OpExecError("Could not shutdown instance %s on"
5826
                                 " node %s: %s" %
5827
                                 (instance.name, source_node, msg))
5828

    
5829
    feedback_fn("* deactivating the instance's disks on source node")
5830
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5831
      raise errors.OpExecError("Can't shut down the instance's disks.")
5832

    
5833
    instance.primary_node = target_node
5834
    # distribute new instance config to the other nodes
5835
    self.cfg.Update(instance, feedback_fn)
5836

    
5837
    # Only start the instance if it's marked as up
5838
    if instance.admin_up:
5839
      feedback_fn("* activating the instance's disks on target node")
5840
      logging.info("Starting instance %s on node %s",
5841
                   instance.name, target_node)
5842

    
5843
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5844
                                           ignore_secondaries=True)
5845
      if not disks_ok:
5846
        _ShutdownInstanceDisks(self, instance)
5847
        raise errors.OpExecError("Can't activate the instance's disks")
5848

    
5849
      feedback_fn("* starting the instance on the target node")
5850
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5851
      msg = result.fail_msg
5852
      if msg:
5853
        _ShutdownInstanceDisks(self, instance)
5854
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5855
                                 (instance.name, target_node, msg))
5856

    
5857
  def _RunAllocator(self):
5858
    """Run the allocator based on input opcode.
5859

5860
    """
5861
    ial = IAllocator(self.cfg, self.rpc,
5862
                     mode=constants.IALLOCATOR_MODE_RELOC,
5863
                     name=self.instance.name,
5864
                     # TODO See why hail breaks with a single node below
5865
                     relocate_from=[self.instance.primary_node,
5866
                                    self.instance.primary_node],
5867
                     )
5868

    
5869
    ial.Run(self.op.iallocator)
5870

    
5871
    if not ial.success:
5872
      raise errors.OpPrereqError("Can't compute nodes using"
5873
                                 " iallocator '%s': %s" %
5874
                                 (self.op.iallocator, ial.info),
5875
                                 errors.ECODE_NORES)
5876
    if len(ial.result) != ial.required_nodes:
5877
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
5878
                                 " of nodes (%s), required %s" %
5879
                                 (self.op.iallocator, len(ial.result),
5880
                                  ial.required_nodes), errors.ECODE_FAULT)
5881
    self.op.target_node = ial.result[0]
5882
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
5883
                 self.instance.name, self.op.iallocator,
5884
                 utils.CommaJoin(ial.result))
5885

    
5886

    
5887
class LUInstanceMigrate(LogicalUnit):
5888
  """Migrate an instance.
5889

5890
  This is migration without shutting down, compared to the failover,
5891
  which is done with shutdown.
5892

5893
  """
5894
  HPATH = "instance-migrate"
5895
  HTYPE = constants.HTYPE_INSTANCE
5896
  REQ_BGL = False
5897

    
5898
  def ExpandNames(self):
5899
    self._ExpandAndLockInstance()
5900

    
5901
    if self.op.target_node is not None:
5902
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5903

    
5904
    self.needed_locks[locking.LEVEL_NODE] = []
5905
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5906

    
5907
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5908
                                       self.op.cleanup, self.op.iallocator,
5909
                                       self.op.target_node)
5910
    self.tasklets = [self._migrater]
5911

    
5912
  def DeclareLocks(self, level):
5913
    if level == locking.LEVEL_NODE:
5914
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
5915
      if instance.disk_template in constants.DTS_EXT_MIRROR:
5916
        if self.op.target_node is None:
5917
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5918
        else:
5919
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
5920
                                                   self.op.target_node]
5921
        del self.recalculate_locks[locking.LEVEL_NODE]
5922
      else:
5923
        self._LockInstancesNodes()
5924

    
5925
  def BuildHooksEnv(self):
5926
    """Build hooks env.
5927

5928
    This runs on master, primary and secondary nodes of the instance.
5929

5930
    """
5931
    instance = self._migrater.instance
5932
    source_node = instance.primary_node
5933
    target_node = self._migrater.target_node
5934
    env = _BuildInstanceHookEnvByObject(self, instance)
5935
    env["MIGRATE_LIVE"] = self._migrater.live
5936
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5937
    env.update({
5938
        "OLD_PRIMARY": source_node,
5939
        "NEW_PRIMARY": target_node,
5940
        })
5941

    
5942
    if instance.disk_template in constants.DTS_INT_MIRROR:
5943
      env["OLD_SECONDARY"] = target_node
5944
      env["NEW_SECONDARY"] = source_node
5945
    else:
5946
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = None
5947

    
5948
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5949
    nl_post = list(nl)
5950
    nl_post.append(source_node)
5951
    return env, nl, nl_post
5952

    
5953

    
5954
class LUInstanceMove(LogicalUnit):
5955
  """Move an instance by data-copying.
5956

5957
  """
5958
  HPATH = "instance-move"
5959
  HTYPE = constants.HTYPE_INSTANCE
5960
  REQ_BGL = False
5961

    
5962
  def ExpandNames(self):
5963
    self._ExpandAndLockInstance()
5964
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5965
    self.op.target_node = target_node
5966
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5967
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5968

    
5969
  def DeclareLocks(self, level):
5970
    if level == locking.LEVEL_NODE:
5971
      self._LockInstancesNodes(primary_only=True)
5972

    
5973
  def BuildHooksEnv(self):
5974
    """Build hooks env.
5975

5976
    This runs on master, primary and secondary nodes of the instance.
5977

5978
    """
5979
    env = {
5980
      "TARGET_NODE": self.op.target_node,
5981
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5982
      }
5983
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5984
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5985
                                       self.op.target_node]
5986
    return env, nl, nl
5987

    
5988
  def CheckPrereq(self):
5989
    """Check prerequisites.
5990

5991
    This checks that the instance is in the cluster.
5992

5993
    """
5994
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5995
    assert self.instance is not None, \
5996
      "Cannot retrieve locked instance %s" % self.op.instance_name
5997

    
5998
    node = self.cfg.GetNodeInfo(self.op.target_node)
5999
    assert node is not None, \
6000
      "Cannot retrieve locked node %s" % self.op.target_node
6001

    
6002
    self.target_node = target_node = node.name
6003

    
6004
    if target_node == instance.primary_node:
6005
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
6006
                                 (instance.name, target_node),
6007
                                 errors.ECODE_STATE)
6008

    
6009
    bep = self.cfg.GetClusterInfo().FillBE(instance)
6010

    
6011
    for idx, dsk in enumerate(instance.disks):
6012
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
6013
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
6014
                                   " cannot copy" % idx, errors.ECODE_STATE)
6015

    
6016
    _CheckNodeOnline(self, target_node)
6017
    _CheckNodeNotDrained(self, target_node)
6018
    _CheckNodeVmCapable(self, target_node)
6019

    
6020
    if instance.admin_up:
6021
      # check memory requirements on the secondary node
6022
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
6023
                           instance.name, bep[constants.BE_MEMORY],
6024
                           instance.hypervisor)
6025
    else:
6026
      self.LogInfo("Not checking memory on the secondary node as"
6027
                   " instance will not be started")
6028

    
6029
    # check bridge existance
6030
    _CheckInstanceBridgesExist(self, instance, node=target_node)
6031

    
6032
  def Exec(self, feedback_fn):
6033
    """Move an instance.
6034

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

6038
    """
6039
    instance = self.instance
6040

    
6041
    source_node = instance.primary_node
6042
    target_node = self.target_node
6043

    
6044
    self.LogInfo("Shutting down instance %s on source node %s",
6045
                 instance.name, source_node)
6046

    
6047
    result = self.rpc.call_instance_shutdown(source_node, instance,
6048
                                             self.op.shutdown_timeout)
6049
    msg = result.fail_msg
6050
    if msg:
6051
      if self.op.ignore_consistency:
6052
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
6053
                             " Proceeding anyway. Please make sure node"
6054
                             " %s is down. Error details: %s",
6055
                             instance.name, source_node, source_node, msg)
6056
      else:
6057
        raise errors.OpExecError("Could not shutdown instance %s on"
6058
                                 " node %s: %s" %
6059
                                 (instance.name, source_node, msg))
6060

    
6061
    # create the target disks
6062
    try:
6063
      _CreateDisks(self, instance, target_node=target_node)
6064
    except errors.OpExecError:
6065
      self.LogWarning("Device creation failed, reverting...")
6066
      try:
6067
        _RemoveDisks(self, instance, target_node=target_node)
6068
      finally:
6069
        self.cfg.ReleaseDRBDMinors(instance.name)
6070
        raise
6071

    
6072
    cluster_name = self.cfg.GetClusterInfo().cluster_name
6073

    
6074
    errs = []
6075
    # activate, get path, copy the data over
6076
    for idx, disk in enumerate(instance.disks):
6077
      self.LogInfo("Copying data for disk %d", idx)
6078
      result = self.rpc.call_blockdev_assemble(target_node, disk,
6079
                                               instance.name, True, idx)
6080
      if result.fail_msg:
6081
        self.LogWarning("Can't assemble newly created disk %d: %s",
6082
                        idx, result.fail_msg)
6083
        errs.append(result.fail_msg)
6084
        break
6085
      dev_path = result.payload
6086
      result = self.rpc.call_blockdev_export(source_node, disk,
6087
                                             target_node, dev_path,
6088
                                             cluster_name)
6089
      if result.fail_msg:
6090
        self.LogWarning("Can't copy data over for disk %d: %s",
6091
                        idx, result.fail_msg)
6092
        errs.append(result.fail_msg)
6093
        break
6094

    
6095
    if errs:
6096
      self.LogWarning("Some disks failed to copy, aborting")
6097
      try:
6098
        _RemoveDisks(self, instance, target_node=target_node)
6099
      finally:
6100
        self.cfg.ReleaseDRBDMinors(instance.name)
6101
        raise errors.OpExecError("Errors during disk copy: %s" %
6102
                                 (",".join(errs),))
6103

    
6104
    instance.primary_node = target_node
6105
    self.cfg.Update(instance, feedback_fn)
6106

    
6107
    self.LogInfo("Removing the disks on the original node")
6108
    _RemoveDisks(self, instance, target_node=source_node)
6109

    
6110
    # Only start the instance if it's marked as up
6111
    if instance.admin_up:
6112
      self.LogInfo("Starting instance %s on node %s",
6113
                   instance.name, target_node)
6114

    
6115
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
6116
                                           ignore_secondaries=True)
6117
      if not disks_ok:
6118
        _ShutdownInstanceDisks(self, instance)
6119
        raise errors.OpExecError("Can't activate the instance's disks")
6120

    
6121
      result = self.rpc.call_instance_start(target_node, instance, None, None)
6122
      msg = result.fail_msg
6123
      if msg:
6124
        _ShutdownInstanceDisks(self, instance)
6125
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
6126
                                 (instance.name, target_node, msg))
6127

    
6128

    
6129
class LUNodeMigrate(LogicalUnit):
6130
  """Migrate all instances from a node.
6131

6132
  """
6133
  HPATH = "node-migrate"
6134
  HTYPE = constants.HTYPE_NODE
6135
  REQ_BGL = False
6136

    
6137
  def CheckArguments(self):
6138
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
6139

    
6140
  def ExpandNames(self):
6141
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6142

    
6143
    self.needed_locks = {}
6144

    
6145
    # Create tasklets for migrating instances for all instances on this node
6146
    names = []
6147
    tasklets = []
6148

    
6149
    self.lock_all_nodes = False
6150

    
6151
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
6152
      logging.debug("Migrating instance %s", inst.name)
6153
      names.append(inst.name)
6154

    
6155
      tasklets.append(TLMigrateInstance(self, inst.name, False,
6156
                                        self.op.iallocator, None))
6157

    
6158
      if inst.disk_template in constants.DTS_EXT_MIRROR:
6159
        # We need to lock all nodes, as the iallocator will choose the
6160
        # destination nodes afterwards
6161
        self.lock_all_nodes = True
6162

    
6163
    self.tasklets = tasklets
6164

    
6165
    # Declare node locks
6166
    if self.lock_all_nodes:
6167
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6168
    else:
6169
      self.needed_locks[locking.LEVEL_NODE] = [self.op.node_name]
6170
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6171

    
6172
    # Declare instance locks
6173
    self.needed_locks[locking.LEVEL_INSTANCE] = names
6174

    
6175
  def DeclareLocks(self, level):
6176
    if level == locking.LEVEL_NODE and not self.lock_all_nodes:
6177
      self._LockInstancesNodes()
6178

    
6179
  def BuildHooksEnv(self):
6180
    """Build hooks env.
6181

6182
    This runs on the master, the primary and all the secondaries.
6183

6184
    """
6185
    env = {
6186
      "NODE_NAME": self.op.node_name,
6187
      }
6188

    
6189
    nl = [self.cfg.GetMasterNode()]
6190

    
6191
    return (env, nl, nl)
6192

    
6193

    
6194
class TLMigrateInstance(Tasklet):
6195
  """Tasklet class for instance migration.
6196

6197
  @type live: boolean
6198
  @ivar live: whether the migration will be done live or non-live;
6199
      this variable is initalized only after CheckPrereq has run
6200

6201
  """
6202
  def __init__(self, lu, instance_name, cleanup,
6203
               iallocator=None, target_node=None):
6204
    """Initializes this class.
6205

6206
    """
6207
    Tasklet.__init__(self, lu)
6208

    
6209
    # Parameters
6210
    self.instance_name = instance_name
6211
    self.cleanup = cleanup
6212
    self.live = False # will be overridden later
6213
    self.iallocator = iallocator
6214
    self.target_node = target_node
6215

    
6216
  def CheckPrereq(self):
6217
    """Check prerequisites.
6218

6219
    This checks that the instance is in the cluster.
6220

6221
    """
6222
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
6223
    instance = self.cfg.GetInstanceInfo(instance_name)
6224
    assert instance is not None
6225
    self.instance = instance
6226

    
6227
    if instance.disk_template not in constants.DTS_MIRRORED:
6228
      raise errors.OpPrereqError("Instance's disk layout '%s' does not allow"
6229
                                 " migrations" % instance.disk_template,
6230
                                 errors.ECODE_STATE)
6231

    
6232
    if instance.disk_template in constants.DTS_EXT_MIRROR:
6233
      _CheckIAllocatorOrNode(self.lu, "iallocator", "target_node")
6234

    
6235
      if self.iallocator:
6236
        self._RunAllocator()
6237

    
6238
      # self.target_node is already populated, either directly or by the
6239
      # iallocator run
6240
      target_node = self.target_node
6241

    
6242
      if len(self.lu.tasklets) == 1:
6243
        # It is safe to remove locks only when we're the only tasklet in the LU
6244
        nodes_keep = [instance.primary_node, self.target_node]
6245
        nodes_rel = [node for node in self.lu.acquired_locks[locking.LEVEL_NODE]
6246
                     if node not in nodes_keep]
6247
        self.lu.context.glm.release(locking.LEVEL_NODE, nodes_rel)
6248
        self.lu.acquired_locks[locking.LEVEL_NODE] = nodes_keep
6249

    
6250
    else:
6251
      secondary_nodes = instance.secondary_nodes
6252
      if not secondary_nodes:
6253
        raise errors.ConfigurationError("No secondary node but using"
6254
                                        " %s disk template" %
6255
                                        instance.disk_template)
6256
      target_node = secondary_nodes[0]
6257
      if self.lu.op.iallocator or (self.lu.op.target_node and
6258
                                   self.lu.op.target_node != target_node):
6259
        raise errors.OpPrereqError("Instances with disk template %s cannot"
6260
                                   " be migrated over to arbitrary nodes"
6261
                                   " (neither an iallocator nor a target"
6262
                                   " node can be passed)" %
6263
                                   instance.disk_template, errors.ECODE_INVAL)
6264

    
6265
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
6266

    
6267
    # check memory requirements on the secondary node
6268
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
6269
                         instance.name, i_be[constants.BE_MEMORY],
6270
                         instance.hypervisor)
6271

    
6272
    # check bridge existance
6273
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
6274

    
6275
    if not self.cleanup:
6276
      _CheckNodeNotDrained(self.lu, target_node)
6277
      result = self.rpc.call_instance_migratable(instance.primary_node,
6278
                                                 instance)
6279
      result.Raise("Can't migrate, please use failover",
6280
                   prereq=True, ecode=errors.ECODE_STATE)
6281

    
6282

    
6283
  def _RunAllocator(self):
6284
    """Run the allocator based on input opcode.
6285

6286
    """
6287
    ial = IAllocator(self.cfg, self.rpc,
6288
                     mode=constants.IALLOCATOR_MODE_RELOC,
6289
                     name=self.instance_name,
6290
                     # TODO See why hail breaks with a single node below
6291
                     relocate_from=[self.instance.primary_node,
6292
                                    self.instance.primary_node],
6293
                     )
6294

    
6295
    ial.Run(self.iallocator)
6296

    
6297
    if not ial.success:
6298
      raise errors.OpPrereqError("Can't compute nodes using"
6299
                                 " iallocator '%s': %s" %
6300
                                 (self.iallocator, ial.info),
6301
                                 errors.ECODE_NORES)
6302
    if len(ial.result) != ial.required_nodes:
6303
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6304
                                 " of nodes (%s), required %s" %
6305
                                 (self.iallocator, len(ial.result),
6306
                                  ial.required_nodes), errors.ECODE_FAULT)
6307
    self.target_node = ial.result[0]
6308
    self.lu.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6309
                 self.instance_name, self.iallocator,
6310
                 utils.CommaJoin(ial.result))
6311

    
6312
    if self.lu.op.live is not None and self.lu.op.mode is not None:
6313
      raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
6314
                                 " parameters are accepted",
6315
                                 errors.ECODE_INVAL)
6316
    if self.lu.op.live is not None:
6317
      if self.lu.op.live:
6318
        self.lu.op.mode = constants.HT_MIGRATION_LIVE
6319
      else:
6320
        self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6321
      # reset the 'live' parameter to None so that repeated
6322
      # invocations of CheckPrereq do not raise an exception
6323
      self.lu.op.live = None
6324
    elif self.lu.op.mode is None:
6325
      # read the default value from the hypervisor
6326
      i_hv = self.cfg.GetClusterInfo().FillHV(self.instance, skip_globals=False)
6327
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6328

    
6329
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6330

    
6331
  def _WaitUntilSync(self):
6332
    """Poll with custom rpc for disk sync.
6333

6334
    This uses our own step-based rpc call.
6335

6336
    """
6337
    self.feedback_fn("* wait until resync is done")
6338
    all_done = False
6339
    while not all_done:
6340
      all_done = True
6341
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6342
                                            self.nodes_ip,
6343
                                            self.instance.disks)
6344
      min_percent = 100
6345
      for node, nres in result.items():
6346
        nres.Raise("Cannot resync disks on node %s" % node)
6347
        node_done, node_percent = nres.payload
6348
        all_done = all_done and node_done
6349
        if node_percent is not None:
6350
          min_percent = min(min_percent, node_percent)
6351
      if not all_done:
6352
        if min_percent < 100:
6353
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6354
        time.sleep(2)
6355

    
6356
  def _EnsureSecondary(self, node):
6357
    """Demote a node to secondary.
6358

6359
    """
6360
    self.feedback_fn("* switching node %s to secondary mode" % node)
6361

    
6362
    for dev in self.instance.disks:
6363
      self.cfg.SetDiskID(dev, node)
6364

    
6365
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6366
                                          self.instance.disks)
6367
    result.Raise("Cannot change disk to secondary on node %s" % node)
6368

    
6369
  def _GoStandalone(self):
6370
    """Disconnect from the network.
6371

6372
    """
6373
    self.feedback_fn("* changing into standalone mode")
6374
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6375
                                               self.instance.disks)
6376
    for node, nres in result.items():
6377
      nres.Raise("Cannot disconnect disks node %s" % node)
6378

    
6379
  def _GoReconnect(self, multimaster):
6380
    """Reconnect to the network.
6381

6382
    """
6383
    if multimaster:
6384
      msg = "dual-master"
6385
    else:
6386
      msg = "single-master"
6387
    self.feedback_fn("* changing disks into %s mode" % msg)
6388
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6389
                                           self.instance.disks,
6390
                                           self.instance.name, multimaster)
6391
    for node, nres in result.items():
6392
      nres.Raise("Cannot change disks config on node %s" % node)
6393

    
6394
  def _ExecCleanup(self):
6395
    """Try to cleanup after a failed migration.
6396

6397
    The cleanup is done by:
6398
      - check that the instance is running only on one node
6399
        (and update the config if needed)
6400
      - change disks on its secondary node to secondary
6401
      - wait until disks are fully synchronized
6402
      - disconnect from the network
6403
      - change disks into single-master mode
6404
      - wait again until disks are fully synchronized
6405

6406
    """
6407
    instance = self.instance
6408
    target_node = self.target_node
6409
    source_node = self.source_node
6410

    
6411
    # check running on only one node
6412
    self.feedback_fn("* checking where the instance actually runs"
6413
                     " (if this hangs, the hypervisor might be in"
6414
                     " a bad state)")
6415
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
6416
    for node, result in ins_l.items():
6417
      result.Raise("Can't contact node %s" % node)
6418

    
6419
    runningon_source = instance.name in ins_l[source_node].payload
6420
    runningon_target = instance.name in ins_l[target_node].payload
6421

    
6422
    if runningon_source and runningon_target:
6423
      raise errors.OpExecError("Instance seems to be running on two nodes,"
6424
                               " or the hypervisor is confused. You will have"
6425
                               " to ensure manually that it runs only on one"
6426
                               " and restart this operation.")
6427

    
6428
    if not (runningon_source or runningon_target):
6429
      raise errors.OpExecError("Instance does not seem to be running at all."
6430
                               " In this case, it's safer to repair by"
6431
                               " running 'gnt-instance stop' to ensure disk"
6432
                               " shutdown, and then restarting it.")
6433

    
6434
    if runningon_target:
6435
      # the migration has actually succeeded, we need to update the config
6436
      self.feedback_fn("* instance running on secondary node (%s),"
6437
                       " updating config" % target_node)
6438
      instance.primary_node = target_node
6439
      self.cfg.Update(instance, self.feedback_fn)
6440
      demoted_node = source_node
6441
    else:
6442
      self.feedback_fn("* instance confirmed to be running on its"
6443
                       " primary node (%s)" % source_node)
6444
      demoted_node = target_node
6445

    
6446
    if instance.disk_template in constants.DTS_INT_MIRROR:
6447
      self._EnsureSecondary(demoted_node)
6448
      try:
6449
        self._WaitUntilSync()
6450
      except errors.OpExecError:
6451
        # we ignore here errors, since if the device is standalone, it
6452
        # won't be able to sync
6453
        pass
6454
      self._GoStandalone()
6455
      self._GoReconnect(False)
6456
      self._WaitUntilSync()
6457

    
6458
    self.feedback_fn("* done")
6459

    
6460
  def _RevertDiskStatus(self):
6461
    """Try to revert the disk status after a failed migration.
6462

6463
    """
6464
    target_node = self.target_node
6465
    if self.instance.disk_template in constants.DTS_EXT_MIRROR:
6466
      return
6467

    
6468
    try:
6469
      self._EnsureSecondary(target_node)
6470
      self._GoStandalone()
6471
      self._GoReconnect(False)
6472
      self._WaitUntilSync()
6473
    except errors.OpExecError, err:
6474
      self.lu.LogWarning("Migration failed and I can't reconnect the"
6475
                         " drives: error '%s'\n"
6476
                         "Please look and recover the instance status" %
6477
                         str(err))
6478

    
6479
  def _AbortMigration(self):
6480
    """Call the hypervisor code to abort a started migration.
6481

6482
    """
6483
    instance = self.instance
6484
    target_node = self.target_node
6485
    migration_info = self.migration_info
6486

    
6487
    abort_result = self.rpc.call_finalize_migration(target_node,
6488
                                                    instance,
6489
                                                    migration_info,
6490
                                                    False)
6491
    abort_msg = abort_result.fail_msg
6492
    if abort_msg:
6493
      logging.error("Aborting migration failed on target node %s: %s",
6494
                    target_node, abort_msg)
6495
      # Don't raise an exception here, as we stil have to try to revert the
6496
      # disk status, even if this step failed.
6497

    
6498
  def _ExecMigration(self):
6499
    """Migrate an instance.
6500

6501
    The migrate is done by:
6502
      - change the disks into dual-master mode
6503
      - wait until disks are fully synchronized again
6504
      - migrate the instance
6505
      - change disks on the new secondary node (the old primary) to secondary
6506
      - wait until disks are fully synchronized
6507
      - change disks into single-master mode
6508

6509
    """
6510
    instance = self.instance
6511
    target_node = self.target_node
6512
    source_node = self.source_node
6513

    
6514
    self.feedback_fn("* checking disk consistency between source and target")
6515
    for dev in instance.disks:
6516
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6517
        raise errors.OpExecError("Disk %s is degraded or not fully"
6518
                                 " synchronized on target node,"
6519
                                 " aborting migrate." % dev.iv_name)
6520

    
6521
    # First get the migration information from the remote node
6522
    result = self.rpc.call_migration_info(source_node, instance)
6523
    msg = result.fail_msg
6524
    if msg:
6525
      log_err = ("Failed fetching source migration information from %s: %s" %
6526
                 (source_node, msg))
6527
      logging.error(log_err)
6528
      raise errors.OpExecError(log_err)
6529

    
6530
    self.migration_info = migration_info = result.payload
6531

    
6532
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
6533
      # Then switch the disks to master/master mode
6534
      self._EnsureSecondary(target_node)
6535
      self._GoStandalone()
6536
      self._GoReconnect(True)
6537
      self._WaitUntilSync()
6538

    
6539
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6540
    result = self.rpc.call_accept_instance(target_node,
6541
                                           instance,
6542
                                           migration_info,
6543
                                           self.nodes_ip[target_node])
6544

    
6545
    msg = result.fail_msg
6546
    if msg:
6547
      logging.error("Instance pre-migration failed, trying to revert"
6548
                    " disk status: %s", msg)
6549
      self.feedback_fn("Pre-migration failed, aborting")
6550
      self._AbortMigration()
6551
      self._RevertDiskStatus()
6552
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6553
                               (instance.name, msg))
6554

    
6555
    self.feedback_fn("* migrating instance to %s" % target_node)
6556
    time.sleep(10)
6557
    result = self.rpc.call_instance_migrate(source_node, instance,
6558
                                            self.nodes_ip[target_node],
6559
                                            self.live)
6560
    msg = result.fail_msg
6561
    if msg:
6562
      logging.error("Instance migration failed, trying to revert"
6563
                    " disk status: %s", msg)
6564
      self.feedback_fn("Migration failed, aborting")
6565
      self._AbortMigration()
6566
      self._RevertDiskStatus()
6567
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6568
                               (instance.name, msg))
6569
    time.sleep(10)
6570

    
6571
    instance.primary_node = target_node
6572
    # distribute new instance config to the other nodes
6573
    self.cfg.Update(instance, self.feedback_fn)
6574

    
6575
    result = self.rpc.call_finalize_migration(target_node,
6576
                                              instance,
6577
                                              migration_info,
6578
                                              True)
6579
    msg = result.fail_msg
6580
    if msg:
6581
      logging.error("Instance migration succeeded, but finalization failed:"
6582
                    " %s", msg)
6583
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6584
                               msg)
6585

    
6586
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
6587
      self._EnsureSecondary(source_node)
6588
      self._WaitUntilSync()
6589
      self._GoStandalone()
6590
      self._GoReconnect(False)
6591
      self._WaitUntilSync()
6592

    
6593
    self.feedback_fn("* done")
6594

    
6595
  def Exec(self, feedback_fn):
6596
    """Perform the migration.
6597

6598
    """
6599
    feedback_fn("Migrating instance %s" % self.instance.name)
6600

    
6601
    self.feedback_fn = feedback_fn
6602

    
6603
    self.source_node = self.instance.primary_node
6604

    
6605
    # FIXME: if we implement migrate-to-any in DRBD, this needs fixing
6606
    if self.instance.disk_template in constants.DTS_INT_MIRROR:
6607
      self.target_node = self.instance.secondary_nodes[0]
6608
      # Otherwise self.target_node has been populated either
6609
      # directly, or through an iallocator.
6610

    
6611
    self.all_nodes = [self.source_node, self.target_node]
6612
    self.nodes_ip = {
6613
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6614
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6615
      }
6616

    
6617
    if self.cleanup:
6618
      return self._ExecCleanup()
6619
    else:
6620
      return self._ExecMigration()
6621

    
6622

    
6623
def _CreateBlockDev(lu, node, instance, device, force_create,
6624
                    info, force_open):
6625
  """Create a tree of block devices on a given node.
6626

6627
  If this device type has to be created on secondaries, create it and
6628
  all its children.
6629

6630
  If not, just recurse to children keeping the same 'force' value.
6631

6632
  @param lu: the lu on whose behalf we execute
6633
  @param node: the node on which to create the device
6634
  @type instance: L{objects.Instance}
6635
  @param instance: the instance which owns the device
6636
  @type device: L{objects.Disk}
6637
  @param device: the device to create
6638
  @type force_create: boolean
6639
  @param force_create: whether to force creation of this device; this
6640
      will be change to True whenever we find a device which has
6641
      CreateOnSecondary() attribute
6642
  @param info: the extra 'metadata' we should attach to the device
6643
      (this will be represented as a LVM tag)
6644
  @type force_open: boolean
6645
  @param force_open: this parameter will be passes to the
6646
      L{backend.BlockdevCreate} function where it specifies
6647
      whether we run on primary or not, and it affects both
6648
      the child assembly and the device own Open() execution
6649

6650
  """
6651
  if device.CreateOnSecondary():
6652
    force_create = True
6653

    
6654
  if device.children:
6655
    for child in device.children:
6656
      _CreateBlockDev(lu, node, instance, child, force_create,
6657
                      info, force_open)
6658

    
6659
  if not force_create:
6660
    return
6661

    
6662
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6663

    
6664

    
6665
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6666
  """Create a single block device on a given node.
6667

6668
  This will not recurse over children of the device, so they must be
6669
  created in advance.
6670

6671
  @param lu: the lu on whose behalf we execute
6672
  @param node: the node on which to create the device
6673
  @type instance: L{objects.Instance}
6674
  @param instance: the instance which owns the device
6675
  @type device: L{objects.Disk}
6676
  @param device: the device to create
6677
  @param info: the extra 'metadata' we should attach to the device
6678
      (this will be represented as a LVM tag)
6679
  @type force_open: boolean
6680
  @param force_open: this parameter will be passes to the
6681
      L{backend.BlockdevCreate} function where it specifies
6682
      whether we run on primary or not, and it affects both
6683
      the child assembly and the device own Open() execution
6684

6685
  """
6686
  lu.cfg.SetDiskID(device, node)
6687
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6688
                                       instance.name, force_open, info)
6689
  result.Raise("Can't create block device %s on"
6690
               " node %s for instance %s" % (device, node, instance.name))
6691
  if device.physical_id is None:
6692
    device.physical_id = result.payload
6693

    
6694

    
6695
def _GenerateUniqueNames(lu, exts):
6696
  """Generate a suitable LV name.
6697

6698
  This will generate a logical volume name for the given instance.
6699

6700
  """
6701
  results = []
6702
  for val in exts:
6703
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6704
    results.append("%s%s" % (new_id, val))
6705
  return results
6706

    
6707

    
6708
def _GenerateDRBD8Branch(lu, primary, secondary, size, vgname, names, iv_name,
6709
                         p_minor, s_minor):
6710
  """Generate a drbd8 device complete with its children.
6711

6712
  """
6713
  port = lu.cfg.AllocatePort()
6714
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6715
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6716
                          logical_id=(vgname, names[0]))
6717
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6718
                          logical_id=(vgname, names[1]))
6719
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6720
                          logical_id=(primary, secondary, port,
6721
                                      p_minor, s_minor,
6722
                                      shared_secret),
6723
                          children=[dev_data, dev_meta],
6724
                          iv_name=iv_name)
6725
  return drbd_dev
6726

    
6727

    
6728
def _GenerateDiskTemplate(lu, template_name,
6729
                          instance_name, primary_node,
6730
                          secondary_nodes, disk_info,
6731
                          file_storage_dir, file_driver,
6732
                          base_index, feedback_fn):
6733
  """Generate the entire disk layout for a given template type.
6734

6735
  """
6736
  #TODO: compute space requirements
6737

    
6738
  vgname = lu.cfg.GetVGName()
6739
  disk_count = len(disk_info)
6740
  disks = []
6741
  if template_name == constants.DT_DISKLESS:
6742
    pass
6743
  elif template_name == constants.DT_PLAIN:
6744
    if len(secondary_nodes) != 0:
6745
      raise errors.ProgrammerError("Wrong template configuration")
6746

    
6747
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6748
                                      for i in range(disk_count)])
6749
    for idx, disk in enumerate(disk_info):
6750
      disk_index = idx + base_index
6751
      vg = disk.get("vg", vgname)
6752
      feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
6753
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6754
                              logical_id=(vg, names[idx]),
6755
                              iv_name="disk/%d" % disk_index,
6756
                              mode=disk["mode"])
6757
      disks.append(disk_dev)
6758
  elif template_name == constants.DT_DRBD8:
6759
    if len(secondary_nodes) != 1:
6760
      raise errors.ProgrammerError("Wrong template configuration")
6761
    remote_node = secondary_nodes[0]
6762
    minors = lu.cfg.AllocateDRBDMinor(
6763
      [primary_node, remote_node] * len(disk_info), instance_name)
6764

    
6765
    names = []
6766
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6767
                                               for i in range(disk_count)]):
6768
      names.append(lv_prefix + "_data")
6769
      names.append(lv_prefix + "_meta")
6770
    for idx, disk in enumerate(disk_info):
6771
      disk_index = idx + base_index
6772
      vg = disk.get("vg", vgname)
6773
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6774
                                      disk["size"], vg, names[idx*2:idx*2+2],
6775
                                      "disk/%d" % disk_index,
6776
                                      minors[idx*2], minors[idx*2+1])
6777
      disk_dev.mode = disk["mode"]
6778
      disks.append(disk_dev)
6779
  elif template_name == constants.DT_FILE:
6780
    if len(secondary_nodes) != 0:
6781
      raise errors.ProgrammerError("Wrong template configuration")
6782

    
6783
    opcodes.RequireFileStorage()
6784

    
6785
    for idx, disk in enumerate(disk_info):
6786
      disk_index = idx + base_index
6787
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6788
                              iv_name="disk/%d" % disk_index,
6789
                              logical_id=(file_driver,
6790
                                          "%s/disk%d" % (file_storage_dir,
6791
                                                         disk_index)),
6792
                              mode=disk["mode"])
6793
      disks.append(disk_dev)
6794
  elif template_name == constants.DT_SHARED_FILE:
6795
    if len(secondary_nodes) != 0:
6796
      raise errors.ProgrammerError("Wrong template configuration")
6797

    
6798
    opcodes.RequireSharedFileStorage()
6799

    
6800
    for idx, disk in enumerate(disk_info):
6801
      disk_index = idx + base_index
6802
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6803
                              iv_name="disk/%d" % disk_index,
6804
                              logical_id=(file_driver,
6805
                                          "%s/disk%d" % (file_storage_dir,
6806
                                                         disk_index)),
6807
                              mode=disk["mode"])
6808
      disks.append(disk_dev)
6809
  elif template_name == constants.DT_BLOCK:
6810
    if len(secondary_nodes) != 0:
6811
      raise errors.ProgrammerError("Wrong template configuration")
6812

    
6813
    for idx, disk in enumerate(disk_info):
6814
      disk_index = idx + base_index
6815
      disk_dev = objects.Disk(dev_type=constants.LD_BLOCKDEV, size=disk["size"],
6816
                              logical_id=(constants.BLOCKDEV_DRIVER_MANUAL,
6817
                                          disk["adopt"]),
6818
                              iv_name="disk/%d" % disk_index,
6819
                              mode=disk["mode"])
6820
      disks.append(disk_dev)
6821

    
6822
  else:
6823
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6824
  return disks
6825

    
6826

    
6827
def _GetInstanceInfoText(instance):
6828
  """Compute that text that should be added to the disk's metadata.
6829

6830
  """
6831
  return "originstname+%s" % instance.name
6832

    
6833

    
6834
def _CalcEta(time_taken, written, total_size):
6835
  """Calculates the ETA based on size written and total size.
6836

6837
  @param time_taken: The time taken so far
6838
  @param written: amount written so far
6839
  @param total_size: The total size of data to be written
6840
  @return: The remaining time in seconds
6841

6842
  """
6843
  avg_time = time_taken / float(written)
6844
  return (total_size - written) * avg_time
6845

    
6846

    
6847
def _WipeDisks(lu, instance):
6848
  """Wipes instance disks.
6849

6850
  @type lu: L{LogicalUnit}
6851
  @param lu: the logical unit on whose behalf we execute
6852
  @type instance: L{objects.Instance}
6853
  @param instance: the instance whose disks we should create
6854
  @return: the success of the wipe
6855

6856
  """
6857
  node = instance.primary_node
6858

    
6859
  for device in instance.disks:
6860
    lu.cfg.SetDiskID(device, node)
6861

    
6862
  logging.info("Pause sync of instance %s disks", instance.name)
6863
  result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, True)
6864

    
6865
  for idx, success in enumerate(result.payload):
6866
    if not success:
6867
      logging.warn("pause-sync of instance %s for disks %d failed",
6868
                   instance.name, idx)
6869

    
6870
  try:
6871
    for idx, device in enumerate(instance.disks):
6872
      lu.LogInfo("* Wiping disk %d", idx)
6873
      logging.info("Wiping disk %d for instance %s, node %s",
6874
                   idx, instance.name, node)
6875

    
6876
      # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
6877
      # MAX_WIPE_CHUNK at max
6878
      wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
6879
                            constants.MIN_WIPE_CHUNK_PERCENT)
6880

    
6881
      offset = 0
6882
      size = device.size
6883
      last_output = 0
6884
      start_time = time.time()
6885

    
6886
      while offset < size:
6887
        wipe_size = min(wipe_chunk_size, size - offset)
6888
        result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
6889
        result.Raise("Could not wipe disk %d at offset %d for size %d" %
6890
                     (idx, offset, wipe_size))
6891
        now = time.time()
6892
        offset += wipe_size
6893
        if now - last_output >= 60:
6894
          eta = _CalcEta(now - start_time, offset, size)
6895
          lu.LogInfo(" - done: %.1f%% ETA: %s" %
6896
                     (offset / float(size) * 100, utils.FormatSeconds(eta)))
6897
          last_output = now
6898
  finally:
6899
    logging.info("Resume sync of instance %s disks", instance.name)
6900

    
6901
    result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, False)
6902

    
6903
    for idx, success in enumerate(result.payload):
6904
      if not success:
6905
        lu.LogWarning("Warning: Resume sync of disk %d failed. Please have a"
6906
                      " look at the status and troubleshoot the issue.", idx)
6907
        logging.warn("resume-sync of instance %s for disks %d failed",
6908
                     instance.name, idx)
6909

    
6910

    
6911
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6912
  """Create all disks for an instance.
6913

6914
  This abstracts away some work from AddInstance.
6915

6916
  @type lu: L{LogicalUnit}
6917
  @param lu: the logical unit on whose behalf we execute
6918
  @type instance: L{objects.Instance}
6919
  @param instance: the instance whose disks we should create
6920
  @type to_skip: list
6921
  @param to_skip: list of indices to skip
6922
  @type target_node: string
6923
  @param target_node: if passed, overrides the target node for creation
6924
  @rtype: boolean
6925
  @return: the success of the creation
6926

6927
  """
6928
  info = _GetInstanceInfoText(instance)
6929
  if target_node is None:
6930
    pnode = instance.primary_node
6931
    all_nodes = instance.all_nodes
6932
  else:
6933
    pnode = target_node
6934
    all_nodes = [pnode]
6935

    
6936
  if instance.disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE):
6937
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6938
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6939

    
6940
    result.Raise("Failed to create directory '%s' on"
6941
                 " node %s" % (file_storage_dir, pnode))
6942

    
6943
  # Note: this needs to be kept in sync with adding of disks in
6944
  # LUInstanceSetParams
6945
  for idx, device in enumerate(instance.disks):
6946
    if to_skip and idx in to_skip:
6947
      continue
6948
    logging.info("Creating volume %s for instance %s",
6949
                 device.iv_name, instance.name)
6950
    #HARDCODE
6951
    for node in all_nodes:
6952
      f_create = node == pnode
6953
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6954

    
6955

    
6956
def _RemoveDisks(lu, instance, target_node=None):
6957
  """Remove all disks for an instance.
6958

6959
  This abstracts away some work from `AddInstance()` and
6960
  `RemoveInstance()`. Note that in case some of the devices couldn't
6961
  be removed, the removal will continue with the other ones (compare
6962
  with `_CreateDisks()`).
6963

6964
  @type lu: L{LogicalUnit}
6965
  @param lu: the logical unit on whose behalf we execute
6966
  @type instance: L{objects.Instance}
6967
  @param instance: the instance whose disks we should remove
6968
  @type target_node: string
6969
  @param target_node: used to override the node on which to remove the disks
6970
  @rtype: boolean
6971
  @return: the success of the removal
6972

6973
  """
6974
  logging.info("Removing block devices for instance %s", instance.name)
6975

    
6976
  all_result = True
6977
  for device in instance.disks:
6978
    if target_node:
6979
      edata = [(target_node, device)]
6980
    else:
6981
      edata = device.ComputeNodeTree(instance.primary_node)
6982
    for node, disk in edata:
6983
      lu.cfg.SetDiskID(disk, node)
6984
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6985
      if msg:
6986
        lu.LogWarning("Could not remove block device %s on node %s,"
6987
                      " continuing anyway: %s", device.iv_name, node, msg)
6988
        all_result = False
6989

    
6990
  if instance.disk_template == constants.DT_FILE:
6991
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6992
    if target_node:
6993
      tgt = target_node
6994
    else:
6995
      tgt = instance.primary_node
6996
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6997
    if result.fail_msg:
6998
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6999
                    file_storage_dir, instance.primary_node, result.fail_msg)
7000
      all_result = False
7001

    
7002
  return all_result
7003

    
7004

    
7005
def _ComputeDiskSizePerVG(disk_template, disks):
7006
  """Compute disk size requirements in the volume group
7007

7008
  """
7009
  def _compute(disks, payload):
7010
    """Universal algorithm
7011

7012
    """
7013
    vgs = {}
7014
    for disk in disks:
7015
      vgs[disk["vg"]] = vgs.get("vg", 0) + disk["size"] + payload
7016

    
7017
    return vgs
7018

    
7019
  # Required free disk space as a function of disk and swap space
7020
  req_size_dict = {
7021
    constants.DT_DISKLESS: {},
7022
    constants.DT_PLAIN: _compute(disks, 0),
7023
    # 128 MB are added for drbd metadata for each disk
7024
    constants.DT_DRBD8: _compute(disks, 128),
7025
    constants.DT_FILE: {},
7026
    constants.DT_SHARED_FILE: {},
7027
  }
7028

    
7029
  if disk_template not in req_size_dict:
7030
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7031
                                 " is unknown" %  disk_template)
7032

    
7033
  return req_size_dict[disk_template]
7034

    
7035

    
7036
def _ComputeDiskSize(disk_template, disks):
7037
  """Compute disk size requirements in the volume group
7038

7039
  """
7040
  # Required free disk space as a function of disk and swap space
7041
  req_size_dict = {
7042
    constants.DT_DISKLESS: None,
7043
    constants.DT_PLAIN: sum(d["size"] for d in disks),
7044
    # 128 MB are added for drbd metadata for each disk
7045
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
7046
    constants.DT_FILE: None,
7047
    constants.DT_SHARED_FILE: 0,
7048
    constants.DT_BLOCK: 0,
7049
  }
7050

    
7051
  if disk_template not in req_size_dict:
7052
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7053
                                 " is unknown" %  disk_template)
7054

    
7055
  return req_size_dict[disk_template]
7056

    
7057

    
7058
def _FilterVmNodes(lu, nodenames):
7059
  """Filters out non-vm_capable nodes from a list.
7060

7061
  @type lu: L{LogicalUnit}
7062
  @param lu: the logical unit for which we check
7063
  @type nodenames: list
7064
  @param nodenames: the list of nodes on which we should check
7065
  @rtype: list
7066
  @return: the list of vm-capable nodes
7067

7068
  """
7069
  vm_nodes = frozenset(lu.cfg.GetNonVmCapableNodeList())
7070
  return [name for name in nodenames if name not in vm_nodes]
7071

    
7072

    
7073
def _CheckHVParams(lu, nodenames, hvname, hvparams):
7074
  """Hypervisor parameter validation.
7075

7076
  This function abstract the hypervisor parameter validation to be
7077
  used in both instance create and instance modify.
7078

7079
  @type lu: L{LogicalUnit}
7080
  @param lu: the logical unit for which we check
7081
  @type nodenames: list
7082
  @param nodenames: the list of nodes on which we should check
7083
  @type hvname: string
7084
  @param hvname: the name of the hypervisor we should use
7085
  @type hvparams: dict
7086
  @param hvparams: the parameters which we need to check
7087
  @raise errors.OpPrereqError: if the parameters are not valid
7088

7089
  """
7090
  nodenames = _FilterVmNodes(lu, nodenames)
7091
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
7092
                                                  hvname,
7093
                                                  hvparams)
7094
  for node in nodenames:
7095
    info = hvinfo[node]
7096
    if info.offline:
7097
      continue
7098
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
7099

    
7100

    
7101
def _CheckOSParams(lu, required, nodenames, osname, osparams):
7102
  """OS parameters validation.
7103

7104
  @type lu: L{LogicalUnit}
7105
  @param lu: the logical unit for which we check
7106
  @type required: boolean
7107
  @param required: whether the validation should fail if the OS is not
7108
      found
7109
  @type nodenames: list
7110
  @param nodenames: the list of nodes on which we should check
7111
  @type osname: string
7112
  @param osname: the name of the hypervisor we should use
7113
  @type osparams: dict
7114
  @param osparams: the parameters which we need to check
7115
  @raise errors.OpPrereqError: if the parameters are not valid
7116

7117
  """
7118
  nodenames = _FilterVmNodes(lu, nodenames)
7119
  result = lu.rpc.call_os_validate(required, nodenames, osname,
7120
                                   [constants.OS_VALIDATE_PARAMETERS],
7121
                                   osparams)
7122
  for node, nres in result.items():
7123
    # we don't check for offline cases since this should be run only
7124
    # against the master node and/or an instance's nodes
7125
    nres.Raise("OS Parameters validation failed on node %s" % node)
7126
    if not nres.payload:
7127
      lu.LogInfo("OS %s not found on node %s, validation skipped",
7128
                 osname, node)
7129

    
7130

    
7131
class LUInstanceCreate(LogicalUnit):
7132
  """Create an instance.
7133

7134
  """
7135
  HPATH = "instance-add"
7136
  HTYPE = constants.HTYPE_INSTANCE
7137
  REQ_BGL = False
7138

    
7139
  def CheckArguments(self):
7140
    """Check arguments.
7141

7142
    """
7143
    # do not require name_check to ease forward/backward compatibility
7144
    # for tools
7145
    if self.op.no_install and self.op.start:
7146
      self.LogInfo("No-installation mode selected, disabling startup")
7147
      self.op.start = False
7148
    # validate/normalize the instance name
7149
    self.op.instance_name = \
7150
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
7151

    
7152
    if self.op.ip_check and not self.op.name_check:
7153
      # TODO: make the ip check more flexible and not depend on the name check
7154
      raise errors.OpPrereqError("Cannot do ip check without a name check",
7155
                                 errors.ECODE_INVAL)
7156

    
7157
    # check nics' parameter names
7158
    for nic in self.op.nics:
7159
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
7160

    
7161
    # check disks. parameter names and consistent adopt/no-adopt strategy
7162
    has_adopt = has_no_adopt = False
7163
    for disk in self.op.disks:
7164
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
7165
      if "adopt" in disk:
7166
        has_adopt = True
7167
      else:
7168
        has_no_adopt = True
7169
    if has_adopt and has_no_adopt:
7170
      raise errors.OpPrereqError("Either all disks are adopted or none is",
7171
                                 errors.ECODE_INVAL)
7172
    if has_adopt:
7173
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
7174
        raise errors.OpPrereqError("Disk adoption is not supported for the"
7175
                                   " '%s' disk template" %
7176
                                   self.op.disk_template,
7177
                                   errors.ECODE_INVAL)
7178
      if self.op.iallocator is not None:
7179
        raise errors.OpPrereqError("Disk adoption not allowed with an"
7180
                                   " iallocator script", errors.ECODE_INVAL)
7181
      if self.op.mode == constants.INSTANCE_IMPORT:
7182
        raise errors.OpPrereqError("Disk adoption not allowed for"
7183
                                   " instance import", errors.ECODE_INVAL)
7184
    else:
7185
      if self.op.disk_template in constants.DTS_MUST_ADOPT:
7186
        raise errors.OpPrereqError("Disk template %s requires disk adoption,"
7187
                                   " but no 'adopt' parameter given" %
7188
                                   self.op.disk_template,
7189
                                   errors.ECODE_INVAL)
7190

    
7191
    self.adopt_disks = has_adopt
7192

    
7193
    # instance name verification
7194
    if self.op.name_check:
7195
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
7196
      self.op.instance_name = self.hostname1.name
7197
      # used in CheckPrereq for ip ping check
7198
      self.check_ip = self.hostname1.ip
7199
    else:
7200
      self.check_ip = None
7201

    
7202
    # file storage checks
7203
    if (self.op.file_driver and
7204
        not self.op.file_driver in constants.FILE_DRIVER):
7205
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
7206
                                 self.op.file_driver, errors.ECODE_INVAL)
7207

    
7208
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
7209
      raise errors.OpPrereqError("File storage directory path not absolute",
7210
                                 errors.ECODE_INVAL)
7211

    
7212
    ### Node/iallocator related checks
7213
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
7214

    
7215
    if self.op.pnode is not None:
7216
      if self.op.disk_template in constants.DTS_INT_MIRROR:
7217
        if self.op.snode is None:
7218
          raise errors.OpPrereqError("The networked disk templates need"
7219
                                     " a mirror node", errors.ECODE_INVAL)
7220
      elif self.op.snode:
7221
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
7222
                        " template")
7223
        self.op.snode = None
7224

    
7225
    self._cds = _GetClusterDomainSecret()
7226

    
7227
    if self.op.mode == constants.INSTANCE_IMPORT:
7228
      # On import force_variant must be True, because if we forced it at
7229
      # initial install, our only chance when importing it back is that it
7230
      # works again!
7231
      self.op.force_variant = True
7232

    
7233
      if self.op.no_install:
7234
        self.LogInfo("No-installation mode has no effect during import")
7235

    
7236
    elif self.op.mode == constants.INSTANCE_CREATE:
7237
      if self.op.os_type is None:
7238
        raise errors.OpPrereqError("No guest OS specified",
7239
                                   errors.ECODE_INVAL)
7240
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
7241
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
7242
                                   " installation" % self.op.os_type,
7243
                                   errors.ECODE_STATE)
7244
      if self.op.disk_template is None:
7245
        raise errors.OpPrereqError("No disk template specified",
7246
                                   errors.ECODE_INVAL)
7247

    
7248
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7249
      # Check handshake to ensure both clusters have the same domain secret
7250
      src_handshake = self.op.source_handshake
7251
      if not src_handshake:
7252
        raise errors.OpPrereqError("Missing source handshake",
7253
                                   errors.ECODE_INVAL)
7254

    
7255
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
7256
                                                           src_handshake)
7257
      if errmsg:
7258
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
7259
                                   errors.ECODE_INVAL)
7260

    
7261
      # Load and check source CA
7262
      self.source_x509_ca_pem = self.op.source_x509_ca
7263
      if not self.source_x509_ca_pem:
7264
        raise errors.OpPrereqError("Missing source X509 CA",
7265
                                   errors.ECODE_INVAL)
7266

    
7267
      try:
7268
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
7269
                                                    self._cds)
7270
      except OpenSSL.crypto.Error, err:
7271
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
7272
                                   (err, ), errors.ECODE_INVAL)
7273

    
7274
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
7275
      if errcode is not None:
7276
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
7277
                                   errors.ECODE_INVAL)
7278

    
7279
      self.source_x509_ca = cert
7280

    
7281
      src_instance_name = self.op.source_instance_name
7282
      if not src_instance_name:
7283
        raise errors.OpPrereqError("Missing source instance name",
7284
                                   errors.ECODE_INVAL)
7285

    
7286
      self.source_instance_name = \
7287
          netutils.GetHostname(name=src_instance_name).name
7288

    
7289
    else:
7290
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
7291
                                 self.op.mode, errors.ECODE_INVAL)
7292

    
7293
  def ExpandNames(self):
7294
    """ExpandNames for CreateInstance.
7295

7296
    Figure out the right locks for instance creation.
7297

7298
    """
7299
    self.needed_locks = {}
7300

    
7301
    instance_name = self.op.instance_name
7302
    # this is just a preventive check, but someone might still add this
7303
    # instance in the meantime, and creation will fail at lock-add time
7304
    if instance_name in self.cfg.GetInstanceList():
7305
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
7306
                                 instance_name, errors.ECODE_EXISTS)
7307

    
7308
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
7309

    
7310
    if self.op.iallocator:
7311
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7312
    else:
7313
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
7314
      nodelist = [self.op.pnode]
7315
      if self.op.snode is not None:
7316
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
7317
        nodelist.append(self.op.snode)
7318
      self.needed_locks[locking.LEVEL_NODE] = nodelist
7319

    
7320
    # in case of import lock the source node too
7321
    if self.op.mode == constants.INSTANCE_IMPORT:
7322
      src_node = self.op.src_node
7323
      src_path = self.op.src_path
7324

    
7325
      if src_path is None:
7326
        self.op.src_path = src_path = self.op.instance_name
7327

    
7328
      if src_node is None:
7329
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7330
        self.op.src_node = None
7331
        if os.path.isabs(src_path):
7332
          raise errors.OpPrereqError("Importing an instance from an absolute"
7333
                                     " path requires a source node option.",
7334
                                     errors.ECODE_INVAL)
7335
      else:
7336
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
7337
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
7338
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
7339
        if not os.path.isabs(src_path):
7340
          self.op.src_path = src_path = \
7341
            utils.PathJoin(constants.EXPORT_DIR, src_path)
7342

    
7343
  def _RunAllocator(self):
7344
    """Run the allocator based on input opcode.
7345

7346
    """
7347
    nics = [n.ToDict() for n in self.nics]
7348
    ial = IAllocator(self.cfg, self.rpc,
7349
                     mode=constants.IALLOCATOR_MODE_ALLOC,
7350
                     name=self.op.instance_name,
7351
                     disk_template=self.op.disk_template,
7352
                     tags=[],
7353
                     os=self.op.os_type,
7354
                     vcpus=self.be_full[constants.BE_VCPUS],
7355
                     mem_size=self.be_full[constants.BE_MEMORY],
7356
                     disks=self.disks,
7357
                     nics=nics,
7358
                     hypervisor=self.op.hypervisor,
7359
                     )
7360

    
7361
    ial.Run(self.op.iallocator)
7362

    
7363
    if not ial.success:
7364
      raise errors.OpPrereqError("Can't compute nodes using"
7365
                                 " iallocator '%s': %s" %
7366
                                 (self.op.iallocator, ial.info),
7367
                                 errors.ECODE_NORES)
7368
    if len(ial.result) != ial.required_nodes:
7369
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7370
                                 " of nodes (%s), required %s" %
7371
                                 (self.op.iallocator, len(ial.result),
7372
                                  ial.required_nodes), errors.ECODE_FAULT)
7373
    self.op.pnode = ial.result[0]
7374
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
7375
                 self.op.instance_name, self.op.iallocator,
7376
                 utils.CommaJoin(ial.result))
7377
    if ial.required_nodes == 2:
7378
      self.op.snode = ial.result[1]
7379

    
7380
  def BuildHooksEnv(self):
7381
    """Build hooks env.
7382

7383
    This runs on master, primary and secondary nodes of the instance.
7384

7385
    """
7386
    env = {
7387
      "ADD_MODE": self.op.mode,
7388
      }
7389
    if self.op.mode == constants.INSTANCE_IMPORT:
7390
      env["SRC_NODE"] = self.op.src_node
7391
      env["SRC_PATH"] = self.op.src_path
7392
      env["SRC_IMAGES"] = self.src_images
7393

    
7394
    env.update(_BuildInstanceHookEnv(
7395
      name=self.op.instance_name,
7396
      primary_node=self.op.pnode,
7397
      secondary_nodes=self.secondaries,
7398
      status=self.op.start,
7399
      os_type=self.op.os_type,
7400
      memory=self.be_full[constants.BE_MEMORY],
7401
      vcpus=self.be_full[constants.BE_VCPUS],
7402
      nics=_NICListToTuple(self, self.nics),
7403
      disk_template=self.op.disk_template,
7404
      disks=[(d["size"], d["mode"]) for d in self.disks],
7405
      bep=self.be_full,
7406
      hvp=self.hv_full,
7407
      hypervisor_name=self.op.hypervisor,
7408
    ))
7409

    
7410
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
7411
          self.secondaries)
7412
    return env, nl, nl
7413

    
7414
  def _ReadExportInfo(self):
7415
    """Reads the export information from disk.
7416

7417
    It will override the opcode source node and path with the actual
7418
    information, if these two were not specified before.
7419

7420
    @return: the export information
7421

7422
    """
7423
    assert self.op.mode == constants.INSTANCE_IMPORT
7424

    
7425
    src_node = self.op.src_node
7426
    src_path = self.op.src_path
7427

    
7428
    if src_node is None:
7429
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
7430
      exp_list = self.rpc.call_export_list(locked_nodes)
7431
      found = False
7432
      for node in exp_list:
7433
        if exp_list[node].fail_msg:
7434
          continue
7435
        if src_path in exp_list[node].payload:
7436
          found = True
7437
          self.op.src_node = src_node = node
7438
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
7439
                                                       src_path)
7440
          break
7441
      if not found:
7442
        raise errors.OpPrereqError("No export found for relative path %s" %
7443
                                    src_path, errors.ECODE_INVAL)
7444

    
7445
    _CheckNodeOnline(self, src_node)
7446
    result = self.rpc.call_export_info(src_node, src_path)
7447
    result.Raise("No export or invalid export found in dir %s" % src_path)
7448

    
7449
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
7450
    if not export_info.has_section(constants.INISECT_EXP):
7451
      raise errors.ProgrammerError("Corrupted export config",
7452
                                   errors.ECODE_ENVIRON)
7453

    
7454
    ei_version = export_info.get(constants.INISECT_EXP, "version")
7455
    if (int(ei_version) != constants.EXPORT_VERSION):
7456
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
7457
                                 (ei_version, constants.EXPORT_VERSION),
7458
                                 errors.ECODE_ENVIRON)
7459
    return export_info
7460

    
7461
  def _ReadExportParams(self, einfo):
7462
    """Use export parameters as defaults.
7463

7464
    In case the opcode doesn't specify (as in override) some instance
7465
    parameters, then try to use them from the export information, if
7466
    that declares them.
7467

7468
    """
7469
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
7470

    
7471
    if self.op.disk_template is None:
7472
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
7473
        self.op.disk_template = einfo.get(constants.INISECT_INS,
7474
                                          "disk_template")
7475
      else:
7476
        raise errors.OpPrereqError("No disk template specified and the export"
7477
                                   " is missing the disk_template information",
7478
                                   errors.ECODE_INVAL)
7479

    
7480
    if not self.op.disks:
7481
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
7482
        disks = []
7483
        # TODO: import the disk iv_name too
7484
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
7485
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
7486
          disks.append({"size": disk_sz})
7487
        self.op.disks = disks
7488
      else:
7489
        raise errors.OpPrereqError("No disk info specified and the export"
7490
                                   " is missing the disk information",
7491
                                   errors.ECODE_INVAL)
7492

    
7493
    if (not self.op.nics and
7494
        einfo.has_option(constants.INISECT_INS, "nic_count")):
7495
      nics = []
7496
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
7497
        ndict = {}
7498
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
7499
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
7500
          ndict[name] = v
7501
        nics.append(ndict)
7502
      self.op.nics = nics
7503

    
7504
    if (self.op.hypervisor is None and
7505
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
7506
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
7507
    if einfo.has_section(constants.INISECT_HYP):
7508
      # use the export parameters but do not override the ones
7509
      # specified by the user
7510
      for name, value in einfo.items(constants.INISECT_HYP):
7511
        if name not in self.op.hvparams:
7512
          self.op.hvparams[name] = value
7513

    
7514
    if einfo.has_section(constants.INISECT_BEP):
7515
      # use the parameters, without overriding
7516
      for name, value in einfo.items(constants.INISECT_BEP):
7517
        if name not in self.op.beparams:
7518
          self.op.beparams[name] = value
7519
    else:
7520
      # try to read the parameters old style, from the main section
7521
      for name in constants.BES_PARAMETERS:
7522
        if (name not in self.op.beparams and
7523
            einfo.has_option(constants.INISECT_INS, name)):
7524
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
7525

    
7526
    if einfo.has_section(constants.INISECT_OSP):
7527
      # use the parameters, without overriding
7528
      for name, value in einfo.items(constants.INISECT_OSP):
7529
        if name not in self.op.osparams:
7530
          self.op.osparams[name] = value
7531

    
7532
  def _RevertToDefaults(self, cluster):
7533
    """Revert the instance parameters to the default values.
7534

7535
    """
7536
    # hvparams
7537
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
7538
    for name in self.op.hvparams.keys():
7539
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
7540
        del self.op.hvparams[name]
7541
    # beparams
7542
    be_defs = cluster.SimpleFillBE({})
7543
    for name in self.op.beparams.keys():
7544
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
7545
        del self.op.beparams[name]
7546
    # nic params
7547
    nic_defs = cluster.SimpleFillNIC({})
7548
    for nic in self.op.nics:
7549
      for name in constants.NICS_PARAMETERS:
7550
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
7551
          del nic[name]
7552
    # osparams
7553
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
7554
    for name in self.op.osparams.keys():
7555
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
7556
        del self.op.osparams[name]
7557

    
7558
  def CheckPrereq(self):
7559
    """Check prerequisites.
7560

7561
    """
7562
    if self.op.mode == constants.INSTANCE_IMPORT:
7563
      export_info = self._ReadExportInfo()
7564
      self._ReadExportParams(export_info)
7565

    
7566
    if (not self.cfg.GetVGName() and
7567
        self.op.disk_template not in constants.DTS_NOT_LVM):
7568
      raise errors.OpPrereqError("Cluster does not support lvm-based"
7569
                                 " instances", errors.ECODE_STATE)
7570

    
7571
    if self.op.hypervisor is None:
7572
      self.op.hypervisor = self.cfg.GetHypervisorType()
7573

    
7574
    cluster = self.cfg.GetClusterInfo()
7575
    enabled_hvs = cluster.enabled_hypervisors
7576
    if self.op.hypervisor not in enabled_hvs:
7577
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
7578
                                 " cluster (%s)" % (self.op.hypervisor,
7579
                                  ",".join(enabled_hvs)),
7580
                                 errors.ECODE_STATE)
7581

    
7582
    # check hypervisor parameter syntax (locally)
7583
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
7584
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
7585
                                      self.op.hvparams)
7586
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
7587
    hv_type.CheckParameterSyntax(filled_hvp)
7588
    self.hv_full = filled_hvp
7589
    # check that we don't specify global parameters on an instance
7590
    _CheckGlobalHvParams(self.op.hvparams)
7591

    
7592
    # fill and remember the beparams dict
7593
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
7594
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
7595

    
7596
    # build os parameters
7597
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
7598

    
7599
    # now that hvp/bep are in final format, let's reset to defaults,
7600
    # if told to do so
7601
    if self.op.identify_defaults:
7602
      self._RevertToDefaults(cluster)
7603

    
7604
    # NIC buildup
7605
    self.nics = []
7606
    for idx, nic in enumerate(self.op.nics):
7607
      nic_mode_req = nic.get("mode", None)
7608
      nic_mode = nic_mode_req
7609
      if nic_mode is None:
7610
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
7611

    
7612
      # in routed mode, for the first nic, the default ip is 'auto'
7613
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
7614
        default_ip_mode = constants.VALUE_AUTO
7615
      else:
7616
        default_ip_mode = constants.VALUE_NONE
7617

    
7618
      # ip validity checks
7619
      ip = nic.get("ip", default_ip_mode)
7620
      if ip is None or ip.lower() == constants.VALUE_NONE:
7621
        nic_ip = None
7622
      elif ip.lower() == constants.VALUE_AUTO:
7623
        if not self.op.name_check:
7624
          raise errors.OpPrereqError("IP address set to auto but name checks"
7625
                                     " have been skipped",
7626
                                     errors.ECODE_INVAL)
7627
        nic_ip = self.hostname1.ip
7628
      else:
7629
        if not netutils.IPAddress.IsValid(ip):
7630
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
7631
                                     errors.ECODE_INVAL)
7632
        nic_ip = ip
7633

    
7634
      # TODO: check the ip address for uniqueness
7635
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7636
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7637
                                   errors.ECODE_INVAL)
7638

    
7639
      # MAC address verification
7640
      mac = nic.get("mac", constants.VALUE_AUTO)
7641
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7642
        mac = utils.NormalizeAndValidateMac(mac)
7643

    
7644
        try:
7645
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7646
        except errors.ReservationError:
7647
          raise errors.OpPrereqError("MAC address %s already in use"
7648
                                     " in cluster" % mac,
7649
                                     errors.ECODE_NOTUNIQUE)
7650

    
7651
      # bridge verification
7652
      bridge = nic.get("bridge", None)
7653
      link = nic.get("link", None)
7654
      if bridge and link:
7655
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7656
                                   " at the same time", errors.ECODE_INVAL)
7657
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7658
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7659
                                   errors.ECODE_INVAL)
7660
      elif bridge:
7661
        link = bridge
7662

    
7663
      nicparams = {}
7664
      if nic_mode_req:
7665
        nicparams[constants.NIC_MODE] = nic_mode_req
7666
      if link:
7667
        nicparams[constants.NIC_LINK] = link
7668

    
7669
      check_params = cluster.SimpleFillNIC(nicparams)
7670
      objects.NIC.CheckParameterSyntax(check_params)
7671
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7672

    
7673
    # disk checks/pre-build
7674
    self.disks = []
7675
    for disk in self.op.disks:
7676
      mode = disk.get("mode", constants.DISK_RDWR)
7677
      if mode not in constants.DISK_ACCESS_SET:
7678
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7679
                                   mode, errors.ECODE_INVAL)
7680
      size = disk.get("size", None)
7681
      if size is None:
7682
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7683
      try:
7684
        size = int(size)
7685
      except (TypeError, ValueError):
7686
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7687
                                   errors.ECODE_INVAL)
7688
      vg = disk.get("vg", self.cfg.GetVGName())
7689
      new_disk = {"size": size, "mode": mode, "vg": vg}
7690
      if "adopt" in disk:
7691
        new_disk["adopt"] = disk["adopt"]
7692
      self.disks.append(new_disk)
7693

    
7694
    if self.op.mode == constants.INSTANCE_IMPORT:
7695

    
7696
      # Check that the new instance doesn't have less disks than the export
7697
      instance_disks = len(self.disks)
7698
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7699
      if instance_disks < export_disks:
7700
        raise errors.OpPrereqError("Not enough disks to import."
7701
                                   " (instance: %d, export: %d)" %
7702
                                   (instance_disks, export_disks),
7703
                                   errors.ECODE_INVAL)
7704

    
7705
      disk_images = []
7706
      for idx in range(export_disks):
7707
        option = 'disk%d_dump' % idx
7708
        if export_info.has_option(constants.INISECT_INS, option):
7709
          # FIXME: are the old os-es, disk sizes, etc. useful?
7710
          export_name = export_info.get(constants.INISECT_INS, option)
7711
          image = utils.PathJoin(self.op.src_path, export_name)
7712
          disk_images.append(image)
7713
        else:
7714
          disk_images.append(False)
7715

    
7716
      self.src_images = disk_images
7717

    
7718
      old_name = export_info.get(constants.INISECT_INS, 'name')
7719
      try:
7720
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7721
      except (TypeError, ValueError), err:
7722
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7723
                                   " an integer: %s" % str(err),
7724
                                   errors.ECODE_STATE)
7725
      if self.op.instance_name == old_name:
7726
        for idx, nic in enumerate(self.nics):
7727
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7728
            nic_mac_ini = 'nic%d_mac' % idx
7729
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7730

    
7731
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7732

    
7733
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7734
    if self.op.ip_check:
7735
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7736
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7737
                                   (self.check_ip, self.op.instance_name),
7738
                                   errors.ECODE_NOTUNIQUE)
7739

    
7740
    #### mac address generation
7741
    # By generating here the mac address both the allocator and the hooks get
7742
    # the real final mac address rather than the 'auto' or 'generate' value.
7743
    # There is a race condition between the generation and the instance object
7744
    # creation, which means that we know the mac is valid now, but we're not
7745
    # sure it will be when we actually add the instance. If things go bad
7746
    # adding the instance will abort because of a duplicate mac, and the
7747
    # creation job will fail.
7748
    for nic in self.nics:
7749
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7750
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7751

    
7752
    #### allocator run
7753

    
7754
    if self.op.iallocator is not None:
7755
      self._RunAllocator()
7756

    
7757
    #### node related checks
7758

    
7759
    # check primary node
7760
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7761
    assert self.pnode is not None, \
7762
      "Cannot retrieve locked node %s" % self.op.pnode
7763
    if pnode.offline:
7764
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7765
                                 pnode.name, errors.ECODE_STATE)
7766
    if pnode.drained:
7767
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7768
                                 pnode.name, errors.ECODE_STATE)
7769
    if not pnode.vm_capable:
7770
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
7771
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
7772

    
7773
    self.secondaries = []
7774

    
7775
    # mirror node verification
7776
    if self.op.disk_template in constants.DTS_INT_MIRROR:
7777
      if self.op.snode == pnode.name:
7778
        raise errors.OpPrereqError("The secondary node cannot be the"
7779
                                   " primary node.", errors.ECODE_INVAL)
7780
      _CheckNodeOnline(self, self.op.snode)
7781
      _CheckNodeNotDrained(self, self.op.snode)
7782
      _CheckNodeVmCapable(self, self.op.snode)
7783
      self.secondaries.append(self.op.snode)
7784

    
7785
    nodenames = [pnode.name] + self.secondaries
7786

    
7787
    if not self.adopt_disks:
7788
      # Check lv size requirements, if not adopting
7789
      req_sizes = _ComputeDiskSizePerVG(self.op.disk_template, self.disks)
7790
      _CheckNodesFreeDiskPerVG(self, nodenames, req_sizes)
7791

    
7792
    elif self.op.disk_template == constants.DT_PLAIN: # Check the adoption data
7793
      all_lvs = set([i["vg"] + "/" + i["adopt"] for i in self.disks])
7794
      if len(all_lvs) != len(self.disks):
7795
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7796
                                   errors.ECODE_INVAL)
7797
      for lv_name in all_lvs:
7798
        try:
7799
          # FIXME: lv_name here is "vg/lv" need to ensure that other calls
7800
          # to ReserveLV uses the same syntax
7801
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7802
        except errors.ReservationError:
7803
          raise errors.OpPrereqError("LV named %s used by another instance" %
7804
                                     lv_name, errors.ECODE_NOTUNIQUE)
7805

    
7806
      vg_names = self.rpc.call_vg_list([pnode.name])[pnode.name]
7807
      vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
7808

    
7809
      node_lvs = self.rpc.call_lv_list([pnode.name],
7810
                                       vg_names.payload.keys())[pnode.name]
7811
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7812
      node_lvs = node_lvs.payload
7813

    
7814
      delta = all_lvs.difference(node_lvs.keys())
7815
      if delta:
7816
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7817
                                   utils.CommaJoin(delta),
7818
                                   errors.ECODE_INVAL)
7819
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7820
      if online_lvs:
7821
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7822
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7823
                                   errors.ECODE_STATE)
7824
      # update the size of disk based on what is found
7825
      for dsk in self.disks:
7826
        dsk["size"] = int(float(node_lvs[dsk["vg"] + "/" + dsk["adopt"]][0]))
7827

    
7828
    elif self.op.disk_template == constants.DT_BLOCK:
7829
      # Normalize and de-duplicate device paths
7830
      all_disks = set([os.path.abspath(i["adopt"]) for i in self.disks])
7831
      if len(all_disks) != len(self.disks):
7832
        raise errors.OpPrereqError("Duplicate disk names given for adoption",
7833
                                   errors.ECODE_INVAL)
7834
      baddisks = [d for d in all_disks
7835
                  if not d.startswith(constants.ADOPTABLE_BLOCKDEV_ROOT)]
7836
      if baddisks:
7837
        raise errors.OpPrereqError("Device node(s) %s lie outside %s and"
7838
                                   " cannot be adopted" %
7839
                                   (", ".join(baddisks),
7840
                                    constants.ADOPTABLE_BLOCKDEV_ROOT),
7841
                                   errors.ECODE_INVAL)
7842

    
7843
      node_disks = self.rpc.call_bdev_sizes([pnode.name],
7844
                                            list(all_disks))[pnode.name]
7845
      node_disks.Raise("Cannot get block device information from node %s" %
7846
                       pnode.name)
7847
      node_disks = node_disks.payload
7848
      delta = all_disks.difference(node_disks.keys())
7849
      if delta:
7850
        raise errors.OpPrereqError("Missing block device(s): %s" %
7851
                                   utils.CommaJoin(delta),
7852
                                   errors.ECODE_INVAL)
7853
      for dsk in self.disks:
7854
        dsk["size"] = int(float(node_disks[dsk["adopt"]]))
7855

    
7856
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7857

    
7858
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7859
    # check OS parameters (remotely)
7860
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7861

    
7862
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7863

    
7864
    # memory check on primary node
7865
    if self.op.start:
7866
      _CheckNodeFreeMemory(self, self.pnode.name,
7867
                           "creating instance %s" % self.op.instance_name,
7868
                           self.be_full[constants.BE_MEMORY],
7869
                           self.op.hypervisor)
7870

    
7871
    self.dry_run_result = list(nodenames)
7872

    
7873
  def Exec(self, feedback_fn):
7874
    """Create and add the instance to the cluster.
7875

7876
    """
7877
    instance = self.op.instance_name
7878
    pnode_name = self.pnode.name
7879

    
7880
    ht_kind = self.op.hypervisor
7881
    if ht_kind in constants.HTS_REQ_PORT:
7882
      network_port = self.cfg.AllocatePort()
7883
    else:
7884
      network_port = None
7885

    
7886
    if constants.ENABLE_FILE_STORAGE or constants.ENABLE_SHARED_FILE_STORAGE:
7887
      # this is needed because os.path.join does not accept None arguments
7888
      if self.op.file_storage_dir is None:
7889
        string_file_storage_dir = ""
7890
      else:
7891
        string_file_storage_dir = self.op.file_storage_dir
7892

    
7893
      # build the full file storage dir path
7894
      if self.op.disk_template == constants.DT_SHARED_FILE:
7895
        get_fsd_fn = self.cfg.GetSharedFileStorageDir
7896
      else:
7897
        get_fsd_fn = self.cfg.GetFileStorageDir
7898

    
7899
      file_storage_dir = utils.PathJoin(get_fsd_fn(),
7900
                                        string_file_storage_dir, instance)
7901
    else:
7902
      file_storage_dir = ""
7903

    
7904
    disks = _GenerateDiskTemplate(self,
7905
                                  self.op.disk_template,
7906
                                  instance, pnode_name,
7907
                                  self.secondaries,
7908
                                  self.disks,
7909
                                  file_storage_dir,
7910
                                  self.op.file_driver,
7911
                                  0,
7912
                                  feedback_fn)
7913

    
7914
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7915
                            primary_node=pnode_name,
7916
                            nics=self.nics, disks=disks,
7917
                            disk_template=self.op.disk_template,
7918
                            admin_up=False,
7919
                            network_port=network_port,
7920
                            beparams=self.op.beparams,
7921
                            hvparams=self.op.hvparams,
7922
                            hypervisor=self.op.hypervisor,
7923
                            osparams=self.op.osparams,
7924
                            )
7925

    
7926
    if self.adopt_disks:
7927
      if self.op.disk_template == constants.DT_PLAIN:
7928
        # rename LVs to the newly-generated names; we need to construct
7929
        # 'fake' LV disks with the old data, plus the new unique_id
7930
        tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7931
        rename_to = []
7932
        for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7933
          rename_to.append(t_dsk.logical_id)
7934
          t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7935
          self.cfg.SetDiskID(t_dsk, pnode_name)
7936
        result = self.rpc.call_blockdev_rename(pnode_name,
7937
                                               zip(tmp_disks, rename_to))
7938
        result.Raise("Failed to rename adoped LVs")
7939
    else:
7940
      feedback_fn("* creating instance disks...")
7941
      try:
7942
        _CreateDisks(self, iobj)
7943
      except errors.OpExecError:
7944
        self.LogWarning("Device creation failed, reverting...")
7945
        try:
7946
          _RemoveDisks(self, iobj)
7947
        finally:
7948
          self.cfg.ReleaseDRBDMinors(instance)
7949
          raise
7950

    
7951
      if self.cfg.GetClusterInfo().prealloc_wipe_disks:
7952
        feedback_fn("* wiping instance disks...")
7953
        try:
7954
          _WipeDisks(self, iobj)
7955
        except errors.OpExecError:
7956
          self.LogWarning("Device wiping failed, reverting...")
7957
          try:
7958
            _RemoveDisks(self, iobj)
7959
          finally:
7960
            self.cfg.ReleaseDRBDMinors(instance)
7961
            raise
7962

    
7963
    feedback_fn("adding instance %s to cluster config" % instance)
7964

    
7965
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7966

    
7967
    # Declare that we don't want to remove the instance lock anymore, as we've
7968
    # added the instance to the config
7969
    del self.remove_locks[locking.LEVEL_INSTANCE]
7970
    # Unlock all the nodes
7971
    if self.op.mode == constants.INSTANCE_IMPORT:
7972
      nodes_keep = [self.op.src_node]
7973
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7974
                       if node != self.op.src_node]
7975
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7976
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7977
    else:
7978
      self.context.glm.release(locking.LEVEL_NODE)
7979
      del self.acquired_locks[locking.LEVEL_NODE]
7980

    
7981
    if self.op.wait_for_sync:
7982
      disk_abort = not _WaitForSync(self, iobj)
7983
    elif iobj.disk_template in constants.DTS_INT_MIRROR:
7984
      # make sure the disks are not degraded (still sync-ing is ok)
7985
      time.sleep(15)
7986
      feedback_fn("* checking mirrors status")
7987
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7988
    else:
7989
      disk_abort = False
7990

    
7991
    if disk_abort:
7992
      _RemoveDisks(self, iobj)
7993
      self.cfg.RemoveInstance(iobj.name)
7994
      # Make sure the instance lock gets removed
7995
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7996
      raise errors.OpExecError("There are some degraded disks for"
7997
                               " this instance")
7998

    
7999
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
8000
      if self.op.mode == constants.INSTANCE_CREATE:
8001
        if not self.op.no_install:
8002
          feedback_fn("* running the instance OS create scripts...")
8003
          # FIXME: pass debug option from opcode to backend
8004
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
8005
                                                 self.op.debug_level)
8006
          result.Raise("Could not add os for instance %s"
8007
                       " on node %s" % (instance, pnode_name))
8008

    
8009
      elif self.op.mode == constants.INSTANCE_IMPORT:
8010
        feedback_fn("* running the instance OS import scripts...")
8011

    
8012
        transfers = []
8013

    
8014
        for idx, image in enumerate(self.src_images):
8015
          if not image:
8016
            continue
8017

    
8018
          # FIXME: pass debug option from opcode to backend
8019
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
8020
                                             constants.IEIO_FILE, (image, ),
8021
                                             constants.IEIO_SCRIPT,
8022
                                             (iobj.disks[idx], idx),
8023
                                             None)
8024
          transfers.append(dt)
8025

    
8026
        import_result = \
8027
          masterd.instance.TransferInstanceData(self, feedback_fn,
8028
                                                self.op.src_node, pnode_name,
8029
                                                self.pnode.secondary_ip,
8030
                                                iobj, transfers)
8031
        if not compat.all(import_result):
8032
          self.LogWarning("Some disks for instance %s on node %s were not"
8033
                          " imported successfully" % (instance, pnode_name))
8034

    
8035
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
8036
        feedback_fn("* preparing remote import...")
8037
        # The source cluster will stop the instance before attempting to make a
8038
        # connection. In some cases stopping an instance can take a long time,
8039
        # hence the shutdown timeout is added to the connection timeout.
8040
        connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
8041
                           self.op.source_shutdown_timeout)
8042
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
8043

    
8044
        assert iobj.primary_node == self.pnode.name
8045
        disk_results = \
8046
          masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
8047
                                        self.source_x509_ca,
8048
                                        self._cds, timeouts)
8049
        if not compat.all(disk_results):
8050
          # TODO: Should the instance still be started, even if some disks
8051
          # failed to import (valid for local imports, too)?
8052
          self.LogWarning("Some disks for instance %s on node %s were not"
8053
                          " imported successfully" % (instance, pnode_name))
8054

    
8055
        # Run rename script on newly imported instance
8056
        assert iobj.name == instance
8057
        feedback_fn("Running rename script for %s" % instance)
8058
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
8059
                                                   self.source_instance_name,
8060
                                                   self.op.debug_level)
8061
        if result.fail_msg:
8062
          self.LogWarning("Failed to run rename script for %s on node"
8063
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
8064

    
8065
      else:
8066
        # also checked in the prereq part
8067
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
8068
                                     % self.op.mode)
8069

    
8070
    if self.op.start:
8071
      iobj.admin_up = True
8072
      self.cfg.Update(iobj, feedback_fn)
8073
      logging.info("Starting instance %s on node %s", instance, pnode_name)
8074
      feedback_fn("* starting instance...")
8075
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
8076
      result.Raise("Could not start instance")
8077

    
8078
    return list(iobj.all_nodes)
8079

    
8080

    
8081
class LUInstanceConsole(NoHooksLU):
8082
  """Connect to an instance's console.
8083

8084
  This is somewhat special in that it returns the command line that
8085
  you need to run on the master node in order to connect to the
8086
  console.
8087

8088
  """
8089
  REQ_BGL = False
8090

    
8091
  def ExpandNames(self):
8092
    self._ExpandAndLockInstance()
8093

    
8094
  def CheckPrereq(self):
8095
    """Check prerequisites.
8096

8097
    This checks that the instance is in the cluster.
8098

8099
    """
8100
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8101
    assert self.instance is not None, \
8102
      "Cannot retrieve locked instance %s" % self.op.instance_name
8103
    _CheckNodeOnline(self, self.instance.primary_node)
8104

    
8105
  def Exec(self, feedback_fn):
8106
    """Connect to the console of an instance
8107

8108
    """
8109
    instance = self.instance
8110
    node = instance.primary_node
8111

    
8112
    node_insts = self.rpc.call_instance_list([node],
8113
                                             [instance.hypervisor])[node]
8114
    node_insts.Raise("Can't get node information from %s" % node)
8115

    
8116
    if instance.name not in node_insts.payload:
8117
      if instance.admin_up:
8118
        state = "ERROR_down"
8119
      else:
8120
        state = "ADMIN_down"
8121
      raise errors.OpExecError("Instance %s is not running (state %s)" %
8122
                               (instance.name, state))
8123

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

    
8126
    return _GetInstanceConsole(self.cfg.GetClusterInfo(), instance)
8127

    
8128

    
8129
def _GetInstanceConsole(cluster, instance):
8130
  """Returns console information for an instance.
8131

8132
  @type cluster: L{objects.Cluster}
8133
  @type instance: L{objects.Instance}
8134
  @rtype: dict
8135

8136
  """
8137
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
8138
  # beparams and hvparams are passed separately, to avoid editing the
8139
  # instance and then saving the defaults in the instance itself.
8140
  hvparams = cluster.FillHV(instance)
8141
  beparams = cluster.FillBE(instance)
8142
  console = hyper.GetInstanceConsole(instance, hvparams, beparams)
8143

    
8144
  assert console.instance == instance.name
8145
  assert console.Validate()
8146

    
8147
  return console.ToDict()
8148

    
8149

    
8150
class LUInstanceReplaceDisks(LogicalUnit):
8151
  """Replace the disks of an instance.
8152

8153
  """
8154
  HPATH = "mirrors-replace"
8155
  HTYPE = constants.HTYPE_INSTANCE
8156
  REQ_BGL = False
8157

    
8158
  def CheckArguments(self):
8159
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
8160
                                  self.op.iallocator)
8161

    
8162
  def ExpandNames(self):
8163
    self._ExpandAndLockInstance()
8164

    
8165
    if self.op.iallocator is not None:
8166
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8167

    
8168
    elif self.op.remote_node is not None:
8169
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8170
      self.op.remote_node = remote_node
8171

    
8172
      # Warning: do not remove the locking of the new secondary here
8173
      # unless DRBD8.AddChildren is changed to work in parallel;
8174
      # currently it doesn't since parallel invocations of
8175
      # FindUnusedMinor will conflict
8176
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
8177
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
8178

    
8179
    else:
8180
      self.needed_locks[locking.LEVEL_NODE] = []
8181
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8182

    
8183
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
8184
                                   self.op.iallocator, self.op.remote_node,
8185
                                   self.op.disks, False, self.op.early_release)
8186

    
8187
    self.tasklets = [self.replacer]
8188

    
8189
  def DeclareLocks(self, level):
8190
    # If we're not already locking all nodes in the set we have to declare the
8191
    # instance's primary/secondary nodes.
8192
    if (level == locking.LEVEL_NODE and
8193
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
8194
      self._LockInstancesNodes()
8195

    
8196
  def BuildHooksEnv(self):
8197
    """Build hooks env.
8198

8199
    This runs on the master, the primary and all the secondaries.
8200

8201
    """
8202
    instance = self.replacer.instance
8203
    env = {
8204
      "MODE": self.op.mode,
8205
      "NEW_SECONDARY": self.op.remote_node,
8206
      "OLD_SECONDARY": instance.secondary_nodes[0],
8207
      }
8208
    env.update(_BuildInstanceHookEnvByObject(self, instance))
8209
    nl = [
8210
      self.cfg.GetMasterNode(),
8211
      instance.primary_node,
8212
      ]
8213
    if self.op.remote_node is not None:
8214
      nl.append(self.op.remote_node)
8215
    return env, nl, nl
8216

    
8217

    
8218
class TLReplaceDisks(Tasklet):
8219
  """Replaces disks for an instance.
8220

8221
  Note: Locking is not within the scope of this class.
8222

8223
  """
8224
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
8225
               disks, delay_iallocator, early_release):
8226
    """Initializes this class.
8227

8228
    """
8229
    Tasklet.__init__(self, lu)
8230

    
8231
    # Parameters
8232
    self.instance_name = instance_name
8233
    self.mode = mode
8234
    self.iallocator_name = iallocator_name
8235
    self.remote_node = remote_node
8236
    self.disks = disks
8237
    self.delay_iallocator = delay_iallocator
8238
    self.early_release = early_release
8239

    
8240
    # Runtime data
8241
    self.instance = None
8242
    self.new_node = None
8243
    self.target_node = None
8244
    self.other_node = None
8245
    self.remote_node_info = None
8246
    self.node_secondary_ip = None
8247

    
8248
  @staticmethod
8249
  def CheckArguments(mode, remote_node, iallocator):
8250
    """Helper function for users of this class.
8251

8252
    """
8253
    # check for valid parameter combination
8254
    if mode == constants.REPLACE_DISK_CHG:
8255
      if remote_node is None and iallocator is None:
8256
        raise errors.OpPrereqError("When changing the secondary either an"
8257
                                   " iallocator script must be used or the"
8258
                                   " new node given", errors.ECODE_INVAL)
8259

    
8260
      if remote_node is not None and iallocator is not None:
8261
        raise errors.OpPrereqError("Give either the iallocator or the new"
8262
                                   " secondary, not both", errors.ECODE_INVAL)
8263

    
8264
    elif remote_node is not None or iallocator is not None:
8265
      # Not replacing the secondary
8266
      raise errors.OpPrereqError("The iallocator and new node options can"
8267
                                 " only be used when changing the"
8268
                                 " secondary node", errors.ECODE_INVAL)
8269

    
8270
  @staticmethod
8271
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
8272
    """Compute a new secondary node using an IAllocator.
8273

8274
    """
8275
    ial = IAllocator(lu.cfg, lu.rpc,
8276
                     mode=constants.IALLOCATOR_MODE_RELOC,
8277
                     name=instance_name,
8278
                     relocate_from=relocate_from)
8279

    
8280
    ial.Run(iallocator_name)
8281

    
8282
    if not ial.success:
8283
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
8284
                                 " %s" % (iallocator_name, ial.info),
8285
                                 errors.ECODE_NORES)
8286

    
8287
    if len(ial.result) != ial.required_nodes:
8288
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
8289
                                 " of nodes (%s), required %s" %
8290
                                 (iallocator_name,
8291
                                  len(ial.result), ial.required_nodes),
8292
                                 errors.ECODE_FAULT)
8293

    
8294
    remote_node_name = ial.result[0]
8295

    
8296
    lu.LogInfo("Selected new secondary for instance '%s': %s",
8297
               instance_name, remote_node_name)
8298

    
8299
    return remote_node_name
8300

    
8301
  def _FindFaultyDisks(self, node_name):
8302
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
8303
                                    node_name, True)
8304

    
8305
  def CheckPrereq(self):
8306
    """Check prerequisites.
8307

8308
    This checks that the instance is in the cluster.
8309

8310
    """
8311
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
8312
    assert instance is not None, \
8313
      "Cannot retrieve locked instance %s" % self.instance_name
8314

    
8315
    if instance.disk_template != constants.DT_DRBD8:
8316
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
8317
                                 " instances", errors.ECODE_INVAL)
8318

    
8319
    if len(instance.secondary_nodes) != 1:
8320
      raise errors.OpPrereqError("The instance has a strange layout,"
8321
                                 " expected one secondary but found %d" %
8322
                                 len(instance.secondary_nodes),
8323
                                 errors.ECODE_FAULT)
8324

    
8325
    if not self.delay_iallocator:
8326
      self._CheckPrereq2()
8327

    
8328
  def _CheckPrereq2(self):
8329
    """Check prerequisites, second part.
8330

8331
    This function should always be part of CheckPrereq. It was separated and is
8332
    now called from Exec because during node evacuation iallocator was only
8333
    called with an unmodified cluster model, not taking planned changes into
8334
    account.
8335

8336
    """
8337
    instance = self.instance
8338
    secondary_node = instance.secondary_nodes[0]
8339

    
8340
    if self.iallocator_name is None:
8341
      remote_node = self.remote_node
8342
    else:
8343
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
8344
                                       instance.name, instance.secondary_nodes)
8345

    
8346
    if remote_node is not None:
8347
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
8348
      assert self.remote_node_info is not None, \
8349
        "Cannot retrieve locked node %s" % remote_node
8350
    else:
8351
      self.remote_node_info = None
8352

    
8353
    if remote_node == self.instance.primary_node:
8354
      raise errors.OpPrereqError("The specified node is the primary node of"
8355
                                 " the instance.", errors.ECODE_INVAL)
8356

    
8357
    if remote_node == secondary_node:
8358
      raise errors.OpPrereqError("The specified node is already the"
8359
                                 " secondary node of the instance.",
8360
                                 errors.ECODE_INVAL)
8361

    
8362
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
8363
                                    constants.REPLACE_DISK_CHG):
8364
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
8365
                                 errors.ECODE_INVAL)
8366

    
8367
    if self.mode == constants.REPLACE_DISK_AUTO:
8368
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
8369
      faulty_secondary = self._FindFaultyDisks(secondary_node)
8370

    
8371
      if faulty_primary and faulty_secondary:
8372
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
8373
                                   " one node and can not be repaired"
8374
                                   " automatically" % self.instance_name,
8375
                                   errors.ECODE_STATE)
8376

    
8377
      if faulty_primary:
8378
        self.disks = faulty_primary
8379
        self.target_node = instance.primary_node
8380
        self.other_node = secondary_node
8381
        check_nodes = [self.target_node, self.other_node]
8382
      elif faulty_secondary:
8383
        self.disks = faulty_secondary
8384
        self.target_node = secondary_node
8385
        self.other_node = instance.primary_node
8386
        check_nodes = [self.target_node, self.other_node]
8387
      else:
8388
        self.disks = []
8389
        check_nodes = []
8390

    
8391
    else:
8392
      # Non-automatic modes
8393
      if self.mode == constants.REPLACE_DISK_PRI:
8394
        self.target_node = instance.primary_node
8395
        self.other_node = secondary_node
8396
        check_nodes = [self.target_node, self.other_node]
8397

    
8398
      elif self.mode == constants.REPLACE_DISK_SEC:
8399
        self.target_node = secondary_node
8400
        self.other_node = instance.primary_node
8401
        check_nodes = [self.target_node, self.other_node]
8402

    
8403
      elif self.mode == constants.REPLACE_DISK_CHG:
8404
        self.new_node = remote_node
8405
        self.other_node = instance.primary_node
8406
        self.target_node = secondary_node
8407
        check_nodes = [self.new_node, self.other_node]
8408

    
8409
        _CheckNodeNotDrained(self.lu, remote_node)
8410
        _CheckNodeVmCapable(self.lu, remote_node)
8411

    
8412
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
8413
        assert old_node_info is not None
8414
        if old_node_info.offline and not self.early_release:
8415
          # doesn't make sense to delay the release
8416
          self.early_release = True
8417
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
8418
                          " early-release mode", secondary_node)
8419

    
8420
      else:
8421
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
8422
                                     self.mode)
8423

    
8424
      # If not specified all disks should be replaced
8425
      if not self.disks:
8426
        self.disks = range(len(self.instance.disks))
8427

    
8428
    for node in check_nodes:
8429
      _CheckNodeOnline(self.lu, node)
8430

    
8431
    # Check whether disks are valid
8432
    for disk_idx in self.disks:
8433
      instance.FindDisk(disk_idx)
8434

    
8435
    # Get secondary node IP addresses
8436
    node_2nd_ip = {}
8437

    
8438
    for node_name in [self.target_node, self.other_node, self.new_node]:
8439
      if node_name is not None:
8440
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
8441

    
8442
    self.node_secondary_ip = node_2nd_ip
8443

    
8444
  def Exec(self, feedback_fn):
8445
    """Execute disk replacement.
8446

8447
    This dispatches the disk replacement to the appropriate handler.
8448

8449
    """
8450
    if self.delay_iallocator:
8451
      self._CheckPrereq2()
8452

    
8453
    if not self.disks:
8454
      feedback_fn("No disks need replacement")
8455
      return
8456

    
8457
    feedback_fn("Replacing disk(s) %s for %s" %
8458
                (utils.CommaJoin(self.disks), self.instance.name))
8459

    
8460
    activate_disks = (not self.instance.admin_up)
8461

    
8462
    # Activate the instance disks if we're replacing them on a down instance
8463
    if activate_disks:
8464
      _StartInstanceDisks(self.lu, self.instance, True)
8465

    
8466
    try:
8467
      # Should we replace the secondary node?
8468
      if self.new_node is not None:
8469
        fn = self._ExecDrbd8Secondary
8470
      else:
8471
        fn = self._ExecDrbd8DiskOnly
8472

    
8473
      return fn(feedback_fn)
8474

    
8475
    finally:
8476
      # Deactivate the instance disks if we're replacing them on a
8477
      # down instance
8478
      if activate_disks:
8479
        _SafeShutdownInstanceDisks(self.lu, self.instance)
8480

    
8481
  def _CheckVolumeGroup(self, nodes):
8482
    self.lu.LogInfo("Checking volume groups")
8483

    
8484
    vgname = self.cfg.GetVGName()
8485

    
8486
    # Make sure volume group exists on all involved nodes
8487
    results = self.rpc.call_vg_list(nodes)
8488
    if not results:
8489
      raise errors.OpExecError("Can't list volume groups on the nodes")
8490

    
8491
    for node in nodes:
8492
      res = results[node]
8493
      res.Raise("Error checking node %s" % node)
8494
      if vgname not in res.payload:
8495
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
8496
                                 (vgname, node))
8497

    
8498
  def _CheckDisksExistence(self, nodes):
8499
    # Check disk existence
8500
    for idx, dev in enumerate(self.instance.disks):
8501
      if idx not in self.disks:
8502
        continue
8503

    
8504
      for node in nodes:
8505
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
8506
        self.cfg.SetDiskID(dev, node)
8507

    
8508
        result = self.rpc.call_blockdev_find(node, dev)
8509

    
8510
        msg = result.fail_msg
8511
        if msg or not result.payload:
8512
          if not msg:
8513
            msg = "disk not found"
8514
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
8515
                                   (idx, node, msg))
8516

    
8517
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
8518
    for idx, dev in enumerate(self.instance.disks):
8519
      if idx not in self.disks:
8520
        continue
8521

    
8522
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
8523
                      (idx, node_name))
8524

    
8525
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
8526
                                   ldisk=ldisk):
8527
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
8528
                                 " replace disks for instance %s" %
8529
                                 (node_name, self.instance.name))
8530

    
8531
  def _CreateNewStorage(self, node_name):
8532
    vgname = self.cfg.GetVGName()
8533
    iv_names = {}
8534

    
8535
    for idx, dev in enumerate(self.instance.disks):
8536
      if idx not in self.disks:
8537
        continue
8538

    
8539
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
8540

    
8541
      self.cfg.SetDiskID(dev, node_name)
8542

    
8543
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
8544
      names = _GenerateUniqueNames(self.lu, lv_names)
8545

    
8546
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
8547
                             logical_id=(vgname, names[0]))
8548
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
8549
                             logical_id=(vgname, names[1]))
8550

    
8551
      new_lvs = [lv_data, lv_meta]
8552
      old_lvs = dev.children
8553
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
8554

    
8555
      # we pass force_create=True to force the LVM creation
8556
      for new_lv in new_lvs:
8557
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
8558
                        _GetInstanceInfoText(self.instance), False)
8559

    
8560
    return iv_names
8561

    
8562
  def _CheckDevices(self, node_name, iv_names):
8563
    for name, (dev, _, _) in iv_names.iteritems():
8564
      self.cfg.SetDiskID(dev, node_name)
8565

    
8566
      result = self.rpc.call_blockdev_find(node_name, dev)
8567

    
8568
      msg = result.fail_msg
8569
      if msg or not result.payload:
8570
        if not msg:
8571
          msg = "disk not found"
8572
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
8573
                                 (name, msg))
8574

    
8575
      if result.payload.is_degraded:
8576
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
8577

    
8578
  def _RemoveOldStorage(self, node_name, iv_names):
8579
    for name, (_, old_lvs, _) in iv_names.iteritems():
8580
      self.lu.LogInfo("Remove logical volumes for %s" % name)
8581

    
8582
      for lv in old_lvs:
8583
        self.cfg.SetDiskID(lv, node_name)
8584

    
8585
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
8586
        if msg:
8587
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
8588
                             hint="remove unused LVs manually")
8589

    
8590
  def _ReleaseNodeLock(self, node_name):
8591
    """Releases the lock for a given node."""
8592
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
8593

    
8594
  def _ExecDrbd8DiskOnly(self, feedback_fn):
8595
    """Replace a disk on the primary or secondary for DRBD 8.
8596

8597
    The algorithm for replace is quite complicated:
8598

8599
      1. for each disk to be replaced:
8600

8601
        1. create new LVs on the target node with unique names
8602
        1. detach old LVs from the drbd device
8603
        1. rename old LVs to name_replaced.<time_t>
8604
        1. rename new LVs to old LVs
8605
        1. attach the new LVs (with the old names now) to the drbd device
8606

8607
      1. wait for sync across all devices
8608

8609
      1. for each modified disk:
8610

8611
        1. remove old LVs (which have the name name_replaces.<time_t>)
8612

8613
    Failures are not very well handled.
8614

8615
    """
8616
    steps_total = 6
8617

    
8618
    # Step: check device activation
8619
    self.lu.LogStep(1, steps_total, "Check device existence")
8620
    self._CheckDisksExistence([self.other_node, self.target_node])
8621
    self._CheckVolumeGroup([self.target_node, self.other_node])
8622

    
8623
    # Step: check other node consistency
8624
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8625
    self._CheckDisksConsistency(self.other_node,
8626
                                self.other_node == self.instance.primary_node,
8627
                                False)
8628

    
8629
    # Step: create new storage
8630
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8631
    iv_names = self._CreateNewStorage(self.target_node)
8632

    
8633
    # Step: for each lv, detach+rename*2+attach
8634
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8635
    for dev, old_lvs, new_lvs in iv_names.itervalues():
8636
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
8637

    
8638
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
8639
                                                     old_lvs)
8640
      result.Raise("Can't detach drbd from local storage on node"
8641
                   " %s for device %s" % (self.target_node, dev.iv_name))
8642
      #dev.children = []
8643
      #cfg.Update(instance)
8644

    
8645
      # ok, we created the new LVs, so now we know we have the needed
8646
      # storage; as such, we proceed on the target node to rename
8647
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
8648
      # using the assumption that logical_id == physical_id (which in
8649
      # turn is the unique_id on that node)
8650

    
8651
      # FIXME(iustin): use a better name for the replaced LVs
8652
      temp_suffix = int(time.time())
8653
      ren_fn = lambda d, suff: (d.physical_id[0],
8654
                                d.physical_id[1] + "_replaced-%s" % suff)
8655

    
8656
      # Build the rename list based on what LVs exist on the node
8657
      rename_old_to_new = []
8658
      for to_ren in old_lvs:
8659
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
8660
        if not result.fail_msg and result.payload:
8661
          # device exists
8662
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
8663

    
8664
      self.lu.LogInfo("Renaming the old LVs on the target node")
8665
      result = self.rpc.call_blockdev_rename(self.target_node,
8666
                                             rename_old_to_new)
8667
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
8668

    
8669
      # Now we rename the new LVs to the old LVs
8670
      self.lu.LogInfo("Renaming the new LVs on the target node")
8671
      rename_new_to_old = [(new, old.physical_id)
8672
                           for old, new in zip(old_lvs, new_lvs)]
8673
      result = self.rpc.call_blockdev_rename(self.target_node,
8674
                                             rename_new_to_old)
8675
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
8676

    
8677
      for old, new in zip(old_lvs, new_lvs):
8678
        new.logical_id = old.logical_id
8679
        self.cfg.SetDiskID(new, self.target_node)
8680

    
8681
      for disk in old_lvs:
8682
        disk.logical_id = ren_fn(disk, temp_suffix)
8683
        self.cfg.SetDiskID(disk, self.target_node)
8684

    
8685
      # Now that the new lvs have the old name, we can add them to the device
8686
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
8687
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
8688
                                                  new_lvs)
8689
      msg = result.fail_msg
8690
      if msg:
8691
        for new_lv in new_lvs:
8692
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
8693
                                               new_lv).fail_msg
8694
          if msg2:
8695
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
8696
                               hint=("cleanup manually the unused logical"
8697
                                     "volumes"))
8698
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8699

    
8700
      dev.children = new_lvs
8701

    
8702
      self.cfg.Update(self.instance, feedback_fn)
8703

    
8704
    cstep = 5
8705
    if self.early_release:
8706
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8707
      cstep += 1
8708
      self._RemoveOldStorage(self.target_node, iv_names)
8709
      # WARNING: we release both node locks here, do not do other RPCs
8710
      # than WaitForSync to the primary node
8711
      self._ReleaseNodeLock([self.target_node, self.other_node])
8712

    
8713
    # Wait for sync
8714
    # This can fail as the old devices are degraded and _WaitForSync
8715
    # does a combined result over all disks, so we don't check its return value
8716
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8717
    cstep += 1
8718
    _WaitForSync(self.lu, self.instance)
8719

    
8720
    # Check all devices manually
8721
    self._CheckDevices(self.instance.primary_node, iv_names)
8722

    
8723
    # Step: remove old storage
8724
    if not self.early_release:
8725
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8726
      cstep += 1
8727
      self._RemoveOldStorage(self.target_node, iv_names)
8728

    
8729
  def _ExecDrbd8Secondary(self, feedback_fn):
8730
    """Replace the secondary node for DRBD 8.
8731

8732
    The algorithm for replace is quite complicated:
8733
      - for all disks of the instance:
8734
        - create new LVs on the new node with same names
8735
        - shutdown the drbd device on the old secondary
8736
        - disconnect the drbd network on the primary
8737
        - create the drbd device on the new secondary
8738
        - network attach the drbd on the primary, using an artifice:
8739
          the drbd code for Attach() will connect to the network if it
8740
          finds a device which is connected to the good local disks but
8741
          not network enabled
8742
      - wait for sync across all devices
8743
      - remove all disks from the old secondary
8744

8745
    Failures are not very well handled.
8746

8747
    """
8748
    steps_total = 6
8749

    
8750
    # Step: check device activation
8751
    self.lu.LogStep(1, steps_total, "Check device existence")
8752
    self._CheckDisksExistence([self.instance.primary_node])
8753
    self._CheckVolumeGroup([self.instance.primary_node])
8754

    
8755
    # Step: check other node consistency
8756
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8757
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8758

    
8759
    # Step: create new storage
8760
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8761
    for idx, dev in enumerate(self.instance.disks):
8762
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8763
                      (self.new_node, idx))
8764
      # we pass force_create=True to force LVM creation
8765
      for new_lv in dev.children:
8766
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8767
                        _GetInstanceInfoText(self.instance), False)
8768

    
8769
    # Step 4: dbrd minors and drbd setups changes
8770
    # after this, we must manually remove the drbd minors on both the
8771
    # error and the success paths
8772
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8773
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8774
                                         for dev in self.instance.disks],
8775
                                        self.instance.name)
8776
    logging.debug("Allocated minors %r", minors)
8777

    
8778
    iv_names = {}
8779
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8780
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8781
                      (self.new_node, idx))
8782
      # create new devices on new_node; note that we create two IDs:
8783
      # one without port, so the drbd will be activated without
8784
      # networking information on the new node at this stage, and one
8785
      # with network, for the latter activation in step 4
8786
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8787
      if self.instance.primary_node == o_node1:
8788
        p_minor = o_minor1
8789
      else:
8790
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8791
        p_minor = o_minor2
8792

    
8793
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8794
                      p_minor, new_minor, o_secret)
8795
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8796
                    p_minor, new_minor, o_secret)
8797

    
8798
      iv_names[idx] = (dev, dev.children, new_net_id)
8799
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8800
                    new_net_id)
8801
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8802
                              logical_id=new_alone_id,
8803
                              children=dev.children,
8804
                              size=dev.size)
8805
      try:
8806
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8807
                              _GetInstanceInfoText(self.instance), False)
8808
      except errors.GenericError:
8809
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8810
        raise
8811

    
8812
    # We have new devices, shutdown the drbd on the old secondary
8813
    for idx, dev in enumerate(self.instance.disks):
8814
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8815
      self.cfg.SetDiskID(dev, self.target_node)
8816
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8817
      if msg:
8818
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8819
                           "node: %s" % (idx, msg),
8820
                           hint=("Please cleanup this device manually as"
8821
                                 " soon as possible"))
8822

    
8823
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8824
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8825
                                               self.node_secondary_ip,
8826
                                               self.instance.disks)\
8827
                                              [self.instance.primary_node]
8828

    
8829
    msg = result.fail_msg
8830
    if msg:
8831
      # detaches didn't succeed (unlikely)
8832
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8833
      raise errors.OpExecError("Can't detach the disks from the network on"
8834
                               " old node: %s" % (msg,))
8835

    
8836
    # if we managed to detach at least one, we update all the disks of
8837
    # the instance to point to the new secondary
8838
    self.lu.LogInfo("Updating instance configuration")
8839
    for dev, _, new_logical_id in iv_names.itervalues():
8840
      dev.logical_id = new_logical_id
8841
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8842

    
8843
    self.cfg.Update(self.instance, feedback_fn)
8844

    
8845
    # and now perform the drbd attach
8846
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8847
                    " (standalone => connected)")
8848
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8849
                                            self.new_node],
8850
                                           self.node_secondary_ip,
8851
                                           self.instance.disks,
8852
                                           self.instance.name,
8853
                                           False)
8854
    for to_node, to_result in result.items():
8855
      msg = to_result.fail_msg
8856
      if msg:
8857
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8858
                           to_node, msg,
8859
                           hint=("please do a gnt-instance info to see the"
8860
                                 " status of disks"))
8861
    cstep = 5
8862
    if self.early_release:
8863
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8864
      cstep += 1
8865
      self._RemoveOldStorage(self.target_node, iv_names)
8866
      # WARNING: we release all node locks here, do not do other RPCs
8867
      # than WaitForSync to the primary node
8868
      self._ReleaseNodeLock([self.instance.primary_node,
8869
                             self.target_node,
8870
                             self.new_node])
8871

    
8872
    # Wait for sync
8873
    # This can fail as the old devices are degraded and _WaitForSync
8874
    # does a combined result over all disks, so we don't check its return value
8875
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8876
    cstep += 1
8877
    _WaitForSync(self.lu, self.instance)
8878

    
8879
    # Check all devices manually
8880
    self._CheckDevices(self.instance.primary_node, iv_names)
8881

    
8882
    # Step: remove old storage
8883
    if not self.early_release:
8884
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8885
      self._RemoveOldStorage(self.target_node, iv_names)
8886

    
8887

    
8888
class LURepairNodeStorage(NoHooksLU):
8889
  """Repairs the volume group on a node.
8890

8891
  """
8892
  REQ_BGL = False
8893

    
8894
  def CheckArguments(self):
8895
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8896

    
8897
    storage_type = self.op.storage_type
8898

    
8899
    if (constants.SO_FIX_CONSISTENCY not in
8900
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8901
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8902
                                 " repaired" % storage_type,
8903
                                 errors.ECODE_INVAL)
8904

    
8905
  def ExpandNames(self):
8906
    self.needed_locks = {
8907
      locking.LEVEL_NODE: [self.op.node_name],
8908
      }
8909

    
8910
  def _CheckFaultyDisks(self, instance, node_name):
8911
    """Ensure faulty disks abort the opcode or at least warn."""
8912
    try:
8913
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8914
                                  node_name, True):
8915
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8916
                                   " node '%s'" % (instance.name, node_name),
8917
                                   errors.ECODE_STATE)
8918
    except errors.OpPrereqError, err:
8919
      if self.op.ignore_consistency:
8920
        self.proc.LogWarning(str(err.args[0]))
8921
      else:
8922
        raise
8923

    
8924
  def CheckPrereq(self):
8925
    """Check prerequisites.
8926

8927
    """
8928
    # Check whether any instance on this node has faulty disks
8929
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8930
      if not inst.admin_up:
8931
        continue
8932
      check_nodes = set(inst.all_nodes)
8933
      check_nodes.discard(self.op.node_name)
8934
      for inst_node_name in check_nodes:
8935
        self._CheckFaultyDisks(inst, inst_node_name)
8936

    
8937
  def Exec(self, feedback_fn):
8938
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8939
                (self.op.name, self.op.node_name))
8940

    
8941
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8942
    result = self.rpc.call_storage_execute(self.op.node_name,
8943
                                           self.op.storage_type, st_args,
8944
                                           self.op.name,
8945
                                           constants.SO_FIX_CONSISTENCY)
8946
    result.Raise("Failed to repair storage unit '%s' on %s" %
8947
                 (self.op.name, self.op.node_name))
8948

    
8949

    
8950
class LUNodeEvacStrategy(NoHooksLU):
8951
  """Computes the node evacuation strategy.
8952

8953
  """
8954
  REQ_BGL = False
8955

    
8956
  def CheckArguments(self):
8957
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8958

    
8959
  def ExpandNames(self):
8960
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8961
    self.needed_locks = locks = {}
8962
    if self.op.remote_node is None:
8963
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8964
    else:
8965
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8966
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8967

    
8968
  def Exec(self, feedback_fn):
8969
    if self.op.remote_node is not None:
8970
      instances = []
8971
      for node in self.op.nodes:
8972
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8973
      result = []
8974
      for i in instances:
8975
        if i.primary_node == self.op.remote_node:
8976
          raise errors.OpPrereqError("Node %s is the primary node of"
8977
                                     " instance %s, cannot use it as"
8978
                                     " secondary" %
8979
                                     (self.op.remote_node, i.name),
8980
                                     errors.ECODE_INVAL)
8981
        result.append([i.name, self.op.remote_node])
8982
    else:
8983
      ial = IAllocator(self.cfg, self.rpc,
8984
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8985
                       evac_nodes=self.op.nodes)
8986
      ial.Run(self.op.iallocator, validate=True)
8987
      if not ial.success:
8988
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8989
                                 errors.ECODE_NORES)
8990
      result = ial.result
8991
    return result
8992

    
8993

    
8994
class LUInstanceGrowDisk(LogicalUnit):
8995
  """Grow a disk of an instance.
8996

8997
  """
8998
  HPATH = "disk-grow"
8999
  HTYPE = constants.HTYPE_INSTANCE
9000
  REQ_BGL = False
9001

    
9002
  def ExpandNames(self):
9003
    self._ExpandAndLockInstance()
9004
    self.needed_locks[locking.LEVEL_NODE] = []
9005
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9006

    
9007
  def DeclareLocks(self, level):
9008
    if level == locking.LEVEL_NODE:
9009
      self._LockInstancesNodes()
9010

    
9011
  def BuildHooksEnv(self):
9012
    """Build hooks env.
9013

9014
    This runs on the master, the primary and all the secondaries.
9015

9016
    """
9017
    env = {
9018
      "DISK": self.op.disk,
9019
      "AMOUNT": self.op.amount,
9020
      }
9021
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9022
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9023
    return env, nl, nl
9024

    
9025
  def CheckPrereq(self):
9026
    """Check prerequisites.
9027

9028
    This checks that the instance is in the cluster.
9029

9030
    """
9031
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9032
    assert instance is not None, \
9033
      "Cannot retrieve locked instance %s" % self.op.instance_name
9034
    nodenames = list(instance.all_nodes)
9035
    for node in nodenames:
9036
      _CheckNodeOnline(self, node)
9037

    
9038
    self.instance = instance
9039

    
9040
    if instance.disk_template not in constants.DTS_GROWABLE:
9041
      raise errors.OpPrereqError("Instance's disk layout does not support"
9042
                                 " growing.", errors.ECODE_INVAL)
9043

    
9044
    self.disk = instance.FindDisk(self.op.disk)
9045

    
9046
    if instance.disk_template not in (constants.DT_FILE,
9047
                                      constants.DT_SHARED_FILE):
9048
      # TODO: check the free disk space for file, when that feature will be
9049
      # supported
9050
      _CheckNodesFreeDiskPerVG(self, nodenames,
9051
                               self.disk.ComputeGrowth(self.op.amount))
9052

    
9053
  def Exec(self, feedback_fn):
9054
    """Execute disk grow.
9055

9056
    """
9057
    instance = self.instance
9058
    disk = self.disk
9059

    
9060
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
9061
    if not disks_ok:
9062
      raise errors.OpExecError("Cannot activate block device to grow")
9063

    
9064
    for node in instance.all_nodes:
9065
      self.cfg.SetDiskID(disk, node)
9066
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
9067
      result.Raise("Grow request failed to node %s" % node)
9068

    
9069
      # TODO: Rewrite code to work properly
9070
      # DRBD goes into sync mode for a short amount of time after executing the
9071
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
9072
      # calling "resize" in sync mode fails. Sleeping for a short amount of
9073
      # time is a work-around.
9074
      time.sleep(5)
9075

    
9076
    disk.RecordGrow(self.op.amount)
9077
    self.cfg.Update(instance, feedback_fn)
9078
    if self.op.wait_for_sync:
9079
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
9080
      if disk_abort:
9081
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
9082
                             " status.\nPlease check the instance.")
9083
      if not instance.admin_up:
9084
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
9085
    elif not instance.admin_up:
9086
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
9087
                           " not supposed to be running because no wait for"
9088
                           " sync mode was requested.")
9089

    
9090

    
9091
class LUInstanceQueryData(NoHooksLU):
9092
  """Query runtime instance data.
9093

9094
  """
9095
  REQ_BGL = False
9096

    
9097
  def ExpandNames(self):
9098
    self.needed_locks = {}
9099
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9100

    
9101
    if self.op.instances:
9102
      self.wanted_names = []
9103
      for name in self.op.instances:
9104
        full_name = _ExpandInstanceName(self.cfg, name)
9105
        self.wanted_names.append(full_name)
9106
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
9107
    else:
9108
      self.wanted_names = None
9109
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
9110

    
9111
    self.needed_locks[locking.LEVEL_NODE] = []
9112
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9113

    
9114
  def DeclareLocks(self, level):
9115
    if level == locking.LEVEL_NODE:
9116
      self._LockInstancesNodes()
9117

    
9118
  def CheckPrereq(self):
9119
    """Check prerequisites.
9120

9121
    This only checks the optional instance list against the existing names.
9122

9123
    """
9124
    if self.wanted_names is None:
9125
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
9126

    
9127
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
9128
                             in self.wanted_names]
9129

    
9130
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
9131
    """Returns the status of a block device
9132

9133
    """
9134
    if self.op.static or not node:
9135
      return None
9136

    
9137
    self.cfg.SetDiskID(dev, node)
9138

    
9139
    result = self.rpc.call_blockdev_find(node, dev)
9140
    if result.offline:
9141
      return None
9142

    
9143
    result.Raise("Can't compute disk status for %s" % instance_name)
9144

    
9145
    status = result.payload
9146
    if status is None:
9147
      return None
9148

    
9149
    return (status.dev_path, status.major, status.minor,
9150
            status.sync_percent, status.estimated_time,
9151
            status.is_degraded, status.ldisk_status)
9152

    
9153
  def _ComputeDiskStatus(self, instance, snode, dev):
9154
    """Compute block device status.
9155

9156
    """
9157
    if dev.dev_type in constants.LDS_DRBD:
9158
      # we change the snode then (otherwise we use the one passed in)
9159
      if dev.logical_id[0] == instance.primary_node:
9160
        snode = dev.logical_id[1]
9161
      else:
9162
        snode = dev.logical_id[0]
9163

    
9164
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
9165
                                              instance.name, dev)
9166
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
9167

    
9168
    if dev.children:
9169
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
9170
                      for child in dev.children]
9171
    else:
9172
      dev_children = []
9173

    
9174
    data = {
9175
      "iv_name": dev.iv_name,
9176
      "dev_type": dev.dev_type,
9177
      "logical_id": dev.logical_id,
9178
      "physical_id": dev.physical_id,
9179
      "pstatus": dev_pstatus,
9180
      "sstatus": dev_sstatus,
9181
      "children": dev_children,
9182
      "mode": dev.mode,
9183
      "size": dev.size,
9184
      }
9185

    
9186
    return data
9187

    
9188
  def Exec(self, feedback_fn):
9189
    """Gather and return data"""
9190
    result = {}
9191

    
9192
    cluster = self.cfg.GetClusterInfo()
9193

    
9194
    for instance in self.wanted_instances:
9195
      if not self.op.static:
9196
        remote_info = self.rpc.call_instance_info(instance.primary_node,
9197
                                                  instance.name,
9198
                                                  instance.hypervisor)
9199
        remote_info.Raise("Error checking node %s" % instance.primary_node)
9200
        remote_info = remote_info.payload
9201
        if remote_info and "state" in remote_info:
9202
          remote_state = "up"
9203
        else:
9204
          remote_state = "down"
9205
      else:
9206
        remote_state = None
9207
      if instance.admin_up:
9208
        config_state = "up"
9209
      else:
9210
        config_state = "down"
9211

    
9212
      disks = [self._ComputeDiskStatus(instance, None, device)
9213
               for device in instance.disks]
9214

    
9215
      idict = {
9216
        "name": instance.name,
9217
        "config_state": config_state,
9218
        "run_state": remote_state,
9219
        "pnode": instance.primary_node,
9220
        "snodes": instance.secondary_nodes,
9221
        "os": instance.os,
9222
        # this happens to be the same format used for hooks
9223
        "nics": _NICListToTuple(self, instance.nics),
9224
        "disk_template": instance.disk_template,
9225
        "disks": disks,
9226
        "hypervisor": instance.hypervisor,
9227
        "network_port": instance.network_port,
9228
        "hv_instance": instance.hvparams,
9229
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
9230
        "be_instance": instance.beparams,
9231
        "be_actual": cluster.FillBE(instance),
9232
        "os_instance": instance.osparams,
9233
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
9234
        "serial_no": instance.serial_no,
9235
        "mtime": instance.mtime,
9236
        "ctime": instance.ctime,
9237
        "uuid": instance.uuid,
9238
        }
9239

    
9240
      result[instance.name] = idict
9241

    
9242
    return result
9243

    
9244

    
9245
class LUInstanceSetParams(LogicalUnit):
9246
  """Modifies an instances's parameters.
9247

9248
  """
9249
  HPATH = "instance-modify"
9250
  HTYPE = constants.HTYPE_INSTANCE
9251
  REQ_BGL = False
9252

    
9253
  def CheckArguments(self):
9254
    if not (self.op.nics or self.op.disks or self.op.disk_template or
9255
            self.op.hvparams or self.op.beparams or self.op.os_name):
9256
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
9257

    
9258
    if self.op.hvparams:
9259
      _CheckGlobalHvParams(self.op.hvparams)
9260

    
9261
    # Disk validation
9262
    disk_addremove = 0
9263
    for disk_op, disk_dict in self.op.disks:
9264
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
9265
      if disk_op == constants.DDM_REMOVE:
9266
        disk_addremove += 1
9267
        continue
9268
      elif disk_op == constants.DDM_ADD:
9269
        disk_addremove += 1
9270
      else:
9271
        if not isinstance(disk_op, int):
9272
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
9273
        if not isinstance(disk_dict, dict):
9274
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
9275
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9276

    
9277
      if disk_op == constants.DDM_ADD:
9278
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
9279
        if mode not in constants.DISK_ACCESS_SET:
9280
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
9281
                                     errors.ECODE_INVAL)
9282
        size = disk_dict.get('size', None)
9283
        if size is None:
9284
          raise errors.OpPrereqError("Required disk parameter size missing",
9285
                                     errors.ECODE_INVAL)
9286
        try:
9287
          size = int(size)
9288
        except (TypeError, ValueError), err:
9289
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
9290
                                     str(err), errors.ECODE_INVAL)
9291
        disk_dict['size'] = size
9292
      else:
9293
        # modification of disk
9294
        if 'size' in disk_dict:
9295
          raise errors.OpPrereqError("Disk size change not possible, use"
9296
                                     " grow-disk", errors.ECODE_INVAL)
9297

    
9298
    if disk_addremove > 1:
9299
      raise errors.OpPrereqError("Only one disk add or remove operation"
9300
                                 " supported at a time", errors.ECODE_INVAL)
9301

    
9302
    if self.op.disks and self.op.disk_template is not None:
9303
      raise errors.OpPrereqError("Disk template conversion and other disk"
9304
                                 " changes not supported at the same time",
9305
                                 errors.ECODE_INVAL)
9306

    
9307
    if (self.op.disk_template and
9308
        self.op.disk_template in constants.DTS_INT_MIRROR and
9309
        self.op.remote_node is None):
9310
      raise errors.OpPrereqError("Changing the disk template to a mirrored"
9311
                                 " one requires specifying a secondary node",
9312
                                 errors.ECODE_INVAL)
9313

    
9314
    # NIC validation
9315
    nic_addremove = 0
9316
    for nic_op, nic_dict in self.op.nics:
9317
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
9318
      if nic_op == constants.DDM_REMOVE:
9319
        nic_addremove += 1
9320
        continue
9321
      elif nic_op == constants.DDM_ADD:
9322
        nic_addremove += 1
9323
      else:
9324
        if not isinstance(nic_op, int):
9325
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
9326
        if not isinstance(nic_dict, dict):
9327
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
9328
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9329

    
9330
      # nic_dict should be a dict
9331
      nic_ip = nic_dict.get('ip', None)
9332
      if nic_ip is not None:
9333
        if nic_ip.lower() == constants.VALUE_NONE:
9334
          nic_dict['ip'] = None
9335
        else:
9336
          if not netutils.IPAddress.IsValid(nic_ip):
9337
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
9338
                                       errors.ECODE_INVAL)
9339

    
9340
      nic_bridge = nic_dict.get('bridge', None)
9341
      nic_link = nic_dict.get('link', None)
9342
      if nic_bridge and nic_link:
9343
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
9344
                                   " at the same time", errors.ECODE_INVAL)
9345
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
9346
        nic_dict['bridge'] = None
9347
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
9348
        nic_dict['link'] = None
9349

    
9350
      if nic_op == constants.DDM_ADD:
9351
        nic_mac = nic_dict.get('mac', None)
9352
        if nic_mac is None:
9353
          nic_dict['mac'] = constants.VALUE_AUTO
9354

    
9355
      if 'mac' in nic_dict:
9356
        nic_mac = nic_dict['mac']
9357
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9358
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
9359

    
9360
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
9361
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
9362
                                     " modifying an existing nic",
9363
                                     errors.ECODE_INVAL)
9364

    
9365
    if nic_addremove > 1:
9366
      raise errors.OpPrereqError("Only one NIC add or remove operation"
9367
                                 " supported at a time", errors.ECODE_INVAL)
9368

    
9369
  def ExpandNames(self):
9370
    self._ExpandAndLockInstance()
9371
    self.needed_locks[locking.LEVEL_NODE] = []
9372
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9373

    
9374
  def DeclareLocks(self, level):
9375
    if level == locking.LEVEL_NODE:
9376
      self._LockInstancesNodes()
9377
      if self.op.disk_template and self.op.remote_node:
9378
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9379
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
9380

    
9381
  def BuildHooksEnv(self):
9382
    """Build hooks env.
9383

9384
    This runs on the master, primary and secondaries.
9385

9386
    """
9387
    args = dict()
9388
    if constants.BE_MEMORY in self.be_new:
9389
      args['memory'] = self.be_new[constants.BE_MEMORY]
9390
    if constants.BE_VCPUS in self.be_new:
9391
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
9392
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
9393
    # information at all.
9394
    if self.op.nics:
9395
      args['nics'] = []
9396
      nic_override = dict(self.op.nics)
9397
      for idx, nic in enumerate(self.instance.nics):
9398
        if idx in nic_override:
9399
          this_nic_override = nic_override[idx]
9400
        else:
9401
          this_nic_override = {}
9402
        if 'ip' in this_nic_override:
9403
          ip = this_nic_override['ip']
9404
        else:
9405
          ip = nic.ip
9406
        if 'mac' in this_nic_override:
9407
          mac = this_nic_override['mac']
9408
        else:
9409
          mac = nic.mac
9410
        if idx in self.nic_pnew:
9411
          nicparams = self.nic_pnew[idx]
9412
        else:
9413
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
9414
        mode = nicparams[constants.NIC_MODE]
9415
        link = nicparams[constants.NIC_LINK]
9416
        args['nics'].append((ip, mac, mode, link))
9417
      if constants.DDM_ADD in nic_override:
9418
        ip = nic_override[constants.DDM_ADD].get('ip', None)
9419
        mac = nic_override[constants.DDM_ADD]['mac']
9420
        nicparams = self.nic_pnew[constants.DDM_ADD]
9421
        mode = nicparams[constants.NIC_MODE]
9422
        link = nicparams[constants.NIC_LINK]
9423
        args['nics'].append((ip, mac, mode, link))
9424
      elif constants.DDM_REMOVE in nic_override:
9425
        del args['nics'][-1]
9426

    
9427
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
9428
    if self.op.disk_template:
9429
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
9430
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9431
    return env, nl, nl
9432

    
9433
  def CheckPrereq(self):
9434
    """Check prerequisites.
9435

9436
    This only checks the instance list against the existing names.
9437

9438
    """
9439
    # checking the new params on the primary/secondary nodes
9440

    
9441
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9442
    cluster = self.cluster = self.cfg.GetClusterInfo()
9443
    assert self.instance is not None, \
9444
      "Cannot retrieve locked instance %s" % self.op.instance_name
9445
    pnode = instance.primary_node
9446
    nodelist = list(instance.all_nodes)
9447

    
9448
    # OS change
9449
    if self.op.os_name and not self.op.force:
9450
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
9451
                      self.op.force_variant)
9452
      instance_os = self.op.os_name
9453
    else:
9454
      instance_os = instance.os
9455

    
9456
    if self.op.disk_template:
9457
      if instance.disk_template == self.op.disk_template:
9458
        raise errors.OpPrereqError("Instance already has disk template %s" %
9459
                                   instance.disk_template, errors.ECODE_INVAL)
9460

    
9461
      if (instance.disk_template,
9462
          self.op.disk_template) not in self._DISK_CONVERSIONS:
9463
        raise errors.OpPrereqError("Unsupported disk template conversion from"
9464
                                   " %s to %s" % (instance.disk_template,
9465
                                                  self.op.disk_template),
9466
                                   errors.ECODE_INVAL)
9467
      _CheckInstanceDown(self, instance, "cannot change disk template")
9468
      if self.op.disk_template in constants.DTS_INT_MIRROR:
9469
        if self.op.remote_node == pnode:
9470
          raise errors.OpPrereqError("Given new secondary node %s is the same"
9471
                                     " as the primary node of the instance" %
9472
                                     self.op.remote_node, errors.ECODE_STATE)
9473
        _CheckNodeOnline(self, self.op.remote_node)
9474
        _CheckNodeNotDrained(self, self.op.remote_node)
9475
        # FIXME: here we assume that the old instance type is DT_PLAIN
9476
        assert instance.disk_template == constants.DT_PLAIN
9477
        disks = [{"size": d.size, "vg": d.logical_id[0]}
9478
                 for d in instance.disks]
9479
        required = _ComputeDiskSizePerVG(self.op.disk_template, disks)
9480
        _CheckNodesFreeDiskPerVG(self, [self.op.remote_node], required)
9481

    
9482
    # hvparams processing
9483
    if self.op.hvparams:
9484
      hv_type = instance.hypervisor
9485
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
9486
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
9487
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
9488

    
9489
      # local check
9490
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
9491
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
9492
      self.hv_new = hv_new # the new actual values
9493
      self.hv_inst = i_hvdict # the new dict (without defaults)
9494
    else:
9495
      self.hv_new = self.hv_inst = {}
9496

    
9497
    # beparams processing
9498
    if self.op.beparams:
9499
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
9500
                                   use_none=True)
9501
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
9502
      be_new = cluster.SimpleFillBE(i_bedict)
9503
      self.be_new = be_new # the new actual values
9504
      self.be_inst = i_bedict # the new dict (without defaults)
9505
    else:
9506
      self.be_new = self.be_inst = {}
9507

    
9508
    # osparams processing
9509
    if self.op.osparams:
9510
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
9511
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
9512
      self.os_inst = i_osdict # the new dict (without defaults)
9513
    else:
9514
      self.os_inst = {}
9515

    
9516
    self.warn = []
9517

    
9518
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
9519
      mem_check_list = [pnode]
9520
      if be_new[constants.BE_AUTO_BALANCE]:
9521
        # either we changed auto_balance to yes or it was from before
9522
        mem_check_list.extend(instance.secondary_nodes)
9523
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
9524
                                                  instance.hypervisor)
9525
      nodeinfo = self.rpc.call_node_info(mem_check_list, None,
9526
                                         instance.hypervisor)
9527
      pninfo = nodeinfo[pnode]
9528
      msg = pninfo.fail_msg
9529
      if msg:
9530
        # Assume the primary node is unreachable and go ahead
9531
        self.warn.append("Can't get info from primary node %s: %s" %
9532
                         (pnode,  msg))
9533
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
9534
        self.warn.append("Node data from primary node %s doesn't contain"
9535
                         " free memory information" % pnode)
9536
      elif instance_info.fail_msg:
9537
        self.warn.append("Can't get instance runtime information: %s" %
9538
                        instance_info.fail_msg)
9539
      else:
9540
        if instance_info.payload:
9541
          current_mem = int(instance_info.payload['memory'])
9542
        else:
9543
          # Assume instance not running
9544
          # (there is a slight race condition here, but it's not very probable,
9545
          # and we have no other way to check)
9546
          current_mem = 0
9547
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
9548
                    pninfo.payload['memory_free'])
9549
        if miss_mem > 0:
9550
          raise errors.OpPrereqError("This change will prevent the instance"
9551
                                     " from starting, due to %d MB of memory"
9552
                                     " missing on its primary node" % miss_mem,
9553
                                     errors.ECODE_NORES)
9554

    
9555
      if be_new[constants.BE_AUTO_BALANCE]:
9556
        for node, nres in nodeinfo.items():
9557
          if node not in instance.secondary_nodes:
9558
            continue
9559
          msg = nres.fail_msg
9560
          if msg:
9561
            self.warn.append("Can't get info from secondary node %s: %s" %
9562
                             (node, msg))
9563
          elif not isinstance(nres.payload.get('memory_free', None), int):
9564
            self.warn.append("Secondary node %s didn't return free"
9565
                             " memory information" % node)
9566
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
9567
            self.warn.append("Not enough memory to failover instance to"
9568
                             " secondary node %s" % node)
9569

    
9570
    # NIC processing
9571
    self.nic_pnew = {}
9572
    self.nic_pinst = {}
9573
    for nic_op, nic_dict in self.op.nics:
9574
      if nic_op == constants.DDM_REMOVE:
9575
        if not instance.nics:
9576
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
9577
                                     errors.ECODE_INVAL)
9578
        continue
9579
      if nic_op != constants.DDM_ADD:
9580
        # an existing nic
9581
        if not instance.nics:
9582
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
9583
                                     " no NICs" % nic_op,
9584
                                     errors.ECODE_INVAL)
9585
        if nic_op < 0 or nic_op >= len(instance.nics):
9586
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
9587
                                     " are 0 to %d" %
9588
                                     (nic_op, len(instance.nics) - 1),
9589
                                     errors.ECODE_INVAL)
9590
        old_nic_params = instance.nics[nic_op].nicparams
9591
        old_nic_ip = instance.nics[nic_op].ip
9592
      else:
9593
        old_nic_params = {}
9594
        old_nic_ip = None
9595

    
9596
      update_params_dict = dict([(key, nic_dict[key])
9597
                                 for key in constants.NICS_PARAMETERS
9598
                                 if key in nic_dict])
9599

    
9600
      if 'bridge' in nic_dict:
9601
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
9602

    
9603
      new_nic_params = _GetUpdatedParams(old_nic_params,
9604
                                         update_params_dict)
9605
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
9606
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
9607
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
9608
      self.nic_pinst[nic_op] = new_nic_params
9609
      self.nic_pnew[nic_op] = new_filled_nic_params
9610
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
9611

    
9612
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
9613
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
9614
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
9615
        if msg:
9616
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
9617
          if self.op.force:
9618
            self.warn.append(msg)
9619
          else:
9620
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
9621
      if new_nic_mode == constants.NIC_MODE_ROUTED:
9622
        if 'ip' in nic_dict:
9623
          nic_ip = nic_dict['ip']
9624
        else:
9625
          nic_ip = old_nic_ip
9626
        if nic_ip is None:
9627
          raise errors.OpPrereqError('Cannot set the nic ip to None'
9628
                                     ' on a routed nic', errors.ECODE_INVAL)
9629
      if 'mac' in nic_dict:
9630
        nic_mac = nic_dict['mac']
9631
        if nic_mac is None:
9632
          raise errors.OpPrereqError('Cannot set the nic mac to None',
9633
                                     errors.ECODE_INVAL)
9634
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9635
          # otherwise generate the mac
9636
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
9637
        else:
9638
          # or validate/reserve the current one
9639
          try:
9640
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
9641
          except errors.ReservationError:
9642
            raise errors.OpPrereqError("MAC address %s already in use"
9643
                                       " in cluster" % nic_mac,
9644
                                       errors.ECODE_NOTUNIQUE)
9645

    
9646
    # DISK processing
9647
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
9648
      raise errors.OpPrereqError("Disk operations not supported for"
9649
                                 " diskless instances",
9650
                                 errors.ECODE_INVAL)
9651
    for disk_op, _ in self.op.disks:
9652
      if disk_op == constants.DDM_REMOVE:
9653
        if len(instance.disks) == 1:
9654
          raise errors.OpPrereqError("Cannot remove the last disk of"
9655
                                     " an instance", errors.ECODE_INVAL)
9656
        _CheckInstanceDown(self, instance, "cannot remove disks")
9657

    
9658
      if (disk_op == constants.DDM_ADD and
9659
          len(instance.disks) >= constants.MAX_DISKS):
9660
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
9661
                                   " add more" % constants.MAX_DISKS,
9662
                                   errors.ECODE_STATE)
9663
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
9664
        # an existing disk
9665
        if disk_op < 0 or disk_op >= len(instance.disks):
9666
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9667
                                     " are 0 to %d" %
9668
                                     (disk_op, len(instance.disks)),
9669
                                     errors.ECODE_INVAL)
9670

    
9671
    return
9672

    
9673
  def _ConvertPlainToDrbd(self, feedback_fn):
9674
    """Converts an instance from plain to drbd.
9675

9676
    """
9677
    feedback_fn("Converting template to drbd")
9678
    instance = self.instance
9679
    pnode = instance.primary_node
9680
    snode = self.op.remote_node
9681

    
9682
    # create a fake disk info for _GenerateDiskTemplate
9683
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
9684
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9685
                                      instance.name, pnode, [snode],
9686
                                      disk_info, None, None, 0, feedback_fn)
9687
    info = _GetInstanceInfoText(instance)
9688
    feedback_fn("Creating aditional volumes...")
9689
    # first, create the missing data and meta devices
9690
    for disk in new_disks:
9691
      # unfortunately this is... not too nice
9692
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9693
                            info, True)
9694
      for child in disk.children:
9695
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9696
    # at this stage, all new LVs have been created, we can rename the
9697
    # old ones
9698
    feedback_fn("Renaming original volumes...")
9699
    rename_list = [(o, n.children[0].logical_id)
9700
                   for (o, n) in zip(instance.disks, new_disks)]
9701
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9702
    result.Raise("Failed to rename original LVs")
9703

    
9704
    feedback_fn("Initializing DRBD devices...")
9705
    # all child devices are in place, we can now create the DRBD devices
9706
    for disk in new_disks:
9707
      for node in [pnode, snode]:
9708
        f_create = node == pnode
9709
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9710

    
9711
    # at this point, the instance has been modified
9712
    instance.disk_template = constants.DT_DRBD8
9713
    instance.disks = new_disks
9714
    self.cfg.Update(instance, feedback_fn)
9715

    
9716
    # disks are created, waiting for sync
9717
    disk_abort = not _WaitForSync(self, instance)
9718
    if disk_abort:
9719
      raise errors.OpExecError("There are some degraded disks for"
9720
                               " this instance, please cleanup manually")
9721

    
9722
  def _ConvertDrbdToPlain(self, feedback_fn):
9723
    """Converts an instance from drbd to plain.
9724

9725
    """
9726
    instance = self.instance
9727
    assert len(instance.secondary_nodes) == 1
9728
    pnode = instance.primary_node
9729
    snode = instance.secondary_nodes[0]
9730
    feedback_fn("Converting template to plain")
9731

    
9732
    old_disks = instance.disks
9733
    new_disks = [d.children[0] for d in old_disks]
9734

    
9735
    # copy over size and mode
9736
    for parent, child in zip(old_disks, new_disks):
9737
      child.size = parent.size
9738
      child.mode = parent.mode
9739

    
9740
    # update instance structure
9741
    instance.disks = new_disks
9742
    instance.disk_template = constants.DT_PLAIN
9743
    self.cfg.Update(instance, feedback_fn)
9744

    
9745
    feedback_fn("Removing volumes on the secondary node...")
9746
    for disk in old_disks:
9747
      self.cfg.SetDiskID(disk, snode)
9748
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9749
      if msg:
9750
        self.LogWarning("Could not remove block device %s on node %s,"
9751
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9752

    
9753
    feedback_fn("Removing unneeded volumes on the primary node...")
9754
    for idx, disk in enumerate(old_disks):
9755
      meta = disk.children[1]
9756
      self.cfg.SetDiskID(meta, pnode)
9757
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9758
      if msg:
9759
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9760
                        " continuing anyway: %s", idx, pnode, msg)
9761

    
9762
  def Exec(self, feedback_fn):
9763
    """Modifies an instance.
9764

9765
    All parameters take effect only at the next restart of the instance.
9766

9767
    """
9768
    # Process here the warnings from CheckPrereq, as we don't have a
9769
    # feedback_fn there.
9770
    for warn in self.warn:
9771
      feedback_fn("WARNING: %s" % warn)
9772

    
9773
    result = []
9774
    instance = self.instance
9775
    # disk changes
9776
    for disk_op, disk_dict in self.op.disks:
9777
      if disk_op == constants.DDM_REMOVE:
9778
        # remove the last disk
9779
        device = instance.disks.pop()
9780
        device_idx = len(instance.disks)
9781
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9782
          self.cfg.SetDiskID(disk, node)
9783
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9784
          if msg:
9785
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9786
                            " continuing anyway", device_idx, node, msg)
9787
        result.append(("disk/%d" % device_idx, "remove"))
9788
      elif disk_op == constants.DDM_ADD:
9789
        # add a new disk
9790
        if instance.disk_template in (constants.DT_FILE,
9791
                                        constants.DT_SHARED_FILE):
9792
          file_driver, file_path = instance.disks[0].logical_id
9793
          file_path = os.path.dirname(file_path)
9794
        else:
9795
          file_driver = file_path = None
9796
        disk_idx_base = len(instance.disks)
9797
        new_disk = _GenerateDiskTemplate(self,
9798
                                         instance.disk_template,
9799
                                         instance.name, instance.primary_node,
9800
                                         instance.secondary_nodes,
9801
                                         [disk_dict],
9802
                                         file_path,
9803
                                         file_driver,
9804
                                         disk_idx_base, feedback_fn)[0]
9805
        instance.disks.append(new_disk)
9806
        info = _GetInstanceInfoText(instance)
9807

    
9808
        logging.info("Creating volume %s for instance %s",
9809
                     new_disk.iv_name, instance.name)
9810
        # Note: this needs to be kept in sync with _CreateDisks
9811
        #HARDCODE
9812
        for node in instance.all_nodes:
9813
          f_create = node == instance.primary_node
9814
          try:
9815
            _CreateBlockDev(self, node, instance, new_disk,
9816
                            f_create, info, f_create)
9817
          except errors.OpExecError, err:
9818
            self.LogWarning("Failed to create volume %s (%s) on"
9819
                            " node %s: %s",
9820
                            new_disk.iv_name, new_disk, node, err)
9821
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9822
                       (new_disk.size, new_disk.mode)))
9823
      else:
9824
        # change a given disk
9825
        instance.disks[disk_op].mode = disk_dict['mode']
9826
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9827

    
9828
    if self.op.disk_template:
9829
      r_shut = _ShutdownInstanceDisks(self, instance)
9830
      if not r_shut:
9831
        raise errors.OpExecError("Cannot shutdown instance disks, unable to"
9832
                                 " proceed with disk template conversion")
9833
      mode = (instance.disk_template, self.op.disk_template)
9834
      try:
9835
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9836
      except:
9837
        self.cfg.ReleaseDRBDMinors(instance.name)
9838
        raise
9839
      result.append(("disk_template", self.op.disk_template))
9840

    
9841
    # NIC changes
9842
    for nic_op, nic_dict in self.op.nics:
9843
      if nic_op == constants.DDM_REMOVE:
9844
        # remove the last nic
9845
        del instance.nics[-1]
9846
        result.append(("nic.%d" % len(instance.nics), "remove"))
9847
      elif nic_op == constants.DDM_ADD:
9848
        # mac and bridge should be set, by now
9849
        mac = nic_dict['mac']
9850
        ip = nic_dict.get('ip', None)
9851
        nicparams = self.nic_pinst[constants.DDM_ADD]
9852
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9853
        instance.nics.append(new_nic)
9854
        result.append(("nic.%d" % (len(instance.nics) - 1),
9855
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9856
                       (new_nic.mac, new_nic.ip,
9857
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9858
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9859
                       )))
9860
      else:
9861
        for key in 'mac', 'ip':
9862
          if key in nic_dict:
9863
            setattr(instance.nics[nic_op], key, nic_dict[key])
9864
        if nic_op in self.nic_pinst:
9865
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9866
        for key, val in nic_dict.iteritems():
9867
          result.append(("nic.%s/%d" % (key, nic_op), val))
9868

    
9869
    # hvparams changes
9870
    if self.op.hvparams:
9871
      instance.hvparams = self.hv_inst
9872
      for key, val in self.op.hvparams.iteritems():
9873
        result.append(("hv/%s" % key, val))
9874

    
9875
    # beparams changes
9876
    if self.op.beparams:
9877
      instance.beparams = self.be_inst
9878
      for key, val in self.op.beparams.iteritems():
9879
        result.append(("be/%s" % key, val))
9880

    
9881
    # OS change
9882
    if self.op.os_name:
9883
      instance.os = self.op.os_name
9884

    
9885
    # osparams changes
9886
    if self.op.osparams:
9887
      instance.osparams = self.os_inst
9888
      for key, val in self.op.osparams.iteritems():
9889
        result.append(("os/%s" % key, val))
9890

    
9891
    self.cfg.Update(instance, feedback_fn)
9892

    
9893
    return result
9894

    
9895
  _DISK_CONVERSIONS = {
9896
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9897
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9898
    }
9899

    
9900

    
9901
class LUBackupQuery(NoHooksLU):
9902
  """Query the exports list
9903

9904
  """
9905
  REQ_BGL = False
9906

    
9907
  def ExpandNames(self):
9908
    self.needed_locks = {}
9909
    self.share_locks[locking.LEVEL_NODE] = 1
9910
    if not self.op.nodes:
9911
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9912
    else:
9913
      self.needed_locks[locking.LEVEL_NODE] = \
9914
        _GetWantedNodes(self, self.op.nodes)
9915

    
9916
  def Exec(self, feedback_fn):
9917
    """Compute the list of all the exported system images.
9918

9919
    @rtype: dict
9920
    @return: a dictionary with the structure node->(export-list)
9921
        where export-list is a list of the instances exported on
9922
        that node.
9923

9924
    """
9925
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9926
    rpcresult = self.rpc.call_export_list(self.nodes)
9927
    result = {}
9928
    for node in rpcresult:
9929
      if rpcresult[node].fail_msg:
9930
        result[node] = False
9931
      else:
9932
        result[node] = rpcresult[node].payload
9933

    
9934
    return result
9935

    
9936

    
9937
class LUBackupPrepare(NoHooksLU):
9938
  """Prepares an instance for an export and returns useful information.
9939

9940
  """
9941
  REQ_BGL = False
9942

    
9943
  def ExpandNames(self):
9944
    self._ExpandAndLockInstance()
9945

    
9946
  def CheckPrereq(self):
9947
    """Check prerequisites.
9948

9949
    """
9950
    instance_name = self.op.instance_name
9951

    
9952
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9953
    assert self.instance is not None, \
9954
          "Cannot retrieve locked instance %s" % self.op.instance_name
9955
    _CheckNodeOnline(self, self.instance.primary_node)
9956

    
9957
    self._cds = _GetClusterDomainSecret()
9958

    
9959
  def Exec(self, feedback_fn):
9960
    """Prepares an instance for an export.
9961

9962
    """
9963
    instance = self.instance
9964

    
9965
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9966
      salt = utils.GenerateSecret(8)
9967

    
9968
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9969
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9970
                                              constants.RIE_CERT_VALIDITY)
9971
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9972

    
9973
      (name, cert_pem) = result.payload
9974

    
9975
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9976
                                             cert_pem)
9977

    
9978
      return {
9979
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9980
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9981
                          salt),
9982
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9983
        }
9984

    
9985
    return None
9986

    
9987

    
9988
class LUBackupExport(LogicalUnit):
9989
  """Export an instance to an image in the cluster.
9990

9991
  """
9992
  HPATH = "instance-export"
9993
  HTYPE = constants.HTYPE_INSTANCE
9994
  REQ_BGL = False
9995

    
9996
  def CheckArguments(self):
9997
    """Check the arguments.
9998

9999
    """
10000
    self.x509_key_name = self.op.x509_key_name
10001
    self.dest_x509_ca_pem = self.op.destination_x509_ca
10002

    
10003
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
10004
      if not self.x509_key_name:
10005
        raise errors.OpPrereqError("Missing X509 key name for encryption",
10006
                                   errors.ECODE_INVAL)
10007

    
10008
      if not self.dest_x509_ca_pem:
10009
        raise errors.OpPrereqError("Missing destination X509 CA",
10010
                                   errors.ECODE_INVAL)
10011

    
10012
  def ExpandNames(self):
10013
    self._ExpandAndLockInstance()
10014

    
10015
    # Lock all nodes for local exports
10016
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10017
      # FIXME: lock only instance primary and destination node
10018
      #
10019
      # Sad but true, for now we have do lock all nodes, as we don't know where
10020
      # the previous export might be, and in this LU we search for it and
10021
      # remove it from its current node. In the future we could fix this by:
10022
      #  - making a tasklet to search (share-lock all), then create the
10023
      #    new one, then one to remove, after
10024
      #  - removing the removal operation altogether
10025
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10026

    
10027
  def DeclareLocks(self, level):
10028
    """Last minute lock declaration."""
10029
    # All nodes are locked anyway, so nothing to do here.
10030

    
10031
  def BuildHooksEnv(self):
10032
    """Build hooks env.
10033

10034
    This will run on the master, primary node and target node.
10035

10036
    """
10037
    env = {
10038
      "EXPORT_MODE": self.op.mode,
10039
      "EXPORT_NODE": self.op.target_node,
10040
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
10041
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
10042
      # TODO: Generic function for boolean env variables
10043
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
10044
      }
10045

    
10046
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
10047

    
10048
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
10049

    
10050
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10051
      nl.append(self.op.target_node)
10052

    
10053
    return env, nl, nl
10054

    
10055
  def CheckPrereq(self):
10056
    """Check prerequisites.
10057

10058
    This checks that the instance and node names are valid.
10059

10060
    """
10061
    instance_name = self.op.instance_name
10062

    
10063
    self.instance = self.cfg.GetInstanceInfo(instance_name)
10064
    assert self.instance is not None, \
10065
          "Cannot retrieve locked instance %s" % self.op.instance_name
10066
    _CheckNodeOnline(self, self.instance.primary_node)
10067

    
10068
    if (self.op.remove_instance and self.instance.admin_up and
10069
        not self.op.shutdown):
10070
      raise errors.OpPrereqError("Can not remove instance without shutting it"
10071
                                 " down before")
10072

    
10073
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10074
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
10075
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
10076
      assert self.dst_node is not None
10077

    
10078
      _CheckNodeOnline(self, self.dst_node.name)
10079
      _CheckNodeNotDrained(self, self.dst_node.name)
10080

    
10081
      self._cds = None
10082
      self.dest_disk_info = None
10083
      self.dest_x509_ca = None
10084

    
10085
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
10086
      self.dst_node = None
10087

    
10088
      if len(self.op.target_node) != len(self.instance.disks):
10089
        raise errors.OpPrereqError(("Received destination information for %s"
10090
                                    " disks, but instance %s has %s disks") %
10091
                                   (len(self.op.target_node), instance_name,
10092
                                    len(self.instance.disks)),
10093
                                   errors.ECODE_INVAL)
10094

    
10095
      cds = _GetClusterDomainSecret()
10096

    
10097
      # Check X509 key name
10098
      try:
10099
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
10100
      except (TypeError, ValueError), err:
10101
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
10102

    
10103
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
10104
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
10105
                                   errors.ECODE_INVAL)
10106

    
10107
      # Load and verify CA
10108
      try:
10109
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
10110
      except OpenSSL.crypto.Error, err:
10111
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
10112
                                   (err, ), errors.ECODE_INVAL)
10113

    
10114
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
10115
      if errcode is not None:
10116
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
10117
                                   (msg, ), errors.ECODE_INVAL)
10118

    
10119
      self.dest_x509_ca = cert
10120

    
10121
      # Verify target information
10122
      disk_info = []
10123
      for idx, disk_data in enumerate(self.op.target_node):
10124
        try:
10125
          (host, port, magic) = \
10126
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
10127
        except errors.GenericError, err:
10128
          raise errors.OpPrereqError("Target info for disk %s: %s" %
10129
                                     (idx, err), errors.ECODE_INVAL)
10130

    
10131
        disk_info.append((host, port, magic))
10132

    
10133
      assert len(disk_info) == len(self.op.target_node)
10134
      self.dest_disk_info = disk_info
10135

    
10136
    else:
10137
      raise errors.ProgrammerError("Unhandled export mode %r" %
10138
                                   self.op.mode)
10139

    
10140
    # instance disk type verification
10141
    # TODO: Implement export support for file-based disks
10142
    for disk in self.instance.disks:
10143
      if disk.dev_type == constants.LD_FILE:
10144
        raise errors.OpPrereqError("Export not supported for instances with"
10145
                                   " file-based disks", errors.ECODE_INVAL)
10146

    
10147
  def _CleanupExports(self, feedback_fn):
10148
    """Removes exports of current instance from all other nodes.
10149

10150
    If an instance in a cluster with nodes A..D was exported to node C, its
10151
    exports will be removed from the nodes A, B and D.
10152

10153
    """
10154
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
10155

    
10156
    nodelist = self.cfg.GetNodeList()
10157
    nodelist.remove(self.dst_node.name)
10158

    
10159
    # on one-node clusters nodelist will be empty after the removal
10160
    # if we proceed the backup would be removed because OpBackupQuery
10161
    # substitutes an empty list with the full cluster node list.
10162
    iname = self.instance.name
10163
    if nodelist:
10164
      feedback_fn("Removing old exports for instance %s" % iname)
10165
      exportlist = self.rpc.call_export_list(nodelist)
10166
      for node in exportlist:
10167
        if exportlist[node].fail_msg:
10168
          continue
10169
        if iname in exportlist[node].payload:
10170
          msg = self.rpc.call_export_remove(node, iname).fail_msg
10171
          if msg:
10172
            self.LogWarning("Could not remove older export for instance %s"
10173
                            " on node %s: %s", iname, node, msg)
10174

    
10175
  def Exec(self, feedback_fn):
10176
    """Export an instance to an image in the cluster.
10177

10178
    """
10179
    assert self.op.mode in constants.EXPORT_MODES
10180

    
10181
    instance = self.instance
10182
    src_node = instance.primary_node
10183

    
10184
    if self.op.shutdown:
10185
      # shutdown the instance, but not the disks
10186
      feedback_fn("Shutting down instance %s" % instance.name)
10187
      result = self.rpc.call_instance_shutdown(src_node, instance,
10188
                                               self.op.shutdown_timeout)
10189
      # TODO: Maybe ignore failures if ignore_remove_failures is set
10190
      result.Raise("Could not shutdown instance %s on"
10191
                   " node %s" % (instance.name, src_node))
10192

    
10193
    # set the disks ID correctly since call_instance_start needs the
10194
    # correct drbd minor to create the symlinks
10195
    for disk in instance.disks:
10196
      self.cfg.SetDiskID(disk, src_node)
10197

    
10198
    activate_disks = (not instance.admin_up)
10199

    
10200
    if activate_disks:
10201
      # Activate the instance disks if we'exporting a stopped instance
10202
      feedback_fn("Activating disks for %s" % instance.name)
10203
      _StartInstanceDisks(self, instance, None)
10204

    
10205
    try:
10206
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
10207
                                                     instance)
10208

    
10209
      helper.CreateSnapshots()
10210
      try:
10211
        if (self.op.shutdown and instance.admin_up and
10212
            not self.op.remove_instance):
10213
          assert not activate_disks
10214
          feedback_fn("Starting instance %s" % instance.name)
10215
          result = self.rpc.call_instance_start(src_node, instance, None, None)
10216
          msg = result.fail_msg
10217
          if msg:
10218
            feedback_fn("Failed to start instance: %s" % msg)
10219
            _ShutdownInstanceDisks(self, instance)
10220
            raise errors.OpExecError("Could not start instance: %s" % msg)
10221

    
10222
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
10223
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
10224
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
10225
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
10226
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
10227

    
10228
          (key_name, _, _) = self.x509_key_name
10229

    
10230
          dest_ca_pem = \
10231
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
10232
                                            self.dest_x509_ca)
10233

    
10234
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
10235
                                                     key_name, dest_ca_pem,
10236
                                                     timeouts)
10237
      finally:
10238
        helper.Cleanup()
10239

    
10240
      # Check for backwards compatibility
10241
      assert len(dresults) == len(instance.disks)
10242
      assert compat.all(isinstance(i, bool) for i in dresults), \
10243
             "Not all results are boolean: %r" % dresults
10244

    
10245
    finally:
10246
      if activate_disks:
10247
        feedback_fn("Deactivating disks for %s" % instance.name)
10248
        _ShutdownInstanceDisks(self, instance)
10249

    
10250
    if not (compat.all(dresults) and fin_resu):
10251
      failures = []
10252
      if not fin_resu:
10253
        failures.append("export finalization")
10254
      if not compat.all(dresults):
10255
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
10256
                               if not dsk)
10257
        failures.append("disk export: disk(s) %s" % fdsk)
10258

    
10259
      raise errors.OpExecError("Export failed, errors in %s" %
10260
                               utils.CommaJoin(failures))
10261

    
10262
    # At this point, the export was successful, we can cleanup/finish
10263

    
10264
    # Remove instance if requested
10265
    if self.op.remove_instance:
10266
      feedback_fn("Removing instance %s" % instance.name)
10267
      _RemoveInstance(self, feedback_fn, instance,
10268
                      self.op.ignore_remove_failures)
10269

    
10270
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10271
      self._CleanupExports(feedback_fn)
10272

    
10273
    return fin_resu, dresults
10274

    
10275

    
10276
class LUBackupRemove(NoHooksLU):
10277
  """Remove exports related to the named instance.
10278

10279
  """
10280
  REQ_BGL = False
10281

    
10282
  def ExpandNames(self):
10283
    self.needed_locks = {}
10284
    # We need all nodes to be locked in order for RemoveExport to work, but we
10285
    # don't need to lock the instance itself, as nothing will happen to it (and
10286
    # we can remove exports also for a removed instance)
10287
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10288

    
10289
  def Exec(self, feedback_fn):
10290
    """Remove any export.
10291

10292
    """
10293
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
10294
    # If the instance was not found we'll try with the name that was passed in.
10295
    # This will only work if it was an FQDN, though.
10296
    fqdn_warn = False
10297
    if not instance_name:
10298
      fqdn_warn = True
10299
      instance_name = self.op.instance_name
10300

    
10301
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
10302
    exportlist = self.rpc.call_export_list(locked_nodes)
10303
    found = False
10304
    for node in exportlist:
10305
      msg = exportlist[node].fail_msg
10306
      if msg:
10307
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
10308
        continue
10309
      if instance_name in exportlist[node].payload:
10310
        found = True
10311
        result = self.rpc.call_export_remove(node, instance_name)
10312
        msg = result.fail_msg
10313
        if msg:
10314
          logging.error("Could not remove export for instance %s"
10315
                        " on node %s: %s", instance_name, node, msg)
10316

    
10317
    if fqdn_warn and not found:
10318
      feedback_fn("Export not found. If trying to remove an export belonging"
10319
                  " to a deleted instance please use its Fully Qualified"
10320
                  " Domain Name.")
10321

    
10322

    
10323
class LUGroupAdd(LogicalUnit):
10324
  """Logical unit for creating node groups.
10325

10326
  """
10327
  HPATH = "group-add"
10328
  HTYPE = constants.HTYPE_GROUP
10329
  REQ_BGL = False
10330

    
10331
  def ExpandNames(self):
10332
    # We need the new group's UUID here so that we can create and acquire the
10333
    # corresponding lock. Later, in Exec(), we'll indicate to cfg.AddNodeGroup
10334
    # that it should not check whether the UUID exists in the configuration.
10335
    self.group_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
10336
    self.needed_locks = {}
10337
    self.add_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
10338

    
10339
  def CheckPrereq(self):
10340
    """Check prerequisites.
10341

10342
    This checks that the given group name is not an existing node group
10343
    already.
10344

10345
    """
10346
    try:
10347
      existing_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10348
    except errors.OpPrereqError:
10349
      pass
10350
    else:
10351
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
10352
                                 " node group (UUID: %s)" %
10353
                                 (self.op.group_name, existing_uuid),
10354
                                 errors.ECODE_EXISTS)
10355

    
10356
    if self.op.ndparams:
10357
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
10358

    
10359
  def BuildHooksEnv(self):
10360
    """Build hooks env.
10361

10362
    """
10363
    env = {
10364
      "GROUP_NAME": self.op.group_name,
10365
      }
10366
    mn = self.cfg.GetMasterNode()
10367
    return env, [mn], [mn]
10368

    
10369
  def Exec(self, feedback_fn):
10370
    """Add the node group to the cluster.
10371

10372
    """
10373
    group_obj = objects.NodeGroup(name=self.op.group_name, members=[],
10374
                                  uuid=self.group_uuid,
10375
                                  alloc_policy=self.op.alloc_policy,
10376
                                  ndparams=self.op.ndparams)
10377

    
10378
    self.cfg.AddNodeGroup(group_obj, self.proc.GetECId(), check_uuid=False)
10379
    del self.remove_locks[locking.LEVEL_NODEGROUP]
10380

    
10381

    
10382
class LUGroupAssignNodes(NoHooksLU):
10383
  """Logical unit for assigning nodes to groups.
10384

10385
  """
10386
  REQ_BGL = False
10387

    
10388
  def ExpandNames(self):
10389
    # These raise errors.OpPrereqError on their own:
10390
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10391
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
10392

    
10393
    # We want to lock all the affected nodes and groups. We have readily
10394
    # available the list of nodes, and the *destination* group. To gather the
10395
    # list of "source" groups, we need to fetch node information.
10396
    self.node_data = self.cfg.GetAllNodesInfo()
10397
    affected_groups = set(self.node_data[node].group for node in self.op.nodes)
10398
    affected_groups.add(self.group_uuid)
10399

    
10400
    self.needed_locks = {
10401
      locking.LEVEL_NODEGROUP: list(affected_groups),
10402
      locking.LEVEL_NODE: self.op.nodes,
10403
      }
10404

    
10405
  def CheckPrereq(self):
10406
    """Check prerequisites.
10407

10408
    """
10409
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
10410
    instance_data = self.cfg.GetAllInstancesInfo()
10411

    
10412
    if self.group is None:
10413
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10414
                               (self.op.group_name, self.group_uuid))
10415

    
10416
    (new_splits, previous_splits) = \
10417
      self.CheckAssignmentForSplitInstances([(node, self.group_uuid)
10418
                                             for node in self.op.nodes],
10419
                                            self.node_data, instance_data)
10420

    
10421
    if new_splits:
10422
      fmt_new_splits = utils.CommaJoin(utils.NiceSort(new_splits))
10423

    
10424
      if not self.op.force:
10425
        raise errors.OpExecError("The following instances get split by this"
10426
                                 " change and --force was not given: %s" %
10427
                                 fmt_new_splits)
10428
      else:
10429
        self.LogWarning("This operation will split the following instances: %s",
10430
                        fmt_new_splits)
10431

    
10432
        if previous_splits:
10433
          self.LogWarning("In addition, these already-split instances continue"
10434
                          " to be spit across groups: %s",
10435
                          utils.CommaJoin(utils.NiceSort(previous_splits)))
10436

    
10437
  def Exec(self, feedback_fn):
10438
    """Assign nodes to a new group.
10439

10440
    """
10441
    for node in self.op.nodes:
10442
      self.node_data[node].group = self.group_uuid
10443

    
10444
    self.cfg.Update(self.group, feedback_fn) # Saves all modified nodes.
10445

    
10446
  @staticmethod
10447
  def CheckAssignmentForSplitInstances(changes, node_data, instance_data):
10448
    """Check for split instances after a node assignment.
10449

10450
    This method considers a series of node assignments as an atomic operation,
10451
    and returns information about split instances after applying the set of
10452
    changes.
10453

10454
    In particular, it returns information about newly split instances, and
10455
    instances that were already split, and remain so after the change.
10456

10457
    Only instances whose disk template is listed in constants.DTS_INT_MIRROR are
10458
    considered.
10459

10460
    @type changes: list of (node_name, new_group_uuid) pairs.
10461
    @param changes: list of node assignments to consider.
10462
    @param node_data: a dict with data for all nodes
10463
    @param instance_data: a dict with all instances to consider
10464
    @rtype: a two-tuple
10465
    @return: a list of instances that were previously okay and result split as a
10466
      consequence of this change, and a list of instances that were previously
10467
      split and this change does not fix.
10468

10469
    """
10470
    changed_nodes = dict((node, group) for node, group in changes
10471
                         if node_data[node].group != group)
10472

    
10473
    all_split_instances = set()
10474
    previously_split_instances = set()
10475

    
10476
    def InstanceNodes(instance):
10477
      return [instance.primary_node] + list(instance.secondary_nodes)
10478

    
10479
    for inst in instance_data.values():
10480
      if inst.disk_template not in constants.DTS_INT_MIRROR:
10481
        continue
10482

    
10483
      instance_nodes = InstanceNodes(inst)
10484

    
10485
      if len(set(node_data[node].group for node in instance_nodes)) > 1:
10486
        previously_split_instances.add(inst.name)
10487

    
10488
      if len(set(changed_nodes.get(node, node_data[node].group)
10489
                 for node in instance_nodes)) > 1:
10490
        all_split_instances.add(inst.name)
10491

    
10492
    return (list(all_split_instances - previously_split_instances),
10493
            list(previously_split_instances & all_split_instances))
10494

    
10495

    
10496
class _GroupQuery(_QueryBase):
10497

    
10498
  FIELDS = query.GROUP_FIELDS
10499

    
10500
  def ExpandNames(self, lu):
10501
    lu.needed_locks = {}
10502

    
10503
    self._all_groups = lu.cfg.GetAllNodeGroupsInfo()
10504
    name_to_uuid = dict((g.name, g.uuid) for g in self._all_groups.values())
10505

    
10506
    if not self.names:
10507
      self.wanted = [name_to_uuid[name]
10508
                     for name in utils.NiceSort(name_to_uuid.keys())]
10509
    else:
10510
      # Accept names to be either names or UUIDs.
10511
      missing = []
10512
      self.wanted = []
10513
      all_uuid = frozenset(self._all_groups.keys())
10514

    
10515
      for name in self.names:
10516
        if name in all_uuid:
10517
          self.wanted.append(name)
10518
        elif name in name_to_uuid:
10519
          self.wanted.append(name_to_uuid[name])
10520
        else:
10521
          missing.append(name)
10522

    
10523
      if missing:
10524
        raise errors.OpPrereqError("Some groups do not exist: %s" % missing,
10525
                                   errors.ECODE_NOENT)
10526

    
10527
  def DeclareLocks(self, lu, level):
10528
    pass
10529

    
10530
  def _GetQueryData(self, lu):
10531
    """Computes the list of node groups and their attributes.
10532

10533
    """
10534
    do_nodes = query.GQ_NODE in self.requested_data
10535
    do_instances = query.GQ_INST in self.requested_data
10536

    
10537
    group_to_nodes = None
10538
    group_to_instances = None
10539

    
10540
    # For GQ_NODE, we need to map group->[nodes], and group->[instances] for
10541
    # GQ_INST. The former is attainable with just GetAllNodesInfo(), but for the
10542
    # latter GetAllInstancesInfo() is not enough, for we have to go through
10543
    # instance->node. Hence, we will need to process nodes even if we only need
10544
    # instance information.
10545
    if do_nodes or do_instances:
10546
      all_nodes = lu.cfg.GetAllNodesInfo()
10547
      group_to_nodes = dict((uuid, []) for uuid in self.wanted)
10548
      node_to_group = {}
10549

    
10550
      for node in all_nodes.values():
10551
        if node.group in group_to_nodes:
10552
          group_to_nodes[node.group].append(node.name)
10553
          node_to_group[node.name] = node.group
10554

    
10555
      if do_instances:
10556
        all_instances = lu.cfg.GetAllInstancesInfo()
10557
        group_to_instances = dict((uuid, []) for uuid in self.wanted)
10558

    
10559
        for instance in all_instances.values():
10560
          node = instance.primary_node
10561
          if node in node_to_group:
10562
            group_to_instances[node_to_group[node]].append(instance.name)
10563

    
10564
        if not do_nodes:
10565
          # Do not pass on node information if it was not requested.
10566
          group_to_nodes = None
10567

    
10568
    return query.GroupQueryData([self._all_groups[uuid]
10569
                                 for uuid in self.wanted],
10570
                                group_to_nodes, group_to_instances)
10571

    
10572

    
10573
class LUGroupQuery(NoHooksLU):
10574
  """Logical unit for querying node groups.
10575

10576
  """
10577
  REQ_BGL = False
10578

    
10579
  def CheckArguments(self):
10580
    self.gq = _GroupQuery(self.op.names, self.op.output_fields, False)
10581

    
10582
  def ExpandNames(self):
10583
    self.gq.ExpandNames(self)
10584

    
10585
  def Exec(self, feedback_fn):
10586
    return self.gq.OldStyleQuery(self)
10587

    
10588

    
10589
class LUGroupSetParams(LogicalUnit):
10590
  """Modifies the parameters of a node group.
10591

10592
  """
10593
  HPATH = "group-modify"
10594
  HTYPE = constants.HTYPE_GROUP
10595
  REQ_BGL = False
10596

    
10597
  def CheckArguments(self):
10598
    all_changes = [
10599
      self.op.ndparams,
10600
      self.op.alloc_policy,
10601
      ]
10602

    
10603
    if all_changes.count(None) == len(all_changes):
10604
      raise errors.OpPrereqError("Please pass at least one modification",
10605
                                 errors.ECODE_INVAL)
10606

    
10607
  def ExpandNames(self):
10608
    # This raises errors.OpPrereqError on its own:
10609
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10610

    
10611
    self.needed_locks = {
10612
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10613
      }
10614

    
10615
  def CheckPrereq(self):
10616
    """Check prerequisites.
10617

10618
    """
10619
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
10620

    
10621
    if self.group is None:
10622
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10623
                               (self.op.group_name, self.group_uuid))
10624

    
10625
    if self.op.ndparams:
10626
      new_ndparams = _GetUpdatedParams(self.group.ndparams, self.op.ndparams)
10627
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
10628
      self.new_ndparams = new_ndparams
10629

    
10630
  def BuildHooksEnv(self):
10631
    """Build hooks env.
10632

10633
    """
10634
    env = {
10635
      "GROUP_NAME": self.op.group_name,
10636
      "NEW_ALLOC_POLICY": self.op.alloc_policy,
10637
      }
10638
    mn = self.cfg.GetMasterNode()
10639
    return env, [mn], [mn]
10640

    
10641
  def Exec(self, feedback_fn):
10642
    """Modifies the node group.
10643

10644
    """
10645
    result = []
10646

    
10647
    if self.op.ndparams:
10648
      self.group.ndparams = self.new_ndparams
10649
      result.append(("ndparams", str(self.group.ndparams)))
10650

    
10651
    if self.op.alloc_policy:
10652
      self.group.alloc_policy = self.op.alloc_policy
10653

    
10654
    self.cfg.Update(self.group, feedback_fn)
10655
    return result
10656

    
10657

    
10658

    
10659
class LUGroupRemove(LogicalUnit):
10660
  HPATH = "group-remove"
10661
  HTYPE = constants.HTYPE_GROUP
10662
  REQ_BGL = False
10663

    
10664
  def ExpandNames(self):
10665
    # This will raises errors.OpPrereqError on its own:
10666
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10667
    self.needed_locks = {
10668
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10669
      }
10670

    
10671
  def CheckPrereq(self):
10672
    """Check prerequisites.
10673

10674
    This checks that the given group name exists as a node group, that is
10675
    empty (i.e., contains no nodes), and that is not the last group of the
10676
    cluster.
10677

10678
    """
10679
    # Verify that the group is empty.
10680
    group_nodes = [node.name
10681
                   for node in self.cfg.GetAllNodesInfo().values()
10682
                   if node.group == self.group_uuid]
10683

    
10684
    if group_nodes:
10685
      raise errors.OpPrereqError("Group '%s' not empty, has the following"
10686
                                 " nodes: %s" %
10687
                                 (self.op.group_name,
10688
                                  utils.CommaJoin(utils.NiceSort(group_nodes))),
10689
                                 errors.ECODE_STATE)
10690

    
10691
    # Verify the cluster would not be left group-less.
10692
    if len(self.cfg.GetNodeGroupList()) == 1:
10693
      raise errors.OpPrereqError("Group '%s' is the only group,"
10694
                                 " cannot be removed" %
10695
                                 self.op.group_name,
10696
                                 errors.ECODE_STATE)
10697

    
10698
  def BuildHooksEnv(self):
10699
    """Build hooks env.
10700

10701
    """
10702
    env = {
10703
      "GROUP_NAME": self.op.group_name,
10704
      }
10705
    mn = self.cfg.GetMasterNode()
10706
    return env, [mn], [mn]
10707

    
10708
  def Exec(self, feedback_fn):
10709
    """Remove the node group.
10710

10711
    """
10712
    try:
10713
      self.cfg.RemoveNodeGroup(self.group_uuid)
10714
    except errors.ConfigurationError:
10715
      raise errors.OpExecError("Group '%s' with UUID %s disappeared" %
10716
                               (self.op.group_name, self.group_uuid))
10717

    
10718
    self.remove_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
10719

    
10720

    
10721
class LUGroupRename(LogicalUnit):
10722
  HPATH = "group-rename"
10723
  HTYPE = constants.HTYPE_GROUP
10724
  REQ_BGL = False
10725

    
10726
  def ExpandNames(self):
10727
    # This raises errors.OpPrereqError on its own:
10728
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.old_name)
10729

    
10730
    self.needed_locks = {
10731
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10732
      }
10733

    
10734
  def CheckPrereq(self):
10735
    """Check prerequisites.
10736

10737
    This checks that the given old_name exists as a node group, and that
10738
    new_name doesn't.
10739

10740
    """
10741
    try:
10742
      new_name_uuid = self.cfg.LookupNodeGroup(self.op.new_name)
10743
    except errors.OpPrereqError:
10744
      pass
10745
    else:
10746
      raise errors.OpPrereqError("Desired new name '%s' clashes with existing"
10747
                                 " node group (UUID: %s)" %
10748
                                 (self.op.new_name, new_name_uuid),
10749
                                 errors.ECODE_EXISTS)
10750

    
10751
  def BuildHooksEnv(self):
10752
    """Build hooks env.
10753

10754
    """
10755
    env = {
10756
      "OLD_NAME": self.op.old_name,
10757
      "NEW_NAME": self.op.new_name,
10758
      }
10759

    
10760
    mn = self.cfg.GetMasterNode()
10761
    all_nodes = self.cfg.GetAllNodesInfo()
10762
    run_nodes = [mn]
10763
    all_nodes.pop(mn, None)
10764

    
10765
    for node in all_nodes.values():
10766
      if node.group == self.group_uuid:
10767
        run_nodes.append(node.name)
10768

    
10769
    return env, run_nodes, run_nodes
10770

    
10771
  def Exec(self, feedback_fn):
10772
    """Rename the node group.
10773

10774
    """
10775
    group = self.cfg.GetNodeGroup(self.group_uuid)
10776

    
10777
    if group is None:
10778
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10779
                               (self.op.old_name, self.group_uuid))
10780

    
10781
    group.name = self.op.new_name
10782
    self.cfg.Update(group, feedback_fn)
10783

    
10784
    return self.op.new_name
10785

    
10786

    
10787
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
10788
  """Generic tags LU.
10789

10790
  This is an abstract class which is the parent of all the other tags LUs.
10791

10792
  """
10793

    
10794
  def ExpandNames(self):
10795
    self.needed_locks = {}
10796
    if self.op.kind == constants.TAG_NODE:
10797
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
10798
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
10799
    elif self.op.kind == constants.TAG_INSTANCE:
10800
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
10801
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
10802

    
10803
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
10804
    # not possible to acquire the BGL based on opcode parameters)
10805

    
10806
  def CheckPrereq(self):
10807
    """Check prerequisites.
10808

10809
    """
10810
    if self.op.kind == constants.TAG_CLUSTER:
10811
      self.target = self.cfg.GetClusterInfo()
10812
    elif self.op.kind == constants.TAG_NODE:
10813
      self.target = self.cfg.GetNodeInfo(self.op.name)
10814
    elif self.op.kind == constants.TAG_INSTANCE:
10815
      self.target = self.cfg.GetInstanceInfo(self.op.name)
10816
    else:
10817
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
10818
                                 str(self.op.kind), errors.ECODE_INVAL)
10819

    
10820

    
10821
class LUTagsGet(TagsLU):
10822
  """Returns the tags of a given object.
10823

10824
  """
10825
  REQ_BGL = False
10826

    
10827
  def ExpandNames(self):
10828
    TagsLU.ExpandNames(self)
10829

    
10830
    # Share locks as this is only a read operation
10831
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
10832

    
10833
  def Exec(self, feedback_fn):
10834
    """Returns the tag list.
10835

10836
    """
10837
    return list(self.target.GetTags())
10838

    
10839

    
10840
class LUTagsSearch(NoHooksLU):
10841
  """Searches the tags for a given pattern.
10842

10843
  """
10844
  REQ_BGL = False
10845

    
10846
  def ExpandNames(self):
10847
    self.needed_locks = {}
10848

    
10849
  def CheckPrereq(self):
10850
    """Check prerequisites.
10851

10852
    This checks the pattern passed for validity by compiling it.
10853

10854
    """
10855
    try:
10856
      self.re = re.compile(self.op.pattern)
10857
    except re.error, err:
10858
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
10859
                                 (self.op.pattern, err), errors.ECODE_INVAL)
10860

    
10861
  def Exec(self, feedback_fn):
10862
    """Returns the tag list.
10863

10864
    """
10865
    cfg = self.cfg
10866
    tgts = [("/cluster", cfg.GetClusterInfo())]
10867
    ilist = cfg.GetAllInstancesInfo().values()
10868
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
10869
    nlist = cfg.GetAllNodesInfo().values()
10870
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
10871
    results = []
10872
    for path, target in tgts:
10873
      for tag in target.GetTags():
10874
        if self.re.search(tag):
10875
          results.append((path, tag))
10876
    return results
10877

    
10878

    
10879
class LUTagsSet(TagsLU):
10880
  """Sets a tag on a given object.
10881

10882
  """
10883
  REQ_BGL = False
10884

    
10885
  def CheckPrereq(self):
10886
    """Check prerequisites.
10887

10888
    This checks the type and length of the tag name and value.
10889

10890
    """
10891
    TagsLU.CheckPrereq(self)
10892
    for tag in self.op.tags:
10893
      objects.TaggableObject.ValidateTag(tag)
10894

    
10895
  def Exec(self, feedback_fn):
10896
    """Sets the tag.
10897

10898
    """
10899
    try:
10900
      for tag in self.op.tags:
10901
        self.target.AddTag(tag)
10902
    except errors.TagError, err:
10903
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
10904
    self.cfg.Update(self.target, feedback_fn)
10905

    
10906

    
10907
class LUTagsDel(TagsLU):
10908
  """Delete a list of tags from a given object.
10909

10910
  """
10911
  REQ_BGL = False
10912

    
10913
  def CheckPrereq(self):
10914
    """Check prerequisites.
10915

10916
    This checks that we have the given tag.
10917

10918
    """
10919
    TagsLU.CheckPrereq(self)
10920
    for tag in self.op.tags:
10921
      objects.TaggableObject.ValidateTag(tag)
10922
    del_tags = frozenset(self.op.tags)
10923
    cur_tags = self.target.GetTags()
10924

    
10925
    diff_tags = del_tags - cur_tags
10926
    if diff_tags:
10927
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
10928
      raise errors.OpPrereqError("Tag(s) %s not found" %
10929
                                 (utils.CommaJoin(diff_names), ),
10930
                                 errors.ECODE_NOENT)
10931

    
10932
  def Exec(self, feedback_fn):
10933
    """Remove the tag from the object.
10934

10935
    """
10936
    for tag in self.op.tags:
10937
      self.target.RemoveTag(tag)
10938
    self.cfg.Update(self.target, feedback_fn)
10939

    
10940

    
10941
class LUTestDelay(NoHooksLU):
10942
  """Sleep for a specified amount of time.
10943

10944
  This LU sleeps on the master and/or nodes for a specified amount of
10945
  time.
10946

10947
  """
10948
  REQ_BGL = False
10949

    
10950
  def ExpandNames(self):
10951
    """Expand names and set required locks.
10952

10953
    This expands the node list, if any.
10954

10955
    """
10956
    self.needed_locks = {}
10957
    if self.op.on_nodes:
10958
      # _GetWantedNodes can be used here, but is not always appropriate to use
10959
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
10960
      # more information.
10961
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
10962
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
10963

    
10964
  def _TestDelay(self):
10965
    """Do the actual sleep.
10966

10967
    """
10968
    if self.op.on_master:
10969
      if not utils.TestDelay(self.op.duration):
10970
        raise errors.OpExecError("Error during master delay test")
10971
    if self.op.on_nodes:
10972
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
10973
      for node, node_result in result.items():
10974
        node_result.Raise("Failure during rpc call to node %s" % node)
10975

    
10976
  def Exec(self, feedback_fn):
10977
    """Execute the test delay opcode, with the wanted repetitions.
10978

10979
    """
10980
    if self.op.repeat == 0:
10981
      self._TestDelay()
10982
    else:
10983
      top_value = self.op.repeat - 1
10984
      for i in range(self.op.repeat):
10985
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
10986
        self._TestDelay()
10987

    
10988

    
10989
class LUTestJqueue(NoHooksLU):
10990
  """Utility LU to test some aspects of the job queue.
10991

10992
  """
10993
  REQ_BGL = False
10994

    
10995
  # Must be lower than default timeout for WaitForJobChange to see whether it
10996
  # notices changed jobs
10997
  _CLIENT_CONNECT_TIMEOUT = 20.0
10998
  _CLIENT_CONFIRM_TIMEOUT = 60.0
10999

    
11000
  @classmethod
11001
  def _NotifyUsingSocket(cls, cb, errcls):
11002
    """Opens a Unix socket and waits for another program to connect.
11003

11004
    @type cb: callable
11005
    @param cb: Callback to send socket name to client
11006
    @type errcls: class
11007
    @param errcls: Exception class to use for errors
11008

11009
    """
11010
    # Using a temporary directory as there's no easy way to create temporary
11011
    # sockets without writing a custom loop around tempfile.mktemp and
11012
    # socket.bind
11013
    tmpdir = tempfile.mkdtemp()
11014
    try:
11015
      tmpsock = utils.PathJoin(tmpdir, "sock")
11016

    
11017
      logging.debug("Creating temporary socket at %s", tmpsock)
11018
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
11019
      try:
11020
        sock.bind(tmpsock)
11021
        sock.listen(1)
11022

    
11023
        # Send details to client
11024
        cb(tmpsock)
11025

    
11026
        # Wait for client to connect before continuing
11027
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
11028
        try:
11029
          (conn, _) = sock.accept()
11030
        except socket.error, err:
11031
          raise errcls("Client didn't connect in time (%s)" % err)
11032
      finally:
11033
        sock.close()
11034
    finally:
11035
      # Remove as soon as client is connected
11036
      shutil.rmtree(tmpdir)
11037

    
11038
    # Wait for client to close
11039
    try:
11040
      try:
11041
        # pylint: disable-msg=E1101
11042
        # Instance of '_socketobject' has no ... member
11043
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
11044
        conn.recv(1)
11045
      except socket.error, err:
11046
        raise errcls("Client failed to confirm notification (%s)" % err)
11047
    finally:
11048
      conn.close()
11049

    
11050
  def _SendNotification(self, test, arg, sockname):
11051
    """Sends a notification to the client.
11052

11053
    @type test: string
11054
    @param test: Test name
11055
    @param arg: Test argument (depends on test)
11056
    @type sockname: string
11057
    @param sockname: Socket path
11058

11059
    """
11060
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
11061

    
11062
  def _Notify(self, prereq, test, arg):
11063
    """Notifies the client of a test.
11064

11065
    @type prereq: bool
11066
    @param prereq: Whether this is a prereq-phase test
11067
    @type test: string
11068
    @param test: Test name
11069
    @param arg: Test argument (depends on test)
11070

11071
    """
11072
    if prereq:
11073
      errcls = errors.OpPrereqError
11074
    else:
11075
      errcls = errors.OpExecError
11076

    
11077
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
11078
                                                  test, arg),
11079
                                   errcls)
11080

    
11081
  def CheckArguments(self):
11082
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
11083
    self.expandnames_calls = 0
11084

    
11085
  def ExpandNames(self):
11086
    checkargs_calls = getattr(self, "checkargs_calls", 0)
11087
    if checkargs_calls < 1:
11088
      raise errors.ProgrammerError("CheckArguments was not called")
11089

    
11090
    self.expandnames_calls += 1
11091

    
11092
    if self.op.notify_waitlock:
11093
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
11094

    
11095
    self.LogInfo("Expanding names")
11096

    
11097
    # Get lock on master node (just to get a lock, not for a particular reason)
11098
    self.needed_locks = {
11099
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
11100
      }
11101

    
11102
  def Exec(self, feedback_fn):
11103
    if self.expandnames_calls < 1:
11104
      raise errors.ProgrammerError("ExpandNames was not called")
11105

    
11106
    if self.op.notify_exec:
11107
      self._Notify(False, constants.JQT_EXEC, None)
11108

    
11109
    self.LogInfo("Executing")
11110

    
11111
    if self.op.log_messages:
11112
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
11113
      for idx, msg in enumerate(self.op.log_messages):
11114
        self.LogInfo("Sending log message %s", idx + 1)
11115
        feedback_fn(constants.JQT_MSGPREFIX + msg)
11116
        # Report how many test messages have been sent
11117
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
11118

    
11119
    if self.op.fail:
11120
      raise errors.OpExecError("Opcode failure was requested")
11121

    
11122
    return True
11123

    
11124

    
11125
class IAllocator(object):
11126
  """IAllocator framework.
11127

11128
  An IAllocator instance has three sets of attributes:
11129
    - cfg that is needed to query the cluster
11130
    - input data (all members of the _KEYS class attribute are required)
11131
    - four buffer attributes (in|out_data|text), that represent the
11132
      input (to the external script) in text and data structure format,
11133
      and the output from it, again in two formats
11134
    - the result variables from the script (success, info, nodes) for
11135
      easy usage
11136

11137
  """
11138
  # pylint: disable-msg=R0902
11139
  # lots of instance attributes
11140
  _ALLO_KEYS = [
11141
    "name", "mem_size", "disks", "disk_template",
11142
    "os", "tags", "nics", "vcpus", "hypervisor",
11143
    ]
11144
  _RELO_KEYS = [
11145
    "name", "relocate_from",
11146
    ]
11147
  _EVAC_KEYS = [
11148
    "evac_nodes",
11149
    ]
11150

    
11151
  def __init__(self, cfg, rpc, mode, **kwargs):
11152
    self.cfg = cfg
11153
    self.rpc = rpc
11154
    # init buffer variables
11155
    self.in_text = self.out_text = self.in_data = self.out_data = None
11156
    # init all input fields so that pylint is happy
11157
    self.mode = mode
11158
    self.mem_size = self.disks = self.disk_template = None
11159
    self.os = self.tags = self.nics = self.vcpus = None
11160
    self.hypervisor = None
11161
    self.relocate_from = None
11162
    self.name = None
11163
    self.evac_nodes = None
11164
    # computed fields
11165
    self.required_nodes = None
11166
    # init result fields
11167
    self.success = self.info = self.result = None
11168
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
11169
      keyset = self._ALLO_KEYS
11170
      fn = self._AddNewInstance
11171
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
11172
      keyset = self._RELO_KEYS
11173
      fn = self._AddRelocateInstance
11174
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
11175
      keyset = self._EVAC_KEYS
11176
      fn = self._AddEvacuateNodes
11177
    else:
11178
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
11179
                                   " IAllocator" % self.mode)
11180
    for key in kwargs:
11181
      if key not in keyset:
11182
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
11183
                                     " IAllocator" % key)
11184
      setattr(self, key, kwargs[key])
11185

    
11186
    for key in keyset:
11187
      if key not in kwargs:
11188
        raise errors.ProgrammerError("Missing input parameter '%s' to"
11189
                                     " IAllocator" % key)
11190
    self._BuildInputData(fn)
11191

    
11192
  def _ComputeClusterData(self):
11193
    """Compute the generic allocator input data.
11194

11195
    This is the data that is independent of the actual operation.
11196

11197
    """
11198
    cfg = self.cfg
11199
    cluster_info = cfg.GetClusterInfo()
11200
    # cluster data
11201
    data = {
11202
      "version": constants.IALLOCATOR_VERSION,
11203
      "cluster_name": cfg.GetClusterName(),
11204
      "cluster_tags": list(cluster_info.GetTags()),
11205
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
11206
      # we don't have job IDs
11207
      }
11208
    ninfo = cfg.GetAllNodesInfo()
11209
    iinfo = cfg.GetAllInstancesInfo().values()
11210
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
11211

    
11212
    # node data
11213
    node_list = [n.name for n in ninfo.values() if n.vm_capable]
11214

    
11215
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
11216
      hypervisor_name = self.hypervisor
11217
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
11218
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
11219
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
11220
      hypervisor_name = cluster_info.enabled_hypervisors[0]
11221

    
11222
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
11223
                                        hypervisor_name)
11224
    node_iinfo = \
11225
      self.rpc.call_all_instances_info(node_list,
11226
                                       cluster_info.enabled_hypervisors)
11227

    
11228
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
11229

    
11230
    config_ndata = self._ComputeBasicNodeData(ninfo)
11231
    data["nodes"] = self._ComputeDynamicNodeData(ninfo, node_data, node_iinfo,
11232
                                                 i_list, config_ndata)
11233
    assert len(data["nodes"]) == len(ninfo), \
11234
        "Incomplete node data computed"
11235

    
11236
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
11237

    
11238
    self.in_data = data
11239

    
11240
  @staticmethod
11241
  def _ComputeNodeGroupData(cfg):
11242
    """Compute node groups data.
11243

11244
    """
11245
    ng = {}
11246
    for guuid, gdata in cfg.GetAllNodeGroupsInfo().items():
11247
      ng[guuid] = {
11248
        "name": gdata.name,
11249
        "alloc_policy": gdata.alloc_policy,
11250
        }
11251
    return ng
11252

    
11253
  @staticmethod
11254
  def _ComputeBasicNodeData(node_cfg):
11255
    """Compute global node data.
11256

11257
    @rtype: dict
11258
    @returns: a dict of name: (node dict, node config)
11259

11260
    """
11261
    node_results = {}
11262
    for ninfo in node_cfg.values():
11263
      # fill in static (config-based) values
11264
      pnr = {
11265
        "tags": list(ninfo.GetTags()),
11266
        "primary_ip": ninfo.primary_ip,
11267
        "secondary_ip": ninfo.secondary_ip,
11268
        "offline": ninfo.offline,
11269
        "drained": ninfo.drained,
11270
        "master_candidate": ninfo.master_candidate,
11271
        "group": ninfo.group,
11272
        "master_capable": ninfo.master_capable,
11273
        "vm_capable": ninfo.vm_capable,
11274
        }
11275

    
11276
      node_results[ninfo.name] = pnr
11277

    
11278
    return node_results
11279

    
11280
  @staticmethod
11281
  def _ComputeDynamicNodeData(node_cfg, node_data, node_iinfo, i_list,
11282
                              node_results):
11283
    """Compute global node data.
11284

11285
    @param node_results: the basic node structures as filled from the config
11286

11287
    """
11288
    # make a copy of the current dict
11289
    node_results = dict(node_results)
11290
    for nname, nresult in node_data.items():
11291
      assert nname in node_results, "Missing basic data for node %s" % nname
11292
      ninfo = node_cfg[nname]
11293

    
11294
      if not (ninfo.offline or ninfo.drained):
11295
        nresult.Raise("Can't get data for node %s" % nname)
11296
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
11297
                                nname)
11298
        remote_info = nresult.payload
11299

    
11300
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
11301
                     'vg_size', 'vg_free', 'cpu_total']:
11302
          if attr not in remote_info:
11303
            raise errors.OpExecError("Node '%s' didn't return attribute"
11304
                                     " '%s'" % (nname, attr))
11305
          if not isinstance(remote_info[attr], int):
11306
            raise errors.OpExecError("Node '%s' returned invalid value"
11307
                                     " for '%s': %s" %
11308
                                     (nname, attr, remote_info[attr]))
11309
        # compute memory used by primary instances
11310
        i_p_mem = i_p_up_mem = 0
11311
        for iinfo, beinfo in i_list:
11312
          if iinfo.primary_node == nname:
11313
            i_p_mem += beinfo[constants.BE_MEMORY]
11314
            if iinfo.name not in node_iinfo[nname].payload:
11315
              i_used_mem = 0
11316
            else:
11317
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
11318
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
11319
            remote_info['memory_free'] -= max(0, i_mem_diff)
11320

    
11321
            if iinfo.admin_up:
11322
              i_p_up_mem += beinfo[constants.BE_MEMORY]
11323

    
11324
        # compute memory used by instances
11325
        pnr_dyn = {
11326
          "total_memory": remote_info['memory_total'],
11327
          "reserved_memory": remote_info['memory_dom0'],
11328
          "free_memory": remote_info['memory_free'],
11329
          "total_disk": remote_info['vg_size'],
11330
          "free_disk": remote_info['vg_free'],
11331
          "total_cpus": remote_info['cpu_total'],
11332
          "i_pri_memory": i_p_mem,
11333
          "i_pri_up_memory": i_p_up_mem,
11334
          }
11335
        pnr_dyn.update(node_results[nname])
11336
        node_results[nname] = pnr_dyn
11337

    
11338
    return node_results
11339

    
11340
  @staticmethod
11341
  def _ComputeInstanceData(cluster_info, i_list):
11342
    """Compute global instance data.
11343

11344
    """
11345
    instance_data = {}
11346
    for iinfo, beinfo in i_list:
11347
      nic_data = []
11348
      for nic in iinfo.nics:
11349
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
11350
        nic_dict = {"mac": nic.mac,
11351
                    "ip": nic.ip,
11352
                    "mode": filled_params[constants.NIC_MODE],
11353
                    "link": filled_params[constants.NIC_LINK],
11354
                   }
11355
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
11356
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
11357
        nic_data.append(nic_dict)
11358
      pir = {
11359
        "tags": list(iinfo.GetTags()),
11360
        "admin_up": iinfo.admin_up,
11361
        "vcpus": beinfo[constants.BE_VCPUS],
11362
        "memory": beinfo[constants.BE_MEMORY],
11363
        "os": iinfo.os,
11364
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
11365
        "nics": nic_data,
11366
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
11367
        "disk_template": iinfo.disk_template,
11368
        "hypervisor": iinfo.hypervisor,
11369
        }
11370
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
11371
                                                 pir["disks"])
11372
      instance_data[iinfo.name] = pir
11373

    
11374
    return instance_data
11375

    
11376
  def _AddNewInstance(self):
11377
    """Add new instance data to allocator structure.
11378

11379
    This in combination with _AllocatorGetClusterData will create the
11380
    correct structure needed as input for the allocator.
11381

11382
    The checks for the completeness of the opcode must have already been
11383
    done.
11384

11385
    """
11386
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
11387

    
11388
    if self.disk_template in constants.DTS_INT_MIRROR:
11389
      self.required_nodes = 2
11390
    else:
11391
      self.required_nodes = 1
11392
    request = {
11393
      "name": self.name,
11394
      "disk_template": self.disk_template,
11395
      "tags": self.tags,
11396
      "os": self.os,
11397
      "vcpus": self.vcpus,
11398
      "memory": self.mem_size,
11399
      "disks": self.disks,
11400
      "disk_space_total": disk_space,
11401
      "nics": self.nics,
11402
      "required_nodes": self.required_nodes,
11403
      }
11404
    return request
11405

    
11406
  def _AddRelocateInstance(self):
11407
    """Add relocate instance data to allocator structure.
11408

11409
    This in combination with _IAllocatorGetClusterData will create the
11410
    correct structure needed as input for the allocator.
11411

11412
    The checks for the completeness of the opcode must have already been
11413
    done.
11414

11415
    """
11416
    instance = self.cfg.GetInstanceInfo(self.name)
11417
    if instance is None:
11418
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
11419
                                   " IAllocator" % self.name)
11420

    
11421
    if instance.disk_template not in constants.DTS_MIRRORED:
11422
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
11423
                                 errors.ECODE_INVAL)
11424

    
11425
    if instance.disk_template in constants.DTS_INT_MIRROR and \
11426
        len(instance.secondary_nodes) != 1:
11427
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
11428
                                 errors.ECODE_STATE)
11429

    
11430
    self.required_nodes = 1
11431
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
11432
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
11433

    
11434
    request = {
11435
      "name": self.name,
11436
      "disk_space_total": disk_space,
11437
      "required_nodes": self.required_nodes,
11438
      "relocate_from": self.relocate_from,
11439
      }
11440
    return request
11441

    
11442
  def _AddEvacuateNodes(self):
11443
    """Add evacuate nodes data to allocator structure.
11444

11445
    """
11446
    request = {
11447
      "evac_nodes": self.evac_nodes
11448
      }
11449
    return request
11450

    
11451
  def _BuildInputData(self, fn):
11452
    """Build input data structures.
11453

11454
    """
11455
    self._ComputeClusterData()
11456

    
11457
    request = fn()
11458
    request["type"] = self.mode
11459
    self.in_data["request"] = request
11460

    
11461
    self.in_text = serializer.Dump(self.in_data)
11462

    
11463
  def Run(self, name, validate=True, call_fn=None):
11464
    """Run an instance allocator and return the results.
11465

11466
    """
11467
    if call_fn is None:
11468
      call_fn = self.rpc.call_iallocator_runner
11469

    
11470
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
11471
    result.Raise("Failure while running the iallocator script")
11472

    
11473
    self.out_text = result.payload
11474
    if validate:
11475
      self._ValidateResult()
11476

    
11477
  def _ValidateResult(self):
11478
    """Process the allocator results.
11479

11480
    This will process and if successful save the result in
11481
    self.out_data and the other parameters.
11482

11483
    """
11484
    try:
11485
      rdict = serializer.Load(self.out_text)
11486
    except Exception, err:
11487
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
11488

    
11489
    if not isinstance(rdict, dict):
11490
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
11491

    
11492
    # TODO: remove backwards compatiblity in later versions
11493
    if "nodes" in rdict and "result" not in rdict:
11494
      rdict["result"] = rdict["nodes"]
11495
      del rdict["nodes"]
11496

    
11497
    for key in "success", "info", "result":
11498
      if key not in rdict:
11499
        raise errors.OpExecError("Can't parse iallocator results:"
11500
                                 " missing key '%s'" % key)
11501
      setattr(self, key, rdict[key])
11502

    
11503
    if not isinstance(rdict["result"], list):
11504
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
11505
                               " is not a list")
11506
    self.out_data = rdict
11507

    
11508

    
11509
class LUTestAllocator(NoHooksLU):
11510
  """Run allocator tests.
11511

11512
  This LU runs the allocator tests
11513

11514
  """
11515
  def CheckPrereq(self):
11516
    """Check prerequisites.
11517

11518
    This checks the opcode parameters depending on the director and mode test.
11519

11520
    """
11521
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
11522
      for attr in ["mem_size", "disks", "disk_template",
11523
                   "os", "tags", "nics", "vcpus"]:
11524
        if not hasattr(self.op, attr):
11525
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
11526
                                     attr, errors.ECODE_INVAL)
11527
      iname = self.cfg.ExpandInstanceName(self.op.name)
11528
      if iname is not None:
11529
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
11530
                                   iname, errors.ECODE_EXISTS)
11531
      if not isinstance(self.op.nics, list):
11532
        raise errors.OpPrereqError("Invalid parameter 'nics'",
11533
                                   errors.ECODE_INVAL)
11534
      if not isinstance(self.op.disks, list):
11535
        raise errors.OpPrereqError("Invalid parameter 'disks'",
11536
                                   errors.ECODE_INVAL)
11537
      for row in self.op.disks:
11538
        if (not isinstance(row, dict) or
11539
            "size" not in row or
11540
            not isinstance(row["size"], int) or
11541
            "mode" not in row or
11542
            row["mode"] not in ['r', 'w']):
11543
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
11544
                                     " parameter", errors.ECODE_INVAL)
11545
      if self.op.hypervisor is None:
11546
        self.op.hypervisor = self.cfg.GetHypervisorType()
11547
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
11548
      fname = _ExpandInstanceName(self.cfg, self.op.name)
11549
      self.op.name = fname
11550
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
11551
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
11552
      if not hasattr(self.op, "evac_nodes"):
11553
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
11554
                                   " opcode input", errors.ECODE_INVAL)
11555
    else:
11556
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
11557
                                 self.op.mode, errors.ECODE_INVAL)
11558

    
11559
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
11560
      if self.op.allocator is None:
11561
        raise errors.OpPrereqError("Missing allocator name",
11562
                                   errors.ECODE_INVAL)
11563
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
11564
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
11565
                                 self.op.direction, errors.ECODE_INVAL)
11566

    
11567
  def Exec(self, feedback_fn):
11568
    """Run the allocator test.
11569

11570
    """
11571
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
11572
      ial = IAllocator(self.cfg, self.rpc,
11573
                       mode=self.op.mode,
11574
                       name=self.op.name,
11575
                       mem_size=self.op.mem_size,
11576
                       disks=self.op.disks,
11577
                       disk_template=self.op.disk_template,
11578
                       os=self.op.os,
11579
                       tags=self.op.tags,
11580
                       nics=self.op.nics,
11581
                       vcpus=self.op.vcpus,
11582
                       hypervisor=self.op.hypervisor,
11583
                       )
11584
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
11585
      ial = IAllocator(self.cfg, self.rpc,
11586
                       mode=self.op.mode,
11587
                       name=self.op.name,
11588
                       relocate_from=list(self.relocate_from),
11589
                       )
11590
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
11591
      ial = IAllocator(self.cfg, self.rpc,
11592
                       mode=self.op.mode,
11593
                       evac_nodes=self.op.evac_nodes)
11594
    else:
11595
      raise errors.ProgrammerError("Uncatched mode %s in"
11596
                                   " LUTestAllocator.Exec", self.op.mode)
11597

    
11598
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
11599
      result = ial.in_text
11600
    else:
11601
      ial.Run(self.op.allocator, validate=False)
11602
      result = ial.out_text
11603
    return result
11604

    
11605

    
11606
#: Query type implementations
11607
_QUERY_IMPL = {
11608
  constants.QR_INSTANCE: _InstanceQuery,
11609
  constants.QR_NODE: _NodeQuery,
11610
  constants.QR_GROUP: _GroupQuery,
11611
  }
11612

    
11613

    
11614
def _GetQueryImplementation(name):
11615
  """Returns the implemtnation for a query type.
11616

11617
  @param name: Query type, must be one of L{constants.QR_OP_QUERY}
11618

11619
  """
11620
  try:
11621
    return _QUERY_IMPL[name]
11622
  except KeyError:
11623
    raise errors.OpPrereqError("Unknown query resource '%s'" % name,
11624
                               errors.ECODE_INVAL)