Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 72740756

History | View | Annotate | Download (401.7 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 LVM results.
1448

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1797
    nimg.os_fail = test
1798

    
1799
    if test:
1800
      return
1801

    
1802
    os_dict = {}
1803

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

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

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

    
1816
    nimg.oslist = os_dict
1817

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2013
      node_disks[nname] = disks
2014

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

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

    
2022
      node_disks_devonly[nname] = devonly
2023

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

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

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

    
2032
    instdisk = {}
2033

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

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

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

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

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

    
2073
    return instdisk
2074

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

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

    
2089

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

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

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

    
2104
    return env, [], all_nodes
2105

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

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

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

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

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

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

    
2153
    local_checksums = utils.FingerprintFiles(file_names)
2154

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

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

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

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

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

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

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

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

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

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

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

    
2244
      inst_config.MapLVsByNode(node_vol_should)
2245

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

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

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

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

    
2268
    all_drbd_map = self.cfg.ComputeDRBDMap()
2269

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

    
2273
    feedback_fn("* Verifying node status")
2274

    
2275
    refos_img = None
2276

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

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

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

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

    
2305
      nresult = all_nvinfo[node].payload
2306

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

    
2313
      self._VerifyOob(node_i, nresult)
2314

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2430
    return not self.bad
2431

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

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

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

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

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

    
2475
      return lu_result
2476

    
2477

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

2481
  """
2482
  REQ_BGL = False
2483

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

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

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

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

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

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

    
2516
    if not nv_dict:
2517
      return result
2518

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

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

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

    
2543
    return result
2544

    
2545

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

2549
  """
2550
  REQ_BGL = False
2551

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2662

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

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

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

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

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

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

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

    
2703
    self.op.name = new_name
2704

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

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

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

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

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

    
2738
    return clustername
2739

    
2740

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3078

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

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

    
3092

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

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

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

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

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

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

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

    
3141

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

3145
  This is a very simple LU.
3146

3147
  """
3148
  REQ_BGL = False
3149

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

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

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

    
3163

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

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

    
3171
  disks = _ExpandCheckDisks(instance, disks)
3172

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

    
3176
  node = instance.primary_node
3177

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

    
3181
  # TODO: Convert to utils.Retry
3182

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

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

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

    
3229
    if done or oneshot:
3230
      break
3231

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

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

    
3238

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

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

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

    
3249
  result = True
3250

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

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

    
3270
  return result
3271

    
3272

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

3276
  """
3277
  REG_BGL = False
3278

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3379
    return ret
3380

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

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

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

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

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

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

    
3417

    
3418

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3552
    return output
3553

    
3554

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

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

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

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

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

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

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

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

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

    
3596
    instance_list = self.cfg.GetInstanceList()
3597

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

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

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

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

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

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

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

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

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

    
3650

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

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

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

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

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

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

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

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

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

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

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

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

    
3698
      inst_data = lu.cfg.GetAllInstancesInfo()
3699

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

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

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

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

    
3726

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

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

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

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

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

    
3744

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

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

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

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

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

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

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

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

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

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

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

    
3818
        output.append(node_output)
3819

    
3820
    return output
3821

    
3822

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

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

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

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

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

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

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

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

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

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

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

    
3870
    result = []
3871

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

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

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

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

    
3887
        out = []
3888

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

    
3899
          out.append(val)
3900

    
3901
        result.append(out)
3902

    
3903
    return result
3904

    
3905

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4000

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

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

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

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

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

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

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

    
4023

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

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

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

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

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

    
4040

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

4044
  """
4045
  REQ_BGL = False
4046

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

    
4050
    storage_type = self.op.storage_type
4051

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

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

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

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

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

    
4082

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4159
    self.changed_primary_ip = False
4160

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

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

    
4172
        continue
4173

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4349

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

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

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

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

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

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

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

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

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

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

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

4432
    This runs on the master node.
4433

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4540
    self.new_role = new_role
4541

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

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

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

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

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

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

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

    
4597
    result = []
4598

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

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

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

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

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

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

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

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

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

    
4640
    return result
4641

    
4642

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

4646
  """
4647
  REQ_BGL = False
4648

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

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

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

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

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

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

    
4674

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

4678
  """
4679
  REQ_BGL = False
4680

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

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

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

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

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

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

    
4740
    return result
4741

    
4742

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

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

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

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

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

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

    
4781

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

4785
  """
4786
  REQ_BGL = False
4787

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

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

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

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

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

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

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

    
4818
    return disks_info
4819

    
4820

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

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

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

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

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

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

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

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

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

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

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

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

    
4906
  return disks_ok, device_info
4907

    
4908

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

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

    
4923

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

4927
  """
4928
  REQ_BGL = False
4929

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

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

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

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

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

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

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

    
4959

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

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

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

    
4970

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

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

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

    
4988

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

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

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

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

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

    
5014

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

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

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

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

    
5051

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

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

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

5070
  """
5071
  for vg, req_size in req_sizes.items():
5072
    _CheckNodesFreeDiskOnVG(lu, nodenames, vg, req_size)
5073

    
5074

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

5078
  This function check if all given nodes have the needed amount of
5079
  free disk. In case any node has less disk or we cannot get the
5080
  information from the node, this function raise an OpPrereqError
5081
  exception.
5082

5083
  @type lu: C{LogicalUnit}
5084
  @param lu: a logical unit from which we get configuration data
5085
  @type nodenames: C{list}
5086
  @param nodenames: the list of node names to check
5087
  @type vg: C{str}
5088
  @param vg: the volume group to check
5089
  @type requested: C{int}
5090
  @param requested: the amount of disk in MiB to check for
5091
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5092
      or we cannot check the node
5093

5094
  """
5095
  nodeinfo = lu.rpc.call_node_info(nodenames, vg, None)
5096
  for node in nodenames:
5097
    info = nodeinfo[node]
5098
    info.Raise("Cannot get current information from node %s" % node,
5099
               prereq=True, ecode=errors.ECODE_ENVIRON)
5100
    vg_free = info.payload.get("vg_free", None)
5101
    if not isinstance(vg_free, int):
5102
      raise errors.OpPrereqError("Can't compute free disk space on node"
5103
                                 " %s for vg %s, result was '%s'" %
5104
                                 (node, vg, vg_free), errors.ECODE_ENVIRON)
5105
    if requested > vg_free:
5106
      raise errors.OpPrereqError("Not enough disk space on target node %s"
5107
                                 " vg %s: required %d MiB, available %d MiB" %
5108
                                 (node, vg, requested, vg_free),
5109
                                 errors.ECODE_NORES)
5110

    
5111

    
5112
class LUInstanceStartup(LogicalUnit):
5113
  """Starts an instance.
5114

5115
  """
5116
  HPATH = "instance-start"
5117
  HTYPE = constants.HTYPE_INSTANCE
5118
  REQ_BGL = False
5119

    
5120
  def CheckArguments(self):
5121
    # extra beparams
5122
    if self.op.beparams:
5123
      # fill the beparams dict
5124
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5125

    
5126
  def ExpandNames(self):
5127
    self._ExpandAndLockInstance()
5128

    
5129
  def BuildHooksEnv(self):
5130
    """Build hooks env.
5131

5132
    This runs on master, primary and secondary nodes of the instance.
5133

5134
    """
5135
    env = {
5136
      "FORCE": self.op.force,
5137
      }
5138
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5139
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5140
    return env, nl, nl
5141

    
5142
  def CheckPrereq(self):
5143
    """Check prerequisites.
5144

5145
    This checks that the instance is in the cluster.
5146

5147
    """
5148
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5149
    assert self.instance is not None, \
5150
      "Cannot retrieve locked instance %s" % self.op.instance_name
5151

    
5152
    # extra hvparams
5153
    if self.op.hvparams:
5154
      # check hypervisor parameter syntax (locally)
5155
      cluster = self.cfg.GetClusterInfo()
5156
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5157
      filled_hvp = cluster.FillHV(instance)
5158
      filled_hvp.update(self.op.hvparams)
5159
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
5160
      hv_type.CheckParameterSyntax(filled_hvp)
5161
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
5162

    
5163
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
5164

    
5165
    if self.primary_offline and self.op.ignore_offline_nodes:
5166
      self.proc.LogWarning("Ignoring offline primary node")
5167

    
5168
      if self.op.hvparams or self.op.beparams:
5169
        self.proc.LogWarning("Overridden parameters are ignored")
5170
    else:
5171
      _CheckNodeOnline(self, instance.primary_node)
5172

    
5173
      bep = self.cfg.GetClusterInfo().FillBE(instance)
5174

    
5175
      # check bridges existence
5176
      _CheckInstanceBridgesExist(self, instance)
5177

    
5178
      remote_info = self.rpc.call_instance_info(instance.primary_node,
5179
                                                instance.name,
5180
                                                instance.hypervisor)
5181
      remote_info.Raise("Error checking node %s" % instance.primary_node,
5182
                        prereq=True, ecode=errors.ECODE_ENVIRON)
5183
      if not remote_info.payload: # not running already
5184
        _CheckNodeFreeMemory(self, instance.primary_node,
5185
                             "starting instance %s" % instance.name,
5186
                             bep[constants.BE_MEMORY], instance.hypervisor)
5187

    
5188
  def Exec(self, feedback_fn):
5189
    """Start the instance.
5190

5191
    """
5192
    instance = self.instance
5193
    force = self.op.force
5194

    
5195
    self.cfg.MarkInstanceUp(instance.name)
5196

    
5197
    if self.primary_offline:
5198
      assert self.op.ignore_offline_nodes
5199
      self.proc.LogInfo("Primary node offline, marked instance as started")
5200
    else:
5201
      node_current = instance.primary_node
5202

    
5203
      _StartInstanceDisks(self, instance, force)
5204

    
5205
      result = self.rpc.call_instance_start(node_current, instance,
5206
                                            self.op.hvparams, self.op.beparams)
5207
      msg = result.fail_msg
5208
      if msg:
5209
        _ShutdownInstanceDisks(self, instance)
5210
        raise errors.OpExecError("Could not start instance: %s" % msg)
5211

    
5212

    
5213
class LUInstanceReboot(LogicalUnit):
5214
  """Reboot an instance.
5215

5216
  """
5217
  HPATH = "instance-reboot"
5218
  HTYPE = constants.HTYPE_INSTANCE
5219
  REQ_BGL = False
5220

    
5221
  def ExpandNames(self):
5222
    self._ExpandAndLockInstance()
5223

    
5224
  def BuildHooksEnv(self):
5225
    """Build hooks env.
5226

5227
    This runs on master, primary and secondary nodes of the instance.
5228

5229
    """
5230
    env = {
5231
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
5232
      "REBOOT_TYPE": self.op.reboot_type,
5233
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5234
      }
5235
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5236
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5237
    return env, nl, nl
5238

    
5239
  def CheckPrereq(self):
5240
    """Check prerequisites.
5241

5242
    This checks that the instance is in the cluster.
5243

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

    
5249
    _CheckNodeOnline(self, instance.primary_node)
5250

    
5251
    # check bridges existence
5252
    _CheckInstanceBridgesExist(self, instance)
5253

    
5254
  def Exec(self, feedback_fn):
5255
    """Reboot the instance.
5256

5257
    """
5258
    instance = self.instance
5259
    ignore_secondaries = self.op.ignore_secondaries
5260
    reboot_type = self.op.reboot_type
5261

    
5262
    node_current = instance.primary_node
5263

    
5264
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
5265
                       constants.INSTANCE_REBOOT_HARD]:
5266
      for disk in instance.disks:
5267
        self.cfg.SetDiskID(disk, node_current)
5268
      result = self.rpc.call_instance_reboot(node_current, instance,
5269
                                             reboot_type,
5270
                                             self.op.shutdown_timeout)
5271
      result.Raise("Could not reboot instance")
5272
    else:
5273
      result = self.rpc.call_instance_shutdown(node_current, instance,
5274
                                               self.op.shutdown_timeout)
5275
      result.Raise("Could not shutdown instance for full reboot")
5276
      _ShutdownInstanceDisks(self, instance)
5277
      _StartInstanceDisks(self, instance, ignore_secondaries)
5278
      result = self.rpc.call_instance_start(node_current, instance, None, None)
5279
      msg = result.fail_msg
5280
      if msg:
5281
        _ShutdownInstanceDisks(self, instance)
5282
        raise errors.OpExecError("Could not start instance for"
5283
                                 " full reboot: %s" % msg)
5284

    
5285
    self.cfg.MarkInstanceUp(instance.name)
5286

    
5287

    
5288
class LUInstanceShutdown(LogicalUnit):
5289
  """Shutdown an instance.
5290

5291
  """
5292
  HPATH = "instance-stop"
5293
  HTYPE = constants.HTYPE_INSTANCE
5294
  REQ_BGL = False
5295

    
5296
  def ExpandNames(self):
5297
    self._ExpandAndLockInstance()
5298

    
5299
  def BuildHooksEnv(self):
5300
    """Build hooks env.
5301

5302
    This runs on master, primary and secondary nodes of the instance.
5303

5304
    """
5305
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5306
    env["TIMEOUT"] = self.op.timeout
5307
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5308
    return env, nl, nl
5309

    
5310
  def CheckPrereq(self):
5311
    """Check prerequisites.
5312

5313
    This checks that the instance is in the cluster.
5314

5315
    """
5316
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5317
    assert self.instance is not None, \
5318
      "Cannot retrieve locked instance %s" % self.op.instance_name
5319

    
5320
    self.primary_offline = \
5321
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
5322

    
5323
    if self.primary_offline and self.op.ignore_offline_nodes:
5324
      self.proc.LogWarning("Ignoring offline primary node")
5325
    else:
5326
      _CheckNodeOnline(self, self.instance.primary_node)
5327

    
5328
  def Exec(self, feedback_fn):
5329
    """Shutdown the instance.
5330

5331
    """
5332
    instance = self.instance
5333
    node_current = instance.primary_node
5334
    timeout = self.op.timeout
5335

    
5336
    self.cfg.MarkInstanceDown(instance.name)
5337

    
5338
    if self.primary_offline:
5339
      assert self.op.ignore_offline_nodes
5340
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
5341
    else:
5342
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
5343
      msg = result.fail_msg
5344
      if msg:
5345
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
5346

    
5347
      _ShutdownInstanceDisks(self, instance)
5348

    
5349

    
5350
class LUInstanceReinstall(LogicalUnit):
5351
  """Reinstall an instance.
5352

5353
  """
5354
  HPATH = "instance-reinstall"
5355
  HTYPE = constants.HTYPE_INSTANCE
5356
  REQ_BGL = False
5357

    
5358
  def ExpandNames(self):
5359
    self._ExpandAndLockInstance()
5360

    
5361
  def BuildHooksEnv(self):
5362
    """Build hooks env.
5363

5364
    This runs on master, primary and secondary nodes of the instance.
5365

5366
    """
5367
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5368
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5369
    return env, nl, nl
5370

    
5371
  def CheckPrereq(self):
5372
    """Check prerequisites.
5373

5374
    This checks that the instance is in the cluster and is not running.
5375

5376
    """
5377
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5378
    assert instance is not None, \
5379
      "Cannot retrieve locked instance %s" % self.op.instance_name
5380
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
5381
                     " offline, cannot reinstall")
5382
    for node in instance.secondary_nodes:
5383
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
5384
                       " cannot reinstall")
5385

    
5386
    if instance.disk_template == constants.DT_DISKLESS:
5387
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5388
                                 self.op.instance_name,
5389
                                 errors.ECODE_INVAL)
5390
    _CheckInstanceDown(self, instance, "cannot reinstall")
5391

    
5392
    if self.op.os_type is not None:
5393
      # OS verification
5394
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
5395
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
5396
      instance_os = self.op.os_type
5397
    else:
5398
      instance_os = instance.os
5399

    
5400
    nodelist = list(instance.all_nodes)
5401

    
5402
    if self.op.osparams:
5403
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
5404
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
5405
      self.os_inst = i_osdict # the new dict (without defaults)
5406
    else:
5407
      self.os_inst = None
5408

    
5409
    self.instance = instance
5410

    
5411
  def Exec(self, feedback_fn):
5412
    """Reinstall the instance.
5413

5414
    """
5415
    inst = self.instance
5416

    
5417
    if self.op.os_type is not None:
5418
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
5419
      inst.os = self.op.os_type
5420
      # Write to configuration
5421
      self.cfg.Update(inst, feedback_fn)
5422

    
5423
    _StartInstanceDisks(self, inst, None)
5424
    try:
5425
      feedback_fn("Running the instance OS create scripts...")
5426
      # FIXME: pass debug option from opcode to backend
5427
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
5428
                                             self.op.debug_level,
5429
                                             osparams=self.os_inst)
5430
      result.Raise("Could not install OS for instance %s on node %s" %
5431
                   (inst.name, inst.primary_node))
5432
    finally:
5433
      _ShutdownInstanceDisks(self, inst)
5434

    
5435

    
5436
class LUInstanceRecreateDisks(LogicalUnit):
5437
  """Recreate an instance's missing disks.
5438

5439
  """
5440
  HPATH = "instance-recreate-disks"
5441
  HTYPE = constants.HTYPE_INSTANCE
5442
  REQ_BGL = False
5443

    
5444
  def ExpandNames(self):
5445
    self._ExpandAndLockInstance()
5446

    
5447
  def BuildHooksEnv(self):
5448
    """Build hooks env.
5449

5450
    This runs on master, primary and secondary nodes of the instance.
5451

5452
    """
5453
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5454
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5455
    return env, nl, nl
5456

    
5457
  def CheckPrereq(self):
5458
    """Check prerequisites.
5459

5460
    This checks that the instance is in the cluster and is not running.
5461

5462
    """
5463
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5464
    assert instance is not None, \
5465
      "Cannot retrieve locked instance %s" % self.op.instance_name
5466
    _CheckNodeOnline(self, instance.primary_node)
5467

    
5468
    if instance.disk_template == constants.DT_DISKLESS:
5469
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5470
                                 self.op.instance_name, errors.ECODE_INVAL)
5471
    _CheckInstanceDown(self, instance, "cannot recreate disks")
5472

    
5473
    if not self.op.disks:
5474
      self.op.disks = range(len(instance.disks))
5475
    else:
5476
      for idx in self.op.disks:
5477
        if idx >= len(instance.disks):
5478
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
5479
                                     errors.ECODE_INVAL)
5480

    
5481
    self.instance = instance
5482

    
5483
  def Exec(self, feedback_fn):
5484
    """Recreate the disks.
5485

5486
    """
5487
    to_skip = []
5488
    for idx, _ in enumerate(self.instance.disks):
5489
      if idx not in self.op.disks: # disk idx has not been passed in
5490
        to_skip.append(idx)
5491
        continue
5492

    
5493
    _CreateDisks(self, self.instance, to_skip=to_skip)
5494

    
5495

    
5496
class LUInstanceRename(LogicalUnit):
5497
  """Rename an instance.
5498

5499
  """
5500
  HPATH = "instance-rename"
5501
  HTYPE = constants.HTYPE_INSTANCE
5502

    
5503
  def CheckArguments(self):
5504
    """Check arguments.
5505

5506
    """
5507
    if self.op.ip_check and not self.op.name_check:
5508
      # TODO: make the ip check more flexible and not depend on the name check
5509
      raise errors.OpPrereqError("Cannot do ip check without a name check",
5510
                                 errors.ECODE_INVAL)
5511

    
5512
  def BuildHooksEnv(self):
5513
    """Build hooks env.
5514

5515
    This runs on master, primary and secondary nodes of the instance.
5516

5517
    """
5518
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5519
    env["INSTANCE_NEW_NAME"] = self.op.new_name
5520
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5521
    return env, nl, nl
5522

    
5523
  def CheckPrereq(self):
5524
    """Check prerequisites.
5525

5526
    This checks that the instance is in the cluster and is not running.
5527

5528
    """
5529
    self.op.instance_name = _ExpandInstanceName(self.cfg,
5530
                                                self.op.instance_name)
5531
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5532
    assert instance is not None
5533
    _CheckNodeOnline(self, instance.primary_node)
5534
    _CheckInstanceDown(self, instance, "cannot rename")
5535
    self.instance = instance
5536

    
5537
    new_name = self.op.new_name
5538
    if self.op.name_check:
5539
      hostname = netutils.GetHostname(name=new_name)
5540
      self.LogInfo("Resolved given name '%s' to '%s'", new_name,
5541
                   hostname.name)
5542
      new_name = self.op.new_name = hostname.name
5543
      if (self.op.ip_check and
5544
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
5545
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
5546
                                   (hostname.ip, new_name),
5547
                                   errors.ECODE_NOTUNIQUE)
5548

    
5549
    instance_list = self.cfg.GetInstanceList()
5550
    if new_name in instance_list and new_name != instance.name:
5551
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5552
                                 new_name, errors.ECODE_EXISTS)
5553

    
5554
  def Exec(self, feedback_fn):
5555
    """Rename the instance.
5556

5557
    """
5558
    inst = self.instance
5559
    old_name = inst.name
5560

    
5561
    rename_file_storage = False
5562
    if (inst.disk_template == constants.DT_FILE and
5563
        self.op.new_name != inst.name):
5564
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5565
      rename_file_storage = True
5566

    
5567
    self.cfg.RenameInstance(inst.name, self.op.new_name)
5568
    # Change the instance lock. This is definitely safe while we hold the BGL
5569
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
5570
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
5571

    
5572
    # re-read the instance from the configuration after rename
5573
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
5574

    
5575
    if rename_file_storage:
5576
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5577
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
5578
                                                     old_file_storage_dir,
5579
                                                     new_file_storage_dir)
5580
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
5581
                   " (but the instance has been renamed in Ganeti)" %
5582
                   (inst.primary_node, old_file_storage_dir,
5583
                    new_file_storage_dir))
5584

    
5585
    _StartInstanceDisks(self, inst, None)
5586
    try:
5587
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
5588
                                                 old_name, self.op.debug_level)
5589
      msg = result.fail_msg
5590
      if msg:
5591
        msg = ("Could not run OS rename script for instance %s on node %s"
5592
               " (but the instance has been renamed in Ganeti): %s" %
5593
               (inst.name, inst.primary_node, msg))
5594
        self.proc.LogWarning(msg)
5595
    finally:
5596
      _ShutdownInstanceDisks(self, inst)
5597

    
5598
    return inst.name
5599

    
5600

    
5601
class LUInstanceRemove(LogicalUnit):
5602
  """Remove an instance.
5603

5604
  """
5605
  HPATH = "instance-remove"
5606
  HTYPE = constants.HTYPE_INSTANCE
5607
  REQ_BGL = False
5608

    
5609
  def ExpandNames(self):
5610
    self._ExpandAndLockInstance()
5611
    self.needed_locks[locking.LEVEL_NODE] = []
5612
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5613

    
5614
  def DeclareLocks(self, level):
5615
    if level == locking.LEVEL_NODE:
5616
      self._LockInstancesNodes()
5617

    
5618
  def BuildHooksEnv(self):
5619
    """Build hooks env.
5620

5621
    This runs on master, primary and secondary nodes of the instance.
5622

5623
    """
5624
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5625
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
5626
    nl = [self.cfg.GetMasterNode()]
5627
    nl_post = list(self.instance.all_nodes) + nl
5628
    return env, nl, nl_post
5629

    
5630
  def CheckPrereq(self):
5631
    """Check prerequisites.
5632

5633
    This checks that the instance is in the cluster.
5634

5635
    """
5636
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5637
    assert self.instance is not None, \
5638
      "Cannot retrieve locked instance %s" % self.op.instance_name
5639

    
5640
  def Exec(self, feedback_fn):
5641
    """Remove the instance.
5642

5643
    """
5644
    instance = self.instance
5645
    logging.info("Shutting down instance %s on node %s",
5646
                 instance.name, instance.primary_node)
5647

    
5648
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5649
                                             self.op.shutdown_timeout)
5650
    msg = result.fail_msg
5651
    if msg:
5652
      if self.op.ignore_failures:
5653
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5654
      else:
5655
        raise errors.OpExecError("Could not shutdown instance %s on"
5656
                                 " node %s: %s" %
5657
                                 (instance.name, instance.primary_node, msg))
5658

    
5659
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5660

    
5661

    
5662
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5663
  """Utility function to remove an instance.
5664

5665
  """
5666
  logging.info("Removing block devices for instance %s", instance.name)
5667

    
5668
  if not _RemoveDisks(lu, instance):
5669
    if not ignore_failures:
5670
      raise errors.OpExecError("Can't remove instance's disks")
5671
    feedback_fn("Warning: can't remove instance's disks")
5672

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

    
5675
  lu.cfg.RemoveInstance(instance.name)
5676

    
5677
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5678
    "Instance lock removal conflict"
5679

    
5680
  # Remove lock for the instance
5681
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5682

    
5683

    
5684
class LUInstanceQuery(NoHooksLU):
5685
  """Logical unit for querying instances.
5686

5687
  """
5688
  # pylint: disable-msg=W0142
5689
  REQ_BGL = False
5690

    
5691
  def CheckArguments(self):
5692
    self.iq = _InstanceQuery(self.op.names, self.op.output_fields,
5693
                             self.op.use_locking)
5694

    
5695
  def ExpandNames(self):
5696
    self.iq.ExpandNames(self)
5697

    
5698
  def DeclareLocks(self, level):
5699
    self.iq.DeclareLocks(self, level)
5700

    
5701
  def Exec(self, feedback_fn):
5702
    return self.iq.OldStyleQuery(self)
5703

    
5704

    
5705
class LUInstanceFailover(LogicalUnit):
5706
  """Failover an instance.
5707

5708
  """
5709
  HPATH = "instance-failover"
5710
  HTYPE = constants.HTYPE_INSTANCE
5711
  REQ_BGL = False
5712

    
5713
  def ExpandNames(self):
5714
    self._ExpandAndLockInstance()
5715
    self.needed_locks[locking.LEVEL_NODE] = []
5716
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5717

    
5718
  def DeclareLocks(self, level):
5719
    if level == locking.LEVEL_NODE:
5720
      self._LockInstancesNodes()
5721

    
5722
  def BuildHooksEnv(self):
5723
    """Build hooks env.
5724

5725
    This runs on master, primary and secondary nodes of the instance.
5726

5727
    """
5728
    instance = self.instance
5729
    source_node = instance.primary_node
5730
    target_node = instance.secondary_nodes[0]
5731
    env = {
5732
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5733
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5734
      "OLD_PRIMARY": source_node,
5735
      "OLD_SECONDARY": target_node,
5736
      "NEW_PRIMARY": target_node,
5737
      "NEW_SECONDARY": source_node,
5738
      }
5739
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5740
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5741
    nl_post = list(nl)
5742
    nl_post.append(source_node)
5743
    return env, nl, nl_post
5744

    
5745
  def CheckPrereq(self):
5746
    """Check prerequisites.
5747

5748
    This checks that the instance is in the cluster.
5749

5750
    """
5751
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5752
    assert self.instance is not None, \
5753
      "Cannot retrieve locked instance %s" % self.op.instance_name
5754

    
5755
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5756
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5757
      raise errors.OpPrereqError("Instance's disk layout is not"
5758
                                 " network mirrored, cannot failover.",
5759
                                 errors.ECODE_STATE)
5760

    
5761
    secondary_nodes = instance.secondary_nodes
5762
    if not secondary_nodes:
5763
      raise errors.ProgrammerError("no secondary node but using "
5764
                                   "a mirrored disk template")
5765

    
5766
    target_node = secondary_nodes[0]
5767
    _CheckNodeOnline(self, target_node)
5768
    _CheckNodeNotDrained(self, target_node)
5769
    if instance.admin_up:
5770
      # check memory requirements on the secondary node
5771
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5772
                           instance.name, bep[constants.BE_MEMORY],
5773
                           instance.hypervisor)
5774
    else:
5775
      self.LogInfo("Not checking memory on the secondary node as"
5776
                   " instance will not be started")
5777

    
5778
    # check bridge existance
5779
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5780

    
5781
  def Exec(self, feedback_fn):
5782
    """Failover an instance.
5783

5784
    The failover is done by shutting it down on its present node and
5785
    starting it on the secondary.
5786

5787
    """
5788
    instance = self.instance
5789
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
5790

    
5791
    source_node = instance.primary_node
5792
    target_node = instance.secondary_nodes[0]
5793

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

    
5805
    feedback_fn("* shutting down instance on source node")
5806
    logging.info("Shutting down instance %s on node %s",
5807
                 instance.name, source_node)
5808

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

    
5823
    feedback_fn("* deactivating the instance's disks on source node")
5824
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5825
      raise errors.OpExecError("Can't shut down the instance's disks.")
5826

    
5827
    instance.primary_node = target_node
5828
    # distribute new instance config to the other nodes
5829
    self.cfg.Update(instance, feedback_fn)
5830

    
5831
    # Only start the instance if it's marked as up
5832
    if instance.admin_up:
5833
      feedback_fn("* activating the instance's disks on target node")
5834
      logging.info("Starting instance %s on node %s",
5835
                   instance.name, target_node)
5836

    
5837
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5838
                                           ignore_secondaries=True)
5839
      if not disks_ok:
5840
        _ShutdownInstanceDisks(self, instance)
5841
        raise errors.OpExecError("Can't activate the instance's disks")
5842

    
5843
      feedback_fn("* starting the instance on the target node")
5844
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5845
      msg = result.fail_msg
5846
      if msg:
5847
        _ShutdownInstanceDisks(self, instance)
5848
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5849
                                 (instance.name, target_node, msg))
5850

    
5851

    
5852
class LUInstanceMigrate(LogicalUnit):
5853
  """Migrate an instance.
5854

5855
  This is migration without shutting down, compared to the failover,
5856
  which is done with shutdown.
5857

5858
  """
5859
  HPATH = "instance-migrate"
5860
  HTYPE = constants.HTYPE_INSTANCE
5861
  REQ_BGL = False
5862

    
5863
  def ExpandNames(self):
5864
    self._ExpandAndLockInstance()
5865

    
5866
    self.needed_locks[locking.LEVEL_NODE] = []
5867
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5868

    
5869
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5870
                                       self.op.cleanup)
5871
    self.tasklets = [self._migrater]
5872

    
5873
  def DeclareLocks(self, level):
5874
    if level == locking.LEVEL_NODE:
5875
      self._LockInstancesNodes()
5876

    
5877
  def BuildHooksEnv(self):
5878
    """Build hooks env.
5879

5880
    This runs on master, primary and secondary nodes of the instance.
5881

5882
    """
5883
    instance = self._migrater.instance
5884
    source_node = instance.primary_node
5885
    target_node = instance.secondary_nodes[0]
5886
    env = _BuildInstanceHookEnvByObject(self, instance)
5887
    env["MIGRATE_LIVE"] = self._migrater.live
5888
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5889
    env.update({
5890
        "OLD_PRIMARY": source_node,
5891
        "OLD_SECONDARY": target_node,
5892
        "NEW_PRIMARY": target_node,
5893
        "NEW_SECONDARY": source_node,
5894
        })
5895
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5896
    nl_post = list(nl)
5897
    nl_post.append(source_node)
5898
    return env, nl, nl_post
5899

    
5900

    
5901
class LUInstanceMove(LogicalUnit):
5902
  """Move an instance by data-copying.
5903

5904
  """
5905
  HPATH = "instance-move"
5906
  HTYPE = constants.HTYPE_INSTANCE
5907
  REQ_BGL = False
5908

    
5909
  def ExpandNames(self):
5910
    self._ExpandAndLockInstance()
5911
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5912
    self.op.target_node = target_node
5913
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5914
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5915

    
5916
  def DeclareLocks(self, level):
5917
    if level == locking.LEVEL_NODE:
5918
      self._LockInstancesNodes(primary_only=True)
5919

    
5920
  def BuildHooksEnv(self):
5921
    """Build hooks env.
5922

5923
    This runs on master, primary and secondary nodes of the instance.
5924

5925
    """
5926
    env = {
5927
      "TARGET_NODE": self.op.target_node,
5928
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5929
      }
5930
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5931
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5932
                                       self.op.target_node]
5933
    return env, nl, nl
5934

    
5935
  def CheckPrereq(self):
5936
    """Check prerequisites.
5937

5938
    This checks that the instance is in the cluster.
5939

5940
    """
5941
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5942
    assert self.instance is not None, \
5943
      "Cannot retrieve locked instance %s" % self.op.instance_name
5944

    
5945
    node = self.cfg.GetNodeInfo(self.op.target_node)
5946
    assert node is not None, \
5947
      "Cannot retrieve locked node %s" % self.op.target_node
5948

    
5949
    self.target_node = target_node = node.name
5950

    
5951
    if target_node == instance.primary_node:
5952
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5953
                                 (instance.name, target_node),
5954
                                 errors.ECODE_STATE)
5955

    
5956
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5957

    
5958
    for idx, dsk in enumerate(instance.disks):
5959
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5960
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5961
                                   " cannot copy" % idx, errors.ECODE_STATE)
5962

    
5963
    _CheckNodeOnline(self, target_node)
5964
    _CheckNodeNotDrained(self, target_node)
5965
    _CheckNodeVmCapable(self, target_node)
5966

    
5967
    if instance.admin_up:
5968
      # check memory requirements on the secondary node
5969
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5970
                           instance.name, bep[constants.BE_MEMORY],
5971
                           instance.hypervisor)
5972
    else:
5973
      self.LogInfo("Not checking memory on the secondary node as"
5974
                   " instance will not be started")
5975

    
5976
    # check bridge existance
5977
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5978

    
5979
  def Exec(self, feedback_fn):
5980
    """Move an instance.
5981

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

5985
    """
5986
    instance = self.instance
5987

    
5988
    source_node = instance.primary_node
5989
    target_node = self.target_node
5990

    
5991
    self.LogInfo("Shutting down instance %s on source node %s",
5992
                 instance.name, source_node)
5993

    
5994
    result = self.rpc.call_instance_shutdown(source_node, instance,
5995
                                             self.op.shutdown_timeout)
5996
    msg = result.fail_msg
5997
    if msg:
5998
      if self.op.ignore_consistency:
5999
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
6000
                             " Proceeding anyway. Please make sure node"
6001
                             " %s is down. Error details: %s",
6002
                             instance.name, source_node, source_node, msg)
6003
      else:
6004
        raise errors.OpExecError("Could not shutdown instance %s on"
6005
                                 " node %s: %s" %
6006
                                 (instance.name, source_node, msg))
6007

    
6008
    # create the target disks
6009
    try:
6010
      _CreateDisks(self, instance, target_node=target_node)
6011
    except errors.OpExecError:
6012
      self.LogWarning("Device creation failed, reverting...")
6013
      try:
6014
        _RemoveDisks(self, instance, target_node=target_node)
6015
      finally:
6016
        self.cfg.ReleaseDRBDMinors(instance.name)
6017
        raise
6018

    
6019
    cluster_name = self.cfg.GetClusterInfo().cluster_name
6020

    
6021
    errs = []
6022
    # activate, get path, copy the data over
6023
    for idx, disk in enumerate(instance.disks):
6024
      self.LogInfo("Copying data for disk %d", idx)
6025
      result = self.rpc.call_blockdev_assemble(target_node, disk,
6026
                                               instance.name, True, idx)
6027
      if result.fail_msg:
6028
        self.LogWarning("Can't assemble newly created disk %d: %s",
6029
                        idx, result.fail_msg)
6030
        errs.append(result.fail_msg)
6031
        break
6032
      dev_path = result.payload
6033
      result = self.rpc.call_blockdev_export(source_node, disk,
6034
                                             target_node, dev_path,
6035
                                             cluster_name)
6036
      if result.fail_msg:
6037
        self.LogWarning("Can't copy data over for disk %d: %s",
6038
                        idx, result.fail_msg)
6039
        errs.append(result.fail_msg)
6040
        break
6041

    
6042
    if errs:
6043
      self.LogWarning("Some disks failed to copy, aborting")
6044
      try:
6045
        _RemoveDisks(self, instance, target_node=target_node)
6046
      finally:
6047
        self.cfg.ReleaseDRBDMinors(instance.name)
6048
        raise errors.OpExecError("Errors during disk copy: %s" %
6049
                                 (",".join(errs),))
6050

    
6051
    instance.primary_node = target_node
6052
    self.cfg.Update(instance, feedback_fn)
6053

    
6054
    self.LogInfo("Removing the disks on the original node")
6055
    _RemoveDisks(self, instance, target_node=source_node)
6056

    
6057
    # Only start the instance if it's marked as up
6058
    if instance.admin_up:
6059
      self.LogInfo("Starting instance %s on node %s",
6060
                   instance.name, target_node)
6061

    
6062
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
6063
                                           ignore_secondaries=True)
6064
      if not disks_ok:
6065
        _ShutdownInstanceDisks(self, instance)
6066
        raise errors.OpExecError("Can't activate the instance's disks")
6067

    
6068
      result = self.rpc.call_instance_start(target_node, instance, None, None)
6069
      msg = result.fail_msg
6070
      if msg:
6071
        _ShutdownInstanceDisks(self, instance)
6072
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
6073
                                 (instance.name, target_node, msg))
6074

    
6075

    
6076
class LUNodeMigrate(LogicalUnit):
6077
  """Migrate all instances from a node.
6078

6079
  """
6080
  HPATH = "node-migrate"
6081
  HTYPE = constants.HTYPE_NODE
6082
  REQ_BGL = False
6083

    
6084
  def ExpandNames(self):
6085
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6086

    
6087
    self.needed_locks = {
6088
      locking.LEVEL_NODE: [self.op.node_name],
6089
      }
6090

    
6091
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6092

    
6093
    # Create tasklets for migrating instances for all instances on this node
6094
    names = []
6095
    tasklets = []
6096

    
6097
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
6098
      logging.debug("Migrating instance %s", inst.name)
6099
      names.append(inst.name)
6100

    
6101
      tasklets.append(TLMigrateInstance(self, inst.name, False))
6102

    
6103
    self.tasklets = tasklets
6104

    
6105
    # Declare instance locks
6106
    self.needed_locks[locking.LEVEL_INSTANCE] = names
6107

    
6108
  def DeclareLocks(self, level):
6109
    if level == locking.LEVEL_NODE:
6110
      self._LockInstancesNodes()
6111

    
6112
  def BuildHooksEnv(self):
6113
    """Build hooks env.
6114

6115
    This runs on the master, the primary and all the secondaries.
6116

6117
    """
6118
    env = {
6119
      "NODE_NAME": self.op.node_name,
6120
      }
6121

    
6122
    nl = [self.cfg.GetMasterNode()]
6123

    
6124
    return (env, nl, nl)
6125

    
6126

    
6127
class TLMigrateInstance(Tasklet):
6128
  """Tasklet class for instance migration.
6129

6130
  @type live: boolean
6131
  @ivar live: whether the migration will be done live or non-live;
6132
      this variable is initalized only after CheckPrereq has run
6133

6134
  """
6135
  def __init__(self, lu, instance_name, cleanup):
6136
    """Initializes this class.
6137

6138
    """
6139
    Tasklet.__init__(self, lu)
6140

    
6141
    # Parameters
6142
    self.instance_name = instance_name
6143
    self.cleanup = cleanup
6144
    self.live = False # will be overridden later
6145

    
6146
  def CheckPrereq(self):
6147
    """Check prerequisites.
6148

6149
    This checks that the instance is in the cluster.
6150

6151
    """
6152
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
6153
    instance = self.cfg.GetInstanceInfo(instance_name)
6154
    assert instance is not None
6155

    
6156
    if instance.disk_template != constants.DT_DRBD8:
6157
      raise errors.OpPrereqError("Instance's disk layout is not"
6158
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
6159

    
6160
    secondary_nodes = instance.secondary_nodes
6161
    if not secondary_nodes:
6162
      raise errors.ConfigurationError("No secondary node but using"
6163
                                      " drbd8 disk template")
6164

    
6165
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
6166

    
6167
    target_node = secondary_nodes[0]
6168
    # check memory requirements on the secondary node
6169
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
6170
                         instance.name, i_be[constants.BE_MEMORY],
6171
                         instance.hypervisor)
6172

    
6173
    # check bridge existance
6174
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
6175

    
6176
    if not self.cleanup:
6177
      _CheckNodeNotDrained(self.lu, target_node)
6178
      result = self.rpc.call_instance_migratable(instance.primary_node,
6179
                                                 instance)
6180
      result.Raise("Can't migrate, please use failover",
6181
                   prereq=True, ecode=errors.ECODE_STATE)
6182

    
6183
    self.instance = instance
6184

    
6185
    if self.lu.op.live is not None and self.lu.op.mode is not None:
6186
      raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
6187
                                 " parameters are accepted",
6188
                                 errors.ECODE_INVAL)
6189
    if self.lu.op.live is not None:
6190
      if self.lu.op.live:
6191
        self.lu.op.mode = constants.HT_MIGRATION_LIVE
6192
      else:
6193
        self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6194
      # reset the 'live' parameter to None so that repeated
6195
      # invocations of CheckPrereq do not raise an exception
6196
      self.lu.op.live = None
6197
    elif self.lu.op.mode is None:
6198
      # read the default value from the hypervisor
6199
      i_hv = self.cfg.GetClusterInfo().FillHV(instance, skip_globals=False)
6200
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6201

    
6202
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6203

    
6204
  def _WaitUntilSync(self):
6205
    """Poll with custom rpc for disk sync.
6206

6207
    This uses our own step-based rpc call.
6208

6209
    """
6210
    self.feedback_fn("* wait until resync is done")
6211
    all_done = False
6212
    while not all_done:
6213
      all_done = True
6214
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6215
                                            self.nodes_ip,
6216
                                            self.instance.disks)
6217
      min_percent = 100
6218
      for node, nres in result.items():
6219
        nres.Raise("Cannot resync disks on node %s" % node)
6220
        node_done, node_percent = nres.payload
6221
        all_done = all_done and node_done
6222
        if node_percent is not None:
6223
          min_percent = min(min_percent, node_percent)
6224
      if not all_done:
6225
        if min_percent < 100:
6226
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6227
        time.sleep(2)
6228

    
6229
  def _EnsureSecondary(self, node):
6230
    """Demote a node to secondary.
6231

6232
    """
6233
    self.feedback_fn("* switching node %s to secondary mode" % node)
6234

    
6235
    for dev in self.instance.disks:
6236
      self.cfg.SetDiskID(dev, node)
6237

    
6238
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6239
                                          self.instance.disks)
6240
    result.Raise("Cannot change disk to secondary on node %s" % node)
6241

    
6242
  def _GoStandalone(self):
6243
    """Disconnect from the network.
6244

6245
    """
6246
    self.feedback_fn("* changing into standalone mode")
6247
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6248
                                               self.instance.disks)
6249
    for node, nres in result.items():
6250
      nres.Raise("Cannot disconnect disks node %s" % node)
6251

    
6252
  def _GoReconnect(self, multimaster):
6253
    """Reconnect to the network.
6254

6255
    """
6256
    if multimaster:
6257
      msg = "dual-master"
6258
    else:
6259
      msg = "single-master"
6260
    self.feedback_fn("* changing disks into %s mode" % msg)
6261
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6262
                                           self.instance.disks,
6263
                                           self.instance.name, multimaster)
6264
    for node, nres in result.items():
6265
      nres.Raise("Cannot change disks config on node %s" % node)
6266

    
6267
  def _ExecCleanup(self):
6268
    """Try to cleanup after a failed migration.
6269

6270
    The cleanup is done by:
6271
      - check that the instance is running only on one node
6272
        (and update the config if needed)
6273
      - change disks on its secondary node to secondary
6274
      - wait until disks are fully synchronized
6275
      - disconnect from the network
6276
      - change disks into single-master mode
6277
      - wait again until disks are fully synchronized
6278

6279
    """
6280
    instance = self.instance
6281
    target_node = self.target_node
6282
    source_node = self.source_node
6283

    
6284
    # check running on only one node
6285
    self.feedback_fn("* checking where the instance actually runs"
6286
                     " (if this hangs, the hypervisor might be in"
6287
                     " a bad state)")
6288
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
6289
    for node, result in ins_l.items():
6290
      result.Raise("Can't contact node %s" % node)
6291

    
6292
    runningon_source = instance.name in ins_l[source_node].payload
6293
    runningon_target = instance.name in ins_l[target_node].payload
6294

    
6295
    if runningon_source and runningon_target:
6296
      raise errors.OpExecError("Instance seems to be running on two nodes,"
6297
                               " or the hypervisor is confused. You will have"
6298
                               " to ensure manually that it runs only on one"
6299
                               " and restart this operation.")
6300

    
6301
    if not (runningon_source or runningon_target):
6302
      raise errors.OpExecError("Instance does not seem to be running at all."
6303
                               " In this case, it's safer to repair by"
6304
                               " running 'gnt-instance stop' to ensure disk"
6305
                               " shutdown, and then restarting it.")
6306

    
6307
    if runningon_target:
6308
      # the migration has actually succeeded, we need to update the config
6309
      self.feedback_fn("* instance running on secondary node (%s),"
6310
                       " updating config" % target_node)
6311
      instance.primary_node = target_node
6312
      self.cfg.Update(instance, self.feedback_fn)
6313
      demoted_node = source_node
6314
    else:
6315
      self.feedback_fn("* instance confirmed to be running on its"
6316
                       " primary node (%s)" % source_node)
6317
      demoted_node = target_node
6318

    
6319
    self._EnsureSecondary(demoted_node)
6320
    try:
6321
      self._WaitUntilSync()
6322
    except errors.OpExecError:
6323
      # we ignore here errors, since if the device is standalone, it
6324
      # won't be able to sync
6325
      pass
6326
    self._GoStandalone()
6327
    self._GoReconnect(False)
6328
    self._WaitUntilSync()
6329

    
6330
    self.feedback_fn("* done")
6331

    
6332
  def _RevertDiskStatus(self):
6333
    """Try to revert the disk status after a failed migration.
6334

6335
    """
6336
    target_node = self.target_node
6337
    try:
6338
      self._EnsureSecondary(target_node)
6339
      self._GoStandalone()
6340
      self._GoReconnect(False)
6341
      self._WaitUntilSync()
6342
    except errors.OpExecError, err:
6343
      self.lu.LogWarning("Migration failed and I can't reconnect the"
6344
                         " drives: error '%s'\n"
6345
                         "Please look and recover the instance status" %
6346
                         str(err))
6347

    
6348
  def _AbortMigration(self):
6349
    """Call the hypervisor code to abort a started migration.
6350

6351
    """
6352
    instance = self.instance
6353
    target_node = self.target_node
6354
    migration_info = self.migration_info
6355

    
6356
    abort_result = self.rpc.call_finalize_migration(target_node,
6357
                                                    instance,
6358
                                                    migration_info,
6359
                                                    False)
6360
    abort_msg = abort_result.fail_msg
6361
    if abort_msg:
6362
      logging.error("Aborting migration failed on target node %s: %s",
6363
                    target_node, abort_msg)
6364
      # Don't raise an exception here, as we stil have to try to revert the
6365
      # disk status, even if this step failed.
6366

    
6367
  def _ExecMigration(self):
6368
    """Migrate an instance.
6369

6370
    The migrate is done by:
6371
      - change the disks into dual-master mode
6372
      - wait until disks are fully synchronized again
6373
      - migrate the instance
6374
      - change disks on the new secondary node (the old primary) to secondary
6375
      - wait until disks are fully synchronized
6376
      - change disks into single-master mode
6377

6378
    """
6379
    instance = self.instance
6380
    target_node = self.target_node
6381
    source_node = self.source_node
6382

    
6383
    self.feedback_fn("* checking disk consistency between source and target")
6384
    for dev in instance.disks:
6385
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6386
        raise errors.OpExecError("Disk %s is degraded or not fully"
6387
                                 " synchronized on target node,"
6388
                                 " aborting migrate." % dev.iv_name)
6389

    
6390
    # First get the migration information from the remote node
6391
    result = self.rpc.call_migration_info(source_node, instance)
6392
    msg = result.fail_msg
6393
    if msg:
6394
      log_err = ("Failed fetching source migration information from %s: %s" %
6395
                 (source_node, msg))
6396
      logging.error(log_err)
6397
      raise errors.OpExecError(log_err)
6398

    
6399
    self.migration_info = migration_info = result.payload
6400

    
6401
    # Then switch the disks to master/master mode
6402
    self._EnsureSecondary(target_node)
6403
    self._GoStandalone()
6404
    self._GoReconnect(True)
6405
    self._WaitUntilSync()
6406

    
6407
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6408
    result = self.rpc.call_accept_instance(target_node,
6409
                                           instance,
6410
                                           migration_info,
6411
                                           self.nodes_ip[target_node])
6412

    
6413
    msg = result.fail_msg
6414
    if msg:
6415
      logging.error("Instance pre-migration failed, trying to revert"
6416
                    " disk status: %s", msg)
6417
      self.feedback_fn("Pre-migration failed, aborting")
6418
      self._AbortMigration()
6419
      self._RevertDiskStatus()
6420
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6421
                               (instance.name, msg))
6422

    
6423
    self.feedback_fn("* migrating instance to %s" % target_node)
6424
    time.sleep(10)
6425
    result = self.rpc.call_instance_migrate(source_node, instance,
6426
                                            self.nodes_ip[target_node],
6427
                                            self.live)
6428
    msg = result.fail_msg
6429
    if msg:
6430
      logging.error("Instance migration failed, trying to revert"
6431
                    " disk status: %s", msg)
6432
      self.feedback_fn("Migration failed, aborting")
6433
      self._AbortMigration()
6434
      self._RevertDiskStatus()
6435
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6436
                               (instance.name, msg))
6437
    time.sleep(10)
6438

    
6439
    instance.primary_node = target_node
6440
    # distribute new instance config to the other nodes
6441
    self.cfg.Update(instance, self.feedback_fn)
6442

    
6443
    result = self.rpc.call_finalize_migration(target_node,
6444
                                              instance,
6445
                                              migration_info,
6446
                                              True)
6447
    msg = result.fail_msg
6448
    if msg:
6449
      logging.error("Instance migration succeeded, but finalization failed:"
6450
                    " %s", msg)
6451
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6452
                               msg)
6453

    
6454
    self._EnsureSecondary(source_node)
6455
    self._WaitUntilSync()
6456
    self._GoStandalone()
6457
    self._GoReconnect(False)
6458
    self._WaitUntilSync()
6459

    
6460
    self.feedback_fn("* done")
6461

    
6462
  def Exec(self, feedback_fn):
6463
    """Perform the migration.
6464

6465
    """
6466
    feedback_fn("Migrating instance %s" % self.instance.name)
6467

    
6468
    self.feedback_fn = feedback_fn
6469

    
6470
    self.source_node = self.instance.primary_node
6471
    self.target_node = self.instance.secondary_nodes[0]
6472
    self.all_nodes = [self.source_node, self.target_node]
6473
    self.nodes_ip = {
6474
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6475
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6476
      }
6477

    
6478
    if self.cleanup:
6479
      return self._ExecCleanup()
6480
    else:
6481
      return self._ExecMigration()
6482

    
6483

    
6484
def _CreateBlockDev(lu, node, instance, device, force_create,
6485
                    info, force_open):
6486
  """Create a tree of block devices on a given node.
6487

6488
  If this device type has to be created on secondaries, create it and
6489
  all its children.
6490

6491
  If not, just recurse to children keeping the same 'force' value.
6492

6493
  @param lu: the lu on whose behalf we execute
6494
  @param node: the node on which to create the device
6495
  @type instance: L{objects.Instance}
6496
  @param instance: the instance which owns the device
6497
  @type device: L{objects.Disk}
6498
  @param device: the device to create
6499
  @type force_create: boolean
6500
  @param force_create: whether to force creation of this device; this
6501
      will be change to True whenever we find a device which has
6502
      CreateOnSecondary() attribute
6503
  @param info: the extra 'metadata' we should attach to the device
6504
      (this will be represented as a LVM tag)
6505
  @type force_open: boolean
6506
  @param force_open: this parameter will be passes to the
6507
      L{backend.BlockdevCreate} function where it specifies
6508
      whether we run on primary or not, and it affects both
6509
      the child assembly and the device own Open() execution
6510

6511
  """
6512
  if device.CreateOnSecondary():
6513
    force_create = True
6514

    
6515
  if device.children:
6516
    for child in device.children:
6517
      _CreateBlockDev(lu, node, instance, child, force_create,
6518
                      info, force_open)
6519

    
6520
  if not force_create:
6521
    return
6522

    
6523
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6524

    
6525

    
6526
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6527
  """Create a single block device on a given node.
6528

6529
  This will not recurse over children of the device, so they must be
6530
  created in advance.
6531

6532
  @param lu: the lu on whose behalf we execute
6533
  @param node: the node on which to create the device
6534
  @type instance: L{objects.Instance}
6535
  @param instance: the instance which owns the device
6536
  @type device: L{objects.Disk}
6537
  @param device: the device to create
6538
  @param info: the extra 'metadata' we should attach to the device
6539
      (this will be represented as a LVM tag)
6540
  @type force_open: boolean
6541
  @param force_open: this parameter will be passes to the
6542
      L{backend.BlockdevCreate} function where it specifies
6543
      whether we run on primary or not, and it affects both
6544
      the child assembly and the device own Open() execution
6545

6546
  """
6547
  lu.cfg.SetDiskID(device, node)
6548
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6549
                                       instance.name, force_open, info)
6550
  result.Raise("Can't create block device %s on"
6551
               " node %s for instance %s" % (device, node, instance.name))
6552
  if device.physical_id is None:
6553
    device.physical_id = result.payload
6554

    
6555

    
6556
def _GenerateUniqueNames(lu, exts):
6557
  """Generate a suitable LV name.
6558

6559
  This will generate a logical volume name for the given instance.
6560

6561
  """
6562
  results = []
6563
  for val in exts:
6564
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6565
    results.append("%s%s" % (new_id, val))
6566
  return results
6567

    
6568

    
6569
def _GenerateDRBD8Branch(lu, primary, secondary, size, vgnames, names,
6570
                         iv_name, p_minor, s_minor):
6571
  """Generate a drbd8 device complete with its children.
6572

6573
  """
6574
  assert len(vgnames) == len(names) == 2
6575
  port = lu.cfg.AllocatePort()
6576
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6577
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6578
                          logical_id=(vgnames[0], names[0]))
6579
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6580
                          logical_id=(vgnames[1], names[1]))
6581
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6582
                          logical_id=(primary, secondary, port,
6583
                                      p_minor, s_minor,
6584
                                      shared_secret),
6585
                          children=[dev_data, dev_meta],
6586
                          iv_name=iv_name)
6587
  return drbd_dev
6588

    
6589

    
6590
def _GenerateDiskTemplate(lu, template_name,
6591
                          instance_name, primary_node,
6592
                          secondary_nodes, disk_info,
6593
                          file_storage_dir, file_driver,
6594
                          base_index, feedback_fn):
6595
  """Generate the entire disk layout for a given template type.
6596

6597
  """
6598
  #TODO: compute space requirements
6599

    
6600
  vgname = lu.cfg.GetVGName()
6601
  disk_count = len(disk_info)
6602
  disks = []
6603
  if template_name == constants.DT_DISKLESS:
6604
    pass
6605
  elif template_name == constants.DT_PLAIN:
6606
    if len(secondary_nodes) != 0:
6607
      raise errors.ProgrammerError("Wrong template configuration")
6608

    
6609
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6610
                                      for i in range(disk_count)])
6611
    for idx, disk in enumerate(disk_info):
6612
      disk_index = idx + base_index
6613
      vg = disk.get("vg", vgname)
6614
      feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
6615
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6616
                              logical_id=(vg, names[idx]),
6617
                              iv_name="disk/%d" % disk_index,
6618
                              mode=disk["mode"])
6619
      disks.append(disk_dev)
6620
  elif template_name == constants.DT_DRBD8:
6621
    if len(secondary_nodes) != 1:
6622
      raise errors.ProgrammerError("Wrong template configuration")
6623
    remote_node = secondary_nodes[0]
6624
    minors = lu.cfg.AllocateDRBDMinor(
6625
      [primary_node, remote_node] * len(disk_info), instance_name)
6626

    
6627
    names = []
6628
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6629
                                               for i in range(disk_count)]):
6630
      names.append(lv_prefix + "_data")
6631
      names.append(lv_prefix + "_meta")
6632
    for idx, disk in enumerate(disk_info):
6633
      disk_index = idx + base_index
6634
      data_vg = disk.get("vg", vgname)
6635
      meta_vg = disk.get("metavg", data_vg)
6636
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6637
                                      disk["size"], [data_vg, meta_vg],
6638
                                      names[idx*2:idx*2+2],
6639
                                      "disk/%d" % disk_index,
6640
                                      minors[idx*2], minors[idx*2+1])
6641
      disk_dev.mode = disk["mode"]
6642
      disks.append(disk_dev)
6643
  elif template_name == constants.DT_FILE:
6644
    if len(secondary_nodes) != 0:
6645
      raise errors.ProgrammerError("Wrong template configuration")
6646

    
6647
    opcodes.RequireFileStorage()
6648

    
6649
    for idx, disk in enumerate(disk_info):
6650
      disk_index = idx + base_index
6651
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6652
                              iv_name="disk/%d" % disk_index,
6653
                              logical_id=(file_driver,
6654
                                          "%s/disk%d" % (file_storage_dir,
6655
                                                         disk_index)),
6656
                              mode=disk["mode"])
6657
      disks.append(disk_dev)
6658
  else:
6659
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6660
  return disks
6661

    
6662

    
6663
def _GetInstanceInfoText(instance):
6664
  """Compute that text that should be added to the disk's metadata.
6665

6666
  """
6667
  return "originstname+%s" % instance.name
6668

    
6669

    
6670
def _CalcEta(time_taken, written, total_size):
6671
  """Calculates the ETA based on size written and total size.
6672

6673
  @param time_taken: The time taken so far
6674
  @param written: amount written so far
6675
  @param total_size: The total size of data to be written
6676
  @return: The remaining time in seconds
6677

6678
  """
6679
  avg_time = time_taken / float(written)
6680
  return (total_size - written) * avg_time
6681

    
6682

    
6683
def _WipeDisks(lu, instance):
6684
  """Wipes instance disks.
6685

6686
  @type lu: L{LogicalUnit}
6687
  @param lu: the logical unit on whose behalf we execute
6688
  @type instance: L{objects.Instance}
6689
  @param instance: the instance whose disks we should create
6690
  @return: the success of the wipe
6691

6692
  """
6693
  node = instance.primary_node
6694

    
6695
  for device in instance.disks:
6696
    lu.cfg.SetDiskID(device, node)
6697

    
6698
  logging.info("Pause sync of instance %s disks", instance.name)
6699
  result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, True)
6700

    
6701
  for idx, success in enumerate(result.payload):
6702
    if not success:
6703
      logging.warn("pause-sync of instance %s for disks %d failed",
6704
                   instance.name, idx)
6705

    
6706
  try:
6707
    for idx, device in enumerate(instance.disks):
6708
      # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
6709
      # MAX_WIPE_CHUNK at max
6710
      wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
6711
                            constants.MIN_WIPE_CHUNK_PERCENT)
6712
      # we _must_ make this an int, otherwise rounding errors will
6713
      # occur
6714
      wipe_chunk_size = int(wipe_chunk_size)
6715

    
6716
      lu.LogInfo("* Wiping disk %d", idx)
6717
      logging.info("Wiping disk %d for instance %s, node %s using"
6718
                   " chunk size %s", idx, instance.name, node, wipe_chunk_size)
6719

    
6720
      offset = 0
6721
      size = device.size
6722
      last_output = 0
6723
      start_time = time.time()
6724

    
6725
      while offset < size:
6726
        wipe_size = min(wipe_chunk_size, size - offset)
6727
        logging.debug("Wiping disk %d, offset %s, chunk %s",
6728
                      idx, offset, wipe_size)
6729
        result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
6730
        result.Raise("Could not wipe disk %d at offset %d for size %d" %
6731
                     (idx, offset, wipe_size))
6732
        now = time.time()
6733
        offset += wipe_size
6734
        if now - last_output >= 60:
6735
          eta = _CalcEta(now - start_time, offset, size)
6736
          lu.LogInfo(" - done: %.1f%% ETA: %s" %
6737
                     (offset / float(size) * 100, utils.FormatSeconds(eta)))
6738
          last_output = now
6739
  finally:
6740
    logging.info("Resume sync of instance %s disks", instance.name)
6741

    
6742
    result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, False)
6743

    
6744
    for idx, success in enumerate(result.payload):
6745
      if not success:
6746
        lu.LogWarning("Warning: Resume sync of disk %d failed. Please have a"
6747
                      " look at the status and troubleshoot the issue.", idx)
6748
        logging.warn("resume-sync of instance %s for disks %d failed",
6749
                     instance.name, idx)
6750

    
6751

    
6752
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6753
  """Create all disks for an instance.
6754

6755
  This abstracts away some work from AddInstance.
6756

6757
  @type lu: L{LogicalUnit}
6758
  @param lu: the logical unit on whose behalf we execute
6759
  @type instance: L{objects.Instance}
6760
  @param instance: the instance whose disks we should create
6761
  @type to_skip: list
6762
  @param to_skip: list of indices to skip
6763
  @type target_node: string
6764
  @param target_node: if passed, overrides the target node for creation
6765
  @rtype: boolean
6766
  @return: the success of the creation
6767

6768
  """
6769
  info = _GetInstanceInfoText(instance)
6770
  if target_node is None:
6771
    pnode = instance.primary_node
6772
    all_nodes = instance.all_nodes
6773
  else:
6774
    pnode = target_node
6775
    all_nodes = [pnode]
6776

    
6777
  if instance.disk_template == constants.DT_FILE:
6778
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6779
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6780

    
6781
    result.Raise("Failed to create directory '%s' on"
6782
                 " node %s" % (file_storage_dir, pnode))
6783

    
6784
  # Note: this needs to be kept in sync with adding of disks in
6785
  # LUInstanceSetParams
6786
  for idx, device in enumerate(instance.disks):
6787
    if to_skip and idx in to_skip:
6788
      continue
6789
    logging.info("Creating volume %s for instance %s",
6790
                 device.iv_name, instance.name)
6791
    #HARDCODE
6792
    for node in all_nodes:
6793
      f_create = node == pnode
6794
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6795

    
6796

    
6797
def _RemoveDisks(lu, instance, target_node=None):
6798
  """Remove all disks for an instance.
6799

6800
  This abstracts away some work from `AddInstance()` and
6801
  `RemoveInstance()`. Note that in case some of the devices couldn't
6802
  be removed, the removal will continue with the other ones (compare
6803
  with `_CreateDisks()`).
6804

6805
  @type lu: L{LogicalUnit}
6806
  @param lu: the logical unit on whose behalf we execute
6807
  @type instance: L{objects.Instance}
6808
  @param instance: the instance whose disks we should remove
6809
  @type target_node: string
6810
  @param target_node: used to override the node on which to remove the disks
6811
  @rtype: boolean
6812
  @return: the success of the removal
6813

6814
  """
6815
  logging.info("Removing block devices for instance %s", instance.name)
6816

    
6817
  all_result = True
6818
  for device in instance.disks:
6819
    if target_node:
6820
      edata = [(target_node, device)]
6821
    else:
6822
      edata = device.ComputeNodeTree(instance.primary_node)
6823
    for node, disk in edata:
6824
      lu.cfg.SetDiskID(disk, node)
6825
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6826
      if msg:
6827
        lu.LogWarning("Could not remove block device %s on node %s,"
6828
                      " continuing anyway: %s", device.iv_name, node, msg)
6829
        all_result = False
6830

    
6831
  if instance.disk_template == constants.DT_FILE:
6832
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6833
    if target_node:
6834
      tgt = target_node
6835
    else:
6836
      tgt = instance.primary_node
6837
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6838
    if result.fail_msg:
6839
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6840
                    file_storage_dir, instance.primary_node, result.fail_msg)
6841
      all_result = False
6842

    
6843
  return all_result
6844

    
6845

    
6846
def _ComputeDiskSizePerVG(disk_template, disks):
6847
  """Compute disk size requirements in the volume group
6848

6849
  """
6850
  def _compute(disks, payload):
6851
    """Universal algorithm
6852

6853
    """
6854
    vgs = {}
6855
    for disk in disks:
6856
      vgs[disk["vg"]] = vgs.get("vg", 0) + disk["size"] + payload
6857

    
6858
    return vgs
6859

    
6860
  # Required free disk space as a function of disk and swap space
6861
  req_size_dict = {
6862
    constants.DT_DISKLESS: {},
6863
    constants.DT_PLAIN: _compute(disks, 0),
6864
    # 128 MB are added for drbd metadata for each disk
6865
    constants.DT_DRBD8: _compute(disks, 128),
6866
    constants.DT_FILE: {},
6867
  }
6868

    
6869
  if disk_template not in req_size_dict:
6870
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6871
                                 " is unknown" %  disk_template)
6872

    
6873
  return req_size_dict[disk_template]
6874

    
6875

    
6876
def _ComputeDiskSize(disk_template, disks):
6877
  """Compute disk size requirements in the volume group
6878

6879
  """
6880
  # Required free disk space as a function of disk and swap space
6881
  req_size_dict = {
6882
    constants.DT_DISKLESS: None,
6883
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6884
    # 128 MB are added for drbd metadata for each disk
6885
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6886
    constants.DT_FILE: None,
6887
  }
6888

    
6889
  if disk_template not in req_size_dict:
6890
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6891
                                 " is unknown" %  disk_template)
6892

    
6893
  return req_size_dict[disk_template]
6894

    
6895

    
6896
def _FilterVmNodes(lu, nodenames):
6897
  """Filters out non-vm_capable nodes from a list.
6898

6899
  @type lu: L{LogicalUnit}
6900
  @param lu: the logical unit for which we check
6901
  @type nodenames: list
6902
  @param nodenames: the list of nodes on which we should check
6903
  @rtype: list
6904
  @return: the list of vm-capable nodes
6905

6906
  """
6907
  vm_nodes = frozenset(lu.cfg.GetNonVmCapableNodeList())
6908
  return [name for name in nodenames if name not in vm_nodes]
6909

    
6910

    
6911
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6912
  """Hypervisor parameter validation.
6913

6914
  This function abstract the hypervisor parameter validation to be
6915
  used in both instance create and instance modify.
6916

6917
  @type lu: L{LogicalUnit}
6918
  @param lu: the logical unit for which we check
6919
  @type nodenames: list
6920
  @param nodenames: the list of nodes on which we should check
6921
  @type hvname: string
6922
  @param hvname: the name of the hypervisor we should use
6923
  @type hvparams: dict
6924
  @param hvparams: the parameters which we need to check
6925
  @raise errors.OpPrereqError: if the parameters are not valid
6926

6927
  """
6928
  nodenames = _FilterVmNodes(lu, nodenames)
6929
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6930
                                                  hvname,
6931
                                                  hvparams)
6932
  for node in nodenames:
6933
    info = hvinfo[node]
6934
    if info.offline:
6935
      continue
6936
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6937

    
6938

    
6939
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6940
  """OS parameters validation.
6941

6942
  @type lu: L{LogicalUnit}
6943
  @param lu: the logical unit for which we check
6944
  @type required: boolean
6945
  @param required: whether the validation should fail if the OS is not
6946
      found
6947
  @type nodenames: list
6948
  @param nodenames: the list of nodes on which we should check
6949
  @type osname: string
6950
  @param osname: the name of the hypervisor we should use
6951
  @type osparams: dict
6952
  @param osparams: the parameters which we need to check
6953
  @raise errors.OpPrereqError: if the parameters are not valid
6954

6955
  """
6956
  nodenames = _FilterVmNodes(lu, nodenames)
6957
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6958
                                   [constants.OS_VALIDATE_PARAMETERS],
6959
                                   osparams)
6960
  for node, nres in result.items():
6961
    # we don't check for offline cases since this should be run only
6962
    # against the master node and/or an instance's nodes
6963
    nres.Raise("OS Parameters validation failed on node %s" % node)
6964
    if not nres.payload:
6965
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6966
                 osname, node)
6967

    
6968

    
6969
class LUInstanceCreate(LogicalUnit):
6970
  """Create an instance.
6971

6972
  """
6973
  HPATH = "instance-add"
6974
  HTYPE = constants.HTYPE_INSTANCE
6975
  REQ_BGL = False
6976

    
6977
  def CheckArguments(self):
6978
    """Check arguments.
6979

6980
    """
6981
    # do not require name_check to ease forward/backward compatibility
6982
    # for tools
6983
    if self.op.no_install and self.op.start:
6984
      self.LogInfo("No-installation mode selected, disabling startup")
6985
      self.op.start = False
6986
    # validate/normalize the instance name
6987
    self.op.instance_name = \
6988
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
6989

    
6990
    if self.op.ip_check and not self.op.name_check:
6991
      # TODO: make the ip check more flexible and not depend on the name check
6992
      raise errors.OpPrereqError("Cannot do ip check without a name check",
6993
                                 errors.ECODE_INVAL)
6994

    
6995
    # check nics' parameter names
6996
    for nic in self.op.nics:
6997
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6998

    
6999
    # check disks. parameter names and consistent adopt/no-adopt strategy
7000
    has_adopt = has_no_adopt = False
7001
    for disk in self.op.disks:
7002
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
7003
      if "adopt" in disk:
7004
        has_adopt = True
7005
      else:
7006
        has_no_adopt = True
7007
    if has_adopt and has_no_adopt:
7008
      raise errors.OpPrereqError("Either all disks are adopted or none is",
7009
                                 errors.ECODE_INVAL)
7010
    if has_adopt:
7011
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
7012
        raise errors.OpPrereqError("Disk adoption is not supported for the"
7013
                                   " '%s' disk template" %
7014
                                   self.op.disk_template,
7015
                                   errors.ECODE_INVAL)
7016
      if self.op.iallocator is not None:
7017
        raise errors.OpPrereqError("Disk adoption not allowed with an"
7018
                                   " iallocator script", errors.ECODE_INVAL)
7019
      if self.op.mode == constants.INSTANCE_IMPORT:
7020
        raise errors.OpPrereqError("Disk adoption not allowed for"
7021
                                   " instance import", errors.ECODE_INVAL)
7022

    
7023
    self.adopt_disks = has_adopt
7024

    
7025
    # instance name verification
7026
    if self.op.name_check:
7027
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
7028
      self.op.instance_name = self.hostname1.name
7029
      # used in CheckPrereq for ip ping check
7030
      self.check_ip = self.hostname1.ip
7031
    else:
7032
      self.check_ip = None
7033

    
7034
    # file storage checks
7035
    if (self.op.file_driver and
7036
        not self.op.file_driver in constants.FILE_DRIVER):
7037
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
7038
                                 self.op.file_driver, errors.ECODE_INVAL)
7039

    
7040
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
7041
      raise errors.OpPrereqError("File storage directory path not absolute",
7042
                                 errors.ECODE_INVAL)
7043

    
7044
    ### Node/iallocator related checks
7045
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
7046

    
7047
    if self.op.pnode is not None:
7048
      if self.op.disk_template in constants.DTS_NET_MIRROR:
7049
        if self.op.snode is None:
7050
          raise errors.OpPrereqError("The networked disk templates need"
7051
                                     " a mirror node", errors.ECODE_INVAL)
7052
      elif self.op.snode:
7053
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
7054
                        " template")
7055
        self.op.snode = None
7056

    
7057
    self._cds = _GetClusterDomainSecret()
7058

    
7059
    if self.op.mode == constants.INSTANCE_IMPORT:
7060
      # On import force_variant must be True, because if we forced it at
7061
      # initial install, our only chance when importing it back is that it
7062
      # works again!
7063
      self.op.force_variant = True
7064

    
7065
      if self.op.no_install:
7066
        self.LogInfo("No-installation mode has no effect during import")
7067

    
7068
    elif self.op.mode == constants.INSTANCE_CREATE:
7069
      if self.op.os_type is None:
7070
        raise errors.OpPrereqError("No guest OS specified",
7071
                                   errors.ECODE_INVAL)
7072
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
7073
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
7074
                                   " installation" % self.op.os_type,
7075
                                   errors.ECODE_STATE)
7076
      if self.op.disk_template is None:
7077
        raise errors.OpPrereqError("No disk template specified",
7078
                                   errors.ECODE_INVAL)
7079

    
7080
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7081
      # Check handshake to ensure both clusters have the same domain secret
7082
      src_handshake = self.op.source_handshake
7083
      if not src_handshake:
7084
        raise errors.OpPrereqError("Missing source handshake",
7085
                                   errors.ECODE_INVAL)
7086

    
7087
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
7088
                                                           src_handshake)
7089
      if errmsg:
7090
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
7091
                                   errors.ECODE_INVAL)
7092

    
7093
      # Load and check source CA
7094
      self.source_x509_ca_pem = self.op.source_x509_ca
7095
      if not self.source_x509_ca_pem:
7096
        raise errors.OpPrereqError("Missing source X509 CA",
7097
                                   errors.ECODE_INVAL)
7098

    
7099
      try:
7100
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
7101
                                                    self._cds)
7102
      except OpenSSL.crypto.Error, err:
7103
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
7104
                                   (err, ), errors.ECODE_INVAL)
7105

    
7106
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
7107
      if errcode is not None:
7108
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
7109
                                   errors.ECODE_INVAL)
7110

    
7111
      self.source_x509_ca = cert
7112

    
7113
      src_instance_name = self.op.source_instance_name
7114
      if not src_instance_name:
7115
        raise errors.OpPrereqError("Missing source instance name",
7116
                                   errors.ECODE_INVAL)
7117

    
7118
      self.source_instance_name = \
7119
          netutils.GetHostname(name=src_instance_name).name
7120

    
7121
    else:
7122
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
7123
                                 self.op.mode, errors.ECODE_INVAL)
7124

    
7125
  def ExpandNames(self):
7126
    """ExpandNames for CreateInstance.
7127

7128
    Figure out the right locks for instance creation.
7129

7130
    """
7131
    self.needed_locks = {}
7132

    
7133
    instance_name = self.op.instance_name
7134
    # this is just a preventive check, but someone might still add this
7135
    # instance in the meantime, and creation will fail at lock-add time
7136
    if instance_name in self.cfg.GetInstanceList():
7137
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
7138
                                 instance_name, errors.ECODE_EXISTS)
7139

    
7140
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
7141

    
7142
    if self.op.iallocator:
7143
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7144
    else:
7145
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
7146
      nodelist = [self.op.pnode]
7147
      if self.op.snode is not None:
7148
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
7149
        nodelist.append(self.op.snode)
7150
      self.needed_locks[locking.LEVEL_NODE] = nodelist
7151

    
7152
    # in case of import lock the source node too
7153
    if self.op.mode == constants.INSTANCE_IMPORT:
7154
      src_node = self.op.src_node
7155
      src_path = self.op.src_path
7156

    
7157
      if src_path is None:
7158
        self.op.src_path = src_path = self.op.instance_name
7159

    
7160
      if src_node is None:
7161
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7162
        self.op.src_node = None
7163
        if os.path.isabs(src_path):
7164
          raise errors.OpPrereqError("Importing an instance from an absolute"
7165
                                     " path requires a source node option.",
7166
                                     errors.ECODE_INVAL)
7167
      else:
7168
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
7169
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
7170
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
7171
        if not os.path.isabs(src_path):
7172
          self.op.src_path = src_path = \
7173
            utils.PathJoin(constants.EXPORT_DIR, src_path)
7174

    
7175
  def _RunAllocator(self):
7176
    """Run the allocator based on input opcode.
7177

7178
    """
7179
    nics = [n.ToDict() for n in self.nics]
7180
    ial = IAllocator(self.cfg, self.rpc,
7181
                     mode=constants.IALLOCATOR_MODE_ALLOC,
7182
                     name=self.op.instance_name,
7183
                     disk_template=self.op.disk_template,
7184
                     tags=[],
7185
                     os=self.op.os_type,
7186
                     vcpus=self.be_full[constants.BE_VCPUS],
7187
                     mem_size=self.be_full[constants.BE_MEMORY],
7188
                     disks=self.disks,
7189
                     nics=nics,
7190
                     hypervisor=self.op.hypervisor,
7191
                     )
7192

    
7193
    ial.Run(self.op.iallocator)
7194

    
7195
    if not ial.success:
7196
      raise errors.OpPrereqError("Can't compute nodes using"
7197
                                 " iallocator '%s': %s" %
7198
                                 (self.op.iallocator, ial.info),
7199
                                 errors.ECODE_NORES)
7200
    if len(ial.result) != ial.required_nodes:
7201
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7202
                                 " of nodes (%s), required %s" %
7203
                                 (self.op.iallocator, len(ial.result),
7204
                                  ial.required_nodes), errors.ECODE_FAULT)
7205
    self.op.pnode = ial.result[0]
7206
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
7207
                 self.op.instance_name, self.op.iallocator,
7208
                 utils.CommaJoin(ial.result))
7209
    if ial.required_nodes == 2:
7210
      self.op.snode = ial.result[1]
7211

    
7212
  def BuildHooksEnv(self):
7213
    """Build hooks env.
7214

7215
    This runs on master, primary and secondary nodes of the instance.
7216

7217
    """
7218
    env = {
7219
      "ADD_MODE": self.op.mode,
7220
      }
7221
    if self.op.mode == constants.INSTANCE_IMPORT:
7222
      env["SRC_NODE"] = self.op.src_node
7223
      env["SRC_PATH"] = self.op.src_path
7224
      env["SRC_IMAGES"] = self.src_images
7225

    
7226
    env.update(_BuildInstanceHookEnv(
7227
      name=self.op.instance_name,
7228
      primary_node=self.op.pnode,
7229
      secondary_nodes=self.secondaries,
7230
      status=self.op.start,
7231
      os_type=self.op.os_type,
7232
      memory=self.be_full[constants.BE_MEMORY],
7233
      vcpus=self.be_full[constants.BE_VCPUS],
7234
      nics=_NICListToTuple(self, self.nics),
7235
      disk_template=self.op.disk_template,
7236
      disks=[(d["size"], d["mode"]) for d in self.disks],
7237
      bep=self.be_full,
7238
      hvp=self.hv_full,
7239
      hypervisor_name=self.op.hypervisor,
7240
    ))
7241

    
7242
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
7243
          self.secondaries)
7244
    return env, nl, nl
7245

    
7246
  def _ReadExportInfo(self):
7247
    """Reads the export information from disk.
7248

7249
    It will override the opcode source node and path with the actual
7250
    information, if these two were not specified before.
7251

7252
    @return: the export information
7253

7254
    """
7255
    assert self.op.mode == constants.INSTANCE_IMPORT
7256

    
7257
    src_node = self.op.src_node
7258
    src_path = self.op.src_path
7259

    
7260
    if src_node is None:
7261
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
7262
      exp_list = self.rpc.call_export_list(locked_nodes)
7263
      found = False
7264
      for node in exp_list:
7265
        if exp_list[node].fail_msg:
7266
          continue
7267
        if src_path in exp_list[node].payload:
7268
          found = True
7269
          self.op.src_node = src_node = node
7270
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
7271
                                                       src_path)
7272
          break
7273
      if not found:
7274
        raise errors.OpPrereqError("No export found for relative path %s" %
7275
                                    src_path, errors.ECODE_INVAL)
7276

    
7277
    _CheckNodeOnline(self, src_node)
7278
    result = self.rpc.call_export_info(src_node, src_path)
7279
    result.Raise("No export or invalid export found in dir %s" % src_path)
7280

    
7281
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
7282
    if not export_info.has_section(constants.INISECT_EXP):
7283
      raise errors.ProgrammerError("Corrupted export config",
7284
                                   errors.ECODE_ENVIRON)
7285

    
7286
    ei_version = export_info.get(constants.INISECT_EXP, "version")
7287
    if (int(ei_version) != constants.EXPORT_VERSION):
7288
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
7289
                                 (ei_version, constants.EXPORT_VERSION),
7290
                                 errors.ECODE_ENVIRON)
7291
    return export_info
7292

    
7293
  def _ReadExportParams(self, einfo):
7294
    """Use export parameters as defaults.
7295

7296
    In case the opcode doesn't specify (as in override) some instance
7297
    parameters, then try to use them from the export information, if
7298
    that declares them.
7299

7300
    """
7301
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
7302

    
7303
    if self.op.disk_template is None:
7304
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
7305
        self.op.disk_template = einfo.get(constants.INISECT_INS,
7306
                                          "disk_template")
7307
      else:
7308
        raise errors.OpPrereqError("No disk template specified and the export"
7309
                                   " is missing the disk_template information",
7310
                                   errors.ECODE_INVAL)
7311

    
7312
    if not self.op.disks:
7313
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
7314
        disks = []
7315
        # TODO: import the disk iv_name too
7316
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
7317
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
7318
          disks.append({"size": disk_sz})
7319
        self.op.disks = disks
7320
      else:
7321
        raise errors.OpPrereqError("No disk info specified and the export"
7322
                                   " is missing the disk information",
7323
                                   errors.ECODE_INVAL)
7324

    
7325
    if (not self.op.nics and
7326
        einfo.has_option(constants.INISECT_INS, "nic_count")):
7327
      nics = []
7328
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
7329
        ndict = {}
7330
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
7331
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
7332
          ndict[name] = v
7333
        nics.append(ndict)
7334
      self.op.nics = nics
7335

    
7336
    if (self.op.hypervisor is None and
7337
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
7338
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
7339
    if einfo.has_section(constants.INISECT_HYP):
7340
      # use the export parameters but do not override the ones
7341
      # specified by the user
7342
      for name, value in einfo.items(constants.INISECT_HYP):
7343
        if name not in self.op.hvparams:
7344
          self.op.hvparams[name] = value
7345

    
7346
    if einfo.has_section(constants.INISECT_BEP):
7347
      # use the parameters, without overriding
7348
      for name, value in einfo.items(constants.INISECT_BEP):
7349
        if name not in self.op.beparams:
7350
          self.op.beparams[name] = value
7351
    else:
7352
      # try to read the parameters old style, from the main section
7353
      for name in constants.BES_PARAMETERS:
7354
        if (name not in self.op.beparams and
7355
            einfo.has_option(constants.INISECT_INS, name)):
7356
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
7357

    
7358
    if einfo.has_section(constants.INISECT_OSP):
7359
      # use the parameters, without overriding
7360
      for name, value in einfo.items(constants.INISECT_OSP):
7361
        if name not in self.op.osparams:
7362
          self.op.osparams[name] = value
7363

    
7364
  def _RevertToDefaults(self, cluster):
7365
    """Revert the instance parameters to the default values.
7366

7367
    """
7368
    # hvparams
7369
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
7370
    for name in self.op.hvparams.keys():
7371
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
7372
        del self.op.hvparams[name]
7373
    # beparams
7374
    be_defs = cluster.SimpleFillBE({})
7375
    for name in self.op.beparams.keys():
7376
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
7377
        del self.op.beparams[name]
7378
    # nic params
7379
    nic_defs = cluster.SimpleFillNIC({})
7380
    for nic in self.op.nics:
7381
      for name in constants.NICS_PARAMETERS:
7382
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
7383
          del nic[name]
7384
    # osparams
7385
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
7386
    for name in self.op.osparams.keys():
7387
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
7388
        del self.op.osparams[name]
7389

    
7390
  def CheckPrereq(self):
7391
    """Check prerequisites.
7392

7393
    """
7394
    if self.op.mode == constants.INSTANCE_IMPORT:
7395
      export_info = self._ReadExportInfo()
7396
      self._ReadExportParams(export_info)
7397

    
7398
    if (not self.cfg.GetVGName() and
7399
        self.op.disk_template not in constants.DTS_NOT_LVM):
7400
      raise errors.OpPrereqError("Cluster does not support lvm-based"
7401
                                 " instances", errors.ECODE_STATE)
7402

    
7403
    if self.op.hypervisor is None:
7404
      self.op.hypervisor = self.cfg.GetHypervisorType()
7405

    
7406
    cluster = self.cfg.GetClusterInfo()
7407
    enabled_hvs = cluster.enabled_hypervisors
7408
    if self.op.hypervisor not in enabled_hvs:
7409
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
7410
                                 " cluster (%s)" % (self.op.hypervisor,
7411
                                  ",".join(enabled_hvs)),
7412
                                 errors.ECODE_STATE)
7413

    
7414
    # check hypervisor parameter syntax (locally)
7415
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
7416
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
7417
                                      self.op.hvparams)
7418
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
7419
    hv_type.CheckParameterSyntax(filled_hvp)
7420
    self.hv_full = filled_hvp
7421
    # check that we don't specify global parameters on an instance
7422
    _CheckGlobalHvParams(self.op.hvparams)
7423

    
7424
    # fill and remember the beparams dict
7425
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
7426
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
7427

    
7428
    # build os parameters
7429
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
7430

    
7431
    # now that hvp/bep are in final format, let's reset to defaults,
7432
    # if told to do so
7433
    if self.op.identify_defaults:
7434
      self._RevertToDefaults(cluster)
7435

    
7436
    # NIC buildup
7437
    self.nics = []
7438
    for idx, nic in enumerate(self.op.nics):
7439
      nic_mode_req = nic.get("mode", None)
7440
      nic_mode = nic_mode_req
7441
      if nic_mode is None:
7442
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
7443

    
7444
      # in routed mode, for the first nic, the default ip is 'auto'
7445
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
7446
        default_ip_mode = constants.VALUE_AUTO
7447
      else:
7448
        default_ip_mode = constants.VALUE_NONE
7449

    
7450
      # ip validity checks
7451
      ip = nic.get("ip", default_ip_mode)
7452
      if ip is None or ip.lower() == constants.VALUE_NONE:
7453
        nic_ip = None
7454
      elif ip.lower() == constants.VALUE_AUTO:
7455
        if not self.op.name_check:
7456
          raise errors.OpPrereqError("IP address set to auto but name checks"
7457
                                     " have been skipped",
7458
                                     errors.ECODE_INVAL)
7459
        nic_ip = self.hostname1.ip
7460
      else:
7461
        if not netutils.IPAddress.IsValid(ip):
7462
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
7463
                                     errors.ECODE_INVAL)
7464
        nic_ip = ip
7465

    
7466
      # TODO: check the ip address for uniqueness
7467
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7468
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7469
                                   errors.ECODE_INVAL)
7470

    
7471
      # MAC address verification
7472
      mac = nic.get("mac", constants.VALUE_AUTO)
7473
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7474
        mac = utils.NormalizeAndValidateMac(mac)
7475

    
7476
        try:
7477
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7478
        except errors.ReservationError:
7479
          raise errors.OpPrereqError("MAC address %s already in use"
7480
                                     " in cluster" % mac,
7481
                                     errors.ECODE_NOTUNIQUE)
7482

    
7483
      # bridge verification
7484
      bridge = nic.get("bridge", None)
7485
      link = nic.get("link", None)
7486
      if bridge and link:
7487
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7488
                                   " at the same time", errors.ECODE_INVAL)
7489
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7490
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7491
                                   errors.ECODE_INVAL)
7492
      elif bridge:
7493
        link = bridge
7494

    
7495
      nicparams = {}
7496
      if nic_mode_req:
7497
        nicparams[constants.NIC_MODE] = nic_mode_req
7498
      if link:
7499
        nicparams[constants.NIC_LINK] = link
7500

    
7501
      check_params = cluster.SimpleFillNIC(nicparams)
7502
      objects.NIC.CheckParameterSyntax(check_params)
7503
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7504

    
7505
    # disk checks/pre-build
7506
    self.disks = []
7507
    for disk in self.op.disks:
7508
      mode = disk.get("mode", constants.DISK_RDWR)
7509
      if mode not in constants.DISK_ACCESS_SET:
7510
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7511
                                   mode, errors.ECODE_INVAL)
7512
      size = disk.get("size", None)
7513
      if size is None:
7514
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7515
      try:
7516
        size = int(size)
7517
      except (TypeError, ValueError):
7518
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7519
                                   errors.ECODE_INVAL)
7520
      data_vg = disk.get("vg", self.cfg.GetVGName())
7521
      meta_vg = disk.get("metavg", data_vg)
7522
      new_disk = {"size": size, "mode": mode, "vg": data_vg, "metavg": meta_vg}
7523
      if "adopt" in disk:
7524
        new_disk["adopt"] = disk["adopt"]
7525
      self.disks.append(new_disk)
7526

    
7527
    if self.op.mode == constants.INSTANCE_IMPORT:
7528

    
7529
      # Check that the new instance doesn't have less disks than the export
7530
      instance_disks = len(self.disks)
7531
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7532
      if instance_disks < export_disks:
7533
        raise errors.OpPrereqError("Not enough disks to import."
7534
                                   " (instance: %d, export: %d)" %
7535
                                   (instance_disks, export_disks),
7536
                                   errors.ECODE_INVAL)
7537

    
7538
      disk_images = []
7539
      for idx in range(export_disks):
7540
        option = 'disk%d_dump' % idx
7541
        if export_info.has_option(constants.INISECT_INS, option):
7542
          # FIXME: are the old os-es, disk sizes, etc. useful?
7543
          export_name = export_info.get(constants.INISECT_INS, option)
7544
          image = utils.PathJoin(self.op.src_path, export_name)
7545
          disk_images.append(image)
7546
        else:
7547
          disk_images.append(False)
7548

    
7549
      self.src_images = disk_images
7550

    
7551
      old_name = export_info.get(constants.INISECT_INS, 'name')
7552
      try:
7553
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7554
      except (TypeError, ValueError), err:
7555
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7556
                                   " an integer: %s" % str(err),
7557
                                   errors.ECODE_STATE)
7558
      if self.op.instance_name == old_name:
7559
        for idx, nic in enumerate(self.nics):
7560
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7561
            nic_mac_ini = 'nic%d_mac' % idx
7562
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7563

    
7564
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7565

    
7566
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7567
    if self.op.ip_check:
7568
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7569
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7570
                                   (self.check_ip, self.op.instance_name),
7571
                                   errors.ECODE_NOTUNIQUE)
7572

    
7573
    #### mac address generation
7574
    # By generating here the mac address both the allocator and the hooks get
7575
    # the real final mac address rather than the 'auto' or 'generate' value.
7576
    # There is a race condition between the generation and the instance object
7577
    # creation, which means that we know the mac is valid now, but we're not
7578
    # sure it will be when we actually add the instance. If things go bad
7579
    # adding the instance will abort because of a duplicate mac, and the
7580
    # creation job will fail.
7581
    for nic in self.nics:
7582
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7583
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7584

    
7585
    #### allocator run
7586

    
7587
    if self.op.iallocator is not None:
7588
      self._RunAllocator()
7589

    
7590
    #### node related checks
7591

    
7592
    # check primary node
7593
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7594
    assert self.pnode is not None, \
7595
      "Cannot retrieve locked node %s" % self.op.pnode
7596
    if pnode.offline:
7597
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7598
                                 pnode.name, errors.ECODE_STATE)
7599
    if pnode.drained:
7600
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7601
                                 pnode.name, errors.ECODE_STATE)
7602
    if not pnode.vm_capable:
7603
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
7604
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
7605

    
7606
    self.secondaries = []
7607

    
7608
    # mirror node verification
7609
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7610
      if self.op.snode == pnode.name:
7611
        raise errors.OpPrereqError("The secondary node cannot be the"
7612
                                   " primary node.", errors.ECODE_INVAL)
7613
      _CheckNodeOnline(self, self.op.snode)
7614
      _CheckNodeNotDrained(self, self.op.snode)
7615
      _CheckNodeVmCapable(self, self.op.snode)
7616
      self.secondaries.append(self.op.snode)
7617

    
7618
    nodenames = [pnode.name] + self.secondaries
7619

    
7620
    if not self.adopt_disks:
7621
      # Check lv size requirements, if not adopting
7622
      req_sizes = _ComputeDiskSizePerVG(self.op.disk_template, self.disks)
7623
      _CheckNodesFreeDiskPerVG(self, nodenames, req_sizes)
7624

    
7625
    else: # instead, we must check the adoption data
7626
      all_lvs = set([i["vg"] + "/" + i["adopt"] for i in self.disks])
7627
      if len(all_lvs) != len(self.disks):
7628
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7629
                                   errors.ECODE_INVAL)
7630
      for lv_name in all_lvs:
7631
        try:
7632
          # FIXME: lv_name here is "vg/lv" need to ensure that other calls
7633
          # to ReserveLV uses the same syntax
7634
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7635
        except errors.ReservationError:
7636
          raise errors.OpPrereqError("LV named %s used by another instance" %
7637
                                     lv_name, errors.ECODE_NOTUNIQUE)
7638

    
7639
      vg_names = self.rpc.call_vg_list([pnode.name])[pnode.name]
7640
      vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
7641

    
7642
      node_lvs = self.rpc.call_lv_list([pnode.name],
7643
                                       vg_names.payload.keys())[pnode.name]
7644
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7645
      node_lvs = node_lvs.payload
7646

    
7647
      delta = all_lvs.difference(node_lvs.keys())
7648
      if delta:
7649
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7650
                                   utils.CommaJoin(delta),
7651
                                   errors.ECODE_INVAL)
7652
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7653
      if online_lvs:
7654
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7655
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7656
                                   errors.ECODE_STATE)
7657
      # update the size of disk based on what is found
7658
      for dsk in self.disks:
7659
        dsk["size"] = int(float(node_lvs[dsk["vg"] + "/" + dsk["adopt"]][0]))
7660

    
7661
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7662

    
7663
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7664
    # check OS parameters (remotely)
7665
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7666

    
7667
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7668

    
7669
    # memory check on primary node
7670
    if self.op.start:
7671
      _CheckNodeFreeMemory(self, self.pnode.name,
7672
                           "creating instance %s" % self.op.instance_name,
7673
                           self.be_full[constants.BE_MEMORY],
7674
                           self.op.hypervisor)
7675

    
7676
    self.dry_run_result = list(nodenames)
7677

    
7678
  def Exec(self, feedback_fn):
7679
    """Create and add the instance to the cluster.
7680

7681
    """
7682
    instance = self.op.instance_name
7683
    pnode_name = self.pnode.name
7684

    
7685
    ht_kind = self.op.hypervisor
7686
    if ht_kind in constants.HTS_REQ_PORT:
7687
      network_port = self.cfg.AllocatePort()
7688
    else:
7689
      network_port = None
7690

    
7691
    if constants.ENABLE_FILE_STORAGE:
7692
      # this is needed because os.path.join does not accept None arguments
7693
      if self.op.file_storage_dir is None:
7694
        string_file_storage_dir = ""
7695
      else:
7696
        string_file_storage_dir = self.op.file_storage_dir
7697

    
7698
      # build the full file storage dir path
7699
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7700
                                        string_file_storage_dir, instance)
7701
    else:
7702
      file_storage_dir = ""
7703

    
7704
    disks = _GenerateDiskTemplate(self,
7705
                                  self.op.disk_template,
7706
                                  instance, pnode_name,
7707
                                  self.secondaries,
7708
                                  self.disks,
7709
                                  file_storage_dir,
7710
                                  self.op.file_driver,
7711
                                  0,
7712
                                  feedback_fn)
7713

    
7714
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7715
                            primary_node=pnode_name,
7716
                            nics=self.nics, disks=disks,
7717
                            disk_template=self.op.disk_template,
7718
                            admin_up=False,
7719
                            network_port=network_port,
7720
                            beparams=self.op.beparams,
7721
                            hvparams=self.op.hvparams,
7722
                            hypervisor=self.op.hypervisor,
7723
                            osparams=self.op.osparams,
7724
                            )
7725

    
7726
    if self.adopt_disks:
7727
      # rename LVs to the newly-generated names; we need to construct
7728
      # 'fake' LV disks with the old data, plus the new unique_id
7729
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7730
      rename_to = []
7731
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7732
        rename_to.append(t_dsk.logical_id)
7733
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7734
        self.cfg.SetDiskID(t_dsk, pnode_name)
7735
      result = self.rpc.call_blockdev_rename(pnode_name,
7736
                                             zip(tmp_disks, rename_to))
7737
      result.Raise("Failed to rename adoped LVs")
7738
    else:
7739
      feedback_fn("* creating instance disks...")
7740
      try:
7741
        _CreateDisks(self, iobj)
7742
      except errors.OpExecError:
7743
        self.LogWarning("Device creation failed, reverting...")
7744
        try:
7745
          _RemoveDisks(self, iobj)
7746
        finally:
7747
          self.cfg.ReleaseDRBDMinors(instance)
7748
          raise
7749

    
7750
    feedback_fn("adding instance %s to cluster config" % instance)
7751

    
7752
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7753

    
7754
    # Declare that we don't want to remove the instance lock anymore, as we've
7755
    # added the instance to the config
7756
    del self.remove_locks[locking.LEVEL_INSTANCE]
7757
    # Unlock all the nodes
7758
    if self.op.mode == constants.INSTANCE_IMPORT:
7759
      nodes_keep = [self.op.src_node]
7760
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7761
                       if node != self.op.src_node]
7762
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7763
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7764
    else:
7765
      self.context.glm.release(locking.LEVEL_NODE)
7766
      del self.acquired_locks[locking.LEVEL_NODE]
7767

    
7768
    disk_abort = False
7769
    if not self.adopt_disks and self.cfg.GetClusterInfo().prealloc_wipe_disks:
7770
      feedback_fn("* wiping instance disks...")
7771
      try:
7772
        _WipeDisks(self, iobj)
7773
      except errors.OpExecError, err:
7774
        logging.exception("Wiping disks failed")
7775
        self.LogWarning("Wiping instance disks failed (%s)", err)
7776
        disk_abort = True
7777

    
7778
    if disk_abort:
7779
      # Something is already wrong with the disks, don't do anything else
7780
      pass
7781
    elif self.op.wait_for_sync:
7782
      disk_abort = not _WaitForSync(self, iobj)
7783
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7784
      # make sure the disks are not degraded (still sync-ing is ok)
7785
      time.sleep(15)
7786
      feedback_fn("* checking mirrors status")
7787
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7788
    else:
7789
      disk_abort = False
7790

    
7791
    if disk_abort:
7792
      _RemoveDisks(self, iobj)
7793
      self.cfg.RemoveInstance(iobj.name)
7794
      # Make sure the instance lock gets removed
7795
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7796
      raise errors.OpExecError("There are some degraded disks for"
7797
                               " this instance")
7798

    
7799
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7800
      if self.op.mode == constants.INSTANCE_CREATE:
7801
        if not self.op.no_install:
7802
          feedback_fn("* running the instance OS create scripts...")
7803
          # FIXME: pass debug option from opcode to backend
7804
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7805
                                                 self.op.debug_level)
7806
          result.Raise("Could not add os for instance %s"
7807
                       " on node %s" % (instance, pnode_name))
7808

    
7809
      elif self.op.mode == constants.INSTANCE_IMPORT:
7810
        feedback_fn("* running the instance OS import scripts...")
7811

    
7812
        transfers = []
7813

    
7814
        for idx, image in enumerate(self.src_images):
7815
          if not image:
7816
            continue
7817

    
7818
          # FIXME: pass debug option from opcode to backend
7819
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7820
                                             constants.IEIO_FILE, (image, ),
7821
                                             constants.IEIO_SCRIPT,
7822
                                             (iobj.disks[idx], idx),
7823
                                             None)
7824
          transfers.append(dt)
7825

    
7826
        import_result = \
7827
          masterd.instance.TransferInstanceData(self, feedback_fn,
7828
                                                self.op.src_node, pnode_name,
7829
                                                self.pnode.secondary_ip,
7830
                                                iobj, transfers)
7831
        if not compat.all(import_result):
7832
          self.LogWarning("Some disks for instance %s on node %s were not"
7833
                          " imported successfully" % (instance, pnode_name))
7834

    
7835
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7836
        feedback_fn("* preparing remote import...")
7837
        # The source cluster will stop the instance before attempting to make a
7838
        # connection. In some cases stopping an instance can take a long time,
7839
        # hence the shutdown timeout is added to the connection timeout.
7840
        connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
7841
                           self.op.source_shutdown_timeout)
7842
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7843

    
7844
        assert iobj.primary_node == self.pnode.name
7845
        disk_results = \
7846
          masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
7847
                                        self.source_x509_ca,
7848
                                        self._cds, timeouts)
7849
        if not compat.all(disk_results):
7850
          # TODO: Should the instance still be started, even if some disks
7851
          # failed to import (valid for local imports, too)?
7852
          self.LogWarning("Some disks for instance %s on node %s were not"
7853
                          " imported successfully" % (instance, pnode_name))
7854

    
7855
        # Run rename script on newly imported instance
7856
        assert iobj.name == instance
7857
        feedback_fn("Running rename script for %s" % instance)
7858
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7859
                                                   self.source_instance_name,
7860
                                                   self.op.debug_level)
7861
        if result.fail_msg:
7862
          self.LogWarning("Failed to run rename script for %s on node"
7863
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7864

    
7865
      else:
7866
        # also checked in the prereq part
7867
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7868
                                     % self.op.mode)
7869

    
7870
    if self.op.start:
7871
      iobj.admin_up = True
7872
      self.cfg.Update(iobj, feedback_fn)
7873
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7874
      feedback_fn("* starting instance...")
7875
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7876
      result.Raise("Could not start instance")
7877

    
7878
    return list(iobj.all_nodes)
7879

    
7880

    
7881
class LUInstanceConsole(NoHooksLU):
7882
  """Connect to an instance's console.
7883

7884
  This is somewhat special in that it returns the command line that
7885
  you need to run on the master node in order to connect to the
7886
  console.
7887

7888
  """
7889
  REQ_BGL = False
7890

    
7891
  def ExpandNames(self):
7892
    self._ExpandAndLockInstance()
7893

    
7894
  def CheckPrereq(self):
7895
    """Check prerequisites.
7896

7897
    This checks that the instance is in the cluster.
7898

7899
    """
7900
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7901
    assert self.instance is not None, \
7902
      "Cannot retrieve locked instance %s" % self.op.instance_name
7903
    _CheckNodeOnline(self, self.instance.primary_node)
7904

    
7905
  def Exec(self, feedback_fn):
7906
    """Connect to the console of an instance
7907

7908
    """
7909
    instance = self.instance
7910
    node = instance.primary_node
7911

    
7912
    node_insts = self.rpc.call_instance_list([node],
7913
                                             [instance.hypervisor])[node]
7914
    node_insts.Raise("Can't get node information from %s" % node)
7915

    
7916
    if instance.name not in node_insts.payload:
7917
      if instance.admin_up:
7918
        state = "ERROR_down"
7919
      else:
7920
        state = "ADMIN_down"
7921
      raise errors.OpExecError("Instance %s is not running (state %s)" %
7922
                               (instance.name, state))
7923

    
7924
    logging.debug("Connecting to console of %s on %s", instance.name, node)
7925

    
7926
    return _GetInstanceConsole(self.cfg.GetClusterInfo(), instance)
7927

    
7928

    
7929
def _GetInstanceConsole(cluster, instance):
7930
  """Returns console information for an instance.
7931

7932
  @type cluster: L{objects.Cluster}
7933
  @type instance: L{objects.Instance}
7934
  @rtype: dict
7935

7936
  """
7937
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
7938
  # beparams and hvparams are passed separately, to avoid editing the
7939
  # instance and then saving the defaults in the instance itself.
7940
  hvparams = cluster.FillHV(instance)
7941
  beparams = cluster.FillBE(instance)
7942
  console = hyper.GetInstanceConsole(instance, hvparams, beparams)
7943

    
7944
  assert console.instance == instance.name
7945
  assert console.Validate()
7946

    
7947
  return console.ToDict()
7948

    
7949

    
7950
class LUInstanceReplaceDisks(LogicalUnit):
7951
  """Replace the disks of an instance.
7952

7953
  """
7954
  HPATH = "mirrors-replace"
7955
  HTYPE = constants.HTYPE_INSTANCE
7956
  REQ_BGL = False
7957

    
7958
  def CheckArguments(self):
7959
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7960
                                  self.op.iallocator)
7961

    
7962
  def ExpandNames(self):
7963
    self._ExpandAndLockInstance()
7964

    
7965
    if self.op.iallocator is not None:
7966
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7967

    
7968
    elif self.op.remote_node is not None:
7969
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7970
      self.op.remote_node = remote_node
7971

    
7972
      # Warning: do not remove the locking of the new secondary here
7973
      # unless DRBD8.AddChildren is changed to work in parallel;
7974
      # currently it doesn't since parallel invocations of
7975
      # FindUnusedMinor will conflict
7976
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7977
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7978

    
7979
    else:
7980
      self.needed_locks[locking.LEVEL_NODE] = []
7981
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7982

    
7983
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7984
                                   self.op.iallocator, self.op.remote_node,
7985
                                   self.op.disks, False, self.op.early_release)
7986

    
7987
    self.tasklets = [self.replacer]
7988

    
7989
  def DeclareLocks(self, level):
7990
    # If we're not already locking all nodes in the set we have to declare the
7991
    # instance's primary/secondary nodes.
7992
    if (level == locking.LEVEL_NODE and
7993
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7994
      self._LockInstancesNodes()
7995

    
7996
  def BuildHooksEnv(self):
7997
    """Build hooks env.
7998

7999
    This runs on the master, the primary and all the secondaries.
8000

8001
    """
8002
    instance = self.replacer.instance
8003
    env = {
8004
      "MODE": self.op.mode,
8005
      "NEW_SECONDARY": self.op.remote_node,
8006
      "OLD_SECONDARY": instance.secondary_nodes[0],
8007
      }
8008
    env.update(_BuildInstanceHookEnvByObject(self, instance))
8009
    nl = [
8010
      self.cfg.GetMasterNode(),
8011
      instance.primary_node,
8012
      ]
8013
    if self.op.remote_node is not None:
8014
      nl.append(self.op.remote_node)
8015
    return env, nl, nl
8016

    
8017

    
8018
class TLReplaceDisks(Tasklet):
8019
  """Replaces disks for an instance.
8020

8021
  Note: Locking is not within the scope of this class.
8022

8023
  """
8024
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
8025
               disks, delay_iallocator, early_release):
8026
    """Initializes this class.
8027

8028
    """
8029
    Tasklet.__init__(self, lu)
8030

    
8031
    # Parameters
8032
    self.instance_name = instance_name
8033
    self.mode = mode
8034
    self.iallocator_name = iallocator_name
8035
    self.remote_node = remote_node
8036
    self.disks = disks
8037
    self.delay_iallocator = delay_iallocator
8038
    self.early_release = early_release
8039

    
8040
    # Runtime data
8041
    self.instance = None
8042
    self.new_node = None
8043
    self.target_node = None
8044
    self.other_node = None
8045
    self.remote_node_info = None
8046
    self.node_secondary_ip = None
8047

    
8048
  @staticmethod
8049
  def CheckArguments(mode, remote_node, iallocator):
8050
    """Helper function for users of this class.
8051

8052
    """
8053
    # check for valid parameter combination
8054
    if mode == constants.REPLACE_DISK_CHG:
8055
      if remote_node is None and iallocator is None:
8056
        raise errors.OpPrereqError("When changing the secondary either an"
8057
                                   " iallocator script must be used or the"
8058
                                   " new node given", errors.ECODE_INVAL)
8059

    
8060
      if remote_node is not None and iallocator is not None:
8061
        raise errors.OpPrereqError("Give either the iallocator or the new"
8062
                                   " secondary, not both", errors.ECODE_INVAL)
8063

    
8064
    elif remote_node is not None or iallocator is not None:
8065
      # Not replacing the secondary
8066
      raise errors.OpPrereqError("The iallocator and new node options can"
8067
                                 " only be used when changing the"
8068
                                 " secondary node", errors.ECODE_INVAL)
8069

    
8070
  @staticmethod
8071
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
8072
    """Compute a new secondary node using an IAllocator.
8073

8074
    """
8075
    ial = IAllocator(lu.cfg, lu.rpc,
8076
                     mode=constants.IALLOCATOR_MODE_RELOC,
8077
                     name=instance_name,
8078
                     relocate_from=relocate_from)
8079

    
8080
    ial.Run(iallocator_name)
8081

    
8082
    if not ial.success:
8083
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
8084
                                 " %s" % (iallocator_name, ial.info),
8085
                                 errors.ECODE_NORES)
8086

    
8087
    if len(ial.result) != ial.required_nodes:
8088
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
8089
                                 " of nodes (%s), required %s" %
8090
                                 (iallocator_name,
8091
                                  len(ial.result), ial.required_nodes),
8092
                                 errors.ECODE_FAULT)
8093

    
8094
    remote_node_name = ial.result[0]
8095

    
8096
    lu.LogInfo("Selected new secondary for instance '%s': %s",
8097
               instance_name, remote_node_name)
8098

    
8099
    return remote_node_name
8100

    
8101
  def _FindFaultyDisks(self, node_name):
8102
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
8103
                                    node_name, True)
8104

    
8105
  def CheckPrereq(self):
8106
    """Check prerequisites.
8107

8108
    This checks that the instance is in the cluster.
8109

8110
    """
8111
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
8112
    assert instance is not None, \
8113
      "Cannot retrieve locked instance %s" % self.instance_name
8114

    
8115
    if instance.disk_template != constants.DT_DRBD8:
8116
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
8117
                                 " instances", errors.ECODE_INVAL)
8118

    
8119
    if len(instance.secondary_nodes) != 1:
8120
      raise errors.OpPrereqError("The instance has a strange layout,"
8121
                                 " expected one secondary but found %d" %
8122
                                 len(instance.secondary_nodes),
8123
                                 errors.ECODE_FAULT)
8124

    
8125
    if not self.delay_iallocator:
8126
      self._CheckPrereq2()
8127

    
8128
  def _CheckPrereq2(self):
8129
    """Check prerequisites, second part.
8130

8131
    This function should always be part of CheckPrereq. It was separated and is
8132
    now called from Exec because during node evacuation iallocator was only
8133
    called with an unmodified cluster model, not taking planned changes into
8134
    account.
8135

8136
    """
8137
    instance = self.instance
8138
    secondary_node = instance.secondary_nodes[0]
8139

    
8140
    if self.iallocator_name is None:
8141
      remote_node = self.remote_node
8142
    else:
8143
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
8144
                                       instance.name, instance.secondary_nodes)
8145

    
8146
    if remote_node is not None:
8147
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
8148
      assert self.remote_node_info is not None, \
8149
        "Cannot retrieve locked node %s" % remote_node
8150
    else:
8151
      self.remote_node_info = None
8152

    
8153
    if remote_node == self.instance.primary_node:
8154
      raise errors.OpPrereqError("The specified node is the primary node of"
8155
                                 " the instance.", errors.ECODE_INVAL)
8156

    
8157
    if remote_node == secondary_node:
8158
      raise errors.OpPrereqError("The specified node is already the"
8159
                                 " secondary node of the instance.",
8160
                                 errors.ECODE_INVAL)
8161

    
8162
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
8163
                                    constants.REPLACE_DISK_CHG):
8164
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
8165
                                 errors.ECODE_INVAL)
8166

    
8167
    if self.mode == constants.REPLACE_DISK_AUTO:
8168
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
8169
      faulty_secondary = self._FindFaultyDisks(secondary_node)
8170

    
8171
      if faulty_primary and faulty_secondary:
8172
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
8173
                                   " one node and can not be repaired"
8174
                                   " automatically" % self.instance_name,
8175
                                   errors.ECODE_STATE)
8176

    
8177
      if faulty_primary:
8178
        self.disks = faulty_primary
8179
        self.target_node = instance.primary_node
8180
        self.other_node = secondary_node
8181
        check_nodes = [self.target_node, self.other_node]
8182
      elif faulty_secondary:
8183
        self.disks = faulty_secondary
8184
        self.target_node = secondary_node
8185
        self.other_node = instance.primary_node
8186
        check_nodes = [self.target_node, self.other_node]
8187
      else:
8188
        self.disks = []
8189
        check_nodes = []
8190

    
8191
    else:
8192
      # Non-automatic modes
8193
      if self.mode == constants.REPLACE_DISK_PRI:
8194
        self.target_node = instance.primary_node
8195
        self.other_node = secondary_node
8196
        check_nodes = [self.target_node, self.other_node]
8197

    
8198
      elif self.mode == constants.REPLACE_DISK_SEC:
8199
        self.target_node = secondary_node
8200
        self.other_node = instance.primary_node
8201
        check_nodes = [self.target_node, self.other_node]
8202

    
8203
      elif self.mode == constants.REPLACE_DISK_CHG:
8204
        self.new_node = remote_node
8205
        self.other_node = instance.primary_node
8206
        self.target_node = secondary_node
8207
        check_nodes = [self.new_node, self.other_node]
8208

    
8209
        _CheckNodeNotDrained(self.lu, remote_node)
8210
        _CheckNodeVmCapable(self.lu, remote_node)
8211

    
8212
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
8213
        assert old_node_info is not None
8214
        if old_node_info.offline and not self.early_release:
8215
          # doesn't make sense to delay the release
8216
          self.early_release = True
8217
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
8218
                          " early-release mode", secondary_node)
8219

    
8220
      else:
8221
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
8222
                                     self.mode)
8223

    
8224
      # If not specified all disks should be replaced
8225
      if not self.disks:
8226
        self.disks = range(len(self.instance.disks))
8227

    
8228
    for node in check_nodes:
8229
      _CheckNodeOnline(self.lu, node)
8230

    
8231
    touched_nodes = frozenset([self.new_node, self.other_node,
8232
                               self.target_node])
8233

    
8234
    if self.lu.needed_locks[locking.LEVEL_NODE] == locking.ALL_SET:
8235
      # Release unneeded node locks
8236
      for name in self.lu.acquired_locks[locking.LEVEL_NODE]:
8237
        if name not in touched_nodes:
8238
          self._ReleaseNodeLock(name)
8239

    
8240
    # Check whether disks are valid
8241
    for disk_idx in self.disks:
8242
      instance.FindDisk(disk_idx)
8243

    
8244
    # Get secondary node IP addresses
8245
    self.node_secondary_ip = \
8246
      dict((node_name, self.cfg.GetNodeInfo(node_name).secondary_ip)
8247
           for node_name in touched_nodes
8248
           if node_name is not None)
8249

    
8250
  def Exec(self, feedback_fn):
8251
    """Execute disk replacement.
8252

8253
    This dispatches the disk replacement to the appropriate handler.
8254

8255
    """
8256
    if self.delay_iallocator:
8257
      self._CheckPrereq2()
8258

    
8259
    if (self.lu.needed_locks[locking.LEVEL_NODE] == locking.ALL_SET and
8260
        __debug__):
8261
      # Verify owned locks before starting operation
8262
      owned_locks = self.lu.context.glm.list_owned(locking.LEVEL_NODE)
8263
      assert set(owned_locks) == set(self.node_secondary_ip), \
8264
          "Not owning the correct locks: %s" % (owned_locks, )
8265

    
8266
    if not self.disks:
8267
      feedback_fn("No disks need replacement")
8268
      return
8269

    
8270
    feedback_fn("Replacing disk(s) %s for %s" %
8271
                (utils.CommaJoin(self.disks), self.instance.name))
8272

    
8273
    activate_disks = (not self.instance.admin_up)
8274

    
8275
    # Activate the instance disks if we're replacing them on a down instance
8276
    if activate_disks:
8277
      _StartInstanceDisks(self.lu, self.instance, True)
8278

    
8279
    try:
8280
      # Should we replace the secondary node?
8281
      if self.new_node is not None:
8282
        fn = self._ExecDrbd8Secondary
8283
      else:
8284
        fn = self._ExecDrbd8DiskOnly
8285

    
8286
      return fn(feedback_fn)
8287

    
8288
    finally:
8289
      # Deactivate the instance disks if we're replacing them on a
8290
      # down instance
8291
      if activate_disks:
8292
        _SafeShutdownInstanceDisks(self.lu, self.instance)
8293

    
8294
      if __debug__:
8295
        # Verify owned locks
8296
        owned_locks = self.lu.context.glm.list_owned(locking.LEVEL_NODE)
8297
        assert ((self.early_release and not owned_locks) or
8298
                (not self.early_release and
8299
                 set(owned_locks) == set(self.node_secondary_ip))), \
8300
          ("Not owning the correct locks, early_release=%s, owned=%r" %
8301
           (self.early_release, owned_locks))
8302

    
8303
  def _CheckVolumeGroup(self, nodes):
8304
    self.lu.LogInfo("Checking volume groups")
8305

    
8306
    vgname = self.cfg.GetVGName()
8307

    
8308
    # Make sure volume group exists on all involved nodes
8309
    results = self.rpc.call_vg_list(nodes)
8310
    if not results:
8311
      raise errors.OpExecError("Can't list volume groups on the nodes")
8312

    
8313
    for node in nodes:
8314
      res = results[node]
8315
      res.Raise("Error checking node %s" % node)
8316
      if vgname not in res.payload:
8317
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
8318
                                 (vgname, node))
8319

    
8320
  def _CheckDisksExistence(self, nodes):
8321
    # Check disk existence
8322
    for idx, dev in enumerate(self.instance.disks):
8323
      if idx not in self.disks:
8324
        continue
8325

    
8326
      for node in nodes:
8327
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
8328
        self.cfg.SetDiskID(dev, node)
8329

    
8330
        result = self.rpc.call_blockdev_find(node, dev)
8331

    
8332
        msg = result.fail_msg
8333
        if msg or not result.payload:
8334
          if not msg:
8335
            msg = "disk not found"
8336
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
8337
                                   (idx, node, msg))
8338

    
8339
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
8340
    for idx, dev in enumerate(self.instance.disks):
8341
      if idx not in self.disks:
8342
        continue
8343

    
8344
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
8345
                      (idx, node_name))
8346

    
8347
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
8348
                                   ldisk=ldisk):
8349
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
8350
                                 " replace disks for instance %s" %
8351
                                 (node_name, self.instance.name))
8352

    
8353
  def _CreateNewStorage(self, node_name):
8354
    iv_names = {}
8355

    
8356
    for idx, dev in enumerate(self.instance.disks):
8357
      if idx not in self.disks:
8358
        continue
8359

    
8360
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
8361

    
8362
      self.cfg.SetDiskID(dev, node_name)
8363

    
8364
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
8365
      names = _GenerateUniqueNames(self.lu, lv_names)
8366

    
8367
      vg_data = dev.children[0].logical_id[0]
8368
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
8369
                             logical_id=(vg_data, names[0]))
8370
      vg_meta = dev.children[1].logical_id[0]
8371
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
8372
                             logical_id=(vg_meta, names[1]))
8373

    
8374
      new_lvs = [lv_data, lv_meta]
8375
      old_lvs = dev.children
8376
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
8377

    
8378
      # we pass force_create=True to force the LVM creation
8379
      for new_lv in new_lvs:
8380
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
8381
                        _GetInstanceInfoText(self.instance), False)
8382

    
8383
    return iv_names
8384

    
8385
  def _CheckDevices(self, node_name, iv_names):
8386
    for name, (dev, _, _) in iv_names.iteritems():
8387
      self.cfg.SetDiskID(dev, node_name)
8388

    
8389
      result = self.rpc.call_blockdev_find(node_name, dev)
8390

    
8391
      msg = result.fail_msg
8392
      if msg or not result.payload:
8393
        if not msg:
8394
          msg = "disk not found"
8395
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
8396
                                 (name, msg))
8397

    
8398
      if result.payload.is_degraded:
8399
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
8400

    
8401
  def _RemoveOldStorage(self, node_name, iv_names):
8402
    for name, (_, old_lvs, _) in iv_names.iteritems():
8403
      self.lu.LogInfo("Remove logical volumes for %s" % name)
8404

    
8405
      for lv in old_lvs:
8406
        self.cfg.SetDiskID(lv, node_name)
8407

    
8408
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
8409
        if msg:
8410
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
8411
                             hint="remove unused LVs manually")
8412

    
8413
  def _ReleaseNodeLock(self, node_name):
8414
    """Releases the lock for a given node."""
8415
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
8416

    
8417
  def _ExecDrbd8DiskOnly(self, feedback_fn):
8418
    """Replace a disk on the primary or secondary for DRBD 8.
8419

8420
    The algorithm for replace is quite complicated:
8421

8422
      1. for each disk to be replaced:
8423

8424
        1. create new LVs on the target node with unique names
8425
        1. detach old LVs from the drbd device
8426
        1. rename old LVs to name_replaced.<time_t>
8427
        1. rename new LVs to old LVs
8428
        1. attach the new LVs (with the old names now) to the drbd device
8429

8430
      1. wait for sync across all devices
8431

8432
      1. for each modified disk:
8433

8434
        1. remove old LVs (which have the name name_replaces.<time_t>)
8435

8436
    Failures are not very well handled.
8437

8438
    """
8439
    steps_total = 6
8440

    
8441
    # Step: check device activation
8442
    self.lu.LogStep(1, steps_total, "Check device existence")
8443
    self._CheckDisksExistence([self.other_node, self.target_node])
8444
    self._CheckVolumeGroup([self.target_node, self.other_node])
8445

    
8446
    # Step: check other node consistency
8447
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8448
    self._CheckDisksConsistency(self.other_node,
8449
                                self.other_node == self.instance.primary_node,
8450
                                False)
8451

    
8452
    # Step: create new storage
8453
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8454
    iv_names = self._CreateNewStorage(self.target_node)
8455

    
8456
    # Step: for each lv, detach+rename*2+attach
8457
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8458
    for dev, old_lvs, new_lvs in iv_names.itervalues():
8459
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
8460

    
8461
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
8462
                                                     old_lvs)
8463
      result.Raise("Can't detach drbd from local storage on node"
8464
                   " %s for device %s" % (self.target_node, dev.iv_name))
8465
      #dev.children = []
8466
      #cfg.Update(instance)
8467

    
8468
      # ok, we created the new LVs, so now we know we have the needed
8469
      # storage; as such, we proceed on the target node to rename
8470
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
8471
      # using the assumption that logical_id == physical_id (which in
8472
      # turn is the unique_id on that node)
8473

    
8474
      # FIXME(iustin): use a better name for the replaced LVs
8475
      temp_suffix = int(time.time())
8476
      ren_fn = lambda d, suff: (d.physical_id[0],
8477
                                d.physical_id[1] + "_replaced-%s" % suff)
8478

    
8479
      # Build the rename list based on what LVs exist on the node
8480
      rename_old_to_new = []
8481
      for to_ren in old_lvs:
8482
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
8483
        if not result.fail_msg and result.payload:
8484
          # device exists
8485
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
8486

    
8487
      self.lu.LogInfo("Renaming the old LVs on the target node")
8488
      result = self.rpc.call_blockdev_rename(self.target_node,
8489
                                             rename_old_to_new)
8490
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
8491

    
8492
      # Now we rename the new LVs to the old LVs
8493
      self.lu.LogInfo("Renaming the new LVs on the target node")
8494
      rename_new_to_old = [(new, old.physical_id)
8495
                           for old, new in zip(old_lvs, new_lvs)]
8496
      result = self.rpc.call_blockdev_rename(self.target_node,
8497
                                             rename_new_to_old)
8498
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
8499

    
8500
      for old, new in zip(old_lvs, new_lvs):
8501
        new.logical_id = old.logical_id
8502
        self.cfg.SetDiskID(new, self.target_node)
8503

    
8504
      for disk in old_lvs:
8505
        disk.logical_id = ren_fn(disk, temp_suffix)
8506
        self.cfg.SetDiskID(disk, self.target_node)
8507

    
8508
      # Now that the new lvs have the old name, we can add them to the device
8509
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
8510
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
8511
                                                  new_lvs)
8512
      msg = result.fail_msg
8513
      if msg:
8514
        for new_lv in new_lvs:
8515
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
8516
                                               new_lv).fail_msg
8517
          if msg2:
8518
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
8519
                               hint=("cleanup manually the unused logical"
8520
                                     "volumes"))
8521
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8522

    
8523
      dev.children = new_lvs
8524

    
8525
      self.cfg.Update(self.instance, feedback_fn)
8526

    
8527
    cstep = 5
8528
    if self.early_release:
8529
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8530
      cstep += 1
8531
      self._RemoveOldStorage(self.target_node, iv_names)
8532
      # WARNING: we release both node locks here, do not do other RPCs
8533
      # than WaitForSync to the primary node
8534
      self._ReleaseNodeLock([self.target_node, self.other_node])
8535

    
8536
    # Wait for sync
8537
    # This can fail as the old devices are degraded and _WaitForSync
8538
    # does a combined result over all disks, so we don't check its return value
8539
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8540
    cstep += 1
8541
    _WaitForSync(self.lu, self.instance)
8542

    
8543
    # Check all devices manually
8544
    self._CheckDevices(self.instance.primary_node, iv_names)
8545

    
8546
    # Step: remove old storage
8547
    if not self.early_release:
8548
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8549
      cstep += 1
8550
      self._RemoveOldStorage(self.target_node, iv_names)
8551

    
8552
  def _ExecDrbd8Secondary(self, feedback_fn):
8553
    """Replace the secondary node for DRBD 8.
8554

8555
    The algorithm for replace is quite complicated:
8556
      - for all disks of the instance:
8557
        - create new LVs on the new node with same names
8558
        - shutdown the drbd device on the old secondary
8559
        - disconnect the drbd network on the primary
8560
        - create the drbd device on the new secondary
8561
        - network attach the drbd on the primary, using an artifice:
8562
          the drbd code for Attach() will connect to the network if it
8563
          finds a device which is connected to the good local disks but
8564
          not network enabled
8565
      - wait for sync across all devices
8566
      - remove all disks from the old secondary
8567

8568
    Failures are not very well handled.
8569

8570
    """
8571
    steps_total = 6
8572

    
8573
    # Step: check device activation
8574
    self.lu.LogStep(1, steps_total, "Check device existence")
8575
    self._CheckDisksExistence([self.instance.primary_node])
8576
    self._CheckVolumeGroup([self.instance.primary_node])
8577

    
8578
    # Step: check other node consistency
8579
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8580
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8581

    
8582
    # Step: create new storage
8583
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8584
    for idx, dev in enumerate(self.instance.disks):
8585
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8586
                      (self.new_node, idx))
8587
      # we pass force_create=True to force LVM creation
8588
      for new_lv in dev.children:
8589
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8590
                        _GetInstanceInfoText(self.instance), False)
8591

    
8592
    # Step 4: dbrd minors and drbd setups changes
8593
    # after this, we must manually remove the drbd minors on both the
8594
    # error and the success paths
8595
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8596
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8597
                                         for dev in self.instance.disks],
8598
                                        self.instance.name)
8599
    logging.debug("Allocated minors %r", minors)
8600

    
8601
    iv_names = {}
8602
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8603
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8604
                      (self.new_node, idx))
8605
      # create new devices on new_node; note that we create two IDs:
8606
      # one without port, so the drbd will be activated without
8607
      # networking information on the new node at this stage, and one
8608
      # with network, for the latter activation in step 4
8609
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8610
      if self.instance.primary_node == o_node1:
8611
        p_minor = o_minor1
8612
      else:
8613
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8614
        p_minor = o_minor2
8615

    
8616
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8617
                      p_minor, new_minor, o_secret)
8618
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8619
                    p_minor, new_minor, o_secret)
8620

    
8621
      iv_names[idx] = (dev, dev.children, new_net_id)
8622
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8623
                    new_net_id)
8624
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8625
                              logical_id=new_alone_id,
8626
                              children=dev.children,
8627
                              size=dev.size)
8628
      try:
8629
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8630
                              _GetInstanceInfoText(self.instance), False)
8631
      except errors.GenericError:
8632
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8633
        raise
8634

    
8635
    # We have new devices, shutdown the drbd on the old secondary
8636
    for idx, dev in enumerate(self.instance.disks):
8637
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8638
      self.cfg.SetDiskID(dev, self.target_node)
8639
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8640
      if msg:
8641
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8642
                           "node: %s" % (idx, msg),
8643
                           hint=("Please cleanup this device manually as"
8644
                                 " soon as possible"))
8645

    
8646
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8647
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8648
                                               self.node_secondary_ip,
8649
                                               self.instance.disks)\
8650
                                              [self.instance.primary_node]
8651

    
8652
    msg = result.fail_msg
8653
    if msg:
8654
      # detaches didn't succeed (unlikely)
8655
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8656
      raise errors.OpExecError("Can't detach the disks from the network on"
8657
                               " old node: %s" % (msg,))
8658

    
8659
    # if we managed to detach at least one, we update all the disks of
8660
    # the instance to point to the new secondary
8661
    self.lu.LogInfo("Updating instance configuration")
8662
    for dev, _, new_logical_id in iv_names.itervalues():
8663
      dev.logical_id = new_logical_id
8664
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8665

    
8666
    self.cfg.Update(self.instance, feedback_fn)
8667

    
8668
    # and now perform the drbd attach
8669
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8670
                    " (standalone => connected)")
8671
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8672
                                            self.new_node],
8673
                                           self.node_secondary_ip,
8674
                                           self.instance.disks,
8675
                                           self.instance.name,
8676
                                           False)
8677
    for to_node, to_result in result.items():
8678
      msg = to_result.fail_msg
8679
      if msg:
8680
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8681
                           to_node, msg,
8682
                           hint=("please do a gnt-instance info to see the"
8683
                                 " status of disks"))
8684
    cstep = 5
8685
    if self.early_release:
8686
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8687
      cstep += 1
8688
      self._RemoveOldStorage(self.target_node, iv_names)
8689
      # WARNING: we release all node locks here, do not do other RPCs
8690
      # than WaitForSync to the primary node
8691
      self._ReleaseNodeLock([self.instance.primary_node,
8692
                             self.target_node,
8693
                             self.new_node])
8694

    
8695
    # Wait for sync
8696
    # This can fail as the old devices are degraded and _WaitForSync
8697
    # does a combined result over all disks, so we don't check its return value
8698
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8699
    cstep += 1
8700
    _WaitForSync(self.lu, self.instance)
8701

    
8702
    # Check all devices manually
8703
    self._CheckDevices(self.instance.primary_node, iv_names)
8704

    
8705
    # Step: remove old storage
8706
    if not self.early_release:
8707
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8708
      self._RemoveOldStorage(self.target_node, iv_names)
8709

    
8710

    
8711
class LURepairNodeStorage(NoHooksLU):
8712
  """Repairs the volume group on a node.
8713

8714
  """
8715
  REQ_BGL = False
8716

    
8717
  def CheckArguments(self):
8718
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8719

    
8720
    storage_type = self.op.storage_type
8721

    
8722
    if (constants.SO_FIX_CONSISTENCY not in
8723
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8724
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8725
                                 " repaired" % storage_type,
8726
                                 errors.ECODE_INVAL)
8727

    
8728
  def ExpandNames(self):
8729
    self.needed_locks = {
8730
      locking.LEVEL_NODE: [self.op.node_name],
8731
      }
8732

    
8733
  def _CheckFaultyDisks(self, instance, node_name):
8734
    """Ensure faulty disks abort the opcode or at least warn."""
8735
    try:
8736
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8737
                                  node_name, True):
8738
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8739
                                   " node '%s'" % (instance.name, node_name),
8740
                                   errors.ECODE_STATE)
8741
    except errors.OpPrereqError, err:
8742
      if self.op.ignore_consistency:
8743
        self.proc.LogWarning(str(err.args[0]))
8744
      else:
8745
        raise
8746

    
8747
  def CheckPrereq(self):
8748
    """Check prerequisites.
8749

8750
    """
8751
    # Check whether any instance on this node has faulty disks
8752
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8753
      if not inst.admin_up:
8754
        continue
8755
      check_nodes = set(inst.all_nodes)
8756
      check_nodes.discard(self.op.node_name)
8757
      for inst_node_name in check_nodes:
8758
        self._CheckFaultyDisks(inst, inst_node_name)
8759

    
8760
  def Exec(self, feedback_fn):
8761
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8762
                (self.op.name, self.op.node_name))
8763

    
8764
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8765
    result = self.rpc.call_storage_execute(self.op.node_name,
8766
                                           self.op.storage_type, st_args,
8767
                                           self.op.name,
8768
                                           constants.SO_FIX_CONSISTENCY)
8769
    result.Raise("Failed to repair storage unit '%s' on %s" %
8770
                 (self.op.name, self.op.node_name))
8771

    
8772

    
8773
class LUNodeEvacStrategy(NoHooksLU):
8774
  """Computes the node evacuation strategy.
8775

8776
  """
8777
  REQ_BGL = False
8778

    
8779
  def CheckArguments(self):
8780
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8781

    
8782
  def ExpandNames(self):
8783
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8784
    self.needed_locks = locks = {}
8785
    if self.op.remote_node is None:
8786
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8787
    else:
8788
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8789
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8790

    
8791
  def Exec(self, feedback_fn):
8792
    if self.op.remote_node is not None:
8793
      instances = []
8794
      for node in self.op.nodes:
8795
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8796
      result = []
8797
      for i in instances:
8798
        if i.primary_node == self.op.remote_node:
8799
          raise errors.OpPrereqError("Node %s is the primary node of"
8800
                                     " instance %s, cannot use it as"
8801
                                     " secondary" %
8802
                                     (self.op.remote_node, i.name),
8803
                                     errors.ECODE_INVAL)
8804
        result.append([i.name, self.op.remote_node])
8805
    else:
8806
      ial = IAllocator(self.cfg, self.rpc,
8807
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8808
                       evac_nodes=self.op.nodes)
8809
      ial.Run(self.op.iallocator, validate=True)
8810
      if not ial.success:
8811
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8812
                                 errors.ECODE_NORES)
8813
      result = ial.result
8814
    return result
8815

    
8816

    
8817
class LUInstanceGrowDisk(LogicalUnit):
8818
  """Grow a disk of an instance.
8819

8820
  """
8821
  HPATH = "disk-grow"
8822
  HTYPE = constants.HTYPE_INSTANCE
8823
  REQ_BGL = False
8824

    
8825
  def ExpandNames(self):
8826
    self._ExpandAndLockInstance()
8827
    self.needed_locks[locking.LEVEL_NODE] = []
8828
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8829

    
8830
  def DeclareLocks(self, level):
8831
    if level == locking.LEVEL_NODE:
8832
      self._LockInstancesNodes()
8833

    
8834
  def BuildHooksEnv(self):
8835
    """Build hooks env.
8836

8837
    This runs on the master, the primary and all the secondaries.
8838

8839
    """
8840
    env = {
8841
      "DISK": self.op.disk,
8842
      "AMOUNT": self.op.amount,
8843
      }
8844
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8845
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8846
    return env, nl, nl
8847

    
8848
  def CheckPrereq(self):
8849
    """Check prerequisites.
8850

8851
    This checks that the instance is in the cluster.
8852

8853
    """
8854
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8855
    assert instance is not None, \
8856
      "Cannot retrieve locked instance %s" % self.op.instance_name
8857
    nodenames = list(instance.all_nodes)
8858
    for node in nodenames:
8859
      _CheckNodeOnline(self, node)
8860

    
8861
    self.instance = instance
8862

    
8863
    if instance.disk_template not in constants.DTS_GROWABLE:
8864
      raise errors.OpPrereqError("Instance's disk layout does not support"
8865
                                 " growing.", errors.ECODE_INVAL)
8866

    
8867
    self.disk = instance.FindDisk(self.op.disk)
8868

    
8869
    if instance.disk_template != constants.DT_FILE:
8870
      # TODO: check the free disk space for file, when that feature
8871
      # will be supported
8872
      _CheckNodesFreeDiskPerVG(self, nodenames,
8873
                               self.disk.ComputeGrowth(self.op.amount))
8874

    
8875
  def Exec(self, feedback_fn):
8876
    """Execute disk grow.
8877

8878
    """
8879
    instance = self.instance
8880
    disk = self.disk
8881

    
8882
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8883
    if not disks_ok:
8884
      raise errors.OpExecError("Cannot activate block device to grow")
8885

    
8886
    for node in instance.all_nodes:
8887
      self.cfg.SetDiskID(disk, node)
8888
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8889
      result.Raise("Grow request failed to node %s" % node)
8890

    
8891
      # TODO: Rewrite code to work properly
8892
      # DRBD goes into sync mode for a short amount of time after executing the
8893
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8894
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8895
      # time is a work-around.
8896
      time.sleep(5)
8897

    
8898
    disk.RecordGrow(self.op.amount)
8899
    self.cfg.Update(instance, feedback_fn)
8900
    if self.op.wait_for_sync:
8901
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8902
      if disk_abort:
8903
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8904
                             " status.\nPlease check the instance.")
8905
      if not instance.admin_up:
8906
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8907
    elif not instance.admin_up:
8908
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8909
                           " not supposed to be running because no wait for"
8910
                           " sync mode was requested.")
8911

    
8912

    
8913
class LUInstanceQueryData(NoHooksLU):
8914
  """Query runtime instance data.
8915

8916
  """
8917
  REQ_BGL = False
8918

    
8919
  def ExpandNames(self):
8920
    self.needed_locks = {}
8921

    
8922
    # Use locking if requested or when non-static information is wanted
8923
    if not (self.op.static or self.op.use_locking):
8924
      self.LogWarning("Non-static data requested, locks need to be acquired")
8925
      self.op.use_locking = True
8926

    
8927
    if self.op.instances or not self.op.use_locking:
8928
      # Expand instance names right here
8929
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
8930
    else:
8931
      # Will use acquired locks
8932
      self.wanted_names = None
8933

    
8934
    if self.op.use_locking:
8935
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8936

    
8937
      if self.wanted_names is None:
8938
        self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8939
      else:
8940
        self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8941

    
8942
      self.needed_locks[locking.LEVEL_NODE] = []
8943
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8944
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8945

    
8946
  def DeclareLocks(self, level):
8947
    if self.op.use_locking and level == locking.LEVEL_NODE:
8948
      self._LockInstancesNodes()
8949

    
8950
  def CheckPrereq(self):
8951
    """Check prerequisites.
8952

8953
    This only checks the optional instance list against the existing names.
8954

8955
    """
8956
    if self.wanted_names is None:
8957
      assert self.op.use_locking, "Locking was not used"
8958
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8959

    
8960
    self.wanted_instances = [self.cfg.GetInstanceInfo(name)
8961
                             for name in self.wanted_names]
8962

    
8963
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8964
    """Returns the status of a block device
8965

8966
    """
8967
    if self.op.static or not node:
8968
      return None
8969

    
8970
    self.cfg.SetDiskID(dev, node)
8971

    
8972
    result = self.rpc.call_blockdev_find(node, dev)
8973
    if result.offline:
8974
      return None
8975

    
8976
    result.Raise("Can't compute disk status for %s" % instance_name)
8977

    
8978
    status = result.payload
8979
    if status is None:
8980
      return None
8981

    
8982
    return (status.dev_path, status.major, status.minor,
8983
            status.sync_percent, status.estimated_time,
8984
            status.is_degraded, status.ldisk_status)
8985

    
8986
  def _ComputeDiskStatus(self, instance, snode, dev):
8987
    """Compute block device status.
8988

8989
    """
8990
    if dev.dev_type in constants.LDS_DRBD:
8991
      # we change the snode then (otherwise we use the one passed in)
8992
      if dev.logical_id[0] == instance.primary_node:
8993
        snode = dev.logical_id[1]
8994
      else:
8995
        snode = dev.logical_id[0]
8996

    
8997
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8998
                                              instance.name, dev)
8999
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
9000

    
9001
    if dev.children:
9002
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
9003
                      for child in dev.children]
9004
    else:
9005
      dev_children = []
9006

    
9007
    return {
9008
      "iv_name": dev.iv_name,
9009
      "dev_type": dev.dev_type,
9010
      "logical_id": dev.logical_id,
9011
      "physical_id": dev.physical_id,
9012
      "pstatus": dev_pstatus,
9013
      "sstatus": dev_sstatus,
9014
      "children": dev_children,
9015
      "mode": dev.mode,
9016
      "size": dev.size,
9017
      }
9018

    
9019
  def Exec(self, feedback_fn):
9020
    """Gather and return data"""
9021
    result = {}
9022

    
9023
    cluster = self.cfg.GetClusterInfo()
9024

    
9025
    for instance in self.wanted_instances:
9026
      if not self.op.static:
9027
        remote_info = self.rpc.call_instance_info(instance.primary_node,
9028
                                                  instance.name,
9029
                                                  instance.hypervisor)
9030
        remote_info.Raise("Error checking node %s" % instance.primary_node)
9031
        remote_info = remote_info.payload
9032
        if remote_info and "state" in remote_info:
9033
          remote_state = "up"
9034
        else:
9035
          remote_state = "down"
9036
      else:
9037
        remote_state = None
9038
      if instance.admin_up:
9039
        config_state = "up"
9040
      else:
9041
        config_state = "down"
9042

    
9043
      disks = [self._ComputeDiskStatus(instance, None, device)
9044
               for device in instance.disks]
9045

    
9046
      result[instance.name] = {
9047
        "name": instance.name,
9048
        "config_state": config_state,
9049
        "run_state": remote_state,
9050
        "pnode": instance.primary_node,
9051
        "snodes": instance.secondary_nodes,
9052
        "os": instance.os,
9053
        # this happens to be the same format used for hooks
9054
        "nics": _NICListToTuple(self, instance.nics),
9055
        "disk_template": instance.disk_template,
9056
        "disks": disks,
9057
        "hypervisor": instance.hypervisor,
9058
        "network_port": instance.network_port,
9059
        "hv_instance": instance.hvparams,
9060
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
9061
        "be_instance": instance.beparams,
9062
        "be_actual": cluster.FillBE(instance),
9063
        "os_instance": instance.osparams,
9064
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
9065
        "serial_no": instance.serial_no,
9066
        "mtime": instance.mtime,
9067
        "ctime": instance.ctime,
9068
        "uuid": instance.uuid,
9069
        }
9070

    
9071
    return result
9072

    
9073

    
9074
class LUInstanceSetParams(LogicalUnit):
9075
  """Modifies an instances's parameters.
9076

9077
  """
9078
  HPATH = "instance-modify"
9079
  HTYPE = constants.HTYPE_INSTANCE
9080
  REQ_BGL = False
9081

    
9082
  def CheckArguments(self):
9083
    if not (self.op.nics or self.op.disks or self.op.disk_template or
9084
            self.op.hvparams or self.op.beparams or self.op.os_name):
9085
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
9086

    
9087
    if self.op.hvparams:
9088
      _CheckGlobalHvParams(self.op.hvparams)
9089

    
9090
    # Disk validation
9091
    disk_addremove = 0
9092
    for disk_op, disk_dict in self.op.disks:
9093
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
9094
      if disk_op == constants.DDM_REMOVE:
9095
        disk_addremove += 1
9096
        continue
9097
      elif disk_op == constants.DDM_ADD:
9098
        disk_addremove += 1
9099
      else:
9100
        if not isinstance(disk_op, int):
9101
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
9102
        if not isinstance(disk_dict, dict):
9103
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
9104
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9105

    
9106
      if disk_op == constants.DDM_ADD:
9107
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
9108
        if mode not in constants.DISK_ACCESS_SET:
9109
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
9110
                                     errors.ECODE_INVAL)
9111
        size = disk_dict.get('size', None)
9112
        if size is None:
9113
          raise errors.OpPrereqError("Required disk parameter size missing",
9114
                                     errors.ECODE_INVAL)
9115
        try:
9116
          size = int(size)
9117
        except (TypeError, ValueError), err:
9118
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
9119
                                     str(err), errors.ECODE_INVAL)
9120
        disk_dict['size'] = size
9121
      else:
9122
        # modification of disk
9123
        if 'size' in disk_dict:
9124
          raise errors.OpPrereqError("Disk size change not possible, use"
9125
                                     " grow-disk", errors.ECODE_INVAL)
9126

    
9127
    if disk_addremove > 1:
9128
      raise errors.OpPrereqError("Only one disk add or remove operation"
9129
                                 " supported at a time", errors.ECODE_INVAL)
9130

    
9131
    if self.op.disks and self.op.disk_template is not None:
9132
      raise errors.OpPrereqError("Disk template conversion and other disk"
9133
                                 " changes not supported at the same time",
9134
                                 errors.ECODE_INVAL)
9135

    
9136
    if (self.op.disk_template and
9137
        self.op.disk_template in constants.DTS_NET_MIRROR and
9138
        self.op.remote_node is None):
9139
      raise errors.OpPrereqError("Changing the disk template to a mirrored"
9140
                                 " one requires specifying a secondary node",
9141
                                 errors.ECODE_INVAL)
9142

    
9143
    # NIC validation
9144
    nic_addremove = 0
9145
    for nic_op, nic_dict in self.op.nics:
9146
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
9147
      if nic_op == constants.DDM_REMOVE:
9148
        nic_addremove += 1
9149
        continue
9150
      elif nic_op == constants.DDM_ADD:
9151
        nic_addremove += 1
9152
      else:
9153
        if not isinstance(nic_op, int):
9154
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
9155
        if not isinstance(nic_dict, dict):
9156
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
9157
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9158

    
9159
      # nic_dict should be a dict
9160
      nic_ip = nic_dict.get('ip', None)
9161
      if nic_ip is not None:
9162
        if nic_ip.lower() == constants.VALUE_NONE:
9163
          nic_dict['ip'] = None
9164
        else:
9165
          if not netutils.IPAddress.IsValid(nic_ip):
9166
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
9167
                                       errors.ECODE_INVAL)
9168

    
9169
      nic_bridge = nic_dict.get('bridge', None)
9170
      nic_link = nic_dict.get('link', None)
9171
      if nic_bridge and nic_link:
9172
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
9173
                                   " at the same time", errors.ECODE_INVAL)
9174
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
9175
        nic_dict['bridge'] = None
9176
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
9177
        nic_dict['link'] = None
9178

    
9179
      if nic_op == constants.DDM_ADD:
9180
        nic_mac = nic_dict.get('mac', None)
9181
        if nic_mac is None:
9182
          nic_dict['mac'] = constants.VALUE_AUTO
9183

    
9184
      if 'mac' in nic_dict:
9185
        nic_mac = nic_dict['mac']
9186
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9187
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
9188

    
9189
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
9190
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
9191
                                     " modifying an existing nic",
9192
                                     errors.ECODE_INVAL)
9193

    
9194
    if nic_addremove > 1:
9195
      raise errors.OpPrereqError("Only one NIC add or remove operation"
9196
                                 " supported at a time", errors.ECODE_INVAL)
9197

    
9198
  def ExpandNames(self):
9199
    self._ExpandAndLockInstance()
9200
    self.needed_locks[locking.LEVEL_NODE] = []
9201
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9202

    
9203
  def DeclareLocks(self, level):
9204
    if level == locking.LEVEL_NODE:
9205
      self._LockInstancesNodes()
9206
      if self.op.disk_template and self.op.remote_node:
9207
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9208
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
9209

    
9210
  def BuildHooksEnv(self):
9211
    """Build hooks env.
9212

9213
    This runs on the master, primary and secondaries.
9214

9215
    """
9216
    args = dict()
9217
    if constants.BE_MEMORY in self.be_new:
9218
      args['memory'] = self.be_new[constants.BE_MEMORY]
9219
    if constants.BE_VCPUS in self.be_new:
9220
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
9221
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
9222
    # information at all.
9223
    if self.op.nics:
9224
      args['nics'] = []
9225
      nic_override = dict(self.op.nics)
9226
      for idx, nic in enumerate(self.instance.nics):
9227
        if idx in nic_override:
9228
          this_nic_override = nic_override[idx]
9229
        else:
9230
          this_nic_override = {}
9231
        if 'ip' in this_nic_override:
9232
          ip = this_nic_override['ip']
9233
        else:
9234
          ip = nic.ip
9235
        if 'mac' in this_nic_override:
9236
          mac = this_nic_override['mac']
9237
        else:
9238
          mac = nic.mac
9239
        if idx in self.nic_pnew:
9240
          nicparams = self.nic_pnew[idx]
9241
        else:
9242
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
9243
        mode = nicparams[constants.NIC_MODE]
9244
        link = nicparams[constants.NIC_LINK]
9245
        args['nics'].append((ip, mac, mode, link))
9246
      if constants.DDM_ADD in nic_override:
9247
        ip = nic_override[constants.DDM_ADD].get('ip', None)
9248
        mac = nic_override[constants.DDM_ADD]['mac']
9249
        nicparams = self.nic_pnew[constants.DDM_ADD]
9250
        mode = nicparams[constants.NIC_MODE]
9251
        link = nicparams[constants.NIC_LINK]
9252
        args['nics'].append((ip, mac, mode, link))
9253
      elif constants.DDM_REMOVE in nic_override:
9254
        del args['nics'][-1]
9255

    
9256
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
9257
    if self.op.disk_template:
9258
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
9259
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9260
    return env, nl, nl
9261

    
9262
  def CheckPrereq(self):
9263
    """Check prerequisites.
9264

9265
    This only checks the instance list against the existing names.
9266

9267
    """
9268
    # checking the new params on the primary/secondary nodes
9269

    
9270
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9271
    cluster = self.cluster = self.cfg.GetClusterInfo()
9272
    assert self.instance is not None, \
9273
      "Cannot retrieve locked instance %s" % self.op.instance_name
9274
    pnode = instance.primary_node
9275
    nodelist = list(instance.all_nodes)
9276

    
9277
    # OS change
9278
    if self.op.os_name and not self.op.force:
9279
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
9280
                      self.op.force_variant)
9281
      instance_os = self.op.os_name
9282
    else:
9283
      instance_os = instance.os
9284

    
9285
    if self.op.disk_template:
9286
      if instance.disk_template == self.op.disk_template:
9287
        raise errors.OpPrereqError("Instance already has disk template %s" %
9288
                                   instance.disk_template, errors.ECODE_INVAL)
9289

    
9290
      if (instance.disk_template,
9291
          self.op.disk_template) not in self._DISK_CONVERSIONS:
9292
        raise errors.OpPrereqError("Unsupported disk template conversion from"
9293
                                   " %s to %s" % (instance.disk_template,
9294
                                                  self.op.disk_template),
9295
                                   errors.ECODE_INVAL)
9296
      _CheckInstanceDown(self, instance, "cannot change disk template")
9297
      if self.op.disk_template in constants.DTS_NET_MIRROR:
9298
        if self.op.remote_node == pnode:
9299
          raise errors.OpPrereqError("Given new secondary node %s is the same"
9300
                                     " as the primary node of the instance" %
9301
                                     self.op.remote_node, errors.ECODE_STATE)
9302
        _CheckNodeOnline(self, self.op.remote_node)
9303
        _CheckNodeNotDrained(self, self.op.remote_node)
9304
        # FIXME: here we assume that the old instance type is DT_PLAIN
9305
        assert instance.disk_template == constants.DT_PLAIN
9306
        disks = [{"size": d.size, "vg": d.logical_id[0]}
9307
                 for d in instance.disks]
9308
        required = _ComputeDiskSizePerVG(self.op.disk_template, disks)
9309
        _CheckNodesFreeDiskPerVG(self, [self.op.remote_node], required)
9310

    
9311
    # hvparams processing
9312
    if self.op.hvparams:
9313
      hv_type = instance.hypervisor
9314
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
9315
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
9316
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
9317

    
9318
      # local check
9319
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
9320
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
9321
      self.hv_new = hv_new # the new actual values
9322
      self.hv_inst = i_hvdict # the new dict (without defaults)
9323
    else:
9324
      self.hv_new = self.hv_inst = {}
9325

    
9326
    # beparams processing
9327
    if self.op.beparams:
9328
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
9329
                                   use_none=True)
9330
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
9331
      be_new = cluster.SimpleFillBE(i_bedict)
9332
      self.be_new = be_new # the new actual values
9333
      self.be_inst = i_bedict # the new dict (without defaults)
9334
    else:
9335
      self.be_new = self.be_inst = {}
9336

    
9337
    # osparams processing
9338
    if self.op.osparams:
9339
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
9340
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
9341
      self.os_inst = i_osdict # the new dict (without defaults)
9342
    else:
9343
      self.os_inst = {}
9344

    
9345
    self.warn = []
9346

    
9347
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
9348
      mem_check_list = [pnode]
9349
      if be_new[constants.BE_AUTO_BALANCE]:
9350
        # either we changed auto_balance to yes or it was from before
9351
        mem_check_list.extend(instance.secondary_nodes)
9352
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
9353
                                                  instance.hypervisor)
9354
      nodeinfo = self.rpc.call_node_info(mem_check_list, None,
9355
                                         instance.hypervisor)
9356
      pninfo = nodeinfo[pnode]
9357
      msg = pninfo.fail_msg
9358
      if msg:
9359
        # Assume the primary node is unreachable and go ahead
9360
        self.warn.append("Can't get info from primary node %s: %s" %
9361
                         (pnode,  msg))
9362
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
9363
        self.warn.append("Node data from primary node %s doesn't contain"
9364
                         " free memory information" % pnode)
9365
      elif instance_info.fail_msg:
9366
        self.warn.append("Can't get instance runtime information: %s" %
9367
                        instance_info.fail_msg)
9368
      else:
9369
        if instance_info.payload:
9370
          current_mem = int(instance_info.payload['memory'])
9371
        else:
9372
          # Assume instance not running
9373
          # (there is a slight race condition here, but it's not very probable,
9374
          # and we have no other way to check)
9375
          current_mem = 0
9376
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
9377
                    pninfo.payload['memory_free'])
9378
        if miss_mem > 0:
9379
          raise errors.OpPrereqError("This change will prevent the instance"
9380
                                     " from starting, due to %d MB of memory"
9381
                                     " missing on its primary node" % miss_mem,
9382
                                     errors.ECODE_NORES)
9383

    
9384
      if be_new[constants.BE_AUTO_BALANCE]:
9385
        for node, nres in nodeinfo.items():
9386
          if node not in instance.secondary_nodes:
9387
            continue
9388
          msg = nres.fail_msg
9389
          if msg:
9390
            self.warn.append("Can't get info from secondary node %s: %s" %
9391
                             (node, msg))
9392
          elif not isinstance(nres.payload.get('memory_free', None), int):
9393
            self.warn.append("Secondary node %s didn't return free"
9394
                             " memory information" % node)
9395
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
9396
            self.warn.append("Not enough memory to failover instance to"
9397
                             " secondary node %s" % node)
9398

    
9399
    # NIC processing
9400
    self.nic_pnew = {}
9401
    self.nic_pinst = {}
9402
    for nic_op, nic_dict in self.op.nics:
9403
      if nic_op == constants.DDM_REMOVE:
9404
        if not instance.nics:
9405
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
9406
                                     errors.ECODE_INVAL)
9407
        continue
9408
      if nic_op != constants.DDM_ADD:
9409
        # an existing nic
9410
        if not instance.nics:
9411
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
9412
                                     " no NICs" % nic_op,
9413
                                     errors.ECODE_INVAL)
9414
        if nic_op < 0 or nic_op >= len(instance.nics):
9415
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
9416
                                     " are 0 to %d" %
9417
                                     (nic_op, len(instance.nics) - 1),
9418
                                     errors.ECODE_INVAL)
9419
        old_nic_params = instance.nics[nic_op].nicparams
9420
        old_nic_ip = instance.nics[nic_op].ip
9421
      else:
9422
        old_nic_params = {}
9423
        old_nic_ip = None
9424

    
9425
      update_params_dict = dict([(key, nic_dict[key])
9426
                                 for key in constants.NICS_PARAMETERS
9427
                                 if key in nic_dict])
9428

    
9429
      if 'bridge' in nic_dict:
9430
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
9431

    
9432
      new_nic_params = _GetUpdatedParams(old_nic_params,
9433
                                         update_params_dict)
9434
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
9435
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
9436
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
9437
      self.nic_pinst[nic_op] = new_nic_params
9438
      self.nic_pnew[nic_op] = new_filled_nic_params
9439
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
9440

    
9441
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
9442
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
9443
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
9444
        if msg:
9445
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
9446
          if self.op.force:
9447
            self.warn.append(msg)
9448
          else:
9449
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
9450
      if new_nic_mode == constants.NIC_MODE_ROUTED:
9451
        if 'ip' in nic_dict:
9452
          nic_ip = nic_dict['ip']
9453
        else:
9454
          nic_ip = old_nic_ip
9455
        if nic_ip is None:
9456
          raise errors.OpPrereqError('Cannot set the nic ip to None'
9457
                                     ' on a routed nic', errors.ECODE_INVAL)
9458
      if 'mac' in nic_dict:
9459
        nic_mac = nic_dict['mac']
9460
        if nic_mac is None:
9461
          raise errors.OpPrereqError('Cannot set the nic mac to None',
9462
                                     errors.ECODE_INVAL)
9463
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9464
          # otherwise generate the mac
9465
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
9466
        else:
9467
          # or validate/reserve the current one
9468
          try:
9469
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
9470
          except errors.ReservationError:
9471
            raise errors.OpPrereqError("MAC address %s already in use"
9472
                                       " in cluster" % nic_mac,
9473
                                       errors.ECODE_NOTUNIQUE)
9474

    
9475
    # DISK processing
9476
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
9477
      raise errors.OpPrereqError("Disk operations not supported for"
9478
                                 " diskless instances",
9479
                                 errors.ECODE_INVAL)
9480
    for disk_op, _ in self.op.disks:
9481
      if disk_op == constants.DDM_REMOVE:
9482
        if len(instance.disks) == 1:
9483
          raise errors.OpPrereqError("Cannot remove the last disk of"
9484
                                     " an instance", errors.ECODE_INVAL)
9485
        _CheckInstanceDown(self, instance, "cannot remove disks")
9486

    
9487
      if (disk_op == constants.DDM_ADD and
9488
          len(instance.disks) >= constants.MAX_DISKS):
9489
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
9490
                                   " add more" % constants.MAX_DISKS,
9491
                                   errors.ECODE_STATE)
9492
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
9493
        # an existing disk
9494
        if disk_op < 0 or disk_op >= len(instance.disks):
9495
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9496
                                     " are 0 to %d" %
9497
                                     (disk_op, len(instance.disks)),
9498
                                     errors.ECODE_INVAL)
9499

    
9500
    return
9501

    
9502
  def _ConvertPlainToDrbd(self, feedback_fn):
9503
    """Converts an instance from plain to drbd.
9504

9505
    """
9506
    feedback_fn("Converting template to drbd")
9507
    instance = self.instance
9508
    pnode = instance.primary_node
9509
    snode = self.op.remote_node
9510

    
9511
    # create a fake disk info for _GenerateDiskTemplate
9512
    disk_info = [{"size": d.size, "mode": d.mode,
9513
                  "vg": d.logical_id[0]} for d in instance.disks]
9514
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9515
                                      instance.name, pnode, [snode],
9516
                                      disk_info, None, None, 0, feedback_fn)
9517
    info = _GetInstanceInfoText(instance)
9518
    feedback_fn("Creating aditional volumes...")
9519
    # first, create the missing data and meta devices
9520
    for disk in new_disks:
9521
      # unfortunately this is... not too nice
9522
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9523
                            info, True)
9524
      for child in disk.children:
9525
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9526
    # at this stage, all new LVs have been created, we can rename the
9527
    # old ones
9528
    feedback_fn("Renaming original volumes...")
9529
    rename_list = [(o, n.children[0].logical_id)
9530
                   for (o, n) in zip(instance.disks, new_disks)]
9531
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9532
    result.Raise("Failed to rename original LVs")
9533

    
9534
    feedback_fn("Initializing DRBD devices...")
9535
    # all child devices are in place, we can now create the DRBD devices
9536
    for disk in new_disks:
9537
      for node in [pnode, snode]:
9538
        f_create = node == pnode
9539
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9540

    
9541
    # at this point, the instance has been modified
9542
    instance.disk_template = constants.DT_DRBD8
9543
    instance.disks = new_disks
9544
    self.cfg.Update(instance, feedback_fn)
9545

    
9546
    # disks are created, waiting for sync
9547
    disk_abort = not _WaitForSync(self, instance)
9548
    if disk_abort:
9549
      raise errors.OpExecError("There are some degraded disks for"
9550
                               " this instance, please cleanup manually")
9551

    
9552
  def _ConvertDrbdToPlain(self, feedback_fn):
9553
    """Converts an instance from drbd to plain.
9554

9555
    """
9556
    instance = self.instance
9557
    assert len(instance.secondary_nodes) == 1
9558
    pnode = instance.primary_node
9559
    snode = instance.secondary_nodes[0]
9560
    feedback_fn("Converting template to plain")
9561

    
9562
    old_disks = instance.disks
9563
    new_disks = [d.children[0] for d in old_disks]
9564

    
9565
    # copy over size and mode
9566
    for parent, child in zip(old_disks, new_disks):
9567
      child.size = parent.size
9568
      child.mode = parent.mode
9569

    
9570
    # update instance structure
9571
    instance.disks = new_disks
9572
    instance.disk_template = constants.DT_PLAIN
9573
    self.cfg.Update(instance, feedback_fn)
9574

    
9575
    feedback_fn("Removing volumes on the secondary node...")
9576
    for disk in old_disks:
9577
      self.cfg.SetDiskID(disk, snode)
9578
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9579
      if msg:
9580
        self.LogWarning("Could not remove block device %s on node %s,"
9581
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9582

    
9583
    feedback_fn("Removing unneeded volumes on the primary node...")
9584
    for idx, disk in enumerate(old_disks):
9585
      meta = disk.children[1]
9586
      self.cfg.SetDiskID(meta, pnode)
9587
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9588
      if msg:
9589
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9590
                        " continuing anyway: %s", idx, pnode, msg)
9591

    
9592
  def Exec(self, feedback_fn):
9593
    """Modifies an instance.
9594

9595
    All parameters take effect only at the next restart of the instance.
9596

9597
    """
9598
    # Process here the warnings from CheckPrereq, as we don't have a
9599
    # feedback_fn there.
9600
    for warn in self.warn:
9601
      feedback_fn("WARNING: %s" % warn)
9602

    
9603
    result = []
9604
    instance = self.instance
9605
    # disk changes
9606
    for disk_op, disk_dict in self.op.disks:
9607
      if disk_op == constants.DDM_REMOVE:
9608
        # remove the last disk
9609
        device = instance.disks.pop()
9610
        device_idx = len(instance.disks)
9611
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9612
          self.cfg.SetDiskID(disk, node)
9613
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9614
          if msg:
9615
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9616
                            " continuing anyway", device_idx, node, msg)
9617
        result.append(("disk/%d" % device_idx, "remove"))
9618
      elif disk_op == constants.DDM_ADD:
9619
        # add a new disk
9620
        if instance.disk_template == constants.DT_FILE:
9621
          file_driver, file_path = instance.disks[0].logical_id
9622
          file_path = os.path.dirname(file_path)
9623
        else:
9624
          file_driver = file_path = None
9625
        disk_idx_base = len(instance.disks)
9626
        new_disk = _GenerateDiskTemplate(self,
9627
                                         instance.disk_template,
9628
                                         instance.name, instance.primary_node,
9629
                                         instance.secondary_nodes,
9630
                                         [disk_dict],
9631
                                         file_path,
9632
                                         file_driver,
9633
                                         disk_idx_base, feedback_fn)[0]
9634
        instance.disks.append(new_disk)
9635
        info = _GetInstanceInfoText(instance)
9636

    
9637
        logging.info("Creating volume %s for instance %s",
9638
                     new_disk.iv_name, instance.name)
9639
        # Note: this needs to be kept in sync with _CreateDisks
9640
        #HARDCODE
9641
        for node in instance.all_nodes:
9642
          f_create = node == instance.primary_node
9643
          try:
9644
            _CreateBlockDev(self, node, instance, new_disk,
9645
                            f_create, info, f_create)
9646
          except errors.OpExecError, err:
9647
            self.LogWarning("Failed to create volume %s (%s) on"
9648
                            " node %s: %s",
9649
                            new_disk.iv_name, new_disk, node, err)
9650
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9651
                       (new_disk.size, new_disk.mode)))
9652
      else:
9653
        # change a given disk
9654
        instance.disks[disk_op].mode = disk_dict['mode']
9655
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9656

    
9657
    if self.op.disk_template:
9658
      r_shut = _ShutdownInstanceDisks(self, instance)
9659
      if not r_shut:
9660
        raise errors.OpExecError("Cannot shutdown instance disks, unable to"
9661
                                 " proceed with disk template conversion")
9662
      mode = (instance.disk_template, self.op.disk_template)
9663
      try:
9664
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9665
      except:
9666
        self.cfg.ReleaseDRBDMinors(instance.name)
9667
        raise
9668
      result.append(("disk_template", self.op.disk_template))
9669

    
9670
    # NIC changes
9671
    for nic_op, nic_dict in self.op.nics:
9672
      if nic_op == constants.DDM_REMOVE:
9673
        # remove the last nic
9674
        del instance.nics[-1]
9675
        result.append(("nic.%d" % len(instance.nics), "remove"))
9676
      elif nic_op == constants.DDM_ADD:
9677
        # mac and bridge should be set, by now
9678
        mac = nic_dict['mac']
9679
        ip = nic_dict.get('ip', None)
9680
        nicparams = self.nic_pinst[constants.DDM_ADD]
9681
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9682
        instance.nics.append(new_nic)
9683
        result.append(("nic.%d" % (len(instance.nics) - 1),
9684
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9685
                       (new_nic.mac, new_nic.ip,
9686
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9687
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9688
                       )))
9689
      else:
9690
        for key in 'mac', 'ip':
9691
          if key in nic_dict:
9692
            setattr(instance.nics[nic_op], key, nic_dict[key])
9693
        if nic_op in self.nic_pinst:
9694
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9695
        for key, val in nic_dict.iteritems():
9696
          result.append(("nic.%s/%d" % (key, nic_op), val))
9697

    
9698
    # hvparams changes
9699
    if self.op.hvparams:
9700
      instance.hvparams = self.hv_inst
9701
      for key, val in self.op.hvparams.iteritems():
9702
        result.append(("hv/%s" % key, val))
9703

    
9704
    # beparams changes
9705
    if self.op.beparams:
9706
      instance.beparams = self.be_inst
9707
      for key, val in self.op.beparams.iteritems():
9708
        result.append(("be/%s" % key, val))
9709

    
9710
    # OS change
9711
    if self.op.os_name:
9712
      instance.os = self.op.os_name
9713

    
9714
    # osparams changes
9715
    if self.op.osparams:
9716
      instance.osparams = self.os_inst
9717
      for key, val in self.op.osparams.iteritems():
9718
        result.append(("os/%s" % key, val))
9719

    
9720
    self.cfg.Update(instance, feedback_fn)
9721

    
9722
    return result
9723

    
9724
  _DISK_CONVERSIONS = {
9725
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9726
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9727
    }
9728

    
9729

    
9730
class LUBackupQuery(NoHooksLU):
9731
  """Query the exports list
9732

9733
  """
9734
  REQ_BGL = False
9735

    
9736
  def ExpandNames(self):
9737
    self.needed_locks = {}
9738
    self.share_locks[locking.LEVEL_NODE] = 1
9739
    if not self.op.nodes:
9740
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9741
    else:
9742
      self.needed_locks[locking.LEVEL_NODE] = \
9743
        _GetWantedNodes(self, self.op.nodes)
9744

    
9745
  def Exec(self, feedback_fn):
9746
    """Compute the list of all the exported system images.
9747

9748
    @rtype: dict
9749
    @return: a dictionary with the structure node->(export-list)
9750
        where export-list is a list of the instances exported on
9751
        that node.
9752

9753
    """
9754
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9755
    rpcresult = self.rpc.call_export_list(self.nodes)
9756
    result = {}
9757
    for node in rpcresult:
9758
      if rpcresult[node].fail_msg:
9759
        result[node] = False
9760
      else:
9761
        result[node] = rpcresult[node].payload
9762

    
9763
    return result
9764

    
9765

    
9766
class LUBackupPrepare(NoHooksLU):
9767
  """Prepares an instance for an export and returns useful information.
9768

9769
  """
9770
  REQ_BGL = False
9771

    
9772
  def ExpandNames(self):
9773
    self._ExpandAndLockInstance()
9774

    
9775
  def CheckPrereq(self):
9776
    """Check prerequisites.
9777

9778
    """
9779
    instance_name = self.op.instance_name
9780

    
9781
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9782
    assert self.instance is not None, \
9783
          "Cannot retrieve locked instance %s" % self.op.instance_name
9784
    _CheckNodeOnline(self, self.instance.primary_node)
9785

    
9786
    self._cds = _GetClusterDomainSecret()
9787

    
9788
  def Exec(self, feedback_fn):
9789
    """Prepares an instance for an export.
9790

9791
    """
9792
    instance = self.instance
9793

    
9794
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9795
      salt = utils.GenerateSecret(8)
9796

    
9797
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9798
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9799
                                              constants.RIE_CERT_VALIDITY)
9800
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9801

    
9802
      (name, cert_pem) = result.payload
9803

    
9804
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9805
                                             cert_pem)
9806

    
9807
      return {
9808
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9809
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9810
                          salt),
9811
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9812
        }
9813

    
9814
    return None
9815

    
9816

    
9817
class LUBackupExport(LogicalUnit):
9818
  """Export an instance to an image in the cluster.
9819

9820
  """
9821
  HPATH = "instance-export"
9822
  HTYPE = constants.HTYPE_INSTANCE
9823
  REQ_BGL = False
9824

    
9825
  def CheckArguments(self):
9826
    """Check the arguments.
9827

9828
    """
9829
    self.x509_key_name = self.op.x509_key_name
9830
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9831

    
9832
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9833
      if not self.x509_key_name:
9834
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9835
                                   errors.ECODE_INVAL)
9836

    
9837
      if not self.dest_x509_ca_pem:
9838
        raise errors.OpPrereqError("Missing destination X509 CA",
9839
                                   errors.ECODE_INVAL)
9840

    
9841
  def ExpandNames(self):
9842
    self._ExpandAndLockInstance()
9843

    
9844
    # Lock all nodes for local exports
9845
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9846
      # FIXME: lock only instance primary and destination node
9847
      #
9848
      # Sad but true, for now we have do lock all nodes, as we don't know where
9849
      # the previous export might be, and in this LU we search for it and
9850
      # remove it from its current node. In the future we could fix this by:
9851
      #  - making a tasklet to search (share-lock all), then create the
9852
      #    new one, then one to remove, after
9853
      #  - removing the removal operation altogether
9854
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9855

    
9856
  def DeclareLocks(self, level):
9857
    """Last minute lock declaration."""
9858
    # All nodes are locked anyway, so nothing to do here.
9859

    
9860
  def BuildHooksEnv(self):
9861
    """Build hooks env.
9862

9863
    This will run on the master, primary node and target node.
9864

9865
    """
9866
    env = {
9867
      "EXPORT_MODE": self.op.mode,
9868
      "EXPORT_NODE": self.op.target_node,
9869
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9870
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9871
      # TODO: Generic function for boolean env variables
9872
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9873
      }
9874

    
9875
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9876

    
9877
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9878

    
9879
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9880
      nl.append(self.op.target_node)
9881

    
9882
    return env, nl, nl
9883

    
9884
  def CheckPrereq(self):
9885
    """Check prerequisites.
9886

9887
    This checks that the instance and node names are valid.
9888

9889
    """
9890
    instance_name = self.op.instance_name
9891

    
9892
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9893
    assert self.instance is not None, \
9894
          "Cannot retrieve locked instance %s" % self.op.instance_name
9895
    _CheckNodeOnline(self, self.instance.primary_node)
9896

    
9897
    if (self.op.remove_instance and self.instance.admin_up and
9898
        not self.op.shutdown):
9899
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9900
                                 " down before")
9901

    
9902
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9903
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9904
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9905
      assert self.dst_node is not None
9906

    
9907
      _CheckNodeOnline(self, self.dst_node.name)
9908
      _CheckNodeNotDrained(self, self.dst_node.name)
9909

    
9910
      self._cds = None
9911
      self.dest_disk_info = None
9912
      self.dest_x509_ca = None
9913

    
9914
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9915
      self.dst_node = None
9916

    
9917
      if len(self.op.target_node) != len(self.instance.disks):
9918
        raise errors.OpPrereqError(("Received destination information for %s"
9919
                                    " disks, but instance %s has %s disks") %
9920
                                   (len(self.op.target_node), instance_name,
9921
                                    len(self.instance.disks)),
9922
                                   errors.ECODE_INVAL)
9923

    
9924
      cds = _GetClusterDomainSecret()
9925

    
9926
      # Check X509 key name
9927
      try:
9928
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9929
      except (TypeError, ValueError), err:
9930
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9931

    
9932
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9933
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9934
                                   errors.ECODE_INVAL)
9935

    
9936
      # Load and verify CA
9937
      try:
9938
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9939
      except OpenSSL.crypto.Error, err:
9940
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9941
                                   (err, ), errors.ECODE_INVAL)
9942

    
9943
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9944
      if errcode is not None:
9945
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9946
                                   (msg, ), errors.ECODE_INVAL)
9947

    
9948
      self.dest_x509_ca = cert
9949

    
9950
      # Verify target information
9951
      disk_info = []
9952
      for idx, disk_data in enumerate(self.op.target_node):
9953
        try:
9954
          (host, port, magic) = \
9955
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9956
        except errors.GenericError, err:
9957
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9958
                                     (idx, err), errors.ECODE_INVAL)
9959

    
9960
        disk_info.append((host, port, magic))
9961

    
9962
      assert len(disk_info) == len(self.op.target_node)
9963
      self.dest_disk_info = disk_info
9964

    
9965
    else:
9966
      raise errors.ProgrammerError("Unhandled export mode %r" %
9967
                                   self.op.mode)
9968

    
9969
    # instance disk type verification
9970
    # TODO: Implement export support for file-based disks
9971
    for disk in self.instance.disks:
9972
      if disk.dev_type == constants.LD_FILE:
9973
        raise errors.OpPrereqError("Export not supported for instances with"
9974
                                   " file-based disks", errors.ECODE_INVAL)
9975

    
9976
  def _CleanupExports(self, feedback_fn):
9977
    """Removes exports of current instance from all other nodes.
9978

9979
    If an instance in a cluster with nodes A..D was exported to node C, its
9980
    exports will be removed from the nodes A, B and D.
9981

9982
    """
9983
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9984

    
9985
    nodelist = self.cfg.GetNodeList()
9986
    nodelist.remove(self.dst_node.name)
9987

    
9988
    # on one-node clusters nodelist will be empty after the removal
9989
    # if we proceed the backup would be removed because OpBackupQuery
9990
    # substitutes an empty list with the full cluster node list.
9991
    iname = self.instance.name
9992
    if nodelist:
9993
      feedback_fn("Removing old exports for instance %s" % iname)
9994
      exportlist = self.rpc.call_export_list(nodelist)
9995
      for node in exportlist:
9996
        if exportlist[node].fail_msg:
9997
          continue
9998
        if iname in exportlist[node].payload:
9999
          msg = self.rpc.call_export_remove(node, iname).fail_msg
10000
          if msg:
10001
            self.LogWarning("Could not remove older export for instance %s"
10002
                            " on node %s: %s", iname, node, msg)
10003

    
10004
  def Exec(self, feedback_fn):
10005
    """Export an instance to an image in the cluster.
10006

10007
    """
10008
    assert self.op.mode in constants.EXPORT_MODES
10009

    
10010
    instance = self.instance
10011
    src_node = instance.primary_node
10012

    
10013
    if self.op.shutdown:
10014
      # shutdown the instance, but not the disks
10015
      feedback_fn("Shutting down instance %s" % instance.name)
10016
      result = self.rpc.call_instance_shutdown(src_node, instance,
10017
                                               self.op.shutdown_timeout)
10018
      # TODO: Maybe ignore failures if ignore_remove_failures is set
10019
      result.Raise("Could not shutdown instance %s on"
10020
                   " node %s" % (instance.name, src_node))
10021

    
10022
    # set the disks ID correctly since call_instance_start needs the
10023
    # correct drbd minor to create the symlinks
10024
    for disk in instance.disks:
10025
      self.cfg.SetDiskID(disk, src_node)
10026

    
10027
    activate_disks = (not instance.admin_up)
10028

    
10029
    if activate_disks:
10030
      # Activate the instance disks if we'exporting a stopped instance
10031
      feedback_fn("Activating disks for %s" % instance.name)
10032
      _StartInstanceDisks(self, instance, None)
10033

    
10034
    try:
10035
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
10036
                                                     instance)
10037

    
10038
      helper.CreateSnapshots()
10039
      try:
10040
        if (self.op.shutdown and instance.admin_up and
10041
            not self.op.remove_instance):
10042
          assert not activate_disks
10043
          feedback_fn("Starting instance %s" % instance.name)
10044
          result = self.rpc.call_instance_start(src_node, instance, None, None)
10045
          msg = result.fail_msg
10046
          if msg:
10047
            feedback_fn("Failed to start instance: %s" % msg)
10048
            _ShutdownInstanceDisks(self, instance)
10049
            raise errors.OpExecError("Could not start instance: %s" % msg)
10050

    
10051
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
10052
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
10053
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
10054
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
10055
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
10056

    
10057
          (key_name, _, _) = self.x509_key_name
10058

    
10059
          dest_ca_pem = \
10060
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
10061
                                            self.dest_x509_ca)
10062

    
10063
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
10064
                                                     key_name, dest_ca_pem,
10065
                                                     timeouts)
10066
      finally:
10067
        helper.Cleanup()
10068

    
10069
      # Check for backwards compatibility
10070
      assert len(dresults) == len(instance.disks)
10071
      assert compat.all(isinstance(i, bool) for i in dresults), \
10072
             "Not all results are boolean: %r" % dresults
10073

    
10074
    finally:
10075
      if activate_disks:
10076
        feedback_fn("Deactivating disks for %s" % instance.name)
10077
        _ShutdownInstanceDisks(self, instance)
10078

    
10079
    if not (compat.all(dresults) and fin_resu):
10080
      failures = []
10081
      if not fin_resu:
10082
        failures.append("export finalization")
10083
      if not compat.all(dresults):
10084
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
10085
                               if not dsk)
10086
        failures.append("disk export: disk(s) %s" % fdsk)
10087

    
10088
      raise errors.OpExecError("Export failed, errors in %s" %
10089
                               utils.CommaJoin(failures))
10090

    
10091
    # At this point, the export was successful, we can cleanup/finish
10092

    
10093
    # Remove instance if requested
10094
    if self.op.remove_instance:
10095
      feedback_fn("Removing instance %s" % instance.name)
10096
      _RemoveInstance(self, feedback_fn, instance,
10097
                      self.op.ignore_remove_failures)
10098

    
10099
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10100
      self._CleanupExports(feedback_fn)
10101

    
10102
    return fin_resu, dresults
10103

    
10104

    
10105
class LUBackupRemove(NoHooksLU):
10106
  """Remove exports related to the named instance.
10107

10108
  """
10109
  REQ_BGL = False
10110

    
10111
  def ExpandNames(self):
10112
    self.needed_locks = {}
10113
    # We need all nodes to be locked in order for RemoveExport to work, but we
10114
    # don't need to lock the instance itself, as nothing will happen to it (and
10115
    # we can remove exports also for a removed instance)
10116
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10117

    
10118
  def Exec(self, feedback_fn):
10119
    """Remove any export.
10120

10121
    """
10122
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
10123
    # If the instance was not found we'll try with the name that was passed in.
10124
    # This will only work if it was an FQDN, though.
10125
    fqdn_warn = False
10126
    if not instance_name:
10127
      fqdn_warn = True
10128
      instance_name = self.op.instance_name
10129

    
10130
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
10131
    exportlist = self.rpc.call_export_list(locked_nodes)
10132
    found = False
10133
    for node in exportlist:
10134
      msg = exportlist[node].fail_msg
10135
      if msg:
10136
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
10137
        continue
10138
      if instance_name in exportlist[node].payload:
10139
        found = True
10140
        result = self.rpc.call_export_remove(node, instance_name)
10141
        msg = result.fail_msg
10142
        if msg:
10143
          logging.error("Could not remove export for instance %s"
10144
                        " on node %s: %s", instance_name, node, msg)
10145

    
10146
    if fqdn_warn and not found:
10147
      feedback_fn("Export not found. If trying to remove an export belonging"
10148
                  " to a deleted instance please use its Fully Qualified"
10149
                  " Domain Name.")
10150

    
10151

    
10152
class LUGroupAdd(LogicalUnit):
10153
  """Logical unit for creating node groups.
10154

10155
  """
10156
  HPATH = "group-add"
10157
  HTYPE = constants.HTYPE_GROUP
10158
  REQ_BGL = False
10159

    
10160
  def ExpandNames(self):
10161
    # We need the new group's UUID here so that we can create and acquire the
10162
    # corresponding lock. Later, in Exec(), we'll indicate to cfg.AddNodeGroup
10163
    # that it should not check whether the UUID exists in the configuration.
10164
    self.group_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
10165
    self.needed_locks = {}
10166
    self.add_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
10167

    
10168
  def CheckPrereq(self):
10169
    """Check prerequisites.
10170

10171
    This checks that the given group name is not an existing node group
10172
    already.
10173

10174
    """
10175
    try:
10176
      existing_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10177
    except errors.OpPrereqError:
10178
      pass
10179
    else:
10180
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
10181
                                 " node group (UUID: %s)" %
10182
                                 (self.op.group_name, existing_uuid),
10183
                                 errors.ECODE_EXISTS)
10184

    
10185
    if self.op.ndparams:
10186
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
10187

    
10188
  def BuildHooksEnv(self):
10189
    """Build hooks env.
10190

10191
    """
10192
    env = {
10193
      "GROUP_NAME": self.op.group_name,
10194
      }
10195
    mn = self.cfg.GetMasterNode()
10196
    return env, [mn], [mn]
10197

    
10198
  def Exec(self, feedback_fn):
10199
    """Add the node group to the cluster.
10200

10201
    """
10202
    group_obj = objects.NodeGroup(name=self.op.group_name, members=[],
10203
                                  uuid=self.group_uuid,
10204
                                  alloc_policy=self.op.alloc_policy,
10205
                                  ndparams=self.op.ndparams)
10206

    
10207
    self.cfg.AddNodeGroup(group_obj, self.proc.GetECId(), check_uuid=False)
10208
    del self.remove_locks[locking.LEVEL_NODEGROUP]
10209

    
10210

    
10211
class LUGroupAssignNodes(NoHooksLU):
10212
  """Logical unit for assigning nodes to groups.
10213

10214
  """
10215
  REQ_BGL = False
10216

    
10217
  def ExpandNames(self):
10218
    # These raise errors.OpPrereqError on their own:
10219
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10220
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
10221

    
10222
    # We want to lock all the affected nodes and groups. We have readily
10223
    # available the list of nodes, and the *destination* group. To gather the
10224
    # list of "source" groups, we need to fetch node information.
10225
    self.node_data = self.cfg.GetAllNodesInfo()
10226
    affected_groups = set(self.node_data[node].group for node in self.op.nodes)
10227
    affected_groups.add(self.group_uuid)
10228

    
10229
    self.needed_locks = {
10230
      locking.LEVEL_NODEGROUP: list(affected_groups),
10231
      locking.LEVEL_NODE: self.op.nodes,
10232
      }
10233

    
10234
  def CheckPrereq(self):
10235
    """Check prerequisites.
10236

10237
    """
10238
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
10239
    instance_data = self.cfg.GetAllInstancesInfo()
10240

    
10241
    if self.group is None:
10242
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10243
                               (self.op.group_name, self.group_uuid))
10244

    
10245
    (new_splits, previous_splits) = \
10246
      self.CheckAssignmentForSplitInstances([(node, self.group_uuid)
10247
                                             for node in self.op.nodes],
10248
                                            self.node_data, instance_data)
10249

    
10250
    if new_splits:
10251
      fmt_new_splits = utils.CommaJoin(utils.NiceSort(new_splits))
10252

    
10253
      if not self.op.force:
10254
        raise errors.OpExecError("The following instances get split by this"
10255
                                 " change and --force was not given: %s" %
10256
                                 fmt_new_splits)
10257
      else:
10258
        self.LogWarning("This operation will split the following instances: %s",
10259
                        fmt_new_splits)
10260

    
10261
        if previous_splits:
10262
          self.LogWarning("In addition, these already-split instances continue"
10263
                          " to be split across groups: %s",
10264
                          utils.CommaJoin(utils.NiceSort(previous_splits)))
10265

    
10266
  def Exec(self, feedback_fn):
10267
    """Assign nodes to a new group.
10268

10269
    """
10270
    for node in self.op.nodes:
10271
      self.node_data[node].group = self.group_uuid
10272

    
10273
    self.cfg.Update(self.group, feedback_fn) # Saves all modified nodes.
10274

    
10275
  @staticmethod
10276
  def CheckAssignmentForSplitInstances(changes, node_data, instance_data):
10277
    """Check for split instances after a node assignment.
10278

10279
    This method considers a series of node assignments as an atomic operation,
10280
    and returns information about split instances after applying the set of
10281
    changes.
10282

10283
    In particular, it returns information about newly split instances, and
10284
    instances that were already split, and remain so after the change.
10285

10286
    Only instances whose disk template is listed in constants.DTS_NET_MIRROR are
10287
    considered.
10288

10289
    @type changes: list of (node_name, new_group_uuid) pairs.
10290
    @param changes: list of node assignments to consider.
10291
    @param node_data: a dict with data for all nodes
10292
    @param instance_data: a dict with all instances to consider
10293
    @rtype: a two-tuple
10294
    @return: a list of instances that were previously okay and result split as a
10295
      consequence of this change, and a list of instances that were previously
10296
      split and this change does not fix.
10297

10298
    """
10299
    changed_nodes = dict((node, group) for node, group in changes
10300
                         if node_data[node].group != group)
10301

    
10302
    all_split_instances = set()
10303
    previously_split_instances = set()
10304

    
10305
    def InstanceNodes(instance):
10306
      return [instance.primary_node] + list(instance.secondary_nodes)
10307

    
10308
    for inst in instance_data.values():
10309
      if inst.disk_template not in constants.DTS_NET_MIRROR:
10310
        continue
10311

    
10312
      instance_nodes = InstanceNodes(inst)
10313

    
10314
      if len(set(node_data[node].group for node in instance_nodes)) > 1:
10315
        previously_split_instances.add(inst.name)
10316

    
10317
      if len(set(changed_nodes.get(node, node_data[node].group)
10318
                 for node in instance_nodes)) > 1:
10319
        all_split_instances.add(inst.name)
10320

    
10321
    return (list(all_split_instances - previously_split_instances),
10322
            list(previously_split_instances & all_split_instances))
10323

    
10324

    
10325
class _GroupQuery(_QueryBase):
10326

    
10327
  FIELDS = query.GROUP_FIELDS
10328

    
10329
  def ExpandNames(self, lu):
10330
    lu.needed_locks = {}
10331

    
10332
    self._all_groups = lu.cfg.GetAllNodeGroupsInfo()
10333
    name_to_uuid = dict((g.name, g.uuid) for g in self._all_groups.values())
10334

    
10335
    if not self.names:
10336
      self.wanted = [name_to_uuid[name]
10337
                     for name in utils.NiceSort(name_to_uuid.keys())]
10338
    else:
10339
      # Accept names to be either names or UUIDs.
10340
      missing = []
10341
      self.wanted = []
10342
      all_uuid = frozenset(self._all_groups.keys())
10343

    
10344
      for name in self.names:
10345
        if name in all_uuid:
10346
          self.wanted.append(name)
10347
        elif name in name_to_uuid:
10348
          self.wanted.append(name_to_uuid[name])
10349
        else:
10350
          missing.append(name)
10351

    
10352
      if missing:
10353
        raise errors.OpPrereqError("Some groups do not exist: %s" %
10354
                                   utils.CommaJoin(missing),
10355
                                   errors.ECODE_NOENT)
10356

    
10357
  def DeclareLocks(self, lu, level):
10358
    pass
10359

    
10360
  def _GetQueryData(self, lu):
10361
    """Computes the list of node groups and their attributes.
10362

10363
    """
10364
    do_nodes = query.GQ_NODE in self.requested_data
10365
    do_instances = query.GQ_INST in self.requested_data
10366

    
10367
    group_to_nodes = None
10368
    group_to_instances = None
10369

    
10370
    # For GQ_NODE, we need to map group->[nodes], and group->[instances] for
10371
    # GQ_INST. The former is attainable with just GetAllNodesInfo(), but for the
10372
    # latter GetAllInstancesInfo() is not enough, for we have to go through
10373
    # instance->node. Hence, we will need to process nodes even if we only need
10374
    # instance information.
10375
    if do_nodes or do_instances:
10376
      all_nodes = lu.cfg.GetAllNodesInfo()
10377
      group_to_nodes = dict((uuid, []) for uuid in self.wanted)
10378
      node_to_group = {}
10379

    
10380
      for node in all_nodes.values():
10381
        if node.group in group_to_nodes:
10382
          group_to_nodes[node.group].append(node.name)
10383
          node_to_group[node.name] = node.group
10384

    
10385
      if do_instances:
10386
        all_instances = lu.cfg.GetAllInstancesInfo()
10387
        group_to_instances = dict((uuid, []) for uuid in self.wanted)
10388

    
10389
        for instance in all_instances.values():
10390
          node = instance.primary_node
10391
          if node in node_to_group:
10392
            group_to_instances[node_to_group[node]].append(instance.name)
10393

    
10394
        if not do_nodes:
10395
          # Do not pass on node information if it was not requested.
10396
          group_to_nodes = None
10397

    
10398
    return query.GroupQueryData([self._all_groups[uuid]
10399
                                 for uuid in self.wanted],
10400
                                group_to_nodes, group_to_instances)
10401

    
10402

    
10403
class LUGroupQuery(NoHooksLU):
10404
  """Logical unit for querying node groups.
10405

10406
  """
10407
  REQ_BGL = False
10408

    
10409
  def CheckArguments(self):
10410
    self.gq = _GroupQuery(self.op.names, self.op.output_fields, False)
10411

    
10412
  def ExpandNames(self):
10413
    self.gq.ExpandNames(self)
10414

    
10415
  def Exec(self, feedback_fn):
10416
    return self.gq.OldStyleQuery(self)
10417

    
10418

    
10419
class LUGroupSetParams(LogicalUnit):
10420
  """Modifies the parameters of a node group.
10421

10422
  """
10423
  HPATH = "group-modify"
10424
  HTYPE = constants.HTYPE_GROUP
10425
  REQ_BGL = False
10426

    
10427
  def CheckArguments(self):
10428
    all_changes = [
10429
      self.op.ndparams,
10430
      self.op.alloc_policy,
10431
      ]
10432

    
10433
    if all_changes.count(None) == len(all_changes):
10434
      raise errors.OpPrereqError("Please pass at least one modification",
10435
                                 errors.ECODE_INVAL)
10436

    
10437
  def ExpandNames(self):
10438
    # This raises errors.OpPrereqError on its own:
10439
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10440

    
10441
    self.needed_locks = {
10442
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10443
      }
10444

    
10445
  def CheckPrereq(self):
10446
    """Check prerequisites.
10447

10448
    """
10449
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
10450

    
10451
    if self.group is None:
10452
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10453
                               (self.op.group_name, self.group_uuid))
10454

    
10455
    if self.op.ndparams:
10456
      new_ndparams = _GetUpdatedParams(self.group.ndparams, self.op.ndparams)
10457
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
10458
      self.new_ndparams = new_ndparams
10459

    
10460
  def BuildHooksEnv(self):
10461
    """Build hooks env.
10462

10463
    """
10464
    env = {
10465
      "GROUP_NAME": self.op.group_name,
10466
      "NEW_ALLOC_POLICY": self.op.alloc_policy,
10467
      }
10468
    mn = self.cfg.GetMasterNode()
10469
    return env, [mn], [mn]
10470

    
10471
  def Exec(self, feedback_fn):
10472
    """Modifies the node group.
10473

10474
    """
10475
    result = []
10476

    
10477
    if self.op.ndparams:
10478
      self.group.ndparams = self.new_ndparams
10479
      result.append(("ndparams", str(self.group.ndparams)))
10480

    
10481
    if self.op.alloc_policy:
10482
      self.group.alloc_policy = self.op.alloc_policy
10483

    
10484
    self.cfg.Update(self.group, feedback_fn)
10485
    return result
10486

    
10487

    
10488

    
10489
class LUGroupRemove(LogicalUnit):
10490
  HPATH = "group-remove"
10491
  HTYPE = constants.HTYPE_GROUP
10492
  REQ_BGL = False
10493

    
10494
  def ExpandNames(self):
10495
    # This will raises errors.OpPrereqError on its own:
10496
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10497
    self.needed_locks = {
10498
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10499
      }
10500

    
10501
  def CheckPrereq(self):
10502
    """Check prerequisites.
10503

10504
    This checks that the given group name exists as a node group, that is
10505
    empty (i.e., contains no nodes), and that is not the last group of the
10506
    cluster.
10507

10508
    """
10509
    # Verify that the group is empty.
10510
    group_nodes = [node.name
10511
                   for node in self.cfg.GetAllNodesInfo().values()
10512
                   if node.group == self.group_uuid]
10513

    
10514
    if group_nodes:
10515
      raise errors.OpPrereqError("Group '%s' not empty, has the following"
10516
                                 " nodes: %s" %
10517
                                 (self.op.group_name,
10518
                                  utils.CommaJoin(utils.NiceSort(group_nodes))),
10519
                                 errors.ECODE_STATE)
10520

    
10521
    # Verify the cluster would not be left group-less.
10522
    if len(self.cfg.GetNodeGroupList()) == 1:
10523
      raise errors.OpPrereqError("Group '%s' is the only group,"
10524
                                 " cannot be removed" %
10525
                                 self.op.group_name,
10526
                                 errors.ECODE_STATE)
10527

    
10528
  def BuildHooksEnv(self):
10529
    """Build hooks env.
10530

10531
    """
10532
    env = {
10533
      "GROUP_NAME": self.op.group_name,
10534
      }
10535
    mn = self.cfg.GetMasterNode()
10536
    return env, [mn], [mn]
10537

    
10538
  def Exec(self, feedback_fn):
10539
    """Remove the node group.
10540

10541
    """
10542
    try:
10543
      self.cfg.RemoveNodeGroup(self.group_uuid)
10544
    except errors.ConfigurationError:
10545
      raise errors.OpExecError("Group '%s' with UUID %s disappeared" %
10546
                               (self.op.group_name, self.group_uuid))
10547

    
10548
    self.remove_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
10549

    
10550

    
10551
class LUGroupRename(LogicalUnit):
10552
  HPATH = "group-rename"
10553
  HTYPE = constants.HTYPE_GROUP
10554
  REQ_BGL = False
10555

    
10556
  def ExpandNames(self):
10557
    # This raises errors.OpPrereqError on its own:
10558
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.old_name)
10559

    
10560
    self.needed_locks = {
10561
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10562
      }
10563

    
10564
  def CheckPrereq(self):
10565
    """Check prerequisites.
10566

10567
    This checks that the given old_name exists as a node group, and that
10568
    new_name doesn't.
10569

10570
    """
10571
    try:
10572
      new_name_uuid = self.cfg.LookupNodeGroup(self.op.new_name)
10573
    except errors.OpPrereqError:
10574
      pass
10575
    else:
10576
      raise errors.OpPrereqError("Desired new name '%s' clashes with existing"
10577
                                 " node group (UUID: %s)" %
10578
                                 (self.op.new_name, new_name_uuid),
10579
                                 errors.ECODE_EXISTS)
10580

    
10581
  def BuildHooksEnv(self):
10582
    """Build hooks env.
10583

10584
    """
10585
    env = {
10586
      "OLD_NAME": self.op.old_name,
10587
      "NEW_NAME": self.op.new_name,
10588
      }
10589

    
10590
    mn = self.cfg.GetMasterNode()
10591
    all_nodes = self.cfg.GetAllNodesInfo()
10592
    run_nodes = [mn]
10593
    all_nodes.pop(mn, None)
10594

    
10595
    for node in all_nodes.values():
10596
      if node.group == self.group_uuid:
10597
        run_nodes.append(node.name)
10598

    
10599
    return env, run_nodes, run_nodes
10600

    
10601
  def Exec(self, feedback_fn):
10602
    """Rename the node group.
10603

10604
    """
10605
    group = self.cfg.GetNodeGroup(self.group_uuid)
10606

    
10607
    if group is None:
10608
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10609
                               (self.op.old_name, self.group_uuid))
10610

    
10611
    group.name = self.op.new_name
10612
    self.cfg.Update(group, feedback_fn)
10613

    
10614
    return self.op.new_name
10615

    
10616

    
10617
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
10618
  """Generic tags LU.
10619

10620
  This is an abstract class which is the parent of all the other tags LUs.
10621

10622
  """
10623

    
10624
  def ExpandNames(self):
10625
    self.needed_locks = {}
10626
    if self.op.kind == constants.TAG_NODE:
10627
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
10628
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
10629
    elif self.op.kind == constants.TAG_INSTANCE:
10630
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
10631
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
10632

    
10633
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
10634
    # not possible to acquire the BGL based on opcode parameters)
10635

    
10636
  def CheckPrereq(self):
10637
    """Check prerequisites.
10638

10639
    """
10640
    if self.op.kind == constants.TAG_CLUSTER:
10641
      self.target = self.cfg.GetClusterInfo()
10642
    elif self.op.kind == constants.TAG_NODE:
10643
      self.target = self.cfg.GetNodeInfo(self.op.name)
10644
    elif self.op.kind == constants.TAG_INSTANCE:
10645
      self.target = self.cfg.GetInstanceInfo(self.op.name)
10646
    else:
10647
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
10648
                                 str(self.op.kind), errors.ECODE_INVAL)
10649

    
10650

    
10651
class LUTagsGet(TagsLU):
10652
  """Returns the tags of a given object.
10653

10654
  """
10655
  REQ_BGL = False
10656

    
10657
  def ExpandNames(self):
10658
    TagsLU.ExpandNames(self)
10659

    
10660
    # Share locks as this is only a read operation
10661
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
10662

    
10663
  def Exec(self, feedback_fn):
10664
    """Returns the tag list.
10665

10666
    """
10667
    return list(self.target.GetTags())
10668

    
10669

    
10670
class LUTagsSearch(NoHooksLU):
10671
  """Searches the tags for a given pattern.
10672

10673
  """
10674
  REQ_BGL = False
10675

    
10676
  def ExpandNames(self):
10677
    self.needed_locks = {}
10678

    
10679
  def CheckPrereq(self):
10680
    """Check prerequisites.
10681

10682
    This checks the pattern passed for validity by compiling it.
10683

10684
    """
10685
    try:
10686
      self.re = re.compile(self.op.pattern)
10687
    except re.error, err:
10688
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
10689
                                 (self.op.pattern, err), errors.ECODE_INVAL)
10690

    
10691
  def Exec(self, feedback_fn):
10692
    """Returns the tag list.
10693

10694
    """
10695
    cfg = self.cfg
10696
    tgts = [("/cluster", cfg.GetClusterInfo())]
10697
    ilist = cfg.GetAllInstancesInfo().values()
10698
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
10699
    nlist = cfg.GetAllNodesInfo().values()
10700
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
10701
    results = []
10702
    for path, target in tgts:
10703
      for tag in target.GetTags():
10704
        if self.re.search(tag):
10705
          results.append((path, tag))
10706
    return results
10707

    
10708

    
10709
class LUTagsSet(TagsLU):
10710
  """Sets a tag on a given object.
10711

10712
  """
10713
  REQ_BGL = False
10714

    
10715
  def CheckPrereq(self):
10716
    """Check prerequisites.
10717

10718
    This checks the type and length of the tag name and value.
10719

10720
    """
10721
    TagsLU.CheckPrereq(self)
10722
    for tag in self.op.tags:
10723
      objects.TaggableObject.ValidateTag(tag)
10724

    
10725
  def Exec(self, feedback_fn):
10726
    """Sets the tag.
10727

10728
    """
10729
    try:
10730
      for tag in self.op.tags:
10731
        self.target.AddTag(tag)
10732
    except errors.TagError, err:
10733
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
10734
    self.cfg.Update(self.target, feedback_fn)
10735

    
10736

    
10737
class LUTagsDel(TagsLU):
10738
  """Delete a list of tags from a given object.
10739

10740
  """
10741
  REQ_BGL = False
10742

    
10743
  def CheckPrereq(self):
10744
    """Check prerequisites.
10745

10746
    This checks that we have the given tag.
10747

10748
    """
10749
    TagsLU.CheckPrereq(self)
10750
    for tag in self.op.tags:
10751
      objects.TaggableObject.ValidateTag(tag)
10752
    del_tags = frozenset(self.op.tags)
10753
    cur_tags = self.target.GetTags()
10754

    
10755
    diff_tags = del_tags - cur_tags
10756
    if diff_tags:
10757
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
10758
      raise errors.OpPrereqError("Tag(s) %s not found" %
10759
                                 (utils.CommaJoin(diff_names), ),
10760
                                 errors.ECODE_NOENT)
10761

    
10762
  def Exec(self, feedback_fn):
10763
    """Remove the tag from the object.
10764

10765
    """
10766
    for tag in self.op.tags:
10767
      self.target.RemoveTag(tag)
10768
    self.cfg.Update(self.target, feedback_fn)
10769

    
10770

    
10771
class LUTestDelay(NoHooksLU):
10772
  """Sleep for a specified amount of time.
10773

10774
  This LU sleeps on the master and/or nodes for a specified amount of
10775
  time.
10776

10777
  """
10778
  REQ_BGL = False
10779

    
10780
  def ExpandNames(self):
10781
    """Expand names and set required locks.
10782

10783
    This expands the node list, if any.
10784

10785
    """
10786
    self.needed_locks = {}
10787
    if self.op.on_nodes:
10788
      # _GetWantedNodes can be used here, but is not always appropriate to use
10789
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
10790
      # more information.
10791
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
10792
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
10793

    
10794
  def _TestDelay(self):
10795
    """Do the actual sleep.
10796

10797
    """
10798
    if self.op.on_master:
10799
      if not utils.TestDelay(self.op.duration):
10800
        raise errors.OpExecError("Error during master delay test")
10801
    if self.op.on_nodes:
10802
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
10803
      for node, node_result in result.items():
10804
        node_result.Raise("Failure during rpc call to node %s" % node)
10805

    
10806
  def Exec(self, feedback_fn):
10807
    """Execute the test delay opcode, with the wanted repetitions.
10808

10809
    """
10810
    if self.op.repeat == 0:
10811
      self._TestDelay()
10812
    else:
10813
      top_value = self.op.repeat - 1
10814
      for i in range(self.op.repeat):
10815
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
10816
        self._TestDelay()
10817

    
10818

    
10819
class LUTestJqueue(NoHooksLU):
10820
  """Utility LU to test some aspects of the job queue.
10821

10822
  """
10823
  REQ_BGL = False
10824

    
10825
  # Must be lower than default timeout for WaitForJobChange to see whether it
10826
  # notices changed jobs
10827
  _CLIENT_CONNECT_TIMEOUT = 20.0
10828
  _CLIENT_CONFIRM_TIMEOUT = 60.0
10829

    
10830
  @classmethod
10831
  def _NotifyUsingSocket(cls, cb, errcls):
10832
    """Opens a Unix socket and waits for another program to connect.
10833

10834
    @type cb: callable
10835
    @param cb: Callback to send socket name to client
10836
    @type errcls: class
10837
    @param errcls: Exception class to use for errors
10838

10839
    """
10840
    # Using a temporary directory as there's no easy way to create temporary
10841
    # sockets without writing a custom loop around tempfile.mktemp and
10842
    # socket.bind
10843
    tmpdir = tempfile.mkdtemp()
10844
    try:
10845
      tmpsock = utils.PathJoin(tmpdir, "sock")
10846

    
10847
      logging.debug("Creating temporary socket at %s", tmpsock)
10848
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
10849
      try:
10850
        sock.bind(tmpsock)
10851
        sock.listen(1)
10852

    
10853
        # Send details to client
10854
        cb(tmpsock)
10855

    
10856
        # Wait for client to connect before continuing
10857
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
10858
        try:
10859
          (conn, _) = sock.accept()
10860
        except socket.error, err:
10861
          raise errcls("Client didn't connect in time (%s)" % err)
10862
      finally:
10863
        sock.close()
10864
    finally:
10865
      # Remove as soon as client is connected
10866
      shutil.rmtree(tmpdir)
10867

    
10868
    # Wait for client to close
10869
    try:
10870
      try:
10871
        # pylint: disable-msg=E1101
10872
        # Instance of '_socketobject' has no ... member
10873
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
10874
        conn.recv(1)
10875
      except socket.error, err:
10876
        raise errcls("Client failed to confirm notification (%s)" % err)
10877
    finally:
10878
      conn.close()
10879

    
10880
  def _SendNotification(self, test, arg, sockname):
10881
    """Sends a notification to the client.
10882

10883
    @type test: string
10884
    @param test: Test name
10885
    @param arg: Test argument (depends on test)
10886
    @type sockname: string
10887
    @param sockname: Socket path
10888

10889
    """
10890
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
10891

    
10892
  def _Notify(self, prereq, test, arg):
10893
    """Notifies the client of a test.
10894

10895
    @type prereq: bool
10896
    @param prereq: Whether this is a prereq-phase test
10897
    @type test: string
10898
    @param test: Test name
10899
    @param arg: Test argument (depends on test)
10900

10901
    """
10902
    if prereq:
10903
      errcls = errors.OpPrereqError
10904
    else:
10905
      errcls = errors.OpExecError
10906

    
10907
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
10908
                                                  test, arg),
10909
                                   errcls)
10910

    
10911
  def CheckArguments(self):
10912
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
10913
    self.expandnames_calls = 0
10914

    
10915
  def ExpandNames(self):
10916
    checkargs_calls = getattr(self, "checkargs_calls", 0)
10917
    if checkargs_calls < 1:
10918
      raise errors.ProgrammerError("CheckArguments was not called")
10919

    
10920
    self.expandnames_calls += 1
10921

    
10922
    if self.op.notify_waitlock:
10923
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
10924

    
10925
    self.LogInfo("Expanding names")
10926

    
10927
    # Get lock on master node (just to get a lock, not for a particular reason)
10928
    self.needed_locks = {
10929
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
10930
      }
10931

    
10932
  def Exec(self, feedback_fn):
10933
    if self.expandnames_calls < 1:
10934
      raise errors.ProgrammerError("ExpandNames was not called")
10935

    
10936
    if self.op.notify_exec:
10937
      self._Notify(False, constants.JQT_EXEC, None)
10938

    
10939
    self.LogInfo("Executing")
10940

    
10941
    if self.op.log_messages:
10942
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
10943
      for idx, msg in enumerate(self.op.log_messages):
10944
        self.LogInfo("Sending log message %s", idx + 1)
10945
        feedback_fn(constants.JQT_MSGPREFIX + msg)
10946
        # Report how many test messages have been sent
10947
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
10948

    
10949
    if self.op.fail:
10950
      raise errors.OpExecError("Opcode failure was requested")
10951

    
10952
    return True
10953

    
10954

    
10955
class IAllocator(object):
10956
  """IAllocator framework.
10957

10958
  An IAllocator instance has three sets of attributes:
10959
    - cfg that is needed to query the cluster
10960
    - input data (all members of the _KEYS class attribute are required)
10961
    - four buffer attributes (in|out_data|text), that represent the
10962
      input (to the external script) in text and data structure format,
10963
      and the output from it, again in two formats
10964
    - the result variables from the script (success, info, nodes) for
10965
      easy usage
10966

10967
  """
10968
  # pylint: disable-msg=R0902
10969
  # lots of instance attributes
10970
  _ALLO_KEYS = [
10971
    "name", "mem_size", "disks", "disk_template",
10972
    "os", "tags", "nics", "vcpus", "hypervisor",
10973
    ]
10974
  _RELO_KEYS = [
10975
    "name", "relocate_from",
10976
    ]
10977
  _EVAC_KEYS = [
10978
    "evac_nodes",
10979
    ]
10980

    
10981
  def __init__(self, cfg, rpc, mode, **kwargs):
10982
    self.cfg = cfg
10983
    self.rpc = rpc
10984
    # init buffer variables
10985
    self.in_text = self.out_text = self.in_data = self.out_data = None
10986
    # init all input fields so that pylint is happy
10987
    self.mode = mode
10988
    self.mem_size = self.disks = self.disk_template = None
10989
    self.os = self.tags = self.nics = self.vcpus = None
10990
    self.hypervisor = None
10991
    self.relocate_from = None
10992
    self.name = None
10993
    self.evac_nodes = None
10994
    # computed fields
10995
    self.required_nodes = None
10996
    # init result fields
10997
    self.success = self.info = self.result = None
10998
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10999
      keyset = self._ALLO_KEYS
11000
      fn = self._AddNewInstance
11001
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
11002
      keyset = self._RELO_KEYS
11003
      fn = self._AddRelocateInstance
11004
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
11005
      keyset = self._EVAC_KEYS
11006
      fn = self._AddEvacuateNodes
11007
    else:
11008
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
11009
                                   " IAllocator" % self.mode)
11010
    for key in kwargs:
11011
      if key not in keyset:
11012
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
11013
                                     " IAllocator" % key)
11014
      setattr(self, key, kwargs[key])
11015

    
11016
    for key in keyset:
11017
      if key not in kwargs:
11018
        raise errors.ProgrammerError("Missing input parameter '%s' to"
11019
                                     " IAllocator" % key)
11020
    self._BuildInputData(fn)
11021

    
11022
  def _ComputeClusterData(self):
11023
    """Compute the generic allocator input data.
11024

11025
    This is the data that is independent of the actual operation.
11026

11027
    """
11028
    cfg = self.cfg
11029
    cluster_info = cfg.GetClusterInfo()
11030
    # cluster data
11031
    data = {
11032
      "version": constants.IALLOCATOR_VERSION,
11033
      "cluster_name": cfg.GetClusterName(),
11034
      "cluster_tags": list(cluster_info.GetTags()),
11035
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
11036
      # we don't have job IDs
11037
      }
11038
    ninfo = cfg.GetAllNodesInfo()
11039
    iinfo = cfg.GetAllInstancesInfo().values()
11040
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
11041

    
11042
    # node data
11043
    node_list = [n.name for n in ninfo.values() if n.vm_capable]
11044

    
11045
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
11046
      hypervisor_name = self.hypervisor
11047
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
11048
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
11049
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
11050
      hypervisor_name = cluster_info.enabled_hypervisors[0]
11051

    
11052
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
11053
                                        hypervisor_name)
11054
    node_iinfo = \
11055
      self.rpc.call_all_instances_info(node_list,
11056
                                       cluster_info.enabled_hypervisors)
11057

    
11058
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
11059

    
11060
    config_ndata = self._ComputeBasicNodeData(ninfo)
11061
    data["nodes"] = self._ComputeDynamicNodeData(ninfo, node_data, node_iinfo,
11062
                                                 i_list, config_ndata)
11063
    assert len(data["nodes"]) == len(ninfo), \
11064
        "Incomplete node data computed"
11065

    
11066
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
11067

    
11068
    self.in_data = data
11069

    
11070
  @staticmethod
11071
  def _ComputeNodeGroupData(cfg):
11072
    """Compute node groups data.
11073

11074
    """
11075
    ng = {}
11076
    for guuid, gdata in cfg.GetAllNodeGroupsInfo().items():
11077
      ng[guuid] = {
11078
        "name": gdata.name,
11079
        "alloc_policy": gdata.alloc_policy,
11080
        }
11081
    return ng
11082

    
11083
  @staticmethod
11084
  def _ComputeBasicNodeData(node_cfg):
11085
    """Compute global node data.
11086

11087
    @rtype: dict
11088
    @returns: a dict of name: (node dict, node config)
11089

11090
    """
11091
    node_results = {}
11092
    for ninfo in node_cfg.values():
11093
      # fill in static (config-based) values
11094
      pnr = {
11095
        "tags": list(ninfo.GetTags()),
11096
        "primary_ip": ninfo.primary_ip,
11097
        "secondary_ip": ninfo.secondary_ip,
11098
        "offline": ninfo.offline,
11099
        "drained": ninfo.drained,
11100
        "master_candidate": ninfo.master_candidate,
11101
        "group": ninfo.group,
11102
        "master_capable": ninfo.master_capable,
11103
        "vm_capable": ninfo.vm_capable,
11104
        }
11105

    
11106
      node_results[ninfo.name] = pnr
11107

    
11108
    return node_results
11109

    
11110
  @staticmethod
11111
  def _ComputeDynamicNodeData(node_cfg, node_data, node_iinfo, i_list,
11112
                              node_results):
11113
    """Compute global node data.
11114

11115
    @param node_results: the basic node structures as filled from the config
11116

11117
    """
11118
    # make a copy of the current dict
11119
    node_results = dict(node_results)
11120
    for nname, nresult in node_data.items():
11121
      assert nname in node_results, "Missing basic data for node %s" % nname
11122
      ninfo = node_cfg[nname]
11123

    
11124
      if not (ninfo.offline or ninfo.drained):
11125
        nresult.Raise("Can't get data for node %s" % nname)
11126
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
11127
                                nname)
11128
        remote_info = nresult.payload
11129

    
11130
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
11131
                     'vg_size', 'vg_free', 'cpu_total']:
11132
          if attr not in remote_info:
11133
            raise errors.OpExecError("Node '%s' didn't return attribute"
11134
                                     " '%s'" % (nname, attr))
11135
          if not isinstance(remote_info[attr], int):
11136
            raise errors.OpExecError("Node '%s' returned invalid value"
11137
                                     " for '%s': %s" %
11138
                                     (nname, attr, remote_info[attr]))
11139
        # compute memory used by primary instances
11140
        i_p_mem = i_p_up_mem = 0
11141
        for iinfo, beinfo in i_list:
11142
          if iinfo.primary_node == nname:
11143
            i_p_mem += beinfo[constants.BE_MEMORY]
11144
            if iinfo.name not in node_iinfo[nname].payload:
11145
              i_used_mem = 0
11146
            else:
11147
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
11148
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
11149
            remote_info['memory_free'] -= max(0, i_mem_diff)
11150

    
11151
            if iinfo.admin_up:
11152
              i_p_up_mem += beinfo[constants.BE_MEMORY]
11153

    
11154
        # compute memory used by instances
11155
        pnr_dyn = {
11156
          "total_memory": remote_info['memory_total'],
11157
          "reserved_memory": remote_info['memory_dom0'],
11158
          "free_memory": remote_info['memory_free'],
11159
          "total_disk": remote_info['vg_size'],
11160
          "free_disk": remote_info['vg_free'],
11161
          "total_cpus": remote_info['cpu_total'],
11162
          "i_pri_memory": i_p_mem,
11163
          "i_pri_up_memory": i_p_up_mem,
11164
          }
11165
        pnr_dyn.update(node_results[nname])
11166
        node_results[nname] = pnr_dyn
11167

    
11168
    return node_results
11169

    
11170
  @staticmethod
11171
  def _ComputeInstanceData(cluster_info, i_list):
11172
    """Compute global instance data.
11173

11174
    """
11175
    instance_data = {}
11176
    for iinfo, beinfo in i_list:
11177
      nic_data = []
11178
      for nic in iinfo.nics:
11179
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
11180
        nic_dict = {"mac": nic.mac,
11181
                    "ip": nic.ip,
11182
                    "mode": filled_params[constants.NIC_MODE],
11183
                    "link": filled_params[constants.NIC_LINK],
11184
                   }
11185
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
11186
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
11187
        nic_data.append(nic_dict)
11188
      pir = {
11189
        "tags": list(iinfo.GetTags()),
11190
        "admin_up": iinfo.admin_up,
11191
        "vcpus": beinfo[constants.BE_VCPUS],
11192
        "memory": beinfo[constants.BE_MEMORY],
11193
        "os": iinfo.os,
11194
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
11195
        "nics": nic_data,
11196
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
11197
        "disk_template": iinfo.disk_template,
11198
        "hypervisor": iinfo.hypervisor,
11199
        }
11200
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
11201
                                                 pir["disks"])
11202
      instance_data[iinfo.name] = pir
11203

    
11204
    return instance_data
11205

    
11206
  def _AddNewInstance(self):
11207
    """Add new instance data to allocator structure.
11208

11209
    This in combination with _AllocatorGetClusterData will create the
11210
    correct structure needed as input for the allocator.
11211

11212
    The checks for the completeness of the opcode must have already been
11213
    done.
11214

11215
    """
11216
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
11217

    
11218
    if self.disk_template in constants.DTS_NET_MIRROR:
11219
      self.required_nodes = 2
11220
    else:
11221
      self.required_nodes = 1
11222
    request = {
11223
      "name": self.name,
11224
      "disk_template": self.disk_template,
11225
      "tags": self.tags,
11226
      "os": self.os,
11227
      "vcpus": self.vcpus,
11228
      "memory": self.mem_size,
11229
      "disks": self.disks,
11230
      "disk_space_total": disk_space,
11231
      "nics": self.nics,
11232
      "required_nodes": self.required_nodes,
11233
      }
11234
    return request
11235

    
11236
  def _AddRelocateInstance(self):
11237
    """Add relocate instance data to allocator structure.
11238

11239
    This in combination with _IAllocatorGetClusterData will create the
11240
    correct structure needed as input for the allocator.
11241

11242
    The checks for the completeness of the opcode must have already been
11243
    done.
11244

11245
    """
11246
    instance = self.cfg.GetInstanceInfo(self.name)
11247
    if instance is None:
11248
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
11249
                                   " IAllocator" % self.name)
11250

    
11251
    if instance.disk_template not in constants.DTS_NET_MIRROR:
11252
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
11253
                                 errors.ECODE_INVAL)
11254

    
11255
    if len(instance.secondary_nodes) != 1:
11256
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
11257
                                 errors.ECODE_STATE)
11258

    
11259
    self.required_nodes = 1
11260
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
11261
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
11262

    
11263
    request = {
11264
      "name": self.name,
11265
      "disk_space_total": disk_space,
11266
      "required_nodes": self.required_nodes,
11267
      "relocate_from": self.relocate_from,
11268
      }
11269
    return request
11270

    
11271
  def _AddEvacuateNodes(self):
11272
    """Add evacuate nodes data to allocator structure.
11273

11274
    """
11275
    request = {
11276
      "evac_nodes": self.evac_nodes
11277
      }
11278
    return request
11279

    
11280
  def _BuildInputData(self, fn):
11281
    """Build input data structures.
11282

11283
    """
11284
    self._ComputeClusterData()
11285

    
11286
    request = fn()
11287
    request["type"] = self.mode
11288
    self.in_data["request"] = request
11289

    
11290
    self.in_text = serializer.Dump(self.in_data)
11291

    
11292
  def Run(self, name, validate=True, call_fn=None):
11293
    """Run an instance allocator and return the results.
11294

11295
    """
11296
    if call_fn is None:
11297
      call_fn = self.rpc.call_iallocator_runner
11298

    
11299
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
11300
    result.Raise("Failure while running the iallocator script")
11301

    
11302
    self.out_text = result.payload
11303
    if validate:
11304
      self._ValidateResult()
11305

    
11306
  def _ValidateResult(self):
11307
    """Process the allocator results.
11308

11309
    This will process and if successful save the result in
11310
    self.out_data and the other parameters.
11311

11312
    """
11313
    try:
11314
      rdict = serializer.Load(self.out_text)
11315
    except Exception, err:
11316
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
11317

    
11318
    if not isinstance(rdict, dict):
11319
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
11320

    
11321
    # TODO: remove backwards compatiblity in later versions
11322
    if "nodes" in rdict and "result" not in rdict:
11323
      rdict["result"] = rdict["nodes"]
11324
      del rdict["nodes"]
11325

    
11326
    for key in "success", "info", "result":
11327
      if key not in rdict:
11328
        raise errors.OpExecError("Can't parse iallocator results:"
11329
                                 " missing key '%s'" % key)
11330
      setattr(self, key, rdict[key])
11331

    
11332
    if not isinstance(rdict["result"], list):
11333
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
11334
                               " is not a list")
11335
    self.out_data = rdict
11336

    
11337

    
11338
class LUTestAllocator(NoHooksLU):
11339
  """Run allocator tests.
11340

11341
  This LU runs the allocator tests
11342

11343
  """
11344
  def CheckPrereq(self):
11345
    """Check prerequisites.
11346

11347
    This checks the opcode parameters depending on the director and mode test.
11348

11349
    """
11350
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
11351
      for attr in ["mem_size", "disks", "disk_template",
11352
                   "os", "tags", "nics", "vcpus"]:
11353
        if not hasattr(self.op, attr):
11354
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
11355
                                     attr, errors.ECODE_INVAL)
11356
      iname = self.cfg.ExpandInstanceName(self.op.name)
11357
      if iname is not None:
11358
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
11359
                                   iname, errors.ECODE_EXISTS)
11360
      if not isinstance(self.op.nics, list):
11361
        raise errors.OpPrereqError("Invalid parameter 'nics'",
11362
                                   errors.ECODE_INVAL)
11363
      if not isinstance(self.op.disks, list):
11364
        raise errors.OpPrereqError("Invalid parameter 'disks'",
11365
                                   errors.ECODE_INVAL)
11366
      for row in self.op.disks:
11367
        if (not isinstance(row, dict) or
11368
            "size" not in row or
11369
            not isinstance(row["size"], int) or
11370
            "mode" not in row or
11371
            row["mode"] not in ['r', 'w']):
11372
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
11373
                                     " parameter", errors.ECODE_INVAL)
11374
      if self.op.hypervisor is None:
11375
        self.op.hypervisor = self.cfg.GetHypervisorType()
11376
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
11377
      fname = _ExpandInstanceName(self.cfg, self.op.name)
11378
      self.op.name = fname
11379
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
11380
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
11381
      if not hasattr(self.op, "evac_nodes"):
11382
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
11383
                                   " opcode input", errors.ECODE_INVAL)
11384
    else:
11385
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
11386
                                 self.op.mode, errors.ECODE_INVAL)
11387

    
11388
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
11389
      if self.op.allocator is None:
11390
        raise errors.OpPrereqError("Missing allocator name",
11391
                                   errors.ECODE_INVAL)
11392
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
11393
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
11394
                                 self.op.direction, errors.ECODE_INVAL)
11395

    
11396
  def Exec(self, feedback_fn):
11397
    """Run the allocator test.
11398

11399
    """
11400
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
11401
      ial = IAllocator(self.cfg, self.rpc,
11402
                       mode=self.op.mode,
11403
                       name=self.op.name,
11404
                       mem_size=self.op.mem_size,
11405
                       disks=self.op.disks,
11406
                       disk_template=self.op.disk_template,
11407
                       os=self.op.os,
11408
                       tags=self.op.tags,
11409
                       nics=self.op.nics,
11410
                       vcpus=self.op.vcpus,
11411
                       hypervisor=self.op.hypervisor,
11412
                       )
11413
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
11414
      ial = IAllocator(self.cfg, self.rpc,
11415
                       mode=self.op.mode,
11416
                       name=self.op.name,
11417
                       relocate_from=list(self.relocate_from),
11418
                       )
11419
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
11420
      ial = IAllocator(self.cfg, self.rpc,
11421
                       mode=self.op.mode,
11422
                       evac_nodes=self.op.evac_nodes)
11423
    else:
11424
      raise errors.ProgrammerError("Uncatched mode %s in"
11425
                                   " LUTestAllocator.Exec", self.op.mode)
11426

    
11427
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
11428
      result = ial.in_text
11429
    else:
11430
      ial.Run(self.op.allocator, validate=False)
11431
      result = ial.out_text
11432
    return result
11433

    
11434

    
11435
#: Query type implementations
11436
_QUERY_IMPL = {
11437
  constants.QR_INSTANCE: _InstanceQuery,
11438
  constants.QR_NODE: _NodeQuery,
11439
  constants.QR_GROUP: _GroupQuery,
11440
  }
11441

    
11442

    
11443
def _GetQueryImplementation(name):
11444
  """Returns the implemtnation for a query type.
11445

11446
  @param name: Query type, must be one of L{constants.QR_OP_QUERY}
11447

11448
  """
11449
  try:
11450
    return _QUERY_IMPL[name]
11451
  except KeyError:
11452
    raise errors.OpPrereqError("Unknown query resource '%s'" % name,
11453
                               errors.ECODE_INVAL)