Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 74f258b6

History | View | Annotate | Download (396.4 kB)

1
#
2
#
3

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

    
21

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

    
24
# pylint: disable-msg=W0201,C0302
25

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

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

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

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

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

    
63

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

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

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

    
76

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

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

90
  Note that all commands require root permissions.
91

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

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

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

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

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

    
133
    # Tasklets
134
    self.tasklets = None
135

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

    
139
    self.CheckArguments()
140

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

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

    
149
  ssh = property(fget=__GetSSH)
150

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

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

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

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

166
    """
167
    pass
168

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

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

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

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

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

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

194
    Examples::
195

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

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

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

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

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

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

233
    """
234

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

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

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

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

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

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

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

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

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

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

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

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

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

292
    """
293
    raise NotImplementedError
294

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
381
    del self.recalculate_locks[locking.LEVEL_NODE]
382

    
383

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

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

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

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

397
    This just raises an error.
398

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

    
402

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

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

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

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

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

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

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

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

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

435
    """
436
    pass
437

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

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

445
    """
446
    raise NotImplementedError
447

    
448

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

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

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

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

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

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

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

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

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

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

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

    
492
    # Return expanded names
493
    return self.wanted
494

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

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

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

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

507
    See L{LogicalUnit.ExpandNames}.
508

509
    """
510
    raise NotImplementedError()
511

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

515
    See L{LogicalUnit.DeclareLocks}.
516

517
    """
518
    raise NotImplementedError()
519

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

523
    @return: Query data object
524

525
    """
526
    raise NotImplementedError()
527

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

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

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

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

    
540

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

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

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

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

    
558

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

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

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

    
578

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

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

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

    
611

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

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

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

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

    
630

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

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

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

    
645

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

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

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

    
660

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

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

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

    
673

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

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

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

    
686

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

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

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

    
704

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

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

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

    
731

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

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

    
739

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

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

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

    
755

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

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

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

    
772

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

    
777

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

    
782

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

788
  This builds the hook environment from individual variables.
789

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

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

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

    
852
  env["INSTANCE_NIC_COUNT"] = nic_count
853

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

    
862
  env["INSTANCE_DISK_COUNT"] = disk_count
863

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

    
868
  return env
869

    
870

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

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

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

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

    
894

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

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

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

    
932

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

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

    
948

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

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

    
959

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

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

    
973

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

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

    
982

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

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

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

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

    
1002

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

    
1006

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

1010
  """
1011

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

    
1014

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

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

    
1022

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

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

    
1030

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

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

    
1040
  return []
1041

    
1042

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

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

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

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

    
1057
  return faulty
1058

    
1059

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

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

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

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

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

    
1091

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

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

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

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

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

1110
    """
1111
    return True
1112

    
1113

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

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

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

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

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

1131
    This checks whether the cluster is empty.
1132

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

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

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

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

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

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

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

    
1166
    return master
1167

    
1168

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

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

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

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

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

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

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

    
1201

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1412
    return True
1413

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1773
    nimg.os_fail = test
1774

    
1775
    if test:
1776
      return
1777

    
1778
    os_dict = {}
1779

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

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

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

    
1792
    nimg.oslist = os_dict
1793

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1987
      node_disks[nname] = disks
1988

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

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

    
1996
      node_disks_devonly[nname] = devonly
1997

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

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

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

    
2006
    instdisk = {}
2007

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

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

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

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

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

    
2047
    return instdisk
2048

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

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

    
2063

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

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

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

    
2078
    return env, [], all_nodes
2079

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

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

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

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

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

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

    
2127
    local_checksums = utils.FingerprintFiles(file_names)
2128

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

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

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

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

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

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

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

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

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

    
2203
      inst_config.MapLVsByNode(node_vol_should)
2204

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

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

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

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

    
2227
    all_drbd_map = self.cfg.ComputeDRBDMap()
2228

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

    
2232
    feedback_fn("* Verifying node status")
2233

    
2234
    refos_img = None
2235

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

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

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

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

    
2264
      nresult = all_nvinfo[node].payload
2265

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

    
2272
      self._VerifyOob(node_i, nresult)
2273

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2388
    return not self.bad
2389

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

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

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

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

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

    
2433
      return lu_result
2434

    
2435

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

2439
  """
2440
  REQ_BGL = False
2441

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

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

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

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

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

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

    
2474
    if not nv_dict:
2475
      return result
2476

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

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

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

    
2501
    return result
2502

    
2503

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

2507
  """
2508
  REQ_BGL = False
2509

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2618

    
2619
class LUClusterRename(LogicalUnit):
2620
  """Rename the cluster.
2621

2622
  """
2623
  HPATH = "cluster-rename"
2624
  HTYPE = constants.HTYPE_CLUSTER
2625

    
2626
  def BuildHooksEnv(self):
2627
    """Build hooks env.
2628

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

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

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

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

    
2659
    self.op.name = new_name
2660

    
2661
  def Exec(self, feedback_fn):
2662
    """Rename the cluster.
2663

2664
    """
2665
    clustername = self.op.name
2666
    ip = self.ip
2667

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

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

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

    
2694
    return clustername
2695

    
2696

    
2697
class LUClusterSetParams(LogicalUnit):
2698
  """Change the parameters of the cluster.
2699

2700
  """
2701
  HPATH = "cluster-modify"
2702
  HTYPE = constants.HTYPE_CLUSTER
2703
  REQ_BGL = False
2704

    
2705
  def CheckArguments(self):
2706
    """Check parameters
2707

2708
    """
2709
    if self.op.uid_pool:
2710
      uidpool.CheckUidPool(self.op.uid_pool)
2711

    
2712
    if self.op.add_uids:
2713
      uidpool.CheckUidPool(self.op.add_uids)
2714

    
2715
    if self.op.remove_uids:
2716
      uidpool.CheckUidPool(self.op.remove_uids)
2717

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

    
2726
  def BuildHooksEnv(self):
2727
    """Build hooks env.
2728

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

    
2737
  def CheckPrereq(self):
2738
    """Check prerequisites.
2739

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

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

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

    
2755
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2756

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

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

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

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

    
2802
    if self.op.nicparams:
2803
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2804
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2805
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2806
      nic_errors = []
2807

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

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

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

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

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

    
2852
    # os parameters
2853
    self.new_osp = objects.FillDict(cluster.osparams, {})
2854
    if self.op.osparams:
2855
      for os_name, osp in self.op.osparams.items():
2856
        if os_name not in self.new_osp:
2857
          self.new_osp[os_name] = {}
2858

    
2859
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2860
                                                  use_none=True)
2861

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

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

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

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

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

    
2920
  def Exec(self, feedback_fn):
2921
    """Change the parameters of the cluster.
2922

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

    
2958
    if self.op.candidate_pool_size is not None:
2959
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2960
      # we need to update the pool size here, otherwise the save will fail
2961
      _AdjustCandidatePool(self, [])
2962

    
2963
    if self.op.maintain_node_health is not None:
2964
      self.cluster.maintain_node_health = self.op.maintain_node_health
2965

    
2966
    if self.op.prealloc_wipe_disks is not None:
2967
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
2968

    
2969
    if self.op.add_uids is not None:
2970
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2971

    
2972
    if self.op.remove_uids is not None:
2973
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2974

    
2975
    if self.op.uid_pool is not None:
2976
      self.cluster.uid_pool = self.op.uid_pool
2977

    
2978
    if self.op.default_iallocator is not None:
2979
      self.cluster.default_iallocator = self.op.default_iallocator
2980

    
2981
    if self.op.reserved_lvs is not None:
2982
      self.cluster.reserved_lvs = self.op.reserved_lvs
2983

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

    
3001
    if self.op.hidden_os:
3002
      helper_os("hidden_os", self.op.hidden_os, "hidden")
3003

    
3004
    if self.op.blacklisted_os:
3005
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
3006

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

    
3017
    self.cfg.Update(self.cluster, feedback_fn)
3018

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

    
3028

    
3029
def _UploadHelper(lu, nodes, fname):
3030
  """Helper for uploading a file and showing warnings.
3031

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

    
3042

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

3046
  ConfigWriter takes care of distributing the config and ssconf files, but
3047
  there are more files which should be distributed to all nodes. This function
3048
  makes sure those are copied.
3049

3050
  @param lu: calling logical unit
3051
  @param additional_nodes: list of nodes not in the config to distribute to
3052
  @type additional_vm: boolean
3053
  @param additional_vm: whether the additional nodes are vm-capable or not
3054

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

    
3070
  # 2. Gather files to distribute
3071
  dist_files = set([constants.ETC_HOSTS,
3072
                    constants.SSH_KNOWN_HOSTS_FILE,
3073
                    constants.RAPI_CERT_FILE,
3074
                    constants.RAPI_USERS_FILE,
3075
                    constants.CONFD_HMAC_KEY,
3076
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
3077
                   ])
3078

    
3079
  vm_files = set()
3080
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
3081
  for hv_name in enabled_hypervisors:
3082
    hv_class = hypervisor.GetHypervisor(hv_name)
3083
    vm_files.update(hv_class.GetAncillaryFiles())
3084

    
3085
  # 3. Perform the files upload
3086
  for fname in dist_files:
3087
    _UploadHelper(lu, dist_nodes, fname)
3088
  for fname in vm_files:
3089
    _UploadHelper(lu, vm_nodes, fname)
3090

    
3091

    
3092
class LUClusterRedistConf(NoHooksLU):
3093
  """Force the redistribution of cluster configuration.
3094

3095
  This is a very simple LU.
3096

3097
  """
3098
  REQ_BGL = False
3099

    
3100
  def ExpandNames(self):
3101
    self.needed_locks = {
3102
      locking.LEVEL_NODE: locking.ALL_SET,
3103
    }
3104
    self.share_locks[locking.LEVEL_NODE] = 1
3105

    
3106
  def Exec(self, feedback_fn):
3107
    """Redistribute the configuration.
3108

3109
    """
3110
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
3111
    _RedistributeAncillaryFiles(self)
3112

    
3113

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

3117
  """
3118
  if not instance.disks or disks is not None and not disks:
3119
    return True
3120

    
3121
  disks = _ExpandCheckDisks(instance, disks)
3122

    
3123
  if not oneshot:
3124
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
3125

    
3126
  node = instance.primary_node
3127

    
3128
  for dev in disks:
3129
    lu.cfg.SetDiskID(dev, node)
3130

    
3131
  # TODO: Convert to utils.Retry
3132

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

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

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

    
3179
    if done or oneshot:
3180
      break
3181

    
3182
    time.sleep(min(60, max_time))
3183

    
3184
  if done:
3185
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3186
  return not cumul_degraded
3187

    
3188

    
3189
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3190
  """Check that mirrors are not degraded.
3191

3192
  The ldisk parameter, if True, will change the test from the
3193
  is_degraded attribute (which represents overall non-ok status for
3194
  the device(s)) to the ldisk (representing the local storage status).
3195

3196
  """
3197
  lu.cfg.SetDiskID(dev, node)
3198

    
3199
  result = True
3200

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

    
3216
  if dev.children:
3217
    for child in dev.children:
3218
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3219

    
3220
  return result
3221

    
3222

    
3223
class LUOobCommand(NoHooksLU):
3224
  """Logical unit for OOB handling.
3225

3226
  """
3227
  REG_BGL = False
3228

    
3229
  def CheckPrereq(self):
3230
    """Check prerequisites.
3231

3232
    This checks:
3233
     - the node exists in the configuration
3234
     - OOB is supported
3235

3236
    Any errors are signaled by raising errors.OpPrereqError.
3237

3238
    """
3239
    self.nodes = []
3240
    for node_name in self.op.node_names:
3241
      node = self.cfg.GetNodeInfo(node_name)
3242

    
3243
      if node is None:
3244
        raise errors.OpPrereqError("Node %s not found" % node_name,
3245
                                   errors.ECODE_NOENT)
3246
      else:
3247
        self.nodes.append(node)
3248

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

    
3254
  def ExpandNames(self):
3255
    """Gather locks we need.
3256

3257
    """
3258
    if self.op.node_names:
3259
      self.op.node_names = [_ExpandNodeName(self.cfg, name)
3260
                            for name in self.op.node_names]
3261
    else:
3262
      self.op.node_names = self.cfg.GetNodeList()
3263

    
3264
    self.needed_locks = {
3265
      locking.LEVEL_NODE: self.op.node_names,
3266
      }
3267

    
3268
  def Exec(self, feedback_fn):
3269
    """Execute OOB and return result if we expect any.
3270

3271
    """
3272
    master_node = self.cfg.GetMasterNode()
3273
    ret = []
3274

    
3275
    for node in self.nodes:
3276
      node_entry = [(constants.RS_NORMAL, node.name)]
3277
      ret.append(node_entry)
3278

    
3279
      oob_program = _SupportsOob(self.cfg, node)
3280

    
3281
      if not oob_program:
3282
        node_entry.append((constants.RS_UNAVAIL, None))
3283
        continue
3284

    
3285
      logging.info("Executing out-of-band command '%s' using '%s' on %s",
3286
                   self.op.command, oob_program, node.name)
3287
      result = self.rpc.call_run_oob(master_node, oob_program,
3288
                                     self.op.command, node.name,
3289
                                     self.op.timeout)
3290

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

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

    
3322
          # For configuration changing commands we should update the node
3323
          if self.op.command in (constants.OOB_POWER_ON,
3324
                                 constants.OOB_POWER_OFF):
3325
            self.cfg.Update(node, feedback_fn)
3326

    
3327
          node_entry.append((constants.RS_NORMAL, result.payload))
3328

    
3329
    return ret
3330

    
3331
  def _CheckPayload(self, result):
3332
    """Checks if the payload is valid.
3333

3334
    @param result: RPC result
3335
    @raises errors.OpExecError: If payload is not valid
3336

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

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

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

    
3363
    if errs:
3364
      raise errors.OpExecError("Check of out-of-band payload failed due to %s" %
3365
                               utils.CommaJoin(errs))
3366

    
3367

    
3368

    
3369
class LUOsDiagnose(NoHooksLU):
3370
  """Logical unit for OS diagnose/query.
3371

3372
  """
3373
  REQ_BGL = False
3374
  _HID = "hidden"
3375
  _BLK = "blacklisted"
3376
  _VLD = "valid"
3377
  _FIELDS_STATIC = utils.FieldSet()
3378
  _FIELDS_DYNAMIC = utils.FieldSet("name", _VLD, "node_status", "variants",
3379
                                   "parameters", "api_versions", _HID, _BLK)
3380

    
3381
  def CheckArguments(self):
3382
    if self.op.names:
3383
      raise errors.OpPrereqError("Selective OS query not supported",
3384
                                 errors.ECODE_INVAL)
3385

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

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

    
3398
  @staticmethod
3399
  def _DiagnoseByOS(rlist):
3400
    """Remaps a per-node return list into an a per-os per-node dictionary
3401

3402
    @param rlist: a map with node names as keys and OS objects as values
3403

3404
    @rtype: dict
3405
    @return: a dictionary with osnames as keys and as value another
3406
        map, with nodes as keys and tuples of (path, status, diagnose,
3407
        variants, parameters, api_versions) as values, eg::
3408

3409
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3410
                                     (/srv/..., False, "invalid api")],
3411
                           "node2": [(/srv/..., True, "", [], [])]}
3412
          }
3413

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

    
3438
  def Exec(self, feedback_fn):
3439
    """Compute the list of OSes.
3440

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

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

    
3470
      is_hid = os_name in cluster.hidden_os
3471
      is_blk = os_name in cluster.blacklisted_os
3472
      if ((self._HID not in self.op.output_fields and is_hid) or
3473
          (self._BLK not in self.op.output_fields and is_blk) or
3474
          (self._VLD not in self.op.output_fields and not valid)):
3475
        continue
3476

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

    
3502
    return output
3503

    
3504

    
3505
class LUNodeRemove(LogicalUnit):
3506
  """Logical unit for removing a node.
3507

3508
  """
3509
  HPATH = "node-remove"
3510
  HTYPE = constants.HTYPE_NODE
3511

    
3512
  def BuildHooksEnv(self):
3513
    """Build hooks env.
3514

3515
    This doesn't run on the target node in the pre phase as a failed
3516
    node would then be impossible to remove.
3517

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

    
3531
  def CheckPrereq(self):
3532
    """Check prerequisites.
3533

3534
    This checks:
3535
     - the node exists in the configuration
3536
     - it does not have primary or secondary instances
3537
     - it's not the master
3538

3539
    Any errors are signaled by raising errors.OpPrereqError.
3540

3541
    """
3542
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3543
    node = self.cfg.GetNodeInfo(self.op.node_name)
3544
    assert node is not None
3545

    
3546
    instance_list = self.cfg.GetInstanceList()
3547

    
3548
    masternode = self.cfg.GetMasterNode()
3549
    if node.name == masternode:
3550
      raise errors.OpPrereqError("Node is the master node,"
3551
                                 " you need to failover first.",
3552
                                 errors.ECODE_INVAL)
3553

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

    
3563
  def Exec(self, feedback_fn):
3564
    """Removes the node from the cluster.
3565

3566
    """
3567
    node = self.node
3568
    logging.info("Stopping the node daemon and removing configs from node %s",
3569
                 node.name)
3570

    
3571
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3572

    
3573
    # Promote nodes to master candidate as needed
3574
    _AdjustCandidatePool(self, exceptions=[node.name])
3575
    self.context.RemoveNode(node.name)
3576

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

    
3585
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3586
    msg = result.fail_msg
3587
    if msg:
3588
      self.LogWarning("Errors encountered on the remote node while leaving"
3589
                      " the cluster: %s", msg)
3590

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

    
3600

    
3601
class _NodeQuery(_QueryBase):
3602
  FIELDS = query.NODE_FIELDS
3603

    
3604
  def ExpandNames(self, lu):
3605
    lu.needed_locks = {}
3606
    lu.share_locks[locking.LEVEL_NODE] = 1
3607

    
3608
    if self.names:
3609
      self.wanted = _GetWantedNodes(lu, self.names)
3610
    else:
3611
      self.wanted = locking.ALL_SET
3612

    
3613
    self.do_locking = (self.use_locking and
3614
                       query.NQ_LIVE in self.requested_data)
3615

    
3616
    if self.do_locking:
3617
      # if we don't request only static fields, we need to lock the nodes
3618
      lu.needed_locks[locking.LEVEL_NODE] = self.wanted
3619

    
3620
  def DeclareLocks(self, lu, level):
3621
    pass
3622

    
3623
  def _GetQueryData(self, lu):
3624
    """Computes the list of nodes and their attributes.
3625

3626
    """
3627
    all_info = lu.cfg.GetAllNodesInfo()
3628

    
3629
    nodenames = self._GetNames(lu, all_info.keys(), locking.LEVEL_NODE)
3630

    
3631
    # Gather data as requested
3632
    if query.NQ_LIVE in self.requested_data:
3633
      # filter out non-vm_capable nodes
3634
      toquery_nodes = [name for name in nodenames if all_info[name].vm_capable]
3635

    
3636
      node_data = lu.rpc.call_node_info(toquery_nodes, lu.cfg.GetVGName(),
3637
                                        lu.cfg.GetHypervisorType())
3638
      live_data = dict((name, nresult.payload)
3639
                       for (name, nresult) in node_data.items()
3640
                       if not nresult.fail_msg and nresult.payload)
3641
    else:
3642
      live_data = None
3643

    
3644
    if query.NQ_INST in self.requested_data:
3645
      node_to_primary = dict([(name, set()) for name in nodenames])
3646
      node_to_secondary = dict([(name, set()) for name in nodenames])
3647

    
3648
      inst_data = lu.cfg.GetAllInstancesInfo()
3649

    
3650
      for inst in inst_data.values():
3651
        if inst.primary_node in node_to_primary:
3652
          node_to_primary[inst.primary_node].add(inst.name)
3653
        for secnode in inst.secondary_nodes:
3654
          if secnode in node_to_secondary:
3655
            node_to_secondary[secnode].add(inst.name)
3656
    else:
3657
      node_to_primary = None
3658
      node_to_secondary = None
3659

    
3660
    if query.NQ_OOB in self.requested_data:
3661
      oob_support = dict((name, bool(_SupportsOob(lu.cfg, node)))
3662
                         for name, node in all_info.iteritems())
3663
    else:
3664
      oob_support = None
3665

    
3666
    if query.NQ_GROUP in self.requested_data:
3667
      groups = lu.cfg.GetAllNodeGroupsInfo()
3668
    else:
3669
      groups = {}
3670

    
3671
    return query.NodeQueryData([all_info[name] for name in nodenames],
3672
                               live_data, lu.cfg.GetMasterNode(),
3673
                               node_to_primary, node_to_secondary, groups,
3674
                               oob_support, lu.cfg.GetClusterInfo())
3675

    
3676

    
3677
class LUNodeQuery(NoHooksLU):
3678
  """Logical unit for querying nodes.
3679

3680
  """
3681
  # pylint: disable-msg=W0142
3682
  REQ_BGL = False
3683

    
3684
  def CheckArguments(self):
3685
    self.nq = _NodeQuery(self.op.names, self.op.output_fields,
3686
                         self.op.use_locking)
3687

    
3688
  def ExpandNames(self):
3689
    self.nq.ExpandNames(self)
3690

    
3691
  def Exec(self, feedback_fn):
3692
    return self.nq.OldStyleQuery(self)
3693

    
3694

    
3695
class LUNodeQueryvols(NoHooksLU):
3696
  """Logical unit for getting volumes on node(s).
3697

3698
  """
3699
  REQ_BGL = False
3700
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3701
  _FIELDS_STATIC = utils.FieldSet("node")
3702

    
3703
  def CheckArguments(self):
3704
    _CheckOutputFields(static=self._FIELDS_STATIC,
3705
                       dynamic=self._FIELDS_DYNAMIC,
3706
                       selected=self.op.output_fields)
3707

    
3708
  def ExpandNames(self):
3709
    self.needed_locks = {}
3710
    self.share_locks[locking.LEVEL_NODE] = 1
3711
    if not self.op.nodes:
3712
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3713
    else:
3714
      self.needed_locks[locking.LEVEL_NODE] = \
3715
        _GetWantedNodes(self, self.op.nodes)
3716

    
3717
  def Exec(self, feedback_fn):
3718
    """Computes the list of nodes and their attributes.
3719

3720
    """
3721
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3722
    volumes = self.rpc.call_node_volumes(nodenames)
3723

    
3724
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3725
             in self.cfg.GetInstanceList()]
3726

    
3727
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3728

    
3729
    output = []
3730
    for node in nodenames:
3731
      nresult = volumes[node]
3732
      if nresult.offline:
3733
        continue
3734
      msg = nresult.fail_msg
3735
      if msg:
3736
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3737
        continue
3738

    
3739
      node_vols = nresult.payload[:]
3740
      node_vols.sort(key=lambda vol: vol['dev'])
3741

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

    
3768
        output.append(node_output)
3769

    
3770
    return output
3771

    
3772

    
3773
class LUNodeQueryStorage(NoHooksLU):
3774
  """Logical unit for getting information on storage units on node(s).
3775

3776
  """
3777
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3778
  REQ_BGL = False
3779

    
3780
  def CheckArguments(self):
3781
    _CheckOutputFields(static=self._FIELDS_STATIC,
3782
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3783
                       selected=self.op.output_fields)
3784

    
3785
  def ExpandNames(self):
3786
    self.needed_locks = {}
3787
    self.share_locks[locking.LEVEL_NODE] = 1
3788

    
3789
    if self.op.nodes:
3790
      self.needed_locks[locking.LEVEL_NODE] = \
3791
        _GetWantedNodes(self, self.op.nodes)
3792
    else:
3793
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3794

    
3795
  def Exec(self, feedback_fn):
3796
    """Computes the list of nodes and their attributes.
3797

3798
    """
3799
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3800

    
3801
    # Always get name to sort by
3802
    if constants.SF_NAME in self.op.output_fields:
3803
      fields = self.op.output_fields[:]
3804
    else:
3805
      fields = [constants.SF_NAME] + self.op.output_fields
3806

    
3807
    # Never ask for node or type as it's only known to the LU
3808
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3809
      while extra in fields:
3810
        fields.remove(extra)
3811

    
3812
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3813
    name_idx = field_idx[constants.SF_NAME]
3814

    
3815
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3816
    data = self.rpc.call_storage_list(self.nodes,
3817
                                      self.op.storage_type, st_args,
3818
                                      self.op.name, fields)
3819

    
3820
    result = []
3821

    
3822
    for node in utils.NiceSort(self.nodes):
3823
      nresult = data[node]
3824
      if nresult.offline:
3825
        continue
3826

    
3827
      msg = nresult.fail_msg
3828
      if msg:
3829
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3830
        continue
3831

    
3832
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3833

    
3834
      for name in utils.NiceSort(rows.keys()):
3835
        row = rows[name]
3836

    
3837
        out = []
3838

    
3839
        for field in self.op.output_fields:
3840
          if field == constants.SF_NODE:
3841
            val = node
3842
          elif field == constants.SF_TYPE:
3843
            val = self.op.storage_type
3844
          elif field in field_idx:
3845
            val = row[field_idx[field]]
3846
          else:
3847
            raise errors.ParameterError(field)
3848

    
3849
          out.append(val)
3850

    
3851
        result.append(out)
3852

    
3853
    return result
3854

    
3855

    
3856
class _InstanceQuery(_QueryBase):
3857
  FIELDS = query.INSTANCE_FIELDS
3858

    
3859
  def ExpandNames(self, lu):
3860
    lu.needed_locks = {}
3861
    lu.share_locks[locking.LEVEL_INSTANCE] = 1
3862
    lu.share_locks[locking.LEVEL_NODE] = 1
3863

    
3864
    if self.names:
3865
      self.wanted = _GetWantedInstances(lu, self.names)
3866
    else:
3867
      self.wanted = locking.ALL_SET
3868

    
3869
    self.do_locking = (self.use_locking and
3870
                       query.IQ_LIVE in self.requested_data)
3871
    if self.do_locking:
3872
      lu.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
3873
      lu.needed_locks[locking.LEVEL_NODE] = []
3874
      lu.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3875

    
3876
  def DeclareLocks(self, lu, level):
3877
    if level == locking.LEVEL_NODE and self.do_locking:
3878
      lu._LockInstancesNodes() # pylint: disable-msg=W0212
3879

    
3880
  def _GetQueryData(self, lu):
3881
    """Computes the list of instances and their attributes.
3882

3883
    """
3884
    cluster = lu.cfg.GetClusterInfo()
3885
    all_info = lu.cfg.GetAllInstancesInfo()
3886

    
3887
    instance_names = self._GetNames(lu, all_info.keys(), locking.LEVEL_INSTANCE)
3888

    
3889
    instance_list = [all_info[name] for name in instance_names]
3890
    nodes = frozenset(itertools.chain(*(inst.all_nodes
3891
                                        for inst in instance_list)))
3892
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
3893
    bad_nodes = []
3894
    offline_nodes = []
3895
    wrongnode_inst = set()
3896

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

    
3919
    if query.IQ_DISKUSAGE in self.requested_data:
3920
      disk_usage = dict((inst.name,
3921
                         _ComputeDiskSize(inst.disk_template,
3922
                                          [{"size": disk.size}
3923
                                           for disk in inst.disks]))
3924
                        for inst in instance_list)
3925
    else:
3926
      disk_usage = None
3927

    
3928
    if query.IQ_CONSOLE in self.requested_data:
3929
      consinfo = {}
3930
      for inst in instance_list:
3931
        if inst.name in live_data:
3932
          # Instance is running
3933
          consinfo[inst.name] = _GetInstanceConsole(cluster, inst)
3934
        else:
3935
          consinfo[inst.name] = None
3936
      assert set(consinfo.keys()) == set(instance_names)
3937
    else:
3938
      consinfo = None
3939

    
3940
    return query.InstanceQueryData(instance_list, lu.cfg.GetClusterInfo(),
3941
                                   disk_usage, offline_nodes, bad_nodes,
3942
                                   live_data, wrongnode_inst, consinfo)
3943

    
3944

    
3945
class LUQuery(NoHooksLU):
3946
  """Query for resources/items of a certain kind.
3947

3948
  """
3949
  # pylint: disable-msg=W0142
3950
  REQ_BGL = False
3951

    
3952
  def CheckArguments(self):
3953
    qcls = _GetQueryImplementation(self.op.what)
3954
    names = qlang.ReadSimpleFilter("name", self.op.filter)
3955

    
3956
    self.impl = qcls(names, self.op.fields, False)
3957

    
3958
  def ExpandNames(self):
3959
    self.impl.ExpandNames(self)
3960

    
3961
  def DeclareLocks(self, level):
3962
    self.impl.DeclareLocks(self, level)
3963

    
3964
  def Exec(self, feedback_fn):
3965
    return self.impl.NewStyleQuery(self)
3966

    
3967

    
3968
class LUQueryFields(NoHooksLU):
3969
  """Query for resources/items of a certain kind.
3970

3971
  """
3972
  # pylint: disable-msg=W0142
3973
  REQ_BGL = False
3974

    
3975
  def CheckArguments(self):
3976
    self.qcls = _GetQueryImplementation(self.op.what)
3977

    
3978
  def ExpandNames(self):
3979
    self.needed_locks = {}
3980

    
3981
  def Exec(self, feedback_fn):
3982
    return self.qcls.FieldsQuery(self.op.fields)
3983

    
3984

    
3985
class LUNodeModifyStorage(NoHooksLU):
3986
  """Logical unit for modifying a storage volume on a node.
3987

3988
  """
3989
  REQ_BGL = False
3990

    
3991
  def CheckArguments(self):
3992
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3993

    
3994
    storage_type = self.op.storage_type
3995

    
3996
    try:
3997
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3998
    except KeyError:
3999
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
4000
                                 " modified" % storage_type,
4001
                                 errors.ECODE_INVAL)
4002

    
4003
    diff = set(self.op.changes.keys()) - modifiable
4004
    if diff:
4005
      raise errors.OpPrereqError("The following fields can not be modified for"
4006
                                 " storage units of type '%s': %r" %
4007
                                 (storage_type, list(diff)),
4008
                                 errors.ECODE_INVAL)
4009

    
4010
  def ExpandNames(self):
4011
    self.needed_locks = {
4012
      locking.LEVEL_NODE: self.op.node_name,
4013
      }
4014

    
4015
  def Exec(self, feedback_fn):
4016
    """Computes the list of nodes and their attributes.
4017

4018
    """
4019
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4020
    result = self.rpc.call_storage_modify(self.op.node_name,
4021
                                          self.op.storage_type, st_args,
4022
                                          self.op.name, self.op.changes)
4023
    result.Raise("Failed to modify storage unit '%s' on %s" %
4024
                 (self.op.name, self.op.node_name))
4025

    
4026

    
4027
class LUNodeAdd(LogicalUnit):
4028
  """Logical unit for adding node to the cluster.
4029

4030
  """
4031
  HPATH = "node-add"
4032
  HTYPE = constants.HTYPE_NODE
4033
  _NFLAGS = ["master_capable", "vm_capable"]
4034

    
4035
  def CheckArguments(self):
4036
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
4037
    # validate/normalize the node name
4038
    self.hostname = netutils.GetHostname(name=self.op.node_name,
4039
                                         family=self.primary_ip_family)
4040
    self.op.node_name = self.hostname.name
4041
    if self.op.readd and self.op.group:
4042
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
4043
                                 " being readded", errors.ECODE_INVAL)
4044

    
4045
  def BuildHooksEnv(self):
4046
    """Build hooks env.
4047

4048
    This will run on all nodes before, and on all nodes + the new node after.
4049

4050
    """
4051
    env = {
4052
      "OP_TARGET": self.op.node_name,
4053
      "NODE_NAME": self.op.node_name,
4054
      "NODE_PIP": self.op.primary_ip,
4055
      "NODE_SIP": self.op.secondary_ip,
4056
      "MASTER_CAPABLE": str(self.op.master_capable),
4057
      "VM_CAPABLE": str(self.op.vm_capable),
4058
      }
4059
    nodes_0 = self.cfg.GetNodeList()
4060
    nodes_1 = nodes_0 + [self.op.node_name, ]
4061
    return env, nodes_0, nodes_1
4062

    
4063
  def CheckPrereq(self):
4064
    """Check prerequisites.
4065

4066
    This checks:
4067
     - the new node is not already in the config
4068
     - it is resolvable
4069
     - its parameters (single/dual homed) matches the cluster
4070

4071
    Any errors are signaled by raising errors.OpPrereqError.
4072

4073
    """
4074
    cfg = self.cfg
4075
    hostname = self.hostname
4076
    node = hostname.name
4077
    primary_ip = self.op.primary_ip = hostname.ip
4078
    if self.op.secondary_ip is None:
4079
      if self.primary_ip_family == netutils.IP6Address.family:
4080
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
4081
                                   " IPv4 address must be given as secondary",
4082
                                   errors.ECODE_INVAL)
4083
      self.op.secondary_ip = primary_ip
4084

    
4085
    secondary_ip = self.op.secondary_ip
4086
    if not netutils.IP4Address.IsValid(secondary_ip):
4087
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4088
                                 " address" % secondary_ip, errors.ECODE_INVAL)
4089

    
4090
    node_list = cfg.GetNodeList()
4091
    if not self.op.readd and node in node_list:
4092
      raise errors.OpPrereqError("Node %s is already in the configuration" %
4093
                                 node, errors.ECODE_EXISTS)
4094
    elif self.op.readd and node not in node_list:
4095
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
4096
                                 errors.ECODE_NOENT)
4097

    
4098
    self.changed_primary_ip = False
4099

    
4100
    for existing_node_name in node_list:
4101
      existing_node = cfg.GetNodeInfo(existing_node_name)
4102

    
4103
      if self.op.readd and node == existing_node_name:
4104
        if existing_node.secondary_ip != secondary_ip:
4105
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
4106
                                     " address configuration as before",
4107
                                     errors.ECODE_INVAL)
4108
        if existing_node.primary_ip != primary_ip:
4109
          self.changed_primary_ip = True
4110

    
4111
        continue
4112

    
4113
      if (existing_node.primary_ip == primary_ip or
4114
          existing_node.secondary_ip == primary_ip or
4115
          existing_node.primary_ip == secondary_ip or
4116
          existing_node.secondary_ip == secondary_ip):
4117
        raise errors.OpPrereqError("New node ip address(es) conflict with"
4118
                                   " existing node %s" % existing_node.name,
4119
                                   errors.ECODE_NOTUNIQUE)
4120

    
4121
    # After this 'if' block, None is no longer a valid value for the
4122
    # _capable op attributes
4123
    if self.op.readd:
4124
      old_node = self.cfg.GetNodeInfo(node)
4125
      assert old_node is not None, "Can't retrieve locked node %s" % node
4126
      for attr in self._NFLAGS:
4127
        if getattr(self.op, attr) is None:
4128
          setattr(self.op, attr, getattr(old_node, attr))
4129
    else:
4130
      for attr in self._NFLAGS:
4131
        if getattr(self.op, attr) is None:
4132
          setattr(self.op, attr, True)
4133

    
4134
    if self.op.readd and not self.op.vm_capable:
4135
      pri, sec = cfg.GetNodeInstances(node)
4136
      if pri or sec:
4137
        raise errors.OpPrereqError("Node %s being re-added with vm_capable"
4138
                                   " flag set to false, but it already holds"
4139
                                   " instances" % node,
4140
                                   errors.ECODE_STATE)
4141

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

    
4157
    # checks reachability
4158
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
4159
      raise errors.OpPrereqError("Node not reachable by ping",
4160
                                 errors.ECODE_ENVIRON)
4161

    
4162
    if not newbie_singlehomed:
4163
      # check reachability from my secondary ip to newbie's secondary ip
4164
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
4165
                           source=myself.secondary_ip):
4166
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4167
                                   " based ping to node daemon port",
4168
                                   errors.ECODE_ENVIRON)
4169

    
4170
    if self.op.readd:
4171
      exceptions = [node]
4172
    else:
4173
      exceptions = []
4174

    
4175
    if self.op.master_capable:
4176
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
4177
    else:
4178
      self.master_candidate = False
4179

    
4180
    if self.op.readd:
4181
      self.new_node = old_node
4182
    else:
4183
      node_group = cfg.LookupNodeGroup(self.op.group)
4184
      self.new_node = objects.Node(name=node,
4185
                                   primary_ip=primary_ip,
4186
                                   secondary_ip=secondary_ip,
4187
                                   master_candidate=self.master_candidate,
4188
                                   offline=False, drained=False,
4189
                                   group=node_group)
4190

    
4191
    if self.op.ndparams:
4192
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
4193

    
4194
  def Exec(self, feedback_fn):
4195
    """Adds the new node to the cluster.
4196

4197
    """
4198
    new_node = self.new_node
4199
    node = new_node.name
4200

    
4201
    # We adding a new node so we assume it's powered
4202
    new_node.powered = True
4203

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

    
4216
    # copy the master/vm_capable flags
4217
    for attr in self._NFLAGS:
4218
      setattr(new_node, attr, getattr(self.op, attr))
4219

    
4220
    # notify the user about any possible mc promotion
4221
    if new_node.master_candidate:
4222
      self.LogInfo("Node will be a master candidate")
4223

    
4224
    if self.op.ndparams:
4225
      new_node.ndparams = self.op.ndparams
4226
    else:
4227
      new_node.ndparams = {}
4228

    
4229
    # check connectivity
4230
    result = self.rpc.call_version([node])[node]
4231
    result.Raise("Can't get version information from node %s" % node)
4232
    if constants.PROTOCOL_VERSION == result.payload:
4233
      logging.info("Communication to node %s fine, sw version %s match",
4234
                   node, result.payload)
4235
    else:
4236
      raise errors.OpExecError("Version mismatch master version %s,"
4237
                               " node version %s" %
4238
                               (constants.PROTOCOL_VERSION, result.payload))
4239

    
4240
    # Add node to our /etc/hosts, and add key to known_hosts
4241
    if self.cfg.GetClusterInfo().modify_etc_hosts:
4242
      master_node = self.cfg.GetMasterNode()
4243
      result = self.rpc.call_etc_hosts_modify(master_node,
4244
                                              constants.ETC_HOSTS_ADD,
4245
                                              self.hostname.name,
4246
                                              self.hostname.ip)
4247
      result.Raise("Can't update hosts file with new host data")
4248

    
4249
    if new_node.secondary_ip != new_node.primary_ip:
4250
      _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
4251
                               False)
4252

    
4253
    node_verify_list = [self.cfg.GetMasterNode()]
4254
    node_verify_param = {
4255
      constants.NV_NODELIST: [node],
4256
      # TODO: do a node-net-test as well?
4257
    }
4258

    
4259
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
4260
                                       self.cfg.GetClusterName())
4261
    for verifier in node_verify_list:
4262
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
4263
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
4264
      if nl_payload:
4265
        for failed in nl_payload:
4266
          feedback_fn("ssh/hostname verification failed"
4267
                      " (checking from %s): %s" %
4268
                      (verifier, nl_payload[failed]))
4269
        raise errors.OpExecError("ssh/hostname verification failed.")
4270

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

    
4288

    
4289
class LUNodeSetParams(LogicalUnit):
4290
  """Modifies the parameters of a node.
4291

4292
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
4293
      to the node role (as _ROLE_*)
4294
  @cvar _R2F: a dictionary from node role to tuples of flags
4295
  @cvar _FLAGS: a list of attribute names corresponding to the flags
4296

4297
  """
4298
  HPATH = "node-modify"
4299
  HTYPE = constants.HTYPE_NODE
4300
  REQ_BGL = False
4301
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
4302
  _F2R = {
4303
    (True, False, False): _ROLE_CANDIDATE,
4304
    (False, True, False): _ROLE_DRAINED,
4305
    (False, False, True): _ROLE_OFFLINE,
4306
    (False, False, False): _ROLE_REGULAR,
4307
    }
4308
  _R2F = dict((v, k) for k, v in _F2R.items())
4309
  _FLAGS = ["master_candidate", "drained", "offline"]
4310

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

    
4324
    # Boolean value that tells us whether we might be demoting from MC
4325
    self.might_demote = (self.op.master_candidate == False or
4326
                         self.op.offline == True or
4327
                         self.op.drained == True or
4328
                         self.op.master_capable == False)
4329

    
4330
    if self.op.secondary_ip:
4331
      if not netutils.IP4Address.IsValid(self.op.secondary_ip):
4332
        raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4333
                                   " address" % self.op.secondary_ip,
4334
                                   errors.ECODE_INVAL)
4335

    
4336
    self.lock_all = self.op.auto_promote and self.might_demote
4337
    self.lock_instances = self.op.secondary_ip is not None
4338

    
4339
  def ExpandNames(self):
4340
    if self.lock_all:
4341
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
4342
    else:
4343
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
4344

    
4345
    if self.lock_instances:
4346
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4347

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

    
4368
  def BuildHooksEnv(self):
4369
    """Build hooks env.
4370

4371
    This runs on the master node.
4372

4373
    """
4374
    env = {
4375
      "OP_TARGET": self.op.node_name,
4376
      "MASTER_CANDIDATE": str(self.op.master_candidate),
4377
      "OFFLINE": str(self.op.offline),
4378
      "DRAINED": str(self.op.drained),
4379
      "MASTER_CAPABLE": str(self.op.master_capable),
4380
      "VM_CAPABLE": str(self.op.vm_capable),
4381
      }
4382
    nl = [self.cfg.GetMasterNode(),
4383
          self.op.node_name]
4384
    return env, nl, nl
4385

    
4386
  def CheckPrereq(self):
4387
    """Check prerequisites.
4388

4389
    This only checks the instance list against the existing names.
4390

4391
    """
4392
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
4393

    
4394
    if (self.op.master_candidate is not None or
4395
        self.op.drained is not None or
4396
        self.op.offline is not None):
4397
      # we can't change the master's node flags
4398
      if self.op.node_name == self.cfg.GetMasterNode():
4399
        raise errors.OpPrereqError("The master role can be changed"
4400
                                   " only via master-failover",
4401
                                   errors.ECODE_INVAL)
4402

    
4403
    if self.op.master_candidate and not node.master_capable:
4404
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4405
                                 " it a master candidate" % node.name,
4406
                                 errors.ECODE_STATE)
4407

    
4408
    if self.op.vm_capable == False:
4409
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
4410
      if ipri or isec:
4411
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
4412
                                   " the vm_capable flag" % node.name,
4413
                                   errors.ECODE_STATE)
4414

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

    
4426
    self.old_flags = old_flags = (node.master_candidate,
4427
                                  node.drained, node.offline)
4428
    assert old_flags in self._F2R, "Un-handled old flags  %s" % str(old_flags)
4429
    self.old_role = old_role = self._F2R[old_flags]
4430

    
4431
    # Check for ineffective changes
4432
    for attr in self._FLAGS:
4433
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
4434
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
4435
        setattr(self.op, attr, None)
4436

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

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

    
4452
    # If we're being deofflined/drained, we'll MC ourself if needed
4453
    if (self.op.drained == False or self.op.offline == False or
4454
        (self.op.master_capable and not node.master_capable)):
4455
      if _DecideSelfPromotion(self):
4456
        self.op.master_candidate = True
4457
        self.LogInfo("Auto-promoting node to master candidate")
4458

    
4459
    # If we're no longer master capable, we'll demote ourselves from MC
4460
    if self.op.master_capable == False and node.master_candidate:
4461
      self.LogInfo("Demoting from master candidate")
4462
      self.op.master_candidate = False
4463

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

    
4479
    self.new_role = new_role
4480

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

    
4494
    if self.op.secondary_ip:
4495
      # Ok even without locking, because this can't be changed by any LU
4496
      master = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
4497
      master_singlehomed = master.secondary_ip == master.primary_ip
4498
      if master_singlehomed and self.op.secondary_ip:
4499
        raise errors.OpPrereqError("Cannot change the secondary ip on a single"
4500
                                   " homed cluster", errors.ECODE_INVAL)
4501

    
4502
      if node.offline:
4503
        if self.affected_instances:
4504
          raise errors.OpPrereqError("Cannot change secondary ip: offline"
4505
                                     " node has instances (%s) configured"
4506
                                     " to use it" % self.affected_instances)
4507
      else:
4508
        # On online nodes, check that no instances are running, and that
4509
        # the node has the new ip and we can reach it.
4510
        for instance in self.affected_instances:
4511
          _CheckInstanceDown(self, instance, "cannot change secondary ip")
4512

    
4513
        _CheckNodeHasSecondaryIP(self, node.name, self.op.secondary_ip, True)
4514
        if master.name != node.name:
4515
          # check reachability from master secondary ip to new secondary ip
4516
          if not netutils.TcpPing(self.op.secondary_ip,
4517
                                  constants.DEFAULT_NODED_PORT,
4518
                                  source=master.secondary_ip):
4519
            raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4520
                                       " based ping to node daemon port",
4521
                                       errors.ECODE_ENVIRON)
4522

    
4523
    if self.op.ndparams:
4524
      new_ndparams = _GetUpdatedParams(self.node.ndparams, self.op.ndparams)
4525
      utils.ForceDictType(new_ndparams, constants.NDS_PARAMETER_TYPES)
4526
      self.new_ndparams = new_ndparams
4527

    
4528
  def Exec(self, feedback_fn):
4529
    """Modifies a node.
4530

4531
    """
4532
    node = self.node
4533
    old_role = self.old_role
4534
    new_role = self.new_role
4535

    
4536
    result = []
4537

    
4538
    if self.op.ndparams:
4539
      node.ndparams = self.new_ndparams
4540

    
4541
    if self.op.powered is not None:
4542
      node.powered = self.op.powered
4543

    
4544
    for attr in ["master_capable", "vm_capable"]:
4545
      val = getattr(self.op, attr)
4546
      if val is not None:
4547
        setattr(node, attr, val)
4548
        result.append((attr, str(val)))
4549

    
4550
    if new_role != old_role:
4551
      # Tell the node to demote itself, if no longer MC and not offline
4552
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
4553
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
4554
        if msg:
4555
          self.LogWarning("Node failed to demote itself: %s", msg)
4556

    
4557
      new_flags = self._R2F[new_role]
4558
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
4559
        if of != nf:
4560
          result.append((desc, str(nf)))
4561
      (node.master_candidate, node.drained, node.offline) = new_flags
4562

    
4563
      # we locked all nodes, we adjust the CP before updating this node
4564
      if self.lock_all:
4565
        _AdjustCandidatePool(self, [node.name])
4566

    
4567
    if self.op.secondary_ip:
4568
      node.secondary_ip = self.op.secondary_ip
4569
      result.append(("secondary_ip", self.op.secondary_ip))
4570

    
4571
    # this will trigger configuration file update, if needed
4572
    self.cfg.Update(node, feedback_fn)
4573

    
4574
    # this will trigger job queue propagation or cleanup if the mc
4575
    # flag changed
4576
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
4577
      self.context.ReaddNode(node)
4578

    
4579
    return result
4580

    
4581

    
4582
class LUNodePowercycle(NoHooksLU):
4583
  """Powercycles a node.
4584

4585
  """
4586
  REQ_BGL = False
4587

    
4588
  def CheckArguments(self):
4589
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4590
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4591
      raise errors.OpPrereqError("The node is the master and the force"
4592
                                 " parameter was not set",
4593
                                 errors.ECODE_INVAL)
4594

    
4595
  def ExpandNames(self):
4596
    """Locking for PowercycleNode.
4597

4598
    This is a last-resort option and shouldn't block on other
4599
    jobs. Therefore, we grab no locks.
4600

4601
    """
4602
    self.needed_locks = {}
4603

    
4604
  def Exec(self, feedback_fn):
4605
    """Reboots a node.
4606

4607
    """
4608
    result = self.rpc.call_node_powercycle(self.op.node_name,
4609
                                           self.cfg.GetHypervisorType())
4610
    result.Raise("Failed to schedule the reboot")
4611
    return result.payload
4612

    
4613

    
4614
class LUClusterQuery(NoHooksLU):
4615
  """Query cluster configuration.
4616

4617
  """
4618
  REQ_BGL = False
4619

    
4620
  def ExpandNames(self):
4621
    self.needed_locks = {}
4622

    
4623
  def Exec(self, feedback_fn):
4624
    """Return cluster config.
4625

4626
    """
4627
    cluster = self.cfg.GetClusterInfo()
4628
    os_hvp = {}
4629

    
4630
    # Filter just for enabled hypervisors
4631
    for os_name, hv_dict in cluster.os_hvp.items():
4632
      os_hvp[os_name] = {}
4633
      for hv_name, hv_params in hv_dict.items():
4634
        if hv_name in cluster.enabled_hypervisors:
4635
          os_hvp[os_name][hv_name] = hv_params
4636

    
4637
    # Convert ip_family to ip_version
4638
    primary_ip_version = constants.IP4_VERSION
4639
    if cluster.primary_ip_family == netutils.IP6Address.family:
4640
      primary_ip_version = constants.IP6_VERSION
4641

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

    
4679
    return result
4680

    
4681

    
4682
class LUClusterConfigQuery(NoHooksLU):
4683
  """Return configuration values.
4684

4685
  """
4686
  REQ_BGL = False
4687
  _FIELDS_DYNAMIC = utils.FieldSet()
4688
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4689
                                  "watcher_pause", "volume_group_name")
4690

    
4691
  def CheckArguments(self):
4692
    _CheckOutputFields(static=self._FIELDS_STATIC,
4693
                       dynamic=self._FIELDS_DYNAMIC,
4694
                       selected=self.op.output_fields)
4695

    
4696
  def ExpandNames(self):
4697
    self.needed_locks = {}
4698

    
4699
  def Exec(self, feedback_fn):
4700
    """Dump a representation of the cluster config to the standard output.
4701

4702
    """
4703
    values = []
4704
    for field in self.op.output_fields:
4705
      if field == "cluster_name":
4706
        entry = self.cfg.GetClusterName()
4707
      elif field == "master_node":
4708
        entry = self.cfg.GetMasterNode()
4709
      elif field == "drain_flag":
4710
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4711
      elif field == "watcher_pause":
4712
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4713
      elif field == "volume_group_name":
4714
        entry = self.cfg.GetVGName()
4715
      else:
4716
        raise errors.ParameterError(field)
4717
      values.append(entry)
4718
    return values
4719

    
4720

    
4721
class LUInstanceActivateDisks(NoHooksLU):
4722
  """Bring up an instance's disks.
4723

4724
  """
4725
  REQ_BGL = False
4726

    
4727
  def ExpandNames(self):
4728
    self._ExpandAndLockInstance()
4729
    self.needed_locks[locking.LEVEL_NODE] = []
4730
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4731

    
4732
  def DeclareLocks(self, level):
4733
    if level == locking.LEVEL_NODE:
4734
      self._LockInstancesNodes()
4735

    
4736
  def CheckPrereq(self):
4737
    """Check prerequisites.
4738

4739
    This checks that the instance is in the cluster.
4740

4741
    """
4742
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4743
    assert self.instance is not None, \
4744
      "Cannot retrieve locked instance %s" % self.op.instance_name
4745
    _CheckNodeOnline(self, self.instance.primary_node)
4746

    
4747
  def Exec(self, feedback_fn):
4748
    """Activate the disks.
4749

4750
    """
4751
    disks_ok, disks_info = \
4752
              _AssembleInstanceDisks(self, self.instance,
4753
                                     ignore_size=self.op.ignore_size)
4754
    if not disks_ok:
4755
      raise errors.OpExecError("Cannot activate block devices")
4756

    
4757
    return disks_info
4758

    
4759

    
4760
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4761
                           ignore_size=False):
4762
  """Prepare the block devices for an instance.
4763

4764
  This sets up the block devices on all nodes.
4765

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

4783
  """
4784
  device_info = []
4785
  disks_ok = True
4786
  iname = instance.name
4787
  disks = _ExpandCheckDisks(instance, disks)
4788

    
4789
  # With the two passes mechanism we try to reduce the window of
4790
  # opportunity for the race condition of switching DRBD to primary
4791
  # before handshaking occured, but we do not eliminate it
4792

    
4793
  # The proper fix would be to wait (with some limits) until the
4794
  # connection has been made and drbd transitions from WFConnection
4795
  # into any other network-connected state (Connected, SyncTarget,
4796
  # SyncSource, etc.)
4797

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

    
4814
  # FIXME: race condition on drbd migration to primary
4815

    
4816
  # 2nd pass, do only the primary node
4817
  for idx, inst_disk in enumerate(disks):
4818
    dev_path = None
4819

    
4820
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4821
      if node != instance.primary_node:
4822
        continue
4823
      if ignore_size:
4824
        node_disk = node_disk.Copy()
4825
        node_disk.UnsetSize()
4826
      lu.cfg.SetDiskID(node_disk, node)
4827
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True, idx)
4828
      msg = result.fail_msg
4829
      if msg:
4830
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4831
                           " (is_primary=True, pass=2): %s",
4832
                           inst_disk.iv_name, node, msg)
4833
        disks_ok = False
4834
      else:
4835
        dev_path = result.payload
4836

    
4837
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4838

    
4839
  # leave the disks configured for the primary node
4840
  # this is a workaround that would be fixed better by
4841
  # improving the logical/physical id handling
4842
  for disk in disks:
4843
    lu.cfg.SetDiskID(disk, instance.primary_node)
4844

    
4845
  return disks_ok, device_info
4846

    
4847

    
4848
def _StartInstanceDisks(lu, instance, force):
4849
  """Start the disks of an instance.
4850

4851
  """
4852
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4853
                                           ignore_secondaries=force)
4854
  if not disks_ok:
4855
    _ShutdownInstanceDisks(lu, instance)
4856
    if force is not None and not force:
4857
      lu.proc.LogWarning("", hint="If the message above refers to a"
4858
                         " secondary node,"
4859
                         " you can retry the operation using '--force'.")
4860
    raise errors.OpExecError("Disk consistency error")
4861

    
4862

    
4863
class LUInstanceDeactivateDisks(NoHooksLU):
4864
  """Shutdown an instance's disks.
4865

4866
  """
4867
  REQ_BGL = False
4868

    
4869
  def ExpandNames(self):
4870
    self._ExpandAndLockInstance()
4871
    self.needed_locks[locking.LEVEL_NODE] = []
4872
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4873

    
4874
  def DeclareLocks(self, level):
4875
    if level == locking.LEVEL_NODE:
4876
      self._LockInstancesNodes()
4877

    
4878
  def CheckPrereq(self):
4879
    """Check prerequisites.
4880

4881
    This checks that the instance is in the cluster.
4882

4883
    """
4884
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4885
    assert self.instance is not None, \
4886
      "Cannot retrieve locked instance %s" % self.op.instance_name
4887

    
4888
  def Exec(self, feedback_fn):
4889
    """Deactivate the disks
4890

4891
    """
4892
    instance = self.instance
4893
    if self.op.force:
4894
      _ShutdownInstanceDisks(self, instance)
4895
    else:
4896
      _SafeShutdownInstanceDisks(self, instance)
4897

    
4898

    
4899
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4900
  """Shutdown block devices of an instance.
4901

4902
  This function checks if an instance is running, before calling
4903
  _ShutdownInstanceDisks.
4904

4905
  """
4906
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4907
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4908

    
4909

    
4910
def _ExpandCheckDisks(instance, disks):
4911
  """Return the instance disks selected by the disks list
4912

4913
  @type disks: list of L{objects.Disk} or None
4914
  @param disks: selected disks
4915
  @rtype: list of L{objects.Disk}
4916
  @return: selected instance disks to act on
4917

4918
  """
4919
  if disks is None:
4920
    return instance.disks
4921
  else:
4922
    if not set(disks).issubset(instance.disks):
4923
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4924
                                   " target instance")
4925
    return disks
4926

    
4927

    
4928
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4929
  """Shutdown block devices of an instance.
4930

4931
  This does the shutdown on all nodes of the instance.
4932

4933
  If the ignore_primary is false, errors on the primary node are
4934
  ignored.
4935

4936
  """
4937
  all_result = True
4938
  disks = _ExpandCheckDisks(instance, disks)
4939

    
4940
  for disk in disks:
4941
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4942
      lu.cfg.SetDiskID(top_disk, node)
4943
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4944
      msg = result.fail_msg
4945
      if msg:
4946
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4947
                      disk.iv_name, node, msg)
4948
        if ((node == instance.primary_node and not ignore_primary) or
4949
            (node != instance.primary_node and not result.offline)):
4950
          all_result = False
4951
  return all_result
4952

    
4953

    
4954
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4955
  """Checks if a node has enough free memory.
4956

4957
  This function check if a given node has the needed amount of free
4958
  memory. In case the node has less memory or we cannot get the
4959
  information from the node, this function raise an OpPrereqError
4960
  exception.
4961

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

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

    
4990

    
4991
def _CheckNodesFreeDiskPerVG(lu, nodenames, req_sizes):
4992
  """Checks if nodes have enough free disk space in the all VGs.
4993

4994
  This function check if all given nodes have the needed amount of
4995
  free disk. In case any node has less disk or we cannot get the
4996
  information from the node, this function raise an OpPrereqError
4997
  exception.
4998

4999
  @type lu: C{LogicalUnit}
5000
  @param lu: a logical unit from which we get configuration data
5001
  @type nodenames: C{list}
5002
  @param nodenames: the list of node names to check
5003
  @type req_sizes: C{dict}
5004
  @param req_sizes: the hash of vg and corresponding amount of disk in
5005
      MiB to check for
5006
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5007
      or we cannot check the node
5008

5009
  """
5010
  for vg, req_size in req_sizes.items():
5011
    _CheckNodesFreeDiskOnVG(lu, nodenames, vg, req_size)
5012

    
5013

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

5017
  This function check if all given nodes have the needed amount of
5018
  free disk. In case any node has less disk or we cannot get the
5019
  information from the node, this function raise an OpPrereqError
5020
  exception.
5021

5022
  @type lu: C{LogicalUnit}
5023
  @param lu: a logical unit from which we get configuration data
5024
  @type nodenames: C{list}
5025
  @param nodenames: the list of node names to check
5026
  @type vg: C{str}
5027
  @param vg: the volume group to check
5028
  @type requested: C{int}
5029
  @param requested: the amount of disk in MiB to check for
5030
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5031
      or we cannot check the node
5032

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

    
5050

    
5051
class LUInstanceStartup(LogicalUnit):
5052
  """Starts an instance.
5053

5054
  """
5055
  HPATH = "instance-start"
5056
  HTYPE = constants.HTYPE_INSTANCE
5057
  REQ_BGL = False
5058

    
5059
  def CheckArguments(self):
5060
    # extra beparams
5061
    if self.op.beparams:
5062
      # fill the beparams dict
5063
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5064

    
5065
  def ExpandNames(self):
5066
    self._ExpandAndLockInstance()
5067

    
5068
  def BuildHooksEnv(self):
5069
    """Build hooks env.
5070

5071
    This runs on master, primary and secondary nodes of the instance.
5072

5073
    """
5074
    env = {
5075
      "FORCE": self.op.force,
5076
      }
5077
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5078
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5079
    return env, nl, nl
5080

    
5081
  def CheckPrereq(self):
5082
    """Check prerequisites.
5083

5084
    This checks that the instance is in the cluster.
5085

5086
    """
5087
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5088
    assert self.instance is not None, \
5089
      "Cannot retrieve locked instance %s" % self.op.instance_name
5090

    
5091
    # extra hvparams
5092
    if self.op.hvparams:
5093
      # check hypervisor parameter syntax (locally)
5094
      cluster = self.cfg.GetClusterInfo()
5095
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5096
      filled_hvp = cluster.FillHV(instance)
5097
      filled_hvp.update(self.op.hvparams)
5098
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
5099
      hv_type.CheckParameterSyntax(filled_hvp)
5100
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
5101

    
5102
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
5103

    
5104
    if self.primary_offline and self.op.ignore_offline_nodes:
5105
      self.proc.LogWarning("Ignoring offline primary node")
5106

    
5107
      if self.op.hvparams or self.op.beparams:
5108
        self.proc.LogWarning("Overridden parameters are ignored")
5109
    else:
5110
      _CheckNodeOnline(self, instance.primary_node)
5111

    
5112
      bep = self.cfg.GetClusterInfo().FillBE(instance)
5113

    
5114
      # check bridges existence
5115
      _CheckInstanceBridgesExist(self, instance)
5116

    
5117
      remote_info = self.rpc.call_instance_info(instance.primary_node,
5118
                                                instance.name,
5119
                                                instance.hypervisor)
5120
      remote_info.Raise("Error checking node %s" % instance.primary_node,
5121
                        prereq=True, ecode=errors.ECODE_ENVIRON)
5122
      if not remote_info.payload: # not running already
5123
        _CheckNodeFreeMemory(self, instance.primary_node,
5124
                             "starting instance %s" % instance.name,
5125
                             bep[constants.BE_MEMORY], instance.hypervisor)
5126

    
5127
  def Exec(self, feedback_fn):
5128
    """Start the instance.
5129

5130
    """
5131
    instance = self.instance
5132
    force = self.op.force
5133

    
5134
    self.cfg.MarkInstanceUp(instance.name)
5135

    
5136
    if self.primary_offline:
5137
      assert self.op.ignore_offline_nodes
5138
      self.proc.LogInfo("Primary node offline, marked instance as started")
5139
    else:
5140
      node_current = instance.primary_node
5141

    
5142
      _StartInstanceDisks(self, instance, force)
5143

    
5144
      result = self.rpc.call_instance_start(node_current, instance,
5145
                                            self.op.hvparams, self.op.beparams)
5146
      msg = result.fail_msg
5147
      if msg:
5148
        _ShutdownInstanceDisks(self, instance)
5149
        raise errors.OpExecError("Could not start instance: %s" % msg)
5150

    
5151

    
5152
class LUInstanceReboot(LogicalUnit):
5153
  """Reboot an instance.
5154

5155
  """
5156
  HPATH = "instance-reboot"
5157
  HTYPE = constants.HTYPE_INSTANCE
5158
  REQ_BGL = False
5159

    
5160
  def ExpandNames(self):
5161
    self._ExpandAndLockInstance()
5162

    
5163
  def BuildHooksEnv(self):
5164
    """Build hooks env.
5165

5166
    This runs on master, primary and secondary nodes of the instance.
5167

5168
    """
5169
    env = {
5170
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
5171
      "REBOOT_TYPE": self.op.reboot_type,
5172
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5173
      }
5174
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5175
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5176
    return env, nl, nl
5177

    
5178
  def CheckPrereq(self):
5179
    """Check prerequisites.
5180

5181
    This checks that the instance is in the cluster.
5182

5183
    """
5184
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5185
    assert self.instance is not None, \
5186
      "Cannot retrieve locked instance %s" % self.op.instance_name
5187

    
5188
    _CheckNodeOnline(self, instance.primary_node)
5189

    
5190
    # check bridges existence
5191
    _CheckInstanceBridgesExist(self, instance)
5192

    
5193
  def Exec(self, feedback_fn):
5194
    """Reboot the instance.
5195

5196
    """
5197
    instance = self.instance
5198
    ignore_secondaries = self.op.ignore_secondaries
5199
    reboot_type = self.op.reboot_type
5200

    
5201
    node_current = instance.primary_node
5202

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

    
5224
    self.cfg.MarkInstanceUp(instance.name)
5225

    
5226

    
5227
class LUInstanceShutdown(LogicalUnit):
5228
  """Shutdown an instance.
5229

5230
  """
5231
  HPATH = "instance-stop"
5232
  HTYPE = constants.HTYPE_INSTANCE
5233
  REQ_BGL = False
5234

    
5235
  def ExpandNames(self):
5236
    self._ExpandAndLockInstance()
5237

    
5238
  def BuildHooksEnv(self):
5239
    """Build hooks env.
5240

5241
    This runs on master, primary and secondary nodes of the instance.
5242

5243
    """
5244
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5245
    env["TIMEOUT"] = self.op.timeout
5246
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5247
    return env, nl, nl
5248

    
5249
  def CheckPrereq(self):
5250
    """Check prerequisites.
5251

5252
    This checks that the instance is in the cluster.
5253

5254
    """
5255
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5256
    assert self.instance is not None, \
5257
      "Cannot retrieve locked instance %s" % self.op.instance_name
5258

    
5259
    self.primary_offline = \
5260
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
5261

    
5262
    if self.primary_offline and self.op.ignore_offline_nodes:
5263
      self.proc.LogWarning("Ignoring offline primary node")
5264
    else:
5265
      _CheckNodeOnline(self, self.instance.primary_node)
5266

    
5267
  def Exec(self, feedback_fn):
5268
    """Shutdown the instance.
5269

5270
    """
5271
    instance = self.instance
5272
    node_current = instance.primary_node
5273
    timeout = self.op.timeout
5274

    
5275
    self.cfg.MarkInstanceDown(instance.name)
5276

    
5277
    if self.primary_offline:
5278
      assert self.op.ignore_offline_nodes
5279
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
5280
    else:
5281
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
5282
      msg = result.fail_msg
5283
      if msg:
5284
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
5285

    
5286
      _ShutdownInstanceDisks(self, instance)
5287

    
5288

    
5289
class LUInstanceReinstall(LogicalUnit):
5290
  """Reinstall an instance.
5291

5292
  """
5293
  HPATH = "instance-reinstall"
5294
  HTYPE = constants.HTYPE_INSTANCE
5295
  REQ_BGL = False
5296

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

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

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

5305
    """
5306
    env = _BuildInstanceHookEnvByObject(self, self.instance)
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 and is not running.
5314

5315
    """
5316
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5317
    assert instance is not None, \
5318
      "Cannot retrieve locked instance %s" % self.op.instance_name
5319
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
5320
                     " offline, cannot reinstall")
5321
    for node in instance.secondary_nodes:
5322
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
5323
                       " cannot reinstall")
5324

    
5325
    if instance.disk_template == constants.DT_DISKLESS:
5326
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5327
                                 self.op.instance_name,
5328
                                 errors.ECODE_INVAL)
5329
    _CheckInstanceDown(self, instance, "cannot reinstall")
5330

    
5331
    if self.op.os_type is not None:
5332
      # OS verification
5333
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
5334
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
5335
      instance_os = self.op.os_type
5336
    else:
5337
      instance_os = instance.os
5338

    
5339
    nodelist = list(instance.all_nodes)
5340

    
5341
    if self.op.osparams:
5342
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
5343
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
5344
      self.os_inst = i_osdict # the new dict (without defaults)
5345
    else:
5346
      self.os_inst = None
5347

    
5348
    self.instance = instance
5349

    
5350
  def Exec(self, feedback_fn):
5351
    """Reinstall the instance.
5352

5353
    """
5354
    inst = self.instance
5355

    
5356
    if self.op.os_type is not None:
5357
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
5358
      inst.os = self.op.os_type
5359
      # Write to configuration
5360
      self.cfg.Update(inst, feedback_fn)
5361

    
5362
    _StartInstanceDisks(self, inst, None)
5363
    try:
5364
      feedback_fn("Running the instance OS create scripts...")
5365
      # FIXME: pass debug option from opcode to backend
5366
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
5367
                                             self.op.debug_level,
5368
                                             osparams=self.os_inst)
5369
      result.Raise("Could not install OS for instance %s on node %s" %
5370
                   (inst.name, inst.primary_node))
5371
    finally:
5372
      _ShutdownInstanceDisks(self, inst)
5373

    
5374

    
5375
class LUInstanceRecreateDisks(LogicalUnit):
5376
  """Recreate an instance's missing disks.
5377

5378
  """
5379
  HPATH = "instance-recreate-disks"
5380
  HTYPE = constants.HTYPE_INSTANCE
5381
  REQ_BGL = False
5382

    
5383
  def ExpandNames(self):
5384
    self._ExpandAndLockInstance()
5385

    
5386
  def BuildHooksEnv(self):
5387
    """Build hooks env.
5388

5389
    This runs on master, primary and secondary nodes of the instance.
5390

5391
    """
5392
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5393
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5394
    return env, nl, nl
5395

    
5396
  def CheckPrereq(self):
5397
    """Check prerequisites.
5398

5399
    This checks that the instance is in the cluster and is not running.
5400

5401
    """
5402
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5403
    assert instance is not None, \
5404
      "Cannot retrieve locked instance %s" % self.op.instance_name
5405
    _CheckNodeOnline(self, instance.primary_node)
5406

    
5407
    if instance.disk_template == constants.DT_DISKLESS:
5408
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5409
                                 self.op.instance_name, errors.ECODE_INVAL)
5410
    _CheckInstanceDown(self, instance, "cannot recreate disks")
5411

    
5412
    if not self.op.disks:
5413
      self.op.disks = range(len(instance.disks))
5414
    else:
5415
      for idx in self.op.disks:
5416
        if idx >= len(instance.disks):
5417
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
5418
                                     errors.ECODE_INVAL)
5419

    
5420
    self.instance = instance
5421

    
5422
  def Exec(self, feedback_fn):
5423
    """Recreate the disks.
5424

5425
    """
5426
    to_skip = []
5427
    for idx, _ in enumerate(self.instance.disks):
5428
      if idx not in self.op.disks: # disk idx has not been passed in
5429
        to_skip.append(idx)
5430
        continue
5431

    
5432
    _CreateDisks(self, self.instance, to_skip=to_skip)
5433

    
5434

    
5435
class LUInstanceRename(LogicalUnit):
5436
  """Rename an instance.
5437

5438
  """
5439
  HPATH = "instance-rename"
5440
  HTYPE = constants.HTYPE_INSTANCE
5441

    
5442
  def CheckArguments(self):
5443
    """Check arguments.
5444

5445
    """
5446
    if self.op.ip_check and not self.op.name_check:
5447
      # TODO: make the ip check more flexible and not depend on the name check
5448
      raise errors.OpPrereqError("Cannot do ip check without a name check",
5449
                                 errors.ECODE_INVAL)
5450

    
5451
  def BuildHooksEnv(self):
5452
    """Build hooks env.
5453

5454
    This runs on master, primary and secondary nodes of the instance.
5455

5456
    """
5457
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5458
    env["INSTANCE_NEW_NAME"] = self.op.new_name
5459
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5460
    return env, nl, nl
5461

    
5462
  def CheckPrereq(self):
5463
    """Check prerequisites.
5464

5465
    This checks that the instance is in the cluster and is not running.
5466

5467
    """
5468
    self.op.instance_name = _ExpandInstanceName(self.cfg,
5469
                                                self.op.instance_name)
5470
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5471
    assert instance is not None
5472
    _CheckNodeOnline(self, instance.primary_node)
5473
    _CheckInstanceDown(self, instance, "cannot rename")
5474
    self.instance = instance
5475

    
5476
    new_name = self.op.new_name
5477
    if self.op.name_check:
5478
      hostname = netutils.GetHostname(name=new_name)
5479
      self.LogInfo("Resolved given name '%s' to '%s'", new_name,
5480
                   hostname.name)
5481
      new_name = self.op.new_name = hostname.name
5482
      if (self.op.ip_check and
5483
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
5484
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
5485
                                   (hostname.ip, new_name),
5486
                                   errors.ECODE_NOTUNIQUE)
5487

    
5488
    instance_list = self.cfg.GetInstanceList()
5489
    if new_name in instance_list and new_name != instance.name:
5490
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5491
                                 new_name, errors.ECODE_EXISTS)
5492

    
5493
  def Exec(self, feedback_fn):
5494
    """Rename the instance.
5495

5496
    """
5497
    inst = self.instance
5498
    old_name = inst.name
5499

    
5500
    rename_file_storage = False
5501
    if (inst.disk_template == constants.DT_FILE and
5502
        self.op.new_name != inst.name):
5503
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5504
      rename_file_storage = True
5505

    
5506
    self.cfg.RenameInstance(inst.name, self.op.new_name)
5507
    # Change the instance lock. This is definitely safe while we hold the BGL
5508
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
5509
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
5510

    
5511
    # re-read the instance from the configuration after rename
5512
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
5513

    
5514
    if rename_file_storage:
5515
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5516
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
5517
                                                     old_file_storage_dir,
5518
                                                     new_file_storage_dir)
5519
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
5520
                   " (but the instance has been renamed in Ganeti)" %
5521
                   (inst.primary_node, old_file_storage_dir,
5522
                    new_file_storage_dir))
5523

    
5524
    _StartInstanceDisks(self, inst, None)
5525
    try:
5526
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
5527
                                                 old_name, self.op.debug_level)
5528
      msg = result.fail_msg
5529
      if msg:
5530
        msg = ("Could not run OS rename script for instance %s on node %s"
5531
               " (but the instance has been renamed in Ganeti): %s" %
5532
               (inst.name, inst.primary_node, msg))
5533
        self.proc.LogWarning(msg)
5534
    finally:
5535
      _ShutdownInstanceDisks(self, inst)
5536

    
5537
    return inst.name
5538

    
5539

    
5540
class LUInstanceRemove(LogicalUnit):
5541
  """Remove an instance.
5542

5543
  """
5544
  HPATH = "instance-remove"
5545
  HTYPE = constants.HTYPE_INSTANCE
5546
  REQ_BGL = False
5547

    
5548
  def ExpandNames(self):
5549
    self._ExpandAndLockInstance()
5550
    self.needed_locks[locking.LEVEL_NODE] = []
5551
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5552

    
5553
  def DeclareLocks(self, level):
5554
    if level == locking.LEVEL_NODE:
5555
      self._LockInstancesNodes()
5556

    
5557
  def BuildHooksEnv(self):
5558
    """Build hooks env.
5559

5560
    This runs on master, primary and secondary nodes of the instance.
5561

5562
    """
5563
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5564
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
5565
    nl = [self.cfg.GetMasterNode()]
5566
    nl_post = list(self.instance.all_nodes) + nl
5567
    return env, nl, nl_post
5568

    
5569
  def CheckPrereq(self):
5570
    """Check prerequisites.
5571

5572
    This checks that the instance is in the cluster.
5573

5574
    """
5575
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5576
    assert self.instance is not None, \
5577
      "Cannot retrieve locked instance %s" % self.op.instance_name
5578

    
5579
  def Exec(self, feedback_fn):
5580
    """Remove the instance.
5581

5582
    """
5583
    instance = self.instance
5584
    logging.info("Shutting down instance %s on node %s",
5585
                 instance.name, instance.primary_node)
5586

    
5587
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5588
                                             self.op.shutdown_timeout)
5589
    msg = result.fail_msg
5590
    if msg:
5591
      if self.op.ignore_failures:
5592
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5593
      else:
5594
        raise errors.OpExecError("Could not shutdown instance %s on"
5595
                                 " node %s: %s" %
5596
                                 (instance.name, instance.primary_node, msg))
5597

    
5598
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5599

    
5600

    
5601
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5602
  """Utility function to remove an instance.
5603

5604
  """
5605
  logging.info("Removing block devices for instance %s", instance.name)
5606

    
5607
  if not _RemoveDisks(lu, instance):
5608
    if not ignore_failures:
5609
      raise errors.OpExecError("Can't remove instance's disks")
5610
    feedback_fn("Warning: can't remove instance's disks")
5611

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

    
5614
  lu.cfg.RemoveInstance(instance.name)
5615

    
5616
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5617
    "Instance lock removal conflict"
5618

    
5619
  # Remove lock for the instance
5620
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5621

    
5622

    
5623
class LUInstanceQuery(NoHooksLU):
5624
  """Logical unit for querying instances.
5625

5626
  """
5627
  # pylint: disable-msg=W0142
5628
  REQ_BGL = False
5629

    
5630
  def CheckArguments(self):
5631
    self.iq = _InstanceQuery(self.op.names, self.op.output_fields,
5632
                             self.op.use_locking)
5633

    
5634
  def ExpandNames(self):
5635
    self.iq.ExpandNames(self)
5636

    
5637
  def DeclareLocks(self, level):
5638
    self.iq.DeclareLocks(self, level)
5639

    
5640
  def Exec(self, feedback_fn):
5641
    return self.iq.OldStyleQuery(self)
5642

    
5643

    
5644
class LUInstanceFailover(LogicalUnit):
5645
  """Failover an instance.
5646

5647
  """
5648
  HPATH = "instance-failover"
5649
  HTYPE = constants.HTYPE_INSTANCE
5650
  REQ_BGL = False
5651

    
5652
  def ExpandNames(self):
5653
    self._ExpandAndLockInstance()
5654
    self.needed_locks[locking.LEVEL_NODE] = []
5655
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5656

    
5657
  def DeclareLocks(self, level):
5658
    if level == locking.LEVEL_NODE:
5659
      self._LockInstancesNodes()
5660

    
5661
  def BuildHooksEnv(self):
5662
    """Build hooks env.
5663

5664
    This runs on master, primary and secondary nodes of the instance.
5665

5666
    """
5667
    instance = self.instance
5668
    source_node = instance.primary_node
5669
    target_node = instance.secondary_nodes[0]
5670
    env = {
5671
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5672
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5673
      "OLD_PRIMARY": source_node,
5674
      "OLD_SECONDARY": target_node,
5675
      "NEW_PRIMARY": target_node,
5676
      "NEW_SECONDARY": source_node,
5677
      }
5678
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5679
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5680
    nl_post = list(nl)
5681
    nl_post.append(source_node)
5682
    return env, nl, nl_post
5683

    
5684
  def CheckPrereq(self):
5685
    """Check prerequisites.
5686

5687
    This checks that the instance is in the cluster.
5688

5689
    """
5690
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5691
    assert self.instance is not None, \
5692
      "Cannot retrieve locked instance %s" % self.op.instance_name
5693

    
5694
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5695
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5696
      raise errors.OpPrereqError("Instance's disk layout is not"
5697
                                 " network mirrored, cannot failover.",
5698
                                 errors.ECODE_STATE)
5699

    
5700
    secondary_nodes = instance.secondary_nodes
5701
    if not secondary_nodes:
5702
      raise errors.ProgrammerError("no secondary node but using "
5703
                                   "a mirrored disk template")
5704

    
5705
    target_node = secondary_nodes[0]
5706
    _CheckNodeOnline(self, target_node)
5707
    _CheckNodeNotDrained(self, target_node)
5708
    if instance.admin_up:
5709
      # check memory requirements on the secondary node
5710
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5711
                           instance.name, bep[constants.BE_MEMORY],
5712
                           instance.hypervisor)
5713
    else:
5714
      self.LogInfo("Not checking memory on the secondary node as"
5715
                   " instance will not be started")
5716

    
5717
    # check bridge existance
5718
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5719

    
5720
  def Exec(self, feedback_fn):
5721
    """Failover an instance.
5722

5723
    The failover is done by shutting it down on its present node and
5724
    starting it on the secondary.
5725

5726
    """
5727
    instance = self.instance
5728
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
5729

    
5730
    source_node = instance.primary_node
5731
    target_node = instance.secondary_nodes[0]
5732

    
5733
    if instance.admin_up:
5734
      feedback_fn("* checking disk consistency between source and target")
5735
      for dev in instance.disks:
5736
        # for drbd, these are drbd over lvm
5737
        if not _CheckDiskConsistency(self, dev, target_node, False):
5738
          if not self.op.ignore_consistency:
5739
            raise errors.OpExecError("Disk %s is degraded on target node,"
5740
                                     " aborting failover." % dev.iv_name)
5741
    else:
5742
      feedback_fn("* not checking disk consistency as instance is not running")
5743

    
5744
    feedback_fn("* shutting down instance on source node")
5745
    logging.info("Shutting down instance %s on node %s",
5746
                 instance.name, source_node)
5747

    
5748
    result = self.rpc.call_instance_shutdown(source_node, instance,
5749
                                             self.op.shutdown_timeout)
5750
    msg = result.fail_msg
5751
    if msg:
5752
      if self.op.ignore_consistency or primary_node.offline:
5753
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5754
                             " Proceeding anyway. Please make sure node"
5755
                             " %s is down. Error details: %s",
5756
                             instance.name, source_node, source_node, msg)
5757
      else:
5758
        raise errors.OpExecError("Could not shutdown instance %s on"
5759
                                 " node %s: %s" %
5760
                                 (instance.name, source_node, msg))
5761

    
5762
    feedback_fn("* deactivating the instance's disks on source node")
5763
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5764
      raise errors.OpExecError("Can't shut down the instance's disks.")
5765

    
5766
    instance.primary_node = target_node
5767
    # distribute new instance config to the other nodes
5768
    self.cfg.Update(instance, feedback_fn)
5769

    
5770
    # Only start the instance if it's marked as up
5771
    if instance.admin_up:
5772
      feedback_fn("* activating the instance's disks on target node")
5773
      logging.info("Starting instance %s on node %s",
5774
                   instance.name, target_node)
5775

    
5776
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5777
                                           ignore_secondaries=True)
5778
      if not disks_ok:
5779
        _ShutdownInstanceDisks(self, instance)
5780
        raise errors.OpExecError("Can't activate the instance's disks")
5781

    
5782
      feedback_fn("* starting the instance on the target node")
5783
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5784
      msg = result.fail_msg
5785
      if msg:
5786
        _ShutdownInstanceDisks(self, instance)
5787
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5788
                                 (instance.name, target_node, msg))
5789

    
5790

    
5791
class LUInstanceMigrate(LogicalUnit):
5792
  """Migrate an instance.
5793

5794
  This is migration without shutting down, compared to the failover,
5795
  which is done with shutdown.
5796

5797
  """
5798
  HPATH = "instance-migrate"
5799
  HTYPE = constants.HTYPE_INSTANCE
5800
  REQ_BGL = False
5801

    
5802
  def ExpandNames(self):
5803
    self._ExpandAndLockInstance()
5804

    
5805
    self.needed_locks[locking.LEVEL_NODE] = []
5806
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5807

    
5808
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5809
                                       self.op.cleanup)
5810
    self.tasklets = [self._migrater]
5811

    
5812
  def DeclareLocks(self, level):
5813
    if level == locking.LEVEL_NODE:
5814
      self._LockInstancesNodes()
5815

    
5816
  def BuildHooksEnv(self):
5817
    """Build hooks env.
5818

5819
    This runs on master, primary and secondary nodes of the instance.
5820

5821
    """
5822
    instance = self._migrater.instance
5823
    source_node = instance.primary_node
5824
    target_node = instance.secondary_nodes[0]
5825
    env = _BuildInstanceHookEnvByObject(self, instance)
5826
    env["MIGRATE_LIVE"] = self._migrater.live
5827
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5828
    env.update({
5829
        "OLD_PRIMARY": source_node,
5830
        "OLD_SECONDARY": target_node,
5831
        "NEW_PRIMARY": target_node,
5832
        "NEW_SECONDARY": source_node,
5833
        })
5834
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5835
    nl_post = list(nl)
5836
    nl_post.append(source_node)
5837
    return env, nl, nl_post
5838

    
5839

    
5840
class LUInstanceMove(LogicalUnit):
5841
  """Move an instance by data-copying.
5842

5843
  """
5844
  HPATH = "instance-move"
5845
  HTYPE = constants.HTYPE_INSTANCE
5846
  REQ_BGL = False
5847

    
5848
  def ExpandNames(self):
5849
    self._ExpandAndLockInstance()
5850
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5851
    self.op.target_node = target_node
5852
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5853
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5854

    
5855
  def DeclareLocks(self, level):
5856
    if level == locking.LEVEL_NODE:
5857
      self._LockInstancesNodes(primary_only=True)
5858

    
5859
  def BuildHooksEnv(self):
5860
    """Build hooks env.
5861

5862
    This runs on master, primary and secondary nodes of the instance.
5863

5864
    """
5865
    env = {
5866
      "TARGET_NODE": self.op.target_node,
5867
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5868
      }
5869
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5870
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5871
                                       self.op.target_node]
5872
    return env, nl, nl
5873

    
5874
  def CheckPrereq(self):
5875
    """Check prerequisites.
5876

5877
    This checks that the instance is in the cluster.
5878

5879
    """
5880
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5881
    assert self.instance is not None, \
5882
      "Cannot retrieve locked instance %s" % self.op.instance_name
5883

    
5884
    node = self.cfg.GetNodeInfo(self.op.target_node)
5885
    assert node is not None, \
5886
      "Cannot retrieve locked node %s" % self.op.target_node
5887

    
5888
    self.target_node = target_node = node.name
5889

    
5890
    if target_node == instance.primary_node:
5891
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5892
                                 (instance.name, target_node),
5893
                                 errors.ECODE_STATE)
5894

    
5895
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5896

    
5897
    for idx, dsk in enumerate(instance.disks):
5898
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5899
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5900
                                   " cannot copy" % idx, errors.ECODE_STATE)
5901

    
5902
    _CheckNodeOnline(self, target_node)
5903
    _CheckNodeNotDrained(self, target_node)
5904
    _CheckNodeVmCapable(self, target_node)
5905

    
5906
    if instance.admin_up:
5907
      # check memory requirements on the secondary node
5908
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5909
                           instance.name, bep[constants.BE_MEMORY],
5910
                           instance.hypervisor)
5911
    else:
5912
      self.LogInfo("Not checking memory on the secondary node as"
5913
                   " instance will not be started")
5914

    
5915
    # check bridge existance
5916
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5917

    
5918
  def Exec(self, feedback_fn):
5919
    """Move an instance.
5920

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

5924
    """
5925
    instance = self.instance
5926

    
5927
    source_node = instance.primary_node
5928
    target_node = self.target_node
5929

    
5930
    self.LogInfo("Shutting down instance %s on source node %s",
5931
                 instance.name, source_node)
5932

    
5933
    result = self.rpc.call_instance_shutdown(source_node, instance,
5934
                                             self.op.shutdown_timeout)
5935
    msg = result.fail_msg
5936
    if msg:
5937
      if self.op.ignore_consistency:
5938
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5939
                             " Proceeding anyway. Please make sure node"
5940
                             " %s is down. Error details: %s",
5941
                             instance.name, source_node, source_node, msg)
5942
      else:
5943
        raise errors.OpExecError("Could not shutdown instance %s on"
5944
                                 " node %s: %s" %
5945
                                 (instance.name, source_node, msg))
5946

    
5947
    # create the target disks
5948
    try:
5949
      _CreateDisks(self, instance, target_node=target_node)
5950
    except errors.OpExecError:
5951
      self.LogWarning("Device creation failed, reverting...")
5952
      try:
5953
        _RemoveDisks(self, instance, target_node=target_node)
5954
      finally:
5955
        self.cfg.ReleaseDRBDMinors(instance.name)
5956
        raise
5957

    
5958
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5959

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

    
5981
    if errs:
5982
      self.LogWarning("Some disks failed to copy, aborting")
5983
      try:
5984
        _RemoveDisks(self, instance, target_node=target_node)
5985
      finally:
5986
        self.cfg.ReleaseDRBDMinors(instance.name)
5987
        raise errors.OpExecError("Errors during disk copy: %s" %
5988
                                 (",".join(errs),))
5989

    
5990
    instance.primary_node = target_node
5991
    self.cfg.Update(instance, feedback_fn)
5992

    
5993
    self.LogInfo("Removing the disks on the original node")
5994
    _RemoveDisks(self, instance, target_node=source_node)
5995

    
5996
    # Only start the instance if it's marked as up
5997
    if instance.admin_up:
5998
      self.LogInfo("Starting instance %s on node %s",
5999
                   instance.name, target_node)
6000

    
6001
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
6002
                                           ignore_secondaries=True)
6003
      if not disks_ok:
6004
        _ShutdownInstanceDisks(self, instance)
6005
        raise errors.OpExecError("Can't activate the instance's disks")
6006

    
6007
      result = self.rpc.call_instance_start(target_node, instance, None, None)
6008
      msg = result.fail_msg
6009
      if msg:
6010
        _ShutdownInstanceDisks(self, instance)
6011
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
6012
                                 (instance.name, target_node, msg))
6013

    
6014

    
6015
class LUNodeMigrate(LogicalUnit):
6016
  """Migrate all instances from a node.
6017

6018
  """
6019
  HPATH = "node-migrate"
6020
  HTYPE = constants.HTYPE_NODE
6021
  REQ_BGL = False
6022

    
6023
  def ExpandNames(self):
6024
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6025

    
6026
    self.needed_locks = {
6027
      locking.LEVEL_NODE: [self.op.node_name],
6028
      }
6029

    
6030
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6031

    
6032
    # Create tasklets for migrating instances for all instances on this node
6033
    names = []
6034
    tasklets = []
6035

    
6036
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
6037
      logging.debug("Migrating instance %s", inst.name)
6038
      names.append(inst.name)
6039

    
6040
      tasklets.append(TLMigrateInstance(self, inst.name, False))
6041

    
6042
    self.tasklets = tasklets
6043

    
6044
    # Declare instance locks
6045
    self.needed_locks[locking.LEVEL_INSTANCE] = names
6046

    
6047
  def DeclareLocks(self, level):
6048
    if level == locking.LEVEL_NODE:
6049
      self._LockInstancesNodes()
6050

    
6051
  def BuildHooksEnv(self):
6052
    """Build hooks env.
6053

6054
    This runs on the master, the primary and all the secondaries.
6055

6056
    """
6057
    env = {
6058
      "NODE_NAME": self.op.node_name,
6059
      }
6060

    
6061
    nl = [self.cfg.GetMasterNode()]
6062

    
6063
    return (env, nl, nl)
6064

    
6065

    
6066
class TLMigrateInstance(Tasklet):
6067
  """Tasklet class for instance migration.
6068

6069
  @type live: boolean
6070
  @ivar live: whether the migration will be done live or non-live;
6071
      this variable is initalized only after CheckPrereq has run
6072

6073
  """
6074
  def __init__(self, lu, instance_name, cleanup):
6075
    """Initializes this class.
6076

6077
    """
6078
    Tasklet.__init__(self, lu)
6079

    
6080
    # Parameters
6081
    self.instance_name = instance_name
6082
    self.cleanup = cleanup
6083
    self.live = False # will be overridden later
6084

    
6085
  def CheckPrereq(self):
6086
    """Check prerequisites.
6087

6088
    This checks that the instance is in the cluster.
6089

6090
    """
6091
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
6092
    instance = self.cfg.GetInstanceInfo(instance_name)
6093
    assert instance is not None
6094

    
6095
    if instance.disk_template != constants.DT_DRBD8:
6096
      raise errors.OpPrereqError("Instance's disk layout is not"
6097
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
6098

    
6099
    secondary_nodes = instance.secondary_nodes
6100
    if not secondary_nodes:
6101
      raise errors.ConfigurationError("No secondary node but using"
6102
                                      " drbd8 disk template")
6103

    
6104
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
6105

    
6106
    target_node = secondary_nodes[0]
6107
    # check memory requirements on the secondary node
6108
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
6109
                         instance.name, i_be[constants.BE_MEMORY],
6110
                         instance.hypervisor)
6111

    
6112
    # check bridge existance
6113
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
6114

    
6115
    if not self.cleanup:
6116
      _CheckNodeNotDrained(self.lu, target_node)
6117
      result = self.rpc.call_instance_migratable(instance.primary_node,
6118
                                                 instance)
6119
      result.Raise("Can't migrate, please use failover",
6120
                   prereq=True, ecode=errors.ECODE_STATE)
6121

    
6122
    self.instance = instance
6123

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

    
6141
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6142

    
6143
  def _WaitUntilSync(self):
6144
    """Poll with custom rpc for disk sync.
6145

6146
    This uses our own step-based rpc call.
6147

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

    
6168
  def _EnsureSecondary(self, node):
6169
    """Demote a node to secondary.
6170

6171
    """
6172
    self.feedback_fn("* switching node %s to secondary mode" % node)
6173

    
6174
    for dev in self.instance.disks:
6175
      self.cfg.SetDiskID(dev, node)
6176

    
6177
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6178
                                          self.instance.disks)
6179
    result.Raise("Cannot change disk to secondary on node %s" % node)
6180

    
6181
  def _GoStandalone(self):
6182
    """Disconnect from the network.
6183

6184
    """
6185
    self.feedback_fn("* changing into standalone mode")
6186
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6187
                                               self.instance.disks)
6188
    for node, nres in result.items():
6189
      nres.Raise("Cannot disconnect disks node %s" % node)
6190

    
6191
  def _GoReconnect(self, multimaster):
6192
    """Reconnect to the network.
6193

6194
    """
6195
    if multimaster:
6196
      msg = "dual-master"
6197
    else:
6198
      msg = "single-master"
6199
    self.feedback_fn("* changing disks into %s mode" % msg)
6200
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6201
                                           self.instance.disks,
6202
                                           self.instance.name, multimaster)
6203
    for node, nres in result.items():
6204
      nres.Raise("Cannot change disks config on node %s" % node)
6205

    
6206
  def _ExecCleanup(self):
6207
    """Try to cleanup after a failed migration.
6208

6209
    The cleanup is done by:
6210
      - check that the instance is running only on one node
6211
        (and update the config if needed)
6212
      - change disks on its secondary node to secondary
6213
      - wait until disks are fully synchronized
6214
      - disconnect from the network
6215
      - change disks into single-master mode
6216
      - wait again until disks are fully synchronized
6217

6218
    """
6219
    instance = self.instance
6220
    target_node = self.target_node
6221
    source_node = self.source_node
6222

    
6223
    # check running on only one node
6224
    self.feedback_fn("* checking where the instance actually runs"
6225
                     " (if this hangs, the hypervisor might be in"
6226
                     " a bad state)")
6227
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
6228
    for node, result in ins_l.items():
6229
      result.Raise("Can't contact node %s" % node)
6230

    
6231
    runningon_source = instance.name in ins_l[source_node].payload
6232
    runningon_target = instance.name in ins_l[target_node].payload
6233

    
6234
    if runningon_source and runningon_target:
6235
      raise errors.OpExecError("Instance seems to be running on two nodes,"
6236
                               " or the hypervisor is confused. You will have"
6237
                               " to ensure manually that it runs only on one"
6238
                               " and restart this operation.")
6239

    
6240
    if not (runningon_source or runningon_target):
6241
      raise errors.OpExecError("Instance does not seem to be running at all."
6242
                               " In this case, it's safer to repair by"
6243
                               " running 'gnt-instance stop' to ensure disk"
6244
                               " shutdown, and then restarting it.")
6245

    
6246
    if runningon_target:
6247
      # the migration has actually succeeded, we need to update the config
6248
      self.feedback_fn("* instance running on secondary node (%s),"
6249
                       " updating config" % target_node)
6250
      instance.primary_node = target_node
6251
      self.cfg.Update(instance, self.feedback_fn)
6252
      demoted_node = source_node
6253
    else:
6254
      self.feedback_fn("* instance confirmed to be running on its"
6255
                       " primary node (%s)" % source_node)
6256
      demoted_node = target_node
6257

    
6258
    self._EnsureSecondary(demoted_node)
6259
    try:
6260
      self._WaitUntilSync()
6261
    except errors.OpExecError:
6262
      # we ignore here errors, since if the device is standalone, it
6263
      # won't be able to sync
6264
      pass
6265
    self._GoStandalone()
6266
    self._GoReconnect(False)
6267
    self._WaitUntilSync()
6268

    
6269
    self.feedback_fn("* done")
6270

    
6271
  def _RevertDiskStatus(self):
6272
    """Try to revert the disk status after a failed migration.
6273

6274
    """
6275
    target_node = self.target_node
6276
    try:
6277
      self._EnsureSecondary(target_node)
6278
      self._GoStandalone()
6279
      self._GoReconnect(False)
6280
      self._WaitUntilSync()
6281
    except errors.OpExecError, err:
6282
      self.lu.LogWarning("Migration failed and I can't reconnect the"
6283
                         " drives: error '%s'\n"
6284
                         "Please look and recover the instance status" %
6285
                         str(err))
6286

    
6287
  def _AbortMigration(self):
6288
    """Call the hypervisor code to abort a started migration.
6289

6290
    """
6291
    instance = self.instance
6292
    target_node = self.target_node
6293
    migration_info = self.migration_info
6294

    
6295
    abort_result = self.rpc.call_finalize_migration(target_node,
6296
                                                    instance,
6297
                                                    migration_info,
6298
                                                    False)
6299
    abort_msg = abort_result.fail_msg
6300
    if abort_msg:
6301
      logging.error("Aborting migration failed on target node %s: %s",
6302
                    target_node, abort_msg)
6303
      # Don't raise an exception here, as we stil have to try to revert the
6304
      # disk status, even if this step failed.
6305

    
6306
  def _ExecMigration(self):
6307
    """Migrate an instance.
6308

6309
    The migrate is done by:
6310
      - change the disks into dual-master mode
6311
      - wait until disks are fully synchronized again
6312
      - migrate the instance
6313
      - change disks on the new secondary node (the old primary) to secondary
6314
      - wait until disks are fully synchronized
6315
      - change disks into single-master mode
6316

6317
    """
6318
    instance = self.instance
6319
    target_node = self.target_node
6320
    source_node = self.source_node
6321

    
6322
    self.feedback_fn("* checking disk consistency between source and target")
6323
    for dev in instance.disks:
6324
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6325
        raise errors.OpExecError("Disk %s is degraded or not fully"
6326
                                 " synchronized on target node,"
6327
                                 " aborting migrate." % dev.iv_name)
6328

    
6329
    # First get the migration information from the remote node
6330
    result = self.rpc.call_migration_info(source_node, instance)
6331
    msg = result.fail_msg
6332
    if msg:
6333
      log_err = ("Failed fetching source migration information from %s: %s" %
6334
                 (source_node, msg))
6335
      logging.error(log_err)
6336
      raise errors.OpExecError(log_err)
6337

    
6338
    self.migration_info = migration_info = result.payload
6339

    
6340
    # Then switch the disks to master/master mode
6341
    self._EnsureSecondary(target_node)
6342
    self._GoStandalone()
6343
    self._GoReconnect(True)
6344
    self._WaitUntilSync()
6345

    
6346
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6347
    result = self.rpc.call_accept_instance(target_node,
6348
                                           instance,
6349
                                           migration_info,
6350
                                           self.nodes_ip[target_node])
6351

    
6352
    msg = result.fail_msg
6353
    if msg:
6354
      logging.error("Instance pre-migration failed, trying to revert"
6355
                    " disk status: %s", msg)
6356
      self.feedback_fn("Pre-migration failed, aborting")
6357
      self._AbortMigration()
6358
      self._RevertDiskStatus()
6359
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6360
                               (instance.name, msg))
6361

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

    
6378
    instance.primary_node = target_node
6379
    # distribute new instance config to the other nodes
6380
    self.cfg.Update(instance, self.feedback_fn)
6381

    
6382
    result = self.rpc.call_finalize_migration(target_node,
6383
                                              instance,
6384
                                              migration_info,
6385
                                              True)
6386
    msg = result.fail_msg
6387
    if msg:
6388
      logging.error("Instance migration succeeded, but finalization failed:"
6389
                    " %s", msg)
6390
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6391
                               msg)
6392

    
6393
    self._EnsureSecondary(source_node)
6394
    self._WaitUntilSync()
6395
    self._GoStandalone()
6396
    self._GoReconnect(False)
6397
    self._WaitUntilSync()
6398

    
6399
    self.feedback_fn("* done")
6400

    
6401
  def Exec(self, feedback_fn):
6402
    """Perform the migration.
6403

6404
    """
6405
    feedback_fn("Migrating instance %s" % self.instance.name)
6406

    
6407
    self.feedback_fn = feedback_fn
6408

    
6409
    self.source_node = self.instance.primary_node
6410
    self.target_node = self.instance.secondary_nodes[0]
6411
    self.all_nodes = [self.source_node, self.target_node]
6412
    self.nodes_ip = {
6413
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6414
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6415
      }
6416

    
6417
    if self.cleanup:
6418
      return self._ExecCleanup()
6419
    else:
6420
      return self._ExecMigration()
6421

    
6422

    
6423
def _CreateBlockDev(lu, node, instance, device, force_create,
6424
                    info, force_open):
6425
  """Create a tree of block devices on a given node.
6426

6427
  If this device type has to be created on secondaries, create it and
6428
  all its children.
6429

6430
  If not, just recurse to children keeping the same 'force' value.
6431

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

6450
  """
6451
  if device.CreateOnSecondary():
6452
    force_create = True
6453

    
6454
  if device.children:
6455
    for child in device.children:
6456
      _CreateBlockDev(lu, node, instance, child, force_create,
6457
                      info, force_open)
6458

    
6459
  if not force_create:
6460
    return
6461

    
6462
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6463

    
6464

    
6465
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6466
  """Create a single block device on a given node.
6467

6468
  This will not recurse over children of the device, so they must be
6469
  created in advance.
6470

6471
  @param lu: the lu on whose behalf we execute
6472
  @param node: the node on which to create the device
6473
  @type instance: L{objects.Instance}
6474
  @param instance: the instance which owns the device
6475
  @type device: L{objects.Disk}
6476
  @param device: the device to create
6477
  @param info: the extra 'metadata' we should attach to the device
6478
      (this will be represented as a LVM tag)
6479
  @type force_open: boolean
6480
  @param force_open: this parameter will be passes to the
6481
      L{backend.BlockdevCreate} function where it specifies
6482
      whether we run on primary or not, and it affects both
6483
      the child assembly and the device own Open() execution
6484

6485
  """
6486
  lu.cfg.SetDiskID(device, node)
6487
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6488
                                       instance.name, force_open, info)
6489
  result.Raise("Can't create block device %s on"
6490
               " node %s for instance %s" % (device, node, instance.name))
6491
  if device.physical_id is None:
6492
    device.physical_id = result.payload
6493

    
6494

    
6495
def _GenerateUniqueNames(lu, exts):
6496
  """Generate a suitable LV name.
6497

6498
  This will generate a logical volume name for the given instance.
6499

6500
  """
6501
  results = []
6502
  for val in exts:
6503
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6504
    results.append("%s%s" % (new_id, val))
6505
  return results
6506

    
6507

    
6508
def _GenerateDRBD8Branch(lu, primary, secondary, size, vgname, names, iv_name,
6509
                         p_minor, s_minor):
6510
  """Generate a drbd8 device complete with its children.
6511

6512
  """
6513
  port = lu.cfg.AllocatePort()
6514
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6515
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6516
                          logical_id=(vgname, names[0]))
6517
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6518
                          logical_id=(vgname, names[1]))
6519
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6520
                          logical_id=(primary, secondary, port,
6521
                                      p_minor, s_minor,
6522
                                      shared_secret),
6523
                          children=[dev_data, dev_meta],
6524
                          iv_name=iv_name)
6525
  return drbd_dev
6526

    
6527

    
6528
def _GenerateDiskTemplate(lu, template_name,
6529
                          instance_name, primary_node,
6530
                          secondary_nodes, disk_info,
6531
                          file_storage_dir, file_driver,
6532
                          base_index, feedback_fn):
6533
  """Generate the entire disk layout for a given template type.
6534

6535
  """
6536
  #TODO: compute space requirements
6537

    
6538
  vgname = lu.cfg.GetVGName()
6539
  disk_count = len(disk_info)
6540
  disks = []
6541
  if template_name == constants.DT_DISKLESS:
6542
    pass
6543
  elif template_name == constants.DT_PLAIN:
6544
    if len(secondary_nodes) != 0:
6545
      raise errors.ProgrammerError("Wrong template configuration")
6546

    
6547
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6548
                                      for i in range(disk_count)])
6549
    for idx, disk in enumerate(disk_info):
6550
      disk_index = idx + base_index
6551
      vg = disk.get("vg", vgname)
6552
      feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
6553
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6554
                              logical_id=(vg, names[idx]),
6555
                              iv_name="disk/%d" % disk_index,
6556
                              mode=disk["mode"])
6557
      disks.append(disk_dev)
6558
  elif template_name == constants.DT_DRBD8:
6559
    if len(secondary_nodes) != 1:
6560
      raise errors.ProgrammerError("Wrong template configuration")
6561
    remote_node = secondary_nodes[0]
6562
    minors = lu.cfg.AllocateDRBDMinor(
6563
      [primary_node, remote_node] * len(disk_info), instance_name)
6564

    
6565
    names = []
6566
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6567
                                               for i in range(disk_count)]):
6568
      names.append(lv_prefix + "_data")
6569
      names.append(lv_prefix + "_meta")
6570
    for idx, disk in enumerate(disk_info):
6571
      disk_index = idx + base_index
6572
      vg = disk.get("vg", vgname)
6573
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6574
                                      disk["size"], vg, names[idx*2:idx*2+2],
6575
                                      "disk/%d" % disk_index,
6576
                                      minors[idx*2], minors[idx*2+1])
6577
      disk_dev.mode = disk["mode"]
6578
      disks.append(disk_dev)
6579
  elif template_name == constants.DT_FILE:
6580
    if len(secondary_nodes) != 0:
6581
      raise errors.ProgrammerError("Wrong template configuration")
6582

    
6583
    opcodes.RequireFileStorage()
6584

    
6585
    for idx, disk in enumerate(disk_info):
6586
      disk_index = idx + base_index
6587
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6588
                              iv_name="disk/%d" % disk_index,
6589
                              logical_id=(file_driver,
6590
                                          "%s/disk%d" % (file_storage_dir,
6591
                                                         disk_index)),
6592
                              mode=disk["mode"])
6593
      disks.append(disk_dev)
6594
  else:
6595
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6596
  return disks
6597

    
6598

    
6599
def _GetInstanceInfoText(instance):
6600
  """Compute that text that should be added to the disk's metadata.
6601

6602
  """
6603
  return "originstname+%s" % instance.name
6604

    
6605

    
6606
def _CalcEta(time_taken, written, total_size):
6607
  """Calculates the ETA based on size written and total size.
6608

6609
  @param time_taken: The time taken so far
6610
  @param written: amount written so far
6611
  @param total_size: The total size of data to be written
6612
  @return: The remaining time in seconds
6613

6614
  """
6615
  avg_time = time_taken / float(written)
6616
  return (total_size - written) * avg_time
6617

    
6618

    
6619
def _WipeDisks(lu, instance):
6620
  """Wipes instance disks.
6621

6622
  @type lu: L{LogicalUnit}
6623
  @param lu: the logical unit on whose behalf we execute
6624
  @type instance: L{objects.Instance}
6625
  @param instance: the instance whose disks we should create
6626
  @return: the success of the wipe
6627

6628
  """
6629
  node = instance.primary_node
6630
  logging.info("Pause sync of instance %s disks", instance.name)
6631
  result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, True)
6632

    
6633
  for idx, success in enumerate(result.payload):
6634
    if not success:
6635
      logging.warn("pause-sync of instance %s for disks %d failed",
6636
                   instance.name, idx)
6637

    
6638
  try:
6639
    for idx, device in enumerate(instance.disks):
6640
      lu.LogInfo("* Wiping disk %d", idx)
6641
      logging.info("Wiping disk %d for instance %s", idx, instance.name)
6642

    
6643
      # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
6644
      # MAX_WIPE_CHUNK at max
6645
      wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
6646
                            constants.MIN_WIPE_CHUNK_PERCENT)
6647

    
6648
      offset = 0
6649
      size = device.size
6650
      last_output = 0
6651
      start_time = time.time()
6652

    
6653
      while offset < size:
6654
        wipe_size = min(wipe_chunk_size, size - offset)
6655
        result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
6656
        result.Raise("Could not wipe disk %d at offset %d for size %d" %
6657
                     (idx, offset, wipe_size))
6658
        now = time.time()
6659
        offset += wipe_size
6660
        if now - last_output >= 60:
6661
          eta = _CalcEta(now - start_time, offset, size)
6662
          lu.LogInfo(" - done: %.1f%% ETA: %s" %
6663
                     (offset / float(size) * 100, utils.FormatSeconds(eta)))
6664
          last_output = now
6665
  finally:
6666
    logging.info("Resume sync of instance %s disks", instance.name)
6667

    
6668
    result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, False)
6669

    
6670
    for idx, success in enumerate(result.payload):
6671
      if not success:
6672
        lu.LogWarning("Warning: Resume sync of disk %d failed. Please have a"
6673
                      " look at the status and troubleshoot the issue.", idx)
6674
        logging.warn("resume-sync of instance %s for disks %d failed",
6675
                     instance.name, idx)
6676

    
6677

    
6678
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6679
  """Create all disks for an instance.
6680

6681
  This abstracts away some work from AddInstance.
6682

6683
  @type lu: L{LogicalUnit}
6684
  @param lu: the logical unit on whose behalf we execute
6685
  @type instance: L{objects.Instance}
6686
  @param instance: the instance whose disks we should create
6687
  @type to_skip: list
6688
  @param to_skip: list of indices to skip
6689
  @type target_node: string
6690
  @param target_node: if passed, overrides the target node for creation
6691
  @rtype: boolean
6692
  @return: the success of the creation
6693

6694
  """
6695
  info = _GetInstanceInfoText(instance)
6696
  if target_node is None:
6697
    pnode = instance.primary_node
6698
    all_nodes = instance.all_nodes
6699
  else:
6700
    pnode = target_node
6701
    all_nodes = [pnode]
6702

    
6703
  if instance.disk_template == constants.DT_FILE:
6704
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6705
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6706

    
6707
    result.Raise("Failed to create directory '%s' on"
6708
                 " node %s" % (file_storage_dir, pnode))
6709

    
6710
  # Note: this needs to be kept in sync with adding of disks in
6711
  # LUInstanceSetParams
6712
  for idx, device in enumerate(instance.disks):
6713
    if to_skip and idx in to_skip:
6714
      continue
6715
    logging.info("Creating volume %s for instance %s",
6716
                 device.iv_name, instance.name)
6717
    #HARDCODE
6718
    for node in all_nodes:
6719
      f_create = node == pnode
6720
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6721

    
6722

    
6723
def _RemoveDisks(lu, instance, target_node=None):
6724
  """Remove all disks for an instance.
6725

6726
  This abstracts away some work from `AddInstance()` and
6727
  `RemoveInstance()`. Note that in case some of the devices couldn't
6728
  be removed, the removal will continue with the other ones (compare
6729
  with `_CreateDisks()`).
6730

6731
  @type lu: L{LogicalUnit}
6732
  @param lu: the logical unit on whose behalf we execute
6733
  @type instance: L{objects.Instance}
6734
  @param instance: the instance whose disks we should remove
6735
  @type target_node: string
6736
  @param target_node: used to override the node on which to remove the disks
6737
  @rtype: boolean
6738
  @return: the success of the removal
6739

6740
  """
6741
  logging.info("Removing block devices for instance %s", instance.name)
6742

    
6743
  all_result = True
6744
  for device in instance.disks:
6745
    if target_node:
6746
      edata = [(target_node, device)]
6747
    else:
6748
      edata = device.ComputeNodeTree(instance.primary_node)
6749
    for node, disk in edata:
6750
      lu.cfg.SetDiskID(disk, node)
6751
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6752
      if msg:
6753
        lu.LogWarning("Could not remove block device %s on node %s,"
6754
                      " continuing anyway: %s", device.iv_name, node, msg)
6755
        all_result = False
6756

    
6757
  if instance.disk_template == constants.DT_FILE:
6758
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6759
    if target_node:
6760
      tgt = target_node
6761
    else:
6762
      tgt = instance.primary_node
6763
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6764
    if result.fail_msg:
6765
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6766
                    file_storage_dir, instance.primary_node, result.fail_msg)
6767
      all_result = False
6768

    
6769
  return all_result
6770

    
6771

    
6772
def _ComputeDiskSizePerVG(disk_template, disks):
6773
  """Compute disk size requirements in the volume group
6774

6775
  """
6776
  def _compute(disks, payload):
6777
    """Universal algorithm
6778

6779
    """
6780
    vgs = {}
6781
    for disk in disks:
6782
      vgs[disk["vg"]] = vgs.get("vg", 0) + disk["size"] + payload
6783

    
6784
    return vgs
6785

    
6786
  # Required free disk space as a function of disk and swap space
6787
  req_size_dict = {
6788
    constants.DT_DISKLESS: {},
6789
    constants.DT_PLAIN: _compute(disks, 0),
6790
    # 128 MB are added for drbd metadata for each disk
6791
    constants.DT_DRBD8: _compute(disks, 128),
6792
    constants.DT_FILE: {},
6793
  }
6794

    
6795
  if disk_template not in req_size_dict:
6796
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6797
                                 " is unknown" %  disk_template)
6798

    
6799
  return req_size_dict[disk_template]
6800

    
6801

    
6802
def _ComputeDiskSize(disk_template, disks):
6803
  """Compute disk size requirements in the volume group
6804

6805
  """
6806
  # Required free disk space as a function of disk and swap space
6807
  req_size_dict = {
6808
    constants.DT_DISKLESS: None,
6809
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6810
    # 128 MB are added for drbd metadata for each disk
6811
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6812
    constants.DT_FILE: None,
6813
  }
6814

    
6815
  if disk_template not in req_size_dict:
6816
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6817
                                 " is unknown" %  disk_template)
6818

    
6819
  return req_size_dict[disk_template]
6820

    
6821

    
6822
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6823
  """Hypervisor parameter validation.
6824

6825
  This function abstract the hypervisor parameter validation to be
6826
  used in both instance create and instance modify.
6827

6828
  @type lu: L{LogicalUnit}
6829
  @param lu: the logical unit for which we check
6830
  @type nodenames: list
6831
  @param nodenames: the list of nodes on which we should check
6832
  @type hvname: string
6833
  @param hvname: the name of the hypervisor we should use
6834
  @type hvparams: dict
6835
  @param hvparams: the parameters which we need to check
6836
  @raise errors.OpPrereqError: if the parameters are not valid
6837

6838
  """
6839
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6840
                                                  hvname,
6841
                                                  hvparams)
6842
  for node in nodenames:
6843
    info = hvinfo[node]
6844
    if info.offline:
6845
      continue
6846
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6847

    
6848

    
6849
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6850
  """OS parameters validation.
6851

6852
  @type lu: L{LogicalUnit}
6853
  @param lu: the logical unit for which we check
6854
  @type required: boolean
6855
  @param required: whether the validation should fail if the OS is not
6856
      found
6857
  @type nodenames: list
6858
  @param nodenames: the list of nodes on which we should check
6859
  @type osname: string
6860
  @param osname: the name of the hypervisor we should use
6861
  @type osparams: dict
6862
  @param osparams: the parameters which we need to check
6863
  @raise errors.OpPrereqError: if the parameters are not valid
6864

6865
  """
6866
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6867
                                   [constants.OS_VALIDATE_PARAMETERS],
6868
                                   osparams)
6869
  for node, nres in result.items():
6870
    # we don't check for offline cases since this should be run only
6871
    # against the master node and/or an instance's nodes
6872
    nres.Raise("OS Parameters validation failed on node %s" % node)
6873
    if not nres.payload:
6874
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6875
                 osname, node)
6876

    
6877

    
6878
class LUInstanceCreate(LogicalUnit):
6879
  """Create an instance.
6880

6881
  """
6882
  HPATH = "instance-add"
6883
  HTYPE = constants.HTYPE_INSTANCE
6884
  REQ_BGL = False
6885

    
6886
  def CheckArguments(self):
6887
    """Check arguments.
6888

6889
    """
6890
    # do not require name_check to ease forward/backward compatibility
6891
    # for tools
6892
    if self.op.no_install and self.op.start:
6893
      self.LogInfo("No-installation mode selected, disabling startup")
6894
      self.op.start = False
6895
    # validate/normalize the instance name
6896
    self.op.instance_name = \
6897
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
6898

    
6899
    if self.op.ip_check and not self.op.name_check:
6900
      # TODO: make the ip check more flexible and not depend on the name check
6901
      raise errors.OpPrereqError("Cannot do ip check without a name check",
6902
                                 errors.ECODE_INVAL)
6903

    
6904
    # check nics' parameter names
6905
    for nic in self.op.nics:
6906
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6907

    
6908
    # check disks. parameter names and consistent adopt/no-adopt strategy
6909
    has_adopt = has_no_adopt = False
6910
    for disk in self.op.disks:
6911
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6912
      if "adopt" in disk:
6913
        has_adopt = True
6914
      else:
6915
        has_no_adopt = True
6916
    if has_adopt and has_no_adopt:
6917
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6918
                                 errors.ECODE_INVAL)
6919
    if has_adopt:
6920
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6921
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6922
                                   " '%s' disk template" %
6923
                                   self.op.disk_template,
6924
                                   errors.ECODE_INVAL)
6925
      if self.op.iallocator is not None:
6926
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6927
                                   " iallocator script", errors.ECODE_INVAL)
6928
      if self.op.mode == constants.INSTANCE_IMPORT:
6929
        raise errors.OpPrereqError("Disk adoption not allowed for"
6930
                                   " instance import", errors.ECODE_INVAL)
6931

    
6932
    self.adopt_disks = has_adopt
6933

    
6934
    # instance name verification
6935
    if self.op.name_check:
6936
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
6937
      self.op.instance_name = self.hostname1.name
6938
      # used in CheckPrereq for ip ping check
6939
      self.check_ip = self.hostname1.ip
6940
    else:
6941
      self.check_ip = None
6942

    
6943
    # file storage checks
6944
    if (self.op.file_driver and
6945
        not self.op.file_driver in constants.FILE_DRIVER):
6946
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6947
                                 self.op.file_driver, errors.ECODE_INVAL)
6948

    
6949
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6950
      raise errors.OpPrereqError("File storage directory path not absolute",
6951
                                 errors.ECODE_INVAL)
6952

    
6953
    ### Node/iallocator related checks
6954
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
6955

    
6956
    if self.op.pnode is not None:
6957
      if self.op.disk_template in constants.DTS_NET_MIRROR:
6958
        if self.op.snode is None:
6959
          raise errors.OpPrereqError("The networked disk templates need"
6960
                                     " a mirror node", errors.ECODE_INVAL)
6961
      elif self.op.snode:
6962
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
6963
                        " template")
6964
        self.op.snode = None
6965

    
6966
    self._cds = _GetClusterDomainSecret()
6967

    
6968
    if self.op.mode == constants.INSTANCE_IMPORT:
6969
      # On import force_variant must be True, because if we forced it at
6970
      # initial install, our only chance when importing it back is that it
6971
      # works again!
6972
      self.op.force_variant = True
6973

    
6974
      if self.op.no_install:
6975
        self.LogInfo("No-installation mode has no effect during import")
6976

    
6977
    elif self.op.mode == constants.INSTANCE_CREATE:
6978
      if self.op.os_type is None:
6979
        raise errors.OpPrereqError("No guest OS specified",
6980
                                   errors.ECODE_INVAL)
6981
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
6982
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
6983
                                   " installation" % self.op.os_type,
6984
                                   errors.ECODE_STATE)
6985
      if self.op.disk_template is None:
6986
        raise errors.OpPrereqError("No disk template specified",
6987
                                   errors.ECODE_INVAL)
6988

    
6989
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6990
      # Check handshake to ensure both clusters have the same domain secret
6991
      src_handshake = self.op.source_handshake
6992
      if not src_handshake:
6993
        raise errors.OpPrereqError("Missing source handshake",
6994
                                   errors.ECODE_INVAL)
6995

    
6996
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6997
                                                           src_handshake)
6998
      if errmsg:
6999
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
7000
                                   errors.ECODE_INVAL)
7001

    
7002
      # Load and check source CA
7003
      self.source_x509_ca_pem = self.op.source_x509_ca
7004
      if not self.source_x509_ca_pem:
7005
        raise errors.OpPrereqError("Missing source X509 CA",
7006
                                   errors.ECODE_INVAL)
7007

    
7008
      try:
7009
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
7010
                                                    self._cds)
7011
      except OpenSSL.crypto.Error, err:
7012
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
7013
                                   (err, ), errors.ECODE_INVAL)
7014

    
7015
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
7016
      if errcode is not None:
7017
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
7018
                                   errors.ECODE_INVAL)
7019

    
7020
      self.source_x509_ca = cert
7021

    
7022
      src_instance_name = self.op.source_instance_name
7023
      if not src_instance_name:
7024
        raise errors.OpPrereqError("Missing source instance name",
7025
                                   errors.ECODE_INVAL)
7026

    
7027
      self.source_instance_name = \
7028
          netutils.GetHostname(name=src_instance_name).name
7029

    
7030
    else:
7031
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
7032
                                 self.op.mode, errors.ECODE_INVAL)
7033

    
7034
  def ExpandNames(self):
7035
    """ExpandNames for CreateInstance.
7036

7037
    Figure out the right locks for instance creation.
7038

7039
    """
7040
    self.needed_locks = {}
7041

    
7042
    instance_name = self.op.instance_name
7043
    # this is just a preventive check, but someone might still add this
7044
    # instance in the meantime, and creation will fail at lock-add time
7045
    if instance_name in self.cfg.GetInstanceList():
7046
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
7047
                                 instance_name, errors.ECODE_EXISTS)
7048

    
7049
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
7050

    
7051
    if self.op.iallocator:
7052
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7053
    else:
7054
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
7055
      nodelist = [self.op.pnode]
7056
      if self.op.snode is not None:
7057
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
7058
        nodelist.append(self.op.snode)
7059
      self.needed_locks[locking.LEVEL_NODE] = nodelist
7060

    
7061
    # in case of import lock the source node too
7062
    if self.op.mode == constants.INSTANCE_IMPORT:
7063
      src_node = self.op.src_node
7064
      src_path = self.op.src_path
7065

    
7066
      if src_path is None:
7067
        self.op.src_path = src_path = self.op.instance_name
7068

    
7069
      if src_node is None:
7070
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7071
        self.op.src_node = None
7072
        if os.path.isabs(src_path):
7073
          raise errors.OpPrereqError("Importing an instance from an absolute"
7074
                                     " path requires a source node option.",
7075
                                     errors.ECODE_INVAL)
7076
      else:
7077
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
7078
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
7079
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
7080
        if not os.path.isabs(src_path):
7081
          self.op.src_path = src_path = \
7082
            utils.PathJoin(constants.EXPORT_DIR, src_path)
7083

    
7084
  def _RunAllocator(self):
7085
    """Run the allocator based on input opcode.
7086

7087
    """
7088
    nics = [n.ToDict() for n in self.nics]
7089
    ial = IAllocator(self.cfg, self.rpc,
7090
                     mode=constants.IALLOCATOR_MODE_ALLOC,
7091
                     name=self.op.instance_name,
7092
                     disk_template=self.op.disk_template,
7093
                     tags=[],
7094
                     os=self.op.os_type,
7095
                     vcpus=self.be_full[constants.BE_VCPUS],
7096
                     mem_size=self.be_full[constants.BE_MEMORY],
7097
                     disks=self.disks,
7098
                     nics=nics,
7099
                     hypervisor=self.op.hypervisor,
7100
                     )
7101

    
7102
    ial.Run(self.op.iallocator)
7103

    
7104
    if not ial.success:
7105
      raise errors.OpPrereqError("Can't compute nodes using"
7106
                                 " iallocator '%s': %s" %
7107
                                 (self.op.iallocator, ial.info),
7108
                                 errors.ECODE_NORES)
7109
    if len(ial.result) != ial.required_nodes:
7110
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7111
                                 " of nodes (%s), required %s" %
7112
                                 (self.op.iallocator, len(ial.result),
7113
                                  ial.required_nodes), errors.ECODE_FAULT)
7114
    self.op.pnode = ial.result[0]
7115
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
7116
                 self.op.instance_name, self.op.iallocator,
7117
                 utils.CommaJoin(ial.result))
7118
    if ial.required_nodes == 2:
7119
      self.op.snode = ial.result[1]
7120

    
7121
  def BuildHooksEnv(self):
7122
    """Build hooks env.
7123

7124
    This runs on master, primary and secondary nodes of the instance.
7125

7126
    """
7127
    env = {
7128
      "ADD_MODE": self.op.mode,
7129
      }
7130
    if self.op.mode == constants.INSTANCE_IMPORT:
7131
      env["SRC_NODE"] = self.op.src_node
7132
      env["SRC_PATH"] = self.op.src_path
7133
      env["SRC_IMAGES"] = self.src_images
7134

    
7135
    env.update(_BuildInstanceHookEnv(
7136
      name=self.op.instance_name,
7137
      primary_node=self.op.pnode,
7138
      secondary_nodes=self.secondaries,
7139
      status=self.op.start,
7140
      os_type=self.op.os_type,
7141
      memory=self.be_full[constants.BE_MEMORY],
7142
      vcpus=self.be_full[constants.BE_VCPUS],
7143
      nics=_NICListToTuple(self, self.nics),
7144
      disk_template=self.op.disk_template,
7145
      disks=[(d["size"], d["mode"]) for d in self.disks],
7146
      bep=self.be_full,
7147
      hvp=self.hv_full,
7148
      hypervisor_name=self.op.hypervisor,
7149
    ))
7150

    
7151
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
7152
          self.secondaries)
7153
    return env, nl, nl
7154

    
7155
  def _ReadExportInfo(self):
7156
    """Reads the export information from disk.
7157

7158
    It will override the opcode source node and path with the actual
7159
    information, if these two were not specified before.
7160

7161
    @return: the export information
7162

7163
    """
7164
    assert self.op.mode == constants.INSTANCE_IMPORT
7165

    
7166
    src_node = self.op.src_node
7167
    src_path = self.op.src_path
7168

    
7169
    if src_node is None:
7170
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
7171
      exp_list = self.rpc.call_export_list(locked_nodes)
7172
      found = False
7173
      for node in exp_list:
7174
        if exp_list[node].fail_msg:
7175
          continue
7176
        if src_path in exp_list[node].payload:
7177
          found = True
7178
          self.op.src_node = src_node = node
7179
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
7180
                                                       src_path)
7181
          break
7182
      if not found:
7183
        raise errors.OpPrereqError("No export found for relative path %s" %
7184
                                    src_path, errors.ECODE_INVAL)
7185

    
7186
    _CheckNodeOnline(self, src_node)
7187
    result = self.rpc.call_export_info(src_node, src_path)
7188
    result.Raise("No export or invalid export found in dir %s" % src_path)
7189

    
7190
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
7191
    if not export_info.has_section(constants.INISECT_EXP):
7192
      raise errors.ProgrammerError("Corrupted export config",
7193
                                   errors.ECODE_ENVIRON)
7194

    
7195
    ei_version = export_info.get(constants.INISECT_EXP, "version")
7196
    if (int(ei_version) != constants.EXPORT_VERSION):
7197
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
7198
                                 (ei_version, constants.EXPORT_VERSION),
7199
                                 errors.ECODE_ENVIRON)
7200
    return export_info
7201

    
7202
  def _ReadExportParams(self, einfo):
7203
    """Use export parameters as defaults.
7204

7205
    In case the opcode doesn't specify (as in override) some instance
7206
    parameters, then try to use them from the export information, if
7207
    that declares them.
7208

7209
    """
7210
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
7211

    
7212
    if self.op.disk_template is None:
7213
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
7214
        self.op.disk_template = einfo.get(constants.INISECT_INS,
7215
                                          "disk_template")
7216
      else:
7217
        raise errors.OpPrereqError("No disk template specified and the export"
7218
                                   " is missing the disk_template information",
7219
                                   errors.ECODE_INVAL)
7220

    
7221
    if not self.op.disks:
7222
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
7223
        disks = []
7224
        # TODO: import the disk iv_name too
7225
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
7226
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
7227
          disks.append({"size": disk_sz})
7228
        self.op.disks = disks
7229
      else:
7230
        raise errors.OpPrereqError("No disk info specified and the export"
7231
                                   " is missing the disk information",
7232
                                   errors.ECODE_INVAL)
7233

    
7234
    if (not self.op.nics and
7235
        einfo.has_option(constants.INISECT_INS, "nic_count")):
7236
      nics = []
7237
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
7238
        ndict = {}
7239
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
7240
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
7241
          ndict[name] = v
7242
        nics.append(ndict)
7243
      self.op.nics = nics
7244

    
7245
    if (self.op.hypervisor is None and
7246
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
7247
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
7248
    if einfo.has_section(constants.INISECT_HYP):
7249
      # use the export parameters but do not override the ones
7250
      # specified by the user
7251
      for name, value in einfo.items(constants.INISECT_HYP):
7252
        if name not in self.op.hvparams:
7253
          self.op.hvparams[name] = value
7254

    
7255
    if einfo.has_section(constants.INISECT_BEP):
7256
      # use the parameters, without overriding
7257
      for name, value in einfo.items(constants.INISECT_BEP):
7258
        if name not in self.op.beparams:
7259
          self.op.beparams[name] = value
7260
    else:
7261
      # try to read the parameters old style, from the main section
7262
      for name in constants.BES_PARAMETERS:
7263
        if (name not in self.op.beparams and
7264
            einfo.has_option(constants.INISECT_INS, name)):
7265
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
7266

    
7267
    if einfo.has_section(constants.INISECT_OSP):
7268
      # use the parameters, without overriding
7269
      for name, value in einfo.items(constants.INISECT_OSP):
7270
        if name not in self.op.osparams:
7271
          self.op.osparams[name] = value
7272

    
7273
  def _RevertToDefaults(self, cluster):
7274
    """Revert the instance parameters to the default values.
7275

7276
    """
7277
    # hvparams
7278
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
7279
    for name in self.op.hvparams.keys():
7280
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
7281
        del self.op.hvparams[name]
7282
    # beparams
7283
    be_defs = cluster.SimpleFillBE({})
7284
    for name in self.op.beparams.keys():
7285
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
7286
        del self.op.beparams[name]
7287
    # nic params
7288
    nic_defs = cluster.SimpleFillNIC({})
7289
    for nic in self.op.nics:
7290
      for name in constants.NICS_PARAMETERS:
7291
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
7292
          del nic[name]
7293
    # osparams
7294
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
7295
    for name in self.op.osparams.keys():
7296
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
7297
        del self.op.osparams[name]
7298

    
7299
  def CheckPrereq(self):
7300
    """Check prerequisites.
7301

7302
    """
7303
    if self.op.mode == constants.INSTANCE_IMPORT:
7304
      export_info = self._ReadExportInfo()
7305
      self._ReadExportParams(export_info)
7306

    
7307
    if (not self.cfg.GetVGName() and
7308
        self.op.disk_template not in constants.DTS_NOT_LVM):
7309
      raise errors.OpPrereqError("Cluster does not support lvm-based"
7310
                                 " instances", errors.ECODE_STATE)
7311

    
7312
    if self.op.hypervisor is None:
7313
      self.op.hypervisor = self.cfg.GetHypervisorType()
7314

    
7315
    cluster = self.cfg.GetClusterInfo()
7316
    enabled_hvs = cluster.enabled_hypervisors
7317
    if self.op.hypervisor not in enabled_hvs:
7318
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
7319
                                 " cluster (%s)" % (self.op.hypervisor,
7320
                                  ",".join(enabled_hvs)),
7321
                                 errors.ECODE_STATE)
7322

    
7323
    # check hypervisor parameter syntax (locally)
7324
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
7325
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
7326
                                      self.op.hvparams)
7327
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
7328
    hv_type.CheckParameterSyntax(filled_hvp)
7329
    self.hv_full = filled_hvp
7330
    # check that we don't specify global parameters on an instance
7331
    _CheckGlobalHvParams(self.op.hvparams)
7332

    
7333
    # fill and remember the beparams dict
7334
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
7335
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
7336

    
7337
    # build os parameters
7338
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
7339

    
7340
    # now that hvp/bep are in final format, let's reset to defaults,
7341
    # if told to do so
7342
    if self.op.identify_defaults:
7343
      self._RevertToDefaults(cluster)
7344

    
7345
    # NIC buildup
7346
    self.nics = []
7347
    for idx, nic in enumerate(self.op.nics):
7348
      nic_mode_req = nic.get("mode", None)
7349
      nic_mode = nic_mode_req
7350
      if nic_mode is None:
7351
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
7352

    
7353
      # in routed mode, for the first nic, the default ip is 'auto'
7354
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
7355
        default_ip_mode = constants.VALUE_AUTO
7356
      else:
7357
        default_ip_mode = constants.VALUE_NONE
7358

    
7359
      # ip validity checks
7360
      ip = nic.get("ip", default_ip_mode)
7361
      if ip is None or ip.lower() == constants.VALUE_NONE:
7362
        nic_ip = None
7363
      elif ip.lower() == constants.VALUE_AUTO:
7364
        if not self.op.name_check:
7365
          raise errors.OpPrereqError("IP address set to auto but name checks"
7366
                                     " have been skipped",
7367
                                     errors.ECODE_INVAL)
7368
        nic_ip = self.hostname1.ip
7369
      else:
7370
        if not netutils.IPAddress.IsValid(ip):
7371
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
7372
                                     errors.ECODE_INVAL)
7373
        nic_ip = ip
7374

    
7375
      # TODO: check the ip address for uniqueness
7376
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7377
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7378
                                   errors.ECODE_INVAL)
7379

    
7380
      # MAC address verification
7381
      mac = nic.get("mac", constants.VALUE_AUTO)
7382
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7383
        mac = utils.NormalizeAndValidateMac(mac)
7384

    
7385
        try:
7386
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7387
        except errors.ReservationError:
7388
          raise errors.OpPrereqError("MAC address %s already in use"
7389
                                     " in cluster" % mac,
7390
                                     errors.ECODE_NOTUNIQUE)
7391

    
7392
      # bridge verification
7393
      bridge = nic.get("bridge", None)
7394
      link = nic.get("link", None)
7395
      if bridge and link:
7396
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7397
                                   " at the same time", errors.ECODE_INVAL)
7398
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7399
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7400
                                   errors.ECODE_INVAL)
7401
      elif bridge:
7402
        link = bridge
7403

    
7404
      nicparams = {}
7405
      if nic_mode_req:
7406
        nicparams[constants.NIC_MODE] = nic_mode_req
7407
      if link:
7408
        nicparams[constants.NIC_LINK] = link
7409

    
7410
      check_params = cluster.SimpleFillNIC(nicparams)
7411
      objects.NIC.CheckParameterSyntax(check_params)
7412
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7413

    
7414
    # disk checks/pre-build
7415
    self.disks = []
7416
    for disk in self.op.disks:
7417
      mode = disk.get("mode", constants.DISK_RDWR)
7418
      if mode not in constants.DISK_ACCESS_SET:
7419
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7420
                                   mode, errors.ECODE_INVAL)
7421
      size = disk.get("size", None)
7422
      if size is None:
7423
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7424
      try:
7425
        size = int(size)
7426
      except (TypeError, ValueError):
7427
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7428
                                   errors.ECODE_INVAL)
7429
      vg = disk.get("vg", self.cfg.GetVGName())
7430
      new_disk = {"size": size, "mode": mode, "vg": vg}
7431
      if "adopt" in disk:
7432
        new_disk["adopt"] = disk["adopt"]
7433
      self.disks.append(new_disk)
7434

    
7435
    if self.op.mode == constants.INSTANCE_IMPORT:
7436

    
7437
      # Check that the new instance doesn't have less disks than the export
7438
      instance_disks = len(self.disks)
7439
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7440
      if instance_disks < export_disks:
7441
        raise errors.OpPrereqError("Not enough disks to import."
7442
                                   " (instance: %d, export: %d)" %
7443
                                   (instance_disks, export_disks),
7444
                                   errors.ECODE_INVAL)
7445

    
7446
      disk_images = []
7447
      for idx in range(export_disks):
7448
        option = 'disk%d_dump' % idx
7449
        if export_info.has_option(constants.INISECT_INS, option):
7450
          # FIXME: are the old os-es, disk sizes, etc. useful?
7451
          export_name = export_info.get(constants.INISECT_INS, option)
7452
          image = utils.PathJoin(self.op.src_path, export_name)
7453
          disk_images.append(image)
7454
        else:
7455
          disk_images.append(False)
7456

    
7457
      self.src_images = disk_images
7458

    
7459
      old_name = export_info.get(constants.INISECT_INS, 'name')
7460
      try:
7461
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7462
      except (TypeError, ValueError), err:
7463
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7464
                                   " an integer: %s" % str(err),
7465
                                   errors.ECODE_STATE)
7466
      if self.op.instance_name == old_name:
7467
        for idx, nic in enumerate(self.nics):
7468
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7469
            nic_mac_ini = 'nic%d_mac' % idx
7470
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7471

    
7472
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7473

    
7474
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7475
    if self.op.ip_check:
7476
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7477
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7478
                                   (self.check_ip, self.op.instance_name),
7479
                                   errors.ECODE_NOTUNIQUE)
7480

    
7481
    #### mac address generation
7482
    # By generating here the mac address both the allocator and the hooks get
7483
    # the real final mac address rather than the 'auto' or 'generate' value.
7484
    # There is a race condition between the generation and the instance object
7485
    # creation, which means that we know the mac is valid now, but we're not
7486
    # sure it will be when we actually add the instance. If things go bad
7487
    # adding the instance will abort because of a duplicate mac, and the
7488
    # creation job will fail.
7489
    for nic in self.nics:
7490
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7491
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7492

    
7493
    #### allocator run
7494

    
7495
    if self.op.iallocator is not None:
7496
      self._RunAllocator()
7497

    
7498
    #### node related checks
7499

    
7500
    # check primary node
7501
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7502
    assert self.pnode is not None, \
7503
      "Cannot retrieve locked node %s" % self.op.pnode
7504
    if pnode.offline:
7505
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7506
                                 pnode.name, errors.ECODE_STATE)
7507
    if pnode.drained:
7508
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7509
                                 pnode.name, errors.ECODE_STATE)
7510
    if not pnode.vm_capable:
7511
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
7512
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
7513

    
7514
    self.secondaries = []
7515

    
7516
    # mirror node verification
7517
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7518
      if self.op.snode == pnode.name:
7519
        raise errors.OpPrereqError("The secondary node cannot be the"
7520
                                   " primary node.", errors.ECODE_INVAL)
7521
      _CheckNodeOnline(self, self.op.snode)
7522
      _CheckNodeNotDrained(self, self.op.snode)
7523
      _CheckNodeVmCapable(self, self.op.snode)
7524
      self.secondaries.append(self.op.snode)
7525

    
7526
    nodenames = [pnode.name] + self.secondaries
7527

    
7528
    if not self.adopt_disks:
7529
      # Check lv size requirements, if not adopting
7530
      req_sizes = _ComputeDiskSizePerVG(self.op.disk_template, self.disks)
7531
      _CheckNodesFreeDiskPerVG(self, nodenames, req_sizes)
7532

    
7533
    else: # instead, we must check the adoption data
7534
      all_lvs = set([i["vg"] + "/" + i["adopt"] for i in self.disks])
7535
      if len(all_lvs) != len(self.disks):
7536
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7537
                                   errors.ECODE_INVAL)
7538
      for lv_name in all_lvs:
7539
        try:
7540
          # FIXME: lv_name here is "vg/lv" need to ensure that other calls
7541
          # to ReserveLV uses the same syntax
7542
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7543
        except errors.ReservationError:
7544
          raise errors.OpPrereqError("LV named %s used by another instance" %
7545
                                     lv_name, errors.ECODE_NOTUNIQUE)
7546

    
7547
      vg_names = self.rpc.call_vg_list([pnode.name])[pnode.name]
7548
      vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
7549

    
7550
      node_lvs = self.rpc.call_lv_list([pnode.name],
7551
                                       vg_names.payload.keys())[pnode.name]
7552
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7553
      node_lvs = node_lvs.payload
7554

    
7555
      delta = all_lvs.difference(node_lvs.keys())
7556
      if delta:
7557
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7558
                                   utils.CommaJoin(delta),
7559
                                   errors.ECODE_INVAL)
7560
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7561
      if online_lvs:
7562
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7563
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7564
                                   errors.ECODE_STATE)
7565
      # update the size of disk based on what is found
7566
      for dsk in self.disks:
7567
        dsk["size"] = int(float(node_lvs[dsk["vg"] + "/" + dsk["adopt"]][0]))
7568

    
7569
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7570

    
7571
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7572
    # check OS parameters (remotely)
7573
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7574

    
7575
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7576

    
7577
    # memory check on primary node
7578
    if self.op.start:
7579
      _CheckNodeFreeMemory(self, self.pnode.name,
7580
                           "creating instance %s" % self.op.instance_name,
7581
                           self.be_full[constants.BE_MEMORY],
7582
                           self.op.hypervisor)
7583

    
7584
    self.dry_run_result = list(nodenames)
7585

    
7586
  def Exec(self, feedback_fn):
7587
    """Create and add the instance to the cluster.
7588

7589
    """
7590
    instance = self.op.instance_name
7591
    pnode_name = self.pnode.name
7592

    
7593
    ht_kind = self.op.hypervisor
7594
    if ht_kind in constants.HTS_REQ_PORT:
7595
      network_port = self.cfg.AllocatePort()
7596
    else:
7597
      network_port = None
7598

    
7599
    if constants.ENABLE_FILE_STORAGE:
7600
      # this is needed because os.path.join does not accept None arguments
7601
      if self.op.file_storage_dir is None:
7602
        string_file_storage_dir = ""
7603
      else:
7604
        string_file_storage_dir = self.op.file_storage_dir
7605

    
7606
      # build the full file storage dir path
7607
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7608
                                        string_file_storage_dir, instance)
7609
    else:
7610
      file_storage_dir = ""
7611

    
7612
    disks = _GenerateDiskTemplate(self,
7613
                                  self.op.disk_template,
7614
                                  instance, pnode_name,
7615
                                  self.secondaries,
7616
                                  self.disks,
7617
                                  file_storage_dir,
7618
                                  self.op.file_driver,
7619
                                  0,
7620
                                  feedback_fn)
7621

    
7622
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7623
                            primary_node=pnode_name,
7624
                            nics=self.nics, disks=disks,
7625
                            disk_template=self.op.disk_template,
7626
                            admin_up=False,
7627
                            network_port=network_port,
7628
                            beparams=self.op.beparams,
7629
                            hvparams=self.op.hvparams,
7630
                            hypervisor=self.op.hypervisor,
7631
                            osparams=self.op.osparams,
7632
                            )
7633

    
7634
    if self.adopt_disks:
7635
      # rename LVs to the newly-generated names; we need to construct
7636
      # 'fake' LV disks with the old data, plus the new unique_id
7637
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7638
      rename_to = []
7639
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7640
        rename_to.append(t_dsk.logical_id)
7641
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7642
        self.cfg.SetDiskID(t_dsk, pnode_name)
7643
      result = self.rpc.call_blockdev_rename(pnode_name,
7644
                                             zip(tmp_disks, rename_to))
7645
      result.Raise("Failed to rename adoped LVs")
7646
    else:
7647
      feedback_fn("* creating instance disks...")
7648
      try:
7649
        _CreateDisks(self, iobj)
7650
      except errors.OpExecError:
7651
        self.LogWarning("Device creation failed, reverting...")
7652
        try:
7653
          _RemoveDisks(self, iobj)
7654
        finally:
7655
          self.cfg.ReleaseDRBDMinors(instance)
7656
          raise
7657

    
7658
      if self.cfg.GetClusterInfo().prealloc_wipe_disks:
7659
        feedback_fn("* wiping instance disks...")
7660
        try:
7661
          _WipeDisks(self, iobj)
7662
        except errors.OpExecError:
7663
          self.LogWarning("Device wiping failed, reverting...")
7664
          try:
7665
            _RemoveDisks(self, iobj)
7666
          finally:
7667
            self.cfg.ReleaseDRBDMinors(instance)
7668
            raise
7669

    
7670
    feedback_fn("adding instance %s to cluster config" % instance)
7671

    
7672
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7673

    
7674
    # Declare that we don't want to remove the instance lock anymore, as we've
7675
    # added the instance to the config
7676
    del self.remove_locks[locking.LEVEL_INSTANCE]
7677
    # Unlock all the nodes
7678
    if self.op.mode == constants.INSTANCE_IMPORT:
7679
      nodes_keep = [self.op.src_node]
7680
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7681
                       if node != self.op.src_node]
7682
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7683
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7684
    else:
7685
      self.context.glm.release(locking.LEVEL_NODE)
7686
      del self.acquired_locks[locking.LEVEL_NODE]
7687

    
7688
    if self.op.wait_for_sync:
7689
      disk_abort = not _WaitForSync(self, iobj)
7690
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7691
      # make sure the disks are not degraded (still sync-ing is ok)
7692
      time.sleep(15)
7693
      feedback_fn("* checking mirrors status")
7694
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7695
    else:
7696
      disk_abort = False
7697

    
7698
    if disk_abort:
7699
      _RemoveDisks(self, iobj)
7700
      self.cfg.RemoveInstance(iobj.name)
7701
      # Make sure the instance lock gets removed
7702
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7703
      raise errors.OpExecError("There are some degraded disks for"
7704
                               " this instance")
7705

    
7706
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7707
      if self.op.mode == constants.INSTANCE_CREATE:
7708
        if not self.op.no_install:
7709
          feedback_fn("* running the instance OS create scripts...")
7710
          # FIXME: pass debug option from opcode to backend
7711
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7712
                                                 self.op.debug_level)
7713
          result.Raise("Could not add os for instance %s"
7714
                       " on node %s" % (instance, pnode_name))
7715

    
7716
      elif self.op.mode == constants.INSTANCE_IMPORT:
7717
        feedback_fn("* running the instance OS import scripts...")
7718

    
7719
        transfers = []
7720

    
7721
        for idx, image in enumerate(self.src_images):
7722
          if not image:
7723
            continue
7724

    
7725
          # FIXME: pass debug option from opcode to backend
7726
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7727
                                             constants.IEIO_FILE, (image, ),
7728
                                             constants.IEIO_SCRIPT,
7729
                                             (iobj.disks[idx], idx),
7730
                                             None)
7731
          transfers.append(dt)
7732

    
7733
        import_result = \
7734
          masterd.instance.TransferInstanceData(self, feedback_fn,
7735
                                                self.op.src_node, pnode_name,
7736
                                                self.pnode.secondary_ip,
7737
                                                iobj, transfers)
7738
        if not compat.all(import_result):
7739
          self.LogWarning("Some disks for instance %s on node %s were not"
7740
                          " imported successfully" % (instance, pnode_name))
7741

    
7742
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7743
        feedback_fn("* preparing remote import...")
7744
        # The source cluster will stop the instance before attempting to make a
7745
        # connection. In some cases stopping an instance can take a long time,
7746
        # hence the shutdown timeout is added to the connection timeout.
7747
        connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
7748
                           self.op.source_shutdown_timeout)
7749
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7750

    
7751
        assert iobj.primary_node == self.pnode.name
7752
        disk_results = \
7753
          masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
7754
                                        self.source_x509_ca,
7755
                                        self._cds, timeouts)
7756
        if not compat.all(disk_results):
7757
          # TODO: Should the instance still be started, even if some disks
7758
          # failed to import (valid for local imports, too)?
7759
          self.LogWarning("Some disks for instance %s on node %s were not"
7760
                          " imported successfully" % (instance, pnode_name))
7761

    
7762
        # Run rename script on newly imported instance
7763
        assert iobj.name == instance
7764
        feedback_fn("Running rename script for %s" % instance)
7765
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7766
                                                   self.source_instance_name,
7767
                                                   self.op.debug_level)
7768
        if result.fail_msg:
7769
          self.LogWarning("Failed to run rename script for %s on node"
7770
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7771

    
7772
      else:
7773
        # also checked in the prereq part
7774
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7775
                                     % self.op.mode)
7776

    
7777
    if self.op.start:
7778
      iobj.admin_up = True
7779
      self.cfg.Update(iobj, feedback_fn)
7780
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7781
      feedback_fn("* starting instance...")
7782
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7783
      result.Raise("Could not start instance")
7784

    
7785
    return list(iobj.all_nodes)
7786

    
7787

    
7788
class LUInstanceConsole(NoHooksLU):
7789
  """Connect to an instance's console.
7790

7791
  This is somewhat special in that it returns the command line that
7792
  you need to run on the master node in order to connect to the
7793
  console.
7794

7795
  """
7796
  REQ_BGL = False
7797

    
7798
  def ExpandNames(self):
7799
    self._ExpandAndLockInstance()
7800

    
7801
  def CheckPrereq(self):
7802
    """Check prerequisites.
7803

7804
    This checks that the instance is in the cluster.
7805

7806
    """
7807
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7808
    assert self.instance is not None, \
7809
      "Cannot retrieve locked instance %s" % self.op.instance_name
7810
    _CheckNodeOnline(self, self.instance.primary_node)
7811

    
7812
  def Exec(self, feedback_fn):
7813
    """Connect to the console of an instance
7814

7815
    """
7816
    instance = self.instance
7817
    node = instance.primary_node
7818

    
7819
    node_insts = self.rpc.call_instance_list([node],
7820
                                             [instance.hypervisor])[node]
7821
    node_insts.Raise("Can't get node information from %s" % node)
7822

    
7823
    if instance.name not in node_insts.payload:
7824
      if instance.admin_up:
7825
        state = "ERROR_down"
7826
      else:
7827
        state = "ADMIN_down"
7828
      raise errors.OpExecError("Instance %s is not running (state %s)" %
7829
                               (instance.name, state))
7830

    
7831
    logging.debug("Connecting to console of %s on %s", instance.name, node)
7832

    
7833
    return _GetInstanceConsole(self.cfg.GetClusterInfo(), instance)
7834

    
7835

    
7836
def _GetInstanceConsole(cluster, instance):
7837
  """Returns console information for an instance.
7838

7839
  @type cluster: L{objects.Cluster}
7840
  @type instance: L{objects.Instance}
7841
  @rtype: dict
7842

7843
  """
7844
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
7845
  # beparams and hvparams are passed separately, to avoid editing the
7846
  # instance and then saving the defaults in the instance itself.
7847
  hvparams = cluster.FillHV(instance)
7848
  beparams = cluster.FillBE(instance)
7849
  console = hyper.GetInstanceConsole(instance, hvparams, beparams)
7850

    
7851
  assert console.instance == instance.name
7852
  assert console.Validate()
7853

    
7854
  return console.ToDict()
7855

    
7856

    
7857
class LUInstanceReplaceDisks(LogicalUnit):
7858
  """Replace the disks of an instance.
7859

7860
  """
7861
  HPATH = "mirrors-replace"
7862
  HTYPE = constants.HTYPE_INSTANCE
7863
  REQ_BGL = False
7864

    
7865
  def CheckArguments(self):
7866
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7867
                                  self.op.iallocator)
7868

    
7869
  def ExpandNames(self):
7870
    self._ExpandAndLockInstance()
7871

    
7872
    if self.op.iallocator is not None:
7873
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7874

    
7875
    elif self.op.remote_node is not None:
7876
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7877
      self.op.remote_node = remote_node
7878

    
7879
      # Warning: do not remove the locking of the new secondary here
7880
      # unless DRBD8.AddChildren is changed to work in parallel;
7881
      # currently it doesn't since parallel invocations of
7882
      # FindUnusedMinor will conflict
7883
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7884
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7885

    
7886
    else:
7887
      self.needed_locks[locking.LEVEL_NODE] = []
7888
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7889

    
7890
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7891
                                   self.op.iallocator, self.op.remote_node,
7892
                                   self.op.disks, False, self.op.early_release)
7893

    
7894
    self.tasklets = [self.replacer]
7895

    
7896
  def DeclareLocks(self, level):
7897
    # If we're not already locking all nodes in the set we have to declare the
7898
    # instance's primary/secondary nodes.
7899
    if (level == locking.LEVEL_NODE and
7900
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7901
      self._LockInstancesNodes()
7902

    
7903
  def BuildHooksEnv(self):
7904
    """Build hooks env.
7905

7906
    This runs on the master, the primary and all the secondaries.
7907

7908
    """
7909
    instance = self.replacer.instance
7910
    env = {
7911
      "MODE": self.op.mode,
7912
      "NEW_SECONDARY": self.op.remote_node,
7913
      "OLD_SECONDARY": instance.secondary_nodes[0],
7914
      }
7915
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7916
    nl = [
7917
      self.cfg.GetMasterNode(),
7918
      instance.primary_node,
7919
      ]
7920
    if self.op.remote_node is not None:
7921
      nl.append(self.op.remote_node)
7922
    return env, nl, nl
7923

    
7924

    
7925
class TLReplaceDisks(Tasklet):
7926
  """Replaces disks for an instance.
7927

7928
  Note: Locking is not within the scope of this class.
7929

7930
  """
7931
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7932
               disks, delay_iallocator, early_release):
7933
    """Initializes this class.
7934

7935
    """
7936
    Tasklet.__init__(self, lu)
7937

    
7938
    # Parameters
7939
    self.instance_name = instance_name
7940
    self.mode = mode
7941
    self.iallocator_name = iallocator_name
7942
    self.remote_node = remote_node
7943
    self.disks = disks
7944
    self.delay_iallocator = delay_iallocator
7945
    self.early_release = early_release
7946

    
7947
    # Runtime data
7948
    self.instance = None
7949
    self.new_node = None
7950
    self.target_node = None
7951
    self.other_node = None
7952
    self.remote_node_info = None
7953
    self.node_secondary_ip = None
7954

    
7955
  @staticmethod
7956
  def CheckArguments(mode, remote_node, iallocator):
7957
    """Helper function for users of this class.
7958

7959
    """
7960
    # check for valid parameter combination
7961
    if mode == constants.REPLACE_DISK_CHG:
7962
      if remote_node is None and iallocator is None:
7963
        raise errors.OpPrereqError("When changing the secondary either an"
7964
                                   " iallocator script must be used or the"
7965
                                   " new node given", errors.ECODE_INVAL)
7966

    
7967
      if remote_node is not None and iallocator is not None:
7968
        raise errors.OpPrereqError("Give either the iallocator or the new"
7969
                                   " secondary, not both", errors.ECODE_INVAL)
7970

    
7971
    elif remote_node is not None or iallocator is not None:
7972
      # Not replacing the secondary
7973
      raise errors.OpPrereqError("The iallocator and new node options can"
7974
                                 " only be used when changing the"
7975
                                 " secondary node", errors.ECODE_INVAL)
7976

    
7977
  @staticmethod
7978
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7979
    """Compute a new secondary node using an IAllocator.
7980

7981
    """
7982
    ial = IAllocator(lu.cfg, lu.rpc,
7983
                     mode=constants.IALLOCATOR_MODE_RELOC,
7984
                     name=instance_name,
7985
                     relocate_from=relocate_from)
7986

    
7987
    ial.Run(iallocator_name)
7988

    
7989
    if not ial.success:
7990
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7991
                                 " %s" % (iallocator_name, ial.info),
7992
                                 errors.ECODE_NORES)
7993

    
7994
    if len(ial.result) != ial.required_nodes:
7995
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7996
                                 " of nodes (%s), required %s" %
7997
                                 (iallocator_name,
7998
                                  len(ial.result), ial.required_nodes),
7999
                                 errors.ECODE_FAULT)
8000

    
8001
    remote_node_name = ial.result[0]
8002

    
8003
    lu.LogInfo("Selected new secondary for instance '%s': %s",
8004
               instance_name, remote_node_name)
8005

    
8006
    return remote_node_name
8007

    
8008
  def _FindFaultyDisks(self, node_name):
8009
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
8010
                                    node_name, True)
8011

    
8012
  def CheckPrereq(self):
8013
    """Check prerequisites.
8014

8015
    This checks that the instance is in the cluster.
8016

8017
    """
8018
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
8019
    assert instance is not None, \
8020
      "Cannot retrieve locked instance %s" % self.instance_name
8021

    
8022
    if instance.disk_template != constants.DT_DRBD8:
8023
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
8024
                                 " instances", errors.ECODE_INVAL)
8025

    
8026
    if len(instance.secondary_nodes) != 1:
8027
      raise errors.OpPrereqError("The instance has a strange layout,"
8028
                                 " expected one secondary but found %d" %
8029
                                 len(instance.secondary_nodes),
8030
                                 errors.ECODE_FAULT)
8031

    
8032
    if not self.delay_iallocator:
8033
      self._CheckPrereq2()
8034

    
8035
  def _CheckPrereq2(self):
8036
    """Check prerequisites, second part.
8037

8038
    This function should always be part of CheckPrereq. It was separated and is
8039
    now called from Exec because during node evacuation iallocator was only
8040
    called with an unmodified cluster model, not taking planned changes into
8041
    account.
8042

8043
    """
8044
    instance = self.instance
8045
    secondary_node = instance.secondary_nodes[0]
8046

    
8047
    if self.iallocator_name is None:
8048
      remote_node = self.remote_node
8049
    else:
8050
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
8051
                                       instance.name, instance.secondary_nodes)
8052

    
8053
    if remote_node is not None:
8054
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
8055
      assert self.remote_node_info is not None, \
8056
        "Cannot retrieve locked node %s" % remote_node
8057
    else:
8058
      self.remote_node_info = None
8059

    
8060
    if remote_node == self.instance.primary_node:
8061
      raise errors.OpPrereqError("The specified node is the primary node of"
8062
                                 " the instance.", errors.ECODE_INVAL)
8063

    
8064
    if remote_node == secondary_node:
8065
      raise errors.OpPrereqError("The specified node is already the"
8066
                                 " secondary node of the instance.",
8067
                                 errors.ECODE_INVAL)
8068

    
8069
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
8070
                                    constants.REPLACE_DISK_CHG):
8071
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
8072
                                 errors.ECODE_INVAL)
8073

    
8074
    if self.mode == constants.REPLACE_DISK_AUTO:
8075
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
8076
      faulty_secondary = self._FindFaultyDisks(secondary_node)
8077

    
8078
      if faulty_primary and faulty_secondary:
8079
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
8080
                                   " one node and can not be repaired"
8081
                                   " automatically" % self.instance_name,
8082
                                   errors.ECODE_STATE)
8083

    
8084
      if faulty_primary:
8085
        self.disks = faulty_primary
8086
        self.target_node = instance.primary_node
8087
        self.other_node = secondary_node
8088
        check_nodes = [self.target_node, self.other_node]
8089
      elif faulty_secondary:
8090
        self.disks = faulty_secondary
8091
        self.target_node = secondary_node
8092
        self.other_node = instance.primary_node
8093
        check_nodes = [self.target_node, self.other_node]
8094
      else:
8095
        self.disks = []
8096
        check_nodes = []
8097

    
8098
    else:
8099
      # Non-automatic modes
8100
      if self.mode == constants.REPLACE_DISK_PRI:
8101
        self.target_node = instance.primary_node
8102
        self.other_node = secondary_node
8103
        check_nodes = [self.target_node, self.other_node]
8104

    
8105
      elif self.mode == constants.REPLACE_DISK_SEC:
8106
        self.target_node = secondary_node
8107
        self.other_node = instance.primary_node
8108
        check_nodes = [self.target_node, self.other_node]
8109

    
8110
      elif self.mode == constants.REPLACE_DISK_CHG:
8111
        self.new_node = remote_node
8112
        self.other_node = instance.primary_node
8113
        self.target_node = secondary_node
8114
        check_nodes = [self.new_node, self.other_node]
8115

    
8116
        _CheckNodeNotDrained(self.lu, remote_node)
8117
        _CheckNodeVmCapable(self.lu, remote_node)
8118

    
8119
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
8120
        assert old_node_info is not None
8121
        if old_node_info.offline and not self.early_release:
8122
          # doesn't make sense to delay the release
8123
          self.early_release = True
8124
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
8125
                          " early-release mode", secondary_node)
8126

    
8127
      else:
8128
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
8129
                                     self.mode)
8130

    
8131
      # If not specified all disks should be replaced
8132
      if not self.disks:
8133
        self.disks = range(len(self.instance.disks))
8134

    
8135
    for node in check_nodes:
8136
      _CheckNodeOnline(self.lu, node)
8137

    
8138
    # Check whether disks are valid
8139
    for disk_idx in self.disks:
8140
      instance.FindDisk(disk_idx)
8141

    
8142
    # Get secondary node IP addresses
8143
    node_2nd_ip = {}
8144

    
8145
    for node_name in [self.target_node, self.other_node, self.new_node]:
8146
      if node_name is not None:
8147
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
8148

    
8149
    self.node_secondary_ip = node_2nd_ip
8150

    
8151
  def Exec(self, feedback_fn):
8152
    """Execute disk replacement.
8153

8154
    This dispatches the disk replacement to the appropriate handler.
8155

8156
    """
8157
    if self.delay_iallocator:
8158
      self._CheckPrereq2()
8159

    
8160
    if not self.disks:
8161
      feedback_fn("No disks need replacement")
8162
      return
8163

    
8164
    feedback_fn("Replacing disk(s) %s for %s" %
8165
                (utils.CommaJoin(self.disks), self.instance.name))
8166

    
8167
    activate_disks = (not self.instance.admin_up)
8168

    
8169
    # Activate the instance disks if we're replacing them on a down instance
8170
    if activate_disks:
8171
      _StartInstanceDisks(self.lu, self.instance, True)
8172

    
8173
    try:
8174
      # Should we replace the secondary node?
8175
      if self.new_node is not None:
8176
        fn = self._ExecDrbd8Secondary
8177
      else:
8178
        fn = self._ExecDrbd8DiskOnly
8179

    
8180
      return fn(feedback_fn)
8181

    
8182
    finally:
8183
      # Deactivate the instance disks if we're replacing them on a
8184
      # down instance
8185
      if activate_disks:
8186
        _SafeShutdownInstanceDisks(self.lu, self.instance)
8187

    
8188
  def _CheckVolumeGroup(self, nodes):
8189
    self.lu.LogInfo("Checking volume groups")
8190

    
8191
    vgname = self.cfg.GetVGName()
8192

    
8193
    # Make sure volume group exists on all involved nodes
8194
    results = self.rpc.call_vg_list(nodes)
8195
    if not results:
8196
      raise errors.OpExecError("Can't list volume groups on the nodes")
8197

    
8198
    for node in nodes:
8199
      res = results[node]
8200
      res.Raise("Error checking node %s" % node)
8201
      if vgname not in res.payload:
8202
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
8203
                                 (vgname, node))
8204

    
8205
  def _CheckDisksExistence(self, nodes):
8206
    # Check disk existence
8207
    for idx, dev in enumerate(self.instance.disks):
8208
      if idx not in self.disks:
8209
        continue
8210

    
8211
      for node in nodes:
8212
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
8213
        self.cfg.SetDiskID(dev, node)
8214

    
8215
        result = self.rpc.call_blockdev_find(node, dev)
8216

    
8217
        msg = result.fail_msg
8218
        if msg or not result.payload:
8219
          if not msg:
8220
            msg = "disk not found"
8221
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
8222
                                   (idx, node, msg))
8223

    
8224
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
8225
    for idx, dev in enumerate(self.instance.disks):
8226
      if idx not in self.disks:
8227
        continue
8228

    
8229
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
8230
                      (idx, node_name))
8231

    
8232
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
8233
                                   ldisk=ldisk):
8234
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
8235
                                 " replace disks for instance %s" %
8236
                                 (node_name, self.instance.name))
8237

    
8238
  def _CreateNewStorage(self, node_name):
8239
    vgname = self.cfg.GetVGName()
8240
    iv_names = {}
8241

    
8242
    for idx, dev in enumerate(self.instance.disks):
8243
      if idx not in self.disks:
8244
        continue
8245

    
8246
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
8247

    
8248
      self.cfg.SetDiskID(dev, node_name)
8249

    
8250
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
8251
      names = _GenerateUniqueNames(self.lu, lv_names)
8252

    
8253
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
8254
                             logical_id=(vgname, names[0]))
8255
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
8256
                             logical_id=(vgname, names[1]))
8257

    
8258
      new_lvs = [lv_data, lv_meta]
8259
      old_lvs = dev.children
8260
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
8261

    
8262
      # we pass force_create=True to force the LVM creation
8263
      for new_lv in new_lvs:
8264
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
8265
                        _GetInstanceInfoText(self.instance), False)
8266

    
8267
    return iv_names
8268

    
8269
  def _CheckDevices(self, node_name, iv_names):
8270
    for name, (dev, _, _) in iv_names.iteritems():
8271
      self.cfg.SetDiskID(dev, node_name)
8272

    
8273
      result = self.rpc.call_blockdev_find(node_name, dev)
8274

    
8275
      msg = result.fail_msg
8276
      if msg or not result.payload:
8277
        if not msg:
8278
          msg = "disk not found"
8279
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
8280
                                 (name, msg))
8281

    
8282
      if result.payload.is_degraded:
8283
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
8284

    
8285
  def _RemoveOldStorage(self, node_name, iv_names):
8286
    for name, (_, old_lvs, _) in iv_names.iteritems():
8287
      self.lu.LogInfo("Remove logical volumes for %s" % name)
8288

    
8289
      for lv in old_lvs:
8290
        self.cfg.SetDiskID(lv, node_name)
8291

    
8292
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
8293
        if msg:
8294
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
8295
                             hint="remove unused LVs manually")
8296

    
8297
  def _ReleaseNodeLock(self, node_name):
8298
    """Releases the lock for a given node."""
8299
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
8300

    
8301
  def _ExecDrbd8DiskOnly(self, feedback_fn):
8302
    """Replace a disk on the primary or secondary for DRBD 8.
8303

8304
    The algorithm for replace is quite complicated:
8305

8306
      1. for each disk to be replaced:
8307

8308
        1. create new LVs on the target node with unique names
8309
        1. detach old LVs from the drbd device
8310
        1. rename old LVs to name_replaced.<time_t>
8311
        1. rename new LVs to old LVs
8312
        1. attach the new LVs (with the old names now) to the drbd device
8313

8314
      1. wait for sync across all devices
8315

8316
      1. for each modified disk:
8317

8318
        1. remove old LVs (which have the name name_replaces.<time_t>)
8319

8320
    Failures are not very well handled.
8321

8322
    """
8323
    steps_total = 6
8324

    
8325
    # Step: check device activation
8326
    self.lu.LogStep(1, steps_total, "Check device existence")
8327
    self._CheckDisksExistence([self.other_node, self.target_node])
8328
    self._CheckVolumeGroup([self.target_node, self.other_node])
8329

    
8330
    # Step: check other node consistency
8331
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8332
    self._CheckDisksConsistency(self.other_node,
8333
                                self.other_node == self.instance.primary_node,
8334
                                False)
8335

    
8336
    # Step: create new storage
8337
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8338
    iv_names = self._CreateNewStorage(self.target_node)
8339

    
8340
    # Step: for each lv, detach+rename*2+attach
8341
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8342
    for dev, old_lvs, new_lvs in iv_names.itervalues():
8343
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
8344

    
8345
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
8346
                                                     old_lvs)
8347
      result.Raise("Can't detach drbd from local storage on node"
8348
                   " %s for device %s" % (self.target_node, dev.iv_name))
8349
      #dev.children = []
8350
      #cfg.Update(instance)
8351

    
8352
      # ok, we created the new LVs, so now we know we have the needed
8353
      # storage; as such, we proceed on the target node to rename
8354
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
8355
      # using the assumption that logical_id == physical_id (which in
8356
      # turn is the unique_id on that node)
8357

    
8358
      # FIXME(iustin): use a better name for the replaced LVs
8359
      temp_suffix = int(time.time())
8360
      ren_fn = lambda d, suff: (d.physical_id[0],
8361
                                d.physical_id[1] + "_replaced-%s" % suff)
8362

    
8363
      # Build the rename list based on what LVs exist on the node
8364
      rename_old_to_new = []
8365
      for to_ren in old_lvs:
8366
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
8367
        if not result.fail_msg and result.payload:
8368
          # device exists
8369
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
8370

    
8371
      self.lu.LogInfo("Renaming the old LVs on the target node")
8372
      result = self.rpc.call_blockdev_rename(self.target_node,
8373
                                             rename_old_to_new)
8374
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
8375

    
8376
      # Now we rename the new LVs to the old LVs
8377
      self.lu.LogInfo("Renaming the new LVs on the target node")
8378
      rename_new_to_old = [(new, old.physical_id)
8379
                           for old, new in zip(old_lvs, new_lvs)]
8380
      result = self.rpc.call_blockdev_rename(self.target_node,
8381
                                             rename_new_to_old)
8382
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
8383

    
8384
      for old, new in zip(old_lvs, new_lvs):
8385
        new.logical_id = old.logical_id
8386
        self.cfg.SetDiskID(new, self.target_node)
8387

    
8388
      for disk in old_lvs:
8389
        disk.logical_id = ren_fn(disk, temp_suffix)
8390
        self.cfg.SetDiskID(disk, self.target_node)
8391

    
8392
      # Now that the new lvs have the old name, we can add them to the device
8393
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
8394
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
8395
                                                  new_lvs)
8396
      msg = result.fail_msg
8397
      if msg:
8398
        for new_lv in new_lvs:
8399
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
8400
                                               new_lv).fail_msg
8401
          if msg2:
8402
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
8403
                               hint=("cleanup manually the unused logical"
8404
                                     "volumes"))
8405
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8406

    
8407
      dev.children = new_lvs
8408

    
8409
      self.cfg.Update(self.instance, feedback_fn)
8410

    
8411
    cstep = 5
8412
    if self.early_release:
8413
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8414
      cstep += 1
8415
      self._RemoveOldStorage(self.target_node, iv_names)
8416
      # WARNING: we release both node locks here, do not do other RPCs
8417
      # than WaitForSync to the primary node
8418
      self._ReleaseNodeLock([self.target_node, self.other_node])
8419

    
8420
    # Wait for sync
8421
    # This can fail as the old devices are degraded and _WaitForSync
8422
    # does a combined result over all disks, so we don't check its return value
8423
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8424
    cstep += 1
8425
    _WaitForSync(self.lu, self.instance)
8426

    
8427
    # Check all devices manually
8428
    self._CheckDevices(self.instance.primary_node, iv_names)
8429

    
8430
    # Step: remove old storage
8431
    if not self.early_release:
8432
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8433
      cstep += 1
8434
      self._RemoveOldStorage(self.target_node, iv_names)
8435

    
8436
  def _ExecDrbd8Secondary(self, feedback_fn):
8437
    """Replace the secondary node for DRBD 8.
8438

8439
    The algorithm for replace is quite complicated:
8440
      - for all disks of the instance:
8441
        - create new LVs on the new node with same names
8442
        - shutdown the drbd device on the old secondary
8443
        - disconnect the drbd network on the primary
8444
        - create the drbd device on the new secondary
8445
        - network attach the drbd on the primary, using an artifice:
8446
          the drbd code for Attach() will connect to the network if it
8447
          finds a device which is connected to the good local disks but
8448
          not network enabled
8449
      - wait for sync across all devices
8450
      - remove all disks from the old secondary
8451

8452
    Failures are not very well handled.
8453

8454
    """
8455
    steps_total = 6
8456

    
8457
    # Step: check device activation
8458
    self.lu.LogStep(1, steps_total, "Check device existence")
8459
    self._CheckDisksExistence([self.instance.primary_node])
8460
    self._CheckVolumeGroup([self.instance.primary_node])
8461

    
8462
    # Step: check other node consistency
8463
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8464
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8465

    
8466
    # Step: create new storage
8467
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8468
    for idx, dev in enumerate(self.instance.disks):
8469
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8470
                      (self.new_node, idx))
8471
      # we pass force_create=True to force LVM creation
8472
      for new_lv in dev.children:
8473
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8474
                        _GetInstanceInfoText(self.instance), False)
8475

    
8476
    # Step 4: dbrd minors and drbd setups changes
8477
    # after this, we must manually remove the drbd minors on both the
8478
    # error and the success paths
8479
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8480
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8481
                                         for dev in self.instance.disks],
8482
                                        self.instance.name)
8483
    logging.debug("Allocated minors %r", minors)
8484

    
8485
    iv_names = {}
8486
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8487
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8488
                      (self.new_node, idx))
8489
      # create new devices on new_node; note that we create two IDs:
8490
      # one without port, so the drbd will be activated without
8491
      # networking information on the new node at this stage, and one
8492
      # with network, for the latter activation in step 4
8493
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8494
      if self.instance.primary_node == o_node1:
8495
        p_minor = o_minor1
8496
      else:
8497
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8498
        p_minor = o_minor2
8499

    
8500
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8501
                      p_minor, new_minor, o_secret)
8502
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8503
                    p_minor, new_minor, o_secret)
8504

    
8505
      iv_names[idx] = (dev, dev.children, new_net_id)
8506
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8507
                    new_net_id)
8508
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8509
                              logical_id=new_alone_id,
8510
                              children=dev.children,
8511
                              size=dev.size)
8512
      try:
8513
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8514
                              _GetInstanceInfoText(self.instance), False)
8515
      except errors.GenericError:
8516
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8517
        raise
8518

    
8519
    # We have new devices, shutdown the drbd on the old secondary
8520
    for idx, dev in enumerate(self.instance.disks):
8521
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8522
      self.cfg.SetDiskID(dev, self.target_node)
8523
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8524
      if msg:
8525
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8526
                           "node: %s" % (idx, msg),
8527
                           hint=("Please cleanup this device manually as"
8528
                                 " soon as possible"))
8529

    
8530
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8531
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8532
                                               self.node_secondary_ip,
8533
                                               self.instance.disks)\
8534
                                              [self.instance.primary_node]
8535

    
8536
    msg = result.fail_msg
8537
    if msg:
8538
      # detaches didn't succeed (unlikely)
8539
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8540
      raise errors.OpExecError("Can't detach the disks from the network on"
8541
                               " old node: %s" % (msg,))
8542

    
8543
    # if we managed to detach at least one, we update all the disks of
8544
    # the instance to point to the new secondary
8545
    self.lu.LogInfo("Updating instance configuration")
8546
    for dev, _, new_logical_id in iv_names.itervalues():
8547
      dev.logical_id = new_logical_id
8548
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8549

    
8550
    self.cfg.Update(self.instance, feedback_fn)
8551

    
8552
    # and now perform the drbd attach
8553
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8554
                    " (standalone => connected)")
8555
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8556
                                            self.new_node],
8557
                                           self.node_secondary_ip,
8558
                                           self.instance.disks,
8559
                                           self.instance.name,
8560
                                           False)
8561
    for to_node, to_result in result.items():
8562
      msg = to_result.fail_msg
8563
      if msg:
8564
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8565
                           to_node, msg,
8566
                           hint=("please do a gnt-instance info to see the"
8567
                                 " status of disks"))
8568
    cstep = 5
8569
    if self.early_release:
8570
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8571
      cstep += 1
8572
      self._RemoveOldStorage(self.target_node, iv_names)
8573
      # WARNING: we release all node locks here, do not do other RPCs
8574
      # than WaitForSync to the primary node
8575
      self._ReleaseNodeLock([self.instance.primary_node,
8576
                             self.target_node,
8577
                             self.new_node])
8578

    
8579
    # Wait for sync
8580
    # This can fail as the old devices are degraded and _WaitForSync
8581
    # does a combined result over all disks, so we don't check its return value
8582
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8583
    cstep += 1
8584
    _WaitForSync(self.lu, self.instance)
8585

    
8586
    # Check all devices manually
8587
    self._CheckDevices(self.instance.primary_node, iv_names)
8588

    
8589
    # Step: remove old storage
8590
    if not self.early_release:
8591
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8592
      self._RemoveOldStorage(self.target_node, iv_names)
8593

    
8594

    
8595
class LURepairNodeStorage(NoHooksLU):
8596
  """Repairs the volume group on a node.
8597

8598
  """
8599
  REQ_BGL = False
8600

    
8601
  def CheckArguments(self):
8602
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8603

    
8604
    storage_type = self.op.storage_type
8605

    
8606
    if (constants.SO_FIX_CONSISTENCY not in
8607
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8608
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8609
                                 " repaired" % storage_type,
8610
                                 errors.ECODE_INVAL)
8611

    
8612
  def ExpandNames(self):
8613
    self.needed_locks = {
8614
      locking.LEVEL_NODE: [self.op.node_name],
8615
      }
8616

    
8617
  def _CheckFaultyDisks(self, instance, node_name):
8618
    """Ensure faulty disks abort the opcode or at least warn."""
8619
    try:
8620
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8621
                                  node_name, True):
8622
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8623
                                   " node '%s'" % (instance.name, node_name),
8624
                                   errors.ECODE_STATE)
8625
    except errors.OpPrereqError, err:
8626
      if self.op.ignore_consistency:
8627
        self.proc.LogWarning(str(err.args[0]))
8628
      else:
8629
        raise
8630

    
8631
  def CheckPrereq(self):
8632
    """Check prerequisites.
8633

8634
    """
8635
    # Check whether any instance on this node has faulty disks
8636
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8637
      if not inst.admin_up:
8638
        continue
8639
      check_nodes = set(inst.all_nodes)
8640
      check_nodes.discard(self.op.node_name)
8641
      for inst_node_name in check_nodes:
8642
        self._CheckFaultyDisks(inst, inst_node_name)
8643

    
8644
  def Exec(self, feedback_fn):
8645
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8646
                (self.op.name, self.op.node_name))
8647

    
8648
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8649
    result = self.rpc.call_storage_execute(self.op.node_name,
8650
                                           self.op.storage_type, st_args,
8651
                                           self.op.name,
8652
                                           constants.SO_FIX_CONSISTENCY)
8653
    result.Raise("Failed to repair storage unit '%s' on %s" %
8654
                 (self.op.name, self.op.node_name))
8655

    
8656

    
8657
class LUNodeEvacStrategy(NoHooksLU):
8658
  """Computes the node evacuation strategy.
8659

8660
  """
8661
  REQ_BGL = False
8662

    
8663
  def CheckArguments(self):
8664
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8665

    
8666
  def ExpandNames(self):
8667
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8668
    self.needed_locks = locks = {}
8669
    if self.op.remote_node is None:
8670
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8671
    else:
8672
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8673
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8674

    
8675
  def Exec(self, feedback_fn):
8676
    if self.op.remote_node is not None:
8677
      instances = []
8678
      for node in self.op.nodes:
8679
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8680
      result = []
8681
      for i in instances:
8682
        if i.primary_node == self.op.remote_node:
8683
          raise errors.OpPrereqError("Node %s is the primary node of"
8684
                                     " instance %s, cannot use it as"
8685
                                     " secondary" %
8686
                                     (self.op.remote_node, i.name),
8687
                                     errors.ECODE_INVAL)
8688
        result.append([i.name, self.op.remote_node])
8689
    else:
8690
      ial = IAllocator(self.cfg, self.rpc,
8691
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8692
                       evac_nodes=self.op.nodes)
8693
      ial.Run(self.op.iallocator, validate=True)
8694
      if not ial.success:
8695
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8696
                                 errors.ECODE_NORES)
8697
      result = ial.result
8698
    return result
8699

    
8700

    
8701
class LUInstanceGrowDisk(LogicalUnit):
8702
  """Grow a disk of an instance.
8703

8704
  """
8705
  HPATH = "disk-grow"
8706
  HTYPE = constants.HTYPE_INSTANCE
8707
  REQ_BGL = False
8708

    
8709
  def ExpandNames(self):
8710
    self._ExpandAndLockInstance()
8711
    self.needed_locks[locking.LEVEL_NODE] = []
8712
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8713

    
8714
  def DeclareLocks(self, level):
8715
    if level == locking.LEVEL_NODE:
8716
      self._LockInstancesNodes()
8717

    
8718
  def BuildHooksEnv(self):
8719
    """Build hooks env.
8720

8721
    This runs on the master, the primary and all the secondaries.
8722

8723
    """
8724
    env = {
8725
      "DISK": self.op.disk,
8726
      "AMOUNT": self.op.amount,
8727
      }
8728
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8729
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8730
    return env, nl, nl
8731

    
8732
  def CheckPrereq(self):
8733
    """Check prerequisites.
8734

8735
    This checks that the instance is in the cluster.
8736

8737
    """
8738
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8739
    assert instance is not None, \
8740
      "Cannot retrieve locked instance %s" % self.op.instance_name
8741
    nodenames = list(instance.all_nodes)
8742
    for node in nodenames:
8743
      _CheckNodeOnline(self, node)
8744

    
8745
    self.instance = instance
8746

    
8747
    if instance.disk_template not in constants.DTS_GROWABLE:
8748
      raise errors.OpPrereqError("Instance's disk layout does not support"
8749
                                 " growing.", errors.ECODE_INVAL)
8750

    
8751
    self.disk = instance.FindDisk(self.op.disk)
8752

    
8753
    if instance.disk_template != constants.DT_FILE:
8754
      # TODO: check the free disk space for file, when that feature
8755
      # will be supported
8756
      _CheckNodesFreeDiskPerVG(self, nodenames,
8757
                               self.disk.ComputeGrowth(self.op.amount))
8758

    
8759
  def Exec(self, feedback_fn):
8760
    """Execute disk grow.
8761

8762
    """
8763
    instance = self.instance
8764
    disk = self.disk
8765

    
8766
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8767
    if not disks_ok:
8768
      raise errors.OpExecError("Cannot activate block device to grow")
8769

    
8770
    for node in instance.all_nodes:
8771
      self.cfg.SetDiskID(disk, node)
8772
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8773
      result.Raise("Grow request failed to node %s" % node)
8774

    
8775
      # TODO: Rewrite code to work properly
8776
      # DRBD goes into sync mode for a short amount of time after executing the
8777
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8778
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8779
      # time is a work-around.
8780
      time.sleep(5)
8781

    
8782
    disk.RecordGrow(self.op.amount)
8783
    self.cfg.Update(instance, feedback_fn)
8784
    if self.op.wait_for_sync:
8785
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8786
      if disk_abort:
8787
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8788
                             " status.\nPlease check the instance.")
8789
      if not instance.admin_up:
8790
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8791
    elif not instance.admin_up:
8792
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8793
                           " not supposed to be running because no wait for"
8794
                           " sync mode was requested.")
8795

    
8796

    
8797
class LUInstanceQueryData(NoHooksLU):
8798
  """Query runtime instance data.
8799

8800
  """
8801
  REQ_BGL = False
8802

    
8803
  def ExpandNames(self):
8804
    self.needed_locks = {}
8805
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8806

    
8807
    if self.op.instances:
8808
      self.wanted_names = []
8809
      for name in self.op.instances:
8810
        full_name = _ExpandInstanceName(self.cfg, name)
8811
        self.wanted_names.append(full_name)
8812
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8813
    else:
8814
      self.wanted_names = None
8815
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8816

    
8817
    self.needed_locks[locking.LEVEL_NODE] = []
8818
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8819

    
8820
  def DeclareLocks(self, level):
8821
    if level == locking.LEVEL_NODE:
8822
      self._LockInstancesNodes()
8823

    
8824
  def CheckPrereq(self):
8825
    """Check prerequisites.
8826

8827
    This only checks the optional instance list against the existing names.
8828

8829
    """
8830
    if self.wanted_names is None:
8831
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8832

    
8833
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8834
                             in self.wanted_names]
8835

    
8836
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8837
    """Returns the status of a block device
8838

8839
    """
8840
    if self.op.static or not node:
8841
      return None
8842

    
8843
    self.cfg.SetDiskID(dev, node)
8844

    
8845
    result = self.rpc.call_blockdev_find(node, dev)
8846
    if result.offline:
8847
      return None
8848

    
8849
    result.Raise("Can't compute disk status for %s" % instance_name)
8850

    
8851
    status = result.payload
8852
    if status is None:
8853
      return None
8854

    
8855
    return (status.dev_path, status.major, status.minor,
8856
            status.sync_percent, status.estimated_time,
8857
            status.is_degraded, status.ldisk_status)
8858

    
8859
  def _ComputeDiskStatus(self, instance, snode, dev):
8860
    """Compute block device status.
8861

8862
    """
8863
    if dev.dev_type in constants.LDS_DRBD:
8864
      # we change the snode then (otherwise we use the one passed in)
8865
      if dev.logical_id[0] == instance.primary_node:
8866
        snode = dev.logical_id[1]
8867
      else:
8868
        snode = dev.logical_id[0]
8869

    
8870
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8871
                                              instance.name, dev)
8872
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8873

    
8874
    if dev.children:
8875
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8876
                      for child in dev.children]
8877
    else:
8878
      dev_children = []
8879

    
8880
    data = {
8881
      "iv_name": dev.iv_name,
8882
      "dev_type": dev.dev_type,
8883
      "logical_id": dev.logical_id,
8884
      "physical_id": dev.physical_id,
8885
      "pstatus": dev_pstatus,
8886
      "sstatus": dev_sstatus,
8887
      "children": dev_children,
8888
      "mode": dev.mode,
8889
      "size": dev.size,
8890
      }
8891

    
8892
    return data
8893

    
8894
  def Exec(self, feedback_fn):
8895
    """Gather and return data"""
8896
    result = {}
8897

    
8898
    cluster = self.cfg.GetClusterInfo()
8899

    
8900
    for instance in self.wanted_instances:
8901
      if not self.op.static:
8902
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8903
                                                  instance.name,
8904
                                                  instance.hypervisor)
8905
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8906
        remote_info = remote_info.payload
8907
        if remote_info and "state" in remote_info:
8908
          remote_state = "up"
8909
        else:
8910
          remote_state = "down"
8911
      else:
8912
        remote_state = None
8913
      if instance.admin_up:
8914
        config_state = "up"
8915
      else:
8916
        config_state = "down"
8917

    
8918
      disks = [self._ComputeDiskStatus(instance, None, device)
8919
               for device in instance.disks]
8920

    
8921
      idict = {
8922
        "name": instance.name,
8923
        "config_state": config_state,
8924
        "run_state": remote_state,
8925
        "pnode": instance.primary_node,
8926
        "snodes": instance.secondary_nodes,
8927
        "os": instance.os,
8928
        # this happens to be the same format used for hooks
8929
        "nics": _NICListToTuple(self, instance.nics),
8930
        "disk_template": instance.disk_template,
8931
        "disks": disks,
8932
        "hypervisor": instance.hypervisor,
8933
        "network_port": instance.network_port,
8934
        "hv_instance": instance.hvparams,
8935
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8936
        "be_instance": instance.beparams,
8937
        "be_actual": cluster.FillBE(instance),
8938
        "os_instance": instance.osparams,
8939
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8940
        "serial_no": instance.serial_no,
8941
        "mtime": instance.mtime,
8942
        "ctime": instance.ctime,
8943
        "uuid": instance.uuid,
8944
        }
8945

    
8946
      result[instance.name] = idict
8947

    
8948
    return result
8949

    
8950

    
8951
class LUInstanceSetParams(LogicalUnit):
8952
  """Modifies an instances's parameters.
8953

8954
  """
8955
  HPATH = "instance-modify"
8956
  HTYPE = constants.HTYPE_INSTANCE
8957
  REQ_BGL = False
8958

    
8959
  def CheckArguments(self):
8960
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8961
            self.op.hvparams or self.op.beparams or self.op.os_name):
8962
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8963

    
8964
    if self.op.hvparams:
8965
      _CheckGlobalHvParams(self.op.hvparams)
8966

    
8967
    # Disk validation
8968
    disk_addremove = 0
8969
    for disk_op, disk_dict in self.op.disks:
8970
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8971
      if disk_op == constants.DDM_REMOVE:
8972
        disk_addremove += 1
8973
        continue
8974
      elif disk_op == constants.DDM_ADD:
8975
        disk_addremove += 1
8976
      else:
8977
        if not isinstance(disk_op, int):
8978
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8979
        if not isinstance(disk_dict, dict):
8980
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8981
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8982

    
8983
      if disk_op == constants.DDM_ADD:
8984
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8985
        if mode not in constants.DISK_ACCESS_SET:
8986
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8987
                                     errors.ECODE_INVAL)
8988
        size = disk_dict.get('size', None)
8989
        if size is None:
8990
          raise errors.OpPrereqError("Required disk parameter size missing",
8991
                                     errors.ECODE_INVAL)
8992
        try:
8993
          size = int(size)
8994
        except (TypeError, ValueError), err:
8995
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8996
                                     str(err), errors.ECODE_INVAL)
8997
        disk_dict['size'] = size
8998
      else:
8999
        # modification of disk
9000
        if 'size' in disk_dict:
9001
          raise errors.OpPrereqError("Disk size change not possible, use"
9002
                                     " grow-disk", errors.ECODE_INVAL)
9003

    
9004
    if disk_addremove > 1:
9005
      raise errors.OpPrereqError("Only one disk add or remove operation"
9006
                                 " supported at a time", errors.ECODE_INVAL)
9007

    
9008
    if self.op.disks and self.op.disk_template is not None:
9009
      raise errors.OpPrereqError("Disk template conversion and other disk"
9010
                                 " changes not supported at the same time",
9011
                                 errors.ECODE_INVAL)
9012

    
9013
    if (self.op.disk_template and
9014
        self.op.disk_template in constants.DTS_NET_MIRROR and
9015
        self.op.remote_node is None):
9016
      raise errors.OpPrereqError("Changing the disk template to a mirrored"
9017
                                 " one requires specifying a secondary node",
9018
                                 errors.ECODE_INVAL)
9019

    
9020
    # NIC validation
9021
    nic_addremove = 0
9022
    for nic_op, nic_dict in self.op.nics:
9023
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
9024
      if nic_op == constants.DDM_REMOVE:
9025
        nic_addremove += 1
9026
        continue
9027
      elif nic_op == constants.DDM_ADD:
9028
        nic_addremove += 1
9029
      else:
9030
        if not isinstance(nic_op, int):
9031
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
9032
        if not isinstance(nic_dict, dict):
9033
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
9034
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9035

    
9036
      # nic_dict should be a dict
9037
      nic_ip = nic_dict.get('ip', None)
9038
      if nic_ip is not None:
9039
        if nic_ip.lower() == constants.VALUE_NONE:
9040
          nic_dict['ip'] = None
9041
        else:
9042
          if not netutils.IPAddress.IsValid(nic_ip):
9043
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
9044
                                       errors.ECODE_INVAL)
9045

    
9046
      nic_bridge = nic_dict.get('bridge', None)
9047
      nic_link = nic_dict.get('link', None)
9048
      if nic_bridge and nic_link:
9049
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
9050
                                   " at the same time", errors.ECODE_INVAL)
9051
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
9052
        nic_dict['bridge'] = None
9053
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
9054
        nic_dict['link'] = None
9055

    
9056
      if nic_op == constants.DDM_ADD:
9057
        nic_mac = nic_dict.get('mac', None)
9058
        if nic_mac is None:
9059
          nic_dict['mac'] = constants.VALUE_AUTO
9060

    
9061
      if 'mac' in nic_dict:
9062
        nic_mac = nic_dict['mac']
9063
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9064
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
9065

    
9066
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
9067
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
9068
                                     " modifying an existing nic",
9069
                                     errors.ECODE_INVAL)
9070

    
9071
    if nic_addremove > 1:
9072
      raise errors.OpPrereqError("Only one NIC add or remove operation"
9073
                                 " supported at a time", errors.ECODE_INVAL)
9074

    
9075
  def ExpandNames(self):
9076
    self._ExpandAndLockInstance()
9077
    self.needed_locks[locking.LEVEL_NODE] = []
9078
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9079

    
9080
  def DeclareLocks(self, level):
9081
    if level == locking.LEVEL_NODE:
9082
      self._LockInstancesNodes()
9083
      if self.op.disk_template and self.op.remote_node:
9084
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9085
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
9086

    
9087
  def BuildHooksEnv(self):
9088
    """Build hooks env.
9089

9090
    This runs on the master, primary and secondaries.
9091

9092
    """
9093
    args = dict()
9094
    if constants.BE_MEMORY in self.be_new:
9095
      args['memory'] = self.be_new[constants.BE_MEMORY]
9096
    if constants.BE_VCPUS in self.be_new:
9097
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
9098
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
9099
    # information at all.
9100
    if self.op.nics:
9101
      args['nics'] = []
9102
      nic_override = dict(self.op.nics)
9103
      for idx, nic in enumerate(self.instance.nics):
9104
        if idx in nic_override:
9105
          this_nic_override = nic_override[idx]
9106
        else:
9107
          this_nic_override = {}
9108
        if 'ip' in this_nic_override:
9109
          ip = this_nic_override['ip']
9110
        else:
9111
          ip = nic.ip
9112
        if 'mac' in this_nic_override:
9113
          mac = this_nic_override['mac']
9114
        else:
9115
          mac = nic.mac
9116
        if idx in self.nic_pnew:
9117
          nicparams = self.nic_pnew[idx]
9118
        else:
9119
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
9120
        mode = nicparams[constants.NIC_MODE]
9121
        link = nicparams[constants.NIC_LINK]
9122
        args['nics'].append((ip, mac, mode, link))
9123
      if constants.DDM_ADD in nic_override:
9124
        ip = nic_override[constants.DDM_ADD].get('ip', None)
9125
        mac = nic_override[constants.DDM_ADD]['mac']
9126
        nicparams = self.nic_pnew[constants.DDM_ADD]
9127
        mode = nicparams[constants.NIC_MODE]
9128
        link = nicparams[constants.NIC_LINK]
9129
        args['nics'].append((ip, mac, mode, link))
9130
      elif constants.DDM_REMOVE in nic_override:
9131
        del args['nics'][-1]
9132

    
9133
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
9134
    if self.op.disk_template:
9135
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
9136
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9137
    return env, nl, nl
9138

    
9139
  def CheckPrereq(self):
9140
    """Check prerequisites.
9141

9142
    This only checks the instance list against the existing names.
9143

9144
    """
9145
    # checking the new params on the primary/secondary nodes
9146

    
9147
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9148
    cluster = self.cluster = self.cfg.GetClusterInfo()
9149
    assert self.instance is not None, \
9150
      "Cannot retrieve locked instance %s" % self.op.instance_name
9151
    pnode = instance.primary_node
9152
    nodelist = list(instance.all_nodes)
9153

    
9154
    # OS change
9155
    if self.op.os_name and not self.op.force:
9156
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
9157
                      self.op.force_variant)
9158
      instance_os = self.op.os_name
9159
    else:
9160
      instance_os = instance.os
9161

    
9162
    if self.op.disk_template:
9163
      if instance.disk_template == self.op.disk_template:
9164
        raise errors.OpPrereqError("Instance already has disk template %s" %
9165
                                   instance.disk_template, errors.ECODE_INVAL)
9166

    
9167
      if (instance.disk_template,
9168
          self.op.disk_template) not in self._DISK_CONVERSIONS:
9169
        raise errors.OpPrereqError("Unsupported disk template conversion from"
9170
                                   " %s to %s" % (instance.disk_template,
9171
                                                  self.op.disk_template),
9172
                                   errors.ECODE_INVAL)
9173
      _CheckInstanceDown(self, instance, "cannot change disk template")
9174
      if self.op.disk_template in constants.DTS_NET_MIRROR:
9175
        if self.op.remote_node == pnode:
9176
          raise errors.OpPrereqError("Given new secondary node %s is the same"
9177
                                     " as the primary node of the instance" %
9178
                                     self.op.remote_node, errors.ECODE_STATE)
9179
        _CheckNodeOnline(self, self.op.remote_node)
9180
        _CheckNodeNotDrained(self, self.op.remote_node)
9181
        # FIXME: here we assume that the old instance type is DT_PLAIN
9182
        assert instance.disk_template == constants.DT_PLAIN
9183
        disks = [{"size": d.size, "vg": d.logical_id[0]}
9184
                 for d in instance.disks]
9185
        required = _ComputeDiskSizePerVG(self.op.disk_template, disks)
9186
        _CheckNodesFreeDiskPerVG(self, [self.op.remote_node], required)
9187

    
9188
    # hvparams processing
9189
    if self.op.hvparams:
9190
      hv_type = instance.hypervisor
9191
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
9192
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
9193
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
9194

    
9195
      # local check
9196
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
9197
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
9198
      self.hv_new = hv_new # the new actual values
9199
      self.hv_inst = i_hvdict # the new dict (without defaults)
9200
    else:
9201
      self.hv_new = self.hv_inst = {}
9202

    
9203
    # beparams processing
9204
    if self.op.beparams:
9205
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
9206
                                   use_none=True)
9207
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
9208
      be_new = cluster.SimpleFillBE(i_bedict)
9209
      self.be_new = be_new # the new actual values
9210
      self.be_inst = i_bedict # the new dict (without defaults)
9211
    else:
9212
      self.be_new = self.be_inst = {}
9213

    
9214
    # osparams processing
9215
    if self.op.osparams:
9216
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
9217
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
9218
      self.os_inst = i_osdict # the new dict (without defaults)
9219
    else:
9220
      self.os_inst = {}
9221

    
9222
    self.warn = []
9223

    
9224
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
9225
      mem_check_list = [pnode]
9226
      if be_new[constants.BE_AUTO_BALANCE]:
9227
        # either we changed auto_balance to yes or it was from before
9228
        mem_check_list.extend(instance.secondary_nodes)
9229
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
9230
                                                  instance.hypervisor)
9231
      nodeinfo = self.rpc.call_node_info(mem_check_list, None,
9232
                                         instance.hypervisor)
9233
      pninfo = nodeinfo[pnode]
9234
      msg = pninfo.fail_msg
9235
      if msg:
9236
        # Assume the primary node is unreachable and go ahead
9237
        self.warn.append("Can't get info from primary node %s: %s" %
9238
                         (pnode,  msg))
9239
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
9240
        self.warn.append("Node data from primary node %s doesn't contain"
9241
                         " free memory information" % pnode)
9242
      elif instance_info.fail_msg:
9243
        self.warn.append("Can't get instance runtime information: %s" %
9244
                        instance_info.fail_msg)
9245
      else:
9246
        if instance_info.payload:
9247
          current_mem = int(instance_info.payload['memory'])
9248
        else:
9249
          # Assume instance not running
9250
          # (there is a slight race condition here, but it's not very probable,
9251
          # and we have no other way to check)
9252
          current_mem = 0
9253
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
9254
                    pninfo.payload['memory_free'])
9255
        if miss_mem > 0:
9256
          raise errors.OpPrereqError("This change will prevent the instance"
9257
                                     " from starting, due to %d MB of memory"
9258
                                     " missing on its primary node" % miss_mem,
9259
                                     errors.ECODE_NORES)
9260

    
9261
      if be_new[constants.BE_AUTO_BALANCE]:
9262
        for node, nres in nodeinfo.items():
9263
          if node not in instance.secondary_nodes:
9264
            continue
9265
          msg = nres.fail_msg
9266
          if msg:
9267
            self.warn.append("Can't get info from secondary node %s: %s" %
9268
                             (node, msg))
9269
          elif not isinstance(nres.payload.get('memory_free', None), int):
9270
            self.warn.append("Secondary node %s didn't return free"
9271
                             " memory information" % node)
9272
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
9273
            self.warn.append("Not enough memory to failover instance to"
9274
                             " secondary node %s" % node)
9275

    
9276
    # NIC processing
9277
    self.nic_pnew = {}
9278
    self.nic_pinst = {}
9279
    for nic_op, nic_dict in self.op.nics:
9280
      if nic_op == constants.DDM_REMOVE:
9281
        if not instance.nics:
9282
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
9283
                                     errors.ECODE_INVAL)
9284
        continue
9285
      if nic_op != constants.DDM_ADD:
9286
        # an existing nic
9287
        if not instance.nics:
9288
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
9289
                                     " no NICs" % nic_op,
9290
                                     errors.ECODE_INVAL)
9291
        if nic_op < 0 or nic_op >= len(instance.nics):
9292
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
9293
                                     " are 0 to %d" %
9294
                                     (nic_op, len(instance.nics) - 1),
9295
                                     errors.ECODE_INVAL)
9296
        old_nic_params = instance.nics[nic_op].nicparams
9297
        old_nic_ip = instance.nics[nic_op].ip
9298
      else:
9299
        old_nic_params = {}
9300
        old_nic_ip = None
9301

    
9302
      update_params_dict = dict([(key, nic_dict[key])
9303
                                 for key in constants.NICS_PARAMETERS
9304
                                 if key in nic_dict])
9305

    
9306
      if 'bridge' in nic_dict:
9307
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
9308

    
9309
      new_nic_params = _GetUpdatedParams(old_nic_params,
9310
                                         update_params_dict)
9311
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
9312
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
9313
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
9314
      self.nic_pinst[nic_op] = new_nic_params
9315
      self.nic_pnew[nic_op] = new_filled_nic_params
9316
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
9317

    
9318
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
9319
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
9320
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
9321
        if msg:
9322
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
9323
          if self.op.force:
9324
            self.warn.append(msg)
9325
          else:
9326
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
9327
      if new_nic_mode == constants.NIC_MODE_ROUTED:
9328
        if 'ip' in nic_dict:
9329
          nic_ip = nic_dict['ip']
9330
        else:
9331
          nic_ip = old_nic_ip
9332
        if nic_ip is None:
9333
          raise errors.OpPrereqError('Cannot set the nic ip to None'
9334
                                     ' on a routed nic', errors.ECODE_INVAL)
9335
      if 'mac' in nic_dict:
9336
        nic_mac = nic_dict['mac']
9337
        if nic_mac is None:
9338
          raise errors.OpPrereqError('Cannot set the nic mac to None',
9339
                                     errors.ECODE_INVAL)
9340
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9341
          # otherwise generate the mac
9342
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
9343
        else:
9344
          # or validate/reserve the current one
9345
          try:
9346
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
9347
          except errors.ReservationError:
9348
            raise errors.OpPrereqError("MAC address %s already in use"
9349
                                       " in cluster" % nic_mac,
9350
                                       errors.ECODE_NOTUNIQUE)
9351

    
9352
    # DISK processing
9353
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
9354
      raise errors.OpPrereqError("Disk operations not supported for"
9355
                                 " diskless instances",
9356
                                 errors.ECODE_INVAL)
9357
    for disk_op, _ in self.op.disks:
9358
      if disk_op == constants.DDM_REMOVE:
9359
        if len(instance.disks) == 1:
9360
          raise errors.OpPrereqError("Cannot remove the last disk of"
9361
                                     " an instance", errors.ECODE_INVAL)
9362
        _CheckInstanceDown(self, instance, "cannot remove disks")
9363

    
9364
      if (disk_op == constants.DDM_ADD and
9365
          len(instance.disks) >= constants.MAX_DISKS):
9366
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
9367
                                   " add more" % constants.MAX_DISKS,
9368
                                   errors.ECODE_STATE)
9369
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
9370
        # an existing disk
9371
        if disk_op < 0 or disk_op >= len(instance.disks):
9372
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9373
                                     " are 0 to %d" %
9374
                                     (disk_op, len(instance.disks)),
9375
                                     errors.ECODE_INVAL)
9376

    
9377
    return
9378

    
9379
  def _ConvertPlainToDrbd(self, feedback_fn):
9380
    """Converts an instance from plain to drbd.
9381

9382
    """
9383
    feedback_fn("Converting template to drbd")
9384
    instance = self.instance
9385
    pnode = instance.primary_node
9386
    snode = self.op.remote_node
9387

    
9388
    # create a fake disk info for _GenerateDiskTemplate
9389
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
9390
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9391
                                      instance.name, pnode, [snode],
9392
                                      disk_info, None, None, 0, feedback_fn)
9393
    info = _GetInstanceInfoText(instance)
9394
    feedback_fn("Creating aditional volumes...")
9395
    # first, create the missing data and meta devices
9396
    for disk in new_disks:
9397
      # unfortunately this is... not too nice
9398
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9399
                            info, True)
9400
      for child in disk.children:
9401
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9402
    # at this stage, all new LVs have been created, we can rename the
9403
    # old ones
9404
    feedback_fn("Renaming original volumes...")
9405
    rename_list = [(o, n.children[0].logical_id)
9406
                   for (o, n) in zip(instance.disks, new_disks)]
9407
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9408
    result.Raise("Failed to rename original LVs")
9409

    
9410
    feedback_fn("Initializing DRBD devices...")
9411
    # all child devices are in place, we can now create the DRBD devices
9412
    for disk in new_disks:
9413
      for node in [pnode, snode]:
9414
        f_create = node == pnode
9415
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9416

    
9417
    # at this point, the instance has been modified
9418
    instance.disk_template = constants.DT_DRBD8
9419
    instance.disks = new_disks
9420
    self.cfg.Update(instance, feedback_fn)
9421

    
9422
    # disks are created, waiting for sync
9423
    disk_abort = not _WaitForSync(self, instance)
9424
    if disk_abort:
9425
      raise errors.OpExecError("There are some degraded disks for"
9426
                               " this instance, please cleanup manually")
9427

    
9428
  def _ConvertDrbdToPlain(self, feedback_fn):
9429
    """Converts an instance from drbd to plain.
9430

9431
    """
9432
    instance = self.instance
9433
    assert len(instance.secondary_nodes) == 1
9434
    pnode = instance.primary_node
9435
    snode = instance.secondary_nodes[0]
9436
    feedback_fn("Converting template to plain")
9437

    
9438
    old_disks = instance.disks
9439
    new_disks = [d.children[0] for d in old_disks]
9440

    
9441
    # copy over size and mode
9442
    for parent, child in zip(old_disks, new_disks):
9443
      child.size = parent.size
9444
      child.mode = parent.mode
9445

    
9446
    # update instance structure
9447
    instance.disks = new_disks
9448
    instance.disk_template = constants.DT_PLAIN
9449
    self.cfg.Update(instance, feedback_fn)
9450

    
9451
    feedback_fn("Removing volumes on the secondary node...")
9452
    for disk in old_disks:
9453
      self.cfg.SetDiskID(disk, snode)
9454
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9455
      if msg:
9456
        self.LogWarning("Could not remove block device %s on node %s,"
9457
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9458

    
9459
    feedback_fn("Removing unneeded volumes on the primary node...")
9460
    for idx, disk in enumerate(old_disks):
9461
      meta = disk.children[1]
9462
      self.cfg.SetDiskID(meta, pnode)
9463
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9464
      if msg:
9465
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9466
                        " continuing anyway: %s", idx, pnode, msg)
9467

    
9468
  def Exec(self, feedback_fn):
9469
    """Modifies an instance.
9470

9471
    All parameters take effect only at the next restart of the instance.
9472

9473
    """
9474
    # Process here the warnings from CheckPrereq, as we don't have a
9475
    # feedback_fn there.
9476
    for warn in self.warn:
9477
      feedback_fn("WARNING: %s" % warn)
9478

    
9479
    result = []
9480
    instance = self.instance
9481
    # disk changes
9482
    for disk_op, disk_dict in self.op.disks:
9483
      if disk_op == constants.DDM_REMOVE:
9484
        # remove the last disk
9485
        device = instance.disks.pop()
9486
        device_idx = len(instance.disks)
9487
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9488
          self.cfg.SetDiskID(disk, node)
9489
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9490
          if msg:
9491
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9492
                            " continuing anyway", device_idx, node, msg)
9493
        result.append(("disk/%d" % device_idx, "remove"))
9494
      elif disk_op == constants.DDM_ADD:
9495
        # add a new disk
9496
        if instance.disk_template == constants.DT_FILE:
9497
          file_driver, file_path = instance.disks[0].logical_id
9498
          file_path = os.path.dirname(file_path)
9499
        else:
9500
          file_driver = file_path = None
9501
        disk_idx_base = len(instance.disks)
9502
        new_disk = _GenerateDiskTemplate(self,
9503
                                         instance.disk_template,
9504
                                         instance.name, instance.primary_node,
9505
                                         instance.secondary_nodes,
9506
                                         [disk_dict],
9507
                                         file_path,
9508
                                         file_driver,
9509
                                         disk_idx_base, feedback_fn)[0]
9510
        instance.disks.append(new_disk)
9511
        info = _GetInstanceInfoText(instance)
9512

    
9513
        logging.info("Creating volume %s for instance %s",
9514
                     new_disk.iv_name, instance.name)
9515
        # Note: this needs to be kept in sync with _CreateDisks
9516
        #HARDCODE
9517
        for node in instance.all_nodes:
9518
          f_create = node == instance.primary_node
9519
          try:
9520
            _CreateBlockDev(self, node, instance, new_disk,
9521
                            f_create, info, f_create)
9522
          except errors.OpExecError, err:
9523
            self.LogWarning("Failed to create volume %s (%s) on"
9524
                            " node %s: %s",
9525
                            new_disk.iv_name, new_disk, node, err)
9526
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9527
                       (new_disk.size, new_disk.mode)))
9528
      else:
9529
        # change a given disk
9530
        instance.disks[disk_op].mode = disk_dict['mode']
9531
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9532

    
9533
    if self.op.disk_template:
9534
      r_shut = _ShutdownInstanceDisks(self, instance)
9535
      if not r_shut:
9536
        raise errors.OpExecError("Cannot shutdown instance disks, unable to"
9537
                                 " proceed with disk template conversion")
9538
      mode = (instance.disk_template, self.op.disk_template)
9539
      try:
9540
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9541
      except:
9542
        self.cfg.ReleaseDRBDMinors(instance.name)
9543
        raise
9544
      result.append(("disk_template", self.op.disk_template))
9545

    
9546
    # NIC changes
9547
    for nic_op, nic_dict in self.op.nics:
9548
      if nic_op == constants.DDM_REMOVE:
9549
        # remove the last nic
9550
        del instance.nics[-1]
9551
        result.append(("nic.%d" % len(instance.nics), "remove"))
9552
      elif nic_op == constants.DDM_ADD:
9553
        # mac and bridge should be set, by now
9554
        mac = nic_dict['mac']
9555
        ip = nic_dict.get('ip', None)
9556
        nicparams = self.nic_pinst[constants.DDM_ADD]
9557
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9558
        instance.nics.append(new_nic)
9559
        result.append(("nic.%d" % (len(instance.nics) - 1),
9560
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9561
                       (new_nic.mac, new_nic.ip,
9562
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9563
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9564
                       )))
9565
      else:
9566
        for key in 'mac', 'ip':
9567
          if key in nic_dict:
9568
            setattr(instance.nics[nic_op], key, nic_dict[key])
9569
        if nic_op in self.nic_pinst:
9570
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9571
        for key, val in nic_dict.iteritems():
9572
          result.append(("nic.%s/%d" % (key, nic_op), val))
9573

    
9574
    # hvparams changes
9575
    if self.op.hvparams:
9576
      instance.hvparams = self.hv_inst
9577
      for key, val in self.op.hvparams.iteritems():
9578
        result.append(("hv/%s" % key, val))
9579

    
9580
    # beparams changes
9581
    if self.op.beparams:
9582
      instance.beparams = self.be_inst
9583
      for key, val in self.op.beparams.iteritems():
9584
        result.append(("be/%s" % key, val))
9585

    
9586
    # OS change
9587
    if self.op.os_name:
9588
      instance.os = self.op.os_name
9589

    
9590
    # osparams changes
9591
    if self.op.osparams:
9592
      instance.osparams = self.os_inst
9593
      for key, val in self.op.osparams.iteritems():
9594
        result.append(("os/%s" % key, val))
9595

    
9596
    self.cfg.Update(instance, feedback_fn)
9597

    
9598
    return result
9599

    
9600
  _DISK_CONVERSIONS = {
9601
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9602
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9603
    }
9604

    
9605

    
9606
class LUBackupQuery(NoHooksLU):
9607
  """Query the exports list
9608

9609
  """
9610
  REQ_BGL = False
9611

    
9612
  def ExpandNames(self):
9613
    self.needed_locks = {}
9614
    self.share_locks[locking.LEVEL_NODE] = 1
9615
    if not self.op.nodes:
9616
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9617
    else:
9618
      self.needed_locks[locking.LEVEL_NODE] = \
9619
        _GetWantedNodes(self, self.op.nodes)
9620

    
9621
  def Exec(self, feedback_fn):
9622
    """Compute the list of all the exported system images.
9623

9624
    @rtype: dict
9625
    @return: a dictionary with the structure node->(export-list)
9626
        where export-list is a list of the instances exported on
9627
        that node.
9628

9629
    """
9630
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9631
    rpcresult = self.rpc.call_export_list(self.nodes)
9632
    result = {}
9633
    for node in rpcresult:
9634
      if rpcresult[node].fail_msg:
9635
        result[node] = False
9636
      else:
9637
        result[node] = rpcresult[node].payload
9638

    
9639
    return result
9640

    
9641

    
9642
class LUBackupPrepare(NoHooksLU):
9643
  """Prepares an instance for an export and returns useful information.
9644

9645
  """
9646
  REQ_BGL = False
9647

    
9648
  def ExpandNames(self):
9649
    self._ExpandAndLockInstance()
9650

    
9651
  def CheckPrereq(self):
9652
    """Check prerequisites.
9653

9654
    """
9655
    instance_name = self.op.instance_name
9656

    
9657
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9658
    assert self.instance is not None, \
9659
          "Cannot retrieve locked instance %s" % self.op.instance_name
9660
    _CheckNodeOnline(self, self.instance.primary_node)
9661

    
9662
    self._cds = _GetClusterDomainSecret()
9663

    
9664
  def Exec(self, feedback_fn):
9665
    """Prepares an instance for an export.
9666

9667
    """
9668
    instance = self.instance
9669

    
9670
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9671
      salt = utils.GenerateSecret(8)
9672

    
9673
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9674
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9675
                                              constants.RIE_CERT_VALIDITY)
9676
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9677

    
9678
      (name, cert_pem) = result.payload
9679

    
9680
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9681
                                             cert_pem)
9682

    
9683
      return {
9684
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9685
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9686
                          salt),
9687
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9688
        }
9689

    
9690
    return None
9691

    
9692

    
9693
class LUBackupExport(LogicalUnit):
9694
  """Export an instance to an image in the cluster.
9695

9696
  """
9697
  HPATH = "instance-export"
9698
  HTYPE = constants.HTYPE_INSTANCE
9699
  REQ_BGL = False
9700

    
9701
  def CheckArguments(self):
9702
    """Check the arguments.
9703

9704
    """
9705
    self.x509_key_name = self.op.x509_key_name
9706
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9707

    
9708
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9709
      if not self.x509_key_name:
9710
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9711
                                   errors.ECODE_INVAL)
9712

    
9713
      if not self.dest_x509_ca_pem:
9714
        raise errors.OpPrereqError("Missing destination X509 CA",
9715
                                   errors.ECODE_INVAL)
9716

    
9717
  def ExpandNames(self):
9718
    self._ExpandAndLockInstance()
9719

    
9720
    # Lock all nodes for local exports
9721
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9722
      # FIXME: lock only instance primary and destination node
9723
      #
9724
      # Sad but true, for now we have do lock all nodes, as we don't know where
9725
      # the previous export might be, and in this LU we search for it and
9726
      # remove it from its current node. In the future we could fix this by:
9727
      #  - making a tasklet to search (share-lock all), then create the
9728
      #    new one, then one to remove, after
9729
      #  - removing the removal operation altogether
9730
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9731

    
9732
  def DeclareLocks(self, level):
9733
    """Last minute lock declaration."""
9734
    # All nodes are locked anyway, so nothing to do here.
9735

    
9736
  def BuildHooksEnv(self):
9737
    """Build hooks env.
9738

9739
    This will run on the master, primary node and target node.
9740

9741
    """
9742
    env = {
9743
      "EXPORT_MODE": self.op.mode,
9744
      "EXPORT_NODE": self.op.target_node,
9745
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9746
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9747
      # TODO: Generic function for boolean env variables
9748
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9749
      }
9750

    
9751
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9752

    
9753
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9754

    
9755
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9756
      nl.append(self.op.target_node)
9757

    
9758
    return env, nl, nl
9759

    
9760
  def CheckPrereq(self):
9761
    """Check prerequisites.
9762

9763
    This checks that the instance and node names are valid.
9764

9765
    """
9766
    instance_name = self.op.instance_name
9767

    
9768
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9769
    assert self.instance is not None, \
9770
          "Cannot retrieve locked instance %s" % self.op.instance_name
9771
    _CheckNodeOnline(self, self.instance.primary_node)
9772

    
9773
    if (self.op.remove_instance and self.instance.admin_up and
9774
        not self.op.shutdown):
9775
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9776
                                 " down before")
9777

    
9778
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9779
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9780
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9781
      assert self.dst_node is not None
9782

    
9783
      _CheckNodeOnline(self, self.dst_node.name)
9784
      _CheckNodeNotDrained(self, self.dst_node.name)
9785

    
9786
      self._cds = None
9787
      self.dest_disk_info = None
9788
      self.dest_x509_ca = None
9789

    
9790
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9791
      self.dst_node = None
9792

    
9793
      if len(self.op.target_node) != len(self.instance.disks):
9794
        raise errors.OpPrereqError(("Received destination information for %s"
9795
                                    " disks, but instance %s has %s disks") %
9796
                                   (len(self.op.target_node), instance_name,
9797
                                    len(self.instance.disks)),
9798
                                   errors.ECODE_INVAL)
9799

    
9800
      cds = _GetClusterDomainSecret()
9801

    
9802
      # Check X509 key name
9803
      try:
9804
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9805
      except (TypeError, ValueError), err:
9806
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9807

    
9808
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9809
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9810
                                   errors.ECODE_INVAL)
9811

    
9812
      # Load and verify CA
9813
      try:
9814
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9815
      except OpenSSL.crypto.Error, err:
9816
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9817
                                   (err, ), errors.ECODE_INVAL)
9818

    
9819
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9820
      if errcode is not None:
9821
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9822
                                   (msg, ), errors.ECODE_INVAL)
9823

    
9824
      self.dest_x509_ca = cert
9825

    
9826
      # Verify target information
9827
      disk_info = []
9828
      for idx, disk_data in enumerate(self.op.target_node):
9829
        try:
9830
          (host, port, magic) = \
9831
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9832
        except errors.GenericError, err:
9833
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9834
                                     (idx, err), errors.ECODE_INVAL)
9835

    
9836
        disk_info.append((host, port, magic))
9837

    
9838
      assert len(disk_info) == len(self.op.target_node)
9839
      self.dest_disk_info = disk_info
9840

    
9841
    else:
9842
      raise errors.ProgrammerError("Unhandled export mode %r" %
9843
                                   self.op.mode)
9844

    
9845
    # instance disk type verification
9846
    # TODO: Implement export support for file-based disks
9847
    for disk in self.instance.disks:
9848
      if disk.dev_type == constants.LD_FILE:
9849
        raise errors.OpPrereqError("Export not supported for instances with"
9850
                                   " file-based disks", errors.ECODE_INVAL)
9851

    
9852
  def _CleanupExports(self, feedback_fn):
9853
    """Removes exports of current instance from all other nodes.
9854

9855
    If an instance in a cluster with nodes A..D was exported to node C, its
9856
    exports will be removed from the nodes A, B and D.
9857

9858
    """
9859
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9860

    
9861
    nodelist = self.cfg.GetNodeList()
9862
    nodelist.remove(self.dst_node.name)
9863

    
9864
    # on one-node clusters nodelist will be empty after the removal
9865
    # if we proceed the backup would be removed because OpBackupQuery
9866
    # substitutes an empty list with the full cluster node list.
9867
    iname = self.instance.name
9868
    if nodelist:
9869
      feedback_fn("Removing old exports for instance %s" % iname)
9870
      exportlist = self.rpc.call_export_list(nodelist)
9871
      for node in exportlist:
9872
        if exportlist[node].fail_msg:
9873
          continue
9874
        if iname in exportlist[node].payload:
9875
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9876
          if msg:
9877
            self.LogWarning("Could not remove older export for instance %s"
9878
                            " on node %s: %s", iname, node, msg)
9879

    
9880
  def Exec(self, feedback_fn):
9881
    """Export an instance to an image in the cluster.
9882

9883
    """
9884
    assert self.op.mode in constants.EXPORT_MODES
9885

    
9886
    instance = self.instance
9887
    src_node = instance.primary_node
9888

    
9889
    if self.op.shutdown:
9890
      # shutdown the instance, but not the disks
9891
      feedback_fn("Shutting down instance %s" % instance.name)
9892
      result = self.rpc.call_instance_shutdown(src_node, instance,
9893
                                               self.op.shutdown_timeout)
9894
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9895
      result.Raise("Could not shutdown instance %s on"
9896
                   " node %s" % (instance.name, src_node))
9897

    
9898
    # set the disks ID correctly since call_instance_start needs the
9899
    # correct drbd minor to create the symlinks
9900
    for disk in instance.disks:
9901
      self.cfg.SetDiskID(disk, src_node)
9902

    
9903
    activate_disks = (not instance.admin_up)
9904

    
9905
    if activate_disks:
9906
      # Activate the instance disks if we'exporting a stopped instance
9907
      feedback_fn("Activating disks for %s" % instance.name)
9908
      _StartInstanceDisks(self, instance, None)
9909

    
9910
    try:
9911
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9912
                                                     instance)
9913

    
9914
      helper.CreateSnapshots()
9915
      try:
9916
        if (self.op.shutdown and instance.admin_up and
9917
            not self.op.remove_instance):
9918
          assert not activate_disks
9919
          feedback_fn("Starting instance %s" % instance.name)
9920
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9921
          msg = result.fail_msg
9922
          if msg:
9923
            feedback_fn("Failed to start instance: %s" % msg)
9924
            _ShutdownInstanceDisks(self, instance)
9925
            raise errors.OpExecError("Could not start instance: %s" % msg)
9926

    
9927
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9928
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9929
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9930
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9931
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9932

    
9933
          (key_name, _, _) = self.x509_key_name
9934

    
9935
          dest_ca_pem = \
9936
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9937
                                            self.dest_x509_ca)
9938

    
9939
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9940
                                                     key_name, dest_ca_pem,
9941
                                                     timeouts)
9942
      finally:
9943
        helper.Cleanup()
9944

    
9945
      # Check for backwards compatibility
9946
      assert len(dresults) == len(instance.disks)
9947
      assert compat.all(isinstance(i, bool) for i in dresults), \
9948
             "Not all results are boolean: %r" % dresults
9949

    
9950
    finally:
9951
      if activate_disks:
9952
        feedback_fn("Deactivating disks for %s" % instance.name)
9953
        _ShutdownInstanceDisks(self, instance)
9954

    
9955
    if not (compat.all(dresults) and fin_resu):
9956
      failures = []
9957
      if not fin_resu:
9958
        failures.append("export finalization")
9959
      if not compat.all(dresults):
9960
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
9961
                               if not dsk)
9962
        failures.append("disk export: disk(s) %s" % fdsk)
9963

    
9964
      raise errors.OpExecError("Export failed, errors in %s" %
9965
                               utils.CommaJoin(failures))
9966

    
9967
    # At this point, the export was successful, we can cleanup/finish
9968

    
9969
    # Remove instance if requested
9970
    if self.op.remove_instance:
9971
      feedback_fn("Removing instance %s" % instance.name)
9972
      _RemoveInstance(self, feedback_fn, instance,
9973
                      self.op.ignore_remove_failures)
9974

    
9975
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9976
      self._CleanupExports(feedback_fn)
9977

    
9978
    return fin_resu, dresults
9979

    
9980

    
9981
class LUBackupRemove(NoHooksLU):
9982
  """Remove exports related to the named instance.
9983

9984
  """
9985
  REQ_BGL = False
9986

    
9987
  def ExpandNames(self):
9988
    self.needed_locks = {}
9989
    # We need all nodes to be locked in order for RemoveExport to work, but we
9990
    # don't need to lock the instance itself, as nothing will happen to it (and
9991
    # we can remove exports also for a removed instance)
9992
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9993

    
9994
  def Exec(self, feedback_fn):
9995
    """Remove any export.
9996

9997
    """
9998
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9999
    # If the instance was not found we'll try with the name that was passed in.
10000
    # This will only work if it was an FQDN, though.
10001
    fqdn_warn = False
10002
    if not instance_name:
10003
      fqdn_warn = True
10004
      instance_name = self.op.instance_name
10005

    
10006
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
10007
    exportlist = self.rpc.call_export_list(locked_nodes)
10008
    found = False
10009
    for node in exportlist:
10010
      msg = exportlist[node].fail_msg
10011
      if msg:
10012
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
10013
        continue
10014
      if instance_name in exportlist[node].payload:
10015
        found = True
10016
        result = self.rpc.call_export_remove(node, instance_name)
10017
        msg = result.fail_msg
10018
        if msg:
10019
          logging.error("Could not remove export for instance %s"
10020
                        " on node %s: %s", instance_name, node, msg)
10021

    
10022
    if fqdn_warn and not found:
10023
      feedback_fn("Export not found. If trying to remove an export belonging"
10024
                  " to a deleted instance please use its Fully Qualified"
10025
                  " Domain Name.")
10026

    
10027

    
10028
class LUGroupAdd(LogicalUnit):
10029
  """Logical unit for creating node groups.
10030

10031
  """
10032
  HPATH = "group-add"
10033
  HTYPE = constants.HTYPE_GROUP
10034
  REQ_BGL = False
10035

    
10036
  def ExpandNames(self):
10037
    # We need the new group's UUID here so that we can create and acquire the
10038
    # corresponding lock. Later, in Exec(), we'll indicate to cfg.AddNodeGroup
10039
    # that it should not check whether the UUID exists in the configuration.
10040
    self.group_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
10041
    self.needed_locks = {}
10042
    self.add_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
10043

    
10044
  def CheckPrereq(self):
10045
    """Check prerequisites.
10046

10047
    This checks that the given group name is not an existing node group
10048
    already.
10049

10050
    """
10051
    try:
10052
      existing_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10053
    except errors.OpPrereqError:
10054
      pass
10055
    else:
10056
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
10057
                                 " node group (UUID: %s)" %
10058
                                 (self.op.group_name, existing_uuid),
10059
                                 errors.ECODE_EXISTS)
10060

    
10061
    if self.op.ndparams:
10062
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
10063

    
10064
  def BuildHooksEnv(self):
10065
    """Build hooks env.
10066

10067
    """
10068
    env = {
10069
      "GROUP_NAME": self.op.group_name,
10070
      }
10071
    mn = self.cfg.GetMasterNode()
10072
    return env, [mn], [mn]
10073

    
10074
  def Exec(self, feedback_fn):
10075
    """Add the node group to the cluster.
10076

10077
    """
10078
    group_obj = objects.NodeGroup(name=self.op.group_name, members=[],
10079
                                  uuid=self.group_uuid,
10080
                                  alloc_policy=self.op.alloc_policy,
10081
                                  ndparams=self.op.ndparams)
10082

    
10083
    self.cfg.AddNodeGroup(group_obj, self.proc.GetECId(), check_uuid=False)
10084
    del self.remove_locks[locking.LEVEL_NODEGROUP]
10085

    
10086

    
10087
class LUGroupAssignNodes(NoHooksLU):
10088
  """Logical unit for assigning nodes to groups.
10089

10090
  """
10091
  REQ_BGL = False
10092

    
10093
  def ExpandNames(self):
10094
    # These raise errors.OpPrereqError on their own:
10095
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10096
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
10097

    
10098
    # We want to lock all the affected nodes and groups. We have readily
10099
    # available the list of nodes, and the *destination* group. To gather the
10100
    # list of "source" groups, we need to fetch node information.
10101
    self.node_data = self.cfg.GetAllNodesInfo()
10102
    affected_groups = set(self.node_data[node].group for node in self.op.nodes)
10103
    affected_groups.add(self.group_uuid)
10104

    
10105
    self.needed_locks = {
10106
      locking.LEVEL_NODEGROUP: list(affected_groups),
10107
      locking.LEVEL_NODE: self.op.nodes,
10108
      }
10109

    
10110
  def CheckPrereq(self):
10111
    """Check prerequisites.
10112

10113
    """
10114
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
10115
    instance_data = self.cfg.GetAllInstancesInfo()
10116

    
10117
    if self.group is None:
10118
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10119
                               (self.op.group_name, self.group_uuid))
10120

    
10121
    (new_splits, previous_splits) = \
10122
      self.CheckAssignmentForSplitInstances([(node, self.group_uuid)
10123
                                             for node in self.op.nodes],
10124
                                            self.node_data, instance_data)
10125

    
10126
    if new_splits:
10127
      fmt_new_splits = utils.CommaJoin(utils.NiceSort(new_splits))
10128

    
10129
      if not self.op.force:
10130
        raise errors.OpExecError("The following instances get split by this"
10131
                                 " change and --force was not given: %s" %
10132
                                 fmt_new_splits)
10133
      else:
10134
        self.LogWarning("This operation will split the following instances: %s",
10135
                        fmt_new_splits)
10136

    
10137
        if previous_splits:
10138
          self.LogWarning("In addition, these already-split instances continue"
10139
                          " to be spit across groups: %s",
10140
                          utils.CommaJoin(utils.NiceSort(previous_splits)))
10141

    
10142
  def Exec(self, feedback_fn):
10143
    """Assign nodes to a new group.
10144

10145
    """
10146
    for node in self.op.nodes:
10147
      self.node_data[node].group = self.group_uuid
10148

    
10149
    self.cfg.Update(self.group, feedback_fn) # Saves all modified nodes.
10150

    
10151
  @staticmethod
10152
  def CheckAssignmentForSplitInstances(changes, node_data, instance_data):
10153
    """Check for split instances after a node assignment.
10154

10155
    This method considers a series of node assignments as an atomic operation,
10156
    and returns information about split instances after applying the set of
10157
    changes.
10158

10159
    In particular, it returns information about newly split instances, and
10160
    instances that were already split, and remain so after the change.
10161

10162
    Only instances whose disk template is listed in constants.DTS_NET_MIRROR are
10163
    considered.
10164

10165
    @type changes: list of (node_name, new_group_uuid) pairs.
10166
    @param changes: list of node assignments to consider.
10167
    @param node_data: a dict with data for all nodes
10168
    @param instance_data: a dict with all instances to consider
10169
    @rtype: a two-tuple
10170
    @return: a list of instances that were previously okay and result split as a
10171
      consequence of this change, and a list of instances that were previously
10172
      split and this change does not fix.
10173

10174
    """
10175
    changed_nodes = dict((node, group) for node, group in changes
10176
                         if node_data[node].group != group)
10177

    
10178
    all_split_instances = set()
10179
    previously_split_instances = set()
10180

    
10181
    def InstanceNodes(instance):
10182
      return [instance.primary_node] + list(instance.secondary_nodes)
10183

    
10184
    for inst in instance_data.values():
10185
      if inst.disk_template not in constants.DTS_NET_MIRROR:
10186
        continue
10187

    
10188
      instance_nodes = InstanceNodes(inst)
10189

    
10190
      if len(set(node_data[node].group for node in instance_nodes)) > 1:
10191
        previously_split_instances.add(inst.name)
10192

    
10193
      if len(set(changed_nodes.get(node, node_data[node].group)
10194
                 for node in instance_nodes)) > 1:
10195
        all_split_instances.add(inst.name)
10196

    
10197
    return (list(all_split_instances - previously_split_instances),
10198
            list(previously_split_instances & all_split_instances))
10199

    
10200

    
10201
class _GroupQuery(_QueryBase):
10202

    
10203
  FIELDS = query.GROUP_FIELDS
10204

    
10205
  def ExpandNames(self, lu):
10206
    lu.needed_locks = {}
10207

    
10208
    self._all_groups = lu.cfg.GetAllNodeGroupsInfo()
10209
    name_to_uuid = dict((g.name, g.uuid) for g in self._all_groups.values())
10210

    
10211
    if not self.names:
10212
      self.wanted = [name_to_uuid[name]
10213
                     for name in utils.NiceSort(name_to_uuid.keys())]
10214
    else:
10215
      # Accept names to be either names or UUIDs.
10216
      missing = []
10217
      self.wanted = []
10218
      all_uuid = frozenset(self._all_groups.keys())
10219

    
10220
      for name in self.names:
10221
        if name in all_uuid:
10222
          self.wanted.append(name)
10223
        elif name in name_to_uuid:
10224
          self.wanted.append(name_to_uuid[name])
10225
        else:
10226
          missing.append(name)
10227

    
10228
      if missing:
10229
        raise errors.OpPrereqError("Some groups do not exist: %s" % missing,
10230
                                   errors.ECODE_NOENT)
10231

    
10232
  def DeclareLocks(self, lu, level):
10233
    pass
10234

    
10235
  def _GetQueryData(self, lu):
10236
    """Computes the list of node groups and their attributes.
10237

10238
    """
10239
    do_nodes = query.GQ_NODE in self.requested_data
10240
    do_instances = query.GQ_INST in self.requested_data
10241

    
10242
    group_to_nodes = None
10243
    group_to_instances = None
10244

    
10245
    # For GQ_NODE, we need to map group->[nodes], and group->[instances] for
10246
    # GQ_INST. The former is attainable with just GetAllNodesInfo(), but for the
10247
    # latter GetAllInstancesInfo() is not enough, for we have to go through
10248
    # instance->node. Hence, we will need to process nodes even if we only need
10249
    # instance information.
10250
    if do_nodes or do_instances:
10251
      all_nodes = lu.cfg.GetAllNodesInfo()
10252
      group_to_nodes = dict((uuid, []) for uuid in self.wanted)
10253
      node_to_group = {}
10254

    
10255
      for node in all_nodes.values():
10256
        if node.group in group_to_nodes:
10257
          group_to_nodes[node.group].append(node.name)
10258
          node_to_group[node.name] = node.group
10259

    
10260
      if do_instances:
10261
        all_instances = lu.cfg.GetAllInstancesInfo()
10262
        group_to_instances = dict((uuid, []) for uuid in self.wanted)
10263

    
10264
        for instance in all_instances.values():
10265
          node = instance.primary_node
10266
          if node in node_to_group:
10267
            group_to_instances[node_to_group[node]].append(instance.name)
10268

    
10269
        if not do_nodes:
10270
          # Do not pass on node information if it was not requested.
10271
          group_to_nodes = None
10272

    
10273
    return query.GroupQueryData([self._all_groups[uuid]
10274
                                 for uuid in self.wanted],
10275
                                group_to_nodes, group_to_instances)
10276

    
10277

    
10278
class LUGroupQuery(NoHooksLU):
10279
  """Logical unit for querying node groups.
10280

10281
  """
10282
  REQ_BGL = False
10283

    
10284
  def CheckArguments(self):
10285
    self.gq = _GroupQuery(self.op.names, self.op.output_fields, False)
10286

    
10287
  def ExpandNames(self):
10288
    self.gq.ExpandNames(self)
10289

    
10290
  def Exec(self, feedback_fn):
10291
    return self.gq.OldStyleQuery(self)
10292

    
10293

    
10294
class LUGroupSetParams(LogicalUnit):
10295
  """Modifies the parameters of a node group.
10296

10297
  """
10298
  HPATH = "group-modify"
10299
  HTYPE = constants.HTYPE_GROUP
10300
  REQ_BGL = False
10301

    
10302
  def CheckArguments(self):
10303
    all_changes = [
10304
      self.op.ndparams,
10305
      self.op.alloc_policy,
10306
      ]
10307

    
10308
    if all_changes.count(None) == len(all_changes):
10309
      raise errors.OpPrereqError("Please pass at least one modification",
10310
                                 errors.ECODE_INVAL)
10311

    
10312
  def ExpandNames(self):
10313
    # This raises errors.OpPrereqError on its own:
10314
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10315

    
10316
    self.needed_locks = {
10317
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10318
      }
10319

    
10320
  def CheckPrereq(self):
10321
    """Check prerequisites.
10322

10323
    """
10324
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
10325

    
10326
    if self.group is None:
10327
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10328
                               (self.op.group_name, self.group_uuid))
10329

    
10330
    if self.op.ndparams:
10331
      new_ndparams = _GetUpdatedParams(self.group.ndparams, self.op.ndparams)
10332
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
10333
      self.new_ndparams = new_ndparams
10334

    
10335
  def BuildHooksEnv(self):
10336
    """Build hooks env.
10337

10338
    """
10339
    env = {
10340
      "GROUP_NAME": self.op.group_name,
10341
      "NEW_ALLOC_POLICY": self.op.alloc_policy,
10342
      }
10343
    mn = self.cfg.GetMasterNode()
10344
    return env, [mn], [mn]
10345

    
10346
  def Exec(self, feedback_fn):
10347
    """Modifies the node group.
10348

10349
    """
10350
    result = []
10351

    
10352
    if self.op.ndparams:
10353
      self.group.ndparams = self.new_ndparams
10354
      result.append(("ndparams", str(self.group.ndparams)))
10355

    
10356
    if self.op.alloc_policy:
10357
      self.group.alloc_policy = self.op.alloc_policy
10358

    
10359
    self.cfg.Update(self.group, feedback_fn)
10360
    return result
10361

    
10362

    
10363

    
10364
class LUGroupRemove(LogicalUnit):
10365
  HPATH = "group-remove"
10366
  HTYPE = constants.HTYPE_GROUP
10367
  REQ_BGL = False
10368

    
10369
  def ExpandNames(self):
10370
    # This will raises errors.OpPrereqError on its own:
10371
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10372
    self.needed_locks = {
10373
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10374
      }
10375

    
10376
  def CheckPrereq(self):
10377
    """Check prerequisites.
10378

10379
    This checks that the given group name exists as a node group, that is
10380
    empty (i.e., contains no nodes), and that is not the last group of the
10381
    cluster.
10382

10383
    """
10384
    # Verify that the group is empty.
10385
    group_nodes = [node.name
10386
                   for node in self.cfg.GetAllNodesInfo().values()
10387
                   if node.group == self.group_uuid]
10388

    
10389
    if group_nodes:
10390
      raise errors.OpPrereqError("Group '%s' not empty, has the following"
10391
                                 " nodes: %s" %
10392
                                 (self.op.group_name,
10393
                                  utils.CommaJoin(utils.NiceSort(group_nodes))),
10394
                                 errors.ECODE_STATE)
10395

    
10396
    # Verify the cluster would not be left group-less.
10397
    if len(self.cfg.GetNodeGroupList()) == 1:
10398
      raise errors.OpPrereqError("Group '%s' is the only group,"
10399
                                 " cannot be removed" %
10400
                                 self.op.group_name,
10401
                                 errors.ECODE_STATE)
10402

    
10403
  def BuildHooksEnv(self):
10404
    """Build hooks env.
10405

10406
    """
10407
    env = {
10408
      "GROUP_NAME": self.op.group_name,
10409
      }
10410
    mn = self.cfg.GetMasterNode()
10411
    return env, [mn], [mn]
10412

    
10413
  def Exec(self, feedback_fn):
10414
    """Remove the node group.
10415

10416
    """
10417
    try:
10418
      self.cfg.RemoveNodeGroup(self.group_uuid)
10419
    except errors.ConfigurationError:
10420
      raise errors.OpExecError("Group '%s' with UUID %s disappeared" %
10421
                               (self.op.group_name, self.group_uuid))
10422

    
10423
    self.remove_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
10424

    
10425

    
10426
class LUGroupRename(LogicalUnit):
10427
  HPATH = "group-rename"
10428
  HTYPE = constants.HTYPE_GROUP
10429
  REQ_BGL = False
10430

    
10431
  def ExpandNames(self):
10432
    # This raises errors.OpPrereqError on its own:
10433
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.old_name)
10434

    
10435
    self.needed_locks = {
10436
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10437
      }
10438

    
10439
  def CheckPrereq(self):
10440
    """Check prerequisites.
10441

10442
    This checks that the given old_name exists as a node group, and that
10443
    new_name doesn't.
10444

10445
    """
10446
    try:
10447
      new_name_uuid = self.cfg.LookupNodeGroup(self.op.new_name)
10448
    except errors.OpPrereqError:
10449
      pass
10450
    else:
10451
      raise errors.OpPrereqError("Desired new name '%s' clashes with existing"
10452
                                 " node group (UUID: %s)" %
10453
                                 (self.op.new_name, new_name_uuid),
10454
                                 errors.ECODE_EXISTS)
10455

    
10456
  def BuildHooksEnv(self):
10457
    """Build hooks env.
10458

10459
    """
10460
    env = {
10461
      "OLD_NAME": self.op.old_name,
10462
      "NEW_NAME": self.op.new_name,
10463
      }
10464

    
10465
    mn = self.cfg.GetMasterNode()
10466
    all_nodes = self.cfg.GetAllNodesInfo()
10467
    run_nodes = [mn]
10468
    all_nodes.pop(mn, None)
10469

    
10470
    for node in all_nodes.values():
10471
      if node.group == self.group_uuid:
10472
        run_nodes.append(node.name)
10473

    
10474
    return env, run_nodes, run_nodes
10475

    
10476
  def Exec(self, feedback_fn):
10477
    """Rename the node group.
10478

10479
    """
10480
    group = self.cfg.GetNodeGroup(self.group_uuid)
10481

    
10482
    if group is None:
10483
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10484
                               (self.op.old_name, self.group_uuid))
10485

    
10486
    group.name = self.op.new_name
10487
    self.cfg.Update(group, feedback_fn)
10488

    
10489
    return self.op.new_name
10490

    
10491

    
10492
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
10493
  """Generic tags LU.
10494

10495
  This is an abstract class which is the parent of all the other tags LUs.
10496

10497
  """
10498

    
10499
  def ExpandNames(self):
10500
    self.needed_locks = {}
10501
    if self.op.kind == constants.TAG_NODE:
10502
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
10503
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
10504
    elif self.op.kind == constants.TAG_INSTANCE:
10505
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
10506
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
10507

    
10508
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
10509
    # not possible to acquire the BGL based on opcode parameters)
10510

    
10511
  def CheckPrereq(self):
10512
    """Check prerequisites.
10513

10514
    """
10515
    if self.op.kind == constants.TAG_CLUSTER:
10516
      self.target = self.cfg.GetClusterInfo()
10517
    elif self.op.kind == constants.TAG_NODE:
10518
      self.target = self.cfg.GetNodeInfo(self.op.name)
10519
    elif self.op.kind == constants.TAG_INSTANCE:
10520
      self.target = self.cfg.GetInstanceInfo(self.op.name)
10521
    else:
10522
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
10523
                                 str(self.op.kind), errors.ECODE_INVAL)
10524

    
10525

    
10526
class LUTagsGet(TagsLU):
10527
  """Returns the tags of a given object.
10528

10529
  """
10530
  REQ_BGL = False
10531

    
10532
  def ExpandNames(self):
10533
    TagsLU.ExpandNames(self)
10534

    
10535
    # Share locks as this is only a read operation
10536
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
10537

    
10538
  def Exec(self, feedback_fn):
10539
    """Returns the tag list.
10540

10541
    """
10542
    return list(self.target.GetTags())
10543

    
10544

    
10545
class LUTagsSearch(NoHooksLU):
10546
  """Searches the tags for a given pattern.
10547

10548
  """
10549
  REQ_BGL = False
10550

    
10551
  def ExpandNames(self):
10552
    self.needed_locks = {}
10553

    
10554
  def CheckPrereq(self):
10555
    """Check prerequisites.
10556

10557
    This checks the pattern passed for validity by compiling it.
10558

10559
    """
10560
    try:
10561
      self.re = re.compile(self.op.pattern)
10562
    except re.error, err:
10563
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
10564
                                 (self.op.pattern, err), errors.ECODE_INVAL)
10565

    
10566
  def Exec(self, feedback_fn):
10567
    """Returns the tag list.
10568

10569
    """
10570
    cfg = self.cfg
10571
    tgts = [("/cluster", cfg.GetClusterInfo())]
10572
    ilist = cfg.GetAllInstancesInfo().values()
10573
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
10574
    nlist = cfg.GetAllNodesInfo().values()
10575
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
10576
    results = []
10577
    for path, target in tgts:
10578
      for tag in target.GetTags():
10579
        if self.re.search(tag):
10580
          results.append((path, tag))
10581
    return results
10582

    
10583

    
10584
class LUTagsSet(TagsLU):
10585
  """Sets a tag on a given object.
10586

10587
  """
10588
  REQ_BGL = False
10589

    
10590
  def CheckPrereq(self):
10591
    """Check prerequisites.
10592

10593
    This checks the type and length of the tag name and value.
10594

10595
    """
10596
    TagsLU.CheckPrereq(self)
10597
    for tag in self.op.tags:
10598
      objects.TaggableObject.ValidateTag(tag)
10599

    
10600
  def Exec(self, feedback_fn):
10601
    """Sets the tag.
10602

10603
    """
10604
    try:
10605
      for tag in self.op.tags:
10606
        self.target.AddTag(tag)
10607
    except errors.TagError, err:
10608
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
10609
    self.cfg.Update(self.target, feedback_fn)
10610

    
10611

    
10612
class LUTagsDel(TagsLU):
10613
  """Delete a list of tags from a given object.
10614

10615
  """
10616
  REQ_BGL = False
10617

    
10618
  def CheckPrereq(self):
10619
    """Check prerequisites.
10620

10621
    This checks that we have the given tag.
10622

10623
    """
10624
    TagsLU.CheckPrereq(self)
10625
    for tag in self.op.tags:
10626
      objects.TaggableObject.ValidateTag(tag)
10627
    del_tags = frozenset(self.op.tags)
10628
    cur_tags = self.target.GetTags()
10629

    
10630
    diff_tags = del_tags - cur_tags
10631
    if diff_tags:
10632
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
10633
      raise errors.OpPrereqError("Tag(s) %s not found" %
10634
                                 (utils.CommaJoin(diff_names), ),
10635
                                 errors.ECODE_NOENT)
10636

    
10637
  def Exec(self, feedback_fn):
10638
    """Remove the tag from the object.
10639

10640
    """
10641
    for tag in self.op.tags:
10642
      self.target.RemoveTag(tag)
10643
    self.cfg.Update(self.target, feedback_fn)
10644

    
10645

    
10646
class LUTestDelay(NoHooksLU):
10647
  """Sleep for a specified amount of time.
10648

10649
  This LU sleeps on the master and/or nodes for a specified amount of
10650
  time.
10651

10652
  """
10653
  REQ_BGL = False
10654

    
10655
  def ExpandNames(self):
10656
    """Expand names and set required locks.
10657

10658
    This expands the node list, if any.
10659

10660
    """
10661
    self.needed_locks = {}
10662
    if self.op.on_nodes:
10663
      # _GetWantedNodes can be used here, but is not always appropriate to use
10664
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
10665
      # more information.
10666
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
10667
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
10668

    
10669
  def _TestDelay(self):
10670
    """Do the actual sleep.
10671

10672
    """
10673
    if self.op.on_master:
10674
      if not utils.TestDelay(self.op.duration):
10675
        raise errors.OpExecError("Error during master delay test")
10676
    if self.op.on_nodes:
10677
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
10678
      for node, node_result in result.items():
10679
        node_result.Raise("Failure during rpc call to node %s" % node)
10680

    
10681
  def Exec(self, feedback_fn):
10682
    """Execute the test delay opcode, with the wanted repetitions.
10683

10684
    """
10685
    if self.op.repeat == 0:
10686
      self._TestDelay()
10687
    else:
10688
      top_value = self.op.repeat - 1
10689
      for i in range(self.op.repeat):
10690
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
10691
        self._TestDelay()
10692

    
10693

    
10694
class LUTestJqueue(NoHooksLU):
10695
  """Utility LU to test some aspects of the job queue.
10696

10697
  """
10698
  REQ_BGL = False
10699

    
10700
  # Must be lower than default timeout for WaitForJobChange to see whether it
10701
  # notices changed jobs
10702
  _CLIENT_CONNECT_TIMEOUT = 20.0
10703
  _CLIENT_CONFIRM_TIMEOUT = 60.0
10704

    
10705
  @classmethod
10706
  def _NotifyUsingSocket(cls, cb, errcls):
10707
    """Opens a Unix socket and waits for another program to connect.
10708

10709
    @type cb: callable
10710
    @param cb: Callback to send socket name to client
10711
    @type errcls: class
10712
    @param errcls: Exception class to use for errors
10713

10714
    """
10715
    # Using a temporary directory as there's no easy way to create temporary
10716
    # sockets without writing a custom loop around tempfile.mktemp and
10717
    # socket.bind
10718
    tmpdir = tempfile.mkdtemp()
10719
    try:
10720
      tmpsock = utils.PathJoin(tmpdir, "sock")
10721

    
10722
      logging.debug("Creating temporary socket at %s", tmpsock)
10723
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
10724
      try:
10725
        sock.bind(tmpsock)
10726
        sock.listen(1)
10727

    
10728
        # Send details to client
10729
        cb(tmpsock)
10730

    
10731
        # Wait for client to connect before continuing
10732
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
10733
        try:
10734
          (conn, _) = sock.accept()
10735
        except socket.error, err:
10736
          raise errcls("Client didn't connect in time (%s)" % err)
10737
      finally:
10738
        sock.close()
10739
    finally:
10740
      # Remove as soon as client is connected
10741
      shutil.rmtree(tmpdir)
10742

    
10743
    # Wait for client to close
10744
    try:
10745
      try:
10746
        # pylint: disable-msg=E1101
10747
        # Instance of '_socketobject' has no ... member
10748
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
10749
        conn.recv(1)
10750
      except socket.error, err:
10751
        raise errcls("Client failed to confirm notification (%s)" % err)
10752
    finally:
10753
      conn.close()
10754

    
10755
  def _SendNotification(self, test, arg, sockname):
10756
    """Sends a notification to the client.
10757

10758
    @type test: string
10759
    @param test: Test name
10760
    @param arg: Test argument (depends on test)
10761
    @type sockname: string
10762
    @param sockname: Socket path
10763

10764
    """
10765
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
10766

    
10767
  def _Notify(self, prereq, test, arg):
10768
    """Notifies the client of a test.
10769

10770
    @type prereq: bool
10771
    @param prereq: Whether this is a prereq-phase test
10772
    @type test: string
10773
    @param test: Test name
10774
    @param arg: Test argument (depends on test)
10775

10776
    """
10777
    if prereq:
10778
      errcls = errors.OpPrereqError
10779
    else:
10780
      errcls = errors.OpExecError
10781

    
10782
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
10783
                                                  test, arg),
10784
                                   errcls)
10785

    
10786
  def CheckArguments(self):
10787
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
10788
    self.expandnames_calls = 0
10789

    
10790
  def ExpandNames(self):
10791
    checkargs_calls = getattr(self, "checkargs_calls", 0)
10792
    if checkargs_calls < 1:
10793
      raise errors.ProgrammerError("CheckArguments was not called")
10794

    
10795
    self.expandnames_calls += 1
10796

    
10797
    if self.op.notify_waitlock:
10798
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
10799

    
10800
    self.LogInfo("Expanding names")
10801

    
10802
    # Get lock on master node (just to get a lock, not for a particular reason)
10803
    self.needed_locks = {
10804
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
10805
      }
10806

    
10807
  def Exec(self, feedback_fn):
10808
    if self.expandnames_calls < 1:
10809
      raise errors.ProgrammerError("ExpandNames was not called")
10810

    
10811
    if self.op.notify_exec:
10812
      self._Notify(False, constants.JQT_EXEC, None)
10813

    
10814
    self.LogInfo("Executing")
10815

    
10816
    if self.op.log_messages:
10817
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
10818
      for idx, msg in enumerate(self.op.log_messages):
10819
        self.LogInfo("Sending log message %s", idx + 1)
10820
        feedback_fn(constants.JQT_MSGPREFIX + msg)
10821
        # Report how many test messages have been sent
10822
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
10823

    
10824
    if self.op.fail:
10825
      raise errors.OpExecError("Opcode failure was requested")
10826

    
10827
    return True
10828

    
10829

    
10830
class IAllocator(object):
10831
  """IAllocator framework.
10832

10833
  An IAllocator instance has three sets of attributes:
10834
    - cfg that is needed to query the cluster
10835
    - input data (all members of the _KEYS class attribute are required)
10836
    - four buffer attributes (in|out_data|text), that represent the
10837
      input (to the external script) in text and data structure format,
10838
      and the output from it, again in two formats
10839
    - the result variables from the script (success, info, nodes) for
10840
      easy usage
10841

10842
  """
10843
  # pylint: disable-msg=R0902
10844
  # lots of instance attributes
10845
  _ALLO_KEYS = [
10846
    "name", "mem_size", "disks", "disk_template",
10847
    "os", "tags", "nics", "vcpus", "hypervisor",
10848
    ]
10849
  _RELO_KEYS = [
10850
    "name", "relocate_from",
10851
    ]
10852
  _EVAC_KEYS = [
10853
    "evac_nodes",
10854
    ]
10855

    
10856
  def __init__(self, cfg, rpc, mode, **kwargs):
10857
    self.cfg = cfg
10858
    self.rpc = rpc
10859
    # init buffer variables
10860
    self.in_text = self.out_text = self.in_data = self.out_data = None
10861
    # init all input fields so that pylint is happy
10862
    self.mode = mode
10863
    self.mem_size = self.disks = self.disk_template = None
10864
    self.os = self.tags = self.nics = self.vcpus = None
10865
    self.hypervisor = None
10866
    self.relocate_from = None
10867
    self.name = None
10868
    self.evac_nodes = None
10869
    # computed fields
10870
    self.required_nodes = None
10871
    # init result fields
10872
    self.success = self.info = self.result = None
10873
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10874
      keyset = self._ALLO_KEYS
10875
      fn = self._AddNewInstance
10876
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10877
      keyset = self._RELO_KEYS
10878
      fn = self._AddRelocateInstance
10879
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10880
      keyset = self._EVAC_KEYS
10881
      fn = self._AddEvacuateNodes
10882
    else:
10883
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
10884
                                   " IAllocator" % self.mode)
10885
    for key in kwargs:
10886
      if key not in keyset:
10887
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
10888
                                     " IAllocator" % key)
10889
      setattr(self, key, kwargs[key])
10890

    
10891
    for key in keyset:
10892
      if key not in kwargs:
10893
        raise errors.ProgrammerError("Missing input parameter '%s' to"
10894
                                     " IAllocator" % key)
10895
    self._BuildInputData(fn)
10896

    
10897
  def _ComputeClusterData(self):
10898
    """Compute the generic allocator input data.
10899

10900
    This is the data that is independent of the actual operation.
10901

10902
    """
10903
    cfg = self.cfg
10904
    cluster_info = cfg.GetClusterInfo()
10905
    # cluster data
10906
    data = {
10907
      "version": constants.IALLOCATOR_VERSION,
10908
      "cluster_name": cfg.GetClusterName(),
10909
      "cluster_tags": list(cluster_info.GetTags()),
10910
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
10911
      # we don't have job IDs
10912
      }
10913
    ninfo = cfg.GetAllNodesInfo()
10914
    iinfo = cfg.GetAllInstancesInfo().values()
10915
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
10916

    
10917
    # node data
10918
    node_list = [n.name for n in ninfo.values() if n.vm_capable]
10919

    
10920
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10921
      hypervisor_name = self.hypervisor
10922
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10923
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
10924
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10925
      hypervisor_name = cluster_info.enabled_hypervisors[0]
10926

    
10927
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
10928
                                        hypervisor_name)
10929
    node_iinfo = \
10930
      self.rpc.call_all_instances_info(node_list,
10931
                                       cluster_info.enabled_hypervisors)
10932

    
10933
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
10934

    
10935
    config_ndata = self._ComputeBasicNodeData(ninfo)
10936
    data["nodes"] = self._ComputeDynamicNodeData(ninfo, node_data, node_iinfo,
10937
                                                 i_list, config_ndata)
10938
    assert len(data["nodes"]) == len(ninfo), \
10939
        "Incomplete node data computed"
10940

    
10941
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
10942

    
10943
    self.in_data = data
10944

    
10945
  @staticmethod
10946
  def _ComputeNodeGroupData(cfg):
10947
    """Compute node groups data.
10948

10949
    """
10950
    ng = {}
10951
    for guuid, gdata in cfg.GetAllNodeGroupsInfo().items():
10952
      ng[guuid] = {
10953
        "name": gdata.name,
10954
        "alloc_policy": gdata.alloc_policy,
10955
        }
10956
    return ng
10957

    
10958
  @staticmethod
10959
  def _ComputeBasicNodeData(node_cfg):
10960
    """Compute global node data.
10961

10962
    @rtype: dict
10963
    @returns: a dict of name: (node dict, node config)
10964

10965
    """
10966
    node_results = {}
10967
    for ninfo in node_cfg.values():
10968
      # fill in static (config-based) values
10969
      pnr = {
10970
        "tags": list(ninfo.GetTags()),
10971
        "primary_ip": ninfo.primary_ip,
10972
        "secondary_ip": ninfo.secondary_ip,
10973
        "offline": ninfo.offline,
10974
        "drained": ninfo.drained,
10975
        "master_candidate": ninfo.master_candidate,
10976
        "group": ninfo.group,
10977
        "master_capable": ninfo.master_capable,
10978
        "vm_capable": ninfo.vm_capable,
10979
        }
10980

    
10981
      node_results[ninfo.name] = pnr
10982

    
10983
    return node_results
10984

    
10985
  @staticmethod
10986
  def _ComputeDynamicNodeData(node_cfg, node_data, node_iinfo, i_list,
10987
                              node_results):
10988
    """Compute global node data.
10989

10990
    @param node_results: the basic node structures as filled from the config
10991

10992
    """
10993
    # make a copy of the current dict
10994
    node_results = dict(node_results)
10995
    for nname, nresult in node_data.items():
10996
      assert nname in node_results, "Missing basic data for node %s" % nname
10997
      ninfo = node_cfg[nname]
10998

    
10999
      if not (ninfo.offline or ninfo.drained):
11000
        nresult.Raise("Can't get data for node %s" % nname)
11001
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
11002
                                nname)
11003
        remote_info = nresult.payload
11004

    
11005
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
11006
                     'vg_size', 'vg_free', 'cpu_total']:
11007
          if attr not in remote_info:
11008
            raise errors.OpExecError("Node '%s' didn't return attribute"
11009
                                     " '%s'" % (nname, attr))
11010
          if not isinstance(remote_info[attr], int):
11011
            raise errors.OpExecError("Node '%s' returned invalid value"
11012
                                     " for '%s': %s" %
11013
                                     (nname, attr, remote_info[attr]))
11014
        # compute memory used by primary instances
11015
        i_p_mem = i_p_up_mem = 0
11016
        for iinfo, beinfo in i_list:
11017
          if iinfo.primary_node == nname:
11018
            i_p_mem += beinfo[constants.BE_MEMORY]
11019
            if iinfo.name not in node_iinfo[nname].payload:
11020
              i_used_mem = 0
11021
            else:
11022
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
11023
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
11024
            remote_info['memory_free'] -= max(0, i_mem_diff)
11025

    
11026
            if iinfo.admin_up:
11027
              i_p_up_mem += beinfo[constants.BE_MEMORY]
11028

    
11029
        # compute memory used by instances
11030
        pnr_dyn = {
11031
          "total_memory": remote_info['memory_total'],
11032
          "reserved_memory": remote_info['memory_dom0'],
11033
          "free_memory": remote_info['memory_free'],
11034
          "total_disk": remote_info['vg_size'],
11035
          "free_disk": remote_info['vg_free'],
11036
          "total_cpus": remote_info['cpu_total'],
11037
          "i_pri_memory": i_p_mem,
11038
          "i_pri_up_memory": i_p_up_mem,
11039
          }
11040
        pnr_dyn.update(node_results[nname])
11041

    
11042
      node_results[nname] = pnr_dyn
11043

    
11044
    return node_results
11045

    
11046
  @staticmethod
11047
  def _ComputeInstanceData(cluster_info, i_list):
11048
    """Compute global instance data.
11049

11050
    """
11051
    instance_data = {}
11052
    for iinfo, beinfo in i_list:
11053
      nic_data = []
11054
      for nic in iinfo.nics:
11055
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
11056
        nic_dict = {"mac": nic.mac,
11057
                    "ip": nic.ip,
11058
                    "mode": filled_params[constants.NIC_MODE],
11059
                    "link": filled_params[constants.NIC_LINK],
11060
                   }
11061
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
11062
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
11063
        nic_data.append(nic_dict)
11064
      pir = {
11065
        "tags": list(iinfo.GetTags()),
11066
        "admin_up": iinfo.admin_up,
11067
        "vcpus": beinfo[constants.BE_VCPUS],
11068
        "memory": beinfo[constants.BE_MEMORY],
11069
        "os": iinfo.os,
11070
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
11071
        "nics": nic_data,
11072
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
11073
        "disk_template": iinfo.disk_template,
11074
        "hypervisor": iinfo.hypervisor,
11075
        }
11076
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
11077
                                                 pir["disks"])
11078
      instance_data[iinfo.name] = pir
11079

    
11080
    return instance_data
11081

    
11082
  def _AddNewInstance(self):
11083
    """Add new instance data to allocator structure.
11084

11085
    This in combination with _AllocatorGetClusterData will create the
11086
    correct structure needed as input for the allocator.
11087

11088
    The checks for the completeness of the opcode must have already been
11089
    done.
11090

11091
    """
11092
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
11093

    
11094
    if self.disk_template in constants.DTS_NET_MIRROR:
11095
      self.required_nodes = 2
11096
    else:
11097
      self.required_nodes = 1
11098
    request = {
11099
      "name": self.name,
11100
      "disk_template": self.disk_template,
11101
      "tags": self.tags,
11102
      "os": self.os,
11103
      "vcpus": self.vcpus,
11104
      "memory": self.mem_size,
11105
      "disks": self.disks,
11106
      "disk_space_total": disk_space,
11107
      "nics": self.nics,
11108
      "required_nodes": self.required_nodes,
11109
      }
11110
    return request
11111

    
11112
  def _AddRelocateInstance(self):
11113
    """Add relocate instance data to allocator structure.
11114

11115
    This in combination with _IAllocatorGetClusterData will create the
11116
    correct structure needed as input for the allocator.
11117

11118
    The checks for the completeness of the opcode must have already been
11119
    done.
11120

11121
    """
11122
    instance = self.cfg.GetInstanceInfo(self.name)
11123
    if instance is None:
11124
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
11125
                                   " IAllocator" % self.name)
11126

    
11127
    if instance.disk_template not in constants.DTS_NET_MIRROR:
11128
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
11129
                                 errors.ECODE_INVAL)
11130

    
11131
    if len(instance.secondary_nodes) != 1:
11132
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
11133
                                 errors.ECODE_STATE)
11134

    
11135
    self.required_nodes = 1
11136
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
11137
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
11138

    
11139
    request = {
11140
      "name": self.name,
11141
      "disk_space_total": disk_space,
11142
      "required_nodes": self.required_nodes,
11143
      "relocate_from": self.relocate_from,
11144
      }
11145
    return request
11146

    
11147
  def _AddEvacuateNodes(self):
11148
    """Add evacuate nodes data to allocator structure.
11149

11150
    """
11151
    request = {
11152
      "evac_nodes": self.evac_nodes
11153
      }
11154
    return request
11155

    
11156
  def _BuildInputData(self, fn):
11157
    """Build input data structures.
11158

11159
    """
11160
    self._ComputeClusterData()
11161

    
11162
    request = fn()
11163
    request["type"] = self.mode
11164
    self.in_data["request"] = request
11165

    
11166
    self.in_text = serializer.Dump(self.in_data)
11167

    
11168
  def Run(self, name, validate=True, call_fn=None):
11169
    """Run an instance allocator and return the results.
11170

11171
    """
11172
    if call_fn is None:
11173
      call_fn = self.rpc.call_iallocator_runner
11174

    
11175
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
11176
    result.Raise("Failure while running the iallocator script")
11177

    
11178
    self.out_text = result.payload
11179
    if validate:
11180
      self._ValidateResult()
11181

    
11182
  def _ValidateResult(self):
11183
    """Process the allocator results.
11184

11185
    This will process and if successful save the result in
11186
    self.out_data and the other parameters.
11187

11188
    """
11189
    try:
11190
      rdict = serializer.Load(self.out_text)
11191
    except Exception, err:
11192
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
11193

    
11194
    if not isinstance(rdict, dict):
11195
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
11196

    
11197
    # TODO: remove backwards compatiblity in later versions
11198
    if "nodes" in rdict and "result" not in rdict:
11199
      rdict["result"] = rdict["nodes"]
11200
      del rdict["nodes"]
11201

    
11202
    for key in "success", "info", "result":
11203
      if key not in rdict:
11204
        raise errors.OpExecError("Can't parse iallocator results:"
11205
                                 " missing key '%s'" % key)
11206
      setattr(self, key, rdict[key])
11207

    
11208
    if not isinstance(rdict["result"], list):
11209
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
11210
                               " is not a list")
11211
    self.out_data = rdict
11212

    
11213

    
11214
class LUTestAllocator(NoHooksLU):
11215
  """Run allocator tests.
11216

11217
  This LU runs the allocator tests
11218

11219
  """
11220
  def CheckPrereq(self):
11221
    """Check prerequisites.
11222

11223
    This checks the opcode parameters depending on the director and mode test.
11224

11225
    """
11226
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
11227
      for attr in ["mem_size", "disks", "disk_template",
11228
                   "os", "tags", "nics", "vcpus"]:
11229
        if not hasattr(self.op, attr):
11230
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
11231
                                     attr, errors.ECODE_INVAL)
11232
      iname = self.cfg.ExpandInstanceName(self.op.name)
11233
      if iname is not None:
11234
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
11235
                                   iname, errors.ECODE_EXISTS)
11236
      if not isinstance(self.op.nics, list):
11237
        raise errors.OpPrereqError("Invalid parameter 'nics'",
11238
                                   errors.ECODE_INVAL)
11239
      if not isinstance(self.op.disks, list):
11240
        raise errors.OpPrereqError("Invalid parameter 'disks'",
11241
                                   errors.ECODE_INVAL)
11242
      for row in self.op.disks:
11243
        if (not isinstance(row, dict) or
11244
            "size" not in row or
11245
            not isinstance(row["size"], int) or
11246
            "mode" not in row or
11247
            row["mode"] not in ['r', 'w']):
11248
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
11249
                                     " parameter", errors.ECODE_INVAL)
11250
      if self.op.hypervisor is None:
11251
        self.op.hypervisor = self.cfg.GetHypervisorType()
11252
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
11253
      fname = _ExpandInstanceName(self.cfg, self.op.name)
11254
      self.op.name = fname
11255
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
11256
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
11257
      if not hasattr(self.op, "evac_nodes"):
11258
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
11259
                                   " opcode input", errors.ECODE_INVAL)
11260
    else:
11261
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
11262
                                 self.op.mode, errors.ECODE_INVAL)
11263

    
11264
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
11265
      if self.op.allocator is None:
11266
        raise errors.OpPrereqError("Missing allocator name",
11267
                                   errors.ECODE_INVAL)
11268
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
11269
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
11270
                                 self.op.direction, errors.ECODE_INVAL)
11271

    
11272
  def Exec(self, feedback_fn):
11273
    """Run the allocator test.
11274

11275
    """
11276
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
11277
      ial = IAllocator(self.cfg, self.rpc,
11278
                       mode=self.op.mode,
11279
                       name=self.op.name,
11280
                       mem_size=self.op.mem_size,
11281
                       disks=self.op.disks,
11282
                       disk_template=self.op.disk_template,
11283
                       os=self.op.os,
11284
                       tags=self.op.tags,
11285
                       nics=self.op.nics,
11286
                       vcpus=self.op.vcpus,
11287
                       hypervisor=self.op.hypervisor,
11288
                       )
11289
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
11290
      ial = IAllocator(self.cfg, self.rpc,
11291
                       mode=self.op.mode,
11292
                       name=self.op.name,
11293
                       relocate_from=list(self.relocate_from),
11294
                       )
11295
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
11296
      ial = IAllocator(self.cfg, self.rpc,
11297
                       mode=self.op.mode,
11298
                       evac_nodes=self.op.evac_nodes)
11299
    else:
11300
      raise errors.ProgrammerError("Uncatched mode %s in"
11301
                                   " LUTestAllocator.Exec", self.op.mode)
11302

    
11303
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
11304
      result = ial.in_text
11305
    else:
11306
      ial.Run(self.op.allocator, validate=False)
11307
      result = ial.out_text
11308
    return result
11309

    
11310

    
11311
#: Query type implementations
11312
_QUERY_IMPL = {
11313
  constants.QR_INSTANCE: _InstanceQuery,
11314
  constants.QR_NODE: _NodeQuery,
11315
  constants.QR_GROUP: _GroupQuery,
11316
  }
11317

    
11318

    
11319
def _GetQueryImplementation(name):
11320
  """Returns the implemtnation for a query type.
11321

11322
  @param name: Query type, must be one of L{constants.QR_OP_QUERY}
11323

11324
  """
11325
  try:
11326
    return _QUERY_IMPL[name]
11327
  except KeyError:
11328
    raise errors.OpPrereqError("Unknown query resource '%s'" % name,
11329
                               errors.ECODE_INVAL)