Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ f7661f6b

History | View | Annotate | Download (396 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()]]
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 (not 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
      _ErrorIf(instanceconfig.admin_up and not success,
1568
               self.EINSTANCEFAULTYDISK, instance,
1569
               "couldn't retrieve status for disk/%s on %s: %s",
1570
               idx, nname, bdev_status)
1571
      _ErrorIf((instanceconfig.admin_up and success and
1572
                bdev_status.ldisk_status == constants.LDS_FAULTY),
1573
               self.EINSTANCEFAULTYDISK, instance,
1574
               "disk/%s on %s is faulty", idx, nname)
1575

    
1576
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1577
    """Verify if there are any unknown volumes in the cluster.
1578

1579
    The .os, .swap and backup volumes are ignored. All other volumes are
1580
    reported as unknown.
1581

1582
    @type reserved: L{ganeti.utils.FieldSet}
1583
    @param reserved: a FieldSet of reserved volume names
1584

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

    
1597
  def _VerifyOrphanInstances(self, instancelist, node_image):
1598
    """Verify the list of running instances.
1599

1600
    This checks what instances are running but unknown to the cluster.
1601

1602
    """
1603
    for node, n_img in node_image.items():
1604
      for o_inst in n_img.instances:
1605
        test = o_inst not in instancelist
1606
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1607
                      "instance %s on node %s should not exist", o_inst, node)
1608

    
1609
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1610
    """Verify N+1 Memory Resilience.
1611

1612
    Check that if one single node dies we can still start all the
1613
    instances it was primary for.
1614

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

    
1642
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1643
                       master_files):
1644
    """Verifies and computes the node required file checksums.
1645

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

1653
    """
1654
    node = ninfo.name
1655
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1656

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

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

    
1686
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1687
                      drbd_map):
1688
    """Verifies and the node DRBD status.
1689

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

1698
    """
1699
    node = ninfo.name
1700
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1701

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

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

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

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

    
1749
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1750
    """Builds the node OS structures.
1751

1752
    @type ninfo: L{objects.Node}
1753
    @param ninfo: the node to check
1754
    @param nresult: the remote results for the node
1755
    @param nimg: the node image object
1756

1757
    """
1758
    node = ninfo.name
1759
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1760

    
1761
    remote_os = nresult.get(constants.NV_OSLIST, None)
1762
    test = (not isinstance(remote_os, list) or
1763
            not compat.all(isinstance(v, list) and len(v) == 7
1764
                           for v in remote_os))
1765

    
1766
    _ErrorIf(test, self.ENODEOS, node,
1767
             "node hasn't returned valid OS data")
1768

    
1769
    nimg.os_fail = test
1770

    
1771
    if test:
1772
      return
1773

    
1774
    os_dict = {}
1775

    
1776
    for (name, os_path, status, diagnose,
1777
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1778

    
1779
      if name not in os_dict:
1780
        os_dict[name] = []
1781

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

    
1788
    nimg.oslist = os_dict
1789

    
1790
  def _VerifyNodeOS(self, ninfo, nimg, base):
1791
    """Verifies the node OS list.
1792

1793
    @type ninfo: L{objects.Node}
1794
    @param ninfo: the node to check
1795
    @param nimg: the node image object
1796
    @param base: the 'template' node we match against (e.g. from the master)
1797

1798
    """
1799
    node = ninfo.name
1800
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1801

    
1802
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1803

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

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

    
1843
  def _VerifyOob(self, ninfo, nresult):
1844
    """Verifies out of band functionality of a node.
1845

1846
    @type ninfo: L{objects.Node}
1847
    @param ninfo: the node to check
1848
    @param nresult: the remote results for the node
1849

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

    
1859
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1860
    """Verifies and updates the node volume data.
1861

1862
    This function will update a L{NodeImage}'s internal structures
1863
    with data from the remote call.
1864

1865
    @type ninfo: L{objects.Node}
1866
    @param ninfo: the node to check
1867
    @param nresult: the remote results for the node
1868
    @param nimg: the node image object
1869
    @param vg_name: the configured VG name
1870

1871
    """
1872
    node = ninfo.name
1873
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1874

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

    
1888
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1889
    """Verifies and updates the node instance list.
1890

1891
    If the listing was successful, then updates this node's instance
1892
    list. Otherwise, it marks the RPC call as failed for the instance
1893
    list key.
1894

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

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

    
1910
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1911
    """Verifies and computes a node information map
1912

1913
    @type ninfo: L{objects.Node}
1914
    @param ninfo: the node to check
1915
    @param nresult: the remote results for the node
1916
    @param nimg: the node image object
1917
    @param vg_name: the configured VG name
1918

1919
    """
1920
    node = ninfo.name
1921
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1922

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

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

    
1948
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
1949
    """Gets per-disk status information for all instances.
1950

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

1962
    """
1963
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1964

    
1965
    node_disks = {}
1966
    node_disks_devonly = {}
1967
    diskless_instances = set()
1968
    diskless = constants.DT_DISKLESS
1969

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

    
1979
      if not disks:
1980
        # No need to collect data
1981
        continue
1982

    
1983
      node_disks[nname] = disks
1984

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

    
1989
      for dev in devonly:
1990
        self.cfg.SetDiskID(dev, nname)
1991

    
1992
      node_disks_devonly[nname] = devonly
1993

    
1994
    assert len(node_disks) == len(node_disks_devonly)
1995

    
1996
    # Collect data from all nodes with disks
1997
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
1998
                                                          node_disks_devonly)
1999

    
2000
    assert len(result) == len(node_disks)
2001

    
2002
    instdisk = {}
2003

    
2004
    for (nname, nres) in result.items():
2005
      disks = node_disks[nname]
2006

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

    
2027
      for ((inst, _), status) in zip(disks, data):
2028
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
2029

    
2030
    # Add empty entries for diskless instances.
2031
    for inst in diskless_instances:
2032
      assert inst not in instdisk
2033
      instdisk[inst] = {}
2034

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

    
2043
    return instdisk
2044

    
2045
  def _VerifyHVP(self, hvp_data):
2046
    """Verifies locally the syntax of the hypervisor parameters.
2047

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

    
2059

    
2060
  def BuildHooksEnv(self):
2061
    """Build hooks env.
2062

2063
    Cluster-Verify hooks just ran in the post phase and their failure makes
2064
    the output be logged in the verify output and the verification to fail.
2065

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

    
2074
    return env, [], all_nodes
2075

    
2076
  def Exec(self, feedback_fn):
2077
    """Verify integrity of cluster, performing various test on nodes.
2078

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

    
2089
    # Check the cluster certificates
2090
    for cert_filename in constants.ALL_CERT_FILES:
2091
      (errcode, msg) = _VerifyCertificate(cert_filename)
2092
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
2093

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

    
2111
    # FIXME: verify OS list
2112
    # do local checksums
2113
    master_files = [constants.CLUSTER_CONF_FILE]
2114
    master_node = self.master_node = self.cfg.GetMasterNode()
2115
    master_ip = self.cfg.GetMasterIP()
2116

    
2117
    file_names = ssconf.SimpleStore().GetFileList()
2118
    file_names.extend(constants.ALL_CERT_FILES)
2119
    file_names.extend(master_files)
2120
    if cluster.modify_etc_hosts:
2121
      file_names.append(constants.ETC_HOSTS)
2122

    
2123
    local_checksums = utils.FingerprintFiles(file_names)
2124

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

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

    
2164
    if vg_name is not None:
2165
      node_verify_param[constants.NV_VGLIST] = None
2166
      node_verify_param[constants.NV_LVLIST] = vg_name
2167
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2168
      node_verify_param[constants.NV_DRBDLIST] = None
2169

    
2170
    if drbd_helper:
2171
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2172

    
2173
    # Build our expected cluster state
2174
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2175
                                                 name=node.name,
2176
                                                 vm_capable=node.vm_capable))
2177
                      for node in nodeinfo)
2178

    
2179
    # Gather OOB paths
2180
    oob_paths = []
2181
    for node in nodeinfo:
2182
      path = _SupportsOob(self.cfg, node)
2183
      if path and path not in oob_paths:
2184
        oob_paths.append(path)
2185

    
2186
    if oob_paths:
2187
      node_verify_param[constants.NV_OOB_PATHS] = oob_paths
2188

    
2189
    for instance in instancelist:
2190
      inst_config = instanceinfo[instance]
2191

    
2192
      for nname in inst_config.all_nodes:
2193
        if nname not in node_image:
2194
          # ghost node
2195
          gnode = self.NodeImage(name=nname)
2196
          gnode.ghost = True
2197
          node_image[nname] = gnode
2198

    
2199
      inst_config.MapLVsByNode(node_vol_should)
2200

    
2201
      pnode = inst_config.primary_node
2202
      node_image[pnode].pinst.append(instance)
2203

    
2204
      for snode in inst_config.secondary_nodes:
2205
        nimg = node_image[snode]
2206
        nimg.sinst.append(instance)
2207
        if pnode not in nimg.sbp:
2208
          nimg.sbp[pnode] = []
2209
        nimg.sbp[pnode].append(instance)
2210

    
2211
    # At this point, we have the in-memory data structures complete,
2212
    # except for the runtime information, which we'll gather next
2213

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

    
2223
    all_drbd_map = self.cfg.ComputeDRBDMap()
2224

    
2225
    feedback_fn("* Gathering disk information (%s nodes)" % len(nodelist))
2226
    instdisk = self._CollectDiskInfo(nodelist, node_image, instanceinfo)
2227

    
2228
    feedback_fn("* Verifying node status")
2229

    
2230
    refos_img = None
2231

    
2232
    for node_i in nodeinfo:
2233
      node = node_i.name
2234
      nimg = node_image[node]
2235

    
2236
      if node_i.offline:
2237
        if verbose:
2238
          feedback_fn("* Skipping offline node %s" % (node,))
2239
        n_offline += 1
2240
        continue
2241

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

    
2254
      msg = all_nvinfo[node].fail_msg
2255
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2256
      if msg:
2257
        nimg.rpc_fail = True
2258
        continue
2259

    
2260
      nresult = all_nvinfo[node].payload
2261

    
2262
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2263
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2264
      self._VerifyNodeNetwork(node_i, nresult)
2265
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2266
                            master_files)
2267

    
2268
      self._VerifyOob(node_i, nresult)
2269

    
2270
      if nimg.vm_capable:
2271
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2272
        self._VerifyNodeDrbd(node_i, nresult, instanceinfo, drbd_helper,
2273
                             all_drbd_map)
2274

    
2275
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2276
        self._UpdateNodeInstances(node_i, nresult, nimg)
2277
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2278
        self._UpdateNodeOS(node_i, nresult, nimg)
2279
        if not nimg.os_fail:
2280
          if refos_img is None:
2281
            refos_img = nimg
2282
          self._VerifyNodeOS(node_i, nimg, refos_img)
2283

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

    
2293
      pnode = inst_config.primary_node
2294
      pnode_img = node_image[pnode]
2295
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2296
               self.ENODERPC, pnode, "instance %s, connection to"
2297
               " primary node failed", instance)
2298

    
2299
      if pnode_img.offline:
2300
        inst_nodes_offline.append(pnode)
2301

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

    
2310
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2311
               instance, "instance has multiple secondary nodes: %s",
2312
               utils.CommaJoin(inst_config.secondary_nodes),
2313
               code=self.ETYPE_WARNING)
2314

    
2315
      if inst_config.disk_template in constants.DTS_NET_MIRROR:
2316
        pnode = inst_config.primary_node
2317
        instance_nodes = utils.NiceSort(inst_config.all_nodes)
2318
        instance_groups = {}
2319

    
2320
        for node in instance_nodes:
2321
          instance_groups.setdefault(nodeinfo_byname[node].group,
2322
                                     []).append(node)
2323

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

    
2331
        self._ErrorIf(len(instance_groups) > 1, self.EINSTANCESPLITGROUPS,
2332
                      instance, "instance has primary and secondary nodes in"
2333
                      " different groups: %s", utils.CommaJoin(pretty_list),
2334
                      code=self.ETYPE_WARNING)
2335

    
2336
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2337
        i_non_a_balanced.append(instance)
2338

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

    
2344
        if s_img.offline:
2345
          inst_nodes_offline.append(snode)
2346

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

    
2358
    feedback_fn("* Verifying orphan volumes")
2359
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2360
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2361

    
2362
    feedback_fn("* Verifying orphan instances")
2363
    self._VerifyOrphanInstances(instancelist, node_image)
2364

    
2365
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2366
      feedback_fn("* Verifying N+1 Memory redundancy")
2367
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2368

    
2369
    feedback_fn("* Other Notes")
2370
    if i_non_redundant:
2371
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2372
                  % len(i_non_redundant))
2373

    
2374
    if i_non_a_balanced:
2375
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2376
                  % len(i_non_a_balanced))
2377

    
2378
    if n_offline:
2379
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2380

    
2381
    if n_drained:
2382
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2383

    
2384
    return not self.bad
2385

    
2386
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2387
    """Analyze the post-hooks' result
2388

2389
    This method analyses the hook result, handles it, and sends some
2390
    nicely-formatted feedback back to the user.
2391

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

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

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

    
2429
      return lu_result
2430

    
2431

    
2432
class LUClusterVerifyDisks(NoHooksLU):
2433
  """Verifies the cluster disks status.
2434

2435
  """
2436
  REQ_BGL = False
2437

    
2438
  def ExpandNames(self):
2439
    self.needed_locks = {
2440
      locking.LEVEL_NODE: locking.ALL_SET,
2441
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2442
    }
2443
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2444

    
2445
  def Exec(self, feedback_fn):
2446
    """Verify integrity of cluster disks.
2447

2448
    @rtype: tuple of three items
2449
    @return: a tuple of (dict of node-to-node_error, list of instances
2450
        which need activate-disks, dict of instance: (node, volume) for
2451
        missing volumes
2452

2453
    """
2454
    result = res_nodes, res_instances, res_missing = {}, [], {}
2455

    
2456
    nodes = utils.NiceSort(self.cfg.GetVmCapableNodeList())
2457
    instances = self.cfg.GetAllInstancesInfo().values()
2458

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

    
2470
    if not nv_dict:
2471
      return result
2472

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

    
2483
      lvs = node_res.payload
2484
      for lv_name, (_, _, lv_online) in lvs.items():
2485
        inst = nv_dict.pop((node, lv_name), None)
2486
        if (not lv_online and inst is not None
2487
            and inst.name not in res_instances):
2488
          res_instances.append(inst.name)
2489

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

    
2497
    return result
2498

    
2499

    
2500
class LUClusterRepairDiskSizes(NoHooksLU):
2501
  """Verifies the cluster disks sizes.
2502

2503
  """
2504
  REQ_BGL = False
2505

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

    
2525
  def DeclareLocks(self, level):
2526
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2527
      self._LockInstancesNodes(primary_only=True)
2528

    
2529
  def CheckPrereq(self):
2530
    """Check prerequisites.
2531

2532
    This only checks the optional instance list against the existing names.
2533

2534
    """
2535
    if self.wanted_names is None:
2536
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2537

    
2538
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2539
                             in self.wanted_names]
2540

    
2541
  def _EnsureChildSizes(self, disk):
2542
    """Ensure children of the disk have the needed disk size.
2543

2544
    This is valid mainly for DRBD8 and fixes an issue where the
2545
    children have smaller disk size.
2546

2547
    @param disk: an L{ganeti.objects.Disk} object
2548

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

    
2559
      # and we recurse on this child only, not on the metadev
2560
      return self._EnsureChildSizes(fchild) or mismatch
2561
    else:
2562
      return False
2563

    
2564
  def Exec(self, feedback_fn):
2565
    """Verify the size of cluster disks.
2566

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

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

    
2614

    
2615
class LUClusterRename(LogicalUnit):
2616
  """Rename the cluster.
2617

2618
  """
2619
  HPATH = "cluster-rename"
2620
  HTYPE = constants.HTYPE_CLUSTER
2621

    
2622
  def BuildHooksEnv(self):
2623
    """Build hooks env.
2624

2625
    """
2626
    env = {
2627
      "OP_TARGET": self.cfg.GetClusterName(),
2628
      "NEW_NAME": self.op.name,
2629
      }
2630
    mn = self.cfg.GetMasterNode()
2631
    all_nodes = self.cfg.GetNodeList()
2632
    return env, [mn], all_nodes
2633

    
2634
  def CheckPrereq(self):
2635
    """Verify that the passed name is a valid one.
2636

2637
    """
2638
    hostname = netutils.GetHostname(name=self.op.name,
2639
                                    family=self.cfg.GetPrimaryIPFamily())
2640

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

    
2655
    self.op.name = new_name
2656

    
2657
  def Exec(self, feedback_fn):
2658
    """Rename the cluster.
2659

2660
    """
2661
    clustername = self.op.name
2662
    ip = self.ip
2663

    
2664
    # shutdown the master IP
2665
    master = self.cfg.GetMasterNode()
2666
    result = self.rpc.call_node_stop_master(master, False)
2667
    result.Raise("Could not disable the master role")
2668

    
2669
    try:
2670
      cluster = self.cfg.GetClusterInfo()
2671
      cluster.cluster_name = clustername
2672
      cluster.master_ip = ip
2673
      self.cfg.Update(cluster, feedback_fn)
2674

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

    
2690
    return clustername
2691

    
2692

    
2693
class LUClusterSetParams(LogicalUnit):
2694
  """Change the parameters of the cluster.
2695

2696
  """
2697
  HPATH = "cluster-modify"
2698
  HTYPE = constants.HTYPE_CLUSTER
2699
  REQ_BGL = False
2700

    
2701
  def CheckArguments(self):
2702
    """Check parameters
2703

2704
    """
2705
    if self.op.uid_pool:
2706
      uidpool.CheckUidPool(self.op.uid_pool)
2707

    
2708
    if self.op.add_uids:
2709
      uidpool.CheckUidPool(self.op.add_uids)
2710

    
2711
    if self.op.remove_uids:
2712
      uidpool.CheckUidPool(self.op.remove_uids)
2713

    
2714
  def ExpandNames(self):
2715
    # FIXME: in the future maybe other cluster params won't require checking on
2716
    # all nodes to be modified.
2717
    self.needed_locks = {
2718
      locking.LEVEL_NODE: locking.ALL_SET,
2719
    }
2720
    self.share_locks[locking.LEVEL_NODE] = 1
2721

    
2722
  def BuildHooksEnv(self):
2723
    """Build hooks env.
2724

2725
    """
2726
    env = {
2727
      "OP_TARGET": self.cfg.GetClusterName(),
2728
      "NEW_VG_NAME": self.op.vg_name,
2729
      }
2730
    mn = self.cfg.GetMasterNode()
2731
    return env, [mn], [mn]
2732

    
2733
  def CheckPrereq(self):
2734
    """Check prerequisites.
2735

2736
    This checks whether the given params don't conflict and
2737
    if the given volume group is valid.
2738

2739
    """
2740
    if self.op.vg_name is not None and not self.op.vg_name:
2741
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2742
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2743
                                   " instances exist", errors.ECODE_INVAL)
2744

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

    
2751
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2752

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

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

    
2788
    self.cluster = cluster = self.cfg.GetClusterInfo()
2789
    # validate params changes
2790
    if self.op.beparams:
2791
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2792
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2793

    
2794
    if self.op.ndparams:
2795
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
2796
      self.new_ndparams = cluster.SimpleFillND(self.op.ndparams)
2797

    
2798
    if self.op.nicparams:
2799
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2800
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2801
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2802
      nic_errors = []
2803

    
2804
      # check all instances for consistency
2805
      for instance in self.cfg.GetAllInstancesInfo().values():
2806
        for nic_idx, nic in enumerate(instance.nics):
2807
          params_copy = copy.deepcopy(nic.nicparams)
2808
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2809

    
2810
          # check parameter syntax
2811
          try:
2812
            objects.NIC.CheckParameterSyntax(params_filled)
2813
          except errors.ConfigurationError, err:
2814
            nic_errors.append("Instance %s, nic/%d: %s" %
2815
                              (instance.name, nic_idx, err))
2816

    
2817
          # if we're moving instances to routed, check that they have an ip
2818
          target_mode = params_filled[constants.NIC_MODE]
2819
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2820
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2821
                              (instance.name, nic_idx))
2822
      if nic_errors:
2823
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2824
                                   "\n".join(nic_errors))
2825

    
2826
    # hypervisor list/parameters
2827
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2828
    if self.op.hvparams:
2829
      for hv_name, hv_dict in self.op.hvparams.items():
2830
        if hv_name not in self.new_hvparams:
2831
          self.new_hvparams[hv_name] = hv_dict
2832
        else:
2833
          self.new_hvparams[hv_name].update(hv_dict)
2834

    
2835
    # os hypervisor parameters
2836
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2837
    if self.op.os_hvp:
2838
      for os_name, hvs in self.op.os_hvp.items():
2839
        if os_name not in self.new_os_hvp:
2840
          self.new_os_hvp[os_name] = hvs
2841
        else:
2842
          for hv_name, hv_dict in hvs.items():
2843
            if hv_name not in self.new_os_hvp[os_name]:
2844
              self.new_os_hvp[os_name][hv_name] = hv_dict
2845
            else:
2846
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2847

    
2848
    # os parameters
2849
    self.new_osp = objects.FillDict(cluster.osparams, {})
2850
    if self.op.osparams:
2851
      for os_name, osp in self.op.osparams.items():
2852
        if os_name not in self.new_osp:
2853
          self.new_osp[os_name] = {}
2854

    
2855
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2856
                                                  use_none=True)
2857

    
2858
        if not self.new_osp[os_name]:
2859
          # we removed all parameters
2860
          del self.new_osp[os_name]
2861
        else:
2862
          # check the parameter validity (remote check)
2863
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
2864
                         os_name, self.new_osp[os_name])
2865

    
2866
    # changes to the hypervisor list
2867
    if self.op.enabled_hypervisors is not None:
2868
      self.hv_list = self.op.enabled_hypervisors
2869
      for hv in self.hv_list:
2870
        # if the hypervisor doesn't already exist in the cluster
2871
        # hvparams, we initialize it to empty, and then (in both
2872
        # cases) we make sure to fill the defaults, as we might not
2873
        # have a complete defaults list if the hypervisor wasn't
2874
        # enabled before
2875
        if hv not in new_hvp:
2876
          new_hvp[hv] = {}
2877
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2878
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2879
    else:
2880
      self.hv_list = cluster.enabled_hypervisors
2881

    
2882
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2883
      # either the enabled list has changed, or the parameters have, validate
2884
      for hv_name, hv_params in self.new_hvparams.items():
2885
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2886
            (self.op.enabled_hypervisors and
2887
             hv_name in self.op.enabled_hypervisors)):
2888
          # either this is a new hypervisor, or its parameters have changed
2889
          hv_class = hypervisor.GetHypervisor(hv_name)
2890
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2891
          hv_class.CheckParameterSyntax(hv_params)
2892
          _CheckHVParams(self, node_list, hv_name, hv_params)
2893

    
2894
    if self.op.os_hvp:
2895
      # no need to check any newly-enabled hypervisors, since the
2896
      # defaults have already been checked in the above code-block
2897
      for os_name, os_hvp in self.new_os_hvp.items():
2898
        for hv_name, hv_params in os_hvp.items():
2899
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2900
          # we need to fill in the new os_hvp on top of the actual hv_p
2901
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2902
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2903
          hv_class = hypervisor.GetHypervisor(hv_name)
2904
          hv_class.CheckParameterSyntax(new_osp)
2905
          _CheckHVParams(self, node_list, hv_name, new_osp)
2906

    
2907
    if self.op.default_iallocator:
2908
      alloc_script = utils.FindFile(self.op.default_iallocator,
2909
                                    constants.IALLOCATOR_SEARCH_PATH,
2910
                                    os.path.isfile)
2911
      if alloc_script is None:
2912
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
2913
                                   " specified" % self.op.default_iallocator,
2914
                                   errors.ECODE_INVAL)
2915

    
2916
  def Exec(self, feedback_fn):
2917
    """Change the parameters of the cluster.
2918

2919
    """
2920
    if self.op.vg_name is not None:
2921
      new_volume = self.op.vg_name
2922
      if not new_volume:
2923
        new_volume = None
2924
      if new_volume != self.cfg.GetVGName():
2925
        self.cfg.SetVGName(new_volume)
2926
      else:
2927
        feedback_fn("Cluster LVM configuration already in desired"
2928
                    " state, not changing")
2929
    if self.op.drbd_helper is not None:
2930
      new_helper = self.op.drbd_helper
2931
      if not new_helper:
2932
        new_helper = None
2933
      if new_helper != self.cfg.GetDRBDHelper():
2934
        self.cfg.SetDRBDHelper(new_helper)
2935
      else:
2936
        feedback_fn("Cluster DRBD helper already in desired state,"
2937
                    " not changing")
2938
    if self.op.hvparams:
2939
      self.cluster.hvparams = self.new_hvparams
2940
    if self.op.os_hvp:
2941
      self.cluster.os_hvp = self.new_os_hvp
2942
    if self.op.enabled_hypervisors is not None:
2943
      self.cluster.hvparams = self.new_hvparams
2944
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2945
    if self.op.beparams:
2946
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2947
    if self.op.nicparams:
2948
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2949
    if self.op.osparams:
2950
      self.cluster.osparams = self.new_osp
2951
    if self.op.ndparams:
2952
      self.cluster.ndparams = self.new_ndparams
2953

    
2954
    if self.op.candidate_pool_size is not None:
2955
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2956
      # we need to update the pool size here, otherwise the save will fail
2957
      _AdjustCandidatePool(self, [])
2958

    
2959
    if self.op.maintain_node_health is not None:
2960
      self.cluster.maintain_node_health = self.op.maintain_node_health
2961

    
2962
    if self.op.prealloc_wipe_disks is not None:
2963
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
2964

    
2965
    if self.op.add_uids is not None:
2966
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2967

    
2968
    if self.op.remove_uids is not None:
2969
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2970

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

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

    
2977
    if self.op.reserved_lvs is not None:
2978
      self.cluster.reserved_lvs = self.op.reserved_lvs
2979

    
2980
    def helper_os(aname, mods, desc):
2981
      desc += " OS list"
2982
      lst = getattr(self.cluster, aname)
2983
      for key, val in mods:
2984
        if key == constants.DDM_ADD:
2985
          if val in lst:
2986
            feedback_fn("OS %s already in %s, ignoring" % (val, desc))
2987
          else:
2988
            lst.append(val)
2989
        elif key == constants.DDM_REMOVE:
2990
          if val in lst:
2991
            lst.remove(val)
2992
          else:
2993
            feedback_fn("OS %s not found in %s, ignoring" % (val, desc))
2994
        else:
2995
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
2996

    
2997
    if self.op.hidden_os:
2998
      helper_os("hidden_os", self.op.hidden_os, "hidden")
2999

    
3000
    if self.op.blacklisted_os:
3001
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
3002

    
3003
    if self.op.master_netdev:
3004
      master = self.cfg.GetMasterNode()
3005
      feedback_fn("Shutting down master ip on the current netdev (%s)" %
3006
                  self.cluster.master_netdev)
3007
      result = self.rpc.call_node_stop_master(master, False)
3008
      result.Raise("Could not disable the master ip")
3009
      feedback_fn("Changing master_netdev from %s to %s" %
3010
                  (self.cluster.master_netdev, self.op.master_netdev))
3011
      self.cluster.master_netdev = self.op.master_netdev
3012

    
3013
    self.cfg.Update(self.cluster, feedback_fn)
3014

    
3015
    if self.op.master_netdev:
3016
      feedback_fn("Starting the master ip on the new master netdev (%s)" %
3017
                  self.op.master_netdev)
3018
      result = self.rpc.call_node_start_master(master, False, False)
3019
      if result.fail_msg:
3020
        self.LogWarning("Could not re-enable the master ip on"
3021
                        " the master, please restart manually: %s",
3022
                        result.fail_msg)
3023

    
3024

    
3025
def _UploadHelper(lu, nodes, fname):
3026
  """Helper for uploading a file and showing warnings.
3027

3028
  """
3029
  if os.path.exists(fname):
3030
    result = lu.rpc.call_upload_file(nodes, fname)
3031
    for to_node, to_result in result.items():
3032
      msg = to_result.fail_msg
3033
      if msg:
3034
        msg = ("Copy of file %s to node %s failed: %s" %
3035
               (fname, to_node, msg))
3036
        lu.proc.LogWarning(msg)
3037

    
3038

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

3042
  ConfigWriter takes care of distributing the config and ssconf files, but
3043
  there are more files which should be distributed to all nodes. This function
3044
  makes sure those are copied.
3045

3046
  @param lu: calling logical unit
3047
  @param additional_nodes: list of nodes not in the config to distribute to
3048
  @type additional_vm: boolean
3049
  @param additional_vm: whether the additional nodes are vm-capable or not
3050

3051
  """
3052
  # 1. Gather target nodes
3053
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
3054
  dist_nodes = lu.cfg.GetOnlineNodeList()
3055
  nvm_nodes = lu.cfg.GetNonVmCapableNodeList()
3056
  vm_nodes = [name for name in dist_nodes if name not in nvm_nodes]
3057
  if additional_nodes is not None:
3058
    dist_nodes.extend(additional_nodes)
3059
    if additional_vm:
3060
      vm_nodes.extend(additional_nodes)
3061
  if myself.name in dist_nodes:
3062
    dist_nodes.remove(myself.name)
3063
  if myself.name in vm_nodes:
3064
    vm_nodes.remove(myself.name)
3065

    
3066
  # 2. Gather files to distribute
3067
  dist_files = set([constants.ETC_HOSTS,
3068
                    constants.SSH_KNOWN_HOSTS_FILE,
3069
                    constants.RAPI_CERT_FILE,
3070
                    constants.RAPI_USERS_FILE,
3071
                    constants.CONFD_HMAC_KEY,
3072
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
3073
                   ])
3074

    
3075
  vm_files = set()
3076
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
3077
  for hv_name in enabled_hypervisors:
3078
    hv_class = hypervisor.GetHypervisor(hv_name)
3079
    vm_files.update(hv_class.GetAncillaryFiles())
3080

    
3081
  # 3. Perform the files upload
3082
  for fname in dist_files:
3083
    _UploadHelper(lu, dist_nodes, fname)
3084
  for fname in vm_files:
3085
    _UploadHelper(lu, vm_nodes, fname)
3086

    
3087

    
3088
class LUClusterRedistConf(NoHooksLU):
3089
  """Force the redistribution of cluster configuration.
3090

3091
  This is a very simple LU.
3092

3093
  """
3094
  REQ_BGL = False
3095

    
3096
  def ExpandNames(self):
3097
    self.needed_locks = {
3098
      locking.LEVEL_NODE: locking.ALL_SET,
3099
    }
3100
    self.share_locks[locking.LEVEL_NODE] = 1
3101

    
3102
  def Exec(self, feedback_fn):
3103
    """Redistribute the configuration.
3104

3105
    """
3106
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
3107
    _RedistributeAncillaryFiles(self)
3108

    
3109

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

3113
  """
3114
  if not instance.disks or disks is not None and not disks:
3115
    return True
3116

    
3117
  disks = _ExpandCheckDisks(instance, disks)
3118

    
3119
  if not oneshot:
3120
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
3121

    
3122
  node = instance.primary_node
3123

    
3124
  for dev in disks:
3125
    lu.cfg.SetDiskID(dev, node)
3126

    
3127
  # TODO: Convert to utils.Retry
3128

    
3129
  retries = 0
3130
  degr_retries = 10 # in seconds, as we sleep 1 second each time
3131
  while True:
3132
    max_time = 0
3133
    done = True
3134
    cumul_degraded = False
3135
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
3136
    msg = rstats.fail_msg
3137
    if msg:
3138
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
3139
      retries += 1
3140
      if retries >= 10:
3141
        raise errors.RemoteError("Can't contact node %s for mirror data,"
3142
                                 " aborting." % node)
3143
      time.sleep(6)
3144
      continue
3145
    rstats = rstats.payload
3146
    retries = 0
3147
    for i, mstat in enumerate(rstats):
3148
      if mstat is None:
3149
        lu.LogWarning("Can't compute data for node %s/%s",
3150
                           node, disks[i].iv_name)
3151
        continue
3152

    
3153
      cumul_degraded = (cumul_degraded or
3154
                        (mstat.is_degraded and mstat.sync_percent is None))
3155
      if mstat.sync_percent is not None:
3156
        done = False
3157
        if mstat.estimated_time is not None:
3158
          rem_time = ("%s remaining (estimated)" %
3159
                      utils.FormatSeconds(mstat.estimated_time))
3160
          max_time = mstat.estimated_time
3161
        else:
3162
          rem_time = "no time estimate"
3163
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3164
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3165

    
3166
    # if we're done but degraded, let's do a few small retries, to
3167
    # make sure we see a stable and not transient situation; therefore
3168
    # we force restart of the loop
3169
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3170
      logging.info("Degraded disks found, %d retries left", degr_retries)
3171
      degr_retries -= 1
3172
      time.sleep(1)
3173
      continue
3174

    
3175
    if done or oneshot:
3176
      break
3177

    
3178
    time.sleep(min(60, max_time))
3179

    
3180
  if done:
3181
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3182
  return not cumul_degraded
3183

    
3184

    
3185
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3186
  """Check that mirrors are not degraded.
3187

3188
  The ldisk parameter, if True, will change the test from the
3189
  is_degraded attribute (which represents overall non-ok status for
3190
  the device(s)) to the ldisk (representing the local storage status).
3191

3192
  """
3193
  lu.cfg.SetDiskID(dev, node)
3194

    
3195
  result = True
3196

    
3197
  if on_primary or dev.AssembleOnSecondary():
3198
    rstats = lu.rpc.call_blockdev_find(node, dev)
3199
    msg = rstats.fail_msg
3200
    if msg:
3201
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3202
      result = False
3203
    elif not rstats.payload:
3204
      lu.LogWarning("Can't find disk on node %s", node)
3205
      result = False
3206
    else:
3207
      if ldisk:
3208
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3209
      else:
3210
        result = result and not rstats.payload.is_degraded
3211

    
3212
  if dev.children:
3213
    for child in dev.children:
3214
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3215

    
3216
  return result
3217

    
3218

    
3219
class LUOobCommand(NoHooksLU):
3220
  """Logical unit for OOB handling.
3221

3222
  """
3223
  REG_BGL = False
3224

    
3225
  def CheckPrereq(self):
3226
    """Check prerequisites.
3227

3228
    This checks:
3229
     - the node exists in the configuration
3230
     - OOB is supported
3231

3232
    Any errors are signaled by raising errors.OpPrereqError.
3233

3234
    """
3235
    self.nodes = []
3236
    for node_name in self.op.node_names:
3237
      node = self.cfg.GetNodeInfo(node_name)
3238

    
3239
      if node is None:
3240
        raise errors.OpPrereqError("Node %s not found" % node_name,
3241
                                   errors.ECODE_NOENT)
3242
      else:
3243
        self.nodes.append(node)
3244

    
3245
      if (self.op.command == constants.OOB_POWER_OFF and not node.offline):
3246
        raise errors.OpPrereqError(("Cannot power off node %s because it is"
3247
                                    " not marked offline") % node_name,
3248
                                   errors.ECODE_STATE)
3249

    
3250
  def ExpandNames(self):
3251
    """Gather locks we need.
3252

3253
    """
3254
    if self.op.node_names:
3255
      self.op.node_names = [_ExpandNodeName(self.cfg, name)
3256
                            for name in self.op.node_names]
3257
    else:
3258
      self.op.node_names = self.cfg.GetNodeList()
3259

    
3260
    self.needed_locks = {
3261
      locking.LEVEL_NODE: self.op.node_names,
3262
      }
3263

    
3264
  def Exec(self, feedback_fn):
3265
    """Execute OOB and return result if we expect any.
3266

3267
    """
3268
    master_node = self.cfg.GetMasterNode()
3269
    ret = []
3270

    
3271
    for node in self.nodes:
3272
      node_entry = [(constants.RS_NORMAL, node.name)]
3273
      ret.append(node_entry)
3274

    
3275
      oob_program = _SupportsOob(self.cfg, node)
3276

    
3277
      if not oob_program:
3278
        node_entry.append((constants.RS_UNAVAIL, None))
3279
        continue
3280

    
3281
      logging.info("Executing out-of-band command '%s' using '%s' on %s",
3282
                   self.op.command, oob_program, node.name)
3283
      result = self.rpc.call_run_oob(master_node, oob_program,
3284
                                     self.op.command, node.name,
3285
                                     self.op.timeout)
3286

    
3287
      if result.fail_msg:
3288
        self.LogWarning("On node '%s' out-of-band RPC failed with: %s",
3289
                        node.name, result.fail_msg)
3290
        node_entry.append((constants.RS_NODATA, None))
3291
      else:
3292
        try:
3293
          self._CheckPayload(result)
3294
        except errors.OpExecError, err:
3295
          self.LogWarning("The payload returned by '%s' is not valid: %s",
3296
                          node.name, err)
3297
          node_entry.append((constants.RS_NODATA, None))
3298
        else:
3299
          if self.op.command == constants.OOB_HEALTH:
3300
            # For health we should log important events
3301
            for item, status in result.payload:
3302
              if status in [constants.OOB_STATUS_WARNING,
3303
                            constants.OOB_STATUS_CRITICAL]:
3304
                self.LogWarning("On node '%s' item '%s' has status '%s'",
3305
                                node.name, item, status)
3306

    
3307
          if self.op.command == constants.OOB_POWER_ON:
3308
            node.powered = True
3309
          elif self.op.command == constants.OOB_POWER_OFF:
3310
            node.powered = False
3311
          elif self.op.command == constants.OOB_POWER_STATUS:
3312
            powered = result.payload[constants.OOB_POWER_STATUS_POWERED]
3313
            if powered != node.powered:
3314
              logging.warning(("Recorded power state (%s) of node '%s' does not"
3315
                               " match actual power state (%s)"), node.powered,
3316
                              node.name, powered)
3317

    
3318
          # For configuration changing commands we should update the node
3319
          if self.op.command in (constants.OOB_POWER_ON,
3320
                                 constants.OOB_POWER_OFF):
3321
            self.cfg.Update(node, feedback_fn)
3322

    
3323
          node_entry.append((constants.RS_NORMAL, result.payload))
3324

    
3325
    return ret
3326

    
3327
  def _CheckPayload(self, result):
3328
    """Checks if the payload is valid.
3329

3330
    @param result: RPC result
3331
    @raises errors.OpExecError: If payload is not valid
3332

3333
    """
3334
    errs = []
3335
    if self.op.command == constants.OOB_HEALTH:
3336
      if not isinstance(result.payload, list):
3337
        errs.append("command 'health' is expected to return a list but got %s" %
3338
                    type(result.payload))
3339
      else:
3340
        for item, status in result.payload:
3341
          if status not in constants.OOB_STATUSES:
3342
            errs.append("health item '%s' has invalid status '%s'" %
3343
                        (item, status))
3344

    
3345
    if self.op.command == constants.OOB_POWER_STATUS:
3346
      if not isinstance(result.payload, dict):
3347
        errs.append("power-status is expected to return a dict but got %s" %
3348
                    type(result.payload))
3349

    
3350
    if self.op.command in [
3351
        constants.OOB_POWER_ON,
3352
        constants.OOB_POWER_OFF,
3353
        constants.OOB_POWER_CYCLE,
3354
        ]:
3355
      if result.payload is not None:
3356
        errs.append("%s is expected to not return payload but got '%s'" %
3357
                    (self.op.command, result.payload))
3358

    
3359
    if errs:
3360
      raise errors.OpExecError("Check of out-of-band payload failed due to %s" %
3361
                               utils.CommaJoin(errs))
3362

    
3363

    
3364

    
3365
class LUOsDiagnose(NoHooksLU):
3366
  """Logical unit for OS diagnose/query.
3367

3368
  """
3369
  REQ_BGL = False
3370
  _HID = "hidden"
3371
  _BLK = "blacklisted"
3372
  _VLD = "valid"
3373
  _FIELDS_STATIC = utils.FieldSet()
3374
  _FIELDS_DYNAMIC = utils.FieldSet("name", _VLD, "node_status", "variants",
3375
                                   "parameters", "api_versions", _HID, _BLK)
3376

    
3377
  def CheckArguments(self):
3378
    if self.op.names:
3379
      raise errors.OpPrereqError("Selective OS query not supported",
3380
                                 errors.ECODE_INVAL)
3381

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

    
3386
  def ExpandNames(self):
3387
    # Lock all nodes, in shared mode
3388
    # Temporary removal of locks, should be reverted later
3389
    # TODO: reintroduce locks when they are lighter-weight
3390
    self.needed_locks = {}
3391
    #self.share_locks[locking.LEVEL_NODE] = 1
3392
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3393

    
3394
  @staticmethod
3395
  def _DiagnoseByOS(rlist):
3396
    """Remaps a per-node return list into an a per-os per-node dictionary
3397

3398
    @param rlist: a map with node names as keys and OS objects as values
3399

3400
    @rtype: dict
3401
    @return: a dictionary with osnames as keys and as value another
3402
        map, with nodes as keys and tuples of (path, status, diagnose,
3403
        variants, parameters, api_versions) as values, eg::
3404

3405
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3406
                                     (/srv/..., False, "invalid api")],
3407
                           "node2": [(/srv/..., True, "", [], [])]}
3408
          }
3409

3410
    """
3411
    all_os = {}
3412
    # we build here the list of nodes that didn't fail the RPC (at RPC
3413
    # level), so that nodes with a non-responding node daemon don't
3414
    # make all OSes invalid
3415
    good_nodes = [node_name for node_name in rlist
3416
                  if not rlist[node_name].fail_msg]
3417
    for node_name, nr in rlist.items():
3418
      if nr.fail_msg or not nr.payload:
3419
        continue
3420
      for (name, path, status, diagnose, variants,
3421
           params, api_versions) in nr.payload:
3422
        if name not in all_os:
3423
          # build a list of nodes for this os containing empty lists
3424
          # for each node in node_list
3425
          all_os[name] = {}
3426
          for nname in good_nodes:
3427
            all_os[name][nname] = []
3428
        # convert params from [name, help] to (name, help)
3429
        params = [tuple(v) for v in params]
3430
        all_os[name][node_name].append((path, status, diagnose,
3431
                                        variants, params, api_versions))
3432
    return all_os
3433

    
3434
  def Exec(self, feedback_fn):
3435
    """Compute the list of OSes.
3436

3437
    """
3438
    valid_nodes = [node.name
3439
                   for node in self.cfg.GetAllNodesInfo().values()
3440
                   if not node.offline and node.vm_capable]
3441
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3442
    pol = self._DiagnoseByOS(node_data)
3443
    output = []
3444
    cluster = self.cfg.GetClusterInfo()
3445

    
3446
    for os_name in utils.NiceSort(pol.keys()):
3447
      os_data = pol[os_name]
3448
      row = []
3449
      valid = True
3450
      (variants, params, api_versions) = null_state = (set(), set(), set())
3451
      for idx, osl in enumerate(os_data.values()):
3452
        valid = bool(valid and osl and osl[0][1])
3453
        if not valid:
3454
          (variants, params, api_versions) = null_state
3455
          break
3456
        node_variants, node_params, node_api = osl[0][3:6]
3457
        if idx == 0: # first entry
3458
          variants = set(node_variants)
3459
          params = set(node_params)
3460
          api_versions = set(node_api)
3461
        else: # keep consistency
3462
          variants.intersection_update(node_variants)
3463
          params.intersection_update(node_params)
3464
          api_versions.intersection_update(node_api)
3465

    
3466
      is_hid = os_name in cluster.hidden_os
3467
      is_blk = os_name in cluster.blacklisted_os
3468
      if ((self._HID not in self.op.output_fields and is_hid) or
3469
          (self._BLK not in self.op.output_fields and is_blk) or
3470
          (self._VLD not in self.op.output_fields and not valid)):
3471
        continue
3472

    
3473
      for field in self.op.output_fields:
3474
        if field == "name":
3475
          val = os_name
3476
        elif field == self._VLD:
3477
          val = valid
3478
        elif field == "node_status":
3479
          # this is just a copy of the dict
3480
          val = {}
3481
          for node_name, nos_list in os_data.items():
3482
            val[node_name] = nos_list
3483
        elif field == "variants":
3484
          val = utils.NiceSort(list(variants))
3485
        elif field == "parameters":
3486
          val = list(params)
3487
        elif field == "api_versions":
3488
          val = list(api_versions)
3489
        elif field == self._HID:
3490
          val = is_hid
3491
        elif field == self._BLK:
3492
          val = is_blk
3493
        else:
3494
          raise errors.ParameterError(field)
3495
        row.append(val)
3496
      output.append(row)
3497

    
3498
    return output
3499

    
3500

    
3501
class LUNodeRemove(LogicalUnit):
3502
  """Logical unit for removing a node.
3503

3504
  """
3505
  HPATH = "node-remove"
3506
  HTYPE = constants.HTYPE_NODE
3507

    
3508
  def BuildHooksEnv(self):
3509
    """Build hooks env.
3510

3511
    This doesn't run on the target node in the pre phase as a failed
3512
    node would then be impossible to remove.
3513

3514
    """
3515
    env = {
3516
      "OP_TARGET": self.op.node_name,
3517
      "NODE_NAME": self.op.node_name,
3518
      }
3519
    all_nodes = self.cfg.GetNodeList()
3520
    try:
3521
      all_nodes.remove(self.op.node_name)
3522
    except ValueError:
3523
      logging.warning("Node %s which is about to be removed not found"
3524
                      " in the all nodes list", self.op.node_name)
3525
    return env, all_nodes, all_nodes
3526

    
3527
  def CheckPrereq(self):
3528
    """Check prerequisites.
3529

3530
    This checks:
3531
     - the node exists in the configuration
3532
     - it does not have primary or secondary instances
3533
     - it's not the master
3534

3535
    Any errors are signaled by raising errors.OpPrereqError.
3536

3537
    """
3538
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3539
    node = self.cfg.GetNodeInfo(self.op.node_name)
3540
    assert node is not None
3541

    
3542
    instance_list = self.cfg.GetInstanceList()
3543

    
3544
    masternode = self.cfg.GetMasterNode()
3545
    if node.name == masternode:
3546
      raise errors.OpPrereqError("Node is the master node,"
3547
                                 " you need to failover first.",
3548
                                 errors.ECODE_INVAL)
3549

    
3550
    for instance_name in instance_list:
3551
      instance = self.cfg.GetInstanceInfo(instance_name)
3552
      if node.name in instance.all_nodes:
3553
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3554
                                   " please remove first." % instance_name,
3555
                                   errors.ECODE_INVAL)
3556
    self.op.node_name = node.name
3557
    self.node = node
3558

    
3559
  def Exec(self, feedback_fn):
3560
    """Removes the node from the cluster.
3561

3562
    """
3563
    node = self.node
3564
    logging.info("Stopping the node daemon and removing configs from node %s",
3565
                 node.name)
3566

    
3567
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3568

    
3569
    # Promote nodes to master candidate as needed
3570
    _AdjustCandidatePool(self, exceptions=[node.name])
3571
    self.context.RemoveNode(node.name)
3572

    
3573
    # Run post hooks on the node before it's removed
3574
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3575
    try:
3576
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3577
    except:
3578
      # pylint: disable-msg=W0702
3579
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3580

    
3581
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3582
    msg = result.fail_msg
3583
    if msg:
3584
      self.LogWarning("Errors encountered on the remote node while leaving"
3585
                      " the cluster: %s", msg)
3586

    
3587
    # Remove node from our /etc/hosts
3588
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3589
      master_node = self.cfg.GetMasterNode()
3590
      result = self.rpc.call_etc_hosts_modify(master_node,
3591
                                              constants.ETC_HOSTS_REMOVE,
3592
                                              node.name, None)
3593
      result.Raise("Can't update hosts file with new host data")
3594
      _RedistributeAncillaryFiles(self)
3595

    
3596

    
3597
class _NodeQuery(_QueryBase):
3598
  FIELDS = query.NODE_FIELDS
3599

    
3600
  def ExpandNames(self, lu):
3601
    lu.needed_locks = {}
3602
    lu.share_locks[locking.LEVEL_NODE] = 1
3603

    
3604
    if self.names:
3605
      self.wanted = _GetWantedNodes(lu, self.names)
3606
    else:
3607
      self.wanted = locking.ALL_SET
3608

    
3609
    self.do_locking = (self.use_locking and
3610
                       query.NQ_LIVE in self.requested_data)
3611

    
3612
    if self.do_locking:
3613
      # if we don't request only static fields, we need to lock the nodes
3614
      lu.needed_locks[locking.LEVEL_NODE] = self.wanted
3615

    
3616
  def DeclareLocks(self, lu, level):
3617
    pass
3618

    
3619
  def _GetQueryData(self, lu):
3620
    """Computes the list of nodes and their attributes.
3621

3622
    """
3623
    all_info = lu.cfg.GetAllNodesInfo()
3624

    
3625
    nodenames = self._GetNames(lu, all_info.keys(), locking.LEVEL_NODE)
3626

    
3627
    # Gather data as requested
3628
    if query.NQ_LIVE in self.requested_data:
3629
      node_data = lu.rpc.call_node_info(nodenames, lu.cfg.GetVGName(),
3630
                                        lu.cfg.GetHypervisorType())
3631
      live_data = dict((name, nresult.payload)
3632
                       for (name, nresult) in node_data.items()
3633
                       if not nresult.fail_msg and nresult.payload)
3634
    else:
3635
      live_data = None
3636

    
3637
    if query.NQ_INST in self.requested_data:
3638
      node_to_primary = dict([(name, set()) for name in nodenames])
3639
      node_to_secondary = dict([(name, set()) for name in nodenames])
3640

    
3641
      inst_data = lu.cfg.GetAllInstancesInfo()
3642

    
3643
      for inst in inst_data.values():
3644
        if inst.primary_node in node_to_primary:
3645
          node_to_primary[inst.primary_node].add(inst.name)
3646
        for secnode in inst.secondary_nodes:
3647
          if secnode in node_to_secondary:
3648
            node_to_secondary[secnode].add(inst.name)
3649
    else:
3650
      node_to_primary = None
3651
      node_to_secondary = None
3652

    
3653
    if query.NQ_OOB in self.requested_data:
3654
      oob_support = dict((name, bool(_SupportsOob(lu.cfg, node)))
3655
                         for name, node in all_info.iteritems())
3656
    else:
3657
      oob_support = None
3658

    
3659
    if query.NQ_GROUP in self.requested_data:
3660
      groups = lu.cfg.GetAllNodeGroupsInfo()
3661
    else:
3662
      groups = {}
3663

    
3664
    return query.NodeQueryData([all_info[name] for name in nodenames],
3665
                               live_data, lu.cfg.GetMasterNode(),
3666
                               node_to_primary, node_to_secondary, groups,
3667
                               oob_support, lu.cfg.GetClusterInfo())
3668

    
3669

    
3670
class LUNodeQuery(NoHooksLU):
3671
  """Logical unit for querying nodes.
3672

3673
  """
3674
  # pylint: disable-msg=W0142
3675
  REQ_BGL = False
3676

    
3677
  def CheckArguments(self):
3678
    self.nq = _NodeQuery(self.op.names, self.op.output_fields,
3679
                         self.op.use_locking)
3680

    
3681
  def ExpandNames(self):
3682
    self.nq.ExpandNames(self)
3683

    
3684
  def Exec(self, feedback_fn):
3685
    return self.nq.OldStyleQuery(self)
3686

    
3687

    
3688
class LUNodeQueryvols(NoHooksLU):
3689
  """Logical unit for getting volumes on node(s).
3690

3691
  """
3692
  REQ_BGL = False
3693
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3694
  _FIELDS_STATIC = utils.FieldSet("node")
3695

    
3696
  def CheckArguments(self):
3697
    _CheckOutputFields(static=self._FIELDS_STATIC,
3698
                       dynamic=self._FIELDS_DYNAMIC,
3699
                       selected=self.op.output_fields)
3700

    
3701
  def ExpandNames(self):
3702
    self.needed_locks = {}
3703
    self.share_locks[locking.LEVEL_NODE] = 1
3704
    if not self.op.nodes:
3705
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3706
    else:
3707
      self.needed_locks[locking.LEVEL_NODE] = \
3708
        _GetWantedNodes(self, self.op.nodes)
3709

    
3710
  def Exec(self, feedback_fn):
3711
    """Computes the list of nodes and their attributes.
3712

3713
    """
3714
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3715
    volumes = self.rpc.call_node_volumes(nodenames)
3716

    
3717
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3718
             in self.cfg.GetInstanceList()]
3719

    
3720
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3721

    
3722
    output = []
3723
    for node in nodenames:
3724
      nresult = volumes[node]
3725
      if nresult.offline:
3726
        continue
3727
      msg = nresult.fail_msg
3728
      if msg:
3729
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3730
        continue
3731

    
3732
      node_vols = nresult.payload[:]
3733
      node_vols.sort(key=lambda vol: vol['dev'])
3734

    
3735
      for vol in node_vols:
3736
        node_output = []
3737
        for field in self.op.output_fields:
3738
          if field == "node":
3739
            val = node
3740
          elif field == "phys":
3741
            val = vol['dev']
3742
          elif field == "vg":
3743
            val = vol['vg']
3744
          elif field == "name":
3745
            val = vol['name']
3746
          elif field == "size":
3747
            val = int(float(vol['size']))
3748
          elif field == "instance":
3749
            for inst in ilist:
3750
              if node not in lv_by_node[inst]:
3751
                continue
3752
              if vol['name'] in lv_by_node[inst][node]:
3753
                val = inst.name
3754
                break
3755
            else:
3756
              val = '-'
3757
          else:
3758
            raise errors.ParameterError(field)
3759
          node_output.append(str(val))
3760

    
3761
        output.append(node_output)
3762

    
3763
    return output
3764

    
3765

    
3766
class LUNodeQueryStorage(NoHooksLU):
3767
  """Logical unit for getting information on storage units on node(s).
3768

3769
  """
3770
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3771
  REQ_BGL = False
3772

    
3773
  def CheckArguments(self):
3774
    _CheckOutputFields(static=self._FIELDS_STATIC,
3775
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3776
                       selected=self.op.output_fields)
3777

    
3778
  def ExpandNames(self):
3779
    self.needed_locks = {}
3780
    self.share_locks[locking.LEVEL_NODE] = 1
3781

    
3782
    if self.op.nodes:
3783
      self.needed_locks[locking.LEVEL_NODE] = \
3784
        _GetWantedNodes(self, self.op.nodes)
3785
    else:
3786
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3787

    
3788
  def Exec(self, feedback_fn):
3789
    """Computes the list of nodes and their attributes.
3790

3791
    """
3792
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3793

    
3794
    # Always get name to sort by
3795
    if constants.SF_NAME in self.op.output_fields:
3796
      fields = self.op.output_fields[:]
3797
    else:
3798
      fields = [constants.SF_NAME] + self.op.output_fields
3799

    
3800
    # Never ask for node or type as it's only known to the LU
3801
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3802
      while extra in fields:
3803
        fields.remove(extra)
3804

    
3805
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3806
    name_idx = field_idx[constants.SF_NAME]
3807

    
3808
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3809
    data = self.rpc.call_storage_list(self.nodes,
3810
                                      self.op.storage_type, st_args,
3811
                                      self.op.name, fields)
3812

    
3813
    result = []
3814

    
3815
    for node in utils.NiceSort(self.nodes):
3816
      nresult = data[node]
3817
      if nresult.offline:
3818
        continue
3819

    
3820
      msg = nresult.fail_msg
3821
      if msg:
3822
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3823
        continue
3824

    
3825
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3826

    
3827
      for name in utils.NiceSort(rows.keys()):
3828
        row = rows[name]
3829

    
3830
        out = []
3831

    
3832
        for field in self.op.output_fields:
3833
          if field == constants.SF_NODE:
3834
            val = node
3835
          elif field == constants.SF_TYPE:
3836
            val = self.op.storage_type
3837
          elif field in field_idx:
3838
            val = row[field_idx[field]]
3839
          else:
3840
            raise errors.ParameterError(field)
3841

    
3842
          out.append(val)
3843

    
3844
        result.append(out)
3845

    
3846
    return result
3847

    
3848

    
3849
class _InstanceQuery(_QueryBase):
3850
  FIELDS = query.INSTANCE_FIELDS
3851

    
3852
  def ExpandNames(self, lu):
3853
    lu.needed_locks = {}
3854
    lu.share_locks[locking.LEVEL_INSTANCE] = 1
3855
    lu.share_locks[locking.LEVEL_NODE] = 1
3856

    
3857
    if self.names:
3858
      self.wanted = _GetWantedInstances(lu, self.names)
3859
    else:
3860
      self.wanted = locking.ALL_SET
3861

    
3862
    self.do_locking = (self.use_locking and
3863
                       query.IQ_LIVE in self.requested_data)
3864
    if self.do_locking:
3865
      lu.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
3866
      lu.needed_locks[locking.LEVEL_NODE] = []
3867
      lu.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3868

    
3869
  def DeclareLocks(self, lu, level):
3870
    if level == locking.LEVEL_NODE and self.do_locking:
3871
      lu._LockInstancesNodes() # pylint: disable-msg=W0212
3872

    
3873
  def _GetQueryData(self, lu):
3874
    """Computes the list of instances and their attributes.
3875

3876
    """
3877
    cluster = lu.cfg.GetClusterInfo()
3878
    all_info = lu.cfg.GetAllInstancesInfo()
3879

    
3880
    instance_names = self._GetNames(lu, all_info.keys(), locking.LEVEL_INSTANCE)
3881

    
3882
    instance_list = [all_info[name] for name in instance_names]
3883
    nodes = frozenset(itertools.chain(*(inst.all_nodes
3884
                                        for inst in instance_list)))
3885
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
3886
    bad_nodes = []
3887
    offline_nodes = []
3888
    wrongnode_inst = set()
3889

    
3890
    # Gather data as requested
3891
    if self.requested_data & set([query.IQ_LIVE, query.IQ_CONSOLE]):
3892
      live_data = {}
3893
      node_data = lu.rpc.call_all_instances_info(nodes, hv_list)
3894
      for name in nodes:
3895
        result = node_data[name]
3896
        if result.offline:
3897
          # offline nodes will be in both lists
3898
          assert result.fail_msg
3899
          offline_nodes.append(name)
3900
        if result.fail_msg:
3901
          bad_nodes.append(name)
3902
        elif result.payload:
3903
          for inst in result.payload:
3904
            if all_info[inst].primary_node == name:
3905
              live_data.update(result.payload)
3906
            else:
3907
              wrongnode_inst.add(inst)
3908
        # else no instance is alive
3909
    else:
3910
      live_data = {}
3911

    
3912
    if query.IQ_DISKUSAGE in self.requested_data:
3913
      disk_usage = dict((inst.name,
3914
                         _ComputeDiskSize(inst.disk_template,
3915
                                          [{"size": disk.size}
3916
                                           for disk in inst.disks]))
3917
                        for inst in instance_list)
3918
    else:
3919
      disk_usage = None
3920

    
3921
    if query.IQ_CONSOLE in self.requested_data:
3922
      consinfo = {}
3923
      for inst in instance_list:
3924
        if inst.name in live_data:
3925
          # Instance is running
3926
          consinfo[inst.name] = _GetInstanceConsole(cluster, inst)
3927
        else:
3928
          consinfo[inst.name] = None
3929
      assert set(consinfo.keys()) == set(instance_names)
3930
    else:
3931
      consinfo = None
3932

    
3933
    return query.InstanceQueryData(instance_list, lu.cfg.GetClusterInfo(),
3934
                                   disk_usage, offline_nodes, bad_nodes,
3935
                                   live_data, wrongnode_inst, consinfo)
3936

    
3937

    
3938
class LUQuery(NoHooksLU):
3939
  """Query for resources/items of a certain kind.
3940

3941
  """
3942
  # pylint: disable-msg=W0142
3943
  REQ_BGL = False
3944

    
3945
  def CheckArguments(self):
3946
    qcls = _GetQueryImplementation(self.op.what)
3947
    names = qlang.ReadSimpleFilter("name", self.op.filter)
3948

    
3949
    self.impl = qcls(names, self.op.fields, False)
3950

    
3951
  def ExpandNames(self):
3952
    self.impl.ExpandNames(self)
3953

    
3954
  def DeclareLocks(self, level):
3955
    self.impl.DeclareLocks(self, level)
3956

    
3957
  def Exec(self, feedback_fn):
3958
    return self.impl.NewStyleQuery(self)
3959

    
3960

    
3961
class LUQueryFields(NoHooksLU):
3962
  """Query for resources/items of a certain kind.
3963

3964
  """
3965
  # pylint: disable-msg=W0142
3966
  REQ_BGL = False
3967

    
3968
  def CheckArguments(self):
3969
    self.qcls = _GetQueryImplementation(self.op.what)
3970

    
3971
  def ExpandNames(self):
3972
    self.needed_locks = {}
3973

    
3974
  def Exec(self, feedback_fn):
3975
    return self.qcls.FieldsQuery(self.op.fields)
3976

    
3977

    
3978
class LUNodeModifyStorage(NoHooksLU):
3979
  """Logical unit for modifying a storage volume on a node.
3980

3981
  """
3982
  REQ_BGL = False
3983

    
3984
  def CheckArguments(self):
3985
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3986

    
3987
    storage_type = self.op.storage_type
3988

    
3989
    try:
3990
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3991
    except KeyError:
3992
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3993
                                 " modified" % storage_type,
3994
                                 errors.ECODE_INVAL)
3995

    
3996
    diff = set(self.op.changes.keys()) - modifiable
3997
    if diff:
3998
      raise errors.OpPrereqError("The following fields can not be modified for"
3999
                                 " storage units of type '%s': %r" %
4000
                                 (storage_type, list(diff)),
4001
                                 errors.ECODE_INVAL)
4002

    
4003
  def ExpandNames(self):
4004
    self.needed_locks = {
4005
      locking.LEVEL_NODE: self.op.node_name,
4006
      }
4007

    
4008
  def Exec(self, feedback_fn):
4009
    """Computes the list of nodes and their attributes.
4010

4011
    """
4012
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4013
    result = self.rpc.call_storage_modify(self.op.node_name,
4014
                                          self.op.storage_type, st_args,
4015
                                          self.op.name, self.op.changes)
4016
    result.Raise("Failed to modify storage unit '%s' on %s" %
4017
                 (self.op.name, self.op.node_name))
4018

    
4019

    
4020
class LUNodeAdd(LogicalUnit):
4021
  """Logical unit for adding node to the cluster.
4022

4023
  """
4024
  HPATH = "node-add"
4025
  HTYPE = constants.HTYPE_NODE
4026
  _NFLAGS = ["master_capable", "vm_capable"]
4027

    
4028
  def CheckArguments(self):
4029
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
4030
    # validate/normalize the node name
4031
    self.hostname = netutils.GetHostname(name=self.op.node_name,
4032
                                         family=self.primary_ip_family)
4033
    self.op.node_name = self.hostname.name
4034
    if self.op.readd and self.op.group:
4035
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
4036
                                 " being readded", errors.ECODE_INVAL)
4037

    
4038
  def BuildHooksEnv(self):
4039
    """Build hooks env.
4040

4041
    This will run on all nodes before, and on all nodes + the new node after.
4042

4043
    """
4044
    env = {
4045
      "OP_TARGET": self.op.node_name,
4046
      "NODE_NAME": self.op.node_name,
4047
      "NODE_PIP": self.op.primary_ip,
4048
      "NODE_SIP": self.op.secondary_ip,
4049
      "MASTER_CAPABLE": str(self.op.master_capable),
4050
      "VM_CAPABLE": str(self.op.vm_capable),
4051
      }
4052
    nodes_0 = self.cfg.GetNodeList()
4053
    nodes_1 = nodes_0 + [self.op.node_name, ]
4054
    return env, nodes_0, nodes_1
4055

    
4056
  def CheckPrereq(self):
4057
    """Check prerequisites.
4058

4059
    This checks:
4060
     - the new node is not already in the config
4061
     - it is resolvable
4062
     - its parameters (single/dual homed) matches the cluster
4063

4064
    Any errors are signaled by raising errors.OpPrereqError.
4065

4066
    """
4067
    cfg = self.cfg
4068
    hostname = self.hostname
4069
    node = hostname.name
4070
    primary_ip = self.op.primary_ip = hostname.ip
4071
    if self.op.secondary_ip is None:
4072
      if self.primary_ip_family == netutils.IP6Address.family:
4073
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
4074
                                   " IPv4 address must be given as secondary",
4075
                                   errors.ECODE_INVAL)
4076
      self.op.secondary_ip = primary_ip
4077

    
4078
    secondary_ip = self.op.secondary_ip
4079
    if not netutils.IP4Address.IsValid(secondary_ip):
4080
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4081
                                 " address" % secondary_ip, errors.ECODE_INVAL)
4082

    
4083
    node_list = cfg.GetNodeList()
4084
    if not self.op.readd and node in node_list:
4085
      raise errors.OpPrereqError("Node %s is already in the configuration" %
4086
                                 node, errors.ECODE_EXISTS)
4087
    elif self.op.readd and node not in node_list:
4088
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
4089
                                 errors.ECODE_NOENT)
4090

    
4091
    self.changed_primary_ip = False
4092

    
4093
    for existing_node_name in node_list:
4094
      existing_node = cfg.GetNodeInfo(existing_node_name)
4095

    
4096
      if self.op.readd and node == existing_node_name:
4097
        if existing_node.secondary_ip != secondary_ip:
4098
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
4099
                                     " address configuration as before",
4100
                                     errors.ECODE_INVAL)
4101
        if existing_node.primary_ip != primary_ip:
4102
          self.changed_primary_ip = True
4103

    
4104
        continue
4105

    
4106
      if (existing_node.primary_ip == primary_ip or
4107
          existing_node.secondary_ip == primary_ip or
4108
          existing_node.primary_ip == secondary_ip or
4109
          existing_node.secondary_ip == secondary_ip):
4110
        raise errors.OpPrereqError("New node ip address(es) conflict with"
4111
                                   " existing node %s" % existing_node.name,
4112
                                   errors.ECODE_NOTUNIQUE)
4113

    
4114
    # After this 'if' block, None is no longer a valid value for the
4115
    # _capable op attributes
4116
    if self.op.readd:
4117
      old_node = self.cfg.GetNodeInfo(node)
4118
      assert old_node is not None, "Can't retrieve locked node %s" % node
4119
      for attr in self._NFLAGS:
4120
        if getattr(self.op, attr) is None:
4121
          setattr(self.op, attr, getattr(old_node, attr))
4122
    else:
4123
      for attr in self._NFLAGS:
4124
        if getattr(self.op, attr) is None:
4125
          setattr(self.op, attr, True)
4126

    
4127
    if self.op.readd and not self.op.vm_capable:
4128
      pri, sec = cfg.GetNodeInstances(node)
4129
      if pri or sec:
4130
        raise errors.OpPrereqError("Node %s being re-added with vm_capable"
4131
                                   " flag set to false, but it already holds"
4132
                                   " instances" % node,
4133
                                   errors.ECODE_STATE)
4134

    
4135
    # check that the type of the node (single versus dual homed) is the
4136
    # same as for the master
4137
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
4138
    master_singlehomed = myself.secondary_ip == myself.primary_ip
4139
    newbie_singlehomed = secondary_ip == primary_ip
4140
    if master_singlehomed != newbie_singlehomed:
4141
      if master_singlehomed:
4142
        raise errors.OpPrereqError("The master has no secondary ip but the"
4143
                                   " new node has one",
4144
                                   errors.ECODE_INVAL)
4145
      else:
4146
        raise errors.OpPrereqError("The master has a secondary ip but the"
4147
                                   " new node doesn't have one",
4148
                                   errors.ECODE_INVAL)
4149

    
4150
    # checks reachability
4151
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
4152
      raise errors.OpPrereqError("Node not reachable by ping",
4153
                                 errors.ECODE_ENVIRON)
4154

    
4155
    if not newbie_singlehomed:
4156
      # check reachability from my secondary ip to newbie's secondary ip
4157
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
4158
                           source=myself.secondary_ip):
4159
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4160
                                   " based ping to node daemon port",
4161
                                   errors.ECODE_ENVIRON)
4162

    
4163
    if self.op.readd:
4164
      exceptions = [node]
4165
    else:
4166
      exceptions = []
4167

    
4168
    if self.op.master_capable:
4169
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
4170
    else:
4171
      self.master_candidate = False
4172

    
4173
    if self.op.readd:
4174
      self.new_node = old_node
4175
    else:
4176
      node_group = cfg.LookupNodeGroup(self.op.group)
4177
      self.new_node = objects.Node(name=node,
4178
                                   primary_ip=primary_ip,
4179
                                   secondary_ip=secondary_ip,
4180
                                   master_candidate=self.master_candidate,
4181
                                   offline=False, drained=False,
4182
                                   group=node_group)
4183

    
4184
    if self.op.ndparams:
4185
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
4186

    
4187
  def Exec(self, feedback_fn):
4188
    """Adds the new node to the cluster.
4189

4190
    """
4191
    new_node = self.new_node
4192
    node = new_node.name
4193

    
4194
    # We adding a new node so we assume it's powered
4195
    new_node.powered = True
4196

    
4197
    # for re-adds, reset the offline/drained/master-candidate flags;
4198
    # we need to reset here, otherwise offline would prevent RPC calls
4199
    # later in the procedure; this also means that if the re-add
4200
    # fails, we are left with a non-offlined, broken node
4201
    if self.op.readd:
4202
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
4203
      self.LogInfo("Readding a node, the offline/drained flags were reset")
4204
      # if we demote the node, we do cleanup later in the procedure
4205
      new_node.master_candidate = self.master_candidate
4206
      if self.changed_primary_ip:
4207
        new_node.primary_ip = self.op.primary_ip
4208

    
4209
    # copy the master/vm_capable flags
4210
    for attr in self._NFLAGS:
4211
      setattr(new_node, attr, getattr(self.op, attr))
4212

    
4213
    # notify the user about any possible mc promotion
4214
    if new_node.master_candidate:
4215
      self.LogInfo("Node will be a master candidate")
4216

    
4217
    if self.op.ndparams:
4218
      new_node.ndparams = self.op.ndparams
4219
    else:
4220
      new_node.ndparams = {}
4221

    
4222
    # check connectivity
4223
    result = self.rpc.call_version([node])[node]
4224
    result.Raise("Can't get version information from node %s" % node)
4225
    if constants.PROTOCOL_VERSION == result.payload:
4226
      logging.info("Communication to node %s fine, sw version %s match",
4227
                   node, result.payload)
4228
    else:
4229
      raise errors.OpExecError("Version mismatch master version %s,"
4230
                               " node version %s" %
4231
                               (constants.PROTOCOL_VERSION, result.payload))
4232

    
4233
    # Add node to our /etc/hosts, and add key to known_hosts
4234
    if self.cfg.GetClusterInfo().modify_etc_hosts:
4235
      master_node = self.cfg.GetMasterNode()
4236
      result = self.rpc.call_etc_hosts_modify(master_node,
4237
                                              constants.ETC_HOSTS_ADD,
4238
                                              self.hostname.name,
4239
                                              self.hostname.ip)
4240
      result.Raise("Can't update hosts file with new host data")
4241

    
4242
    if new_node.secondary_ip != new_node.primary_ip:
4243
      _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
4244
                               False)
4245

    
4246
    node_verify_list = [self.cfg.GetMasterNode()]
4247
    node_verify_param = {
4248
      constants.NV_NODELIST: [node],
4249
      # TODO: do a node-net-test as well?
4250
    }
4251

    
4252
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
4253
                                       self.cfg.GetClusterName())
4254
    for verifier in node_verify_list:
4255
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
4256
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
4257
      if nl_payload:
4258
        for failed in nl_payload:
4259
          feedback_fn("ssh/hostname verification failed"
4260
                      " (checking from %s): %s" %
4261
                      (verifier, nl_payload[failed]))
4262
        raise errors.OpExecError("ssh/hostname verification failed.")
4263

    
4264
    if self.op.readd:
4265
      _RedistributeAncillaryFiles(self)
4266
      self.context.ReaddNode(new_node)
4267
      # make sure we redistribute the config
4268
      self.cfg.Update(new_node, feedback_fn)
4269
      # and make sure the new node will not have old files around
4270
      if not new_node.master_candidate:
4271
        result = self.rpc.call_node_demote_from_mc(new_node.name)
4272
        msg = result.fail_msg
4273
        if msg:
4274
          self.LogWarning("Node failed to demote itself from master"
4275
                          " candidate status: %s" % msg)
4276
    else:
4277
      _RedistributeAncillaryFiles(self, additional_nodes=[node],
4278
                                  additional_vm=self.op.vm_capable)
4279
      self.context.AddNode(new_node, self.proc.GetECId())
4280

    
4281

    
4282
class LUNodeSetParams(LogicalUnit):
4283
  """Modifies the parameters of a node.
4284

4285
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
4286
      to the node role (as _ROLE_*)
4287
  @cvar _R2F: a dictionary from node role to tuples of flags
4288
  @cvar _FLAGS: a list of attribute names corresponding to the flags
4289

4290
  """
4291
  HPATH = "node-modify"
4292
  HTYPE = constants.HTYPE_NODE
4293
  REQ_BGL = False
4294
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
4295
  _F2R = {
4296
    (True, False, False): _ROLE_CANDIDATE,
4297
    (False, True, False): _ROLE_DRAINED,
4298
    (False, False, True): _ROLE_OFFLINE,
4299
    (False, False, False): _ROLE_REGULAR,
4300
    }
4301
  _R2F = dict((v, k) for k, v in _F2R.items())
4302
  _FLAGS = ["master_candidate", "drained", "offline"]
4303

    
4304
  def CheckArguments(self):
4305
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4306
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
4307
                self.op.master_capable, self.op.vm_capable,
4308
                self.op.secondary_ip, self.op.ndparams]
4309
    if all_mods.count(None) == len(all_mods):
4310
      raise errors.OpPrereqError("Please pass at least one modification",
4311
                                 errors.ECODE_INVAL)
4312
    if all_mods.count(True) > 1:
4313
      raise errors.OpPrereqError("Can't set the node into more than one"
4314
                                 " state at the same time",
4315
                                 errors.ECODE_INVAL)
4316

    
4317
    # Boolean value that tells us whether we might be demoting from MC
4318
    self.might_demote = (self.op.master_candidate == False or
4319
                         self.op.offline == True or
4320
                         self.op.drained == True or
4321
                         self.op.master_capable == False)
4322

    
4323
    if self.op.secondary_ip:
4324
      if not netutils.IP4Address.IsValid(self.op.secondary_ip):
4325
        raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4326
                                   " address" % self.op.secondary_ip,
4327
                                   errors.ECODE_INVAL)
4328

    
4329
    self.lock_all = self.op.auto_promote and self.might_demote
4330
    self.lock_instances = self.op.secondary_ip is not None
4331

    
4332
  def ExpandNames(self):
4333
    if self.lock_all:
4334
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
4335
    else:
4336
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
4337

    
4338
    if self.lock_instances:
4339
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4340

    
4341
  def DeclareLocks(self, level):
4342
    # If we have locked all instances, before waiting to lock nodes, release
4343
    # all the ones living on nodes unrelated to the current operation.
4344
    if level == locking.LEVEL_NODE and self.lock_instances:
4345
      instances_release = []
4346
      instances_keep = []
4347
      self.affected_instances = []
4348
      if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4349
        for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
4350
          instance = self.context.cfg.GetInstanceInfo(instance_name)
4351
          i_mirrored = instance.disk_template in constants.DTS_NET_MIRROR
4352
          if i_mirrored and self.op.node_name in instance.all_nodes:
4353
            instances_keep.append(instance_name)
4354
            self.affected_instances.append(instance)
4355
          else:
4356
            instances_release.append(instance_name)
4357
        if instances_release:
4358
          self.context.glm.release(locking.LEVEL_INSTANCE, instances_release)
4359
          self.acquired_locks[locking.LEVEL_INSTANCE] = instances_keep
4360

    
4361
  def BuildHooksEnv(self):
4362
    """Build hooks env.
4363

4364
    This runs on the master node.
4365

4366
    """
4367
    env = {
4368
      "OP_TARGET": self.op.node_name,
4369
      "MASTER_CANDIDATE": str(self.op.master_candidate),
4370
      "OFFLINE": str(self.op.offline),
4371
      "DRAINED": str(self.op.drained),
4372
      "MASTER_CAPABLE": str(self.op.master_capable),
4373
      "VM_CAPABLE": str(self.op.vm_capable),
4374
      }
4375
    nl = [self.cfg.GetMasterNode(),
4376
          self.op.node_name]
4377
    return env, nl, nl
4378

    
4379
  def CheckPrereq(self):
4380
    """Check prerequisites.
4381

4382
    This only checks the instance list against the existing names.
4383

4384
    """
4385
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
4386

    
4387
    if (self.op.master_candidate is not None or
4388
        self.op.drained is not None or
4389
        self.op.offline is not None):
4390
      # we can't change the master's node flags
4391
      if self.op.node_name == self.cfg.GetMasterNode():
4392
        raise errors.OpPrereqError("The master role can be changed"
4393
                                   " only via master-failover",
4394
                                   errors.ECODE_INVAL)
4395

    
4396
    if self.op.master_candidate and not node.master_capable:
4397
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4398
                                 " it a master candidate" % node.name,
4399
                                 errors.ECODE_STATE)
4400

    
4401
    if self.op.vm_capable == False:
4402
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
4403
      if ipri or isec:
4404
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
4405
                                   " the vm_capable flag" % node.name,
4406
                                   errors.ECODE_STATE)
4407

    
4408
    if node.master_candidate and self.might_demote and not self.lock_all:
4409
      assert not self.op.auto_promote, "auto_promote set but lock_all not"
4410
      # check if after removing the current node, we're missing master
4411
      # candidates
4412
      (mc_remaining, mc_should, _) = \
4413
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
4414
      if mc_remaining < mc_should:
4415
        raise errors.OpPrereqError("Not enough master candidates, please"
4416
                                   " pass auto promote option to allow"
4417
                                   " promotion", errors.ECODE_STATE)
4418

    
4419
    self.old_flags = old_flags = (node.master_candidate,
4420
                                  node.drained, node.offline)
4421
    assert old_flags in self._F2R, "Un-handled old flags  %s" % str(old_flags)
4422
    self.old_role = old_role = self._F2R[old_flags]
4423

    
4424
    # Check for ineffective changes
4425
    for attr in self._FLAGS:
4426
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
4427
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
4428
        setattr(self.op, attr, None)
4429

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

    
4433
    # TODO: We might query the real power state if it supports OOB
4434
    if _SupportsOob(self.cfg, node):
4435
      if self.op.offline is False and not (node.powered or
4436
                                           self.op.powered == True):
4437
        raise errors.OpPrereqError(("Please power on node %s first before you"
4438
                                    " can reset offline state") %
4439
                                   self.op.node_name)
4440
    elif self.op.powered is not None:
4441
      raise errors.OpPrereqError(("Unable to change powered state for node %s"
4442
                                  " which does not support out-of-band"
4443
                                  " handling") % self.op.node_name)
4444

    
4445
    # If we're being deofflined/drained, we'll MC ourself if needed
4446
    if (self.op.drained == False or self.op.offline == False or
4447
        (self.op.master_capable and not node.master_capable)):
4448
      if _DecideSelfPromotion(self):
4449
        self.op.master_candidate = True
4450
        self.LogInfo("Auto-promoting node to master candidate")
4451

    
4452
    # If we're no longer master capable, we'll demote ourselves from MC
4453
    if self.op.master_capable == False and node.master_candidate:
4454
      self.LogInfo("Demoting from master candidate")
4455
      self.op.master_candidate = False
4456

    
4457
    # Compute new role
4458
    assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
4459
    if self.op.master_candidate:
4460
      new_role = self._ROLE_CANDIDATE
4461
    elif self.op.drained:
4462
      new_role = self._ROLE_DRAINED
4463
    elif self.op.offline:
4464
      new_role = self._ROLE_OFFLINE
4465
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
4466
      # False is still in new flags, which means we're un-setting (the
4467
      # only) True flag
4468
      new_role = self._ROLE_REGULAR
4469
    else: # no new flags, nothing, keep old role
4470
      new_role = old_role
4471

    
4472
    self.new_role = new_role
4473

    
4474
    if old_role == self._ROLE_OFFLINE and new_role != old_role:
4475
      # Trying to transition out of offline status
4476
      result = self.rpc.call_version([node.name])[node.name]
4477
      if result.fail_msg:
4478
        raise errors.OpPrereqError("Node %s is being de-offlined but fails"
4479
                                   " to report its version: %s" %
4480
                                   (node.name, result.fail_msg),
4481
                                   errors.ECODE_STATE)
4482
      else:
4483
        self.LogWarning("Transitioning node from offline to online state"
4484
                        " without using re-add. Please make sure the node"
4485
                        " is healthy!")
4486

    
4487
    if self.op.secondary_ip:
4488
      # Ok even without locking, because this can't be changed by any LU
4489
      master = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
4490
      master_singlehomed = master.secondary_ip == master.primary_ip
4491
      if master_singlehomed and self.op.secondary_ip:
4492
        raise errors.OpPrereqError("Cannot change the secondary ip on a single"
4493
                                   " homed cluster", errors.ECODE_INVAL)
4494

    
4495
      if node.offline:
4496
        if self.affected_instances:
4497
          raise errors.OpPrereqError("Cannot change secondary ip: offline"
4498
                                     " node has instances (%s) configured"
4499
                                     " to use it" % self.affected_instances)
4500
      else:
4501
        # On online nodes, check that no instances are running, and that
4502
        # the node has the new ip and we can reach it.
4503
        for instance in self.affected_instances:
4504
          _CheckInstanceDown(self, instance, "cannot change secondary ip")
4505

    
4506
        _CheckNodeHasSecondaryIP(self, node.name, self.op.secondary_ip, True)
4507
        if master.name != node.name:
4508
          # check reachability from master secondary ip to new secondary ip
4509
          if not netutils.TcpPing(self.op.secondary_ip,
4510
                                  constants.DEFAULT_NODED_PORT,
4511
                                  source=master.secondary_ip):
4512
            raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4513
                                       " based ping to node daemon port",
4514
                                       errors.ECODE_ENVIRON)
4515

    
4516
    if self.op.ndparams:
4517
      new_ndparams = _GetUpdatedParams(self.node.ndparams, self.op.ndparams)
4518
      utils.ForceDictType(new_ndparams, constants.NDS_PARAMETER_TYPES)
4519
      self.new_ndparams = new_ndparams
4520

    
4521
  def Exec(self, feedback_fn):
4522
    """Modifies a node.
4523

4524
    """
4525
    node = self.node
4526
    old_role = self.old_role
4527
    new_role = self.new_role
4528

    
4529
    result = []
4530

    
4531
    if self.op.ndparams:
4532
      node.ndparams = self.new_ndparams
4533

    
4534
    if self.op.powered is not None:
4535
      node.powered = self.op.powered
4536

    
4537
    for attr in ["master_capable", "vm_capable"]:
4538
      val = getattr(self.op, attr)
4539
      if val is not None:
4540
        setattr(node, attr, val)
4541
        result.append((attr, str(val)))
4542

    
4543
    if new_role != old_role:
4544
      # Tell the node to demote itself, if no longer MC and not offline
4545
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
4546
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
4547
        if msg:
4548
          self.LogWarning("Node failed to demote itself: %s", msg)
4549

    
4550
      new_flags = self._R2F[new_role]
4551
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
4552
        if of != nf:
4553
          result.append((desc, str(nf)))
4554
      (node.master_candidate, node.drained, node.offline) = new_flags
4555

    
4556
      # we locked all nodes, we adjust the CP before updating this node
4557
      if self.lock_all:
4558
        _AdjustCandidatePool(self, [node.name])
4559

    
4560
    if self.op.secondary_ip:
4561
      node.secondary_ip = self.op.secondary_ip
4562
      result.append(("secondary_ip", self.op.secondary_ip))
4563

    
4564
    # this will trigger configuration file update, if needed
4565
    self.cfg.Update(node, feedback_fn)
4566

    
4567
    # this will trigger job queue propagation or cleanup if the mc
4568
    # flag changed
4569
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
4570
      self.context.ReaddNode(node)
4571

    
4572
    return result
4573

    
4574

    
4575
class LUNodePowercycle(NoHooksLU):
4576
  """Powercycles a node.
4577

4578
  """
4579
  REQ_BGL = False
4580

    
4581
  def CheckArguments(self):
4582
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4583
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4584
      raise errors.OpPrereqError("The node is the master and the force"
4585
                                 " parameter was not set",
4586
                                 errors.ECODE_INVAL)
4587

    
4588
  def ExpandNames(self):
4589
    """Locking for PowercycleNode.
4590

4591
    This is a last-resort option and shouldn't block on other
4592
    jobs. Therefore, we grab no locks.
4593

4594
    """
4595
    self.needed_locks = {}
4596

    
4597
  def Exec(self, feedback_fn):
4598
    """Reboots a node.
4599

4600
    """
4601
    result = self.rpc.call_node_powercycle(self.op.node_name,
4602
                                           self.cfg.GetHypervisorType())
4603
    result.Raise("Failed to schedule the reboot")
4604
    return result.payload
4605

    
4606

    
4607
class LUClusterQuery(NoHooksLU):
4608
  """Query cluster configuration.
4609

4610
  """
4611
  REQ_BGL = False
4612

    
4613
  def ExpandNames(self):
4614
    self.needed_locks = {}
4615

    
4616
  def Exec(self, feedback_fn):
4617
    """Return cluster config.
4618

4619
    """
4620
    cluster = self.cfg.GetClusterInfo()
4621
    os_hvp = {}
4622

    
4623
    # Filter just for enabled hypervisors
4624
    for os_name, hv_dict in cluster.os_hvp.items():
4625
      os_hvp[os_name] = {}
4626
      for hv_name, hv_params in hv_dict.items():
4627
        if hv_name in cluster.enabled_hypervisors:
4628
          os_hvp[os_name][hv_name] = hv_params
4629

    
4630
    # Convert ip_family to ip_version
4631
    primary_ip_version = constants.IP4_VERSION
4632
    if cluster.primary_ip_family == netutils.IP6Address.family:
4633
      primary_ip_version = constants.IP6_VERSION
4634

    
4635
    result = {
4636
      "software_version": constants.RELEASE_VERSION,
4637
      "protocol_version": constants.PROTOCOL_VERSION,
4638
      "config_version": constants.CONFIG_VERSION,
4639
      "os_api_version": max(constants.OS_API_VERSIONS),
4640
      "export_version": constants.EXPORT_VERSION,
4641
      "architecture": (platform.architecture()[0], platform.machine()),
4642
      "name": cluster.cluster_name,
4643
      "master": cluster.master_node,
4644
      "default_hypervisor": cluster.enabled_hypervisors[0],
4645
      "enabled_hypervisors": cluster.enabled_hypervisors,
4646
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4647
                        for hypervisor_name in cluster.enabled_hypervisors]),
4648
      "os_hvp": os_hvp,
4649
      "beparams": cluster.beparams,
4650
      "osparams": cluster.osparams,
4651
      "nicparams": cluster.nicparams,
4652
      "ndparams": cluster.ndparams,
4653
      "candidate_pool_size": cluster.candidate_pool_size,
4654
      "master_netdev": cluster.master_netdev,
4655
      "volume_group_name": cluster.volume_group_name,
4656
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
4657
      "file_storage_dir": cluster.file_storage_dir,
4658
      "maintain_node_health": cluster.maintain_node_health,
4659
      "ctime": cluster.ctime,
4660
      "mtime": cluster.mtime,
4661
      "uuid": cluster.uuid,
4662
      "tags": list(cluster.GetTags()),
4663
      "uid_pool": cluster.uid_pool,
4664
      "default_iallocator": cluster.default_iallocator,
4665
      "reserved_lvs": cluster.reserved_lvs,
4666
      "primary_ip_version": primary_ip_version,
4667
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
4668
      "hidden_os": cluster.hidden_os,
4669
      "blacklisted_os": cluster.blacklisted_os,
4670
      }
4671

    
4672
    return result
4673

    
4674

    
4675
class LUClusterConfigQuery(NoHooksLU):
4676
  """Return configuration values.
4677

4678
  """
4679
  REQ_BGL = False
4680
  _FIELDS_DYNAMIC = utils.FieldSet()
4681
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4682
                                  "watcher_pause", "volume_group_name")
4683

    
4684
  def CheckArguments(self):
4685
    _CheckOutputFields(static=self._FIELDS_STATIC,
4686
                       dynamic=self._FIELDS_DYNAMIC,
4687
                       selected=self.op.output_fields)
4688

    
4689
  def ExpandNames(self):
4690
    self.needed_locks = {}
4691

    
4692
  def Exec(self, feedback_fn):
4693
    """Dump a representation of the cluster config to the standard output.
4694

4695
    """
4696
    values = []
4697
    for field in self.op.output_fields:
4698
      if field == "cluster_name":
4699
        entry = self.cfg.GetClusterName()
4700
      elif field == "master_node":
4701
        entry = self.cfg.GetMasterNode()
4702
      elif field == "drain_flag":
4703
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4704
      elif field == "watcher_pause":
4705
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4706
      elif field == "volume_group_name":
4707
        entry = self.cfg.GetVGName()
4708
      else:
4709
        raise errors.ParameterError(field)
4710
      values.append(entry)
4711
    return values
4712

    
4713

    
4714
class LUInstanceActivateDisks(NoHooksLU):
4715
  """Bring up an instance's disks.
4716

4717
  """
4718
  REQ_BGL = False
4719

    
4720
  def ExpandNames(self):
4721
    self._ExpandAndLockInstance()
4722
    self.needed_locks[locking.LEVEL_NODE] = []
4723
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4724

    
4725
  def DeclareLocks(self, level):
4726
    if level == locking.LEVEL_NODE:
4727
      self._LockInstancesNodes()
4728

    
4729
  def CheckPrereq(self):
4730
    """Check prerequisites.
4731

4732
    This checks that the instance is in the cluster.
4733

4734
    """
4735
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4736
    assert self.instance is not None, \
4737
      "Cannot retrieve locked instance %s" % self.op.instance_name
4738
    _CheckNodeOnline(self, self.instance.primary_node)
4739

    
4740
  def Exec(self, feedback_fn):
4741
    """Activate the disks.
4742

4743
    """
4744
    disks_ok, disks_info = \
4745
              _AssembleInstanceDisks(self, self.instance,
4746
                                     ignore_size=self.op.ignore_size)
4747
    if not disks_ok:
4748
      raise errors.OpExecError("Cannot activate block devices")
4749

    
4750
    return disks_info
4751

    
4752

    
4753
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4754
                           ignore_size=False):
4755
  """Prepare the block devices for an instance.
4756

4757
  This sets up the block devices on all nodes.
4758

4759
  @type lu: L{LogicalUnit}
4760
  @param lu: the logical unit on whose behalf we execute
4761
  @type instance: L{objects.Instance}
4762
  @param instance: the instance for whose disks we assemble
4763
  @type disks: list of L{objects.Disk} or None
4764
  @param disks: which disks to assemble (or all, if None)
4765
  @type ignore_secondaries: boolean
4766
  @param ignore_secondaries: if true, errors on secondary nodes
4767
      won't result in an error return from the function
4768
  @type ignore_size: boolean
4769
  @param ignore_size: if true, the current known size of the disk
4770
      will not be used during the disk activation, useful for cases
4771
      when the size is wrong
4772
  @return: False if the operation failed, otherwise a list of
4773
      (host, instance_visible_name, node_visible_name)
4774
      with the mapping from node devices to instance devices
4775

4776
  """
4777
  device_info = []
4778
  disks_ok = True
4779
  iname = instance.name
4780
  disks = _ExpandCheckDisks(instance, disks)
4781

    
4782
  # With the two passes mechanism we try to reduce the window of
4783
  # opportunity for the race condition of switching DRBD to primary
4784
  # before handshaking occured, but we do not eliminate it
4785

    
4786
  # The proper fix would be to wait (with some limits) until the
4787
  # connection has been made and drbd transitions from WFConnection
4788
  # into any other network-connected state (Connected, SyncTarget,
4789
  # SyncSource, etc.)
4790

    
4791
  # 1st pass, assemble on all nodes in secondary mode
4792
  for idx, inst_disk in enumerate(disks):
4793
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4794
      if ignore_size:
4795
        node_disk = node_disk.Copy()
4796
        node_disk.UnsetSize()
4797
      lu.cfg.SetDiskID(node_disk, node)
4798
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False, idx)
4799
      msg = result.fail_msg
4800
      if msg:
4801
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4802
                           " (is_primary=False, pass=1): %s",
4803
                           inst_disk.iv_name, node, msg)
4804
        if not ignore_secondaries:
4805
          disks_ok = False
4806

    
4807
  # FIXME: race condition on drbd migration to primary
4808

    
4809
  # 2nd pass, do only the primary node
4810
  for idx, inst_disk in enumerate(disks):
4811
    dev_path = None
4812

    
4813
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4814
      if node != instance.primary_node:
4815
        continue
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, True, 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=True, pass=2): %s",
4825
                           inst_disk.iv_name, node, msg)
4826
        disks_ok = False
4827
      else:
4828
        dev_path = result.payload
4829

    
4830
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4831

    
4832
  # leave the disks configured for the primary node
4833
  # this is a workaround that would be fixed better by
4834
  # improving the logical/physical id handling
4835
  for disk in disks:
4836
    lu.cfg.SetDiskID(disk, instance.primary_node)
4837

    
4838
  return disks_ok, device_info
4839

    
4840

    
4841
def _StartInstanceDisks(lu, instance, force):
4842
  """Start the disks of an instance.
4843

4844
  """
4845
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4846
                                           ignore_secondaries=force)
4847
  if not disks_ok:
4848
    _ShutdownInstanceDisks(lu, instance)
4849
    if force is not None and not force:
4850
      lu.proc.LogWarning("", hint="If the message above refers to a"
4851
                         " secondary node,"
4852
                         " you can retry the operation using '--force'.")
4853
    raise errors.OpExecError("Disk consistency error")
4854

    
4855

    
4856
class LUInstanceDeactivateDisks(NoHooksLU):
4857
  """Shutdown an instance's disks.
4858

4859
  """
4860
  REQ_BGL = False
4861

    
4862
  def ExpandNames(self):
4863
    self._ExpandAndLockInstance()
4864
    self.needed_locks[locking.LEVEL_NODE] = []
4865
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4866

    
4867
  def DeclareLocks(self, level):
4868
    if level == locking.LEVEL_NODE:
4869
      self._LockInstancesNodes()
4870

    
4871
  def CheckPrereq(self):
4872
    """Check prerequisites.
4873

4874
    This checks that the instance is in the cluster.
4875

4876
    """
4877
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4878
    assert self.instance is not None, \
4879
      "Cannot retrieve locked instance %s" % self.op.instance_name
4880

    
4881
  def Exec(self, feedback_fn):
4882
    """Deactivate the disks
4883

4884
    """
4885
    instance = self.instance
4886
    if self.op.force:
4887
      _ShutdownInstanceDisks(self, instance)
4888
    else:
4889
      _SafeShutdownInstanceDisks(self, instance)
4890

    
4891

    
4892
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4893
  """Shutdown block devices of an instance.
4894

4895
  This function checks if an instance is running, before calling
4896
  _ShutdownInstanceDisks.
4897

4898
  """
4899
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4900
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4901

    
4902

    
4903
def _ExpandCheckDisks(instance, disks):
4904
  """Return the instance disks selected by the disks list
4905

4906
  @type disks: list of L{objects.Disk} or None
4907
  @param disks: selected disks
4908
  @rtype: list of L{objects.Disk}
4909
  @return: selected instance disks to act on
4910

4911
  """
4912
  if disks is None:
4913
    return instance.disks
4914
  else:
4915
    if not set(disks).issubset(instance.disks):
4916
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4917
                                   " target instance")
4918
    return disks
4919

    
4920

    
4921
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4922
  """Shutdown block devices of an instance.
4923

4924
  This does the shutdown on all nodes of the instance.
4925

4926
  If the ignore_primary is false, errors on the primary node are
4927
  ignored.
4928

4929
  """
4930
  all_result = True
4931
  disks = _ExpandCheckDisks(instance, disks)
4932

    
4933
  for disk in disks:
4934
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4935
      lu.cfg.SetDiskID(top_disk, node)
4936
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4937
      msg = result.fail_msg
4938
      if msg:
4939
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4940
                      disk.iv_name, node, msg)
4941
        if ((node == instance.primary_node and not ignore_primary) or
4942
            (node != instance.primary_node and not result.offline)):
4943
          all_result = False
4944
  return all_result
4945

    
4946

    
4947
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4948
  """Checks if a node has enough free memory.
4949

4950
  This function check if a given node has the needed amount of free
4951
  memory. In case the node has less memory or we cannot get the
4952
  information from the node, this function raise an OpPrereqError
4953
  exception.
4954

4955
  @type lu: C{LogicalUnit}
4956
  @param lu: a logical unit from which we get configuration data
4957
  @type node: C{str}
4958
  @param node: the node to check
4959
  @type reason: C{str}
4960
  @param reason: string to use in the error message
4961
  @type requested: C{int}
4962
  @param requested: the amount of memory in MiB to check for
4963
  @type hypervisor_name: C{str}
4964
  @param hypervisor_name: the hypervisor to ask for memory stats
4965
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4966
      we cannot check the node
4967

4968
  """
4969
  nodeinfo = lu.rpc.call_node_info([node], None, hypervisor_name)
4970
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4971
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4972
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4973
  if not isinstance(free_mem, int):
4974
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4975
                               " was '%s'" % (node, free_mem),
4976
                               errors.ECODE_ENVIRON)
4977
  if requested > free_mem:
4978
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
4979
                               " needed %s MiB, available %s MiB" %
4980
                               (node, reason, requested, free_mem),
4981
                               errors.ECODE_NORES)
4982

    
4983

    
4984
def _CheckNodesFreeDiskPerVG(lu, nodenames, req_sizes):
4985
  """Checks if nodes have enough free disk space in the all VGs.
4986

4987
  This function check if all given nodes have the needed amount of
4988
  free disk. In case any node has less disk or we cannot get the
4989
  information from the node, this function raise an OpPrereqError
4990
  exception.
4991

4992
  @type lu: C{LogicalUnit}
4993
  @param lu: a logical unit from which we get configuration data
4994
  @type nodenames: C{list}
4995
  @param nodenames: the list of node names to check
4996
  @type req_sizes: C{dict}
4997
  @param req_sizes: the hash of vg and corresponding amount of disk in
4998
      MiB to check for
4999
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5000
      or we cannot check the node
5001

5002
  """
5003
  for vg, req_size in req_sizes.items():
5004
    _CheckNodesFreeDiskOnVG(lu, nodenames, vg, req_size)
5005

    
5006

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

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

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

5026
  """
5027
  nodeinfo = lu.rpc.call_node_info(nodenames, vg, None)
5028
  for node in nodenames:
5029
    info = nodeinfo[node]
5030
    info.Raise("Cannot get current information from node %s" % node,
5031
               prereq=True, ecode=errors.ECODE_ENVIRON)
5032
    vg_free = info.payload.get("vg_free", None)
5033
    if not isinstance(vg_free, int):
5034
      raise errors.OpPrereqError("Can't compute free disk space on node"
5035
                                 " %s for vg %s, result was '%s'" %
5036
                                 (node, vg, vg_free), errors.ECODE_ENVIRON)
5037
    if requested > vg_free:
5038
      raise errors.OpPrereqError("Not enough disk space on target node %s"
5039
                                 " vg %s: required %d MiB, available %d MiB" %
5040
                                 (node, vg, requested, vg_free),
5041
                                 errors.ECODE_NORES)
5042

    
5043

    
5044
class LUInstanceStartup(LogicalUnit):
5045
  """Starts an instance.
5046

5047
  """
5048
  HPATH = "instance-start"
5049
  HTYPE = constants.HTYPE_INSTANCE
5050
  REQ_BGL = False
5051

    
5052
  def CheckArguments(self):
5053
    # extra beparams
5054
    if self.op.beparams:
5055
      # fill the beparams dict
5056
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5057

    
5058
  def ExpandNames(self):
5059
    self._ExpandAndLockInstance()
5060

    
5061
  def BuildHooksEnv(self):
5062
    """Build hooks env.
5063

5064
    This runs on master, primary and secondary nodes of the instance.
5065

5066
    """
5067
    env = {
5068
      "FORCE": self.op.force,
5069
      }
5070
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5071
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5072
    return env, nl, nl
5073

    
5074
  def CheckPrereq(self):
5075
    """Check prerequisites.
5076

5077
    This checks that the instance is in the cluster.
5078

5079
    """
5080
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5081
    assert self.instance is not None, \
5082
      "Cannot retrieve locked instance %s" % self.op.instance_name
5083

    
5084
    # extra hvparams
5085
    if self.op.hvparams:
5086
      # check hypervisor parameter syntax (locally)
5087
      cluster = self.cfg.GetClusterInfo()
5088
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5089
      filled_hvp = cluster.FillHV(instance)
5090
      filled_hvp.update(self.op.hvparams)
5091
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
5092
      hv_type.CheckParameterSyntax(filled_hvp)
5093
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
5094

    
5095
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
5096

    
5097
    if self.primary_offline and self.op.ignore_offline_nodes:
5098
      self.proc.LogWarning("Ignoring offline primary node")
5099

    
5100
      if self.op.hvparams or self.op.beparams:
5101
        self.proc.LogWarning("Overridden parameters are ignored")
5102
    else:
5103
      _CheckNodeOnline(self, instance.primary_node)
5104

    
5105
      bep = self.cfg.GetClusterInfo().FillBE(instance)
5106

    
5107
      # check bridges existence
5108
      _CheckInstanceBridgesExist(self, instance)
5109

    
5110
      remote_info = self.rpc.call_instance_info(instance.primary_node,
5111
                                                instance.name,
5112
                                                instance.hypervisor)
5113
      remote_info.Raise("Error checking node %s" % instance.primary_node,
5114
                        prereq=True, ecode=errors.ECODE_ENVIRON)
5115
      if not remote_info.payload: # not running already
5116
        _CheckNodeFreeMemory(self, instance.primary_node,
5117
                             "starting instance %s" % instance.name,
5118
                             bep[constants.BE_MEMORY], instance.hypervisor)
5119

    
5120
  def Exec(self, feedback_fn):
5121
    """Start the instance.
5122

5123
    """
5124
    instance = self.instance
5125
    force = self.op.force
5126

    
5127
    self.cfg.MarkInstanceUp(instance.name)
5128

    
5129
    if self.primary_offline:
5130
      assert self.op.ignore_offline_nodes
5131
      self.proc.LogInfo("Primary node offline, marked instance as started")
5132
    else:
5133
      node_current = instance.primary_node
5134

    
5135
      _StartInstanceDisks(self, instance, force)
5136

    
5137
      result = self.rpc.call_instance_start(node_current, instance,
5138
                                            self.op.hvparams, self.op.beparams)
5139
      msg = result.fail_msg
5140
      if msg:
5141
        _ShutdownInstanceDisks(self, instance)
5142
        raise errors.OpExecError("Could not start instance: %s" % msg)
5143

    
5144

    
5145
class LUInstanceReboot(LogicalUnit):
5146
  """Reboot an instance.
5147

5148
  """
5149
  HPATH = "instance-reboot"
5150
  HTYPE = constants.HTYPE_INSTANCE
5151
  REQ_BGL = False
5152

    
5153
  def ExpandNames(self):
5154
    self._ExpandAndLockInstance()
5155

    
5156
  def BuildHooksEnv(self):
5157
    """Build hooks env.
5158

5159
    This runs on master, primary and secondary nodes of the instance.
5160

5161
    """
5162
    env = {
5163
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
5164
      "REBOOT_TYPE": self.op.reboot_type,
5165
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5166
      }
5167
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5168
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5169
    return env, nl, nl
5170

    
5171
  def CheckPrereq(self):
5172
    """Check prerequisites.
5173

5174
    This checks that the instance is in the cluster.
5175

5176
    """
5177
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5178
    assert self.instance is not None, \
5179
      "Cannot retrieve locked instance %s" % self.op.instance_name
5180

    
5181
    _CheckNodeOnline(self, instance.primary_node)
5182

    
5183
    # check bridges existence
5184
    _CheckInstanceBridgesExist(self, instance)
5185

    
5186
  def Exec(self, feedback_fn):
5187
    """Reboot the instance.
5188

5189
    """
5190
    instance = self.instance
5191
    ignore_secondaries = self.op.ignore_secondaries
5192
    reboot_type = self.op.reboot_type
5193

    
5194
    node_current = instance.primary_node
5195

    
5196
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
5197
                       constants.INSTANCE_REBOOT_HARD]:
5198
      for disk in instance.disks:
5199
        self.cfg.SetDiskID(disk, node_current)
5200
      result = self.rpc.call_instance_reboot(node_current, instance,
5201
                                             reboot_type,
5202
                                             self.op.shutdown_timeout)
5203
      result.Raise("Could not reboot instance")
5204
    else:
5205
      result = self.rpc.call_instance_shutdown(node_current, instance,
5206
                                               self.op.shutdown_timeout)
5207
      result.Raise("Could not shutdown instance for full reboot")
5208
      _ShutdownInstanceDisks(self, instance)
5209
      _StartInstanceDisks(self, instance, ignore_secondaries)
5210
      result = self.rpc.call_instance_start(node_current, instance, None, None)
5211
      msg = result.fail_msg
5212
      if msg:
5213
        _ShutdownInstanceDisks(self, instance)
5214
        raise errors.OpExecError("Could not start instance for"
5215
                                 " full reboot: %s" % msg)
5216

    
5217
    self.cfg.MarkInstanceUp(instance.name)
5218

    
5219

    
5220
class LUInstanceShutdown(LogicalUnit):
5221
  """Shutdown an instance.
5222

5223
  """
5224
  HPATH = "instance-stop"
5225
  HTYPE = constants.HTYPE_INSTANCE
5226
  REQ_BGL = False
5227

    
5228
  def ExpandNames(self):
5229
    self._ExpandAndLockInstance()
5230

    
5231
  def BuildHooksEnv(self):
5232
    """Build hooks env.
5233

5234
    This runs on master, primary and secondary nodes of the instance.
5235

5236
    """
5237
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5238
    env["TIMEOUT"] = self.op.timeout
5239
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5240
    return env, nl, nl
5241

    
5242
  def CheckPrereq(self):
5243
    """Check prerequisites.
5244

5245
    This checks that the instance is in the cluster.
5246

5247
    """
5248
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5249
    assert self.instance is not None, \
5250
      "Cannot retrieve locked instance %s" % self.op.instance_name
5251

    
5252
    self.primary_offline = \
5253
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
5254

    
5255
    if self.primary_offline and self.op.ignore_offline_nodes:
5256
      self.proc.LogWarning("Ignoring offline primary node")
5257
    else:
5258
      _CheckNodeOnline(self, self.instance.primary_node)
5259

    
5260
  def Exec(self, feedback_fn):
5261
    """Shutdown the instance.
5262

5263
    """
5264
    instance = self.instance
5265
    node_current = instance.primary_node
5266
    timeout = self.op.timeout
5267

    
5268
    self.cfg.MarkInstanceDown(instance.name)
5269

    
5270
    if self.primary_offline:
5271
      assert self.op.ignore_offline_nodes
5272
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
5273
    else:
5274
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
5275
      msg = result.fail_msg
5276
      if msg:
5277
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
5278

    
5279
      _ShutdownInstanceDisks(self, instance)
5280

    
5281

    
5282
class LUInstanceReinstall(LogicalUnit):
5283
  """Reinstall an instance.
5284

5285
  """
5286
  HPATH = "instance-reinstall"
5287
  HTYPE = constants.HTYPE_INSTANCE
5288
  REQ_BGL = False
5289

    
5290
  def ExpandNames(self):
5291
    self._ExpandAndLockInstance()
5292

    
5293
  def BuildHooksEnv(self):
5294
    """Build hooks env.
5295

5296
    This runs on master, primary and secondary nodes of the instance.
5297

5298
    """
5299
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5300
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5301
    return env, nl, nl
5302

    
5303
  def CheckPrereq(self):
5304
    """Check prerequisites.
5305

5306
    This checks that the instance is in the cluster and is not running.
5307

5308
    """
5309
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5310
    assert instance is not None, \
5311
      "Cannot retrieve locked instance %s" % self.op.instance_name
5312
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
5313
                     " offline, cannot reinstall")
5314
    for node in instance.secondary_nodes:
5315
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
5316
                       " cannot reinstall")
5317

    
5318
    if instance.disk_template == constants.DT_DISKLESS:
5319
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5320
                                 self.op.instance_name,
5321
                                 errors.ECODE_INVAL)
5322
    _CheckInstanceDown(self, instance, "cannot reinstall")
5323

    
5324
    if self.op.os_type is not None:
5325
      # OS verification
5326
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
5327
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
5328
      instance_os = self.op.os_type
5329
    else:
5330
      instance_os = instance.os
5331

    
5332
    nodelist = list(instance.all_nodes)
5333

    
5334
    if self.op.osparams:
5335
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
5336
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
5337
      self.os_inst = i_osdict # the new dict (without defaults)
5338
    else:
5339
      self.os_inst = None
5340

    
5341
    self.instance = instance
5342

    
5343
  def Exec(self, feedback_fn):
5344
    """Reinstall the instance.
5345

5346
    """
5347
    inst = self.instance
5348

    
5349
    if self.op.os_type is not None:
5350
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
5351
      inst.os = self.op.os_type
5352
      # Write to configuration
5353
      self.cfg.Update(inst, feedback_fn)
5354

    
5355
    _StartInstanceDisks(self, inst, None)
5356
    try:
5357
      feedback_fn("Running the instance OS create scripts...")
5358
      # FIXME: pass debug option from opcode to backend
5359
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
5360
                                             self.op.debug_level,
5361
                                             osparams=self.os_inst)
5362
      result.Raise("Could not install OS for instance %s on node %s" %
5363
                   (inst.name, inst.primary_node))
5364
    finally:
5365
      _ShutdownInstanceDisks(self, inst)
5366

    
5367

    
5368
class LUInstanceRecreateDisks(LogicalUnit):
5369
  """Recreate an instance's missing disks.
5370

5371
  """
5372
  HPATH = "instance-recreate-disks"
5373
  HTYPE = constants.HTYPE_INSTANCE
5374
  REQ_BGL = False
5375

    
5376
  def ExpandNames(self):
5377
    self._ExpandAndLockInstance()
5378

    
5379
  def BuildHooksEnv(self):
5380
    """Build hooks env.
5381

5382
    This runs on master, primary and secondary nodes of the instance.
5383

5384
    """
5385
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5386
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5387
    return env, nl, nl
5388

    
5389
  def CheckPrereq(self):
5390
    """Check prerequisites.
5391

5392
    This checks that the instance is in the cluster and is not running.
5393

5394
    """
5395
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5396
    assert instance is not None, \
5397
      "Cannot retrieve locked instance %s" % self.op.instance_name
5398
    _CheckNodeOnline(self, instance.primary_node)
5399

    
5400
    if instance.disk_template == constants.DT_DISKLESS:
5401
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5402
                                 self.op.instance_name, errors.ECODE_INVAL)
5403
    _CheckInstanceDown(self, instance, "cannot recreate disks")
5404

    
5405
    if not self.op.disks:
5406
      self.op.disks = range(len(instance.disks))
5407
    else:
5408
      for idx in self.op.disks:
5409
        if idx >= len(instance.disks):
5410
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
5411
                                     errors.ECODE_INVAL)
5412

    
5413
    self.instance = instance
5414

    
5415
  def Exec(self, feedback_fn):
5416
    """Recreate the disks.
5417

5418
    """
5419
    to_skip = []
5420
    for idx, _ in enumerate(self.instance.disks):
5421
      if idx not in self.op.disks: # disk idx has not been passed in
5422
        to_skip.append(idx)
5423
        continue
5424

    
5425
    _CreateDisks(self, self.instance, to_skip=to_skip)
5426

    
5427

    
5428
class LUInstanceRename(LogicalUnit):
5429
  """Rename an instance.
5430

5431
  """
5432
  HPATH = "instance-rename"
5433
  HTYPE = constants.HTYPE_INSTANCE
5434

    
5435
  def CheckArguments(self):
5436
    """Check arguments.
5437

5438
    """
5439
    if self.op.ip_check and not self.op.name_check:
5440
      # TODO: make the ip check more flexible and not depend on the name check
5441
      raise errors.OpPrereqError("Cannot do ip check without a name check",
5442
                                 errors.ECODE_INVAL)
5443

    
5444
  def BuildHooksEnv(self):
5445
    """Build hooks env.
5446

5447
    This runs on master, primary and secondary nodes of the instance.
5448

5449
    """
5450
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5451
    env["INSTANCE_NEW_NAME"] = self.op.new_name
5452
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5453
    return env, nl, nl
5454

    
5455
  def CheckPrereq(self):
5456
    """Check prerequisites.
5457

5458
    This checks that the instance is in the cluster and is not running.
5459

5460
    """
5461
    self.op.instance_name = _ExpandInstanceName(self.cfg,
5462
                                                self.op.instance_name)
5463
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5464
    assert instance is not None
5465
    _CheckNodeOnline(self, instance.primary_node)
5466
    _CheckInstanceDown(self, instance, "cannot rename")
5467
    self.instance = instance
5468

    
5469
    new_name = self.op.new_name
5470
    if self.op.name_check:
5471
      hostname = netutils.GetHostname(name=new_name)
5472
      self.LogInfo("Resolved given name '%s' to '%s'", new_name,
5473
                   hostname.name)
5474
      new_name = self.op.new_name = hostname.name
5475
      if (self.op.ip_check and
5476
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
5477
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
5478
                                   (hostname.ip, new_name),
5479
                                   errors.ECODE_NOTUNIQUE)
5480

    
5481
    instance_list = self.cfg.GetInstanceList()
5482
    if new_name in instance_list and new_name != instance.name:
5483
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5484
                                 new_name, errors.ECODE_EXISTS)
5485

    
5486
  def Exec(self, feedback_fn):
5487
    """Rename the instance.
5488

5489
    """
5490
    inst = self.instance
5491
    old_name = inst.name
5492

    
5493
    rename_file_storage = False
5494
    if (inst.disk_template == constants.DT_FILE and
5495
        self.op.new_name != inst.name):
5496
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5497
      rename_file_storage = True
5498

    
5499
    self.cfg.RenameInstance(inst.name, self.op.new_name)
5500
    # Change the instance lock. This is definitely safe while we hold the BGL
5501
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
5502
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
5503

    
5504
    # re-read the instance from the configuration after rename
5505
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
5506

    
5507
    if rename_file_storage:
5508
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5509
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
5510
                                                     old_file_storage_dir,
5511
                                                     new_file_storage_dir)
5512
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
5513
                   " (but the instance has been renamed in Ganeti)" %
5514
                   (inst.primary_node, old_file_storage_dir,
5515
                    new_file_storage_dir))
5516

    
5517
    _StartInstanceDisks(self, inst, None)
5518
    try:
5519
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
5520
                                                 old_name, self.op.debug_level)
5521
      msg = result.fail_msg
5522
      if msg:
5523
        msg = ("Could not run OS rename script for instance %s on node %s"
5524
               " (but the instance has been renamed in Ganeti): %s" %
5525
               (inst.name, inst.primary_node, msg))
5526
        self.proc.LogWarning(msg)
5527
    finally:
5528
      _ShutdownInstanceDisks(self, inst)
5529

    
5530
    return inst.name
5531

    
5532

    
5533
class LUInstanceRemove(LogicalUnit):
5534
  """Remove an instance.
5535

5536
  """
5537
  HPATH = "instance-remove"
5538
  HTYPE = constants.HTYPE_INSTANCE
5539
  REQ_BGL = False
5540

    
5541
  def ExpandNames(self):
5542
    self._ExpandAndLockInstance()
5543
    self.needed_locks[locking.LEVEL_NODE] = []
5544
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5545

    
5546
  def DeclareLocks(self, level):
5547
    if level == locking.LEVEL_NODE:
5548
      self._LockInstancesNodes()
5549

    
5550
  def BuildHooksEnv(self):
5551
    """Build hooks env.
5552

5553
    This runs on master, primary and secondary nodes of the instance.
5554

5555
    """
5556
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5557
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
5558
    nl = [self.cfg.GetMasterNode()]
5559
    nl_post = list(self.instance.all_nodes) + nl
5560
    return env, nl, nl_post
5561

    
5562
  def CheckPrereq(self):
5563
    """Check prerequisites.
5564

5565
    This checks that the instance is in the cluster.
5566

5567
    """
5568
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5569
    assert self.instance is not None, \
5570
      "Cannot retrieve locked instance %s" % self.op.instance_name
5571

    
5572
  def Exec(self, feedback_fn):
5573
    """Remove the instance.
5574

5575
    """
5576
    instance = self.instance
5577
    logging.info("Shutting down instance %s on node %s",
5578
                 instance.name, instance.primary_node)
5579

    
5580
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5581
                                             self.op.shutdown_timeout)
5582
    msg = result.fail_msg
5583
    if msg:
5584
      if self.op.ignore_failures:
5585
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5586
      else:
5587
        raise errors.OpExecError("Could not shutdown instance %s on"
5588
                                 " node %s: %s" %
5589
                                 (instance.name, instance.primary_node, msg))
5590

    
5591
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5592

    
5593

    
5594
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5595
  """Utility function to remove an instance.
5596

5597
  """
5598
  logging.info("Removing block devices for instance %s", instance.name)
5599

    
5600
  if not _RemoveDisks(lu, instance):
5601
    if not ignore_failures:
5602
      raise errors.OpExecError("Can't remove instance's disks")
5603
    feedback_fn("Warning: can't remove instance's disks")
5604

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

    
5607
  lu.cfg.RemoveInstance(instance.name)
5608

    
5609
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5610
    "Instance lock removal conflict"
5611

    
5612
  # Remove lock for the instance
5613
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5614

    
5615

    
5616
class LUInstanceQuery(NoHooksLU):
5617
  """Logical unit for querying instances.
5618

5619
  """
5620
  # pylint: disable-msg=W0142
5621
  REQ_BGL = False
5622

    
5623
  def CheckArguments(self):
5624
    self.iq = _InstanceQuery(self.op.names, self.op.output_fields,
5625
                             self.op.use_locking)
5626

    
5627
  def ExpandNames(self):
5628
    self.iq.ExpandNames(self)
5629

    
5630
  def DeclareLocks(self, level):
5631
    self.iq.DeclareLocks(self, level)
5632

    
5633
  def Exec(self, feedback_fn):
5634
    return self.iq.OldStyleQuery(self)
5635

    
5636

    
5637
class LUInstanceFailover(LogicalUnit):
5638
  """Failover an instance.
5639

5640
  """
5641
  HPATH = "instance-failover"
5642
  HTYPE = constants.HTYPE_INSTANCE
5643
  REQ_BGL = False
5644

    
5645
  def ExpandNames(self):
5646
    self._ExpandAndLockInstance()
5647
    self.needed_locks[locking.LEVEL_NODE] = []
5648
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5649

    
5650
  def DeclareLocks(self, level):
5651
    if level == locking.LEVEL_NODE:
5652
      self._LockInstancesNodes()
5653

    
5654
  def BuildHooksEnv(self):
5655
    """Build hooks env.
5656

5657
    This runs on master, primary and secondary nodes of the instance.
5658

5659
    """
5660
    instance = self.instance
5661
    source_node = instance.primary_node
5662
    target_node = instance.secondary_nodes[0]
5663
    env = {
5664
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5665
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5666
      "OLD_PRIMARY": source_node,
5667
      "OLD_SECONDARY": target_node,
5668
      "NEW_PRIMARY": target_node,
5669
      "NEW_SECONDARY": source_node,
5670
      }
5671
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5672
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5673
    nl_post = list(nl)
5674
    nl_post.append(source_node)
5675
    return env, nl, nl_post
5676

    
5677
  def CheckPrereq(self):
5678
    """Check prerequisites.
5679

5680
    This checks that the instance is in the cluster.
5681

5682
    """
5683
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5684
    assert self.instance is not None, \
5685
      "Cannot retrieve locked instance %s" % self.op.instance_name
5686

    
5687
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5688
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5689
      raise errors.OpPrereqError("Instance's disk layout is not"
5690
                                 " network mirrored, cannot failover.",
5691
                                 errors.ECODE_STATE)
5692

    
5693
    secondary_nodes = instance.secondary_nodes
5694
    if not secondary_nodes:
5695
      raise errors.ProgrammerError("no secondary node but using "
5696
                                   "a mirrored disk template")
5697

    
5698
    target_node = secondary_nodes[0]
5699
    _CheckNodeOnline(self, target_node)
5700
    _CheckNodeNotDrained(self, target_node)
5701
    if instance.admin_up:
5702
      # check memory requirements on the secondary node
5703
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5704
                           instance.name, bep[constants.BE_MEMORY],
5705
                           instance.hypervisor)
5706
    else:
5707
      self.LogInfo("Not checking memory on the secondary node as"
5708
                   " instance will not be started")
5709

    
5710
    # check bridge existance
5711
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5712

    
5713
  def Exec(self, feedback_fn):
5714
    """Failover an instance.
5715

5716
    The failover is done by shutting it down on its present node and
5717
    starting it on the secondary.
5718

5719
    """
5720
    instance = self.instance
5721
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
5722

    
5723
    source_node = instance.primary_node
5724
    target_node = instance.secondary_nodes[0]
5725

    
5726
    if instance.admin_up:
5727
      feedback_fn("* checking disk consistency between source and target")
5728
      for dev in instance.disks:
5729
        # for drbd, these are drbd over lvm
5730
        if not _CheckDiskConsistency(self, dev, target_node, False):
5731
          if not self.op.ignore_consistency:
5732
            raise errors.OpExecError("Disk %s is degraded on target node,"
5733
                                     " aborting failover." % dev.iv_name)
5734
    else:
5735
      feedback_fn("* not checking disk consistency as instance is not running")
5736

    
5737
    feedback_fn("* shutting down instance on source node")
5738
    logging.info("Shutting down instance %s on node %s",
5739
                 instance.name, source_node)
5740

    
5741
    result = self.rpc.call_instance_shutdown(source_node, instance,
5742
                                             self.op.shutdown_timeout)
5743
    msg = result.fail_msg
5744
    if msg:
5745
      if self.op.ignore_consistency or primary_node.offline:
5746
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5747
                             " Proceeding anyway. Please make sure node"
5748
                             " %s is down. Error details: %s",
5749
                             instance.name, source_node, source_node, msg)
5750
      else:
5751
        raise errors.OpExecError("Could not shutdown instance %s on"
5752
                                 " node %s: %s" %
5753
                                 (instance.name, source_node, msg))
5754

    
5755
    feedback_fn("* deactivating the instance's disks on source node")
5756
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5757
      raise errors.OpExecError("Can't shut down the instance's disks.")
5758

    
5759
    instance.primary_node = target_node
5760
    # distribute new instance config to the other nodes
5761
    self.cfg.Update(instance, feedback_fn)
5762

    
5763
    # Only start the instance if it's marked as up
5764
    if instance.admin_up:
5765
      feedback_fn("* activating the instance's disks on target node")
5766
      logging.info("Starting instance %s on node %s",
5767
                   instance.name, target_node)
5768

    
5769
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5770
                                           ignore_secondaries=True)
5771
      if not disks_ok:
5772
        _ShutdownInstanceDisks(self, instance)
5773
        raise errors.OpExecError("Can't activate the instance's disks")
5774

    
5775
      feedback_fn("* starting the instance on the target node")
5776
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5777
      msg = result.fail_msg
5778
      if msg:
5779
        _ShutdownInstanceDisks(self, instance)
5780
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5781
                                 (instance.name, target_node, msg))
5782

    
5783

    
5784
class LUInstanceMigrate(LogicalUnit):
5785
  """Migrate an instance.
5786

5787
  This is migration without shutting down, compared to the failover,
5788
  which is done with shutdown.
5789

5790
  """
5791
  HPATH = "instance-migrate"
5792
  HTYPE = constants.HTYPE_INSTANCE
5793
  REQ_BGL = False
5794

    
5795
  def ExpandNames(self):
5796
    self._ExpandAndLockInstance()
5797

    
5798
    self.needed_locks[locking.LEVEL_NODE] = []
5799
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5800

    
5801
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5802
                                       self.op.cleanup)
5803
    self.tasklets = [self._migrater]
5804

    
5805
  def DeclareLocks(self, level):
5806
    if level == locking.LEVEL_NODE:
5807
      self._LockInstancesNodes()
5808

    
5809
  def BuildHooksEnv(self):
5810
    """Build hooks env.
5811

5812
    This runs on master, primary and secondary nodes of the instance.
5813

5814
    """
5815
    instance = self._migrater.instance
5816
    source_node = instance.primary_node
5817
    target_node = instance.secondary_nodes[0]
5818
    env = _BuildInstanceHookEnvByObject(self, instance)
5819
    env["MIGRATE_LIVE"] = self._migrater.live
5820
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5821
    env.update({
5822
        "OLD_PRIMARY": source_node,
5823
        "OLD_SECONDARY": target_node,
5824
        "NEW_PRIMARY": target_node,
5825
        "NEW_SECONDARY": source_node,
5826
        })
5827
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5828
    nl_post = list(nl)
5829
    nl_post.append(source_node)
5830
    return env, nl, nl_post
5831

    
5832

    
5833
class LUInstanceMove(LogicalUnit):
5834
  """Move an instance by data-copying.
5835

5836
  """
5837
  HPATH = "instance-move"
5838
  HTYPE = constants.HTYPE_INSTANCE
5839
  REQ_BGL = False
5840

    
5841
  def ExpandNames(self):
5842
    self._ExpandAndLockInstance()
5843
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5844
    self.op.target_node = target_node
5845
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5846
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5847

    
5848
  def DeclareLocks(self, level):
5849
    if level == locking.LEVEL_NODE:
5850
      self._LockInstancesNodes(primary_only=True)
5851

    
5852
  def BuildHooksEnv(self):
5853
    """Build hooks env.
5854

5855
    This runs on master, primary and secondary nodes of the instance.
5856

5857
    """
5858
    env = {
5859
      "TARGET_NODE": self.op.target_node,
5860
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5861
      }
5862
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5863
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5864
                                       self.op.target_node]
5865
    return env, nl, nl
5866

    
5867
  def CheckPrereq(self):
5868
    """Check prerequisites.
5869

5870
    This checks that the instance is in the cluster.
5871

5872
    """
5873
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5874
    assert self.instance is not None, \
5875
      "Cannot retrieve locked instance %s" % self.op.instance_name
5876

    
5877
    node = self.cfg.GetNodeInfo(self.op.target_node)
5878
    assert node is not None, \
5879
      "Cannot retrieve locked node %s" % self.op.target_node
5880

    
5881
    self.target_node = target_node = node.name
5882

    
5883
    if target_node == instance.primary_node:
5884
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5885
                                 (instance.name, target_node),
5886
                                 errors.ECODE_STATE)
5887

    
5888
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5889

    
5890
    for idx, dsk in enumerate(instance.disks):
5891
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5892
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5893
                                   " cannot copy" % idx, errors.ECODE_STATE)
5894

    
5895
    _CheckNodeOnline(self, target_node)
5896
    _CheckNodeNotDrained(self, target_node)
5897
    _CheckNodeVmCapable(self, target_node)
5898

    
5899
    if instance.admin_up:
5900
      # check memory requirements on the secondary node
5901
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5902
                           instance.name, bep[constants.BE_MEMORY],
5903
                           instance.hypervisor)
5904
    else:
5905
      self.LogInfo("Not checking memory on the secondary node as"
5906
                   " instance will not be started")
5907

    
5908
    # check bridge existance
5909
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5910

    
5911
  def Exec(self, feedback_fn):
5912
    """Move an instance.
5913

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

5917
    """
5918
    instance = self.instance
5919

    
5920
    source_node = instance.primary_node
5921
    target_node = self.target_node
5922

    
5923
    self.LogInfo("Shutting down instance %s on source node %s",
5924
                 instance.name, source_node)
5925

    
5926
    result = self.rpc.call_instance_shutdown(source_node, instance,
5927
                                             self.op.shutdown_timeout)
5928
    msg = result.fail_msg
5929
    if msg:
5930
      if self.op.ignore_consistency:
5931
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5932
                             " Proceeding anyway. Please make sure node"
5933
                             " %s is down. Error details: %s",
5934
                             instance.name, source_node, source_node, msg)
5935
      else:
5936
        raise errors.OpExecError("Could not shutdown instance %s on"
5937
                                 " node %s: %s" %
5938
                                 (instance.name, source_node, msg))
5939

    
5940
    # create the target disks
5941
    try:
5942
      _CreateDisks(self, instance, target_node=target_node)
5943
    except errors.OpExecError:
5944
      self.LogWarning("Device creation failed, reverting...")
5945
      try:
5946
        _RemoveDisks(self, instance, target_node=target_node)
5947
      finally:
5948
        self.cfg.ReleaseDRBDMinors(instance.name)
5949
        raise
5950

    
5951
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5952

    
5953
    errs = []
5954
    # activate, get path, copy the data over
5955
    for idx, disk in enumerate(instance.disks):
5956
      self.LogInfo("Copying data for disk %d", idx)
5957
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5958
                                               instance.name, True, idx)
5959
      if result.fail_msg:
5960
        self.LogWarning("Can't assemble newly created disk %d: %s",
5961
                        idx, result.fail_msg)
5962
        errs.append(result.fail_msg)
5963
        break
5964
      dev_path = result.payload
5965
      result = self.rpc.call_blockdev_export(source_node, disk,
5966
                                             target_node, dev_path,
5967
                                             cluster_name)
5968
      if result.fail_msg:
5969
        self.LogWarning("Can't copy data over for disk %d: %s",
5970
                        idx, result.fail_msg)
5971
        errs.append(result.fail_msg)
5972
        break
5973

    
5974
    if errs:
5975
      self.LogWarning("Some disks failed to copy, aborting")
5976
      try:
5977
        _RemoveDisks(self, instance, target_node=target_node)
5978
      finally:
5979
        self.cfg.ReleaseDRBDMinors(instance.name)
5980
        raise errors.OpExecError("Errors during disk copy: %s" %
5981
                                 (",".join(errs),))
5982

    
5983
    instance.primary_node = target_node
5984
    self.cfg.Update(instance, feedback_fn)
5985

    
5986
    self.LogInfo("Removing the disks on the original node")
5987
    _RemoveDisks(self, instance, target_node=source_node)
5988

    
5989
    # Only start the instance if it's marked as up
5990
    if instance.admin_up:
5991
      self.LogInfo("Starting instance %s on node %s",
5992
                   instance.name, target_node)
5993

    
5994
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5995
                                           ignore_secondaries=True)
5996
      if not disks_ok:
5997
        _ShutdownInstanceDisks(self, instance)
5998
        raise errors.OpExecError("Can't activate the instance's disks")
5999

    
6000
      result = self.rpc.call_instance_start(target_node, instance, None, None)
6001
      msg = result.fail_msg
6002
      if msg:
6003
        _ShutdownInstanceDisks(self, instance)
6004
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
6005
                                 (instance.name, target_node, msg))
6006

    
6007

    
6008
class LUNodeMigrate(LogicalUnit):
6009
  """Migrate all instances from a node.
6010

6011
  """
6012
  HPATH = "node-migrate"
6013
  HTYPE = constants.HTYPE_NODE
6014
  REQ_BGL = False
6015

    
6016
  def ExpandNames(self):
6017
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6018

    
6019
    self.needed_locks = {
6020
      locking.LEVEL_NODE: [self.op.node_name],
6021
      }
6022

    
6023
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6024

    
6025
    # Create tasklets for migrating instances for all instances on this node
6026
    names = []
6027
    tasklets = []
6028

    
6029
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
6030
      logging.debug("Migrating instance %s", inst.name)
6031
      names.append(inst.name)
6032

    
6033
      tasklets.append(TLMigrateInstance(self, inst.name, False))
6034

    
6035
    self.tasklets = tasklets
6036

    
6037
    # Declare instance locks
6038
    self.needed_locks[locking.LEVEL_INSTANCE] = names
6039

    
6040
  def DeclareLocks(self, level):
6041
    if level == locking.LEVEL_NODE:
6042
      self._LockInstancesNodes()
6043

    
6044
  def BuildHooksEnv(self):
6045
    """Build hooks env.
6046

6047
    This runs on the master, the primary and all the secondaries.
6048

6049
    """
6050
    env = {
6051
      "NODE_NAME": self.op.node_name,
6052
      }
6053

    
6054
    nl = [self.cfg.GetMasterNode()]
6055

    
6056
    return (env, nl, nl)
6057

    
6058

    
6059
class TLMigrateInstance(Tasklet):
6060
  """Tasklet class for instance migration.
6061

6062
  @type live: boolean
6063
  @ivar live: whether the migration will be done live or non-live;
6064
      this variable is initalized only after CheckPrereq has run
6065

6066
  """
6067
  def __init__(self, lu, instance_name, cleanup):
6068
    """Initializes this class.
6069

6070
    """
6071
    Tasklet.__init__(self, lu)
6072

    
6073
    # Parameters
6074
    self.instance_name = instance_name
6075
    self.cleanup = cleanup
6076
    self.live = False # will be overridden later
6077

    
6078
  def CheckPrereq(self):
6079
    """Check prerequisites.
6080

6081
    This checks that the instance is in the cluster.
6082

6083
    """
6084
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
6085
    instance = self.cfg.GetInstanceInfo(instance_name)
6086
    assert instance is not None
6087

    
6088
    if instance.disk_template != constants.DT_DRBD8:
6089
      raise errors.OpPrereqError("Instance's disk layout is not"
6090
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
6091

    
6092
    secondary_nodes = instance.secondary_nodes
6093
    if not secondary_nodes:
6094
      raise errors.ConfigurationError("No secondary node but using"
6095
                                      " drbd8 disk template")
6096

    
6097
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
6098

    
6099
    target_node = secondary_nodes[0]
6100
    # check memory requirements on the secondary node
6101
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
6102
                         instance.name, i_be[constants.BE_MEMORY],
6103
                         instance.hypervisor)
6104

    
6105
    # check bridge existance
6106
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
6107

    
6108
    if not self.cleanup:
6109
      _CheckNodeNotDrained(self.lu, target_node)
6110
      result = self.rpc.call_instance_migratable(instance.primary_node,
6111
                                                 instance)
6112
      result.Raise("Can't migrate, please use failover",
6113
                   prereq=True, ecode=errors.ECODE_STATE)
6114

    
6115
    self.instance = instance
6116

    
6117
    if self.lu.op.live is not None and self.lu.op.mode is not None:
6118
      raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
6119
                                 " parameters are accepted",
6120
                                 errors.ECODE_INVAL)
6121
    if self.lu.op.live is not None:
6122
      if self.lu.op.live:
6123
        self.lu.op.mode = constants.HT_MIGRATION_LIVE
6124
      else:
6125
        self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6126
      # reset the 'live' parameter to None so that repeated
6127
      # invocations of CheckPrereq do not raise an exception
6128
      self.lu.op.live = None
6129
    elif self.lu.op.mode is None:
6130
      # read the default value from the hypervisor
6131
      i_hv = self.cfg.GetClusterInfo().FillHV(instance, skip_globals=False)
6132
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6133

    
6134
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6135

    
6136
  def _WaitUntilSync(self):
6137
    """Poll with custom rpc for disk sync.
6138

6139
    This uses our own step-based rpc call.
6140

6141
    """
6142
    self.feedback_fn("* wait until resync is done")
6143
    all_done = False
6144
    while not all_done:
6145
      all_done = True
6146
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6147
                                            self.nodes_ip,
6148
                                            self.instance.disks)
6149
      min_percent = 100
6150
      for node, nres in result.items():
6151
        nres.Raise("Cannot resync disks on node %s" % node)
6152
        node_done, node_percent = nres.payload
6153
        all_done = all_done and node_done
6154
        if node_percent is not None:
6155
          min_percent = min(min_percent, node_percent)
6156
      if not all_done:
6157
        if min_percent < 100:
6158
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6159
        time.sleep(2)
6160

    
6161
  def _EnsureSecondary(self, node):
6162
    """Demote a node to secondary.
6163

6164
    """
6165
    self.feedback_fn("* switching node %s to secondary mode" % node)
6166

    
6167
    for dev in self.instance.disks:
6168
      self.cfg.SetDiskID(dev, node)
6169

    
6170
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6171
                                          self.instance.disks)
6172
    result.Raise("Cannot change disk to secondary on node %s" % node)
6173

    
6174
  def _GoStandalone(self):
6175
    """Disconnect from the network.
6176

6177
    """
6178
    self.feedback_fn("* changing into standalone mode")
6179
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6180
                                               self.instance.disks)
6181
    for node, nres in result.items():
6182
      nres.Raise("Cannot disconnect disks node %s" % node)
6183

    
6184
  def _GoReconnect(self, multimaster):
6185
    """Reconnect to the network.
6186

6187
    """
6188
    if multimaster:
6189
      msg = "dual-master"
6190
    else:
6191
      msg = "single-master"
6192
    self.feedback_fn("* changing disks into %s mode" % msg)
6193
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6194
                                           self.instance.disks,
6195
                                           self.instance.name, multimaster)
6196
    for node, nres in result.items():
6197
      nres.Raise("Cannot change disks config on node %s" % node)
6198

    
6199
  def _ExecCleanup(self):
6200
    """Try to cleanup after a failed migration.
6201

6202
    The cleanup is done by:
6203
      - check that the instance is running only on one node
6204
        (and update the config if needed)
6205
      - change disks on its secondary node to secondary
6206
      - wait until disks are fully synchronized
6207
      - disconnect from the network
6208
      - change disks into single-master mode
6209
      - wait again until disks are fully synchronized
6210

6211
    """
6212
    instance = self.instance
6213
    target_node = self.target_node
6214
    source_node = self.source_node
6215

    
6216
    # check running on only one node
6217
    self.feedback_fn("* checking where the instance actually runs"
6218
                     " (if this hangs, the hypervisor might be in"
6219
                     " a bad state)")
6220
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
6221
    for node, result in ins_l.items():
6222
      result.Raise("Can't contact node %s" % node)
6223

    
6224
    runningon_source = instance.name in ins_l[source_node].payload
6225
    runningon_target = instance.name in ins_l[target_node].payload
6226

    
6227
    if runningon_source and runningon_target:
6228
      raise errors.OpExecError("Instance seems to be running on two nodes,"
6229
                               " or the hypervisor is confused. You will have"
6230
                               " to ensure manually that it runs only on one"
6231
                               " and restart this operation.")
6232

    
6233
    if not (runningon_source or runningon_target):
6234
      raise errors.OpExecError("Instance does not seem to be running at all."
6235
                               " In this case, it's safer to repair by"
6236
                               " running 'gnt-instance stop' to ensure disk"
6237
                               " shutdown, and then restarting it.")
6238

    
6239
    if runningon_target:
6240
      # the migration has actually succeeded, we need to update the config
6241
      self.feedback_fn("* instance running on secondary node (%s),"
6242
                       " updating config" % target_node)
6243
      instance.primary_node = target_node
6244
      self.cfg.Update(instance, self.feedback_fn)
6245
      demoted_node = source_node
6246
    else:
6247
      self.feedback_fn("* instance confirmed to be running on its"
6248
                       " primary node (%s)" % source_node)
6249
      demoted_node = target_node
6250

    
6251
    self._EnsureSecondary(demoted_node)
6252
    try:
6253
      self._WaitUntilSync()
6254
    except errors.OpExecError:
6255
      # we ignore here errors, since if the device is standalone, it
6256
      # won't be able to sync
6257
      pass
6258
    self._GoStandalone()
6259
    self._GoReconnect(False)
6260
    self._WaitUntilSync()
6261

    
6262
    self.feedback_fn("* done")
6263

    
6264
  def _RevertDiskStatus(self):
6265
    """Try to revert the disk status after a failed migration.
6266

6267
    """
6268
    target_node = self.target_node
6269
    try:
6270
      self._EnsureSecondary(target_node)
6271
      self._GoStandalone()
6272
      self._GoReconnect(False)
6273
      self._WaitUntilSync()
6274
    except errors.OpExecError, err:
6275
      self.lu.LogWarning("Migration failed and I can't reconnect the"
6276
                         " drives: error '%s'\n"
6277
                         "Please look and recover the instance status" %
6278
                         str(err))
6279

    
6280
  def _AbortMigration(self):
6281
    """Call the hypervisor code to abort a started migration.
6282

6283
    """
6284
    instance = self.instance
6285
    target_node = self.target_node
6286
    migration_info = self.migration_info
6287

    
6288
    abort_result = self.rpc.call_finalize_migration(target_node,
6289
                                                    instance,
6290
                                                    migration_info,
6291
                                                    False)
6292
    abort_msg = abort_result.fail_msg
6293
    if abort_msg:
6294
      logging.error("Aborting migration failed on target node %s: %s",
6295
                    target_node, abort_msg)
6296
      # Don't raise an exception here, as we stil have to try to revert the
6297
      # disk status, even if this step failed.
6298

    
6299
  def _ExecMigration(self):
6300
    """Migrate an instance.
6301

6302
    The migrate is done by:
6303
      - change the disks into dual-master mode
6304
      - wait until disks are fully synchronized again
6305
      - migrate the instance
6306
      - change disks on the new secondary node (the old primary) to secondary
6307
      - wait until disks are fully synchronized
6308
      - change disks into single-master mode
6309

6310
    """
6311
    instance = self.instance
6312
    target_node = self.target_node
6313
    source_node = self.source_node
6314

    
6315
    self.feedback_fn("* checking disk consistency between source and target")
6316
    for dev in instance.disks:
6317
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6318
        raise errors.OpExecError("Disk %s is degraded or not fully"
6319
                                 " synchronized on target node,"
6320
                                 " aborting migrate." % dev.iv_name)
6321

    
6322
    # First get the migration information from the remote node
6323
    result = self.rpc.call_migration_info(source_node, instance)
6324
    msg = result.fail_msg
6325
    if msg:
6326
      log_err = ("Failed fetching source migration information from %s: %s" %
6327
                 (source_node, msg))
6328
      logging.error(log_err)
6329
      raise errors.OpExecError(log_err)
6330

    
6331
    self.migration_info = migration_info = result.payload
6332

    
6333
    # Then switch the disks to master/master mode
6334
    self._EnsureSecondary(target_node)
6335
    self._GoStandalone()
6336
    self._GoReconnect(True)
6337
    self._WaitUntilSync()
6338

    
6339
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6340
    result = self.rpc.call_accept_instance(target_node,
6341
                                           instance,
6342
                                           migration_info,
6343
                                           self.nodes_ip[target_node])
6344

    
6345
    msg = result.fail_msg
6346
    if msg:
6347
      logging.error("Instance pre-migration failed, trying to revert"
6348
                    " disk status: %s", msg)
6349
      self.feedback_fn("Pre-migration failed, aborting")
6350
      self._AbortMigration()
6351
      self._RevertDiskStatus()
6352
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6353
                               (instance.name, msg))
6354

    
6355
    self.feedback_fn("* migrating instance to %s" % target_node)
6356
    time.sleep(10)
6357
    result = self.rpc.call_instance_migrate(source_node, instance,
6358
                                            self.nodes_ip[target_node],
6359
                                            self.live)
6360
    msg = result.fail_msg
6361
    if msg:
6362
      logging.error("Instance migration failed, trying to revert"
6363
                    " disk status: %s", msg)
6364
      self.feedback_fn("Migration failed, aborting")
6365
      self._AbortMigration()
6366
      self._RevertDiskStatus()
6367
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6368
                               (instance.name, msg))
6369
    time.sleep(10)
6370

    
6371
    instance.primary_node = target_node
6372
    # distribute new instance config to the other nodes
6373
    self.cfg.Update(instance, self.feedback_fn)
6374

    
6375
    result = self.rpc.call_finalize_migration(target_node,
6376
                                              instance,
6377
                                              migration_info,
6378
                                              True)
6379
    msg = result.fail_msg
6380
    if msg:
6381
      logging.error("Instance migration succeeded, but finalization failed:"
6382
                    " %s", msg)
6383
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6384
                               msg)
6385

    
6386
    self._EnsureSecondary(source_node)
6387
    self._WaitUntilSync()
6388
    self._GoStandalone()
6389
    self._GoReconnect(False)
6390
    self._WaitUntilSync()
6391

    
6392
    self.feedback_fn("* done")
6393

    
6394
  def Exec(self, feedback_fn):
6395
    """Perform the migration.
6396

6397
    """
6398
    feedback_fn("Migrating instance %s" % self.instance.name)
6399

    
6400
    self.feedback_fn = feedback_fn
6401

    
6402
    self.source_node = self.instance.primary_node
6403
    self.target_node = self.instance.secondary_nodes[0]
6404
    self.all_nodes = [self.source_node, self.target_node]
6405
    self.nodes_ip = {
6406
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6407
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6408
      }
6409

    
6410
    if self.cleanup:
6411
      return self._ExecCleanup()
6412
    else:
6413
      return self._ExecMigration()
6414

    
6415

    
6416
def _CreateBlockDev(lu, node, instance, device, force_create,
6417
                    info, force_open):
6418
  """Create a tree of block devices on a given node.
6419

6420
  If this device type has to be created on secondaries, create it and
6421
  all its children.
6422

6423
  If not, just recurse to children keeping the same 'force' value.
6424

6425
  @param lu: the lu on whose behalf we execute
6426
  @param node: the node on which to create the device
6427
  @type instance: L{objects.Instance}
6428
  @param instance: the instance which owns the device
6429
  @type device: L{objects.Disk}
6430
  @param device: the device to create
6431
  @type force_create: boolean
6432
  @param force_create: whether to force creation of this device; this
6433
      will be change to True whenever we find a device which has
6434
      CreateOnSecondary() attribute
6435
  @param info: the extra 'metadata' we should attach to the device
6436
      (this will be represented as a LVM tag)
6437
  @type force_open: boolean
6438
  @param force_open: this parameter will be passes to the
6439
      L{backend.BlockdevCreate} function where it specifies
6440
      whether we run on primary or not, and it affects both
6441
      the child assembly and the device own Open() execution
6442

6443
  """
6444
  if device.CreateOnSecondary():
6445
    force_create = True
6446

    
6447
  if device.children:
6448
    for child in device.children:
6449
      _CreateBlockDev(lu, node, instance, child, force_create,
6450
                      info, force_open)
6451

    
6452
  if not force_create:
6453
    return
6454

    
6455
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6456

    
6457

    
6458
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6459
  """Create a single block device on a given node.
6460

6461
  This will not recurse over children of the device, so they must be
6462
  created in advance.
6463

6464
  @param lu: the lu on whose behalf we execute
6465
  @param node: the node on which to create the device
6466
  @type instance: L{objects.Instance}
6467
  @param instance: the instance which owns the device
6468
  @type device: L{objects.Disk}
6469
  @param device: the device to create
6470
  @param info: the extra 'metadata' we should attach to the device
6471
      (this will be represented as a LVM tag)
6472
  @type force_open: boolean
6473
  @param force_open: this parameter will be passes to the
6474
      L{backend.BlockdevCreate} function where it specifies
6475
      whether we run on primary or not, and it affects both
6476
      the child assembly and the device own Open() execution
6477

6478
  """
6479
  lu.cfg.SetDiskID(device, node)
6480
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6481
                                       instance.name, force_open, info)
6482
  result.Raise("Can't create block device %s on"
6483
               " node %s for instance %s" % (device, node, instance.name))
6484
  if device.physical_id is None:
6485
    device.physical_id = result.payload
6486

    
6487

    
6488
def _GenerateUniqueNames(lu, exts):
6489
  """Generate a suitable LV name.
6490

6491
  This will generate a logical volume name for the given instance.
6492

6493
  """
6494
  results = []
6495
  for val in exts:
6496
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6497
    results.append("%s%s" % (new_id, val))
6498
  return results
6499

    
6500

    
6501
def _GenerateDRBD8Branch(lu, primary, secondary, size, vgname, names, iv_name,
6502
                         p_minor, s_minor):
6503
  """Generate a drbd8 device complete with its children.
6504

6505
  """
6506
  port = lu.cfg.AllocatePort()
6507
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6508
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6509
                          logical_id=(vgname, names[0]))
6510
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6511
                          logical_id=(vgname, names[1]))
6512
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6513
                          logical_id=(primary, secondary, port,
6514
                                      p_minor, s_minor,
6515
                                      shared_secret),
6516
                          children=[dev_data, dev_meta],
6517
                          iv_name=iv_name)
6518
  return drbd_dev
6519

    
6520

    
6521
def _GenerateDiskTemplate(lu, template_name,
6522
                          instance_name, primary_node,
6523
                          secondary_nodes, disk_info,
6524
                          file_storage_dir, file_driver,
6525
                          base_index, feedback_fn):
6526
  """Generate the entire disk layout for a given template type.
6527

6528
  """
6529
  #TODO: compute space requirements
6530

    
6531
  vgname = lu.cfg.GetVGName()
6532
  disk_count = len(disk_info)
6533
  disks = []
6534
  if template_name == constants.DT_DISKLESS:
6535
    pass
6536
  elif template_name == constants.DT_PLAIN:
6537
    if len(secondary_nodes) != 0:
6538
      raise errors.ProgrammerError("Wrong template configuration")
6539

    
6540
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6541
                                      for i in range(disk_count)])
6542
    for idx, disk in enumerate(disk_info):
6543
      disk_index = idx + base_index
6544
      vg = disk.get("vg", vgname)
6545
      feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
6546
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6547
                              logical_id=(vg, names[idx]),
6548
                              iv_name="disk/%d" % disk_index,
6549
                              mode=disk["mode"])
6550
      disks.append(disk_dev)
6551
  elif template_name == constants.DT_DRBD8:
6552
    if len(secondary_nodes) != 1:
6553
      raise errors.ProgrammerError("Wrong template configuration")
6554
    remote_node = secondary_nodes[0]
6555
    minors = lu.cfg.AllocateDRBDMinor(
6556
      [primary_node, remote_node] * len(disk_info), instance_name)
6557

    
6558
    names = []
6559
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6560
                                               for i in range(disk_count)]):
6561
      names.append(lv_prefix + "_data")
6562
      names.append(lv_prefix + "_meta")
6563
    for idx, disk in enumerate(disk_info):
6564
      disk_index = idx + base_index
6565
      vg = disk.get("vg", vgname)
6566
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6567
                                      disk["size"], vg, names[idx*2:idx*2+2],
6568
                                      "disk/%d" % disk_index,
6569
                                      minors[idx*2], minors[idx*2+1])
6570
      disk_dev.mode = disk["mode"]
6571
      disks.append(disk_dev)
6572
  elif template_name == constants.DT_FILE:
6573
    if len(secondary_nodes) != 0:
6574
      raise errors.ProgrammerError("Wrong template configuration")
6575

    
6576
    opcodes.RequireFileStorage()
6577

    
6578
    for idx, disk in enumerate(disk_info):
6579
      disk_index = idx + base_index
6580
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6581
                              iv_name="disk/%d" % disk_index,
6582
                              logical_id=(file_driver,
6583
                                          "%s/disk%d" % (file_storage_dir,
6584
                                                         disk_index)),
6585
                              mode=disk["mode"])
6586
      disks.append(disk_dev)
6587
  else:
6588
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6589
  return disks
6590

    
6591

    
6592
def _GetInstanceInfoText(instance):
6593
  """Compute that text that should be added to the disk's metadata.
6594

6595
  """
6596
  return "originstname+%s" % instance.name
6597

    
6598

    
6599
def _CalcEta(time_taken, written, total_size):
6600
  """Calculates the ETA based on size written and total size.
6601

6602
  @param time_taken: The time taken so far
6603
  @param written: amount written so far
6604
  @param total_size: The total size of data to be written
6605
  @return: The remaining time in seconds
6606

6607
  """
6608
  avg_time = time_taken / float(written)
6609
  return (total_size - written) * avg_time
6610

    
6611

    
6612
def _WipeDisks(lu, instance):
6613
  """Wipes instance disks.
6614

6615
  @type lu: L{LogicalUnit}
6616
  @param lu: the logical unit on whose behalf we execute
6617
  @type instance: L{objects.Instance}
6618
  @param instance: the instance whose disks we should create
6619
  @return: the success of the wipe
6620

6621
  """
6622
  node = instance.primary_node
6623
  logging.info("Pause sync of instance %s disks", instance.name)
6624
  result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, True)
6625

    
6626
  for idx, success in enumerate(result.payload):
6627
    if not success:
6628
      logging.warn("pause-sync of instance %s for disks %d failed",
6629
                   instance.name, idx)
6630

    
6631
  try:
6632
    for idx, device in enumerate(instance.disks):
6633
      lu.LogInfo("* Wiping disk %d", idx)
6634
      logging.info("Wiping disk %d for instance %s", idx, instance.name)
6635

    
6636
      # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
6637
      # MAX_WIPE_CHUNK at max
6638
      wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
6639
                            constants.MIN_WIPE_CHUNK_PERCENT)
6640

    
6641
      offset = 0
6642
      size = device.size
6643
      last_output = 0
6644
      start_time = time.time()
6645

    
6646
      while offset < size:
6647
        wipe_size = min(wipe_chunk_size, size - offset)
6648
        result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
6649
        result.Raise("Could not wipe disk %d at offset %d for size %d" %
6650
                     (idx, offset, wipe_size))
6651
        now = time.time()
6652
        offset += wipe_size
6653
        if now - last_output >= 60:
6654
          eta = _CalcEta(now - start_time, offset, size)
6655
          lu.LogInfo(" - done: %.1f%% ETA: %s" %
6656
                     (offset / float(size) * 100, utils.FormatSeconds(eta)))
6657
          last_output = now
6658
  finally:
6659
    logging.info("Resume sync of instance %s disks", instance.name)
6660

    
6661
    result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, False)
6662

    
6663
    for idx, success in enumerate(result.payload):
6664
      if not success:
6665
        lu.LogWarning("Warning: Resume sync of disk %d failed. Please have a"
6666
                      " look at the status and troubleshoot the issue.", idx)
6667
        logging.warn("resume-sync of instance %s for disks %d failed",
6668
                     instance.name, idx)
6669

    
6670

    
6671
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6672
  """Create all disks for an instance.
6673

6674
  This abstracts away some work from AddInstance.
6675

6676
  @type lu: L{LogicalUnit}
6677
  @param lu: the logical unit on whose behalf we execute
6678
  @type instance: L{objects.Instance}
6679
  @param instance: the instance whose disks we should create
6680
  @type to_skip: list
6681
  @param to_skip: list of indices to skip
6682
  @type target_node: string
6683
  @param target_node: if passed, overrides the target node for creation
6684
  @rtype: boolean
6685
  @return: the success of the creation
6686

6687
  """
6688
  info = _GetInstanceInfoText(instance)
6689
  if target_node is None:
6690
    pnode = instance.primary_node
6691
    all_nodes = instance.all_nodes
6692
  else:
6693
    pnode = target_node
6694
    all_nodes = [pnode]
6695

    
6696
  if instance.disk_template == constants.DT_FILE:
6697
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6698
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6699

    
6700
    result.Raise("Failed to create directory '%s' on"
6701
                 " node %s" % (file_storage_dir, pnode))
6702

    
6703
  # Note: this needs to be kept in sync with adding of disks in
6704
  # LUInstanceSetParams
6705
  for idx, device in enumerate(instance.disks):
6706
    if to_skip and idx in to_skip:
6707
      continue
6708
    logging.info("Creating volume %s for instance %s",
6709
                 device.iv_name, instance.name)
6710
    #HARDCODE
6711
    for node in all_nodes:
6712
      f_create = node == pnode
6713
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6714

    
6715

    
6716
def _RemoveDisks(lu, instance, target_node=None):
6717
  """Remove all disks for an instance.
6718

6719
  This abstracts away some work from `AddInstance()` and
6720
  `RemoveInstance()`. Note that in case some of the devices couldn't
6721
  be removed, the removal will continue with the other ones (compare
6722
  with `_CreateDisks()`).
6723

6724
  @type lu: L{LogicalUnit}
6725
  @param lu: the logical unit on whose behalf we execute
6726
  @type instance: L{objects.Instance}
6727
  @param instance: the instance whose disks we should remove
6728
  @type target_node: string
6729
  @param target_node: used to override the node on which to remove the disks
6730
  @rtype: boolean
6731
  @return: the success of the removal
6732

6733
  """
6734
  logging.info("Removing block devices for instance %s", instance.name)
6735

    
6736
  all_result = True
6737
  for device in instance.disks:
6738
    if target_node:
6739
      edata = [(target_node, device)]
6740
    else:
6741
      edata = device.ComputeNodeTree(instance.primary_node)
6742
    for node, disk in edata:
6743
      lu.cfg.SetDiskID(disk, node)
6744
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6745
      if msg:
6746
        lu.LogWarning("Could not remove block device %s on node %s,"
6747
                      " continuing anyway: %s", device.iv_name, node, msg)
6748
        all_result = False
6749

    
6750
  if instance.disk_template == constants.DT_FILE:
6751
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6752
    if target_node:
6753
      tgt = target_node
6754
    else:
6755
      tgt = instance.primary_node
6756
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6757
    if result.fail_msg:
6758
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6759
                    file_storage_dir, instance.primary_node, result.fail_msg)
6760
      all_result = False
6761

    
6762
  return all_result
6763

    
6764

    
6765
def _ComputeDiskSizePerVG(disk_template, disks):
6766
  """Compute disk size requirements in the volume group
6767

6768
  """
6769
  def _compute(disks, payload):
6770
    """Universal algorithm
6771

6772
    """
6773
    vgs = {}
6774
    for disk in disks:
6775
      vgs[disk["vg"]] = vgs.get("vg", 0) + disk["size"] + payload
6776

    
6777
    return vgs
6778

    
6779
  # Required free disk space as a function of disk and swap space
6780
  req_size_dict = {
6781
    constants.DT_DISKLESS: {},
6782
    constants.DT_PLAIN: _compute(disks, 0),
6783
    # 128 MB are added for drbd metadata for each disk
6784
    constants.DT_DRBD8: _compute(disks, 128),
6785
    constants.DT_FILE: {},
6786
  }
6787

    
6788
  if disk_template not in req_size_dict:
6789
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6790
                                 " is unknown" %  disk_template)
6791

    
6792
  return req_size_dict[disk_template]
6793

    
6794

    
6795
def _ComputeDiskSize(disk_template, disks):
6796
  """Compute disk size requirements in the volume group
6797

6798
  """
6799
  # Required free disk space as a function of disk and swap space
6800
  req_size_dict = {
6801
    constants.DT_DISKLESS: None,
6802
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6803
    # 128 MB are added for drbd metadata for each disk
6804
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6805
    constants.DT_FILE: None,
6806
  }
6807

    
6808
  if disk_template not in req_size_dict:
6809
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6810
                                 " is unknown" %  disk_template)
6811

    
6812
  return req_size_dict[disk_template]
6813

    
6814

    
6815
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6816
  """Hypervisor parameter validation.
6817

6818
  This function abstract the hypervisor parameter validation to be
6819
  used in both instance create and instance modify.
6820

6821
  @type lu: L{LogicalUnit}
6822
  @param lu: the logical unit for which we check
6823
  @type nodenames: list
6824
  @param nodenames: the list of nodes on which we should check
6825
  @type hvname: string
6826
  @param hvname: the name of the hypervisor we should use
6827
  @type hvparams: dict
6828
  @param hvparams: the parameters which we need to check
6829
  @raise errors.OpPrereqError: if the parameters are not valid
6830

6831
  """
6832
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6833
                                                  hvname,
6834
                                                  hvparams)
6835
  for node in nodenames:
6836
    info = hvinfo[node]
6837
    if info.offline:
6838
      continue
6839
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6840

    
6841

    
6842
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6843
  """OS parameters validation.
6844

6845
  @type lu: L{LogicalUnit}
6846
  @param lu: the logical unit for which we check
6847
  @type required: boolean
6848
  @param required: whether the validation should fail if the OS is not
6849
      found
6850
  @type nodenames: list
6851
  @param nodenames: the list of nodes on which we should check
6852
  @type osname: string
6853
  @param osname: the name of the hypervisor we should use
6854
  @type osparams: dict
6855
  @param osparams: the parameters which we need to check
6856
  @raise errors.OpPrereqError: if the parameters are not valid
6857

6858
  """
6859
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6860
                                   [constants.OS_VALIDATE_PARAMETERS],
6861
                                   osparams)
6862
  for node, nres in result.items():
6863
    # we don't check for offline cases since this should be run only
6864
    # against the master node and/or an instance's nodes
6865
    nres.Raise("OS Parameters validation failed on node %s" % node)
6866
    if not nres.payload:
6867
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6868
                 osname, node)
6869

    
6870

    
6871
class LUInstanceCreate(LogicalUnit):
6872
  """Create an instance.
6873

6874
  """
6875
  HPATH = "instance-add"
6876
  HTYPE = constants.HTYPE_INSTANCE
6877
  REQ_BGL = False
6878

    
6879
  def CheckArguments(self):
6880
    """Check arguments.
6881

6882
    """
6883
    # do not require name_check to ease forward/backward compatibility
6884
    # for tools
6885
    if self.op.no_install and self.op.start:
6886
      self.LogInfo("No-installation mode selected, disabling startup")
6887
      self.op.start = False
6888
    # validate/normalize the instance name
6889
    self.op.instance_name = \
6890
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
6891

    
6892
    if self.op.ip_check and not self.op.name_check:
6893
      # TODO: make the ip check more flexible and not depend on the name check
6894
      raise errors.OpPrereqError("Cannot do ip check without a name check",
6895
                                 errors.ECODE_INVAL)
6896

    
6897
    # check nics' parameter names
6898
    for nic in self.op.nics:
6899
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6900

    
6901
    # check disks. parameter names and consistent adopt/no-adopt strategy
6902
    has_adopt = has_no_adopt = False
6903
    for disk in self.op.disks:
6904
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6905
      if "adopt" in disk:
6906
        has_adopt = True
6907
      else:
6908
        has_no_adopt = True
6909
    if has_adopt and has_no_adopt:
6910
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6911
                                 errors.ECODE_INVAL)
6912
    if has_adopt:
6913
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6914
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6915
                                   " '%s' disk template" %
6916
                                   self.op.disk_template,
6917
                                   errors.ECODE_INVAL)
6918
      if self.op.iallocator is not None:
6919
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6920
                                   " iallocator script", errors.ECODE_INVAL)
6921
      if self.op.mode == constants.INSTANCE_IMPORT:
6922
        raise errors.OpPrereqError("Disk adoption not allowed for"
6923
                                   " instance import", errors.ECODE_INVAL)
6924

    
6925
    self.adopt_disks = has_adopt
6926

    
6927
    # instance name verification
6928
    if self.op.name_check:
6929
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
6930
      self.op.instance_name = self.hostname1.name
6931
      # used in CheckPrereq for ip ping check
6932
      self.check_ip = self.hostname1.ip
6933
    else:
6934
      self.check_ip = None
6935

    
6936
    # file storage checks
6937
    if (self.op.file_driver and
6938
        not self.op.file_driver in constants.FILE_DRIVER):
6939
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6940
                                 self.op.file_driver, errors.ECODE_INVAL)
6941

    
6942
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6943
      raise errors.OpPrereqError("File storage directory path not absolute",
6944
                                 errors.ECODE_INVAL)
6945

    
6946
    ### Node/iallocator related checks
6947
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
6948

    
6949
    if self.op.pnode is not None:
6950
      if self.op.disk_template in constants.DTS_NET_MIRROR:
6951
        if self.op.snode is None:
6952
          raise errors.OpPrereqError("The networked disk templates need"
6953
                                     " a mirror node", errors.ECODE_INVAL)
6954
      elif self.op.snode:
6955
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
6956
                        " template")
6957
        self.op.snode = None
6958

    
6959
    self._cds = _GetClusterDomainSecret()
6960

    
6961
    if self.op.mode == constants.INSTANCE_IMPORT:
6962
      # On import force_variant must be True, because if we forced it at
6963
      # initial install, our only chance when importing it back is that it
6964
      # works again!
6965
      self.op.force_variant = True
6966

    
6967
      if self.op.no_install:
6968
        self.LogInfo("No-installation mode has no effect during import")
6969

    
6970
    elif self.op.mode == constants.INSTANCE_CREATE:
6971
      if self.op.os_type is None:
6972
        raise errors.OpPrereqError("No guest OS specified",
6973
                                   errors.ECODE_INVAL)
6974
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
6975
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
6976
                                   " installation" % self.op.os_type,
6977
                                   errors.ECODE_STATE)
6978
      if self.op.disk_template is None:
6979
        raise errors.OpPrereqError("No disk template specified",
6980
                                   errors.ECODE_INVAL)
6981

    
6982
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6983
      # Check handshake to ensure both clusters have the same domain secret
6984
      src_handshake = self.op.source_handshake
6985
      if not src_handshake:
6986
        raise errors.OpPrereqError("Missing source handshake",
6987
                                   errors.ECODE_INVAL)
6988

    
6989
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6990
                                                           src_handshake)
6991
      if errmsg:
6992
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6993
                                   errors.ECODE_INVAL)
6994

    
6995
      # Load and check source CA
6996
      self.source_x509_ca_pem = self.op.source_x509_ca
6997
      if not self.source_x509_ca_pem:
6998
        raise errors.OpPrereqError("Missing source X509 CA",
6999
                                   errors.ECODE_INVAL)
7000

    
7001
      try:
7002
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
7003
                                                    self._cds)
7004
      except OpenSSL.crypto.Error, err:
7005
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
7006
                                   (err, ), errors.ECODE_INVAL)
7007

    
7008
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
7009
      if errcode is not None:
7010
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
7011
                                   errors.ECODE_INVAL)
7012

    
7013
      self.source_x509_ca = cert
7014

    
7015
      src_instance_name = self.op.source_instance_name
7016
      if not src_instance_name:
7017
        raise errors.OpPrereqError("Missing source instance name",
7018
                                   errors.ECODE_INVAL)
7019

    
7020
      self.source_instance_name = \
7021
          netutils.GetHostname(name=src_instance_name).name
7022

    
7023
    else:
7024
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
7025
                                 self.op.mode, errors.ECODE_INVAL)
7026

    
7027
  def ExpandNames(self):
7028
    """ExpandNames for CreateInstance.
7029

7030
    Figure out the right locks for instance creation.
7031

7032
    """
7033
    self.needed_locks = {}
7034

    
7035
    instance_name = self.op.instance_name
7036
    # this is just a preventive check, but someone might still add this
7037
    # instance in the meantime, and creation will fail at lock-add time
7038
    if instance_name in self.cfg.GetInstanceList():
7039
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
7040
                                 instance_name, errors.ECODE_EXISTS)
7041

    
7042
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
7043

    
7044
    if self.op.iallocator:
7045
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7046
    else:
7047
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
7048
      nodelist = [self.op.pnode]
7049
      if self.op.snode is not None:
7050
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
7051
        nodelist.append(self.op.snode)
7052
      self.needed_locks[locking.LEVEL_NODE] = nodelist
7053

    
7054
    # in case of import lock the source node too
7055
    if self.op.mode == constants.INSTANCE_IMPORT:
7056
      src_node = self.op.src_node
7057
      src_path = self.op.src_path
7058

    
7059
      if src_path is None:
7060
        self.op.src_path = src_path = self.op.instance_name
7061

    
7062
      if src_node is None:
7063
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7064
        self.op.src_node = None
7065
        if os.path.isabs(src_path):
7066
          raise errors.OpPrereqError("Importing an instance from an absolute"
7067
                                     " path requires a source node option.",
7068
                                     errors.ECODE_INVAL)
7069
      else:
7070
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
7071
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
7072
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
7073
        if not os.path.isabs(src_path):
7074
          self.op.src_path = src_path = \
7075
            utils.PathJoin(constants.EXPORT_DIR, src_path)
7076

    
7077
  def _RunAllocator(self):
7078
    """Run the allocator based on input opcode.
7079

7080
    """
7081
    nics = [n.ToDict() for n in self.nics]
7082
    ial = IAllocator(self.cfg, self.rpc,
7083
                     mode=constants.IALLOCATOR_MODE_ALLOC,
7084
                     name=self.op.instance_name,
7085
                     disk_template=self.op.disk_template,
7086
                     tags=[],
7087
                     os=self.op.os_type,
7088
                     vcpus=self.be_full[constants.BE_VCPUS],
7089
                     mem_size=self.be_full[constants.BE_MEMORY],
7090
                     disks=self.disks,
7091
                     nics=nics,
7092
                     hypervisor=self.op.hypervisor,
7093
                     )
7094

    
7095
    ial.Run(self.op.iallocator)
7096

    
7097
    if not ial.success:
7098
      raise errors.OpPrereqError("Can't compute nodes using"
7099
                                 " iallocator '%s': %s" %
7100
                                 (self.op.iallocator, ial.info),
7101
                                 errors.ECODE_NORES)
7102
    if len(ial.result) != ial.required_nodes:
7103
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7104
                                 " of nodes (%s), required %s" %
7105
                                 (self.op.iallocator, len(ial.result),
7106
                                  ial.required_nodes), errors.ECODE_FAULT)
7107
    self.op.pnode = ial.result[0]
7108
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
7109
                 self.op.instance_name, self.op.iallocator,
7110
                 utils.CommaJoin(ial.result))
7111
    if ial.required_nodes == 2:
7112
      self.op.snode = ial.result[1]
7113

    
7114
  def BuildHooksEnv(self):
7115
    """Build hooks env.
7116

7117
    This runs on master, primary and secondary nodes of the instance.
7118

7119
    """
7120
    env = {
7121
      "ADD_MODE": self.op.mode,
7122
      }
7123
    if self.op.mode == constants.INSTANCE_IMPORT:
7124
      env["SRC_NODE"] = self.op.src_node
7125
      env["SRC_PATH"] = self.op.src_path
7126
      env["SRC_IMAGES"] = self.src_images
7127

    
7128
    env.update(_BuildInstanceHookEnv(
7129
      name=self.op.instance_name,
7130
      primary_node=self.op.pnode,
7131
      secondary_nodes=self.secondaries,
7132
      status=self.op.start,
7133
      os_type=self.op.os_type,
7134
      memory=self.be_full[constants.BE_MEMORY],
7135
      vcpus=self.be_full[constants.BE_VCPUS],
7136
      nics=_NICListToTuple(self, self.nics),
7137
      disk_template=self.op.disk_template,
7138
      disks=[(d["size"], d["mode"]) for d in self.disks],
7139
      bep=self.be_full,
7140
      hvp=self.hv_full,
7141
      hypervisor_name=self.op.hypervisor,
7142
    ))
7143

    
7144
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
7145
          self.secondaries)
7146
    return env, nl, nl
7147

    
7148
  def _ReadExportInfo(self):
7149
    """Reads the export information from disk.
7150

7151
    It will override the opcode source node and path with the actual
7152
    information, if these two were not specified before.
7153

7154
    @return: the export information
7155

7156
    """
7157
    assert self.op.mode == constants.INSTANCE_IMPORT
7158

    
7159
    src_node = self.op.src_node
7160
    src_path = self.op.src_path
7161

    
7162
    if src_node is None:
7163
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
7164
      exp_list = self.rpc.call_export_list(locked_nodes)
7165
      found = False
7166
      for node in exp_list:
7167
        if exp_list[node].fail_msg:
7168
          continue
7169
        if src_path in exp_list[node].payload:
7170
          found = True
7171
          self.op.src_node = src_node = node
7172
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
7173
                                                       src_path)
7174
          break
7175
      if not found:
7176
        raise errors.OpPrereqError("No export found for relative path %s" %
7177
                                    src_path, errors.ECODE_INVAL)
7178

    
7179
    _CheckNodeOnline(self, src_node)
7180
    result = self.rpc.call_export_info(src_node, src_path)
7181
    result.Raise("No export or invalid export found in dir %s" % src_path)
7182

    
7183
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
7184
    if not export_info.has_section(constants.INISECT_EXP):
7185
      raise errors.ProgrammerError("Corrupted export config",
7186
                                   errors.ECODE_ENVIRON)
7187

    
7188
    ei_version = export_info.get(constants.INISECT_EXP, "version")
7189
    if (int(ei_version) != constants.EXPORT_VERSION):
7190
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
7191
                                 (ei_version, constants.EXPORT_VERSION),
7192
                                 errors.ECODE_ENVIRON)
7193
    return export_info
7194

    
7195
  def _ReadExportParams(self, einfo):
7196
    """Use export parameters as defaults.
7197

7198
    In case the opcode doesn't specify (as in override) some instance
7199
    parameters, then try to use them from the export information, if
7200
    that declares them.
7201

7202
    """
7203
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
7204

    
7205
    if self.op.disk_template is None:
7206
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
7207
        self.op.disk_template = einfo.get(constants.INISECT_INS,
7208
                                          "disk_template")
7209
      else:
7210
        raise errors.OpPrereqError("No disk template specified and the export"
7211
                                   " is missing the disk_template information",
7212
                                   errors.ECODE_INVAL)
7213

    
7214
    if not self.op.disks:
7215
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
7216
        disks = []
7217
        # TODO: import the disk iv_name too
7218
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
7219
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
7220
          disks.append({"size": disk_sz})
7221
        self.op.disks = disks
7222
      else:
7223
        raise errors.OpPrereqError("No disk info specified and the export"
7224
                                   " is missing the disk information",
7225
                                   errors.ECODE_INVAL)
7226

    
7227
    if (not self.op.nics and
7228
        einfo.has_option(constants.INISECT_INS, "nic_count")):
7229
      nics = []
7230
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
7231
        ndict = {}
7232
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
7233
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
7234
          ndict[name] = v
7235
        nics.append(ndict)
7236
      self.op.nics = nics
7237

    
7238
    if (self.op.hypervisor is None and
7239
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
7240
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
7241
    if einfo.has_section(constants.INISECT_HYP):
7242
      # use the export parameters but do not override the ones
7243
      # specified by the user
7244
      for name, value in einfo.items(constants.INISECT_HYP):
7245
        if name not in self.op.hvparams:
7246
          self.op.hvparams[name] = value
7247

    
7248
    if einfo.has_section(constants.INISECT_BEP):
7249
      # use the parameters, without overriding
7250
      for name, value in einfo.items(constants.INISECT_BEP):
7251
        if name not in self.op.beparams:
7252
          self.op.beparams[name] = value
7253
    else:
7254
      # try to read the parameters old style, from the main section
7255
      for name in constants.BES_PARAMETERS:
7256
        if (name not in self.op.beparams and
7257
            einfo.has_option(constants.INISECT_INS, name)):
7258
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
7259

    
7260
    if einfo.has_section(constants.INISECT_OSP):
7261
      # use the parameters, without overriding
7262
      for name, value in einfo.items(constants.INISECT_OSP):
7263
        if name not in self.op.osparams:
7264
          self.op.osparams[name] = value
7265

    
7266
  def _RevertToDefaults(self, cluster):
7267
    """Revert the instance parameters to the default values.
7268

7269
    """
7270
    # hvparams
7271
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
7272
    for name in self.op.hvparams.keys():
7273
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
7274
        del self.op.hvparams[name]
7275
    # beparams
7276
    be_defs = cluster.SimpleFillBE({})
7277
    for name in self.op.beparams.keys():
7278
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
7279
        del self.op.beparams[name]
7280
    # nic params
7281
    nic_defs = cluster.SimpleFillNIC({})
7282
    for nic in self.op.nics:
7283
      for name in constants.NICS_PARAMETERS:
7284
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
7285
          del nic[name]
7286
    # osparams
7287
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
7288
    for name in self.op.osparams.keys():
7289
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
7290
        del self.op.osparams[name]
7291

    
7292
  def CheckPrereq(self):
7293
    """Check prerequisites.
7294

7295
    """
7296
    if self.op.mode == constants.INSTANCE_IMPORT:
7297
      export_info = self._ReadExportInfo()
7298
      self._ReadExportParams(export_info)
7299

    
7300
    if (not self.cfg.GetVGName() and
7301
        self.op.disk_template not in constants.DTS_NOT_LVM):
7302
      raise errors.OpPrereqError("Cluster does not support lvm-based"
7303
                                 " instances", errors.ECODE_STATE)
7304

    
7305
    if self.op.hypervisor is None:
7306
      self.op.hypervisor = self.cfg.GetHypervisorType()
7307

    
7308
    cluster = self.cfg.GetClusterInfo()
7309
    enabled_hvs = cluster.enabled_hypervisors
7310
    if self.op.hypervisor not in enabled_hvs:
7311
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
7312
                                 " cluster (%s)" % (self.op.hypervisor,
7313
                                  ",".join(enabled_hvs)),
7314
                                 errors.ECODE_STATE)
7315

    
7316
    # check hypervisor parameter syntax (locally)
7317
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
7318
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
7319
                                      self.op.hvparams)
7320
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
7321
    hv_type.CheckParameterSyntax(filled_hvp)
7322
    self.hv_full = filled_hvp
7323
    # check that we don't specify global parameters on an instance
7324
    _CheckGlobalHvParams(self.op.hvparams)
7325

    
7326
    # fill and remember the beparams dict
7327
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
7328
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
7329

    
7330
    # build os parameters
7331
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
7332

    
7333
    # now that hvp/bep are in final format, let's reset to defaults,
7334
    # if told to do so
7335
    if self.op.identify_defaults:
7336
      self._RevertToDefaults(cluster)
7337

    
7338
    # NIC buildup
7339
    self.nics = []
7340
    for idx, nic in enumerate(self.op.nics):
7341
      nic_mode_req = nic.get("mode", None)
7342
      nic_mode = nic_mode_req
7343
      if nic_mode is None:
7344
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
7345

    
7346
      # in routed mode, for the first nic, the default ip is 'auto'
7347
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
7348
        default_ip_mode = constants.VALUE_AUTO
7349
      else:
7350
        default_ip_mode = constants.VALUE_NONE
7351

    
7352
      # ip validity checks
7353
      ip = nic.get("ip", default_ip_mode)
7354
      if ip is None or ip.lower() == constants.VALUE_NONE:
7355
        nic_ip = None
7356
      elif ip.lower() == constants.VALUE_AUTO:
7357
        if not self.op.name_check:
7358
          raise errors.OpPrereqError("IP address set to auto but name checks"
7359
                                     " have been skipped",
7360
                                     errors.ECODE_INVAL)
7361
        nic_ip = self.hostname1.ip
7362
      else:
7363
        if not netutils.IPAddress.IsValid(ip):
7364
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
7365
                                     errors.ECODE_INVAL)
7366
        nic_ip = ip
7367

    
7368
      # TODO: check the ip address for uniqueness
7369
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7370
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7371
                                   errors.ECODE_INVAL)
7372

    
7373
      # MAC address verification
7374
      mac = nic.get("mac", constants.VALUE_AUTO)
7375
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7376
        mac = utils.NormalizeAndValidateMac(mac)
7377

    
7378
        try:
7379
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7380
        except errors.ReservationError:
7381
          raise errors.OpPrereqError("MAC address %s already in use"
7382
                                     " in cluster" % mac,
7383
                                     errors.ECODE_NOTUNIQUE)
7384

    
7385
      # bridge verification
7386
      bridge = nic.get("bridge", None)
7387
      link = nic.get("link", None)
7388
      if bridge and link:
7389
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7390
                                   " at the same time", errors.ECODE_INVAL)
7391
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7392
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7393
                                   errors.ECODE_INVAL)
7394
      elif bridge:
7395
        link = bridge
7396

    
7397
      nicparams = {}
7398
      if nic_mode_req:
7399
        nicparams[constants.NIC_MODE] = nic_mode_req
7400
      if link:
7401
        nicparams[constants.NIC_LINK] = link
7402

    
7403
      check_params = cluster.SimpleFillNIC(nicparams)
7404
      objects.NIC.CheckParameterSyntax(check_params)
7405
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7406

    
7407
    # disk checks/pre-build
7408
    self.disks = []
7409
    for disk in self.op.disks:
7410
      mode = disk.get("mode", constants.DISK_RDWR)
7411
      if mode not in constants.DISK_ACCESS_SET:
7412
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7413
                                   mode, errors.ECODE_INVAL)
7414
      size = disk.get("size", None)
7415
      if size is None:
7416
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7417
      try:
7418
        size = int(size)
7419
      except (TypeError, ValueError):
7420
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7421
                                   errors.ECODE_INVAL)
7422
      vg = disk.get("vg", self.cfg.GetVGName())
7423
      new_disk = {"size": size, "mode": mode, "vg": vg}
7424
      if "adopt" in disk:
7425
        new_disk["adopt"] = disk["adopt"]
7426
      self.disks.append(new_disk)
7427

    
7428
    if self.op.mode == constants.INSTANCE_IMPORT:
7429

    
7430
      # Check that the new instance doesn't have less disks than the export
7431
      instance_disks = len(self.disks)
7432
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7433
      if instance_disks < export_disks:
7434
        raise errors.OpPrereqError("Not enough disks to import."
7435
                                   " (instance: %d, export: %d)" %
7436
                                   (instance_disks, export_disks),
7437
                                   errors.ECODE_INVAL)
7438

    
7439
      disk_images = []
7440
      for idx in range(export_disks):
7441
        option = 'disk%d_dump' % idx
7442
        if export_info.has_option(constants.INISECT_INS, option):
7443
          # FIXME: are the old os-es, disk sizes, etc. useful?
7444
          export_name = export_info.get(constants.INISECT_INS, option)
7445
          image = utils.PathJoin(self.op.src_path, export_name)
7446
          disk_images.append(image)
7447
        else:
7448
          disk_images.append(False)
7449

    
7450
      self.src_images = disk_images
7451

    
7452
      old_name = export_info.get(constants.INISECT_INS, 'name')
7453
      try:
7454
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7455
      except (TypeError, ValueError), err:
7456
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7457
                                   " an integer: %s" % str(err),
7458
                                   errors.ECODE_STATE)
7459
      if self.op.instance_name == old_name:
7460
        for idx, nic in enumerate(self.nics):
7461
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7462
            nic_mac_ini = 'nic%d_mac' % idx
7463
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7464

    
7465
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7466

    
7467
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7468
    if self.op.ip_check:
7469
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7470
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7471
                                   (self.check_ip, self.op.instance_name),
7472
                                   errors.ECODE_NOTUNIQUE)
7473

    
7474
    #### mac address generation
7475
    # By generating here the mac address both the allocator and the hooks get
7476
    # the real final mac address rather than the 'auto' or 'generate' value.
7477
    # There is a race condition between the generation and the instance object
7478
    # creation, which means that we know the mac is valid now, but we're not
7479
    # sure it will be when we actually add the instance. If things go bad
7480
    # adding the instance will abort because of a duplicate mac, and the
7481
    # creation job will fail.
7482
    for nic in self.nics:
7483
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7484
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7485

    
7486
    #### allocator run
7487

    
7488
    if self.op.iallocator is not None:
7489
      self._RunAllocator()
7490

    
7491
    #### node related checks
7492

    
7493
    # check primary node
7494
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7495
    assert self.pnode is not None, \
7496
      "Cannot retrieve locked node %s" % self.op.pnode
7497
    if pnode.offline:
7498
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7499
                                 pnode.name, errors.ECODE_STATE)
7500
    if pnode.drained:
7501
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7502
                                 pnode.name, errors.ECODE_STATE)
7503
    if not pnode.vm_capable:
7504
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
7505
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
7506

    
7507
    self.secondaries = []
7508

    
7509
    # mirror node verification
7510
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7511
      if self.op.snode == pnode.name:
7512
        raise errors.OpPrereqError("The secondary node cannot be the"
7513
                                   " primary node.", errors.ECODE_INVAL)
7514
      _CheckNodeOnline(self, self.op.snode)
7515
      _CheckNodeNotDrained(self, self.op.snode)
7516
      _CheckNodeVmCapable(self, self.op.snode)
7517
      self.secondaries.append(self.op.snode)
7518

    
7519
    nodenames = [pnode.name] + self.secondaries
7520

    
7521
    if not self.adopt_disks:
7522
      # Check lv size requirements, if not adopting
7523
      req_sizes = _ComputeDiskSizePerVG(self.op.disk_template, self.disks)
7524
      _CheckNodesFreeDiskPerVG(self, nodenames, req_sizes)
7525

    
7526
    else: # instead, we must check the adoption data
7527
      all_lvs = set([i["vg"] + "/" + i["adopt"] for i in self.disks])
7528
      if len(all_lvs) != len(self.disks):
7529
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7530
                                   errors.ECODE_INVAL)
7531
      for lv_name in all_lvs:
7532
        try:
7533
          # FIXME: lv_name here is "vg/lv" need to ensure that other calls
7534
          # to ReserveLV uses the same syntax
7535
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7536
        except errors.ReservationError:
7537
          raise errors.OpPrereqError("LV named %s used by another instance" %
7538
                                     lv_name, errors.ECODE_NOTUNIQUE)
7539

    
7540
      vg_names = self.rpc.call_vg_list([pnode.name])[pnode.name]
7541
      vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
7542

    
7543
      node_lvs = self.rpc.call_lv_list([pnode.name],
7544
                                       vg_names.payload.keys())[pnode.name]
7545
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7546
      node_lvs = node_lvs.payload
7547

    
7548
      delta = all_lvs.difference(node_lvs.keys())
7549
      if delta:
7550
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7551
                                   utils.CommaJoin(delta),
7552
                                   errors.ECODE_INVAL)
7553
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7554
      if online_lvs:
7555
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7556
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7557
                                   errors.ECODE_STATE)
7558
      # update the size of disk based on what is found
7559
      for dsk in self.disks:
7560
        dsk["size"] = int(float(node_lvs[dsk["vg"] + "/" + dsk["adopt"]][0]))
7561

    
7562
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7563

    
7564
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7565
    # check OS parameters (remotely)
7566
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7567

    
7568
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7569

    
7570
    # memory check on primary node
7571
    if self.op.start:
7572
      _CheckNodeFreeMemory(self, self.pnode.name,
7573
                           "creating instance %s" % self.op.instance_name,
7574
                           self.be_full[constants.BE_MEMORY],
7575
                           self.op.hypervisor)
7576

    
7577
    self.dry_run_result = list(nodenames)
7578

    
7579
  def Exec(self, feedback_fn):
7580
    """Create and add the instance to the cluster.
7581

7582
    """
7583
    instance = self.op.instance_name
7584
    pnode_name = self.pnode.name
7585

    
7586
    ht_kind = self.op.hypervisor
7587
    if ht_kind in constants.HTS_REQ_PORT:
7588
      network_port = self.cfg.AllocatePort()
7589
    else:
7590
      network_port = None
7591

    
7592
    if constants.ENABLE_FILE_STORAGE:
7593
      # this is needed because os.path.join does not accept None arguments
7594
      if self.op.file_storage_dir is None:
7595
        string_file_storage_dir = ""
7596
      else:
7597
        string_file_storage_dir = self.op.file_storage_dir
7598

    
7599
      # build the full file storage dir path
7600
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7601
                                        string_file_storage_dir, instance)
7602
    else:
7603
      file_storage_dir = ""
7604

    
7605
    disks = _GenerateDiskTemplate(self,
7606
                                  self.op.disk_template,
7607
                                  instance, pnode_name,
7608
                                  self.secondaries,
7609
                                  self.disks,
7610
                                  file_storage_dir,
7611
                                  self.op.file_driver,
7612
                                  0,
7613
                                  feedback_fn)
7614

    
7615
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7616
                            primary_node=pnode_name,
7617
                            nics=self.nics, disks=disks,
7618
                            disk_template=self.op.disk_template,
7619
                            admin_up=False,
7620
                            network_port=network_port,
7621
                            beparams=self.op.beparams,
7622
                            hvparams=self.op.hvparams,
7623
                            hypervisor=self.op.hypervisor,
7624
                            osparams=self.op.osparams,
7625
                            )
7626

    
7627
    if self.adopt_disks:
7628
      # rename LVs to the newly-generated names; we need to construct
7629
      # 'fake' LV disks with the old data, plus the new unique_id
7630
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7631
      rename_to = []
7632
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7633
        rename_to.append(t_dsk.logical_id)
7634
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7635
        self.cfg.SetDiskID(t_dsk, pnode_name)
7636
      result = self.rpc.call_blockdev_rename(pnode_name,
7637
                                             zip(tmp_disks, rename_to))
7638
      result.Raise("Failed to rename adoped LVs")
7639
    else:
7640
      feedback_fn("* creating instance disks...")
7641
      try:
7642
        _CreateDisks(self, iobj)
7643
      except errors.OpExecError:
7644
        self.LogWarning("Device creation failed, reverting...")
7645
        try:
7646
          _RemoveDisks(self, iobj)
7647
        finally:
7648
          self.cfg.ReleaseDRBDMinors(instance)
7649
          raise
7650

    
7651
      if self.cfg.GetClusterInfo().prealloc_wipe_disks:
7652
        feedback_fn("* wiping instance disks...")
7653
        try:
7654
          _WipeDisks(self, iobj)
7655
        except errors.OpExecError:
7656
          self.LogWarning("Device wiping failed, reverting...")
7657
          try:
7658
            _RemoveDisks(self, iobj)
7659
          finally:
7660
            self.cfg.ReleaseDRBDMinors(instance)
7661
            raise
7662

    
7663
    feedback_fn("adding instance %s to cluster config" % instance)
7664

    
7665
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7666

    
7667
    # Declare that we don't want to remove the instance lock anymore, as we've
7668
    # added the instance to the config
7669
    del self.remove_locks[locking.LEVEL_INSTANCE]
7670
    # Unlock all the nodes
7671
    if self.op.mode == constants.INSTANCE_IMPORT:
7672
      nodes_keep = [self.op.src_node]
7673
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7674
                       if node != self.op.src_node]
7675
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7676
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7677
    else:
7678
      self.context.glm.release(locking.LEVEL_NODE)
7679
      del self.acquired_locks[locking.LEVEL_NODE]
7680

    
7681
    if self.op.wait_for_sync:
7682
      disk_abort = not _WaitForSync(self, iobj)
7683
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7684
      # make sure the disks are not degraded (still sync-ing is ok)
7685
      time.sleep(15)
7686
      feedback_fn("* checking mirrors status")
7687
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7688
    else:
7689
      disk_abort = False
7690

    
7691
    if disk_abort:
7692
      _RemoveDisks(self, iobj)
7693
      self.cfg.RemoveInstance(iobj.name)
7694
      # Make sure the instance lock gets removed
7695
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7696
      raise errors.OpExecError("There are some degraded disks for"
7697
                               " this instance")
7698

    
7699
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7700
      if self.op.mode == constants.INSTANCE_CREATE:
7701
        if not self.op.no_install:
7702
          feedback_fn("* running the instance OS create scripts...")
7703
          # FIXME: pass debug option from opcode to backend
7704
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7705
                                                 self.op.debug_level)
7706
          result.Raise("Could not add os for instance %s"
7707
                       " on node %s" % (instance, pnode_name))
7708

    
7709
      elif self.op.mode == constants.INSTANCE_IMPORT:
7710
        feedback_fn("* running the instance OS import scripts...")
7711

    
7712
        transfers = []
7713

    
7714
        for idx, image in enumerate(self.src_images):
7715
          if not image:
7716
            continue
7717

    
7718
          # FIXME: pass debug option from opcode to backend
7719
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7720
                                             constants.IEIO_FILE, (image, ),
7721
                                             constants.IEIO_SCRIPT,
7722
                                             (iobj.disks[idx], idx),
7723
                                             None)
7724
          transfers.append(dt)
7725

    
7726
        import_result = \
7727
          masterd.instance.TransferInstanceData(self, feedback_fn,
7728
                                                self.op.src_node, pnode_name,
7729
                                                self.pnode.secondary_ip,
7730
                                                iobj, transfers)
7731
        if not compat.all(import_result):
7732
          self.LogWarning("Some disks for instance %s on node %s were not"
7733
                          " imported successfully" % (instance, pnode_name))
7734

    
7735
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7736
        feedback_fn("* preparing remote import...")
7737
        # The source cluster will stop the instance before attempting to make a
7738
        # connection. In some cases stopping an instance can take a long time,
7739
        # hence the shutdown timeout is added to the connection timeout.
7740
        connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
7741
                           self.op.source_shutdown_timeout)
7742
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7743

    
7744
        assert iobj.primary_node == self.pnode.name
7745
        disk_results = \
7746
          masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
7747
                                        self.source_x509_ca,
7748
                                        self._cds, timeouts)
7749
        if not compat.all(disk_results):
7750
          # TODO: Should the instance still be started, even if some disks
7751
          # failed to import (valid for local imports, too)?
7752
          self.LogWarning("Some disks for instance %s on node %s were not"
7753
                          " imported successfully" % (instance, pnode_name))
7754

    
7755
        # Run rename script on newly imported instance
7756
        assert iobj.name == instance
7757
        feedback_fn("Running rename script for %s" % instance)
7758
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7759
                                                   self.source_instance_name,
7760
                                                   self.op.debug_level)
7761
        if result.fail_msg:
7762
          self.LogWarning("Failed to run rename script for %s on node"
7763
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7764

    
7765
      else:
7766
        # also checked in the prereq part
7767
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7768
                                     % self.op.mode)
7769

    
7770
    if self.op.start:
7771
      iobj.admin_up = True
7772
      self.cfg.Update(iobj, feedback_fn)
7773
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7774
      feedback_fn("* starting instance...")
7775
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7776
      result.Raise("Could not start instance")
7777

    
7778
    return list(iobj.all_nodes)
7779

    
7780

    
7781
class LUInstanceConsole(NoHooksLU):
7782
  """Connect to an instance's console.
7783

7784
  This is somewhat special in that it returns the command line that
7785
  you need to run on the master node in order to connect to the
7786
  console.
7787

7788
  """
7789
  REQ_BGL = False
7790

    
7791
  def ExpandNames(self):
7792
    self._ExpandAndLockInstance()
7793

    
7794
  def CheckPrereq(self):
7795
    """Check prerequisites.
7796

7797
    This checks that the instance is in the cluster.
7798

7799
    """
7800
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7801
    assert self.instance is not None, \
7802
      "Cannot retrieve locked instance %s" % self.op.instance_name
7803
    _CheckNodeOnline(self, self.instance.primary_node)
7804

    
7805
  def Exec(self, feedback_fn):
7806
    """Connect to the console of an instance
7807

7808
    """
7809
    instance = self.instance
7810
    node = instance.primary_node
7811

    
7812
    node_insts = self.rpc.call_instance_list([node],
7813
                                             [instance.hypervisor])[node]
7814
    node_insts.Raise("Can't get node information from %s" % node)
7815

    
7816
    if instance.name not in node_insts.payload:
7817
      if instance.admin_up:
7818
        state = "ERROR_down"
7819
      else:
7820
        state = "ADMIN_down"
7821
      raise errors.OpExecError("Instance %s is not running (state %s)" %
7822
                               (instance.name, state))
7823

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

    
7826
    return _GetInstanceConsole(self.cfg.GetClusterInfo(), instance)
7827

    
7828

    
7829
def _GetInstanceConsole(cluster, instance):
7830
  """Returns console information for an instance.
7831

7832
  @type cluster: L{objects.Cluster}
7833
  @type instance: L{objects.Instance}
7834
  @rtype: dict
7835

7836
  """
7837
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
7838
  # beparams and hvparams are passed separately, to avoid editing the
7839
  # instance and then saving the defaults in the instance itself.
7840
  hvparams = cluster.FillHV(instance)
7841
  beparams = cluster.FillBE(instance)
7842
  console = hyper.GetInstanceConsole(instance, hvparams, beparams)
7843

    
7844
  assert console.instance == instance.name
7845
  assert console.Validate()
7846

    
7847
  return console.ToDict()
7848

    
7849

    
7850
class LUInstanceReplaceDisks(LogicalUnit):
7851
  """Replace the disks of an instance.
7852

7853
  """
7854
  HPATH = "mirrors-replace"
7855
  HTYPE = constants.HTYPE_INSTANCE
7856
  REQ_BGL = False
7857

    
7858
  def CheckArguments(self):
7859
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7860
                                  self.op.iallocator)
7861

    
7862
  def ExpandNames(self):
7863
    self._ExpandAndLockInstance()
7864

    
7865
    if self.op.iallocator is not None:
7866
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7867

    
7868
    elif self.op.remote_node is not None:
7869
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7870
      self.op.remote_node = remote_node
7871

    
7872
      # Warning: do not remove the locking of the new secondary here
7873
      # unless DRBD8.AddChildren is changed to work in parallel;
7874
      # currently it doesn't since parallel invocations of
7875
      # FindUnusedMinor will conflict
7876
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7877
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7878

    
7879
    else:
7880
      self.needed_locks[locking.LEVEL_NODE] = []
7881
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7882

    
7883
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7884
                                   self.op.iallocator, self.op.remote_node,
7885
                                   self.op.disks, False, self.op.early_release)
7886

    
7887
    self.tasklets = [self.replacer]
7888

    
7889
  def DeclareLocks(self, level):
7890
    # If we're not already locking all nodes in the set we have to declare the
7891
    # instance's primary/secondary nodes.
7892
    if (level == locking.LEVEL_NODE and
7893
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7894
      self._LockInstancesNodes()
7895

    
7896
  def BuildHooksEnv(self):
7897
    """Build hooks env.
7898

7899
    This runs on the master, the primary and all the secondaries.
7900

7901
    """
7902
    instance = self.replacer.instance
7903
    env = {
7904
      "MODE": self.op.mode,
7905
      "NEW_SECONDARY": self.op.remote_node,
7906
      "OLD_SECONDARY": instance.secondary_nodes[0],
7907
      }
7908
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7909
    nl = [
7910
      self.cfg.GetMasterNode(),
7911
      instance.primary_node,
7912
      ]
7913
    if self.op.remote_node is not None:
7914
      nl.append(self.op.remote_node)
7915
    return env, nl, nl
7916

    
7917

    
7918
class TLReplaceDisks(Tasklet):
7919
  """Replaces disks for an instance.
7920

7921
  Note: Locking is not within the scope of this class.
7922

7923
  """
7924
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7925
               disks, delay_iallocator, early_release):
7926
    """Initializes this class.
7927

7928
    """
7929
    Tasklet.__init__(self, lu)
7930

    
7931
    # Parameters
7932
    self.instance_name = instance_name
7933
    self.mode = mode
7934
    self.iallocator_name = iallocator_name
7935
    self.remote_node = remote_node
7936
    self.disks = disks
7937
    self.delay_iallocator = delay_iallocator
7938
    self.early_release = early_release
7939

    
7940
    # Runtime data
7941
    self.instance = None
7942
    self.new_node = None
7943
    self.target_node = None
7944
    self.other_node = None
7945
    self.remote_node_info = None
7946
    self.node_secondary_ip = None
7947

    
7948
  @staticmethod
7949
  def CheckArguments(mode, remote_node, iallocator):
7950
    """Helper function for users of this class.
7951

7952
    """
7953
    # check for valid parameter combination
7954
    if mode == constants.REPLACE_DISK_CHG:
7955
      if remote_node is None and iallocator is None:
7956
        raise errors.OpPrereqError("When changing the secondary either an"
7957
                                   " iallocator script must be used or the"
7958
                                   " new node given", errors.ECODE_INVAL)
7959

    
7960
      if remote_node is not None and iallocator is not None:
7961
        raise errors.OpPrereqError("Give either the iallocator or the new"
7962
                                   " secondary, not both", errors.ECODE_INVAL)
7963

    
7964
    elif remote_node is not None or iallocator is not None:
7965
      # Not replacing the secondary
7966
      raise errors.OpPrereqError("The iallocator and new node options can"
7967
                                 " only be used when changing the"
7968
                                 " secondary node", errors.ECODE_INVAL)
7969

    
7970
  @staticmethod
7971
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7972
    """Compute a new secondary node using an IAllocator.
7973

7974
    """
7975
    ial = IAllocator(lu.cfg, lu.rpc,
7976
                     mode=constants.IALLOCATOR_MODE_RELOC,
7977
                     name=instance_name,
7978
                     relocate_from=relocate_from)
7979

    
7980
    ial.Run(iallocator_name)
7981

    
7982
    if not ial.success:
7983
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7984
                                 " %s" % (iallocator_name, ial.info),
7985
                                 errors.ECODE_NORES)
7986

    
7987
    if len(ial.result) != ial.required_nodes:
7988
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7989
                                 " of nodes (%s), required %s" %
7990
                                 (iallocator_name,
7991
                                  len(ial.result), ial.required_nodes),
7992
                                 errors.ECODE_FAULT)
7993

    
7994
    remote_node_name = ial.result[0]
7995

    
7996
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7997
               instance_name, remote_node_name)
7998

    
7999
    return remote_node_name
8000

    
8001
  def _FindFaultyDisks(self, node_name):
8002
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
8003
                                    node_name, True)
8004

    
8005
  def CheckPrereq(self):
8006
    """Check prerequisites.
8007

8008
    This checks that the instance is in the cluster.
8009

8010
    """
8011
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
8012
    assert instance is not None, \
8013
      "Cannot retrieve locked instance %s" % self.instance_name
8014

    
8015
    if instance.disk_template != constants.DT_DRBD8:
8016
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
8017
                                 " instances", errors.ECODE_INVAL)
8018

    
8019
    if len(instance.secondary_nodes) != 1:
8020
      raise errors.OpPrereqError("The instance has a strange layout,"
8021
                                 " expected one secondary but found %d" %
8022
                                 len(instance.secondary_nodes),
8023
                                 errors.ECODE_FAULT)
8024

    
8025
    if not self.delay_iallocator:
8026
      self._CheckPrereq2()
8027

    
8028
  def _CheckPrereq2(self):
8029
    """Check prerequisites, second part.
8030

8031
    This function should always be part of CheckPrereq. It was separated and is
8032
    now called from Exec because during node evacuation iallocator was only
8033
    called with an unmodified cluster model, not taking planned changes into
8034
    account.
8035

8036
    """
8037
    instance = self.instance
8038
    secondary_node = instance.secondary_nodes[0]
8039

    
8040
    if self.iallocator_name is None:
8041
      remote_node = self.remote_node
8042
    else:
8043
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
8044
                                       instance.name, instance.secondary_nodes)
8045

    
8046
    if remote_node is not None:
8047
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
8048
      assert self.remote_node_info is not None, \
8049
        "Cannot retrieve locked node %s" % remote_node
8050
    else:
8051
      self.remote_node_info = None
8052

    
8053
    if remote_node == self.instance.primary_node:
8054
      raise errors.OpPrereqError("The specified node is the primary node of"
8055
                                 " the instance.", errors.ECODE_INVAL)
8056

    
8057
    if remote_node == secondary_node:
8058
      raise errors.OpPrereqError("The specified node is already the"
8059
                                 " secondary node of the instance.",
8060
                                 errors.ECODE_INVAL)
8061

    
8062
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
8063
                                    constants.REPLACE_DISK_CHG):
8064
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
8065
                                 errors.ECODE_INVAL)
8066

    
8067
    if self.mode == constants.REPLACE_DISK_AUTO:
8068
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
8069
      faulty_secondary = self._FindFaultyDisks(secondary_node)
8070

    
8071
      if faulty_primary and faulty_secondary:
8072
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
8073
                                   " one node and can not be repaired"
8074
                                   " automatically" % self.instance_name,
8075
                                   errors.ECODE_STATE)
8076

    
8077
      if faulty_primary:
8078
        self.disks = faulty_primary
8079
        self.target_node = instance.primary_node
8080
        self.other_node = secondary_node
8081
        check_nodes = [self.target_node, self.other_node]
8082
      elif faulty_secondary:
8083
        self.disks = faulty_secondary
8084
        self.target_node = secondary_node
8085
        self.other_node = instance.primary_node
8086
        check_nodes = [self.target_node, self.other_node]
8087
      else:
8088
        self.disks = []
8089
        check_nodes = []
8090

    
8091
    else:
8092
      # Non-automatic modes
8093
      if self.mode == constants.REPLACE_DISK_PRI:
8094
        self.target_node = instance.primary_node
8095
        self.other_node = secondary_node
8096
        check_nodes = [self.target_node, self.other_node]
8097

    
8098
      elif self.mode == constants.REPLACE_DISK_SEC:
8099
        self.target_node = secondary_node
8100
        self.other_node = instance.primary_node
8101
        check_nodes = [self.target_node, self.other_node]
8102

    
8103
      elif self.mode == constants.REPLACE_DISK_CHG:
8104
        self.new_node = remote_node
8105
        self.other_node = instance.primary_node
8106
        self.target_node = secondary_node
8107
        check_nodes = [self.new_node, self.other_node]
8108

    
8109
        _CheckNodeNotDrained(self.lu, remote_node)
8110
        _CheckNodeVmCapable(self.lu, remote_node)
8111

    
8112
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
8113
        assert old_node_info is not None
8114
        if old_node_info.offline and not self.early_release:
8115
          # doesn't make sense to delay the release
8116
          self.early_release = True
8117
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
8118
                          " early-release mode", secondary_node)
8119

    
8120
      else:
8121
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
8122
                                     self.mode)
8123

    
8124
      # If not specified all disks should be replaced
8125
      if not self.disks:
8126
        self.disks = range(len(self.instance.disks))
8127

    
8128
    for node in check_nodes:
8129
      _CheckNodeOnline(self.lu, node)
8130

    
8131
    # Check whether disks are valid
8132
    for disk_idx in self.disks:
8133
      instance.FindDisk(disk_idx)
8134

    
8135
    # Get secondary node IP addresses
8136
    node_2nd_ip = {}
8137

    
8138
    for node_name in [self.target_node, self.other_node, self.new_node]:
8139
      if node_name is not None:
8140
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
8141

    
8142
    self.node_secondary_ip = node_2nd_ip
8143

    
8144
  def Exec(self, feedback_fn):
8145
    """Execute disk replacement.
8146

8147
    This dispatches the disk replacement to the appropriate handler.
8148

8149
    """
8150
    if self.delay_iallocator:
8151
      self._CheckPrereq2()
8152

    
8153
    if not self.disks:
8154
      feedback_fn("No disks need replacement")
8155
      return
8156

    
8157
    feedback_fn("Replacing disk(s) %s for %s" %
8158
                (utils.CommaJoin(self.disks), self.instance.name))
8159

    
8160
    activate_disks = (not self.instance.admin_up)
8161

    
8162
    # Activate the instance disks if we're replacing them on a down instance
8163
    if activate_disks:
8164
      _StartInstanceDisks(self.lu, self.instance, True)
8165

    
8166
    try:
8167
      # Should we replace the secondary node?
8168
      if self.new_node is not None:
8169
        fn = self._ExecDrbd8Secondary
8170
      else:
8171
        fn = self._ExecDrbd8DiskOnly
8172

    
8173
      return fn(feedback_fn)
8174

    
8175
    finally:
8176
      # Deactivate the instance disks if we're replacing them on a
8177
      # down instance
8178
      if activate_disks:
8179
        _SafeShutdownInstanceDisks(self.lu, self.instance)
8180

    
8181
  def _CheckVolumeGroup(self, nodes):
8182
    self.lu.LogInfo("Checking volume groups")
8183

    
8184
    vgname = self.cfg.GetVGName()
8185

    
8186
    # Make sure volume group exists on all involved nodes
8187
    results = self.rpc.call_vg_list(nodes)
8188
    if not results:
8189
      raise errors.OpExecError("Can't list volume groups on the nodes")
8190

    
8191
    for node in nodes:
8192
      res = results[node]
8193
      res.Raise("Error checking node %s" % node)
8194
      if vgname not in res.payload:
8195
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
8196
                                 (vgname, node))
8197

    
8198
  def _CheckDisksExistence(self, nodes):
8199
    # Check disk existence
8200
    for idx, dev in enumerate(self.instance.disks):
8201
      if idx not in self.disks:
8202
        continue
8203

    
8204
      for node in nodes:
8205
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
8206
        self.cfg.SetDiskID(dev, node)
8207

    
8208
        result = self.rpc.call_blockdev_find(node, dev)
8209

    
8210
        msg = result.fail_msg
8211
        if msg or not result.payload:
8212
          if not msg:
8213
            msg = "disk not found"
8214
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
8215
                                   (idx, node, msg))
8216

    
8217
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
8218
    for idx, dev in enumerate(self.instance.disks):
8219
      if idx not in self.disks:
8220
        continue
8221

    
8222
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
8223
                      (idx, node_name))
8224

    
8225
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
8226
                                   ldisk=ldisk):
8227
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
8228
                                 " replace disks for instance %s" %
8229
                                 (node_name, self.instance.name))
8230

    
8231
  def _CreateNewStorage(self, node_name):
8232
    vgname = self.cfg.GetVGName()
8233
    iv_names = {}
8234

    
8235
    for idx, dev in enumerate(self.instance.disks):
8236
      if idx not in self.disks:
8237
        continue
8238

    
8239
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
8240

    
8241
      self.cfg.SetDiskID(dev, node_name)
8242

    
8243
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
8244
      names = _GenerateUniqueNames(self.lu, lv_names)
8245

    
8246
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
8247
                             logical_id=(vgname, names[0]))
8248
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
8249
                             logical_id=(vgname, names[1]))
8250

    
8251
      new_lvs = [lv_data, lv_meta]
8252
      old_lvs = dev.children
8253
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
8254

    
8255
      # we pass force_create=True to force the LVM creation
8256
      for new_lv in new_lvs:
8257
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
8258
                        _GetInstanceInfoText(self.instance), False)
8259

    
8260
    return iv_names
8261

    
8262
  def _CheckDevices(self, node_name, iv_names):
8263
    for name, (dev, _, _) in iv_names.iteritems():
8264
      self.cfg.SetDiskID(dev, node_name)
8265

    
8266
      result = self.rpc.call_blockdev_find(node_name, dev)
8267

    
8268
      msg = result.fail_msg
8269
      if msg or not result.payload:
8270
        if not msg:
8271
          msg = "disk not found"
8272
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
8273
                                 (name, msg))
8274

    
8275
      if result.payload.is_degraded:
8276
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
8277

    
8278
  def _RemoveOldStorage(self, node_name, iv_names):
8279
    for name, (_, old_lvs, _) in iv_names.iteritems():
8280
      self.lu.LogInfo("Remove logical volumes for %s" % name)
8281

    
8282
      for lv in old_lvs:
8283
        self.cfg.SetDiskID(lv, node_name)
8284

    
8285
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
8286
        if msg:
8287
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
8288
                             hint="remove unused LVs manually")
8289

    
8290
  def _ReleaseNodeLock(self, node_name):
8291
    """Releases the lock for a given node."""
8292
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
8293

    
8294
  def _ExecDrbd8DiskOnly(self, feedback_fn):
8295
    """Replace a disk on the primary or secondary for DRBD 8.
8296

8297
    The algorithm for replace is quite complicated:
8298

8299
      1. for each disk to be replaced:
8300

8301
        1. create new LVs on the target node with unique names
8302
        1. detach old LVs from the drbd device
8303
        1. rename old LVs to name_replaced.<time_t>
8304
        1. rename new LVs to old LVs
8305
        1. attach the new LVs (with the old names now) to the drbd device
8306

8307
      1. wait for sync across all devices
8308

8309
      1. for each modified disk:
8310

8311
        1. remove old LVs (which have the name name_replaces.<time_t>)
8312

8313
    Failures are not very well handled.
8314

8315
    """
8316
    steps_total = 6
8317

    
8318
    # Step: check device activation
8319
    self.lu.LogStep(1, steps_total, "Check device existence")
8320
    self._CheckDisksExistence([self.other_node, self.target_node])
8321
    self._CheckVolumeGroup([self.target_node, self.other_node])
8322

    
8323
    # Step: check other node consistency
8324
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8325
    self._CheckDisksConsistency(self.other_node,
8326
                                self.other_node == self.instance.primary_node,
8327
                                False)
8328

    
8329
    # Step: create new storage
8330
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8331
    iv_names = self._CreateNewStorage(self.target_node)
8332

    
8333
    # Step: for each lv, detach+rename*2+attach
8334
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8335
    for dev, old_lvs, new_lvs in iv_names.itervalues():
8336
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
8337

    
8338
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
8339
                                                     old_lvs)
8340
      result.Raise("Can't detach drbd from local storage on node"
8341
                   " %s for device %s" % (self.target_node, dev.iv_name))
8342
      #dev.children = []
8343
      #cfg.Update(instance)
8344

    
8345
      # ok, we created the new LVs, so now we know we have the needed
8346
      # storage; as such, we proceed on the target node to rename
8347
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
8348
      # using the assumption that logical_id == physical_id (which in
8349
      # turn is the unique_id on that node)
8350

    
8351
      # FIXME(iustin): use a better name for the replaced LVs
8352
      temp_suffix = int(time.time())
8353
      ren_fn = lambda d, suff: (d.physical_id[0],
8354
                                d.physical_id[1] + "_replaced-%s" % suff)
8355

    
8356
      # Build the rename list based on what LVs exist on the node
8357
      rename_old_to_new = []
8358
      for to_ren in old_lvs:
8359
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
8360
        if not result.fail_msg and result.payload:
8361
          # device exists
8362
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
8363

    
8364
      self.lu.LogInfo("Renaming the old LVs on the target node")
8365
      result = self.rpc.call_blockdev_rename(self.target_node,
8366
                                             rename_old_to_new)
8367
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
8368

    
8369
      # Now we rename the new LVs to the old LVs
8370
      self.lu.LogInfo("Renaming the new LVs on the target node")
8371
      rename_new_to_old = [(new, old.physical_id)
8372
                           for old, new in zip(old_lvs, new_lvs)]
8373
      result = self.rpc.call_blockdev_rename(self.target_node,
8374
                                             rename_new_to_old)
8375
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
8376

    
8377
      for old, new in zip(old_lvs, new_lvs):
8378
        new.logical_id = old.logical_id
8379
        self.cfg.SetDiskID(new, self.target_node)
8380

    
8381
      for disk in old_lvs:
8382
        disk.logical_id = ren_fn(disk, temp_suffix)
8383
        self.cfg.SetDiskID(disk, self.target_node)
8384

    
8385
      # Now that the new lvs have the old name, we can add them to the device
8386
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
8387
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
8388
                                                  new_lvs)
8389
      msg = result.fail_msg
8390
      if msg:
8391
        for new_lv in new_lvs:
8392
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
8393
                                               new_lv).fail_msg
8394
          if msg2:
8395
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
8396
                               hint=("cleanup manually the unused logical"
8397
                                     "volumes"))
8398
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8399

    
8400
      dev.children = new_lvs
8401

    
8402
      self.cfg.Update(self.instance, feedback_fn)
8403

    
8404
    cstep = 5
8405
    if self.early_release:
8406
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8407
      cstep += 1
8408
      self._RemoveOldStorage(self.target_node, iv_names)
8409
      # WARNING: we release both node locks here, do not do other RPCs
8410
      # than WaitForSync to the primary node
8411
      self._ReleaseNodeLock([self.target_node, self.other_node])
8412

    
8413
    # Wait for sync
8414
    # This can fail as the old devices are degraded and _WaitForSync
8415
    # does a combined result over all disks, so we don't check its return value
8416
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8417
    cstep += 1
8418
    _WaitForSync(self.lu, self.instance)
8419

    
8420
    # Check all devices manually
8421
    self._CheckDevices(self.instance.primary_node, iv_names)
8422

    
8423
    # Step: remove old storage
8424
    if not self.early_release:
8425
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8426
      cstep += 1
8427
      self._RemoveOldStorage(self.target_node, iv_names)
8428

    
8429
  def _ExecDrbd8Secondary(self, feedback_fn):
8430
    """Replace the secondary node for DRBD 8.
8431

8432
    The algorithm for replace is quite complicated:
8433
      - for all disks of the instance:
8434
        - create new LVs on the new node with same names
8435
        - shutdown the drbd device on the old secondary
8436
        - disconnect the drbd network on the primary
8437
        - create the drbd device on the new secondary
8438
        - network attach the drbd on the primary, using an artifice:
8439
          the drbd code for Attach() will connect to the network if it
8440
          finds a device which is connected to the good local disks but
8441
          not network enabled
8442
      - wait for sync across all devices
8443
      - remove all disks from the old secondary
8444

8445
    Failures are not very well handled.
8446

8447
    """
8448
    steps_total = 6
8449

    
8450
    # Step: check device activation
8451
    self.lu.LogStep(1, steps_total, "Check device existence")
8452
    self._CheckDisksExistence([self.instance.primary_node])
8453
    self._CheckVolumeGroup([self.instance.primary_node])
8454

    
8455
    # Step: check other node consistency
8456
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8457
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8458

    
8459
    # Step: create new storage
8460
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8461
    for idx, dev in enumerate(self.instance.disks):
8462
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8463
                      (self.new_node, idx))
8464
      # we pass force_create=True to force LVM creation
8465
      for new_lv in dev.children:
8466
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8467
                        _GetInstanceInfoText(self.instance), False)
8468

    
8469
    # Step 4: dbrd minors and drbd setups changes
8470
    # after this, we must manually remove the drbd minors on both the
8471
    # error and the success paths
8472
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8473
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8474
                                         for dev in self.instance.disks],
8475
                                        self.instance.name)
8476
    logging.debug("Allocated minors %r", minors)
8477

    
8478
    iv_names = {}
8479
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8480
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8481
                      (self.new_node, idx))
8482
      # create new devices on new_node; note that we create two IDs:
8483
      # one without port, so the drbd will be activated without
8484
      # networking information on the new node at this stage, and one
8485
      # with network, for the latter activation in step 4
8486
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8487
      if self.instance.primary_node == o_node1:
8488
        p_minor = o_minor1
8489
      else:
8490
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8491
        p_minor = o_minor2
8492

    
8493
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8494
                      p_minor, new_minor, o_secret)
8495
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8496
                    p_minor, new_minor, o_secret)
8497

    
8498
      iv_names[idx] = (dev, dev.children, new_net_id)
8499
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8500
                    new_net_id)
8501
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8502
                              logical_id=new_alone_id,
8503
                              children=dev.children,
8504
                              size=dev.size)
8505
      try:
8506
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8507
                              _GetInstanceInfoText(self.instance), False)
8508
      except errors.GenericError:
8509
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8510
        raise
8511

    
8512
    # We have new devices, shutdown the drbd on the old secondary
8513
    for idx, dev in enumerate(self.instance.disks):
8514
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8515
      self.cfg.SetDiskID(dev, self.target_node)
8516
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8517
      if msg:
8518
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8519
                           "node: %s" % (idx, msg),
8520
                           hint=("Please cleanup this device manually as"
8521
                                 " soon as possible"))
8522

    
8523
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8524
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8525
                                               self.node_secondary_ip,
8526
                                               self.instance.disks)\
8527
                                              [self.instance.primary_node]
8528

    
8529
    msg = result.fail_msg
8530
    if msg:
8531
      # detaches didn't succeed (unlikely)
8532
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8533
      raise errors.OpExecError("Can't detach the disks from the network on"
8534
                               " old node: %s" % (msg,))
8535

    
8536
    # if we managed to detach at least one, we update all the disks of
8537
    # the instance to point to the new secondary
8538
    self.lu.LogInfo("Updating instance configuration")
8539
    for dev, _, new_logical_id in iv_names.itervalues():
8540
      dev.logical_id = new_logical_id
8541
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8542

    
8543
    self.cfg.Update(self.instance, feedback_fn)
8544

    
8545
    # and now perform the drbd attach
8546
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8547
                    " (standalone => connected)")
8548
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8549
                                            self.new_node],
8550
                                           self.node_secondary_ip,
8551
                                           self.instance.disks,
8552
                                           self.instance.name,
8553
                                           False)
8554
    for to_node, to_result in result.items():
8555
      msg = to_result.fail_msg
8556
      if msg:
8557
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8558
                           to_node, msg,
8559
                           hint=("please do a gnt-instance info to see the"
8560
                                 " status of disks"))
8561
    cstep = 5
8562
    if self.early_release:
8563
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8564
      cstep += 1
8565
      self._RemoveOldStorage(self.target_node, iv_names)
8566
      # WARNING: we release all node locks here, do not do other RPCs
8567
      # than WaitForSync to the primary node
8568
      self._ReleaseNodeLock([self.instance.primary_node,
8569
                             self.target_node,
8570
                             self.new_node])
8571

    
8572
    # Wait for sync
8573
    # This can fail as the old devices are degraded and _WaitForSync
8574
    # does a combined result over all disks, so we don't check its return value
8575
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8576
    cstep += 1
8577
    _WaitForSync(self.lu, self.instance)
8578

    
8579
    # Check all devices manually
8580
    self._CheckDevices(self.instance.primary_node, iv_names)
8581

    
8582
    # Step: remove old storage
8583
    if not self.early_release:
8584
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8585
      self._RemoveOldStorage(self.target_node, iv_names)
8586

    
8587

    
8588
class LURepairNodeStorage(NoHooksLU):
8589
  """Repairs the volume group on a node.
8590

8591
  """
8592
  REQ_BGL = False
8593

    
8594
  def CheckArguments(self):
8595
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8596

    
8597
    storage_type = self.op.storage_type
8598

    
8599
    if (constants.SO_FIX_CONSISTENCY not in
8600
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8601
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8602
                                 " repaired" % storage_type,
8603
                                 errors.ECODE_INVAL)
8604

    
8605
  def ExpandNames(self):
8606
    self.needed_locks = {
8607
      locking.LEVEL_NODE: [self.op.node_name],
8608
      }
8609

    
8610
  def _CheckFaultyDisks(self, instance, node_name):
8611
    """Ensure faulty disks abort the opcode or at least warn."""
8612
    try:
8613
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8614
                                  node_name, True):
8615
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8616
                                   " node '%s'" % (instance.name, node_name),
8617
                                   errors.ECODE_STATE)
8618
    except errors.OpPrereqError, err:
8619
      if self.op.ignore_consistency:
8620
        self.proc.LogWarning(str(err.args[0]))
8621
      else:
8622
        raise
8623

    
8624
  def CheckPrereq(self):
8625
    """Check prerequisites.
8626

8627
    """
8628
    # Check whether any instance on this node has faulty disks
8629
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8630
      if not inst.admin_up:
8631
        continue
8632
      check_nodes = set(inst.all_nodes)
8633
      check_nodes.discard(self.op.node_name)
8634
      for inst_node_name in check_nodes:
8635
        self._CheckFaultyDisks(inst, inst_node_name)
8636

    
8637
  def Exec(self, feedback_fn):
8638
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8639
                (self.op.name, self.op.node_name))
8640

    
8641
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8642
    result = self.rpc.call_storage_execute(self.op.node_name,
8643
                                           self.op.storage_type, st_args,
8644
                                           self.op.name,
8645
                                           constants.SO_FIX_CONSISTENCY)
8646
    result.Raise("Failed to repair storage unit '%s' on %s" %
8647
                 (self.op.name, self.op.node_name))
8648

    
8649

    
8650
class LUNodeEvacStrategy(NoHooksLU):
8651
  """Computes the node evacuation strategy.
8652

8653
  """
8654
  REQ_BGL = False
8655

    
8656
  def CheckArguments(self):
8657
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8658

    
8659
  def ExpandNames(self):
8660
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8661
    self.needed_locks = locks = {}
8662
    if self.op.remote_node is None:
8663
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8664
    else:
8665
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8666
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8667

    
8668
  def Exec(self, feedback_fn):
8669
    if self.op.remote_node is not None:
8670
      instances = []
8671
      for node in self.op.nodes:
8672
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8673
      result = []
8674
      for i in instances:
8675
        if i.primary_node == self.op.remote_node:
8676
          raise errors.OpPrereqError("Node %s is the primary node of"
8677
                                     " instance %s, cannot use it as"
8678
                                     " secondary" %
8679
                                     (self.op.remote_node, i.name),
8680
                                     errors.ECODE_INVAL)
8681
        result.append([i.name, self.op.remote_node])
8682
    else:
8683
      ial = IAllocator(self.cfg, self.rpc,
8684
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8685
                       evac_nodes=self.op.nodes)
8686
      ial.Run(self.op.iallocator, validate=True)
8687
      if not ial.success:
8688
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8689
                                 errors.ECODE_NORES)
8690
      result = ial.result
8691
    return result
8692

    
8693

    
8694
class LUInstanceGrowDisk(LogicalUnit):
8695
  """Grow a disk of an instance.
8696

8697
  """
8698
  HPATH = "disk-grow"
8699
  HTYPE = constants.HTYPE_INSTANCE
8700
  REQ_BGL = False
8701

    
8702
  def ExpandNames(self):
8703
    self._ExpandAndLockInstance()
8704
    self.needed_locks[locking.LEVEL_NODE] = []
8705
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8706

    
8707
  def DeclareLocks(self, level):
8708
    if level == locking.LEVEL_NODE:
8709
      self._LockInstancesNodes()
8710

    
8711
  def BuildHooksEnv(self):
8712
    """Build hooks env.
8713

8714
    This runs on the master, the primary and all the secondaries.
8715

8716
    """
8717
    env = {
8718
      "DISK": self.op.disk,
8719
      "AMOUNT": self.op.amount,
8720
      }
8721
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8722
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8723
    return env, nl, nl
8724

    
8725
  def CheckPrereq(self):
8726
    """Check prerequisites.
8727

8728
    This checks that the instance is in the cluster.
8729

8730
    """
8731
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8732
    assert instance is not None, \
8733
      "Cannot retrieve locked instance %s" % self.op.instance_name
8734
    nodenames = list(instance.all_nodes)
8735
    for node in nodenames:
8736
      _CheckNodeOnline(self, node)
8737

    
8738
    self.instance = instance
8739

    
8740
    if instance.disk_template not in constants.DTS_GROWABLE:
8741
      raise errors.OpPrereqError("Instance's disk layout does not support"
8742
                                 " growing.", errors.ECODE_INVAL)
8743

    
8744
    self.disk = instance.FindDisk(self.op.disk)
8745

    
8746
    if instance.disk_template != constants.DT_FILE:
8747
      # TODO: check the free disk space for file, when that feature
8748
      # will be supported
8749
      _CheckNodesFreeDiskPerVG(self, nodenames,
8750
                               self.disk.ComputeGrowth(self.op.amount))
8751

    
8752
  def Exec(self, feedback_fn):
8753
    """Execute disk grow.
8754

8755
    """
8756
    instance = self.instance
8757
    disk = self.disk
8758

    
8759
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8760
    if not disks_ok:
8761
      raise errors.OpExecError("Cannot activate block device to grow")
8762

    
8763
    for node in instance.all_nodes:
8764
      self.cfg.SetDiskID(disk, node)
8765
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8766
      result.Raise("Grow request failed to node %s" % node)
8767

    
8768
      # TODO: Rewrite code to work properly
8769
      # DRBD goes into sync mode for a short amount of time after executing the
8770
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8771
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8772
      # time is a work-around.
8773
      time.sleep(5)
8774

    
8775
    disk.RecordGrow(self.op.amount)
8776
    self.cfg.Update(instance, feedback_fn)
8777
    if self.op.wait_for_sync:
8778
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8779
      if disk_abort:
8780
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8781
                             " status.\nPlease check the instance.")
8782
      if not instance.admin_up:
8783
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8784
    elif not instance.admin_up:
8785
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8786
                           " not supposed to be running because no wait for"
8787
                           " sync mode was requested.")
8788

    
8789

    
8790
class LUInstanceQueryData(NoHooksLU):
8791
  """Query runtime instance data.
8792

8793
  """
8794
  REQ_BGL = False
8795

    
8796
  def ExpandNames(self):
8797
    self.needed_locks = {}
8798
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8799

    
8800
    if self.op.instances:
8801
      self.wanted_names = []
8802
      for name in self.op.instances:
8803
        full_name = _ExpandInstanceName(self.cfg, name)
8804
        self.wanted_names.append(full_name)
8805
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8806
    else:
8807
      self.wanted_names = None
8808
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8809

    
8810
    self.needed_locks[locking.LEVEL_NODE] = []
8811
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8812

    
8813
  def DeclareLocks(self, level):
8814
    if level == locking.LEVEL_NODE:
8815
      self._LockInstancesNodes()
8816

    
8817
  def CheckPrereq(self):
8818
    """Check prerequisites.
8819

8820
    This only checks the optional instance list against the existing names.
8821

8822
    """
8823
    if self.wanted_names is None:
8824
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8825

    
8826
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8827
                             in self.wanted_names]
8828

    
8829
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8830
    """Returns the status of a block device
8831

8832
    """
8833
    if self.op.static or not node:
8834
      return None
8835

    
8836
    self.cfg.SetDiskID(dev, node)
8837

    
8838
    result = self.rpc.call_blockdev_find(node, dev)
8839
    if result.offline:
8840
      return None
8841

    
8842
    result.Raise("Can't compute disk status for %s" % instance_name)
8843

    
8844
    status = result.payload
8845
    if status is None:
8846
      return None
8847

    
8848
    return (status.dev_path, status.major, status.minor,
8849
            status.sync_percent, status.estimated_time,
8850
            status.is_degraded, status.ldisk_status)
8851

    
8852
  def _ComputeDiskStatus(self, instance, snode, dev):
8853
    """Compute block device status.
8854

8855
    """
8856
    if dev.dev_type in constants.LDS_DRBD:
8857
      # we change the snode then (otherwise we use the one passed in)
8858
      if dev.logical_id[0] == instance.primary_node:
8859
        snode = dev.logical_id[1]
8860
      else:
8861
        snode = dev.logical_id[0]
8862

    
8863
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8864
                                              instance.name, dev)
8865
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8866

    
8867
    if dev.children:
8868
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8869
                      for child in dev.children]
8870
    else:
8871
      dev_children = []
8872

    
8873
    data = {
8874
      "iv_name": dev.iv_name,
8875
      "dev_type": dev.dev_type,
8876
      "logical_id": dev.logical_id,
8877
      "physical_id": dev.physical_id,
8878
      "pstatus": dev_pstatus,
8879
      "sstatus": dev_sstatus,
8880
      "children": dev_children,
8881
      "mode": dev.mode,
8882
      "size": dev.size,
8883
      }
8884

    
8885
    return data
8886

    
8887
  def Exec(self, feedback_fn):
8888
    """Gather and return data"""
8889
    result = {}
8890

    
8891
    cluster = self.cfg.GetClusterInfo()
8892

    
8893
    for instance in self.wanted_instances:
8894
      if not self.op.static:
8895
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8896
                                                  instance.name,
8897
                                                  instance.hypervisor)
8898
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8899
        remote_info = remote_info.payload
8900
        if remote_info and "state" in remote_info:
8901
          remote_state = "up"
8902
        else:
8903
          remote_state = "down"
8904
      else:
8905
        remote_state = None
8906
      if instance.admin_up:
8907
        config_state = "up"
8908
      else:
8909
        config_state = "down"
8910

    
8911
      disks = [self._ComputeDiskStatus(instance, None, device)
8912
               for device in instance.disks]
8913

    
8914
      idict = {
8915
        "name": instance.name,
8916
        "config_state": config_state,
8917
        "run_state": remote_state,
8918
        "pnode": instance.primary_node,
8919
        "snodes": instance.secondary_nodes,
8920
        "os": instance.os,
8921
        # this happens to be the same format used for hooks
8922
        "nics": _NICListToTuple(self, instance.nics),
8923
        "disk_template": instance.disk_template,
8924
        "disks": disks,
8925
        "hypervisor": instance.hypervisor,
8926
        "network_port": instance.network_port,
8927
        "hv_instance": instance.hvparams,
8928
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8929
        "be_instance": instance.beparams,
8930
        "be_actual": cluster.FillBE(instance),
8931
        "os_instance": instance.osparams,
8932
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8933
        "serial_no": instance.serial_no,
8934
        "mtime": instance.mtime,
8935
        "ctime": instance.ctime,
8936
        "uuid": instance.uuid,
8937
        }
8938

    
8939
      result[instance.name] = idict
8940

    
8941
    return result
8942

    
8943

    
8944
class LUInstanceSetParams(LogicalUnit):
8945
  """Modifies an instances's parameters.
8946

8947
  """
8948
  HPATH = "instance-modify"
8949
  HTYPE = constants.HTYPE_INSTANCE
8950
  REQ_BGL = False
8951

    
8952
  def CheckArguments(self):
8953
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8954
            self.op.hvparams or self.op.beparams or self.op.os_name):
8955
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8956

    
8957
    if self.op.hvparams:
8958
      _CheckGlobalHvParams(self.op.hvparams)
8959

    
8960
    # Disk validation
8961
    disk_addremove = 0
8962
    for disk_op, disk_dict in self.op.disks:
8963
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8964
      if disk_op == constants.DDM_REMOVE:
8965
        disk_addremove += 1
8966
        continue
8967
      elif disk_op == constants.DDM_ADD:
8968
        disk_addremove += 1
8969
      else:
8970
        if not isinstance(disk_op, int):
8971
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8972
        if not isinstance(disk_dict, dict):
8973
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8974
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8975

    
8976
      if disk_op == constants.DDM_ADD:
8977
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8978
        if mode not in constants.DISK_ACCESS_SET:
8979
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8980
                                     errors.ECODE_INVAL)
8981
        size = disk_dict.get('size', None)
8982
        if size is None:
8983
          raise errors.OpPrereqError("Required disk parameter size missing",
8984
                                     errors.ECODE_INVAL)
8985
        try:
8986
          size = int(size)
8987
        except (TypeError, ValueError), err:
8988
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8989
                                     str(err), errors.ECODE_INVAL)
8990
        disk_dict['size'] = size
8991
      else:
8992
        # modification of disk
8993
        if 'size' in disk_dict:
8994
          raise errors.OpPrereqError("Disk size change not possible, use"
8995
                                     " grow-disk", errors.ECODE_INVAL)
8996

    
8997
    if disk_addremove > 1:
8998
      raise errors.OpPrereqError("Only one disk add or remove operation"
8999
                                 " supported at a time", errors.ECODE_INVAL)
9000

    
9001
    if self.op.disks and self.op.disk_template is not None:
9002
      raise errors.OpPrereqError("Disk template conversion and other disk"
9003
                                 " changes not supported at the same time",
9004
                                 errors.ECODE_INVAL)
9005

    
9006
    if (self.op.disk_template and
9007
        self.op.disk_template in constants.DTS_NET_MIRROR and
9008
        self.op.remote_node is None):
9009
      raise errors.OpPrereqError("Changing the disk template to a mirrored"
9010
                                 " one requires specifying a secondary node",
9011
                                 errors.ECODE_INVAL)
9012

    
9013
    # NIC validation
9014
    nic_addremove = 0
9015
    for nic_op, nic_dict in self.op.nics:
9016
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
9017
      if nic_op == constants.DDM_REMOVE:
9018
        nic_addremove += 1
9019
        continue
9020
      elif nic_op == constants.DDM_ADD:
9021
        nic_addremove += 1
9022
      else:
9023
        if not isinstance(nic_op, int):
9024
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
9025
        if not isinstance(nic_dict, dict):
9026
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
9027
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9028

    
9029
      # nic_dict should be a dict
9030
      nic_ip = nic_dict.get('ip', None)
9031
      if nic_ip is not None:
9032
        if nic_ip.lower() == constants.VALUE_NONE:
9033
          nic_dict['ip'] = None
9034
        else:
9035
          if not netutils.IPAddress.IsValid(nic_ip):
9036
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
9037
                                       errors.ECODE_INVAL)
9038

    
9039
      nic_bridge = nic_dict.get('bridge', None)
9040
      nic_link = nic_dict.get('link', None)
9041
      if nic_bridge and nic_link:
9042
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
9043
                                   " at the same time", errors.ECODE_INVAL)
9044
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
9045
        nic_dict['bridge'] = None
9046
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
9047
        nic_dict['link'] = None
9048

    
9049
      if nic_op == constants.DDM_ADD:
9050
        nic_mac = nic_dict.get('mac', None)
9051
        if nic_mac is None:
9052
          nic_dict['mac'] = constants.VALUE_AUTO
9053

    
9054
      if 'mac' in nic_dict:
9055
        nic_mac = nic_dict['mac']
9056
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9057
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
9058

    
9059
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
9060
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
9061
                                     " modifying an existing nic",
9062
                                     errors.ECODE_INVAL)
9063

    
9064
    if nic_addremove > 1:
9065
      raise errors.OpPrereqError("Only one NIC add or remove operation"
9066
                                 " supported at a time", errors.ECODE_INVAL)
9067

    
9068
  def ExpandNames(self):
9069
    self._ExpandAndLockInstance()
9070
    self.needed_locks[locking.LEVEL_NODE] = []
9071
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9072

    
9073
  def DeclareLocks(self, level):
9074
    if level == locking.LEVEL_NODE:
9075
      self._LockInstancesNodes()
9076
      if self.op.disk_template and self.op.remote_node:
9077
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9078
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
9079

    
9080
  def BuildHooksEnv(self):
9081
    """Build hooks env.
9082

9083
    This runs on the master, primary and secondaries.
9084

9085
    """
9086
    args = dict()
9087
    if constants.BE_MEMORY in self.be_new:
9088
      args['memory'] = self.be_new[constants.BE_MEMORY]
9089
    if constants.BE_VCPUS in self.be_new:
9090
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
9091
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
9092
    # information at all.
9093
    if self.op.nics:
9094
      args['nics'] = []
9095
      nic_override = dict(self.op.nics)
9096
      for idx, nic in enumerate(self.instance.nics):
9097
        if idx in nic_override:
9098
          this_nic_override = nic_override[idx]
9099
        else:
9100
          this_nic_override = {}
9101
        if 'ip' in this_nic_override:
9102
          ip = this_nic_override['ip']
9103
        else:
9104
          ip = nic.ip
9105
        if 'mac' in this_nic_override:
9106
          mac = this_nic_override['mac']
9107
        else:
9108
          mac = nic.mac
9109
        if idx in self.nic_pnew:
9110
          nicparams = self.nic_pnew[idx]
9111
        else:
9112
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
9113
        mode = nicparams[constants.NIC_MODE]
9114
        link = nicparams[constants.NIC_LINK]
9115
        args['nics'].append((ip, mac, mode, link))
9116
      if constants.DDM_ADD in nic_override:
9117
        ip = nic_override[constants.DDM_ADD].get('ip', None)
9118
        mac = nic_override[constants.DDM_ADD]['mac']
9119
        nicparams = self.nic_pnew[constants.DDM_ADD]
9120
        mode = nicparams[constants.NIC_MODE]
9121
        link = nicparams[constants.NIC_LINK]
9122
        args['nics'].append((ip, mac, mode, link))
9123
      elif constants.DDM_REMOVE in nic_override:
9124
        del args['nics'][-1]
9125

    
9126
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
9127
    if self.op.disk_template:
9128
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
9129
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9130
    return env, nl, nl
9131

    
9132
  def CheckPrereq(self):
9133
    """Check prerequisites.
9134

9135
    This only checks the instance list against the existing names.
9136

9137
    """
9138
    # checking the new params on the primary/secondary nodes
9139

    
9140
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9141
    cluster = self.cluster = self.cfg.GetClusterInfo()
9142
    assert self.instance is not None, \
9143
      "Cannot retrieve locked instance %s" % self.op.instance_name
9144
    pnode = instance.primary_node
9145
    nodelist = list(instance.all_nodes)
9146

    
9147
    # OS change
9148
    if self.op.os_name and not self.op.force:
9149
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
9150
                      self.op.force_variant)
9151
      instance_os = self.op.os_name
9152
    else:
9153
      instance_os = instance.os
9154

    
9155
    if self.op.disk_template:
9156
      if instance.disk_template == self.op.disk_template:
9157
        raise errors.OpPrereqError("Instance already has disk template %s" %
9158
                                   instance.disk_template, errors.ECODE_INVAL)
9159

    
9160
      if (instance.disk_template,
9161
          self.op.disk_template) not in self._DISK_CONVERSIONS:
9162
        raise errors.OpPrereqError("Unsupported disk template conversion from"
9163
                                   " %s to %s" % (instance.disk_template,
9164
                                                  self.op.disk_template),
9165
                                   errors.ECODE_INVAL)
9166
      _CheckInstanceDown(self, instance, "cannot change disk template")
9167
      if self.op.disk_template in constants.DTS_NET_MIRROR:
9168
        if self.op.remote_node == pnode:
9169
          raise errors.OpPrereqError("Given new secondary node %s is the same"
9170
                                     " as the primary node of the instance" %
9171
                                     self.op.remote_node, errors.ECODE_STATE)
9172
        _CheckNodeOnline(self, self.op.remote_node)
9173
        _CheckNodeNotDrained(self, self.op.remote_node)
9174
        # FIXME: here we assume that the old instance type is DT_PLAIN
9175
        assert instance.disk_template == constants.DT_PLAIN
9176
        disks = [{"size": d.size, "vg": d.logical_id[0]}
9177
                 for d in instance.disks]
9178
        required = _ComputeDiskSizePerVG(self.op.disk_template, disks)
9179
        _CheckNodesFreeDiskPerVG(self, [self.op.remote_node], required)
9180

    
9181
    # hvparams processing
9182
    if self.op.hvparams:
9183
      hv_type = instance.hypervisor
9184
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
9185
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
9186
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
9187

    
9188
      # local check
9189
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
9190
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
9191
      self.hv_new = hv_new # the new actual values
9192
      self.hv_inst = i_hvdict # the new dict (without defaults)
9193
    else:
9194
      self.hv_new = self.hv_inst = {}
9195

    
9196
    # beparams processing
9197
    if self.op.beparams:
9198
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
9199
                                   use_none=True)
9200
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
9201
      be_new = cluster.SimpleFillBE(i_bedict)
9202
      self.be_new = be_new # the new actual values
9203
      self.be_inst = i_bedict # the new dict (without defaults)
9204
    else:
9205
      self.be_new = self.be_inst = {}
9206

    
9207
    # osparams processing
9208
    if self.op.osparams:
9209
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
9210
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
9211
      self.os_inst = i_osdict # the new dict (without defaults)
9212
    else:
9213
      self.os_inst = {}
9214

    
9215
    self.warn = []
9216

    
9217
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
9218
      mem_check_list = [pnode]
9219
      if be_new[constants.BE_AUTO_BALANCE]:
9220
        # either we changed auto_balance to yes or it was from before
9221
        mem_check_list.extend(instance.secondary_nodes)
9222
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
9223
                                                  instance.hypervisor)
9224
      nodeinfo = self.rpc.call_node_info(mem_check_list, None,
9225
                                         instance.hypervisor)
9226
      pninfo = nodeinfo[pnode]
9227
      msg = pninfo.fail_msg
9228
      if msg:
9229
        # Assume the primary node is unreachable and go ahead
9230
        self.warn.append("Can't get info from primary node %s: %s" %
9231
                         (pnode,  msg))
9232
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
9233
        self.warn.append("Node data from primary node %s doesn't contain"
9234
                         " free memory information" % pnode)
9235
      elif instance_info.fail_msg:
9236
        self.warn.append("Can't get instance runtime information: %s" %
9237
                        instance_info.fail_msg)
9238
      else:
9239
        if instance_info.payload:
9240
          current_mem = int(instance_info.payload['memory'])
9241
        else:
9242
          # Assume instance not running
9243
          # (there is a slight race condition here, but it's not very probable,
9244
          # and we have no other way to check)
9245
          current_mem = 0
9246
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
9247
                    pninfo.payload['memory_free'])
9248
        if miss_mem > 0:
9249
          raise errors.OpPrereqError("This change will prevent the instance"
9250
                                     " from starting, due to %d MB of memory"
9251
                                     " missing on its primary node" % miss_mem,
9252
                                     errors.ECODE_NORES)
9253

    
9254
      if be_new[constants.BE_AUTO_BALANCE]:
9255
        for node, nres in nodeinfo.items():
9256
          if node not in instance.secondary_nodes:
9257
            continue
9258
          msg = nres.fail_msg
9259
          if msg:
9260
            self.warn.append("Can't get info from secondary node %s: %s" %
9261
                             (node, msg))
9262
          elif not isinstance(nres.payload.get('memory_free', None), int):
9263
            self.warn.append("Secondary node %s didn't return free"
9264
                             " memory information" % node)
9265
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
9266
            self.warn.append("Not enough memory to failover instance to"
9267
                             " secondary node %s" % node)
9268

    
9269
    # NIC processing
9270
    self.nic_pnew = {}
9271
    self.nic_pinst = {}
9272
    for nic_op, nic_dict in self.op.nics:
9273
      if nic_op == constants.DDM_REMOVE:
9274
        if not instance.nics:
9275
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
9276
                                     errors.ECODE_INVAL)
9277
        continue
9278
      if nic_op != constants.DDM_ADD:
9279
        # an existing nic
9280
        if not instance.nics:
9281
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
9282
                                     " no NICs" % nic_op,
9283
                                     errors.ECODE_INVAL)
9284
        if nic_op < 0 or nic_op >= len(instance.nics):
9285
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
9286
                                     " are 0 to %d" %
9287
                                     (nic_op, len(instance.nics) - 1),
9288
                                     errors.ECODE_INVAL)
9289
        old_nic_params = instance.nics[nic_op].nicparams
9290
        old_nic_ip = instance.nics[nic_op].ip
9291
      else:
9292
        old_nic_params = {}
9293
        old_nic_ip = None
9294

    
9295
      update_params_dict = dict([(key, nic_dict[key])
9296
                                 for key in constants.NICS_PARAMETERS
9297
                                 if key in nic_dict])
9298

    
9299
      if 'bridge' in nic_dict:
9300
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
9301

    
9302
      new_nic_params = _GetUpdatedParams(old_nic_params,
9303
                                         update_params_dict)
9304
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
9305
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
9306
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
9307
      self.nic_pinst[nic_op] = new_nic_params
9308
      self.nic_pnew[nic_op] = new_filled_nic_params
9309
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
9310

    
9311
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
9312
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
9313
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
9314
        if msg:
9315
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
9316
          if self.op.force:
9317
            self.warn.append(msg)
9318
          else:
9319
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
9320
      if new_nic_mode == constants.NIC_MODE_ROUTED:
9321
        if 'ip' in nic_dict:
9322
          nic_ip = nic_dict['ip']
9323
        else:
9324
          nic_ip = old_nic_ip
9325
        if nic_ip is None:
9326
          raise errors.OpPrereqError('Cannot set the nic ip to None'
9327
                                     ' on a routed nic', errors.ECODE_INVAL)
9328
      if 'mac' in nic_dict:
9329
        nic_mac = nic_dict['mac']
9330
        if nic_mac is None:
9331
          raise errors.OpPrereqError('Cannot set the nic mac to None',
9332
                                     errors.ECODE_INVAL)
9333
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9334
          # otherwise generate the mac
9335
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
9336
        else:
9337
          # or validate/reserve the current one
9338
          try:
9339
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
9340
          except errors.ReservationError:
9341
            raise errors.OpPrereqError("MAC address %s already in use"
9342
                                       " in cluster" % nic_mac,
9343
                                       errors.ECODE_NOTUNIQUE)
9344

    
9345
    # DISK processing
9346
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
9347
      raise errors.OpPrereqError("Disk operations not supported for"
9348
                                 " diskless instances",
9349
                                 errors.ECODE_INVAL)
9350
    for disk_op, _ in self.op.disks:
9351
      if disk_op == constants.DDM_REMOVE:
9352
        if len(instance.disks) == 1:
9353
          raise errors.OpPrereqError("Cannot remove the last disk of"
9354
                                     " an instance", errors.ECODE_INVAL)
9355
        _CheckInstanceDown(self, instance, "cannot remove disks")
9356

    
9357
      if (disk_op == constants.DDM_ADD and
9358
          len(instance.disks) >= constants.MAX_DISKS):
9359
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
9360
                                   " add more" % constants.MAX_DISKS,
9361
                                   errors.ECODE_STATE)
9362
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
9363
        # an existing disk
9364
        if disk_op < 0 or disk_op >= len(instance.disks):
9365
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9366
                                     " are 0 to %d" %
9367
                                     (disk_op, len(instance.disks)),
9368
                                     errors.ECODE_INVAL)
9369

    
9370
    return
9371

    
9372
  def _ConvertPlainToDrbd(self, feedback_fn):
9373
    """Converts an instance from plain to drbd.
9374

9375
    """
9376
    feedback_fn("Converting template to drbd")
9377
    instance = self.instance
9378
    pnode = instance.primary_node
9379
    snode = self.op.remote_node
9380

    
9381
    # create a fake disk info for _GenerateDiskTemplate
9382
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
9383
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9384
                                      instance.name, pnode, [snode],
9385
                                      disk_info, None, None, 0, feedback_fn)
9386
    info = _GetInstanceInfoText(instance)
9387
    feedback_fn("Creating aditional volumes...")
9388
    # first, create the missing data and meta devices
9389
    for disk in new_disks:
9390
      # unfortunately this is... not too nice
9391
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9392
                            info, True)
9393
      for child in disk.children:
9394
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9395
    # at this stage, all new LVs have been created, we can rename the
9396
    # old ones
9397
    feedback_fn("Renaming original volumes...")
9398
    rename_list = [(o, n.children[0].logical_id)
9399
                   for (o, n) in zip(instance.disks, new_disks)]
9400
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9401
    result.Raise("Failed to rename original LVs")
9402

    
9403
    feedback_fn("Initializing DRBD devices...")
9404
    # all child devices are in place, we can now create the DRBD devices
9405
    for disk in new_disks:
9406
      for node in [pnode, snode]:
9407
        f_create = node == pnode
9408
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9409

    
9410
    # at this point, the instance has been modified
9411
    instance.disk_template = constants.DT_DRBD8
9412
    instance.disks = new_disks
9413
    self.cfg.Update(instance, feedback_fn)
9414

    
9415
    # disks are created, waiting for sync
9416
    disk_abort = not _WaitForSync(self, instance)
9417
    if disk_abort:
9418
      raise errors.OpExecError("There are some degraded disks for"
9419
                               " this instance, please cleanup manually")
9420

    
9421
  def _ConvertDrbdToPlain(self, feedback_fn):
9422
    """Converts an instance from drbd to plain.
9423

9424
    """
9425
    instance = self.instance
9426
    assert len(instance.secondary_nodes) == 1
9427
    pnode = instance.primary_node
9428
    snode = instance.secondary_nodes[0]
9429
    feedback_fn("Converting template to plain")
9430

    
9431
    old_disks = instance.disks
9432
    new_disks = [d.children[0] for d in old_disks]
9433

    
9434
    # copy over size and mode
9435
    for parent, child in zip(old_disks, new_disks):
9436
      child.size = parent.size
9437
      child.mode = parent.mode
9438

    
9439
    # update instance structure
9440
    instance.disks = new_disks
9441
    instance.disk_template = constants.DT_PLAIN
9442
    self.cfg.Update(instance, feedback_fn)
9443

    
9444
    feedback_fn("Removing volumes on the secondary node...")
9445
    for disk in old_disks:
9446
      self.cfg.SetDiskID(disk, snode)
9447
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9448
      if msg:
9449
        self.LogWarning("Could not remove block device %s on node %s,"
9450
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9451

    
9452
    feedback_fn("Removing unneeded volumes on the primary node...")
9453
    for idx, disk in enumerate(old_disks):
9454
      meta = disk.children[1]
9455
      self.cfg.SetDiskID(meta, pnode)
9456
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9457
      if msg:
9458
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9459
                        " continuing anyway: %s", idx, pnode, msg)
9460

    
9461
  def Exec(self, feedback_fn):
9462
    """Modifies an instance.
9463

9464
    All parameters take effect only at the next restart of the instance.
9465

9466
    """
9467
    # Process here the warnings from CheckPrereq, as we don't have a
9468
    # feedback_fn there.
9469
    for warn in self.warn:
9470
      feedback_fn("WARNING: %s" % warn)
9471

    
9472
    result = []
9473
    instance = self.instance
9474
    # disk changes
9475
    for disk_op, disk_dict in self.op.disks:
9476
      if disk_op == constants.DDM_REMOVE:
9477
        # remove the last disk
9478
        device = instance.disks.pop()
9479
        device_idx = len(instance.disks)
9480
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9481
          self.cfg.SetDiskID(disk, node)
9482
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9483
          if msg:
9484
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9485
                            " continuing anyway", device_idx, node, msg)
9486
        result.append(("disk/%d" % device_idx, "remove"))
9487
      elif disk_op == constants.DDM_ADD:
9488
        # add a new disk
9489
        if instance.disk_template == constants.DT_FILE:
9490
          file_driver, file_path = instance.disks[0].logical_id
9491
          file_path = os.path.dirname(file_path)
9492
        else:
9493
          file_driver = file_path = None
9494
        disk_idx_base = len(instance.disks)
9495
        new_disk = _GenerateDiskTemplate(self,
9496
                                         instance.disk_template,
9497
                                         instance.name, instance.primary_node,
9498
                                         instance.secondary_nodes,
9499
                                         [disk_dict],
9500
                                         file_path,
9501
                                         file_driver,
9502
                                         disk_idx_base, feedback_fn)[0]
9503
        instance.disks.append(new_disk)
9504
        info = _GetInstanceInfoText(instance)
9505

    
9506
        logging.info("Creating volume %s for instance %s",
9507
                     new_disk.iv_name, instance.name)
9508
        # Note: this needs to be kept in sync with _CreateDisks
9509
        #HARDCODE
9510
        for node in instance.all_nodes:
9511
          f_create = node == instance.primary_node
9512
          try:
9513
            _CreateBlockDev(self, node, instance, new_disk,
9514
                            f_create, info, f_create)
9515
          except errors.OpExecError, err:
9516
            self.LogWarning("Failed to create volume %s (%s) on"
9517
                            " node %s: %s",
9518
                            new_disk.iv_name, new_disk, node, err)
9519
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9520
                       (new_disk.size, new_disk.mode)))
9521
      else:
9522
        # change a given disk
9523
        instance.disks[disk_op].mode = disk_dict['mode']
9524
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9525

    
9526
    if self.op.disk_template:
9527
      r_shut = _ShutdownInstanceDisks(self, instance)
9528
      if not r_shut:
9529
        raise errors.OpExecError("Cannot shutdown instance disks, unable to"
9530
                                 " proceed with disk template conversion")
9531
      mode = (instance.disk_template, self.op.disk_template)
9532
      try:
9533
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9534
      except:
9535
        self.cfg.ReleaseDRBDMinors(instance.name)
9536
        raise
9537
      result.append(("disk_template", self.op.disk_template))
9538

    
9539
    # NIC changes
9540
    for nic_op, nic_dict in self.op.nics:
9541
      if nic_op == constants.DDM_REMOVE:
9542
        # remove the last nic
9543
        del instance.nics[-1]
9544
        result.append(("nic.%d" % len(instance.nics), "remove"))
9545
      elif nic_op == constants.DDM_ADD:
9546
        # mac and bridge should be set, by now
9547
        mac = nic_dict['mac']
9548
        ip = nic_dict.get('ip', None)
9549
        nicparams = self.nic_pinst[constants.DDM_ADD]
9550
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9551
        instance.nics.append(new_nic)
9552
        result.append(("nic.%d" % (len(instance.nics) - 1),
9553
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9554
                       (new_nic.mac, new_nic.ip,
9555
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9556
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9557
                       )))
9558
      else:
9559
        for key in 'mac', 'ip':
9560
          if key in nic_dict:
9561
            setattr(instance.nics[nic_op], key, nic_dict[key])
9562
        if nic_op in self.nic_pinst:
9563
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9564
        for key, val in nic_dict.iteritems():
9565
          result.append(("nic.%s/%d" % (key, nic_op), val))
9566

    
9567
    # hvparams changes
9568
    if self.op.hvparams:
9569
      instance.hvparams = self.hv_inst
9570
      for key, val in self.op.hvparams.iteritems():
9571
        result.append(("hv/%s" % key, val))
9572

    
9573
    # beparams changes
9574
    if self.op.beparams:
9575
      instance.beparams = self.be_inst
9576
      for key, val in self.op.beparams.iteritems():
9577
        result.append(("be/%s" % key, val))
9578

    
9579
    # OS change
9580
    if self.op.os_name:
9581
      instance.os = self.op.os_name
9582

    
9583
    # osparams changes
9584
    if self.op.osparams:
9585
      instance.osparams = self.os_inst
9586
      for key, val in self.op.osparams.iteritems():
9587
        result.append(("os/%s" % key, val))
9588

    
9589
    self.cfg.Update(instance, feedback_fn)
9590

    
9591
    return result
9592

    
9593
  _DISK_CONVERSIONS = {
9594
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9595
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9596
    }
9597

    
9598

    
9599
class LUBackupQuery(NoHooksLU):
9600
  """Query the exports list
9601

9602
  """
9603
  REQ_BGL = False
9604

    
9605
  def ExpandNames(self):
9606
    self.needed_locks = {}
9607
    self.share_locks[locking.LEVEL_NODE] = 1
9608
    if not self.op.nodes:
9609
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9610
    else:
9611
      self.needed_locks[locking.LEVEL_NODE] = \
9612
        _GetWantedNodes(self, self.op.nodes)
9613

    
9614
  def Exec(self, feedback_fn):
9615
    """Compute the list of all the exported system images.
9616

9617
    @rtype: dict
9618
    @return: a dictionary with the structure node->(export-list)
9619
        where export-list is a list of the instances exported on
9620
        that node.
9621

9622
    """
9623
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9624
    rpcresult = self.rpc.call_export_list(self.nodes)
9625
    result = {}
9626
    for node in rpcresult:
9627
      if rpcresult[node].fail_msg:
9628
        result[node] = False
9629
      else:
9630
        result[node] = rpcresult[node].payload
9631

    
9632
    return result
9633

    
9634

    
9635
class LUBackupPrepare(NoHooksLU):
9636
  """Prepares an instance for an export and returns useful information.
9637

9638
  """
9639
  REQ_BGL = False
9640

    
9641
  def ExpandNames(self):
9642
    self._ExpandAndLockInstance()
9643

    
9644
  def CheckPrereq(self):
9645
    """Check prerequisites.
9646

9647
    """
9648
    instance_name = self.op.instance_name
9649

    
9650
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9651
    assert self.instance is not None, \
9652
          "Cannot retrieve locked instance %s" % self.op.instance_name
9653
    _CheckNodeOnline(self, self.instance.primary_node)
9654

    
9655
    self._cds = _GetClusterDomainSecret()
9656

    
9657
  def Exec(self, feedback_fn):
9658
    """Prepares an instance for an export.
9659

9660
    """
9661
    instance = self.instance
9662

    
9663
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9664
      salt = utils.GenerateSecret(8)
9665

    
9666
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9667
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9668
                                              constants.RIE_CERT_VALIDITY)
9669
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9670

    
9671
      (name, cert_pem) = result.payload
9672

    
9673
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9674
                                             cert_pem)
9675

    
9676
      return {
9677
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9678
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9679
                          salt),
9680
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9681
        }
9682

    
9683
    return None
9684

    
9685

    
9686
class LUBackupExport(LogicalUnit):
9687
  """Export an instance to an image in the cluster.
9688

9689
  """
9690
  HPATH = "instance-export"
9691
  HTYPE = constants.HTYPE_INSTANCE
9692
  REQ_BGL = False
9693

    
9694
  def CheckArguments(self):
9695
    """Check the arguments.
9696

9697
    """
9698
    self.x509_key_name = self.op.x509_key_name
9699
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9700

    
9701
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9702
      if not self.x509_key_name:
9703
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9704
                                   errors.ECODE_INVAL)
9705

    
9706
      if not self.dest_x509_ca_pem:
9707
        raise errors.OpPrereqError("Missing destination X509 CA",
9708
                                   errors.ECODE_INVAL)
9709

    
9710
  def ExpandNames(self):
9711
    self._ExpandAndLockInstance()
9712

    
9713
    # Lock all nodes for local exports
9714
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9715
      # FIXME: lock only instance primary and destination node
9716
      #
9717
      # Sad but true, for now we have do lock all nodes, as we don't know where
9718
      # the previous export might be, and in this LU we search for it and
9719
      # remove it from its current node. In the future we could fix this by:
9720
      #  - making a tasklet to search (share-lock all), then create the
9721
      #    new one, then one to remove, after
9722
      #  - removing the removal operation altogether
9723
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9724

    
9725
  def DeclareLocks(self, level):
9726
    """Last minute lock declaration."""
9727
    # All nodes are locked anyway, so nothing to do here.
9728

    
9729
  def BuildHooksEnv(self):
9730
    """Build hooks env.
9731

9732
    This will run on the master, primary node and target node.
9733

9734
    """
9735
    env = {
9736
      "EXPORT_MODE": self.op.mode,
9737
      "EXPORT_NODE": self.op.target_node,
9738
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9739
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9740
      # TODO: Generic function for boolean env variables
9741
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9742
      }
9743

    
9744
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9745

    
9746
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9747

    
9748
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9749
      nl.append(self.op.target_node)
9750

    
9751
    return env, nl, nl
9752

    
9753
  def CheckPrereq(self):
9754
    """Check prerequisites.
9755

9756
    This checks that the instance and node names are valid.
9757

9758
    """
9759
    instance_name = self.op.instance_name
9760

    
9761
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9762
    assert self.instance is not None, \
9763
          "Cannot retrieve locked instance %s" % self.op.instance_name
9764
    _CheckNodeOnline(self, self.instance.primary_node)
9765

    
9766
    if (self.op.remove_instance and self.instance.admin_up and
9767
        not self.op.shutdown):
9768
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9769
                                 " down before")
9770

    
9771
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9772
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9773
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9774
      assert self.dst_node is not None
9775

    
9776
      _CheckNodeOnline(self, self.dst_node.name)
9777
      _CheckNodeNotDrained(self, self.dst_node.name)
9778

    
9779
      self._cds = None
9780
      self.dest_disk_info = None
9781
      self.dest_x509_ca = None
9782

    
9783
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9784
      self.dst_node = None
9785

    
9786
      if len(self.op.target_node) != len(self.instance.disks):
9787
        raise errors.OpPrereqError(("Received destination information for %s"
9788
                                    " disks, but instance %s has %s disks") %
9789
                                   (len(self.op.target_node), instance_name,
9790
                                    len(self.instance.disks)),
9791
                                   errors.ECODE_INVAL)
9792

    
9793
      cds = _GetClusterDomainSecret()
9794

    
9795
      # Check X509 key name
9796
      try:
9797
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9798
      except (TypeError, ValueError), err:
9799
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9800

    
9801
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9802
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9803
                                   errors.ECODE_INVAL)
9804

    
9805
      # Load and verify CA
9806
      try:
9807
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9808
      except OpenSSL.crypto.Error, err:
9809
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9810
                                   (err, ), errors.ECODE_INVAL)
9811

    
9812
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9813
      if errcode is not None:
9814
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9815
                                   (msg, ), errors.ECODE_INVAL)
9816

    
9817
      self.dest_x509_ca = cert
9818

    
9819
      # Verify target information
9820
      disk_info = []
9821
      for idx, disk_data in enumerate(self.op.target_node):
9822
        try:
9823
          (host, port, magic) = \
9824
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9825
        except errors.GenericError, err:
9826
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9827
                                     (idx, err), errors.ECODE_INVAL)
9828

    
9829
        disk_info.append((host, port, magic))
9830

    
9831
      assert len(disk_info) == len(self.op.target_node)
9832
      self.dest_disk_info = disk_info
9833

    
9834
    else:
9835
      raise errors.ProgrammerError("Unhandled export mode %r" %
9836
                                   self.op.mode)
9837

    
9838
    # instance disk type verification
9839
    # TODO: Implement export support for file-based disks
9840
    for disk in self.instance.disks:
9841
      if disk.dev_type == constants.LD_FILE:
9842
        raise errors.OpPrereqError("Export not supported for instances with"
9843
                                   " file-based disks", errors.ECODE_INVAL)
9844

    
9845
  def _CleanupExports(self, feedback_fn):
9846
    """Removes exports of current instance from all other nodes.
9847

9848
    If an instance in a cluster with nodes A..D was exported to node C, its
9849
    exports will be removed from the nodes A, B and D.
9850

9851
    """
9852
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9853

    
9854
    nodelist = self.cfg.GetNodeList()
9855
    nodelist.remove(self.dst_node.name)
9856

    
9857
    # on one-node clusters nodelist will be empty after the removal
9858
    # if we proceed the backup would be removed because OpBackupQuery
9859
    # substitutes an empty list with the full cluster node list.
9860
    iname = self.instance.name
9861
    if nodelist:
9862
      feedback_fn("Removing old exports for instance %s" % iname)
9863
      exportlist = self.rpc.call_export_list(nodelist)
9864
      for node in exportlist:
9865
        if exportlist[node].fail_msg:
9866
          continue
9867
        if iname in exportlist[node].payload:
9868
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9869
          if msg:
9870
            self.LogWarning("Could not remove older export for instance %s"
9871
                            " on node %s: %s", iname, node, msg)
9872

    
9873
  def Exec(self, feedback_fn):
9874
    """Export an instance to an image in the cluster.
9875

9876
    """
9877
    assert self.op.mode in constants.EXPORT_MODES
9878

    
9879
    instance = self.instance
9880
    src_node = instance.primary_node
9881

    
9882
    if self.op.shutdown:
9883
      # shutdown the instance, but not the disks
9884
      feedback_fn("Shutting down instance %s" % instance.name)
9885
      result = self.rpc.call_instance_shutdown(src_node, instance,
9886
                                               self.op.shutdown_timeout)
9887
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9888
      result.Raise("Could not shutdown instance %s on"
9889
                   " node %s" % (instance.name, src_node))
9890

    
9891
    # set the disks ID correctly since call_instance_start needs the
9892
    # correct drbd minor to create the symlinks
9893
    for disk in instance.disks:
9894
      self.cfg.SetDiskID(disk, src_node)
9895

    
9896
    activate_disks = (not instance.admin_up)
9897

    
9898
    if activate_disks:
9899
      # Activate the instance disks if we'exporting a stopped instance
9900
      feedback_fn("Activating disks for %s" % instance.name)
9901
      _StartInstanceDisks(self, instance, None)
9902

    
9903
    try:
9904
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9905
                                                     instance)
9906

    
9907
      helper.CreateSnapshots()
9908
      try:
9909
        if (self.op.shutdown and instance.admin_up and
9910
            not self.op.remove_instance):
9911
          assert not activate_disks
9912
          feedback_fn("Starting instance %s" % instance.name)
9913
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9914
          msg = result.fail_msg
9915
          if msg:
9916
            feedback_fn("Failed to start instance: %s" % msg)
9917
            _ShutdownInstanceDisks(self, instance)
9918
            raise errors.OpExecError("Could not start instance: %s" % msg)
9919

    
9920
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9921
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9922
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9923
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9924
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9925

    
9926
          (key_name, _, _) = self.x509_key_name
9927

    
9928
          dest_ca_pem = \
9929
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9930
                                            self.dest_x509_ca)
9931

    
9932
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9933
                                                     key_name, dest_ca_pem,
9934
                                                     timeouts)
9935
      finally:
9936
        helper.Cleanup()
9937

    
9938
      # Check for backwards compatibility
9939
      assert len(dresults) == len(instance.disks)
9940
      assert compat.all(isinstance(i, bool) for i in dresults), \
9941
             "Not all results are boolean: %r" % dresults
9942

    
9943
    finally:
9944
      if activate_disks:
9945
        feedback_fn("Deactivating disks for %s" % instance.name)
9946
        _ShutdownInstanceDisks(self, instance)
9947

    
9948
    if not (compat.all(dresults) and fin_resu):
9949
      failures = []
9950
      if not fin_resu:
9951
        failures.append("export finalization")
9952
      if not compat.all(dresults):
9953
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
9954
                               if not dsk)
9955
        failures.append("disk export: disk(s) %s" % fdsk)
9956

    
9957
      raise errors.OpExecError("Export failed, errors in %s" %
9958
                               utils.CommaJoin(failures))
9959

    
9960
    # At this point, the export was successful, we can cleanup/finish
9961

    
9962
    # Remove instance if requested
9963
    if self.op.remove_instance:
9964
      feedback_fn("Removing instance %s" % instance.name)
9965
      _RemoveInstance(self, feedback_fn, instance,
9966
                      self.op.ignore_remove_failures)
9967

    
9968
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9969
      self._CleanupExports(feedback_fn)
9970

    
9971
    return fin_resu, dresults
9972

    
9973

    
9974
class LUBackupRemove(NoHooksLU):
9975
  """Remove exports related to the named instance.
9976

9977
  """
9978
  REQ_BGL = False
9979

    
9980
  def ExpandNames(self):
9981
    self.needed_locks = {}
9982
    # We need all nodes to be locked in order for RemoveExport to work, but we
9983
    # don't need to lock the instance itself, as nothing will happen to it (and
9984
    # we can remove exports also for a removed instance)
9985
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9986

    
9987
  def Exec(self, feedback_fn):
9988
    """Remove any export.
9989

9990
    """
9991
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9992
    # If the instance was not found we'll try with the name that was passed in.
9993
    # This will only work if it was an FQDN, though.
9994
    fqdn_warn = False
9995
    if not instance_name:
9996
      fqdn_warn = True
9997
      instance_name = self.op.instance_name
9998

    
9999
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
10000
    exportlist = self.rpc.call_export_list(locked_nodes)
10001
    found = False
10002
    for node in exportlist:
10003
      msg = exportlist[node].fail_msg
10004
      if msg:
10005
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
10006
        continue
10007
      if instance_name in exportlist[node].payload:
10008
        found = True
10009
        result = self.rpc.call_export_remove(node, instance_name)
10010
        msg = result.fail_msg
10011
        if msg:
10012
          logging.error("Could not remove export for instance %s"
10013
                        " on node %s: %s", instance_name, node, msg)
10014

    
10015
    if fqdn_warn and not found:
10016
      feedback_fn("Export not found. If trying to remove an export belonging"
10017
                  " to a deleted instance please use its Fully Qualified"
10018
                  " Domain Name.")
10019

    
10020

    
10021
class LUGroupAdd(LogicalUnit):
10022
  """Logical unit for creating node groups.
10023

10024
  """
10025
  HPATH = "group-add"
10026
  HTYPE = constants.HTYPE_GROUP
10027
  REQ_BGL = False
10028

    
10029
  def ExpandNames(self):
10030
    # We need the new group's UUID here so that we can create and acquire the
10031
    # corresponding lock. Later, in Exec(), we'll indicate to cfg.AddNodeGroup
10032
    # that it should not check whether the UUID exists in the configuration.
10033
    self.group_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
10034
    self.needed_locks = {}
10035
    self.add_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
10036

    
10037
  def CheckPrereq(self):
10038
    """Check prerequisites.
10039

10040
    This checks that the given group name is not an existing node group
10041
    already.
10042

10043
    """
10044
    try:
10045
      existing_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10046
    except errors.OpPrereqError:
10047
      pass
10048
    else:
10049
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
10050
                                 " node group (UUID: %s)" %
10051
                                 (self.op.group_name, existing_uuid),
10052
                                 errors.ECODE_EXISTS)
10053

    
10054
    if self.op.ndparams:
10055
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
10056

    
10057
  def BuildHooksEnv(self):
10058
    """Build hooks env.
10059

10060
    """
10061
    env = {
10062
      "GROUP_NAME": self.op.group_name,
10063
      }
10064
    mn = self.cfg.GetMasterNode()
10065
    return env, [mn], [mn]
10066

    
10067
  def Exec(self, feedback_fn):
10068
    """Add the node group to the cluster.
10069

10070
    """
10071
    group_obj = objects.NodeGroup(name=self.op.group_name, members=[],
10072
                                  uuid=self.group_uuid,
10073
                                  alloc_policy=self.op.alloc_policy,
10074
                                  ndparams=self.op.ndparams)
10075

    
10076
    self.cfg.AddNodeGroup(group_obj, self.proc.GetECId(), check_uuid=False)
10077
    del self.remove_locks[locking.LEVEL_NODEGROUP]
10078

    
10079

    
10080
class LUGroupAssignNodes(NoHooksLU):
10081
  """Logical unit for assigning nodes to groups.
10082

10083
  """
10084
  REQ_BGL = False
10085

    
10086
  def ExpandNames(self):
10087
    # These raise errors.OpPrereqError on their own:
10088
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10089
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
10090

    
10091
    # We want to lock all the affected nodes and groups. We have readily
10092
    # available the list of nodes, and the *destination* group. To gather the
10093
    # list of "source" groups, we need to fetch node information.
10094
    self.node_data = self.cfg.GetAllNodesInfo()
10095
    affected_groups = set(self.node_data[node].group for node in self.op.nodes)
10096
    affected_groups.add(self.group_uuid)
10097

    
10098
    self.needed_locks = {
10099
      locking.LEVEL_NODEGROUP: list(affected_groups),
10100
      locking.LEVEL_NODE: self.op.nodes,
10101
      }
10102

    
10103
  def CheckPrereq(self):
10104
    """Check prerequisites.
10105

10106
    """
10107
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
10108
    instance_data = self.cfg.GetAllInstancesInfo()
10109

    
10110
    if self.group is None:
10111
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10112
                               (self.op.group_name, self.group_uuid))
10113

    
10114
    (new_splits, previous_splits) = \
10115
      self.CheckAssignmentForSplitInstances([(node, self.group_uuid)
10116
                                             for node in self.op.nodes],
10117
                                            self.node_data, instance_data)
10118

    
10119
    if new_splits:
10120
      fmt_new_splits = utils.CommaJoin(utils.NiceSort(new_splits))
10121

    
10122
      if not self.op.force:
10123
        raise errors.OpExecError("The following instances get split by this"
10124
                                 " change and --force was not given: %s" %
10125
                                 fmt_new_splits)
10126
      else:
10127
        self.LogWarning("This operation will split the following instances: %s",
10128
                        fmt_new_splits)
10129

    
10130
        if previous_splits:
10131
          self.LogWarning("In addition, these already-split instances continue"
10132
                          " to be spit across groups: %s",
10133
                          utils.CommaJoin(utils.NiceSort(previous_splits)))
10134

    
10135
  def Exec(self, feedback_fn):
10136
    """Assign nodes to a new group.
10137

10138
    """
10139
    for node in self.op.nodes:
10140
      self.node_data[node].group = self.group_uuid
10141

    
10142
    self.cfg.Update(self.group, feedback_fn) # Saves all modified nodes.
10143

    
10144
  @staticmethod
10145
  def CheckAssignmentForSplitInstances(changes, node_data, instance_data):
10146
    """Check for split instances after a node assignment.
10147

10148
    This method considers a series of node assignments as an atomic operation,
10149
    and returns information about split instances after applying the set of
10150
    changes.
10151

10152
    In particular, it returns information about newly split instances, and
10153
    instances that were already split, and remain so after the change.
10154

10155
    Only instances whose disk template is listed in constants.DTS_NET_MIRROR are
10156
    considered.
10157

10158
    @type changes: list of (node_name, new_group_uuid) pairs.
10159
    @param changes: list of node assignments to consider.
10160
    @param node_data: a dict with data for all nodes
10161
    @param instance_data: a dict with all instances to consider
10162
    @rtype: a two-tuple
10163
    @return: a list of instances that were previously okay and result split as a
10164
      consequence of this change, and a list of instances that were previously
10165
      split and this change does not fix.
10166

10167
    """
10168
    changed_nodes = dict((node, group) for node, group in changes
10169
                         if node_data[node].group != group)
10170

    
10171
    all_split_instances = set()
10172
    previously_split_instances = set()
10173

    
10174
    def InstanceNodes(instance):
10175
      return [instance.primary_node] + list(instance.secondary_nodes)
10176

    
10177
    for inst in instance_data.values():
10178
      if inst.disk_template not in constants.DTS_NET_MIRROR:
10179
        continue
10180

    
10181
      instance_nodes = InstanceNodes(inst)
10182

    
10183
      if len(set(node_data[node].group for node in instance_nodes)) > 1:
10184
        previously_split_instances.add(inst.name)
10185

    
10186
      if len(set(changed_nodes.get(node, node_data[node].group)
10187
                 for node in instance_nodes)) > 1:
10188
        all_split_instances.add(inst.name)
10189

    
10190
    return (list(all_split_instances - previously_split_instances),
10191
            list(previously_split_instances & all_split_instances))
10192

    
10193

    
10194
class _GroupQuery(_QueryBase):
10195

    
10196
  FIELDS = query.GROUP_FIELDS
10197

    
10198
  def ExpandNames(self, lu):
10199
    lu.needed_locks = {}
10200

    
10201
    self._all_groups = lu.cfg.GetAllNodeGroupsInfo()
10202
    name_to_uuid = dict((g.name, g.uuid) for g in self._all_groups.values())
10203

    
10204
    if not self.names:
10205
      self.wanted = [name_to_uuid[name]
10206
                     for name in utils.NiceSort(name_to_uuid.keys())]
10207
    else:
10208
      # Accept names to be either names or UUIDs.
10209
      missing = []
10210
      self.wanted = []
10211
      all_uuid = frozenset(self._all_groups.keys())
10212

    
10213
      for name in self.names:
10214
        if name in all_uuid:
10215
          self.wanted.append(name)
10216
        elif name in name_to_uuid:
10217
          self.wanted.append(name_to_uuid[name])
10218
        else:
10219
          missing.append(name)
10220

    
10221
      if missing:
10222
        raise errors.OpPrereqError("Some groups do not exist: %s" % missing,
10223
                                   errors.ECODE_NOENT)
10224

    
10225
  def DeclareLocks(self, lu, level):
10226
    pass
10227

    
10228
  def _GetQueryData(self, lu):
10229
    """Computes the list of node groups and their attributes.
10230

10231
    """
10232
    do_nodes = query.GQ_NODE in self.requested_data
10233
    do_instances = query.GQ_INST in self.requested_data
10234

    
10235
    group_to_nodes = None
10236
    group_to_instances = None
10237

    
10238
    # For GQ_NODE, we need to map group->[nodes], and group->[instances] for
10239
    # GQ_INST. The former is attainable with just GetAllNodesInfo(), but for the
10240
    # latter GetAllInstancesInfo() is not enough, for we have to go through
10241
    # instance->node. Hence, we will need to process nodes even if we only need
10242
    # instance information.
10243
    if do_nodes or do_instances:
10244
      all_nodes = lu.cfg.GetAllNodesInfo()
10245
      group_to_nodes = dict((uuid, []) for uuid in self.wanted)
10246
      node_to_group = {}
10247

    
10248
      for node in all_nodes.values():
10249
        if node.group in group_to_nodes:
10250
          group_to_nodes[node.group].append(node.name)
10251
          node_to_group[node.name] = node.group
10252

    
10253
      if do_instances:
10254
        all_instances = lu.cfg.GetAllInstancesInfo()
10255
        group_to_instances = dict((uuid, []) for uuid in self.wanted)
10256

    
10257
        for instance in all_instances.values():
10258
          node = instance.primary_node
10259
          if node in node_to_group:
10260
            group_to_instances[node_to_group[node]].append(instance.name)
10261

    
10262
        if not do_nodes:
10263
          # Do not pass on node information if it was not requested.
10264
          group_to_nodes = None
10265

    
10266
    return query.GroupQueryData([self._all_groups[uuid]
10267
                                 for uuid in self.wanted],
10268
                                group_to_nodes, group_to_instances)
10269

    
10270

    
10271
class LUGroupQuery(NoHooksLU):
10272
  """Logical unit for querying node groups.
10273

10274
  """
10275
  REQ_BGL = False
10276

    
10277
  def CheckArguments(self):
10278
    self.gq = _GroupQuery(self.op.names, self.op.output_fields, False)
10279

    
10280
  def ExpandNames(self):
10281
    self.gq.ExpandNames(self)
10282

    
10283
  def Exec(self, feedback_fn):
10284
    return self.gq.OldStyleQuery(self)
10285

    
10286

    
10287
class LUGroupSetParams(LogicalUnit):
10288
  """Modifies the parameters of a node group.
10289

10290
  """
10291
  HPATH = "group-modify"
10292
  HTYPE = constants.HTYPE_GROUP
10293
  REQ_BGL = False
10294

    
10295
  def CheckArguments(self):
10296
    all_changes = [
10297
      self.op.ndparams,
10298
      self.op.alloc_policy,
10299
      ]
10300

    
10301
    if all_changes.count(None) == len(all_changes):
10302
      raise errors.OpPrereqError("Please pass at least one modification",
10303
                                 errors.ECODE_INVAL)
10304

    
10305
  def ExpandNames(self):
10306
    # This raises errors.OpPrereqError on its own:
10307
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10308

    
10309
    self.needed_locks = {
10310
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10311
      }
10312

    
10313
  def CheckPrereq(self):
10314
    """Check prerequisites.
10315

10316
    """
10317
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
10318

    
10319
    if self.group is None:
10320
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10321
                               (self.op.group_name, self.group_uuid))
10322

    
10323
    if self.op.ndparams:
10324
      new_ndparams = _GetUpdatedParams(self.group.ndparams, self.op.ndparams)
10325
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
10326
      self.new_ndparams = new_ndparams
10327

    
10328
  def BuildHooksEnv(self):
10329
    """Build hooks env.
10330

10331
    """
10332
    env = {
10333
      "GROUP_NAME": self.op.group_name,
10334
      "NEW_ALLOC_POLICY": self.op.alloc_policy,
10335
      }
10336
    mn = self.cfg.GetMasterNode()
10337
    return env, [mn], [mn]
10338

    
10339
  def Exec(self, feedback_fn):
10340
    """Modifies the node group.
10341

10342
    """
10343
    result = []
10344

    
10345
    if self.op.ndparams:
10346
      self.group.ndparams = self.new_ndparams
10347
      result.append(("ndparams", str(self.group.ndparams)))
10348

    
10349
    if self.op.alloc_policy:
10350
      self.group.alloc_policy = self.op.alloc_policy
10351

    
10352
    self.cfg.Update(self.group, feedback_fn)
10353
    return result
10354

    
10355

    
10356

    
10357
class LUGroupRemove(LogicalUnit):
10358
  HPATH = "group-remove"
10359
  HTYPE = constants.HTYPE_GROUP
10360
  REQ_BGL = False
10361

    
10362
  def ExpandNames(self):
10363
    # This will raises errors.OpPrereqError on its own:
10364
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10365
    self.needed_locks = {
10366
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10367
      }
10368

    
10369
  def CheckPrereq(self):
10370
    """Check prerequisites.
10371

10372
    This checks that the given group name exists as a node group, that is
10373
    empty (i.e., contains no nodes), and that is not the last group of the
10374
    cluster.
10375

10376
    """
10377
    # Verify that the group is empty.
10378
    group_nodes = [node.name
10379
                   for node in self.cfg.GetAllNodesInfo().values()
10380
                   if node.group == self.group_uuid]
10381

    
10382
    if group_nodes:
10383
      raise errors.OpPrereqError("Group '%s' not empty, has the following"
10384
                                 " nodes: %s" %
10385
                                 (self.op.group_name,
10386
                                  utils.CommaJoin(utils.NiceSort(group_nodes))),
10387
                                 errors.ECODE_STATE)
10388

    
10389
    # Verify the cluster would not be left group-less.
10390
    if len(self.cfg.GetNodeGroupList()) == 1:
10391
      raise errors.OpPrereqError("Group '%s' is the only group,"
10392
                                 " cannot be removed" %
10393
                                 self.op.group_name,
10394
                                 errors.ECODE_STATE)
10395

    
10396
  def BuildHooksEnv(self):
10397
    """Build hooks env.
10398

10399
    """
10400
    env = {
10401
      "GROUP_NAME": self.op.group_name,
10402
      }
10403
    mn = self.cfg.GetMasterNode()
10404
    return env, [mn], [mn]
10405

    
10406
  def Exec(self, feedback_fn):
10407
    """Remove the node group.
10408

10409
    """
10410
    try:
10411
      self.cfg.RemoveNodeGroup(self.group_uuid)
10412
    except errors.ConfigurationError:
10413
      raise errors.OpExecError("Group '%s' with UUID %s disappeared" %
10414
                               (self.op.group_name, self.group_uuid))
10415

    
10416
    self.remove_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
10417

    
10418

    
10419
class LUGroupRename(LogicalUnit):
10420
  HPATH = "group-rename"
10421
  HTYPE = constants.HTYPE_GROUP
10422
  REQ_BGL = False
10423

    
10424
  def ExpandNames(self):
10425
    # This raises errors.OpPrereqError on its own:
10426
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.old_name)
10427

    
10428
    self.needed_locks = {
10429
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10430
      }
10431

    
10432
  def CheckPrereq(self):
10433
    """Check prerequisites.
10434

10435
    This checks that the given old_name exists as a node group, and that
10436
    new_name doesn't.
10437

10438
    """
10439
    try:
10440
      new_name_uuid = self.cfg.LookupNodeGroup(self.op.new_name)
10441
    except errors.OpPrereqError:
10442
      pass
10443
    else:
10444
      raise errors.OpPrereqError("Desired new name '%s' clashes with existing"
10445
                                 " node group (UUID: %s)" %
10446
                                 (self.op.new_name, new_name_uuid),
10447
                                 errors.ECODE_EXISTS)
10448

    
10449
  def BuildHooksEnv(self):
10450
    """Build hooks env.
10451

10452
    """
10453
    env = {
10454
      "OLD_NAME": self.op.old_name,
10455
      "NEW_NAME": self.op.new_name,
10456
      }
10457

    
10458
    mn = self.cfg.GetMasterNode()
10459
    all_nodes = self.cfg.GetAllNodesInfo()
10460
    run_nodes = [mn]
10461
    all_nodes.pop(mn, None)
10462

    
10463
    for node in all_nodes.values():
10464
      if node.group == self.group_uuid:
10465
        run_nodes.append(node.name)
10466

    
10467
    return env, run_nodes, run_nodes
10468

    
10469
  def Exec(self, feedback_fn):
10470
    """Rename the node group.
10471

10472
    """
10473
    group = self.cfg.GetNodeGroup(self.group_uuid)
10474

    
10475
    if group is None:
10476
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10477
                               (self.op.old_name, self.group_uuid))
10478

    
10479
    group.name = self.op.new_name
10480
    self.cfg.Update(group, feedback_fn)
10481

    
10482
    return self.op.new_name
10483

    
10484

    
10485
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
10486
  """Generic tags LU.
10487

10488
  This is an abstract class which is the parent of all the other tags LUs.
10489

10490
  """
10491

    
10492
  def ExpandNames(self):
10493
    self.needed_locks = {}
10494
    if self.op.kind == constants.TAG_NODE:
10495
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
10496
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
10497
    elif self.op.kind == constants.TAG_INSTANCE:
10498
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
10499
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
10500

    
10501
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
10502
    # not possible to acquire the BGL based on opcode parameters)
10503

    
10504
  def CheckPrereq(self):
10505
    """Check prerequisites.
10506

10507
    """
10508
    if self.op.kind == constants.TAG_CLUSTER:
10509
      self.target = self.cfg.GetClusterInfo()
10510
    elif self.op.kind == constants.TAG_NODE:
10511
      self.target = self.cfg.GetNodeInfo(self.op.name)
10512
    elif self.op.kind == constants.TAG_INSTANCE:
10513
      self.target = self.cfg.GetInstanceInfo(self.op.name)
10514
    else:
10515
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
10516
                                 str(self.op.kind), errors.ECODE_INVAL)
10517

    
10518

    
10519
class LUTagsGet(TagsLU):
10520
  """Returns the tags of a given object.
10521

10522
  """
10523
  REQ_BGL = False
10524

    
10525
  def ExpandNames(self):
10526
    TagsLU.ExpandNames(self)
10527

    
10528
    # Share locks as this is only a read operation
10529
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
10530

    
10531
  def Exec(self, feedback_fn):
10532
    """Returns the tag list.
10533

10534
    """
10535
    return list(self.target.GetTags())
10536

    
10537

    
10538
class LUTagsSearch(NoHooksLU):
10539
  """Searches the tags for a given pattern.
10540

10541
  """
10542
  REQ_BGL = False
10543

    
10544
  def ExpandNames(self):
10545
    self.needed_locks = {}
10546

    
10547
  def CheckPrereq(self):
10548
    """Check prerequisites.
10549

10550
    This checks the pattern passed for validity by compiling it.
10551

10552
    """
10553
    try:
10554
      self.re = re.compile(self.op.pattern)
10555
    except re.error, err:
10556
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
10557
                                 (self.op.pattern, err), errors.ECODE_INVAL)
10558

    
10559
  def Exec(self, feedback_fn):
10560
    """Returns the tag list.
10561

10562
    """
10563
    cfg = self.cfg
10564
    tgts = [("/cluster", cfg.GetClusterInfo())]
10565
    ilist = cfg.GetAllInstancesInfo().values()
10566
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
10567
    nlist = cfg.GetAllNodesInfo().values()
10568
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
10569
    results = []
10570
    for path, target in tgts:
10571
      for tag in target.GetTags():
10572
        if self.re.search(tag):
10573
          results.append((path, tag))
10574
    return results
10575

    
10576

    
10577
class LUTagsSet(TagsLU):
10578
  """Sets a tag on a given object.
10579

10580
  """
10581
  REQ_BGL = False
10582

    
10583
  def CheckPrereq(self):
10584
    """Check prerequisites.
10585

10586
    This checks the type and length of the tag name and value.
10587

10588
    """
10589
    TagsLU.CheckPrereq(self)
10590
    for tag in self.op.tags:
10591
      objects.TaggableObject.ValidateTag(tag)
10592

    
10593
  def Exec(self, feedback_fn):
10594
    """Sets the tag.
10595

10596
    """
10597
    try:
10598
      for tag in self.op.tags:
10599
        self.target.AddTag(tag)
10600
    except errors.TagError, err:
10601
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
10602
    self.cfg.Update(self.target, feedback_fn)
10603

    
10604

    
10605
class LUTagsDel(TagsLU):
10606
  """Delete a list of tags from a given object.
10607

10608
  """
10609
  REQ_BGL = False
10610

    
10611
  def CheckPrereq(self):
10612
    """Check prerequisites.
10613

10614
    This checks that we have the given tag.
10615

10616
    """
10617
    TagsLU.CheckPrereq(self)
10618
    for tag in self.op.tags:
10619
      objects.TaggableObject.ValidateTag(tag)
10620
    del_tags = frozenset(self.op.tags)
10621
    cur_tags = self.target.GetTags()
10622

    
10623
    diff_tags = del_tags - cur_tags
10624
    if diff_tags:
10625
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
10626
      raise errors.OpPrereqError("Tag(s) %s not found" %
10627
                                 (utils.CommaJoin(diff_names), ),
10628
                                 errors.ECODE_NOENT)
10629

    
10630
  def Exec(self, feedback_fn):
10631
    """Remove the tag from the object.
10632

10633
    """
10634
    for tag in self.op.tags:
10635
      self.target.RemoveTag(tag)
10636
    self.cfg.Update(self.target, feedback_fn)
10637

    
10638

    
10639
class LUTestDelay(NoHooksLU):
10640
  """Sleep for a specified amount of time.
10641

10642
  This LU sleeps on the master and/or nodes for a specified amount of
10643
  time.
10644

10645
  """
10646
  REQ_BGL = False
10647

    
10648
  def ExpandNames(self):
10649
    """Expand names and set required locks.
10650

10651
    This expands the node list, if any.
10652

10653
    """
10654
    self.needed_locks = {}
10655
    if self.op.on_nodes:
10656
      # _GetWantedNodes can be used here, but is not always appropriate to use
10657
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
10658
      # more information.
10659
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
10660
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
10661

    
10662
  def _TestDelay(self):
10663
    """Do the actual sleep.
10664

10665
    """
10666
    if self.op.on_master:
10667
      if not utils.TestDelay(self.op.duration):
10668
        raise errors.OpExecError("Error during master delay test")
10669
    if self.op.on_nodes:
10670
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
10671
      for node, node_result in result.items():
10672
        node_result.Raise("Failure during rpc call to node %s" % node)
10673

    
10674
  def Exec(self, feedback_fn):
10675
    """Execute the test delay opcode, with the wanted repetitions.
10676

10677
    """
10678
    if self.op.repeat == 0:
10679
      self._TestDelay()
10680
    else:
10681
      top_value = self.op.repeat - 1
10682
      for i in range(self.op.repeat):
10683
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
10684
        self._TestDelay()
10685

    
10686

    
10687
class LUTestJqueue(NoHooksLU):
10688
  """Utility LU to test some aspects of the job queue.
10689

10690
  """
10691
  REQ_BGL = False
10692

    
10693
  # Must be lower than default timeout for WaitForJobChange to see whether it
10694
  # notices changed jobs
10695
  _CLIENT_CONNECT_TIMEOUT = 20.0
10696
  _CLIENT_CONFIRM_TIMEOUT = 60.0
10697

    
10698
  @classmethod
10699
  def _NotifyUsingSocket(cls, cb, errcls):
10700
    """Opens a Unix socket and waits for another program to connect.
10701

10702
    @type cb: callable
10703
    @param cb: Callback to send socket name to client
10704
    @type errcls: class
10705
    @param errcls: Exception class to use for errors
10706

10707
    """
10708
    # Using a temporary directory as there's no easy way to create temporary
10709
    # sockets without writing a custom loop around tempfile.mktemp and
10710
    # socket.bind
10711
    tmpdir = tempfile.mkdtemp()
10712
    try:
10713
      tmpsock = utils.PathJoin(tmpdir, "sock")
10714

    
10715
      logging.debug("Creating temporary socket at %s", tmpsock)
10716
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
10717
      try:
10718
        sock.bind(tmpsock)
10719
        sock.listen(1)
10720

    
10721
        # Send details to client
10722
        cb(tmpsock)
10723

    
10724
        # Wait for client to connect before continuing
10725
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
10726
        try:
10727
          (conn, _) = sock.accept()
10728
        except socket.error, err:
10729
          raise errcls("Client didn't connect in time (%s)" % err)
10730
      finally:
10731
        sock.close()
10732
    finally:
10733
      # Remove as soon as client is connected
10734
      shutil.rmtree(tmpdir)
10735

    
10736
    # Wait for client to close
10737
    try:
10738
      try:
10739
        # pylint: disable-msg=E1101
10740
        # Instance of '_socketobject' has no ... member
10741
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
10742
        conn.recv(1)
10743
      except socket.error, err:
10744
        raise errcls("Client failed to confirm notification (%s)" % err)
10745
    finally:
10746
      conn.close()
10747

    
10748
  def _SendNotification(self, test, arg, sockname):
10749
    """Sends a notification to the client.
10750

10751
    @type test: string
10752
    @param test: Test name
10753
    @param arg: Test argument (depends on test)
10754
    @type sockname: string
10755
    @param sockname: Socket path
10756

10757
    """
10758
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
10759

    
10760
  def _Notify(self, prereq, test, arg):
10761
    """Notifies the client of a test.
10762

10763
    @type prereq: bool
10764
    @param prereq: Whether this is a prereq-phase test
10765
    @type test: string
10766
    @param test: Test name
10767
    @param arg: Test argument (depends on test)
10768

10769
    """
10770
    if prereq:
10771
      errcls = errors.OpPrereqError
10772
    else:
10773
      errcls = errors.OpExecError
10774

    
10775
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
10776
                                                  test, arg),
10777
                                   errcls)
10778

    
10779
  def CheckArguments(self):
10780
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
10781
    self.expandnames_calls = 0
10782

    
10783
  def ExpandNames(self):
10784
    checkargs_calls = getattr(self, "checkargs_calls", 0)
10785
    if checkargs_calls < 1:
10786
      raise errors.ProgrammerError("CheckArguments was not called")
10787

    
10788
    self.expandnames_calls += 1
10789

    
10790
    if self.op.notify_waitlock:
10791
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
10792

    
10793
    self.LogInfo("Expanding names")
10794

    
10795
    # Get lock on master node (just to get a lock, not for a particular reason)
10796
    self.needed_locks = {
10797
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
10798
      }
10799

    
10800
  def Exec(self, feedback_fn):
10801
    if self.expandnames_calls < 1:
10802
      raise errors.ProgrammerError("ExpandNames was not called")
10803

    
10804
    if self.op.notify_exec:
10805
      self._Notify(False, constants.JQT_EXEC, None)
10806

    
10807
    self.LogInfo("Executing")
10808

    
10809
    if self.op.log_messages:
10810
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
10811
      for idx, msg in enumerate(self.op.log_messages):
10812
        self.LogInfo("Sending log message %s", idx + 1)
10813
        feedback_fn(constants.JQT_MSGPREFIX + msg)
10814
        # Report how many test messages have been sent
10815
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
10816

    
10817
    if self.op.fail:
10818
      raise errors.OpExecError("Opcode failure was requested")
10819

    
10820
    return True
10821

    
10822

    
10823
class IAllocator(object):
10824
  """IAllocator framework.
10825

10826
  An IAllocator instance has three sets of attributes:
10827
    - cfg that is needed to query the cluster
10828
    - input data (all members of the _KEYS class attribute are required)
10829
    - four buffer attributes (in|out_data|text), that represent the
10830
      input (to the external script) in text and data structure format,
10831
      and the output from it, again in two formats
10832
    - the result variables from the script (success, info, nodes) for
10833
      easy usage
10834

10835
  """
10836
  # pylint: disable-msg=R0902
10837
  # lots of instance attributes
10838
  _ALLO_KEYS = [
10839
    "name", "mem_size", "disks", "disk_template",
10840
    "os", "tags", "nics", "vcpus", "hypervisor",
10841
    ]
10842
  _RELO_KEYS = [
10843
    "name", "relocate_from",
10844
    ]
10845
  _EVAC_KEYS = [
10846
    "evac_nodes",
10847
    ]
10848

    
10849
  def __init__(self, cfg, rpc, mode, **kwargs):
10850
    self.cfg = cfg
10851
    self.rpc = rpc
10852
    # init buffer variables
10853
    self.in_text = self.out_text = self.in_data = self.out_data = None
10854
    # init all input fields so that pylint is happy
10855
    self.mode = mode
10856
    self.mem_size = self.disks = self.disk_template = None
10857
    self.os = self.tags = self.nics = self.vcpus = None
10858
    self.hypervisor = None
10859
    self.relocate_from = None
10860
    self.name = None
10861
    self.evac_nodes = None
10862
    # computed fields
10863
    self.required_nodes = None
10864
    # init result fields
10865
    self.success = self.info = self.result = None
10866
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10867
      keyset = self._ALLO_KEYS
10868
      fn = self._AddNewInstance
10869
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10870
      keyset = self._RELO_KEYS
10871
      fn = self._AddRelocateInstance
10872
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10873
      keyset = self._EVAC_KEYS
10874
      fn = self._AddEvacuateNodes
10875
    else:
10876
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
10877
                                   " IAllocator" % self.mode)
10878
    for key in kwargs:
10879
      if key not in keyset:
10880
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
10881
                                     " IAllocator" % key)
10882
      setattr(self, key, kwargs[key])
10883

    
10884
    for key in keyset:
10885
      if key not in kwargs:
10886
        raise errors.ProgrammerError("Missing input parameter '%s' to"
10887
                                     " IAllocator" % key)
10888
    self._BuildInputData(fn)
10889

    
10890
  def _ComputeClusterData(self):
10891
    """Compute the generic allocator input data.
10892

10893
    This is the data that is independent of the actual operation.
10894

10895
    """
10896
    cfg = self.cfg
10897
    cluster_info = cfg.GetClusterInfo()
10898
    # cluster data
10899
    data = {
10900
      "version": constants.IALLOCATOR_VERSION,
10901
      "cluster_name": cfg.GetClusterName(),
10902
      "cluster_tags": list(cluster_info.GetTags()),
10903
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
10904
      # we don't have job IDs
10905
      }
10906
    ninfo = cfg.GetAllNodesInfo()
10907
    iinfo = cfg.GetAllInstancesInfo().values()
10908
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
10909

    
10910
    # node data
10911
    node_list = [n.name for n in ninfo.values() if n.vm_capable]
10912

    
10913
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10914
      hypervisor_name = self.hypervisor
10915
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10916
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
10917
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10918
      hypervisor_name = cluster_info.enabled_hypervisors[0]
10919

    
10920
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
10921
                                        hypervisor_name)
10922
    node_iinfo = \
10923
      self.rpc.call_all_instances_info(node_list,
10924
                                       cluster_info.enabled_hypervisors)
10925

    
10926
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
10927

    
10928
    config_ndata = self._ComputeBasicNodeData(ninfo)
10929
    data["nodes"] = self._ComputeDynamicNodeData(ninfo, node_data, node_iinfo,
10930
                                                 i_list, config_ndata)
10931
    assert len(data["nodes"]) == len(ninfo), \
10932
        "Incomplete node data computed"
10933

    
10934
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
10935

    
10936
    self.in_data = data
10937

    
10938
  @staticmethod
10939
  def _ComputeNodeGroupData(cfg):
10940
    """Compute node groups data.
10941

10942
    """
10943
    ng = {}
10944
    for guuid, gdata in cfg.GetAllNodeGroupsInfo().items():
10945
      ng[guuid] = {
10946
        "name": gdata.name,
10947
        "alloc_policy": gdata.alloc_policy,
10948
        }
10949
    return ng
10950

    
10951
  @staticmethod
10952
  def _ComputeBasicNodeData(node_cfg):
10953
    """Compute global node data.
10954

10955
    @rtype: dict
10956
    @returns: a dict of name: (node dict, node config)
10957

10958
    """
10959
    node_results = {}
10960
    for ninfo in node_cfg.values():
10961
      # fill in static (config-based) values
10962
      pnr = {
10963
        "tags": list(ninfo.GetTags()),
10964
        "primary_ip": ninfo.primary_ip,
10965
        "secondary_ip": ninfo.secondary_ip,
10966
        "offline": ninfo.offline,
10967
        "drained": ninfo.drained,
10968
        "master_candidate": ninfo.master_candidate,
10969
        "group": ninfo.group,
10970
        "master_capable": ninfo.master_capable,
10971
        "vm_capable": ninfo.vm_capable,
10972
        }
10973

    
10974
      node_results[ninfo.name] = pnr
10975

    
10976
    return node_results
10977

    
10978
  @staticmethod
10979
  def _ComputeDynamicNodeData(node_cfg, node_data, node_iinfo, i_list,
10980
                              node_results):
10981
    """Compute global node data.
10982

10983
    @param node_results: the basic node structures as filled from the config
10984

10985
    """
10986
    # make a copy of the current dict
10987
    node_results = dict(node_results)
10988
    for nname, nresult in node_data.items():
10989
      assert nname in node_results, "Missing basic data for node %s" % nname
10990
      ninfo = node_cfg[nname]
10991

    
10992
      if not (ninfo.offline or ninfo.drained):
10993
        nresult.Raise("Can't get data for node %s" % nname)
10994
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
10995
                                nname)
10996
        remote_info = nresult.payload
10997

    
10998
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
10999
                     'vg_size', 'vg_free', 'cpu_total']:
11000
          if attr not in remote_info:
11001
            raise errors.OpExecError("Node '%s' didn't return attribute"
11002
                                     " '%s'" % (nname, attr))
11003
          if not isinstance(remote_info[attr], int):
11004
            raise errors.OpExecError("Node '%s' returned invalid value"
11005
                                     " for '%s': %s" %
11006
                                     (nname, attr, remote_info[attr]))
11007
        # compute memory used by primary instances
11008
        i_p_mem = i_p_up_mem = 0
11009
        for iinfo, beinfo in i_list:
11010
          if iinfo.primary_node == nname:
11011
            i_p_mem += beinfo[constants.BE_MEMORY]
11012
            if iinfo.name not in node_iinfo[nname].payload:
11013
              i_used_mem = 0
11014
            else:
11015
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
11016
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
11017
            remote_info['memory_free'] -= max(0, i_mem_diff)
11018

    
11019
            if iinfo.admin_up:
11020
              i_p_up_mem += beinfo[constants.BE_MEMORY]
11021

    
11022
        # compute memory used by instances
11023
        pnr_dyn = {
11024
          "total_memory": remote_info['memory_total'],
11025
          "reserved_memory": remote_info['memory_dom0'],
11026
          "free_memory": remote_info['memory_free'],
11027
          "total_disk": remote_info['vg_size'],
11028
          "free_disk": remote_info['vg_free'],
11029
          "total_cpus": remote_info['cpu_total'],
11030
          "i_pri_memory": i_p_mem,
11031
          "i_pri_up_memory": i_p_up_mem,
11032
          }
11033
        pnr_dyn.update(node_results[nname])
11034

    
11035
      node_results[nname] = pnr_dyn
11036

    
11037
    return node_results
11038

    
11039
  @staticmethod
11040
  def _ComputeInstanceData(cluster_info, i_list):
11041
    """Compute global instance data.
11042

11043
    """
11044
    instance_data = {}
11045
    for iinfo, beinfo in i_list:
11046
      nic_data = []
11047
      for nic in iinfo.nics:
11048
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
11049
        nic_dict = {"mac": nic.mac,
11050
                    "ip": nic.ip,
11051
                    "mode": filled_params[constants.NIC_MODE],
11052
                    "link": filled_params[constants.NIC_LINK],
11053
                   }
11054
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
11055
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
11056
        nic_data.append(nic_dict)
11057
      pir = {
11058
        "tags": list(iinfo.GetTags()),
11059
        "admin_up": iinfo.admin_up,
11060
        "vcpus": beinfo[constants.BE_VCPUS],
11061
        "memory": beinfo[constants.BE_MEMORY],
11062
        "os": iinfo.os,
11063
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
11064
        "nics": nic_data,
11065
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
11066
        "disk_template": iinfo.disk_template,
11067
        "hypervisor": iinfo.hypervisor,
11068
        }
11069
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
11070
                                                 pir["disks"])
11071
      instance_data[iinfo.name] = pir
11072

    
11073
    return instance_data
11074

    
11075
  def _AddNewInstance(self):
11076
    """Add new instance data to allocator structure.
11077

11078
    This in combination with _AllocatorGetClusterData will create the
11079
    correct structure needed as input for the allocator.
11080

11081
    The checks for the completeness of the opcode must have already been
11082
    done.
11083

11084
    """
11085
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
11086

    
11087
    if self.disk_template in constants.DTS_NET_MIRROR:
11088
      self.required_nodes = 2
11089
    else:
11090
      self.required_nodes = 1
11091
    request = {
11092
      "name": self.name,
11093
      "disk_template": self.disk_template,
11094
      "tags": self.tags,
11095
      "os": self.os,
11096
      "vcpus": self.vcpus,
11097
      "memory": self.mem_size,
11098
      "disks": self.disks,
11099
      "disk_space_total": disk_space,
11100
      "nics": self.nics,
11101
      "required_nodes": self.required_nodes,
11102
      }
11103
    return request
11104

    
11105
  def _AddRelocateInstance(self):
11106
    """Add relocate instance data to allocator structure.
11107

11108
    This in combination with _IAllocatorGetClusterData will create the
11109
    correct structure needed as input for the allocator.
11110

11111
    The checks for the completeness of the opcode must have already been
11112
    done.
11113

11114
    """
11115
    instance = self.cfg.GetInstanceInfo(self.name)
11116
    if instance is None:
11117
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
11118
                                   " IAllocator" % self.name)
11119

    
11120
    if instance.disk_template not in constants.DTS_NET_MIRROR:
11121
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
11122
                                 errors.ECODE_INVAL)
11123

    
11124
    if len(instance.secondary_nodes) != 1:
11125
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
11126
                                 errors.ECODE_STATE)
11127

    
11128
    self.required_nodes = 1
11129
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
11130
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
11131

    
11132
    request = {
11133
      "name": self.name,
11134
      "disk_space_total": disk_space,
11135
      "required_nodes": self.required_nodes,
11136
      "relocate_from": self.relocate_from,
11137
      }
11138
    return request
11139

    
11140
  def _AddEvacuateNodes(self):
11141
    """Add evacuate nodes data to allocator structure.
11142

11143
    """
11144
    request = {
11145
      "evac_nodes": self.evac_nodes
11146
      }
11147
    return request
11148

    
11149
  def _BuildInputData(self, fn):
11150
    """Build input data structures.
11151

11152
    """
11153
    self._ComputeClusterData()
11154

    
11155
    request = fn()
11156
    request["type"] = self.mode
11157
    self.in_data["request"] = request
11158

    
11159
    self.in_text = serializer.Dump(self.in_data)
11160

    
11161
  def Run(self, name, validate=True, call_fn=None):
11162
    """Run an instance allocator and return the results.
11163

11164
    """
11165
    if call_fn is None:
11166
      call_fn = self.rpc.call_iallocator_runner
11167

    
11168
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
11169
    result.Raise("Failure while running the iallocator script")
11170

    
11171
    self.out_text = result.payload
11172
    if validate:
11173
      self._ValidateResult()
11174

    
11175
  def _ValidateResult(self):
11176
    """Process the allocator results.
11177

11178
    This will process and if successful save the result in
11179
    self.out_data and the other parameters.
11180

11181
    """
11182
    try:
11183
      rdict = serializer.Load(self.out_text)
11184
    except Exception, err:
11185
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
11186

    
11187
    if not isinstance(rdict, dict):
11188
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
11189

    
11190
    # TODO: remove backwards compatiblity in later versions
11191
    if "nodes" in rdict and "result" not in rdict:
11192
      rdict["result"] = rdict["nodes"]
11193
      del rdict["nodes"]
11194

    
11195
    for key in "success", "info", "result":
11196
      if key not in rdict:
11197
        raise errors.OpExecError("Can't parse iallocator results:"
11198
                                 " missing key '%s'" % key)
11199
      setattr(self, key, rdict[key])
11200

    
11201
    if not isinstance(rdict["result"], list):
11202
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
11203
                               " is not a list")
11204
    self.out_data = rdict
11205

    
11206

    
11207
class LUTestAllocator(NoHooksLU):
11208
  """Run allocator tests.
11209

11210
  This LU runs the allocator tests
11211

11212
  """
11213
  def CheckPrereq(self):
11214
    """Check prerequisites.
11215

11216
    This checks the opcode parameters depending on the director and mode test.
11217

11218
    """
11219
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
11220
      for attr in ["mem_size", "disks", "disk_template",
11221
                   "os", "tags", "nics", "vcpus"]:
11222
        if not hasattr(self.op, attr):
11223
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
11224
                                     attr, errors.ECODE_INVAL)
11225
      iname = self.cfg.ExpandInstanceName(self.op.name)
11226
      if iname is not None:
11227
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
11228
                                   iname, errors.ECODE_EXISTS)
11229
      if not isinstance(self.op.nics, list):
11230
        raise errors.OpPrereqError("Invalid parameter 'nics'",
11231
                                   errors.ECODE_INVAL)
11232
      if not isinstance(self.op.disks, list):
11233
        raise errors.OpPrereqError("Invalid parameter 'disks'",
11234
                                   errors.ECODE_INVAL)
11235
      for row in self.op.disks:
11236
        if (not isinstance(row, dict) or
11237
            "size" not in row or
11238
            not isinstance(row["size"], int) or
11239
            "mode" not in row or
11240
            row["mode"] not in ['r', 'w']):
11241
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
11242
                                     " parameter", errors.ECODE_INVAL)
11243
      if self.op.hypervisor is None:
11244
        self.op.hypervisor = self.cfg.GetHypervisorType()
11245
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
11246
      fname = _ExpandInstanceName(self.cfg, self.op.name)
11247
      self.op.name = fname
11248
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
11249
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
11250
      if not hasattr(self.op, "evac_nodes"):
11251
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
11252
                                   " opcode input", errors.ECODE_INVAL)
11253
    else:
11254
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
11255
                                 self.op.mode, errors.ECODE_INVAL)
11256

    
11257
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
11258
      if self.op.allocator is None:
11259
        raise errors.OpPrereqError("Missing allocator name",
11260
                                   errors.ECODE_INVAL)
11261
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
11262
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
11263
                                 self.op.direction, errors.ECODE_INVAL)
11264

    
11265
  def Exec(self, feedback_fn):
11266
    """Run the allocator test.
11267

11268
    """
11269
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
11270
      ial = IAllocator(self.cfg, self.rpc,
11271
                       mode=self.op.mode,
11272
                       name=self.op.name,
11273
                       mem_size=self.op.mem_size,
11274
                       disks=self.op.disks,
11275
                       disk_template=self.op.disk_template,
11276
                       os=self.op.os,
11277
                       tags=self.op.tags,
11278
                       nics=self.op.nics,
11279
                       vcpus=self.op.vcpus,
11280
                       hypervisor=self.op.hypervisor,
11281
                       )
11282
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
11283
      ial = IAllocator(self.cfg, self.rpc,
11284
                       mode=self.op.mode,
11285
                       name=self.op.name,
11286
                       relocate_from=list(self.relocate_from),
11287
                       )
11288
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
11289
      ial = IAllocator(self.cfg, self.rpc,
11290
                       mode=self.op.mode,
11291
                       evac_nodes=self.op.evac_nodes)
11292
    else:
11293
      raise errors.ProgrammerError("Uncatched mode %s in"
11294
                                   " LUTestAllocator.Exec", self.op.mode)
11295

    
11296
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
11297
      result = ial.in_text
11298
    else:
11299
      ial.Run(self.op.allocator, validate=False)
11300
      result = ial.out_text
11301
    return result
11302

    
11303

    
11304
#: Query type implementations
11305
_QUERY_IMPL = {
11306
  constants.QR_INSTANCE: _InstanceQuery,
11307
  constants.QR_NODE: _NodeQuery,
11308
  constants.QR_GROUP: _GroupQuery,
11309
  }
11310

    
11311

    
11312
def _GetQueryImplementation(name):
11313
  """Returns the implemtnation for a query type.
11314

11315
  @param name: Query type, must be one of L{constants.QR_OP_QUERY}
11316

11317
  """
11318
  try:
11319
    return _QUERY_IMPL[name]
11320
  except KeyError:
11321
    raise errors.OpPrereqError("Unknown query resource '%s'" % name,
11322
                               errors.ECODE_INVAL)