Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ d6f46b6a

History | View | Annotate | Download (459.9 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
import operator
44

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

    
63
import ganeti.masterd.instance # pylint: disable-msg=W0611
64

    
65

    
66
def _SupportsOob(cfg, node):
67
  """Tells if node supports OOB.
68

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

75
  """
76
  return cfg.GetNdParams(node)[constants.ND_OOB_PROGRAM]
77

    
78

    
79
class ResultWithJobs:
80
  """Data container for LU results with jobs.
81

82
  Instances of this class returned from L{LogicalUnit.Exec} will be recognized
83
  by L{mcpu.Processor._ProcessResult}. The latter will then submit the jobs
84
  contained in the C{jobs} attribute and include the job IDs in the opcode
85
  result.
86

87
  """
88
  def __init__(self, jobs, **kwargs):
89
    """Initializes this class.
90

91
    Additional return values can be specified as keyword arguments.
92

93
    @type jobs: list of lists of L{opcode.OpCode}
94
    @param jobs: A list of lists of opcode objects
95

96
    """
97
    self.jobs = jobs
98
    self.other = kwargs
99

    
100

    
101
class LogicalUnit(object):
102
  """Logical Unit base class.
103

104
  Subclasses must follow these rules:
105
    - implement ExpandNames
106
    - implement CheckPrereq (except when tasklets are used)
107
    - implement Exec (except when tasklets are used)
108
    - implement BuildHooksEnv
109
    - implement BuildHooksNodes
110
    - redefine HPATH and HTYPE
111
    - optionally redefine their run requirements:
112
        REQ_BGL: the LU needs to hold the Big Ganeti Lock exclusively
113

114
  Note that all commands require root permissions.
115

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

119
  """
120
  HPATH = None
121
  HTYPE = None
122
  REQ_BGL = True
123

    
124
  def __init__(self, processor, op, context, rpc):
125
    """Constructor for LogicalUnit.
126

127
    This needs to be overridden in derived classes in order to check op
128
    validity.
129

130
    """
131
    self.proc = processor
132
    self.op = op
133
    self.cfg = context.cfg
134
    self.glm = context.glm
135
    self.context = context
136
    self.rpc = rpc
137
    # Dicts used to declare locking needs to mcpu
138
    self.needed_locks = None
139
    self.share_locks = dict.fromkeys(locking.LEVELS, 0)
140
    self.add_locks = {}
141
    self.remove_locks = {}
142
    # Used to force good behavior when calling helper functions
143
    self.recalculate_locks = {}
144
    # logging
145
    self.Log = processor.Log # pylint: disable-msg=C0103
146
    self.LogWarning = processor.LogWarning # pylint: disable-msg=C0103
147
    self.LogInfo = processor.LogInfo # pylint: disable-msg=C0103
148
    self.LogStep = processor.LogStep # pylint: disable-msg=C0103
149
    # support for dry-run
150
    self.dry_run_result = None
151
    # support for generic debug attribute
152
    if (not hasattr(self.op, "debug_level") or
153
        not isinstance(self.op.debug_level, int)):
154
      self.op.debug_level = 0
155

    
156
    # Tasklets
157
    self.tasklets = None
158

    
159
    # Validate opcode parameters and set defaults
160
    self.op.Validate(True)
161

    
162
    self.CheckArguments()
163

    
164
  def CheckArguments(self):
165
    """Check syntactic validity for the opcode arguments.
166

167
    This method is for doing a simple syntactic check and ensure
168
    validity of opcode parameters, without any cluster-related
169
    checks. While the same can be accomplished in ExpandNames and/or
170
    CheckPrereq, doing these separate is better because:
171

172
      - ExpandNames is left as as purely a lock-related function
173
      - CheckPrereq is run after we have acquired locks (and possible
174
        waited for them)
175

176
    The function is allowed to change the self.op attribute so that
177
    later methods can no longer worry about missing parameters.
178

179
    """
180
    pass
181

    
182
  def ExpandNames(self):
183
    """Expand names for this LU.
184

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

190
    LUs which implement this method must also populate the self.needed_locks
191
    member, as a dict with lock levels as keys, and a list of needed lock names
192
    as values. Rules:
193

194
      - use an empty dict if you don't need any lock
195
      - if you don't need any lock at a particular level omit that level
196
      - don't put anything for the BGL level
197
      - if you want all locks at a level use locking.ALL_SET as a value
198

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

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

207
    Examples::
208

209
      # Acquire all nodes and one instance
210
      self.needed_locks = {
211
        locking.LEVEL_NODE: locking.ALL_SET,
212
        locking.LEVEL_INSTANCE: ['instance1.example.com'],
213
      }
214
      # Acquire just two nodes
215
      self.needed_locks = {
216
        locking.LEVEL_NODE: ['node1.example.com', 'node2.example.com'],
217
      }
218
      # Acquire no locks
219
      self.needed_locks = {} # No, you can't leave it to the default value None
220

221
    """
222
    # The implementation of this method is mandatory only if the new LU is
223
    # concurrent, so that old LUs don't need to be changed all at the same
224
    # time.
225
    if self.REQ_BGL:
226
      self.needed_locks = {} # Exclusive LUs don't need locks.
227
    else:
228
      raise NotImplementedError
229

    
230
  def DeclareLocks(self, level):
231
    """Declare LU locking needs for a level
232

233
    While most LUs can just declare their locking needs at ExpandNames time,
234
    sometimes there's the need to calculate some locks after having acquired
235
    the ones before. This function is called just before acquiring locks at a
236
    particular level, but after acquiring the ones at lower levels, and permits
237
    such calculations. It can be used to modify self.needed_locks, and by
238
    default it does nothing.
239

240
    This function is only called if you have something already set in
241
    self.needed_locks for the level.
242

243
    @param level: Locking level which is going to be locked
244
    @type level: member of ganeti.locking.LEVELS
245

246
    """
247

    
248
  def CheckPrereq(self):
249
    """Check prerequisites for this LU.
250

251
    This method should check that the prerequisites for the execution
252
    of this LU are fulfilled. It can do internode communication, but
253
    it should be idempotent - no cluster or system changes are
254
    allowed.
255

256
    The method should raise errors.OpPrereqError in case something is
257
    not fulfilled. Its return value is ignored.
258

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

262
    """
263
    if self.tasklets is not None:
264
      for (idx, tl) in enumerate(self.tasklets):
265
        logging.debug("Checking prerequisites for tasklet %s/%s",
266
                      idx + 1, len(self.tasklets))
267
        tl.CheckPrereq()
268
    else:
269
      pass
270

    
271
  def Exec(self, feedback_fn):
272
    """Execute the LU.
273

274
    This method should implement the actual work. It should raise
275
    errors.OpExecError for failures that are somewhat dealt with in
276
    code, or expected.
277

278
    """
279
    if self.tasklets is not None:
280
      for (idx, tl) in enumerate(self.tasklets):
281
        logging.debug("Executing tasklet %s/%s", idx + 1, len(self.tasklets))
282
        tl.Exec(feedback_fn)
283
    else:
284
      raise NotImplementedError
285

    
286
  def BuildHooksEnv(self):
287
    """Build hooks environment for this LU.
288

289
    @rtype: dict
290
    @return: Dictionary containing the environment that will be used for
291
      running the hooks for this LU. The keys of the dict must not be prefixed
292
      with "GANETI_"--that'll be added by the hooks runner. The hooks runner
293
      will extend the environment with additional variables. If no environment
294
      should be defined, an empty dictionary should be returned (not C{None}).
295
    @note: If the C{HPATH} attribute of the LU class is C{None}, this function
296
      will not be called.
297

298
    """
299
    raise NotImplementedError
300

    
301
  def BuildHooksNodes(self):
302
    """Build list of nodes to run LU's hooks.
303

304
    @rtype: tuple; (list, list)
305
    @return: Tuple containing a list of node names on which the hook
306
      should run before the execution and a list of node names on which the
307
      hook should run after the execution. No nodes should be returned as an
308
      empty list (and not None).
309
    @note: If the C{HPATH} attribute of the LU class is C{None}, this function
310
      will not be called.
311

312
    """
313
    raise NotImplementedError
314

    
315
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
316
    """Notify the LU about the results of its hooks.
317

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

324
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
325
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
326
    @param hook_results: the results of the multi-node hooks rpc call
327
    @param feedback_fn: function used send feedback back to the caller
328
    @param lu_result: the previous Exec result this LU had, or None
329
        in the PRE phase
330
    @return: the new Exec result, based on the previous result
331
        and hook results
332

333
    """
334
    # API must be kept, thus we ignore the unused argument and could
335
    # be a function warnings
336
    # pylint: disable-msg=W0613,R0201
337
    return lu_result
338

    
339
  def _ExpandAndLockInstance(self):
340
    """Helper function to expand and lock an instance.
341

342
    Many LUs that work on an instance take its name in self.op.instance_name
343
    and need to expand it and then declare the expanded name for locking. This
344
    function does it, and then updates self.op.instance_name to the expanded
345
    name. It also initializes needed_locks as a dict, if this hasn't been done
346
    before.
347

348
    """
349
    if self.needed_locks is None:
350
      self.needed_locks = {}
351
    else:
352
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
353
        "_ExpandAndLockInstance called with instance-level locks set"
354
    self.op.instance_name = _ExpandInstanceName(self.cfg,
355
                                                self.op.instance_name)
356
    self.needed_locks[locking.LEVEL_INSTANCE] = self.op.instance_name
357

    
358
  def _LockInstancesNodes(self, primary_only=False):
359
    """Helper function to declare instances' nodes for locking.
360

361
    This function should be called after locking one or more instances to lock
362
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
363
    with all primary or secondary nodes for instances already locked and
364
    present in self.needed_locks[locking.LEVEL_INSTANCE].
365

366
    It should be called from DeclareLocks, and for safety only works if
367
    self.recalculate_locks[locking.LEVEL_NODE] is set.
368

369
    In the future it may grow parameters to just lock some instance's nodes, or
370
    to just lock primaries or secondary nodes, if needed.
371

372
    If should be called in DeclareLocks in a way similar to::
373

374
      if level == locking.LEVEL_NODE:
375
        self._LockInstancesNodes()
376

377
    @type primary_only: boolean
378
    @param primary_only: only lock primary nodes of locked instances
379

380
    """
381
    assert locking.LEVEL_NODE in self.recalculate_locks, \
382
      "_LockInstancesNodes helper function called with no nodes to recalculate"
383

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

    
386
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
387
    # future we might want to have different behaviors depending on the value
388
    # of self.recalculate_locks[locking.LEVEL_NODE]
389
    wanted_nodes = []
390
    for instance_name in self.glm.list_owned(locking.LEVEL_INSTANCE):
391
      instance = self.context.cfg.GetInstanceInfo(instance_name)
392
      wanted_nodes.append(instance.primary_node)
393
      if not primary_only:
394
        wanted_nodes.extend(instance.secondary_nodes)
395

    
396
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
397
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
398
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
399
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
400

    
401
    del self.recalculate_locks[locking.LEVEL_NODE]
402

    
403

    
404
class NoHooksLU(LogicalUnit): # pylint: disable-msg=W0223
405
  """Simple LU which runs no hooks.
406

407
  This LU is intended as a parent for other LogicalUnits which will
408
  run no hooks, in order to reduce duplicate code.
409

410
  """
411
  HPATH = None
412
  HTYPE = None
413

    
414
  def BuildHooksEnv(self):
415
    """Empty BuildHooksEnv for NoHooksLu.
416

417
    This just raises an error.
418

419
    """
420
    raise AssertionError("BuildHooksEnv called for NoHooksLUs")
421

    
422
  def BuildHooksNodes(self):
423
    """Empty BuildHooksNodes for NoHooksLU.
424

425
    """
426
    raise AssertionError("BuildHooksNodes called for NoHooksLU")
427

    
428

    
429
class Tasklet:
430
  """Tasklet base class.
431

432
  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
433
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
434
  tasklets know nothing about locks.
435

436
  Subclasses must follow these rules:
437
    - Implement CheckPrereq
438
    - Implement Exec
439

440
  """
441
  def __init__(self, lu):
442
    self.lu = lu
443

    
444
    # Shortcuts
445
    self.cfg = lu.cfg
446
    self.rpc = lu.rpc
447

    
448
  def CheckPrereq(self):
449
    """Check prerequisites for this tasklets.
450

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

455
    The method should raise errors.OpPrereqError in case something is not
456
    fulfilled. Its return value is ignored.
457

458
    This method should also update all parameters to their canonical form if it
459
    hasn't been done before.
460

461
    """
462
    pass
463

    
464
  def Exec(self, feedback_fn):
465
    """Execute the tasklet.
466

467
    This method should implement the actual work. It should raise
468
    errors.OpExecError for failures that are somewhat dealt with in code, or
469
    expected.
470

471
    """
472
    raise NotImplementedError
473

    
474

    
475
class _QueryBase:
476
  """Base for query utility classes.
477

478
  """
479
  #: Attribute holding field definitions
480
  FIELDS = None
481

    
482
  def __init__(self, filter_, fields, use_locking):
483
    """Initializes this class.
484

485
    """
486
    self.use_locking = use_locking
487

    
488
    self.query = query.Query(self.FIELDS, fields, filter_=filter_,
489
                             namefield="name")
490
    self.requested_data = self.query.RequestedData()
491
    self.names = self.query.RequestedNames()
492

    
493
    # Sort only if no names were requested
494
    self.sort_by_name = not self.names
495

    
496
    self.do_locking = None
497
    self.wanted = None
498

    
499
  def _GetNames(self, lu, all_names, lock_level):
500
    """Helper function to determine names asked for in the query.
501

502
    """
503
    if self.do_locking:
504
      names = lu.glm.list_owned(lock_level)
505
    else:
506
      names = all_names
507

    
508
    if self.wanted == locking.ALL_SET:
509
      assert not self.names
510
      # caller didn't specify names, so ordering is not important
511
      return utils.NiceSort(names)
512

    
513
    # caller specified names and we must keep the same order
514
    assert self.names
515
    assert not self.do_locking or lu.glm.is_owned(lock_level)
516

    
517
    missing = set(self.wanted).difference(names)
518
    if missing:
519
      raise errors.OpExecError("Some items were removed before retrieving"
520
                               " their data: %s" % missing)
521

    
522
    # Return expanded names
523
    return self.wanted
524

    
525
  def ExpandNames(self, lu):
526
    """Expand names for this query.
527

528
    See L{LogicalUnit.ExpandNames}.
529

530
    """
531
    raise NotImplementedError()
532

    
533
  def DeclareLocks(self, lu, level):
534
    """Declare locks for this query.
535

536
    See L{LogicalUnit.DeclareLocks}.
537

538
    """
539
    raise NotImplementedError()
540

    
541
  def _GetQueryData(self, lu):
542
    """Collects all data for this query.
543

544
    @return: Query data object
545

546
    """
547
    raise NotImplementedError()
548

    
549
  def NewStyleQuery(self, lu):
550
    """Collect data and execute query.
551

552
    """
553
    return query.GetQueryResponse(self.query, self._GetQueryData(lu),
554
                                  sort_by_name=self.sort_by_name)
555

    
556
  def OldStyleQuery(self, lu):
557
    """Collect data and execute query.
558

559
    """
560
    return self.query.OldStyleQuery(self._GetQueryData(lu),
561
                                    sort_by_name=self.sort_by_name)
562

    
563

    
564
def _GetWantedNodes(lu, nodes):
565
  """Returns list of checked and expanded node names.
566

567
  @type lu: L{LogicalUnit}
568
  @param lu: the logical unit on whose behalf we execute
569
  @type nodes: list
570
  @param nodes: list of node names or None for all nodes
571
  @rtype: list
572
  @return: the list of nodes, sorted
573
  @raise errors.ProgrammerError: if the nodes parameter is wrong type
574

575
  """
576
  if nodes:
577
    return [_ExpandNodeName(lu.cfg, name) for name in nodes]
578

    
579
  return utils.NiceSort(lu.cfg.GetNodeList())
580

    
581

    
582
def _GetWantedInstances(lu, instances):
583
  """Returns list of checked and expanded instance names.
584

585
  @type lu: L{LogicalUnit}
586
  @param lu: the logical unit on whose behalf we execute
587
  @type instances: list
588
  @param instances: list of instance names or None for all instances
589
  @rtype: list
590
  @return: the list of instances, sorted
591
  @raise errors.OpPrereqError: if the instances parameter is wrong type
592
  @raise errors.OpPrereqError: if any of the passed instances is not found
593

594
  """
595
  if instances:
596
    wanted = [_ExpandInstanceName(lu.cfg, name) for name in instances]
597
  else:
598
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
599
  return wanted
600

    
601

    
602
def _GetUpdatedParams(old_params, update_dict,
603
                      use_default=True, use_none=False):
604
  """Return the new version of a parameter dictionary.
605

606
  @type old_params: dict
607
  @param old_params: old parameters
608
  @type update_dict: dict
609
  @param update_dict: dict containing new parameter values, or
610
      constants.VALUE_DEFAULT to reset the parameter to its default
611
      value
612
  @param use_default: boolean
613
  @type use_default: whether to recognise L{constants.VALUE_DEFAULT}
614
      values as 'to be deleted' values
615
  @param use_none: boolean
616
  @type use_none: whether to recognise C{None} values as 'to be
617
      deleted' values
618
  @rtype: dict
619
  @return: the new parameter dictionary
620

621
  """
622
  params_copy = copy.deepcopy(old_params)
623
  for key, val in update_dict.iteritems():
624
    if ((use_default and val == constants.VALUE_DEFAULT) or
625
        (use_none and val is None)):
626
      try:
627
        del params_copy[key]
628
      except KeyError:
629
        pass
630
    else:
631
      params_copy[key] = val
632
  return params_copy
633

    
634

    
635
def _ReleaseLocks(lu, level, names=None, keep=None):
636
  """Releases locks owned by an LU.
637

638
  @type lu: L{LogicalUnit}
639
  @param level: Lock level
640
  @type names: list or None
641
  @param names: Names of locks to release
642
  @type keep: list or None
643
  @param keep: Names of locks to retain
644

645
  """
646
  assert not (keep is not None and names is not None), \
647
         "Only one of the 'names' and the 'keep' parameters can be given"
648

    
649
  if names is not None:
650
    should_release = names.__contains__
651
  elif keep:
652
    should_release = lambda name: name not in keep
653
  else:
654
    should_release = None
655

    
656
  if should_release:
657
    retain = []
658
    release = []
659

    
660
    # Determine which locks to release
661
    for name in lu.glm.list_owned(level):
662
      if should_release(name):
663
        release.append(name)
664
      else:
665
        retain.append(name)
666

    
667
    assert len(lu.glm.list_owned(level)) == (len(retain) + len(release))
668

    
669
    # Release just some locks
670
    lu.glm.release(level, names=release)
671

    
672
    assert frozenset(lu.glm.list_owned(level)) == frozenset(retain)
673
  else:
674
    # Release everything
675
    lu.glm.release(level)
676

    
677
    assert not lu.glm.is_owned(level), "No locks should be owned"
678

    
679

    
680
def _RunPostHook(lu, node_name):
681
  """Runs the post-hook for an opcode on a single node.
682

683
  """
684
  hm = lu.proc.hmclass(lu.rpc.call_hooks_runner, lu)
685
  try:
686
    hm.RunPhase(constants.HOOKS_PHASE_POST, nodes=[node_name])
687
  except:
688
    # pylint: disable-msg=W0702
689
    lu.LogWarning("Errors occurred running hooks on %s" % node_name)
690

    
691

    
692
def _CheckOutputFields(static, dynamic, selected):
693
  """Checks whether all selected fields are valid.
694

695
  @type static: L{utils.FieldSet}
696
  @param static: static fields set
697
  @type dynamic: L{utils.FieldSet}
698
  @param dynamic: dynamic fields set
699

700
  """
701
  f = utils.FieldSet()
702
  f.Extend(static)
703
  f.Extend(dynamic)
704

    
705
  delta = f.NonMatching(selected)
706
  if delta:
707
    raise errors.OpPrereqError("Unknown output fields selected: %s"
708
                               % ",".join(delta), errors.ECODE_INVAL)
709

    
710

    
711
def _CheckGlobalHvParams(params):
712
  """Validates that given hypervisor params are not global ones.
713

714
  This will ensure that instances don't get customised versions of
715
  global params.
716

717
  """
718
  used_globals = constants.HVC_GLOBALS.intersection(params)
719
  if used_globals:
720
    msg = ("The following hypervisor parameters are global and cannot"
721
           " be customized at instance level, please modify them at"
722
           " cluster level: %s" % utils.CommaJoin(used_globals))
723
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
724

    
725

    
726
def _CheckNodeOnline(lu, node, msg=None):
727
  """Ensure that a given node is online.
728

729
  @param lu: the LU on behalf of which we make the check
730
  @param node: the node to check
731
  @param msg: if passed, should be a message to replace the default one
732
  @raise errors.OpPrereqError: if the node is offline
733

734
  """
735
  if msg is None:
736
    msg = "Can't use offline node"
737
  if lu.cfg.GetNodeInfo(node).offline:
738
    raise errors.OpPrereqError("%s: %s" % (msg, node), errors.ECODE_STATE)
739

    
740

    
741
def _CheckNodeNotDrained(lu, node):
742
  """Ensure that a given node is not drained.
743

744
  @param lu: the LU on behalf of which we make the check
745
  @param node: the node to check
746
  @raise errors.OpPrereqError: if the node is drained
747

748
  """
749
  if lu.cfg.GetNodeInfo(node).drained:
750
    raise errors.OpPrereqError("Can't use drained node %s" % node,
751
                               errors.ECODE_STATE)
752

    
753

    
754
def _CheckNodeVmCapable(lu, node):
755
  """Ensure that a given node is vm capable.
756

757
  @param lu: the LU on behalf of which we make the check
758
  @param node: the node to check
759
  @raise errors.OpPrereqError: if the node is not vm capable
760

761
  """
762
  if not lu.cfg.GetNodeInfo(node).vm_capable:
763
    raise errors.OpPrereqError("Can't use non-vm_capable node %s" % node,
764
                               errors.ECODE_STATE)
765

    
766

    
767
def _CheckNodeHasOS(lu, node, os_name, force_variant):
768
  """Ensure that a node supports a given OS.
769

770
  @param lu: the LU on behalf of which we make the check
771
  @param node: the node to check
772
  @param os_name: the OS to query about
773
  @param force_variant: whether to ignore variant errors
774
  @raise errors.OpPrereqError: if the node is not supporting the OS
775

776
  """
777
  result = lu.rpc.call_os_get(node, os_name)
778
  result.Raise("OS '%s' not in supported OS list for node %s" %
779
               (os_name, node),
780
               prereq=True, ecode=errors.ECODE_INVAL)
781
  if not force_variant:
782
    _CheckOSVariant(result.payload, os_name)
783

    
784

    
785
def _CheckNodeHasSecondaryIP(lu, node, secondary_ip, prereq):
786
  """Ensure that a node has the given secondary ip.
787

788
  @type lu: L{LogicalUnit}
789
  @param lu: the LU on behalf of which we make the check
790
  @type node: string
791
  @param node: the node to check
792
  @type secondary_ip: string
793
  @param secondary_ip: the ip to check
794
  @type prereq: boolean
795
  @param prereq: whether to throw a prerequisite or an execute error
796
  @raise errors.OpPrereqError: if the node doesn't have the ip, and prereq=True
797
  @raise errors.OpExecError: if the node doesn't have the ip, and prereq=False
798

799
  """
800
  result = lu.rpc.call_node_has_ip_address(node, secondary_ip)
801
  result.Raise("Failure checking secondary ip on node %s" % node,
802
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
803
  if not result.payload:
804
    msg = ("Node claims it doesn't have the secondary ip you gave (%s),"
805
           " please fix and re-run this command" % secondary_ip)
806
    if prereq:
807
      raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
808
    else:
809
      raise errors.OpExecError(msg)
810

    
811

    
812
def _GetClusterDomainSecret():
813
  """Reads the cluster domain secret.
814

815
  """
816
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
817
                               strict=True)
818

    
819

    
820
def _CheckInstanceDown(lu, instance, reason):
821
  """Ensure that an instance is not running."""
822
  if instance.admin_up:
823
    raise errors.OpPrereqError("Instance %s is marked to be up, %s" %
824
                               (instance.name, reason), errors.ECODE_STATE)
825

    
826
  pnode = instance.primary_node
827
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
828
  ins_l.Raise("Can't contact node %s for instance information" % pnode,
829
              prereq=True, ecode=errors.ECODE_ENVIRON)
830

    
831
  if instance.name in ins_l.payload:
832
    raise errors.OpPrereqError("Instance %s is running, %s" %
833
                               (instance.name, reason), errors.ECODE_STATE)
834

    
835

    
836
def _ExpandItemName(fn, name, kind):
837
  """Expand an item name.
838

839
  @param fn: the function to use for expansion
840
  @param name: requested item name
841
  @param kind: text description ('Node' or 'Instance')
842
  @return: the resolved (full) name
843
  @raise errors.OpPrereqError: if the item is not found
844

845
  """
846
  full_name = fn(name)
847
  if full_name is None:
848
    raise errors.OpPrereqError("%s '%s' not known" % (kind, name),
849
                               errors.ECODE_NOENT)
850
  return full_name
851

    
852

    
853
def _ExpandNodeName(cfg, name):
854
  """Wrapper over L{_ExpandItemName} for nodes."""
855
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
856

    
857

    
858
def _ExpandInstanceName(cfg, name):
859
  """Wrapper over L{_ExpandItemName} for instance."""
860
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
861

    
862

    
863
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
864
                          memory, vcpus, nics, disk_template, disks,
865
                          bep, hvp, hypervisor_name, tags):
866
  """Builds instance related env variables for hooks
867

868
  This builds the hook environment from individual variables.
869

870
  @type name: string
871
  @param name: the name of the instance
872
  @type primary_node: string
873
  @param primary_node: the name of the instance's primary node
874
  @type secondary_nodes: list
875
  @param secondary_nodes: list of secondary nodes as strings
876
  @type os_type: string
877
  @param os_type: the name of the instance's OS
878
  @type status: boolean
879
  @param status: the should_run status of the instance
880
  @type memory: string
881
  @param memory: the memory size of the instance
882
  @type vcpus: string
883
  @param vcpus: the count of VCPUs the instance has
884
  @type nics: list
885
  @param nics: list of tuples (ip, mac, mode, link) representing
886
      the NICs the instance has
887
  @type disk_template: string
888
  @param disk_template: the disk template of the instance
889
  @type disks: list
890
  @param disks: the list of (size, mode) pairs
891
  @type bep: dict
892
  @param bep: the backend parameters for the instance
893
  @type hvp: dict
894
  @param hvp: the hypervisor parameters for the instance
895
  @type hypervisor_name: string
896
  @param hypervisor_name: the hypervisor for the instance
897
  @type tags: list
898
  @param tags: list of instance tags as strings
899
  @rtype: dict
900
  @return: the hook environment for this instance
901

902
  """
903
  if status:
904
    str_status = "up"
905
  else:
906
    str_status = "down"
907
  env = {
908
    "OP_TARGET": name,
909
    "INSTANCE_NAME": name,
910
    "INSTANCE_PRIMARY": primary_node,
911
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
912
    "INSTANCE_OS_TYPE": os_type,
913
    "INSTANCE_STATUS": str_status,
914
    "INSTANCE_MEMORY": memory,
915
    "INSTANCE_VCPUS": vcpus,
916
    "INSTANCE_DISK_TEMPLATE": disk_template,
917
    "INSTANCE_HYPERVISOR": hypervisor_name,
918
  }
919

    
920
  if nics:
921
    nic_count = len(nics)
922
    for idx, (ip, mac, mode, link) in enumerate(nics):
923
      if ip is None:
924
        ip = ""
925
      env["INSTANCE_NIC%d_IP" % idx] = ip
926
      env["INSTANCE_NIC%d_MAC" % idx] = mac
927
      env["INSTANCE_NIC%d_MODE" % idx] = mode
928
      env["INSTANCE_NIC%d_LINK" % idx] = link
929
      if mode == constants.NIC_MODE_BRIDGED:
930
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
931
  else:
932
    nic_count = 0
933

    
934
  env["INSTANCE_NIC_COUNT"] = nic_count
935

    
936
  if disks:
937
    disk_count = len(disks)
938
    for idx, (size, mode) in enumerate(disks):
939
      env["INSTANCE_DISK%d_SIZE" % idx] = size
940
      env["INSTANCE_DISK%d_MODE" % idx] = mode
941
  else:
942
    disk_count = 0
943

    
944
  env["INSTANCE_DISK_COUNT"] = disk_count
945

    
946
  if not tags:
947
    tags = []
948

    
949
  env["INSTANCE_TAGS"] = " ".join(tags)
950

    
951
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
952
    for key, value in source.items():
953
      env["INSTANCE_%s_%s" % (kind, key)] = value
954

    
955
  return env
956

    
957

    
958
def _NICListToTuple(lu, nics):
959
  """Build a list of nic information tuples.
960

961
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
962
  value in LUInstanceQueryData.
963

964
  @type lu:  L{LogicalUnit}
965
  @param lu: the logical unit on whose behalf we execute
966
  @type nics: list of L{objects.NIC}
967
  @param nics: list of nics to convert to hooks tuples
968

969
  """
970
  hooks_nics = []
971
  cluster = lu.cfg.GetClusterInfo()
972
  for nic in nics:
973
    ip = nic.ip
974
    mac = nic.mac
975
    filled_params = cluster.SimpleFillNIC(nic.nicparams)
976
    mode = filled_params[constants.NIC_MODE]
977
    link = filled_params[constants.NIC_LINK]
978
    hooks_nics.append((ip, mac, mode, link))
979
  return hooks_nics
980

    
981

    
982
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
983
  """Builds instance related env variables for hooks from an object.
984

985
  @type lu: L{LogicalUnit}
986
  @param lu: the logical unit on whose behalf we execute
987
  @type instance: L{objects.Instance}
988
  @param instance: the instance for which we should build the
989
      environment
990
  @type override: dict
991
  @param override: dictionary with key/values that will override
992
      our values
993
  @rtype: dict
994
  @return: the hook environment dictionary
995

996
  """
997
  cluster = lu.cfg.GetClusterInfo()
998
  bep = cluster.FillBE(instance)
999
  hvp = cluster.FillHV(instance)
1000
  args = {
1001
    'name': instance.name,
1002
    'primary_node': instance.primary_node,
1003
    'secondary_nodes': instance.secondary_nodes,
1004
    'os_type': instance.os,
1005
    'status': instance.admin_up,
1006
    'memory': bep[constants.BE_MEMORY],
1007
    'vcpus': bep[constants.BE_VCPUS],
1008
    'nics': _NICListToTuple(lu, instance.nics),
1009
    'disk_template': instance.disk_template,
1010
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
1011
    'bep': bep,
1012
    'hvp': hvp,
1013
    'hypervisor_name': instance.hypervisor,
1014
    'tags': instance.tags,
1015
  }
1016
  if override:
1017
    args.update(override)
1018
  return _BuildInstanceHookEnv(**args) # pylint: disable-msg=W0142
1019

    
1020

    
1021
def _AdjustCandidatePool(lu, exceptions):
1022
  """Adjust the candidate pool after node operations.
1023

1024
  """
1025
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
1026
  if mod_list:
1027
    lu.LogInfo("Promoted nodes to master candidate role: %s",
1028
               utils.CommaJoin(node.name for node in mod_list))
1029
    for name in mod_list:
1030
      lu.context.ReaddNode(name)
1031
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
1032
  if mc_now > mc_max:
1033
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
1034
               (mc_now, mc_max))
1035

    
1036

    
1037
def _DecideSelfPromotion(lu, exceptions=None):
1038
  """Decide whether I should promote myself as a master candidate.
1039

1040
  """
1041
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
1042
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
1043
  # the new node will increase mc_max with one, so:
1044
  mc_should = min(mc_should + 1, cp_size)
1045
  return mc_now < mc_should
1046

    
1047

    
1048
def _CheckNicsBridgesExist(lu, target_nics, target_node):
1049
  """Check that the brigdes needed by a list of nics exist.
1050

1051
  """
1052
  cluster = lu.cfg.GetClusterInfo()
1053
  paramslist = [cluster.SimpleFillNIC(nic.nicparams) for nic in target_nics]
1054
  brlist = [params[constants.NIC_LINK] for params in paramslist
1055
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
1056
  if brlist:
1057
    result = lu.rpc.call_bridges_exist(target_node, brlist)
1058
    result.Raise("Error checking bridges on destination node '%s'" %
1059
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
1060

    
1061

    
1062
def _CheckInstanceBridgesExist(lu, instance, node=None):
1063
  """Check that the brigdes needed by an instance exist.
1064

1065
  """
1066
  if node is None:
1067
    node = instance.primary_node
1068
  _CheckNicsBridgesExist(lu, instance.nics, node)
1069

    
1070

    
1071
def _CheckOSVariant(os_obj, name):
1072
  """Check whether an OS name conforms to the os variants specification.
1073

1074
  @type os_obj: L{objects.OS}
1075
  @param os_obj: OS object to check
1076
  @type name: string
1077
  @param name: OS name passed by the user, to check for validity
1078

1079
  """
1080
  if not os_obj.supported_variants:
1081
    return
1082
  variant = objects.OS.GetVariant(name)
1083
  if not variant:
1084
    raise errors.OpPrereqError("OS name must include a variant",
1085
                               errors.ECODE_INVAL)
1086

    
1087
  if variant not in os_obj.supported_variants:
1088
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
1089

    
1090

    
1091
def _GetNodeInstancesInner(cfg, fn):
1092
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
1093

    
1094

    
1095
def _GetNodeInstances(cfg, node_name):
1096
  """Returns a list of all primary and secondary instances on a node.
1097

1098
  """
1099

    
1100
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
1101

    
1102

    
1103
def _GetNodePrimaryInstances(cfg, node_name):
1104
  """Returns primary instances on a node.
1105

1106
  """
1107
  return _GetNodeInstancesInner(cfg,
1108
                                lambda inst: node_name == inst.primary_node)
1109

    
1110

    
1111
def _GetNodeSecondaryInstances(cfg, node_name):
1112
  """Returns secondary instances on a node.
1113

1114
  """
1115
  return _GetNodeInstancesInner(cfg,
1116
                                lambda inst: node_name in inst.secondary_nodes)
1117

    
1118

    
1119
def _GetStorageTypeArgs(cfg, storage_type):
1120
  """Returns the arguments for a storage type.
1121

1122
  """
1123
  # Special case for file storage
1124
  if storage_type == constants.ST_FILE:
1125
    # storage.FileStorage wants a list of storage directories
1126
    return [[cfg.GetFileStorageDir(), cfg.GetSharedFileStorageDir()]]
1127

    
1128
  return []
1129

    
1130

    
1131
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
1132
  faulty = []
1133

    
1134
  for dev in instance.disks:
1135
    cfg.SetDiskID(dev, node_name)
1136

    
1137
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
1138
  result.Raise("Failed to get disk status from node %s" % node_name,
1139
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
1140

    
1141
  for idx, bdev_status in enumerate(result.payload):
1142
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
1143
      faulty.append(idx)
1144

    
1145
  return faulty
1146

    
1147

    
1148
def _CheckIAllocatorOrNode(lu, iallocator_slot, node_slot):
1149
  """Check the sanity of iallocator and node arguments and use the
1150
  cluster-wide iallocator if appropriate.
1151

1152
  Check that at most one of (iallocator, node) is specified. If none is
1153
  specified, then the LU's opcode's iallocator slot is filled with the
1154
  cluster-wide default iallocator.
1155

1156
  @type iallocator_slot: string
1157
  @param iallocator_slot: the name of the opcode iallocator slot
1158
  @type node_slot: string
1159
  @param node_slot: the name of the opcode target node slot
1160

1161
  """
1162
  node = getattr(lu.op, node_slot, None)
1163
  iallocator = getattr(lu.op, iallocator_slot, None)
1164

    
1165
  if node is not None and iallocator is not None:
1166
    raise errors.OpPrereqError("Do not specify both, iallocator and node",
1167
                               errors.ECODE_INVAL)
1168
  elif node is None and iallocator is None:
1169
    default_iallocator = lu.cfg.GetDefaultIAllocator()
1170
    if default_iallocator:
1171
      setattr(lu.op, iallocator_slot, default_iallocator)
1172
    else:
1173
      raise errors.OpPrereqError("No iallocator or node given and no"
1174
                                 " cluster-wide default iallocator found;"
1175
                                 " please specify either an iallocator or a"
1176
                                 " node, or set a cluster-wide default"
1177
                                 " iallocator")
1178

    
1179

    
1180
class LUClusterPostInit(LogicalUnit):
1181
  """Logical unit for running hooks after cluster initialization.
1182

1183
  """
1184
  HPATH = "cluster-init"
1185
  HTYPE = constants.HTYPE_CLUSTER
1186

    
1187
  def BuildHooksEnv(self):
1188
    """Build hooks env.
1189

1190
    """
1191
    return {
1192
      "OP_TARGET": self.cfg.GetClusterName(),
1193
      }
1194

    
1195
  def BuildHooksNodes(self):
1196
    """Build hooks nodes.
1197

1198
    """
1199
    return ([], [self.cfg.GetMasterNode()])
1200

    
1201
  def Exec(self, feedback_fn):
1202
    """Nothing to do.
1203

1204
    """
1205
    return True
1206

    
1207

    
1208
class LUClusterDestroy(LogicalUnit):
1209
  """Logical unit for destroying the cluster.
1210

1211
  """
1212
  HPATH = "cluster-destroy"
1213
  HTYPE = constants.HTYPE_CLUSTER
1214

    
1215
  def BuildHooksEnv(self):
1216
    """Build hooks env.
1217

1218
    """
1219
    return {
1220
      "OP_TARGET": self.cfg.GetClusterName(),
1221
      }
1222

    
1223
  def BuildHooksNodes(self):
1224
    """Build hooks nodes.
1225

1226
    """
1227
    return ([], [])
1228

    
1229
  def CheckPrereq(self):
1230
    """Check prerequisites.
1231

1232
    This checks whether the cluster is empty.
1233

1234
    Any errors are signaled by raising errors.OpPrereqError.
1235

1236
    """
1237
    master = self.cfg.GetMasterNode()
1238

    
1239
    nodelist = self.cfg.GetNodeList()
1240
    if len(nodelist) != 1 or nodelist[0] != master:
1241
      raise errors.OpPrereqError("There are still %d node(s) in"
1242
                                 " this cluster." % (len(nodelist) - 1),
1243
                                 errors.ECODE_INVAL)
1244
    instancelist = self.cfg.GetInstanceList()
1245
    if instancelist:
1246
      raise errors.OpPrereqError("There are still %d instance(s) in"
1247
                                 " this cluster." % len(instancelist),
1248
                                 errors.ECODE_INVAL)
1249

    
1250
  def Exec(self, feedback_fn):
1251
    """Destroys the cluster.
1252

1253
    """
1254
    master = self.cfg.GetMasterNode()
1255

    
1256
    # Run post hooks on master node before it's removed
1257
    _RunPostHook(self, master)
1258

    
1259
    result = self.rpc.call_node_stop_master(master, False)
1260
    result.Raise("Could not disable the master role")
1261

    
1262
    return master
1263

    
1264

    
1265
def _VerifyCertificate(filename):
1266
  """Verifies a certificate for L{LUClusterVerifyConfig}.
1267

1268
  @type filename: string
1269
  @param filename: Path to PEM file
1270

1271
  """
1272
  try:
1273
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1274
                                           utils.ReadFile(filename))
1275
  except Exception, err: # pylint: disable-msg=W0703
1276
    return (LUClusterVerifyConfig.ETYPE_ERROR,
1277
            "Failed to load X509 certificate %s: %s" % (filename, err))
1278

    
1279
  (errcode, msg) = \
1280
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1281
                                constants.SSL_CERT_EXPIRATION_ERROR)
1282

    
1283
  if msg:
1284
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1285
  else:
1286
    fnamemsg = None
1287

    
1288
  if errcode is None:
1289
    return (None, fnamemsg)
1290
  elif errcode == utils.CERT_WARNING:
1291
    return (LUClusterVerifyConfig.ETYPE_WARNING, fnamemsg)
1292
  elif errcode == utils.CERT_ERROR:
1293
    return (LUClusterVerifyConfig.ETYPE_ERROR, fnamemsg)
1294

    
1295
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1296

    
1297

    
1298
def _GetAllHypervisorParameters(cluster, instances):
1299
  """Compute the set of all hypervisor parameters.
1300

1301
  @type cluster: L{objects.Cluster}
1302
  @param cluster: the cluster object
1303
  @param instances: list of L{objects.Instance}
1304
  @param instances: additional instances from which to obtain parameters
1305
  @rtype: list of (origin, hypervisor, parameters)
1306
  @return: a list with all parameters found, indicating the hypervisor they
1307
       apply to, and the origin (can be "cluster", "os X", or "instance Y")
1308

1309
  """
1310
  hvp_data = []
1311

    
1312
  for hv_name in cluster.enabled_hypervisors:
1313
    hvp_data.append(("cluster", hv_name, cluster.GetHVDefaults(hv_name)))
1314

    
1315
  for os_name, os_hvp in cluster.os_hvp.items():
1316
    for hv_name, hv_params in os_hvp.items():
1317
      if hv_params:
1318
        full_params = cluster.GetHVDefaults(hv_name, os_name=os_name)
1319
        hvp_data.append(("os %s" % os_name, hv_name, full_params))
1320

    
1321
  # TODO: collapse identical parameter values in a single one
1322
  for instance in instances:
1323
    if instance.hvparams:
1324
      hvp_data.append(("instance %s" % instance.name, instance.hypervisor,
1325
                       cluster.FillHV(instance)))
1326

    
1327
  return hvp_data
1328

    
1329

    
1330
class _VerifyErrors(object):
1331
  """Mix-in for cluster/group verify LUs.
1332

1333
  It provides _Error and _ErrorIf, and updates the self.bad boolean. (Expects
1334
  self.op and self._feedback_fn to be available.)
1335

1336
  """
1337
  TCLUSTER = "cluster"
1338
  TNODE = "node"
1339
  TINSTANCE = "instance"
1340

    
1341
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1342
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1343
  ECLUSTERFILECHECK = (TCLUSTER, "ECLUSTERFILECHECK")
1344
  ECLUSTERDANGLINGNODES = (TNODE, "ECLUSTERDANGLINGNODES")
1345
  ECLUSTERDANGLINGINST = (TNODE, "ECLUSTERDANGLINGINST")
1346
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1347
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1348
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1349
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1350
  EINSTANCEFAULTYDISK = (TINSTANCE, "EINSTANCEFAULTYDISK")
1351
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1352
  EINSTANCESPLITGROUPS = (TINSTANCE, "EINSTANCESPLITGROUPS")
1353
  ENODEDRBD = (TNODE, "ENODEDRBD")
1354
  ENODEDRBDHELPER = (TNODE, "ENODEDRBDHELPER")
1355
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1356
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1357
  ENODEHV = (TNODE, "ENODEHV")
1358
  ENODELVM = (TNODE, "ENODELVM")
1359
  ENODEN1 = (TNODE, "ENODEN1")
1360
  ENODENET = (TNODE, "ENODENET")
1361
  ENODEOS = (TNODE, "ENODEOS")
1362
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1363
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1364
  ENODERPC = (TNODE, "ENODERPC")
1365
  ENODESSH = (TNODE, "ENODESSH")
1366
  ENODEVERSION = (TNODE, "ENODEVERSION")
1367
  ENODESETUP = (TNODE, "ENODESETUP")
1368
  ENODETIME = (TNODE, "ENODETIME")
1369
  ENODEOOBPATH = (TNODE, "ENODEOOBPATH")
1370

    
1371
  ETYPE_FIELD = "code"
1372
  ETYPE_ERROR = "ERROR"
1373
  ETYPE_WARNING = "WARNING"
1374

    
1375
  def _Error(self, ecode, item, msg, *args, **kwargs):
1376
    """Format an error message.
1377

1378
    Based on the opcode's error_codes parameter, either format a
1379
    parseable error code, or a simpler error string.
1380

1381
    This must be called only from Exec and functions called from Exec.
1382

1383
    """
1384
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1385
    itype, etxt = ecode
1386
    # first complete the msg
1387
    if args:
1388
      msg = msg % args
1389
    # then format the whole message
1390
    if self.op.error_codes: # This is a mix-in. pylint: disable-msg=E1101
1391
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1392
    else:
1393
      if item:
1394
        item = " " + item
1395
      else:
1396
        item = ""
1397
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1398
    # and finally report it via the feedback_fn
1399
    self._feedback_fn("  - %s" % msg) # Mix-in. pylint: disable-msg=E1101
1400

    
1401
  def _ErrorIf(self, cond, *args, **kwargs):
1402
    """Log an error message if the passed condition is True.
1403

1404
    """
1405
    cond = (bool(cond)
1406
            or self.op.debug_simulate_errors) # pylint: disable-msg=E1101
1407
    if cond:
1408
      self._Error(*args, **kwargs)
1409
    # do not mark the operation as failed for WARN cases only
1410
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1411
      self.bad = self.bad or cond
1412

    
1413

    
1414
class LUClusterVerifyConfig(NoHooksLU, _VerifyErrors):
1415
  """Verifies the cluster config.
1416

1417
  """
1418
  REQ_BGL = True
1419

    
1420
  def _VerifyHVP(self, hvp_data):
1421
    """Verifies locally the syntax of the hypervisor parameters.
1422

1423
    """
1424
    for item, hv_name, hv_params in hvp_data:
1425
      msg = ("hypervisor %s parameters syntax check (source %s): %%s" %
1426
             (item, hv_name))
1427
      try:
1428
        hv_class = hypervisor.GetHypervisor(hv_name)
1429
        utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
1430
        hv_class.CheckParameterSyntax(hv_params)
1431
      except errors.GenericError, err:
1432
        self._ErrorIf(True, self.ECLUSTERCFG, None, msg % str(err))
1433

    
1434
  def ExpandNames(self):
1435
    # Information can be safely retrieved as the BGL is acquired in exclusive
1436
    # mode
1437
    self.all_group_info = self.cfg.GetAllNodeGroupsInfo()
1438
    self.all_node_info = self.cfg.GetAllNodesInfo()
1439
    self.all_inst_info = self.cfg.GetAllInstancesInfo()
1440
    self.needed_locks = {}
1441

    
1442
  def Exec(self, feedback_fn):
1443
    """Verify integrity of cluster, performing various test on nodes.
1444

1445
    """
1446
    self.bad = False
1447
    self._feedback_fn = feedback_fn
1448

    
1449
    feedback_fn("* Verifying cluster config")
1450

    
1451
    for msg in self.cfg.VerifyConfig():
1452
      self._ErrorIf(True, self.ECLUSTERCFG, None, msg)
1453

    
1454
    feedback_fn("* Verifying cluster certificate files")
1455

    
1456
    for cert_filename in constants.ALL_CERT_FILES:
1457
      (errcode, msg) = _VerifyCertificate(cert_filename)
1458
      self._ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
1459

    
1460
    feedback_fn("* Verifying hypervisor parameters")
1461

    
1462
    self._VerifyHVP(_GetAllHypervisorParameters(self.cfg.GetClusterInfo(),
1463
                                                self.all_inst_info.values()))
1464

    
1465
    feedback_fn("* Verifying all nodes belong to an existing group")
1466

    
1467
    # We do this verification here because, should this bogus circumstance
1468
    # occur, it would never be caught by VerifyGroup, which only acts on
1469
    # nodes/instances reachable from existing node groups.
1470

    
1471
    dangling_nodes = set(node.name for node in self.all_node_info.values()
1472
                         if node.group not in self.all_group_info)
1473

    
1474
    dangling_instances = {}
1475
    no_node_instances = []
1476

    
1477
    for inst in self.all_inst_info.values():
1478
      if inst.primary_node in dangling_nodes:
1479
        dangling_instances.setdefault(inst.primary_node, []).append(inst.name)
1480
      elif inst.primary_node not in self.all_node_info:
1481
        no_node_instances.append(inst.name)
1482

    
1483
    pretty_dangling = [
1484
        "%s (%s)" %
1485
        (node.name,
1486
         utils.CommaJoin(dangling_instances.get(node.name,
1487
                                                ["no instances"])))
1488
        for node in dangling_nodes]
1489

    
1490
    self._ErrorIf(bool(dangling_nodes), self.ECLUSTERDANGLINGNODES, None,
1491
                  "the following nodes (and their instances) belong to a non"
1492
                  " existing group: %s", utils.CommaJoin(pretty_dangling))
1493

    
1494
    self._ErrorIf(bool(no_node_instances), self.ECLUSTERDANGLINGINST, None,
1495
                  "the following instances have a non-existing primary-node:"
1496
                  " %s", utils.CommaJoin(no_node_instances))
1497

    
1498
    return (not self.bad, [g.name for g in self.all_group_info.values()])
1499

    
1500

    
1501
class LUClusterVerifyGroup(LogicalUnit, _VerifyErrors):
1502
  """Verifies the status of a node group.
1503

1504
  """
1505
  HPATH = "cluster-verify"
1506
  HTYPE = constants.HTYPE_CLUSTER
1507
  REQ_BGL = False
1508

    
1509
  _HOOKS_INDENT_RE = re.compile("^", re.M)
1510

    
1511
  class NodeImage(object):
1512
    """A class representing the logical and physical status of a node.
1513

1514
    @type name: string
1515
    @ivar name: the node name to which this object refers
1516
    @ivar volumes: a structure as returned from
1517
        L{ganeti.backend.GetVolumeList} (runtime)
1518
    @ivar instances: a list of running instances (runtime)
1519
    @ivar pinst: list of configured primary instances (config)
1520
    @ivar sinst: list of configured secondary instances (config)
1521
    @ivar sbp: dictionary of {primary-node: list of instances} for all
1522
        instances for which this node is secondary (config)
1523
    @ivar mfree: free memory, as reported by hypervisor (runtime)
1524
    @ivar dfree: free disk, as reported by the node (runtime)
1525
    @ivar offline: the offline status (config)
1526
    @type rpc_fail: boolean
1527
    @ivar rpc_fail: whether the RPC verify call was successfull (overall,
1528
        not whether the individual keys were correct) (runtime)
1529
    @type lvm_fail: boolean
1530
    @ivar lvm_fail: whether the RPC call didn't return valid LVM data
1531
    @type hyp_fail: boolean
1532
    @ivar hyp_fail: whether the RPC call didn't return the instance list
1533
    @type ghost: boolean
1534
    @ivar ghost: whether this is a known node or not (config)
1535
    @type os_fail: boolean
1536
    @ivar os_fail: whether the RPC call didn't return valid OS data
1537
    @type oslist: list
1538
    @ivar oslist: list of OSes as diagnosed by DiagnoseOS
1539
    @type vm_capable: boolean
1540
    @ivar vm_capable: whether the node can host instances
1541

1542
    """
1543
    def __init__(self, offline=False, name=None, vm_capable=True):
1544
      self.name = name
1545
      self.volumes = {}
1546
      self.instances = []
1547
      self.pinst = []
1548
      self.sinst = []
1549
      self.sbp = {}
1550
      self.mfree = 0
1551
      self.dfree = 0
1552
      self.offline = offline
1553
      self.vm_capable = vm_capable
1554
      self.rpc_fail = False
1555
      self.lvm_fail = False
1556
      self.hyp_fail = False
1557
      self.ghost = False
1558
      self.os_fail = False
1559
      self.oslist = {}
1560

    
1561
  def ExpandNames(self):
1562
    # This raises errors.OpPrereqError on its own:
1563
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
1564

    
1565
    # Get instances in node group; this is unsafe and needs verification later
1566
    inst_names = self.cfg.GetNodeGroupInstances(self.group_uuid)
1567

    
1568
    self.needed_locks = {
1569
      locking.LEVEL_INSTANCE: inst_names,
1570
      locking.LEVEL_NODEGROUP: [self.group_uuid],
1571
      locking.LEVEL_NODE: [],
1572
      }
1573

    
1574
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1575

    
1576
  def DeclareLocks(self, level):
1577
    if level == locking.LEVEL_NODE:
1578
      # Get members of node group; this is unsafe and needs verification later
1579
      nodes = set(self.cfg.GetNodeGroup(self.group_uuid).members)
1580

    
1581
      all_inst_info = self.cfg.GetAllInstancesInfo()
1582

    
1583
      # In Exec(), we warn about mirrored instances that have primary and
1584
      # secondary living in separate node groups. To fully verify that
1585
      # volumes for these instances are healthy, we will need to do an
1586
      # extra call to their secondaries. We ensure here those nodes will
1587
      # be locked.
1588
      for inst in self.glm.list_owned(locking.LEVEL_INSTANCE):
1589
        # Important: access only the instances whose lock is owned
1590
        if all_inst_info[inst].disk_template in constants.DTS_INT_MIRROR:
1591
          nodes.update(all_inst_info[inst].secondary_nodes)
1592

    
1593
      self.needed_locks[locking.LEVEL_NODE] = nodes
1594

    
1595
  def CheckPrereq(self):
1596
    group_nodes = set(self.cfg.GetNodeGroup(self.group_uuid).members)
1597
    group_instances = self.cfg.GetNodeGroupInstances(self.group_uuid)
1598

    
1599
    unlocked_nodes = \
1600
        group_nodes.difference(self.glm.list_owned(locking.LEVEL_NODE))
1601

    
1602
    unlocked_instances = \
1603
        group_instances.difference(self.glm.list_owned(locking.LEVEL_INSTANCE))
1604

    
1605
    if unlocked_nodes:
1606
      raise errors.OpPrereqError("Missing lock for nodes: %s" %
1607
                                 utils.CommaJoin(unlocked_nodes))
1608

    
1609
    if unlocked_instances:
1610
      raise errors.OpPrereqError("Missing lock for instances: %s" %
1611
                                 utils.CommaJoin(unlocked_instances))
1612

    
1613
    self.all_node_info = self.cfg.GetAllNodesInfo()
1614
    self.all_inst_info = self.cfg.GetAllInstancesInfo()
1615

    
1616
    self.my_node_names = utils.NiceSort(group_nodes)
1617
    self.my_inst_names = utils.NiceSort(group_instances)
1618

    
1619
    self.my_node_info = dict((name, self.all_node_info[name])
1620
                             for name in self.my_node_names)
1621

    
1622
    self.my_inst_info = dict((name, self.all_inst_info[name])
1623
                             for name in self.my_inst_names)
1624

    
1625
    # We detect here the nodes that will need the extra RPC calls for verifying
1626
    # split LV volumes; they should be locked.
1627
    extra_lv_nodes = set()
1628

    
1629
    for inst in self.my_inst_info.values():
1630
      if inst.disk_template in constants.DTS_INT_MIRROR:
1631
        group = self.my_node_info[inst.primary_node].group
1632
        for nname in inst.secondary_nodes:
1633
          if self.all_node_info[nname].group != group:
1634
            extra_lv_nodes.add(nname)
1635

    
1636
    unlocked_lv_nodes = \
1637
        extra_lv_nodes.difference(self.glm.list_owned(locking.LEVEL_NODE))
1638

    
1639
    if unlocked_lv_nodes:
1640
      raise errors.OpPrereqError("these nodes could be locked: %s" %
1641
                                 utils.CommaJoin(unlocked_lv_nodes))
1642
    self.extra_lv_nodes = list(extra_lv_nodes)
1643

    
1644
  def _VerifyNode(self, ninfo, nresult):
1645
    """Perform some basic validation on data returned from a node.
1646

1647
      - check the result data structure is well formed and has all the
1648
        mandatory fields
1649
      - check ganeti version
1650

1651
    @type ninfo: L{objects.Node}
1652
    @param ninfo: the node to check
1653
    @param nresult: the results from the node
1654
    @rtype: boolean
1655
    @return: whether overall this call was successful (and we can expect
1656
         reasonable values in the respose)
1657

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

    
1662
    # main result, nresult should be a non-empty dict
1663
    test = not nresult or not isinstance(nresult, dict)
1664
    _ErrorIf(test, self.ENODERPC, node,
1665
                  "unable to verify node: no data returned")
1666
    if test:
1667
      return False
1668

    
1669
    # compares ganeti version
1670
    local_version = constants.PROTOCOL_VERSION
1671
    remote_version = nresult.get("version", None)
1672
    test = not (remote_version and
1673
                isinstance(remote_version, (list, tuple)) and
1674
                len(remote_version) == 2)
1675
    _ErrorIf(test, self.ENODERPC, node,
1676
             "connection to node returned invalid data")
1677
    if test:
1678
      return False
1679

    
1680
    test = local_version != remote_version[0]
1681
    _ErrorIf(test, self.ENODEVERSION, node,
1682
             "incompatible protocol versions: master %s,"
1683
             " node %s", local_version, remote_version[0])
1684
    if test:
1685
      return False
1686

    
1687
    # node seems compatible, we can actually try to look into its results
1688

    
1689
    # full package version
1690
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1691
                  self.ENODEVERSION, node,
1692
                  "software version mismatch: master %s, node %s",
1693
                  constants.RELEASE_VERSION, remote_version[1],
1694
                  code=self.ETYPE_WARNING)
1695

    
1696
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1697
    if ninfo.vm_capable and isinstance(hyp_result, dict):
1698
      for hv_name, hv_result in hyp_result.iteritems():
1699
        test = hv_result is not None
1700
        _ErrorIf(test, self.ENODEHV, node,
1701
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1702

    
1703
    hvp_result = nresult.get(constants.NV_HVPARAMS, None)
1704
    if ninfo.vm_capable and isinstance(hvp_result, list):
1705
      for item, hv_name, hv_result in hvp_result:
1706
        _ErrorIf(True, self.ENODEHV, node,
1707
                 "hypervisor %s parameter verify failure (source %s): %s",
1708
                 hv_name, item, hv_result)
1709

    
1710
    test = nresult.get(constants.NV_NODESETUP,
1711
                       ["Missing NODESETUP results"])
1712
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1713
             "; ".join(test))
1714

    
1715
    return True
1716

    
1717
  def _VerifyNodeTime(self, ninfo, nresult,
1718
                      nvinfo_starttime, nvinfo_endtime):
1719
    """Check the node time.
1720

1721
    @type ninfo: L{objects.Node}
1722
    @param ninfo: the node to check
1723
    @param nresult: the remote results for the node
1724
    @param nvinfo_starttime: the start time of the RPC call
1725
    @param nvinfo_endtime: the end time of the RPC call
1726

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

    
1731
    ntime = nresult.get(constants.NV_TIME, None)
1732
    try:
1733
      ntime_merged = utils.MergeTime(ntime)
1734
    except (ValueError, TypeError):
1735
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1736
      return
1737

    
1738
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1739
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1740
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1741
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1742
    else:
1743
      ntime_diff = None
1744

    
1745
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1746
             "Node time diverges by at least %s from master node time",
1747
             ntime_diff)
1748

    
1749
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1750
    """Check the node LVM results.
1751

1752
    @type ninfo: L{objects.Node}
1753
    @param ninfo: the node to check
1754
    @param nresult: the remote results for the node
1755
    @param vg_name: the configured VG name
1756

1757
    """
1758
    if vg_name is None:
1759
      return
1760

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

    
1764
    # checks vg existence and size > 20G
1765
    vglist = nresult.get(constants.NV_VGLIST, None)
1766
    test = not vglist
1767
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1768
    if not test:
1769
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1770
                                            constants.MIN_VG_SIZE)
1771
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1772

    
1773
    # check pv names
1774
    pvlist = nresult.get(constants.NV_PVLIST, None)
1775
    test = pvlist is None
1776
    _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1777
    if not test:
1778
      # check that ':' is not present in PV names, since it's a
1779
      # special character for lvcreate (denotes the range of PEs to
1780
      # use on the PV)
1781
      for _, pvname, owner_vg in pvlist:
1782
        test = ":" in pvname
1783
        _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1784
                 " '%s' of VG '%s'", pvname, owner_vg)
1785

    
1786
  def _VerifyNodeBridges(self, ninfo, nresult, bridges):
1787
    """Check the node bridges.
1788

1789
    @type ninfo: L{objects.Node}
1790
    @param ninfo: the node to check
1791
    @param nresult: the remote results for the node
1792
    @param bridges: the expected list of bridges
1793

1794
    """
1795
    if not bridges:
1796
      return
1797

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

    
1801
    missing = nresult.get(constants.NV_BRIDGES, None)
1802
    test = not isinstance(missing, list)
1803
    _ErrorIf(test, self.ENODENET, node,
1804
             "did not return valid bridge information")
1805
    if not test:
1806
      _ErrorIf(bool(missing), self.ENODENET, node, "missing bridges: %s" %
1807
               utils.CommaJoin(sorted(missing)))
1808

    
1809
  def _VerifyNodeNetwork(self, ninfo, nresult):
1810
    """Check the node network connectivity results.
1811

1812
    @type ninfo: L{objects.Node}
1813
    @param ninfo: the node to check
1814
    @param nresult: the remote results for the node
1815

1816
    """
1817
    node = ninfo.name
1818
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1819

    
1820
    test = constants.NV_NODELIST not in nresult
1821
    _ErrorIf(test, self.ENODESSH, node,
1822
             "node hasn't returned node ssh connectivity data")
1823
    if not test:
1824
      if nresult[constants.NV_NODELIST]:
1825
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1826
          _ErrorIf(True, self.ENODESSH, node,
1827
                   "ssh communication with node '%s': %s", a_node, a_msg)
1828

    
1829
    test = constants.NV_NODENETTEST not in nresult
1830
    _ErrorIf(test, self.ENODENET, node,
1831
             "node hasn't returned node tcp connectivity data")
1832
    if not test:
1833
      if nresult[constants.NV_NODENETTEST]:
1834
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1835
        for anode in nlist:
1836
          _ErrorIf(True, self.ENODENET, node,
1837
                   "tcp communication with node '%s': %s",
1838
                   anode, nresult[constants.NV_NODENETTEST][anode])
1839

    
1840
    test = constants.NV_MASTERIP not in nresult
1841
    _ErrorIf(test, self.ENODENET, node,
1842
             "node hasn't returned node master IP reachability data")
1843
    if not test:
1844
      if not nresult[constants.NV_MASTERIP]:
1845
        if node == self.master_node:
1846
          msg = "the master node cannot reach the master IP (not configured?)"
1847
        else:
1848
          msg = "cannot reach the master IP"
1849
        _ErrorIf(True, self.ENODENET, node, msg)
1850

    
1851
  def _VerifyInstance(self, instance, instanceconfig, node_image,
1852
                      diskstatus):
1853
    """Verify an instance.
1854

1855
    This function checks to see if the required block devices are
1856
    available on the instance's node.
1857

1858
    """
1859
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1860
    node_current = instanceconfig.primary_node
1861

    
1862
    node_vol_should = {}
1863
    instanceconfig.MapLVsByNode(node_vol_should)
1864

    
1865
    for node in node_vol_should:
1866
      n_img = node_image[node]
1867
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1868
        # ignore missing volumes on offline or broken nodes
1869
        continue
1870
      for volume in node_vol_should[node]:
1871
        test = volume not in n_img.volumes
1872
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1873
                 "volume %s missing on node %s", volume, node)
1874

    
1875
    if instanceconfig.admin_up:
1876
      pri_img = node_image[node_current]
1877
      test = instance not in pri_img.instances and not pri_img.offline
1878
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1879
               "instance not running on its primary node %s",
1880
               node_current)
1881

    
1882
    diskdata = [(nname, success, status, idx)
1883
                for (nname, disks) in diskstatus.items()
1884
                for idx, (success, status) in enumerate(disks)]
1885

    
1886
    for nname, success, bdev_status, idx in diskdata:
1887
      # the 'ghost node' construction in Exec() ensures that we have a
1888
      # node here
1889
      snode = node_image[nname]
1890
      bad_snode = snode.ghost or snode.offline
1891
      _ErrorIf(instanceconfig.admin_up and not success and not bad_snode,
1892
               self.EINSTANCEFAULTYDISK, instance,
1893
               "couldn't retrieve status for disk/%s on %s: %s",
1894
               idx, nname, bdev_status)
1895
      _ErrorIf((instanceconfig.admin_up and success and
1896
                bdev_status.ldisk_status == constants.LDS_FAULTY),
1897
               self.EINSTANCEFAULTYDISK, instance,
1898
               "disk/%s on %s is faulty", idx, nname)
1899

    
1900
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1901
    """Verify if there are any unknown volumes in the cluster.
1902

1903
    The .os, .swap and backup volumes are ignored. All other volumes are
1904
    reported as unknown.
1905

1906
    @type reserved: L{ganeti.utils.FieldSet}
1907
    @param reserved: a FieldSet of reserved volume names
1908

1909
    """
1910
    for node, n_img in node_image.items():
1911
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1912
        # skip non-healthy nodes
1913
        continue
1914
      for volume in n_img.volumes:
1915
        test = ((node not in node_vol_should or
1916
                volume not in node_vol_should[node]) and
1917
                not reserved.Matches(volume))
1918
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1919
                      "volume %s is unknown", volume)
1920

    
1921
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1922
    """Verify N+1 Memory Resilience.
1923

1924
    Check that if one single node dies we can still start all the
1925
    instances it was primary for.
1926

1927
    """
1928
    cluster_info = self.cfg.GetClusterInfo()
1929
    for node, n_img in node_image.items():
1930
      # This code checks that every node which is now listed as
1931
      # secondary has enough memory to host all instances it is
1932
      # supposed to should a single other node in the cluster fail.
1933
      # FIXME: not ready for failover to an arbitrary node
1934
      # FIXME: does not support file-backed instances
1935
      # WARNING: we currently take into account down instances as well
1936
      # as up ones, considering that even if they're down someone
1937
      # might want to start them even in the event of a node failure.
1938
      if n_img.offline:
1939
        # we're skipping offline nodes from the N+1 warning, since
1940
        # most likely we don't have good memory infromation from them;
1941
        # we already list instances living on such nodes, and that's
1942
        # enough warning
1943
        continue
1944
      for prinode, instances in n_img.sbp.items():
1945
        needed_mem = 0
1946
        for instance in instances:
1947
          bep = cluster_info.FillBE(instance_cfg[instance])
1948
          if bep[constants.BE_AUTO_BALANCE]:
1949
            needed_mem += bep[constants.BE_MEMORY]
1950
        test = n_img.mfree < needed_mem
1951
        self._ErrorIf(test, self.ENODEN1, node,
1952
                      "not enough memory to accomodate instance failovers"
1953
                      " should node %s fail (%dMiB needed, %dMiB available)",
1954
                      prinode, needed_mem, n_img.mfree)
1955

    
1956
  @classmethod
1957
  def _VerifyFiles(cls, errorif, nodeinfo, master_node, all_nvinfo,
1958
                   (files_all, files_all_opt, files_mc, files_vm)):
1959
    """Verifies file checksums collected from all nodes.
1960

1961
    @param errorif: Callback for reporting errors
1962
    @param nodeinfo: List of L{objects.Node} objects
1963
    @param master_node: Name of master node
1964
    @param all_nvinfo: RPC results
1965

1966
    """
1967
    node_names = frozenset(node.name for node in nodeinfo)
1968

    
1969
    assert master_node in node_names
1970
    assert (len(files_all | files_all_opt | files_mc | files_vm) ==
1971
            sum(map(len, [files_all, files_all_opt, files_mc, files_vm]))), \
1972
           "Found file listed in more than one file list"
1973

    
1974
    # Define functions determining which nodes to consider for a file
1975
    file2nodefn = dict([(filename, fn)
1976
      for (files, fn) in [(files_all, None),
1977
                          (files_all_opt, None),
1978
                          (files_mc, lambda node: (node.master_candidate or
1979
                                                   node.name == master_node)),
1980
                          (files_vm, lambda node: node.vm_capable)]
1981
      for filename in files])
1982

    
1983
    fileinfo = dict((filename, {}) for filename in file2nodefn.keys())
1984

    
1985
    for node in nodeinfo:
1986
      nresult = all_nvinfo[node.name]
1987

    
1988
      if nresult.fail_msg or not nresult.payload:
1989
        node_files = None
1990
      else:
1991
        node_files = nresult.payload.get(constants.NV_FILELIST, None)
1992

    
1993
      test = not (node_files and isinstance(node_files, dict))
1994
      errorif(test, cls.ENODEFILECHECK, node.name,
1995
              "Node did not return file checksum data")
1996
      if test:
1997
        continue
1998

    
1999
      for (filename, checksum) in node_files.items():
2000
        # Check if the file should be considered for a node
2001
        fn = file2nodefn[filename]
2002
        if fn is None or fn(node):
2003
          fileinfo[filename].setdefault(checksum, set()).add(node.name)
2004

    
2005
    for (filename, checksums) in fileinfo.items():
2006
      assert compat.all(len(i) > 10 for i in checksums), "Invalid checksum"
2007

    
2008
      # Nodes having the file
2009
      with_file = frozenset(node_name
2010
                            for nodes in fileinfo[filename].values()
2011
                            for node_name in nodes)
2012

    
2013
      # Nodes missing file
2014
      missing_file = node_names - with_file
2015

    
2016
      if filename in files_all_opt:
2017
        # All or no nodes
2018
        errorif(missing_file and missing_file != node_names,
2019
                cls.ECLUSTERFILECHECK, None,
2020
                "File %s is optional, but it must exist on all or no"
2021
                " nodes (not found on %s)",
2022
                filename, utils.CommaJoin(utils.NiceSort(missing_file)))
2023
      else:
2024
        errorif(missing_file, cls.ECLUSTERFILECHECK, None,
2025
                "File %s is missing from node(s) %s", filename,
2026
                utils.CommaJoin(utils.NiceSort(missing_file)))
2027

    
2028
      # See if there are multiple versions of the file
2029
      test = len(checksums) > 1
2030
      if test:
2031
        variants = ["variant %s on %s" %
2032
                    (idx + 1, utils.CommaJoin(utils.NiceSort(nodes)))
2033
                    for (idx, (checksum, nodes)) in
2034
                      enumerate(sorted(checksums.items()))]
2035
      else:
2036
        variants = []
2037

    
2038
      errorif(test, cls.ECLUSTERFILECHECK, None,
2039
              "File %s found with %s different checksums (%s)",
2040
              filename, len(checksums), "; ".join(variants))
2041

    
2042
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
2043
                      drbd_map):
2044
    """Verifies and the node DRBD status.
2045

2046
    @type ninfo: L{objects.Node}
2047
    @param ninfo: the node to check
2048
    @param nresult: the remote results for the node
2049
    @param instanceinfo: the dict of instances
2050
    @param drbd_helper: the configured DRBD usermode helper
2051
    @param drbd_map: the DRBD map as returned by
2052
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
2053

2054
    """
2055
    node = ninfo.name
2056
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2057

    
2058
    if drbd_helper:
2059
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
2060
      test = (helper_result == None)
2061
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
2062
               "no drbd usermode helper returned")
2063
      if helper_result:
2064
        status, payload = helper_result
2065
        test = not status
2066
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
2067
                 "drbd usermode helper check unsuccessful: %s", payload)
2068
        test = status and (payload != drbd_helper)
2069
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
2070
                 "wrong drbd usermode helper: %s", payload)
2071

    
2072
    # compute the DRBD minors
2073
    node_drbd = {}
2074
    for minor, instance in drbd_map[node].items():
2075
      test = instance not in instanceinfo
2076
      _ErrorIf(test, self.ECLUSTERCFG, None,
2077
               "ghost instance '%s' in temporary DRBD map", instance)
2078
        # ghost instance should not be running, but otherwise we
2079
        # don't give double warnings (both ghost instance and
2080
        # unallocated minor in use)
2081
      if test:
2082
        node_drbd[minor] = (instance, False)
2083
      else:
2084
        instance = instanceinfo[instance]
2085
        node_drbd[minor] = (instance.name, instance.admin_up)
2086

    
2087
    # and now check them
2088
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
2089
    test = not isinstance(used_minors, (tuple, list))
2090
    _ErrorIf(test, self.ENODEDRBD, node,
2091
             "cannot parse drbd status file: %s", str(used_minors))
2092
    if test:
2093
      # we cannot check drbd status
2094
      return
2095

    
2096
    for minor, (iname, must_exist) in node_drbd.items():
2097
      test = minor not in used_minors and must_exist
2098
      _ErrorIf(test, self.ENODEDRBD, node,
2099
               "drbd minor %d of instance %s is not active", minor, iname)
2100
    for minor in used_minors:
2101
      test = minor not in node_drbd
2102
      _ErrorIf(test, self.ENODEDRBD, node,
2103
               "unallocated drbd minor %d is in use", minor)
2104

    
2105
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
2106
    """Builds the node OS structures.
2107

2108
    @type ninfo: L{objects.Node}
2109
    @param ninfo: the node to check
2110
    @param nresult: the remote results for the node
2111
    @param nimg: the node image object
2112

2113
    """
2114
    node = ninfo.name
2115
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2116

    
2117
    remote_os = nresult.get(constants.NV_OSLIST, None)
2118
    test = (not isinstance(remote_os, list) or
2119
            not compat.all(isinstance(v, list) and len(v) == 7
2120
                           for v in remote_os))
2121

    
2122
    _ErrorIf(test, self.ENODEOS, node,
2123
             "node hasn't returned valid OS data")
2124

    
2125
    nimg.os_fail = test
2126

    
2127
    if test:
2128
      return
2129

    
2130
    os_dict = {}
2131

    
2132
    for (name, os_path, status, diagnose,
2133
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
2134

    
2135
      if name not in os_dict:
2136
        os_dict[name] = []
2137

    
2138
      # parameters is a list of lists instead of list of tuples due to
2139
      # JSON lacking a real tuple type, fix it:
2140
      parameters = [tuple(v) for v in parameters]
2141
      os_dict[name].append((os_path, status, diagnose,
2142
                            set(variants), set(parameters), set(api_ver)))
2143

    
2144
    nimg.oslist = os_dict
2145

    
2146
  def _VerifyNodeOS(self, ninfo, nimg, base):
2147
    """Verifies the node OS list.
2148

2149
    @type ninfo: L{objects.Node}
2150
    @param ninfo: the node to check
2151
    @param nimg: the node image object
2152
    @param base: the 'template' node we match against (e.g. from the master)
2153

2154
    """
2155
    node = ninfo.name
2156
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2157

    
2158
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
2159

    
2160
    beautify_params = lambda l: ["%s: %s" % (k, v) for (k, v) in l]
2161
    for os_name, os_data in nimg.oslist.items():
2162
      assert os_data, "Empty OS status for OS %s?!" % os_name
2163
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
2164
      _ErrorIf(not f_status, self.ENODEOS, node,
2165
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
2166
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
2167
               "OS '%s' has multiple entries (first one shadows the rest): %s",
2168
               os_name, utils.CommaJoin([v[0] for v in os_data]))
2169
      # this will catched in backend too
2170
      _ErrorIf(compat.any(v >= constants.OS_API_V15 for v in f_api)
2171
               and not f_var, self.ENODEOS, node,
2172
               "OS %s with API at least %d does not declare any variant",
2173
               os_name, constants.OS_API_V15)
2174
      # comparisons with the 'base' image
2175
      test = os_name not in base.oslist
2176
      _ErrorIf(test, self.ENODEOS, node,
2177
               "Extra OS %s not present on reference node (%s)",
2178
               os_name, base.name)
2179
      if test:
2180
        continue
2181
      assert base.oslist[os_name], "Base node has empty OS status?"
2182
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
2183
      if not b_status:
2184
        # base OS is invalid, skipping
2185
        continue
2186
      for kind, a, b in [("API version", f_api, b_api),
2187
                         ("variants list", f_var, b_var),
2188
                         ("parameters", beautify_params(f_param),
2189
                          beautify_params(b_param))]:
2190
        _ErrorIf(a != b, self.ENODEOS, node,
2191
                 "OS %s for %s differs from reference node %s: [%s] vs. [%s]",
2192
                 kind, os_name, base.name,
2193
                 utils.CommaJoin(sorted(a)), utils.CommaJoin(sorted(b)))
2194

    
2195
    # check any missing OSes
2196
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
2197
    _ErrorIf(missing, self.ENODEOS, node,
2198
             "OSes present on reference node %s but missing on this node: %s",
2199
             base.name, utils.CommaJoin(missing))
2200

    
2201
  def _VerifyOob(self, ninfo, nresult):
2202
    """Verifies out of band functionality of a node.
2203

2204
    @type ninfo: L{objects.Node}
2205
    @param ninfo: the node to check
2206
    @param nresult: the remote results for the node
2207

2208
    """
2209
    node = ninfo.name
2210
    # We just have to verify the paths on master and/or master candidates
2211
    # as the oob helper is invoked on the master
2212
    if ((ninfo.master_candidate or ninfo.master_capable) and
2213
        constants.NV_OOB_PATHS in nresult):
2214
      for path_result in nresult[constants.NV_OOB_PATHS]:
2215
        self._ErrorIf(path_result, self.ENODEOOBPATH, node, path_result)
2216

    
2217
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
2218
    """Verifies and updates the node volume data.
2219

2220
    This function will update a L{NodeImage}'s internal structures
2221
    with data from the remote call.
2222

2223
    @type ninfo: L{objects.Node}
2224
    @param ninfo: the node to check
2225
    @param nresult: the remote results for the node
2226
    @param nimg: the node image object
2227
    @param vg_name: the configured VG name
2228

2229
    """
2230
    node = ninfo.name
2231
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2232

    
2233
    nimg.lvm_fail = True
2234
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
2235
    if vg_name is None:
2236
      pass
2237
    elif isinstance(lvdata, basestring):
2238
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
2239
               utils.SafeEncode(lvdata))
2240
    elif not isinstance(lvdata, dict):
2241
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
2242
    else:
2243
      nimg.volumes = lvdata
2244
      nimg.lvm_fail = False
2245

    
2246
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
2247
    """Verifies and updates the node instance list.
2248

2249
    If the listing was successful, then updates this node's instance
2250
    list. Otherwise, it marks the RPC call as failed for the instance
2251
    list key.
2252

2253
    @type ninfo: L{objects.Node}
2254
    @param ninfo: the node to check
2255
    @param nresult: the remote results for the node
2256
    @param nimg: the node image object
2257

2258
    """
2259
    idata = nresult.get(constants.NV_INSTANCELIST, None)
2260
    test = not isinstance(idata, list)
2261
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
2262
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
2263
    if test:
2264
      nimg.hyp_fail = True
2265
    else:
2266
      nimg.instances = idata
2267

    
2268
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
2269
    """Verifies and computes a node information map
2270

2271
    @type ninfo: L{objects.Node}
2272
    @param ninfo: the node to check
2273
    @param nresult: the remote results for the node
2274
    @param nimg: the node image object
2275
    @param vg_name: the configured VG name
2276

2277
    """
2278
    node = ninfo.name
2279
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2280

    
2281
    # try to read free memory (from the hypervisor)
2282
    hv_info = nresult.get(constants.NV_HVINFO, None)
2283
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
2284
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
2285
    if not test:
2286
      try:
2287
        nimg.mfree = int(hv_info["memory_free"])
2288
      except (ValueError, TypeError):
2289
        _ErrorIf(True, self.ENODERPC, node,
2290
                 "node returned invalid nodeinfo, check hypervisor")
2291

    
2292
    # FIXME: devise a free space model for file based instances as well
2293
    if vg_name is not None:
2294
      test = (constants.NV_VGLIST not in nresult or
2295
              vg_name not in nresult[constants.NV_VGLIST])
2296
      _ErrorIf(test, self.ENODELVM, node,
2297
               "node didn't return data for the volume group '%s'"
2298
               " - it is either missing or broken", vg_name)
2299
      if not test:
2300
        try:
2301
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
2302
        except (ValueError, TypeError):
2303
          _ErrorIf(True, self.ENODERPC, node,
2304
                   "node returned invalid LVM info, check LVM status")
2305

    
2306
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
2307
    """Gets per-disk status information for all instances.
2308

2309
    @type nodelist: list of strings
2310
    @param nodelist: Node names
2311
    @type node_image: dict of (name, L{objects.Node})
2312
    @param node_image: Node objects
2313
    @type instanceinfo: dict of (name, L{objects.Instance})
2314
    @param instanceinfo: Instance objects
2315
    @rtype: {instance: {node: [(succes, payload)]}}
2316
    @return: a dictionary of per-instance dictionaries with nodes as
2317
        keys and disk information as values; the disk information is a
2318
        list of tuples (success, payload)
2319

2320
    """
2321
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2322

    
2323
    node_disks = {}
2324
    node_disks_devonly = {}
2325
    diskless_instances = set()
2326
    diskless = constants.DT_DISKLESS
2327

    
2328
    for nname in nodelist:
2329
      node_instances = list(itertools.chain(node_image[nname].pinst,
2330
                                            node_image[nname].sinst))
2331
      diskless_instances.update(inst for inst in node_instances
2332
                                if instanceinfo[inst].disk_template == diskless)
2333
      disks = [(inst, disk)
2334
               for inst in node_instances
2335
               for disk in instanceinfo[inst].disks]
2336

    
2337
      if not disks:
2338
        # No need to collect data
2339
        continue
2340

    
2341
      node_disks[nname] = disks
2342

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

    
2347
      for dev in devonly:
2348
        self.cfg.SetDiskID(dev, nname)
2349

    
2350
      node_disks_devonly[nname] = devonly
2351

    
2352
    assert len(node_disks) == len(node_disks_devonly)
2353

    
2354
    # Collect data from all nodes with disks
2355
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
2356
                                                          node_disks_devonly)
2357

    
2358
    assert len(result) == len(node_disks)
2359

    
2360
    instdisk = {}
2361

    
2362
    for (nname, nres) in result.items():
2363
      disks = node_disks[nname]
2364

    
2365
      if nres.offline:
2366
        # No data from this node
2367
        data = len(disks) * [(False, "node offline")]
2368
      else:
2369
        msg = nres.fail_msg
2370
        _ErrorIf(msg, self.ENODERPC, nname,
2371
                 "while getting disk information: %s", msg)
2372
        if msg:
2373
          # No data from this node
2374
          data = len(disks) * [(False, msg)]
2375
        else:
2376
          data = []
2377
          for idx, i in enumerate(nres.payload):
2378
            if isinstance(i, (tuple, list)) and len(i) == 2:
2379
              data.append(i)
2380
            else:
2381
              logging.warning("Invalid result from node %s, entry %d: %s",
2382
                              nname, idx, i)
2383
              data.append((False, "Invalid result from the remote node"))
2384

    
2385
      for ((inst, _), status) in zip(disks, data):
2386
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
2387

    
2388
    # Add empty entries for diskless instances.
2389
    for inst in diskless_instances:
2390
      assert inst not in instdisk
2391
      instdisk[inst] = {}
2392

    
2393
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
2394
                      len(nnames) <= len(instanceinfo[inst].all_nodes) and
2395
                      compat.all(isinstance(s, (tuple, list)) and
2396
                                 len(s) == 2 for s in statuses)
2397
                      for inst, nnames in instdisk.items()
2398
                      for nname, statuses in nnames.items())
2399
    assert set(instdisk) == set(instanceinfo), "instdisk consistency failure"
2400

    
2401
    return instdisk
2402

    
2403
  def BuildHooksEnv(self):
2404
    """Build hooks env.
2405

2406
    Cluster-Verify hooks just ran in the post phase and their failure makes
2407
    the output be logged in the verify output and the verification to fail.
2408

2409
    """
2410
    env = {
2411
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2412
      }
2413

    
2414
    env.update(("NODE_TAGS_%s" % node.name, " ".join(node.GetTags()))
2415
               for node in self.my_node_info.values())
2416

    
2417
    return env
2418

    
2419
  def BuildHooksNodes(self):
2420
    """Build hooks nodes.
2421

2422
    """
2423
    return ([], self.my_node_names)
2424

    
2425
  def Exec(self, feedback_fn):
2426
    """Verify integrity of the node group, performing various test on nodes.
2427

2428
    """
2429
    # This method has too many local variables. pylint: disable-msg=R0914
2430

    
2431
    if not self.my_node_names:
2432
      # empty node group
2433
      feedback_fn("* Empty node group, skipping verification")
2434
      return True
2435

    
2436
    self.bad = False
2437
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2438
    verbose = self.op.verbose
2439
    self._feedback_fn = feedback_fn
2440

    
2441
    vg_name = self.cfg.GetVGName()
2442
    drbd_helper = self.cfg.GetDRBDHelper()
2443
    cluster = self.cfg.GetClusterInfo()
2444
    groupinfo = self.cfg.GetAllNodeGroupsInfo()
2445
    hypervisors = cluster.enabled_hypervisors
2446
    node_data_list = [self.my_node_info[name] for name in self.my_node_names]
2447

    
2448
    i_non_redundant = [] # Non redundant instances
2449
    i_non_a_balanced = [] # Non auto-balanced instances
2450
    n_offline = 0 # Count of offline nodes
2451
    n_drained = 0 # Count of nodes being drained
2452
    node_vol_should = {}
2453

    
2454
    # FIXME: verify OS list
2455

    
2456
    # File verification
2457
    filemap = _ComputeAncillaryFiles(cluster, False)
2458

    
2459
    # do local checksums
2460
    master_node = self.master_node = self.cfg.GetMasterNode()
2461
    master_ip = self.cfg.GetMasterIP()
2462

    
2463
    feedback_fn("* Gathering data (%d nodes)" % len(self.my_node_names))
2464

    
2465
    # We will make nodes contact all nodes in their group, and one node from
2466
    # every other group.
2467
    # TODO: should it be a *random* node, different every time?
2468
    online_nodes = [node.name for node in node_data_list if not node.offline]
2469
    other_group_nodes = {}
2470

    
2471
    for name in sorted(self.all_node_info):
2472
      node = self.all_node_info[name]
2473
      if (node.group not in other_group_nodes
2474
          and node.group != self.group_uuid
2475
          and not node.offline):
2476
        other_group_nodes[node.group] = node.name
2477

    
2478
    node_verify_param = {
2479
      constants.NV_FILELIST:
2480
        utils.UniqueSequence(filename
2481
                             for files in filemap
2482
                             for filename in files),
2483
      constants.NV_NODELIST: online_nodes + other_group_nodes.values(),
2484
      constants.NV_HYPERVISOR: hypervisors,
2485
      constants.NV_HVPARAMS:
2486
        _GetAllHypervisorParameters(cluster, self.all_inst_info.values()),
2487
      constants.NV_NODENETTEST: [(node.name, node.primary_ip, node.secondary_ip)
2488
                                 for node in node_data_list
2489
                                 if not node.offline],
2490
      constants.NV_INSTANCELIST: hypervisors,
2491
      constants.NV_VERSION: None,
2492
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2493
      constants.NV_NODESETUP: None,
2494
      constants.NV_TIME: None,
2495
      constants.NV_MASTERIP: (master_node, master_ip),
2496
      constants.NV_OSLIST: None,
2497
      constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2498
      }
2499

    
2500
    if vg_name is not None:
2501
      node_verify_param[constants.NV_VGLIST] = None
2502
      node_verify_param[constants.NV_LVLIST] = vg_name
2503
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2504
      node_verify_param[constants.NV_DRBDLIST] = None
2505

    
2506
    if drbd_helper:
2507
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2508

    
2509
    # bridge checks
2510
    # FIXME: this needs to be changed per node-group, not cluster-wide
2511
    bridges = set()
2512
    default_nicpp = cluster.nicparams[constants.PP_DEFAULT]
2513
    if default_nicpp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2514
      bridges.add(default_nicpp[constants.NIC_LINK])
2515
    for instance in self.my_inst_info.values():
2516
      for nic in instance.nics:
2517
        full_nic = cluster.SimpleFillNIC(nic.nicparams)
2518
        if full_nic[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2519
          bridges.add(full_nic[constants.NIC_LINK])
2520

    
2521
    if bridges:
2522
      node_verify_param[constants.NV_BRIDGES] = list(bridges)
2523

    
2524
    # Build our expected cluster state
2525
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2526
                                                 name=node.name,
2527
                                                 vm_capable=node.vm_capable))
2528
                      for node in node_data_list)
2529

    
2530
    # Gather OOB paths
2531
    oob_paths = []
2532
    for node in self.all_node_info.values():
2533
      path = _SupportsOob(self.cfg, node)
2534
      if path and path not in oob_paths:
2535
        oob_paths.append(path)
2536

    
2537
    if oob_paths:
2538
      node_verify_param[constants.NV_OOB_PATHS] = oob_paths
2539

    
2540
    for instance in self.my_inst_names:
2541
      inst_config = self.my_inst_info[instance]
2542

    
2543
      for nname in inst_config.all_nodes:
2544
        if nname not in node_image:
2545
          gnode = self.NodeImage(name=nname)
2546
          gnode.ghost = (nname not in self.all_node_info)
2547
          node_image[nname] = gnode
2548

    
2549
      inst_config.MapLVsByNode(node_vol_should)
2550

    
2551
      pnode = inst_config.primary_node
2552
      node_image[pnode].pinst.append(instance)
2553

    
2554
      for snode in inst_config.secondary_nodes:
2555
        nimg = node_image[snode]
2556
        nimg.sinst.append(instance)
2557
        if pnode not in nimg.sbp:
2558
          nimg.sbp[pnode] = []
2559
        nimg.sbp[pnode].append(instance)
2560

    
2561
    # At this point, we have the in-memory data structures complete,
2562
    # except for the runtime information, which we'll gather next
2563

    
2564
    # Due to the way our RPC system works, exact response times cannot be
2565
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2566
    # time before and after executing the request, we can at least have a time
2567
    # window.
2568
    nvinfo_starttime = time.time()
2569
    all_nvinfo = self.rpc.call_node_verify(self.my_node_names,
2570
                                           node_verify_param,
2571
                                           self.cfg.GetClusterName())
2572
    nvinfo_endtime = time.time()
2573

    
2574
    if self.extra_lv_nodes and vg_name is not None:
2575
      extra_lv_nvinfo = \
2576
          self.rpc.call_node_verify(self.extra_lv_nodes,
2577
                                    {constants.NV_LVLIST: vg_name},
2578
                                    self.cfg.GetClusterName())
2579
    else:
2580
      extra_lv_nvinfo = {}
2581

    
2582
    all_drbd_map = self.cfg.ComputeDRBDMap()
2583

    
2584
    feedback_fn("* Gathering disk information (%s nodes)" %
2585
                len(self.my_node_names))
2586
    instdisk = self._CollectDiskInfo(self.my_node_names, node_image,
2587
                                     self.my_inst_info)
2588

    
2589
    feedback_fn("* Verifying configuration file consistency")
2590

    
2591
    # If not all nodes are being checked, we need to make sure the master node
2592
    # and a non-checked vm_capable node are in the list.
2593
    absent_nodes = set(self.all_node_info).difference(self.my_node_info)
2594
    if absent_nodes:
2595
      vf_nvinfo = all_nvinfo.copy()
2596
      vf_node_info = list(self.my_node_info.values())
2597
      additional_nodes = []
2598
      if master_node not in self.my_node_info:
2599
        additional_nodes.append(master_node)
2600
        vf_node_info.append(self.all_node_info[master_node])
2601
      # Add the first vm_capable node we find which is not included
2602
      for node in absent_nodes:
2603
        nodeinfo = self.all_node_info[node]
2604
        if nodeinfo.vm_capable and not nodeinfo.offline:
2605
          additional_nodes.append(node)
2606
          vf_node_info.append(self.all_node_info[node])
2607
          break
2608
      key = constants.NV_FILELIST
2609
      vf_nvinfo.update(self.rpc.call_node_verify(additional_nodes,
2610
                                                 {key: node_verify_param[key]},
2611
                                                 self.cfg.GetClusterName()))
2612
    else:
2613
      vf_nvinfo = all_nvinfo
2614
      vf_node_info = self.my_node_info.values()
2615

    
2616
    self._VerifyFiles(_ErrorIf, vf_node_info, master_node, vf_nvinfo, filemap)
2617

    
2618
    feedback_fn("* Verifying node status")
2619

    
2620
    refos_img = None
2621

    
2622
    for node_i in node_data_list:
2623
      node = node_i.name
2624
      nimg = node_image[node]
2625

    
2626
      if node_i.offline:
2627
        if verbose:
2628
          feedback_fn("* Skipping offline node %s" % (node,))
2629
        n_offline += 1
2630
        continue
2631

    
2632
      if node == master_node:
2633
        ntype = "master"
2634
      elif node_i.master_candidate:
2635
        ntype = "master candidate"
2636
      elif node_i.drained:
2637
        ntype = "drained"
2638
        n_drained += 1
2639
      else:
2640
        ntype = "regular"
2641
      if verbose:
2642
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2643

    
2644
      msg = all_nvinfo[node].fail_msg
2645
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2646
      if msg:
2647
        nimg.rpc_fail = True
2648
        continue
2649

    
2650
      nresult = all_nvinfo[node].payload
2651

    
2652
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2653
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2654
      self._VerifyNodeNetwork(node_i, nresult)
2655
      self._VerifyOob(node_i, nresult)
2656

    
2657
      if nimg.vm_capable:
2658
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2659
        self._VerifyNodeDrbd(node_i, nresult, self.all_inst_info, drbd_helper,
2660
                             all_drbd_map)
2661

    
2662
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2663
        self._UpdateNodeInstances(node_i, nresult, nimg)
2664
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2665
        self._UpdateNodeOS(node_i, nresult, nimg)
2666

    
2667
        if not nimg.os_fail:
2668
          if refos_img is None:
2669
            refos_img = nimg
2670
          self._VerifyNodeOS(node_i, nimg, refos_img)
2671
        self._VerifyNodeBridges(node_i, nresult, bridges)
2672

    
2673
        # Check whether all running instancies are primary for the node. (This
2674
        # can no longer be done from _VerifyInstance below, since some of the
2675
        # wrong instances could be from other node groups.)
2676
        non_primary_inst = set(nimg.instances).difference(nimg.pinst)
2677

    
2678
        for inst in non_primary_inst:
2679
          test = inst in self.all_inst_info
2680
          _ErrorIf(test, self.EINSTANCEWRONGNODE, inst,
2681
                   "instance should not run on node %s", node_i.name)
2682
          _ErrorIf(not test, self.ENODEORPHANINSTANCE, node_i.name,
2683
                   "node is running unknown instance %s", inst)
2684

    
2685
    for node, result in extra_lv_nvinfo.items():
2686
      self._UpdateNodeVolumes(self.all_node_info[node], result.payload,
2687
                              node_image[node], vg_name)
2688

    
2689
    feedback_fn("* Verifying instance status")
2690
    for instance in self.my_inst_names:
2691
      if verbose:
2692
        feedback_fn("* Verifying instance %s" % instance)
2693
      inst_config = self.my_inst_info[instance]
2694
      self._VerifyInstance(instance, inst_config, node_image,
2695
                           instdisk[instance])
2696
      inst_nodes_offline = []
2697

    
2698
      pnode = inst_config.primary_node
2699
      pnode_img = node_image[pnode]
2700
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2701
               self.ENODERPC, pnode, "instance %s, connection to"
2702
               " primary node failed", instance)
2703

    
2704
      _ErrorIf(inst_config.admin_up and pnode_img.offline,
2705
               self.EINSTANCEBADNODE, instance,
2706
               "instance is marked as running and lives on offline node %s",
2707
               inst_config.primary_node)
2708

    
2709
      # If the instance is non-redundant we cannot survive losing its primary
2710
      # node, so we are not N+1 compliant. On the other hand we have no disk
2711
      # templates with more than one secondary so that situation is not well
2712
      # supported either.
2713
      # FIXME: does not support file-backed instances
2714
      if not inst_config.secondary_nodes:
2715
        i_non_redundant.append(instance)
2716

    
2717
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2718
               instance, "instance has multiple secondary nodes: %s",
2719
               utils.CommaJoin(inst_config.secondary_nodes),
2720
               code=self.ETYPE_WARNING)
2721

    
2722
      if inst_config.disk_template in constants.DTS_INT_MIRROR:
2723
        pnode = inst_config.primary_node
2724
        instance_nodes = utils.NiceSort(inst_config.all_nodes)
2725
        instance_groups = {}
2726

    
2727
        for node in instance_nodes:
2728
          instance_groups.setdefault(self.all_node_info[node].group,
2729
                                     []).append(node)
2730

    
2731
        pretty_list = [
2732
          "%s (group %s)" % (utils.CommaJoin(nodes), groupinfo[group].name)
2733
          # Sort so that we always list the primary node first.
2734
          for group, nodes in sorted(instance_groups.items(),
2735
                                     key=lambda (_, nodes): pnode in nodes,
2736
                                     reverse=True)]
2737

    
2738
        self._ErrorIf(len(instance_groups) > 1, self.EINSTANCESPLITGROUPS,
2739
                      instance, "instance has primary and secondary nodes in"
2740
                      " different groups: %s", utils.CommaJoin(pretty_list),
2741
                      code=self.ETYPE_WARNING)
2742

    
2743
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2744
        i_non_a_balanced.append(instance)
2745

    
2746
      for snode in inst_config.secondary_nodes:
2747
        s_img = node_image[snode]
2748
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2749
                 "instance %s, connection to secondary node failed", instance)
2750

    
2751
        if s_img.offline:
2752
          inst_nodes_offline.append(snode)
2753

    
2754
      # warn that the instance lives on offline nodes
2755
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2756
               "instance has offline secondary node(s) %s",
2757
               utils.CommaJoin(inst_nodes_offline))
2758
      # ... or ghost/non-vm_capable nodes
2759
      for node in inst_config.all_nodes:
2760
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2761
                 "instance lives on ghost node %s", node)
2762
        _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2763
                 instance, "instance lives on non-vm_capable node %s", node)
2764

    
2765
    feedback_fn("* Verifying orphan volumes")
2766
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2767

    
2768
    # We will get spurious "unknown volume" warnings if any node of this group
2769
    # is secondary for an instance whose primary is in another group. To avoid
2770
    # them, we find these instances and add their volumes to node_vol_should.
2771
    for inst in self.all_inst_info.values():
2772
      for secondary in inst.secondary_nodes:
2773
        if (secondary in self.my_node_info
2774
            and inst.name not in self.my_inst_info):
2775
          inst.MapLVsByNode(node_vol_should)
2776
          break
2777

    
2778
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2779

    
2780
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2781
      feedback_fn("* Verifying N+1 Memory redundancy")
2782
      self._VerifyNPlusOneMemory(node_image, self.my_inst_info)
2783

    
2784
    feedback_fn("* Other Notes")
2785
    if i_non_redundant:
2786
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2787
                  % len(i_non_redundant))
2788

    
2789
    if i_non_a_balanced:
2790
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2791
                  % len(i_non_a_balanced))
2792

    
2793
    if n_offline:
2794
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2795

    
2796
    if n_drained:
2797
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2798

    
2799
    return not self.bad
2800

    
2801
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2802
    """Analyze the post-hooks' result
2803

2804
    This method analyses the hook result, handles it, and sends some
2805
    nicely-formatted feedback back to the user.
2806

2807
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2808
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2809
    @param hooks_results: the results of the multi-node hooks rpc call
2810
    @param feedback_fn: function used send feedback back to the caller
2811
    @param lu_result: previous Exec result
2812
    @return: the new Exec result, based on the previous result
2813
        and hook results
2814

2815
    """
2816
    # We only really run POST phase hooks, only for non-empty groups,
2817
    # and are only interested in their results
2818
    if not self.my_node_names:
2819
      # empty node group
2820
      pass
2821
    elif phase == constants.HOOKS_PHASE_POST:
2822
      # Used to change hooks' output to proper indentation
2823
      feedback_fn("* Hooks Results")
2824
      assert hooks_results, "invalid result from hooks"
2825

    
2826
      for node_name in hooks_results:
2827
        res = hooks_results[node_name]
2828
        msg = res.fail_msg
2829
        test = msg and not res.offline
2830
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2831
                      "Communication failure in hooks execution: %s", msg)
2832
        if res.offline or msg:
2833
          # No need to investigate payload if node is offline or gave an error.
2834
          # override manually lu_result here as _ErrorIf only
2835
          # overrides self.bad
2836
          lu_result = 1
2837
          continue
2838
        for script, hkr, output in res.payload:
2839
          test = hkr == constants.HKR_FAIL
2840
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2841
                        "Script %s failed, output:", script)
2842
          if test:
2843
            output = self._HOOKS_INDENT_RE.sub('      ', output)
2844
            feedback_fn("%s" % output)
2845
            lu_result = 0
2846

    
2847
    return lu_result
2848

    
2849

    
2850
class LUClusterVerifyDisks(NoHooksLU):
2851
  """Verifies the cluster disks status.
2852

2853
  """
2854
  REQ_BGL = False
2855

    
2856
  def ExpandNames(self):
2857
    self.needed_locks = {
2858
      locking.LEVEL_NODE: locking.ALL_SET,
2859
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2860
    }
2861
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2862

    
2863
  def Exec(self, feedback_fn):
2864
    """Verify integrity of cluster disks.
2865

2866
    @rtype: tuple of three items
2867
    @return: a tuple of (dict of node-to-node_error, list of instances
2868
        which need activate-disks, dict of instance: (node, volume) for
2869
        missing volumes
2870

2871
    """
2872
    result = res_nodes, res_instances, res_missing = {}, [], {}
2873

    
2874
    nodes = utils.NiceSort(self.cfg.GetVmCapableNodeList())
2875
    instances = self.cfg.GetAllInstancesInfo().values()
2876

    
2877
    nv_dict = {}
2878
    for inst in instances:
2879
      inst_lvs = {}
2880
      if not inst.admin_up:
2881
        continue
2882
      inst.MapLVsByNode(inst_lvs)
2883
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2884
      for node, vol_list in inst_lvs.iteritems():
2885
        for vol in vol_list:
2886
          nv_dict[(node, vol)] = inst
2887

    
2888
    if not nv_dict:
2889
      return result
2890

    
2891
    node_lvs = self.rpc.call_lv_list(nodes, [])
2892
    for node, node_res in node_lvs.items():
2893
      if node_res.offline:
2894
        continue
2895
      msg = node_res.fail_msg
2896
      if msg:
2897
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2898
        res_nodes[node] = msg
2899
        continue
2900

    
2901
      lvs = node_res.payload
2902
      for lv_name, (_, _, lv_online) in lvs.items():
2903
        inst = nv_dict.pop((node, lv_name), None)
2904
        if (not lv_online and inst is not None
2905
            and inst.name not in res_instances):
2906
          res_instances.append(inst.name)
2907

    
2908
    # any leftover items in nv_dict are missing LVs, let's arrange the
2909
    # data better
2910
    for key, inst in nv_dict.iteritems():
2911
      if inst.name not in res_missing:
2912
        res_missing[inst.name] = []
2913
      res_missing[inst.name].append(key)
2914

    
2915
    return result
2916

    
2917

    
2918
class LUClusterRepairDiskSizes(NoHooksLU):
2919
  """Verifies the cluster disks sizes.
2920

2921
  """
2922
  REQ_BGL = False
2923

    
2924
  def ExpandNames(self):
2925
    if self.op.instances:
2926
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
2927
      self.needed_locks = {
2928
        locking.LEVEL_NODE: [],
2929
        locking.LEVEL_INSTANCE: self.wanted_names,
2930
        }
2931
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2932
    else:
2933
      self.wanted_names = None
2934
      self.needed_locks = {
2935
        locking.LEVEL_NODE: locking.ALL_SET,
2936
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2937
        }
2938
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2939

    
2940
  def DeclareLocks(self, level):
2941
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2942
      self._LockInstancesNodes(primary_only=True)
2943

    
2944
  def CheckPrereq(self):
2945
    """Check prerequisites.
2946

2947
    This only checks the optional instance list against the existing names.
2948

2949
    """
2950
    if self.wanted_names is None:
2951
      self.wanted_names = self.glm.list_owned(locking.LEVEL_INSTANCE)
2952

    
2953
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2954
                             in self.wanted_names]
2955

    
2956
  def _EnsureChildSizes(self, disk):
2957
    """Ensure children of the disk have the needed disk size.
2958

2959
    This is valid mainly for DRBD8 and fixes an issue where the
2960
    children have smaller disk size.
2961

2962
    @param disk: an L{ganeti.objects.Disk} object
2963

2964
    """
2965
    if disk.dev_type == constants.LD_DRBD8:
2966
      assert disk.children, "Empty children for DRBD8?"
2967
      fchild = disk.children[0]
2968
      mismatch = fchild.size < disk.size
2969
      if mismatch:
2970
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2971
                     fchild.size, disk.size)
2972
        fchild.size = disk.size
2973

    
2974
      # and we recurse on this child only, not on the metadev
2975
      return self._EnsureChildSizes(fchild) or mismatch
2976
    else:
2977
      return False
2978

    
2979
  def Exec(self, feedback_fn):
2980
    """Verify the size of cluster disks.
2981

2982
    """
2983
    # TODO: check child disks too
2984
    # TODO: check differences in size between primary/secondary nodes
2985
    per_node_disks = {}
2986
    for instance in self.wanted_instances:
2987
      pnode = instance.primary_node
2988
      if pnode not in per_node_disks:
2989
        per_node_disks[pnode] = []
2990
      for idx, disk in enumerate(instance.disks):
2991
        per_node_disks[pnode].append((instance, idx, disk))
2992

    
2993
    changed = []
2994
    for node, dskl in per_node_disks.items():
2995
      newl = [v[2].Copy() for v in dskl]
2996
      for dsk in newl:
2997
        self.cfg.SetDiskID(dsk, node)
2998
      result = self.rpc.call_blockdev_getsize(node, newl)
2999
      if result.fail_msg:
3000
        self.LogWarning("Failure in blockdev_getsize call to node"
3001
                        " %s, ignoring", node)
3002
        continue
3003
      if len(result.payload) != len(dskl):
3004
        logging.warning("Invalid result from node %s: len(dksl)=%d,"
3005
                        " result.payload=%s", node, len(dskl), result.payload)
3006
        self.LogWarning("Invalid result from node %s, ignoring node results",
3007
                        node)
3008
        continue
3009
      for ((instance, idx, disk), size) in zip(dskl, result.payload):
3010
        if size is None:
3011
          self.LogWarning("Disk %d of instance %s did not return size"
3012
                          " information, ignoring", idx, instance.name)
3013
          continue
3014
        if not isinstance(size, (int, long)):
3015
          self.LogWarning("Disk %d of instance %s did not return valid"
3016
                          " size information, ignoring", idx, instance.name)
3017
          continue
3018
        size = size >> 20
3019
        if size != disk.size:
3020
          self.LogInfo("Disk %d of instance %s has mismatched size,"
3021
                       " correcting: recorded %d, actual %d", idx,
3022
                       instance.name, disk.size, size)
3023
          disk.size = size
3024
          self.cfg.Update(instance, feedback_fn)
3025
          changed.append((instance.name, idx, size))
3026
        if self._EnsureChildSizes(disk):
3027
          self.cfg.Update(instance, feedback_fn)
3028
          changed.append((instance.name, idx, disk.size))
3029
    return changed
3030

    
3031

    
3032
class LUClusterRename(LogicalUnit):
3033
  """Rename the cluster.
3034

3035
  """
3036
  HPATH = "cluster-rename"
3037
  HTYPE = constants.HTYPE_CLUSTER
3038

    
3039
  def BuildHooksEnv(self):
3040
    """Build hooks env.
3041

3042
    """
3043
    return {
3044
      "OP_TARGET": self.cfg.GetClusterName(),
3045
      "NEW_NAME": self.op.name,
3046
      }
3047

    
3048
  def BuildHooksNodes(self):
3049
    """Build hooks nodes.
3050

3051
    """
3052
    return ([self.cfg.GetMasterNode()], self.cfg.GetNodeList())
3053

    
3054
  def CheckPrereq(self):
3055
    """Verify that the passed name is a valid one.
3056

3057
    """
3058
    hostname = netutils.GetHostname(name=self.op.name,
3059
                                    family=self.cfg.GetPrimaryIPFamily())
3060

    
3061
    new_name = hostname.name
3062
    self.ip = new_ip = hostname.ip
3063
    old_name = self.cfg.GetClusterName()
3064
    old_ip = self.cfg.GetMasterIP()
3065
    if new_name == old_name and new_ip == old_ip:
3066
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
3067
                                 " cluster has changed",
3068
                                 errors.ECODE_INVAL)
3069
    if new_ip != old_ip:
3070
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
3071
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
3072
                                   " reachable on the network" %
3073
                                   new_ip, errors.ECODE_NOTUNIQUE)
3074

    
3075
    self.op.name = new_name
3076

    
3077
  def Exec(self, feedback_fn):
3078
    """Rename the cluster.
3079

3080
    """
3081
    clustername = self.op.name
3082
    ip = self.ip
3083

    
3084
    # shutdown the master IP
3085
    master = self.cfg.GetMasterNode()
3086
    result = self.rpc.call_node_stop_master(master, False)
3087
    result.Raise("Could not disable the master role")
3088

    
3089
    try:
3090
      cluster = self.cfg.GetClusterInfo()
3091
      cluster.cluster_name = clustername
3092
      cluster.master_ip = ip
3093
      self.cfg.Update(cluster, feedback_fn)
3094

    
3095
      # update the known hosts file
3096
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
3097
      node_list = self.cfg.GetOnlineNodeList()
3098
      try:
3099
        node_list.remove(master)
3100
      except ValueError:
3101
        pass
3102
      _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
3103
    finally:
3104
      result = self.rpc.call_node_start_master(master, False, False)
3105
      msg = result.fail_msg
3106
      if msg:
3107
        self.LogWarning("Could not re-enable the master role on"
3108
                        " the master, please restart manually: %s", msg)
3109

    
3110
    return clustername
3111

    
3112

    
3113
class LUClusterSetParams(LogicalUnit):
3114
  """Change the parameters of the cluster.
3115

3116
  """
3117
  HPATH = "cluster-modify"
3118
  HTYPE = constants.HTYPE_CLUSTER
3119
  REQ_BGL = False
3120

    
3121
  def CheckArguments(self):
3122
    """Check parameters
3123

3124
    """
3125
    if self.op.uid_pool:
3126
      uidpool.CheckUidPool(self.op.uid_pool)
3127

    
3128
    if self.op.add_uids:
3129
      uidpool.CheckUidPool(self.op.add_uids)
3130

    
3131
    if self.op.remove_uids:
3132
      uidpool.CheckUidPool(self.op.remove_uids)
3133

    
3134
  def ExpandNames(self):
3135
    # FIXME: in the future maybe other cluster params won't require checking on
3136
    # all nodes to be modified.
3137
    self.needed_locks = {
3138
      locking.LEVEL_NODE: locking.ALL_SET,
3139
    }
3140
    self.share_locks[locking.LEVEL_NODE] = 1
3141

    
3142
  def BuildHooksEnv(self):
3143
    """Build hooks env.
3144

3145
    """
3146
    return {
3147
      "OP_TARGET": self.cfg.GetClusterName(),
3148
      "NEW_VG_NAME": self.op.vg_name,
3149
      }
3150

    
3151
  def BuildHooksNodes(self):
3152
    """Build hooks nodes.
3153

3154
    """
3155
    mn = self.cfg.GetMasterNode()
3156
    return ([mn], [mn])
3157

    
3158
  def CheckPrereq(self):
3159
    """Check prerequisites.
3160

3161
    This checks whether the given params don't conflict and
3162
    if the given volume group is valid.
3163

3164
    """
3165
    if self.op.vg_name is not None and not self.op.vg_name:
3166
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
3167
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
3168
                                   " instances exist", errors.ECODE_INVAL)
3169

    
3170
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
3171
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
3172
        raise errors.OpPrereqError("Cannot disable drbd helper while"
3173
                                   " drbd-based instances exist",
3174
                                   errors.ECODE_INVAL)
3175

    
3176
    node_list = self.glm.list_owned(locking.LEVEL_NODE)
3177

    
3178
    # if vg_name not None, checks given volume group on all nodes
3179
    if self.op.vg_name:
3180
      vglist = self.rpc.call_vg_list(node_list)
3181
      for node in node_list:
3182
        msg = vglist[node].fail_msg
3183
        if msg:
3184
          # ignoring down node
3185
          self.LogWarning("Error while gathering data on node %s"
3186
                          " (ignoring node): %s", node, msg)
3187
          continue
3188
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
3189
                                              self.op.vg_name,
3190
                                              constants.MIN_VG_SIZE)
3191
        if vgstatus:
3192
          raise errors.OpPrereqError("Error on node '%s': %s" %
3193
                                     (node, vgstatus), errors.ECODE_ENVIRON)
3194

    
3195
    if self.op.drbd_helper:
3196
      # checks given drbd helper on all nodes
3197
      helpers = self.rpc.call_drbd_helper(node_list)
3198
      for node in node_list:
3199
        ninfo = self.cfg.GetNodeInfo(node)
3200
        if ninfo.offline:
3201
          self.LogInfo("Not checking drbd helper on offline node %s", node)
3202
          continue
3203
        msg = helpers[node].fail_msg
3204
        if msg:
3205
          raise errors.OpPrereqError("Error checking drbd helper on node"
3206
                                     " '%s': %s" % (node, msg),
3207
                                     errors.ECODE_ENVIRON)
3208
        node_helper = helpers[node].payload
3209
        if node_helper != self.op.drbd_helper:
3210
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
3211
                                     (node, node_helper), errors.ECODE_ENVIRON)
3212

    
3213
    self.cluster = cluster = self.cfg.GetClusterInfo()
3214
    # validate params changes
3215
    if self.op.beparams:
3216
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
3217
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
3218

    
3219
    if self.op.ndparams:
3220
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
3221
      self.new_ndparams = cluster.SimpleFillND(self.op.ndparams)
3222

    
3223
      # TODO: we need a more general way to handle resetting
3224
      # cluster-level parameters to default values
3225
      if self.new_ndparams["oob_program"] == "":
3226
        self.new_ndparams["oob_program"] = \
3227
            constants.NDC_DEFAULTS[constants.ND_OOB_PROGRAM]
3228

    
3229
    if self.op.nicparams:
3230
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
3231
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
3232
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
3233
      nic_errors = []
3234

    
3235
      # check all instances for consistency
3236
      for instance in self.cfg.GetAllInstancesInfo().values():
3237
        for nic_idx, nic in enumerate(instance.nics):
3238
          params_copy = copy.deepcopy(nic.nicparams)
3239
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
3240

    
3241
          # check parameter syntax
3242
          try:
3243
            objects.NIC.CheckParameterSyntax(params_filled)
3244
          except errors.ConfigurationError, err:
3245
            nic_errors.append("Instance %s, nic/%d: %s" %
3246
                              (instance.name, nic_idx, err))
3247

    
3248
          # if we're moving instances to routed, check that they have an ip
3249
          target_mode = params_filled[constants.NIC_MODE]
3250
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
3251
            nic_errors.append("Instance %s, nic/%d: routed NIC with no ip"
3252
                              " address" % (instance.name, nic_idx))
3253
      if nic_errors:
3254
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
3255
                                   "\n".join(nic_errors))
3256

    
3257
    # hypervisor list/parameters
3258
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
3259
    if self.op.hvparams:
3260
      for hv_name, hv_dict in self.op.hvparams.items():
3261
        if hv_name not in self.new_hvparams:
3262
          self.new_hvparams[hv_name] = hv_dict
3263
        else:
3264
          self.new_hvparams[hv_name].update(hv_dict)
3265

    
3266
    # os hypervisor parameters
3267
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
3268
    if self.op.os_hvp:
3269
      for os_name, hvs in self.op.os_hvp.items():
3270
        if os_name not in self.new_os_hvp:
3271
          self.new_os_hvp[os_name] = hvs
3272
        else:
3273
          for hv_name, hv_dict in hvs.items():
3274
            if hv_name not in self.new_os_hvp[os_name]:
3275
              self.new_os_hvp[os_name][hv_name] = hv_dict
3276
            else:
3277
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
3278

    
3279
    # os parameters
3280
    self.new_osp = objects.FillDict(cluster.osparams, {})
3281
    if self.op.osparams:
3282
      for os_name, osp in self.op.osparams.items():
3283
        if os_name not in self.new_osp:
3284
          self.new_osp[os_name] = {}
3285

    
3286
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
3287
                                                  use_none=True)
3288

    
3289
        if not self.new_osp[os_name]:
3290
          # we removed all parameters
3291
          del self.new_osp[os_name]
3292
        else:
3293
          # check the parameter validity (remote check)
3294
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
3295
                         os_name, self.new_osp[os_name])
3296

    
3297
    # changes to the hypervisor list
3298
    if self.op.enabled_hypervisors is not None:
3299
      self.hv_list = self.op.enabled_hypervisors
3300
      for hv in self.hv_list:
3301
        # if the hypervisor doesn't already exist in the cluster
3302
        # hvparams, we initialize it to empty, and then (in both
3303
        # cases) we make sure to fill the defaults, as we might not
3304
        # have a complete defaults list if the hypervisor wasn't
3305
        # enabled before
3306
        if hv not in new_hvp:
3307
          new_hvp[hv] = {}
3308
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
3309
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
3310
    else:
3311
      self.hv_list = cluster.enabled_hypervisors
3312

    
3313
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
3314
      # either the enabled list has changed, or the parameters have, validate
3315
      for hv_name, hv_params in self.new_hvparams.items():
3316
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
3317
            (self.op.enabled_hypervisors and
3318
             hv_name in self.op.enabled_hypervisors)):
3319
          # either this is a new hypervisor, or its parameters have changed
3320
          hv_class = hypervisor.GetHypervisor(hv_name)
3321
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3322
          hv_class.CheckParameterSyntax(hv_params)
3323
          _CheckHVParams(self, node_list, hv_name, hv_params)
3324

    
3325
    if self.op.os_hvp:
3326
      # no need to check any newly-enabled hypervisors, since the
3327
      # defaults have already been checked in the above code-block
3328
      for os_name, os_hvp in self.new_os_hvp.items():
3329
        for hv_name, hv_params in os_hvp.items():
3330
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3331
          # we need to fill in the new os_hvp on top of the actual hv_p
3332
          cluster_defaults = self.new_hvparams.get(hv_name, {})
3333
          new_osp = objects.FillDict(cluster_defaults, hv_params)
3334
          hv_class = hypervisor.GetHypervisor(hv_name)
3335
          hv_class.CheckParameterSyntax(new_osp)
3336
          _CheckHVParams(self, node_list, hv_name, new_osp)
3337

    
3338
    if self.op.default_iallocator:
3339
      alloc_script = utils.FindFile(self.op.default_iallocator,
3340
                                    constants.IALLOCATOR_SEARCH_PATH,
3341
                                    os.path.isfile)
3342
      if alloc_script is None:
3343
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
3344
                                   " specified" % self.op.default_iallocator,
3345
                                   errors.ECODE_INVAL)
3346

    
3347
  def Exec(self, feedback_fn):
3348
    """Change the parameters of the cluster.
3349

3350
    """
3351
    if self.op.vg_name is not None:
3352
      new_volume = self.op.vg_name
3353
      if not new_volume:
3354
        new_volume = None
3355
      if new_volume != self.cfg.GetVGName():
3356
        self.cfg.SetVGName(new_volume)
3357
      else:
3358
        feedback_fn("Cluster LVM configuration already in desired"
3359
                    " state, not changing")
3360
    if self.op.drbd_helper is not None:
3361
      new_helper = self.op.drbd_helper
3362
      if not new_helper:
3363
        new_helper = None
3364
      if new_helper != self.cfg.GetDRBDHelper():
3365
        self.cfg.SetDRBDHelper(new_helper)
3366
      else:
3367
        feedback_fn("Cluster DRBD helper already in desired state,"
3368
                    " not changing")
3369
    if self.op.hvparams:
3370
      self.cluster.hvparams = self.new_hvparams
3371
    if self.op.os_hvp:
3372
      self.cluster.os_hvp = self.new_os_hvp
3373
    if self.op.enabled_hypervisors is not None:
3374
      self.cluster.hvparams = self.new_hvparams
3375
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
3376
    if self.op.beparams:
3377
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
3378
    if self.op.nicparams:
3379
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
3380
    if self.op.osparams:
3381
      self.cluster.osparams = self.new_osp
3382
    if self.op.ndparams:
3383
      self.cluster.ndparams = self.new_ndparams
3384

    
3385
    if self.op.candidate_pool_size is not None:
3386
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
3387
      # we need to update the pool size here, otherwise the save will fail
3388
      _AdjustCandidatePool(self, [])
3389

    
3390
    if self.op.maintain_node_health is not None:
3391
      self.cluster.maintain_node_health = self.op.maintain_node_health
3392

    
3393
    if self.op.prealloc_wipe_disks is not None:
3394
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
3395

    
3396
    if self.op.add_uids is not None:
3397
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
3398

    
3399
    if self.op.remove_uids is not None:
3400
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
3401

    
3402
    if self.op.uid_pool is not None:
3403
      self.cluster.uid_pool = self.op.uid_pool
3404

    
3405
    if self.op.default_iallocator is not None:
3406
      self.cluster.default_iallocator = self.op.default_iallocator
3407

    
3408
    if self.op.reserved_lvs is not None:
3409
      self.cluster.reserved_lvs = self.op.reserved_lvs
3410

    
3411
    def helper_os(aname, mods, desc):
3412
      desc += " OS list"
3413
      lst = getattr(self.cluster, aname)
3414
      for key, val in mods:
3415
        if key == constants.DDM_ADD:
3416
          if val in lst:
3417
            feedback_fn("OS %s already in %s, ignoring" % (val, desc))
3418
          else:
3419
            lst.append(val)
3420
        elif key == constants.DDM_REMOVE:
3421
          if val in lst:
3422
            lst.remove(val)
3423
          else:
3424
            feedback_fn("OS %s not found in %s, ignoring" % (val, desc))
3425
        else:
3426
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
3427

    
3428
    if self.op.hidden_os:
3429
      helper_os("hidden_os", self.op.hidden_os, "hidden")
3430

    
3431
    if self.op.blacklisted_os:
3432
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
3433

    
3434
    if self.op.master_netdev:
3435
      master = self.cfg.GetMasterNode()
3436
      feedback_fn("Shutting down master ip on the current netdev (%s)" %
3437
                  self.cluster.master_netdev)
3438
      result = self.rpc.call_node_stop_master(master, False)
3439
      result.Raise("Could not disable the master ip")
3440
      feedback_fn("Changing master_netdev from %s to %s" %
3441
                  (self.cluster.master_netdev, self.op.master_netdev))
3442
      self.cluster.master_netdev = self.op.master_netdev
3443

    
3444
    self.cfg.Update(self.cluster, feedback_fn)
3445

    
3446
    if self.op.master_netdev:
3447
      feedback_fn("Starting the master ip on the new master netdev (%s)" %
3448
                  self.op.master_netdev)
3449
      result = self.rpc.call_node_start_master(master, False, False)
3450
      if result.fail_msg:
3451
        self.LogWarning("Could not re-enable the master ip on"
3452
                        " the master, please restart manually: %s",
3453
                        result.fail_msg)
3454

    
3455

    
3456
def _UploadHelper(lu, nodes, fname):
3457
  """Helper for uploading a file and showing warnings.
3458

3459
  """
3460
  if os.path.exists(fname):
3461
    result = lu.rpc.call_upload_file(nodes, fname)
3462
    for to_node, to_result in result.items():
3463
      msg = to_result.fail_msg
3464
      if msg:
3465
        msg = ("Copy of file %s to node %s failed: %s" %
3466
               (fname, to_node, msg))
3467
        lu.proc.LogWarning(msg)
3468

    
3469

    
3470
def _ComputeAncillaryFiles(cluster, redist):
3471
  """Compute files external to Ganeti which need to be consistent.
3472

3473
  @type redist: boolean
3474
  @param redist: Whether to include files which need to be redistributed
3475

3476
  """
3477
  # Compute files for all nodes
3478
  files_all = set([
3479
    constants.SSH_KNOWN_HOSTS_FILE,
3480
    constants.CONFD_HMAC_KEY,
3481
    constants.CLUSTER_DOMAIN_SECRET_FILE,
3482
    ])
3483

    
3484
  if not redist:
3485
    files_all.update(constants.ALL_CERT_FILES)
3486
    files_all.update(ssconf.SimpleStore().GetFileList())
3487

    
3488
  if cluster.modify_etc_hosts:
3489
    files_all.add(constants.ETC_HOSTS)
3490

    
3491
  # Files which must either exist on all nodes or on none
3492
  files_all_opt = set([
3493
    constants.RAPI_USERS_FILE,
3494
    ])
3495

    
3496
  # Files which should only be on master candidates
3497
  files_mc = set()
3498
  if not redist:
3499
    files_mc.add(constants.CLUSTER_CONF_FILE)
3500

    
3501
  # Files which should only be on VM-capable nodes
3502
  files_vm = set(filename
3503
    for hv_name in cluster.enabled_hypervisors
3504
    for filename in hypervisor.GetHypervisor(hv_name).GetAncillaryFiles())
3505

    
3506
  # Filenames must be unique
3507
  assert (len(files_all | files_all_opt | files_mc | files_vm) ==
3508
          sum(map(len, [files_all, files_all_opt, files_mc, files_vm]))), \
3509
         "Found file listed in more than one file list"
3510

    
3511
  return (files_all, files_all_opt, files_mc, files_vm)
3512

    
3513

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

3517
  ConfigWriter takes care of distributing the config and ssconf files, but
3518
  there are more files which should be distributed to all nodes. This function
3519
  makes sure those are copied.
3520

3521
  @param lu: calling logical unit
3522
  @param additional_nodes: list of nodes not in the config to distribute to
3523
  @type additional_vm: boolean
3524
  @param additional_vm: whether the additional nodes are vm-capable or not
3525

3526
  """
3527
  # Gather target nodes
3528
  cluster = lu.cfg.GetClusterInfo()
3529
  master_info = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
3530

    
3531
  online_nodes = lu.cfg.GetOnlineNodeList()
3532
  vm_nodes = lu.cfg.GetVmCapableNodeList()
3533

    
3534
  if additional_nodes is not None:
3535
    online_nodes.extend(additional_nodes)
3536
    if additional_vm:
3537
      vm_nodes.extend(additional_nodes)
3538

    
3539
  # Never distribute to master node
3540
  for nodelist in [online_nodes, vm_nodes]:
3541
    if master_info.name in nodelist:
3542
      nodelist.remove(master_info.name)
3543

    
3544
  # Gather file lists
3545
  (files_all, files_all_opt, files_mc, files_vm) = \
3546
    _ComputeAncillaryFiles(cluster, True)
3547

    
3548
  # Never re-distribute configuration file from here
3549
  assert not (constants.CLUSTER_CONF_FILE in files_all or
3550
              constants.CLUSTER_CONF_FILE in files_vm)
3551
  assert not files_mc, "Master candidates not handled in this function"
3552

    
3553
  filemap = [
3554
    (online_nodes, files_all),
3555
    (online_nodes, files_all_opt),
3556
    (vm_nodes, files_vm),
3557
    ]
3558

    
3559
  # Upload the files
3560
  for (node_list, files) in filemap:
3561
    for fname in files:
3562
      _UploadHelper(lu, node_list, fname)
3563

    
3564

    
3565
class LUClusterRedistConf(NoHooksLU):
3566
  """Force the redistribution of cluster configuration.
3567

3568
  This is a very simple LU.
3569

3570
  """
3571
  REQ_BGL = False
3572

    
3573
  def ExpandNames(self):
3574
    self.needed_locks = {
3575
      locking.LEVEL_NODE: locking.ALL_SET,
3576
    }
3577
    self.share_locks[locking.LEVEL_NODE] = 1
3578

    
3579
  def Exec(self, feedback_fn):
3580
    """Redistribute the configuration.
3581

3582
    """
3583
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
3584
    _RedistributeAncillaryFiles(self)
3585

    
3586

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

3590
  """
3591
  if not instance.disks or disks is not None and not disks:
3592
    return True
3593

    
3594
  disks = _ExpandCheckDisks(instance, disks)
3595

    
3596
  if not oneshot:
3597
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
3598

    
3599
  node = instance.primary_node
3600

    
3601
  for dev in disks:
3602
    lu.cfg.SetDiskID(dev, node)
3603

    
3604
  # TODO: Convert to utils.Retry
3605

    
3606
  retries = 0
3607
  degr_retries = 10 # in seconds, as we sleep 1 second each time
3608
  while True:
3609
    max_time = 0
3610
    done = True
3611
    cumul_degraded = False
3612
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
3613
    msg = rstats.fail_msg
3614
    if msg:
3615
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
3616
      retries += 1
3617
      if retries >= 10:
3618
        raise errors.RemoteError("Can't contact node %s for mirror data,"
3619
                                 " aborting." % node)
3620
      time.sleep(6)
3621
      continue
3622
    rstats = rstats.payload
3623
    retries = 0
3624
    for i, mstat in enumerate(rstats):
3625
      if mstat is None:
3626
        lu.LogWarning("Can't compute data for node %s/%s",
3627
                           node, disks[i].iv_name)
3628
        continue
3629

    
3630
      cumul_degraded = (cumul_degraded or
3631
                        (mstat.is_degraded and mstat.sync_percent is None))
3632
      if mstat.sync_percent is not None:
3633
        done = False
3634
        if mstat.estimated_time is not None:
3635
          rem_time = ("%s remaining (estimated)" %
3636
                      utils.FormatSeconds(mstat.estimated_time))
3637
          max_time = mstat.estimated_time
3638
        else:
3639
          rem_time = "no time estimate"
3640
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3641
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3642

    
3643
    # if we're done but degraded, let's do a few small retries, to
3644
    # make sure we see a stable and not transient situation; therefore
3645
    # we force restart of the loop
3646
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3647
      logging.info("Degraded disks found, %d retries left", degr_retries)
3648
      degr_retries -= 1
3649
      time.sleep(1)
3650
      continue
3651

    
3652
    if done or oneshot:
3653
      break
3654

    
3655
    time.sleep(min(60, max_time))
3656

    
3657
  if done:
3658
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3659
  return not cumul_degraded
3660

    
3661

    
3662
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3663
  """Check that mirrors are not degraded.
3664

3665
  The ldisk parameter, if True, will change the test from the
3666
  is_degraded attribute (which represents overall non-ok status for
3667
  the device(s)) to the ldisk (representing the local storage status).
3668

3669
  """
3670
  lu.cfg.SetDiskID(dev, node)
3671

    
3672
  result = True
3673

    
3674
  if on_primary or dev.AssembleOnSecondary():
3675
    rstats = lu.rpc.call_blockdev_find(node, dev)
3676
    msg = rstats.fail_msg
3677
    if msg:
3678
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3679
      result = False
3680
    elif not rstats.payload:
3681
      lu.LogWarning("Can't find disk on node %s", node)
3682
      result = False
3683
    else:
3684
      if ldisk:
3685
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3686
      else:
3687
        result = result and not rstats.payload.is_degraded
3688

    
3689
  if dev.children:
3690
    for child in dev.children:
3691
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3692

    
3693
  return result
3694

    
3695

    
3696
class LUOobCommand(NoHooksLU):
3697
  """Logical unit for OOB handling.
3698

3699
  """
3700
  REG_BGL = False
3701
  _SKIP_MASTER = (constants.OOB_POWER_OFF, constants.OOB_POWER_CYCLE)
3702

    
3703
  def ExpandNames(self):
3704
    """Gather locks we need.
3705

3706
    """
3707
    if self.op.node_names:
3708
      self.op.node_names = _GetWantedNodes(self, self.op.node_names)
3709
      lock_names = self.op.node_names
3710
    else:
3711
      lock_names = locking.ALL_SET
3712

    
3713
    self.needed_locks = {
3714
      locking.LEVEL_NODE: lock_names,
3715
      }
3716

    
3717
  def CheckPrereq(self):
3718
    """Check prerequisites.
3719

3720
    This checks:
3721
     - the node exists in the configuration
3722
     - OOB is supported
3723

3724
    Any errors are signaled by raising errors.OpPrereqError.
3725

3726
    """
3727
    self.nodes = []
3728
    self.master_node = self.cfg.GetMasterNode()
3729

    
3730
    assert self.op.power_delay >= 0.0
3731

    
3732
    if self.op.node_names:
3733
      if (self.op.command in self._SKIP_MASTER and
3734
          self.master_node in self.op.node_names):
3735
        master_node_obj = self.cfg.GetNodeInfo(self.master_node)
3736
        master_oob_handler = _SupportsOob(self.cfg, master_node_obj)
3737

    
3738
        if master_oob_handler:
3739
          additional_text = ("run '%s %s %s' if you want to operate on the"
3740
                             " master regardless") % (master_oob_handler,
3741
                                                      self.op.command,
3742
                                                      self.master_node)
3743
        else:
3744
          additional_text = "it does not support out-of-band operations"
3745

    
3746
        raise errors.OpPrereqError(("Operating on the master node %s is not"
3747
                                    " allowed for %s; %s") %
3748
                                   (self.master_node, self.op.command,
3749
                                    additional_text), errors.ECODE_INVAL)
3750
    else:
3751
      self.op.node_names = self.cfg.GetNodeList()
3752
      if self.op.command in self._SKIP_MASTER:
3753
        self.op.node_names.remove(self.master_node)
3754

    
3755
    if self.op.command in self._SKIP_MASTER:
3756
      assert self.master_node not in self.op.node_names
3757

    
3758
    for node_name in self.op.node_names:
3759
      node = self.cfg.GetNodeInfo(node_name)
3760

    
3761
      if node is None:
3762
        raise errors.OpPrereqError("Node %s not found" % node_name,
3763
                                   errors.ECODE_NOENT)
3764
      else:
3765
        self.nodes.append(node)
3766

    
3767
      if (not self.op.ignore_status and
3768
          (self.op.command == constants.OOB_POWER_OFF and not node.offline)):
3769
        raise errors.OpPrereqError(("Cannot power off node %s because it is"
3770
                                    " not marked offline") % node_name,
3771
                                   errors.ECODE_STATE)
3772

    
3773
  def Exec(self, feedback_fn):
3774
    """Execute OOB and return result if we expect any.
3775

3776
    """
3777
    master_node = self.master_node
3778
    ret = []
3779

    
3780
    for idx, node in enumerate(utils.NiceSort(self.nodes,
3781
                                              key=lambda node: node.name)):
3782
      node_entry = [(constants.RS_NORMAL, node.name)]
3783
      ret.append(node_entry)
3784

    
3785
      oob_program = _SupportsOob(self.cfg, node)
3786

    
3787
      if not oob_program:
3788
        node_entry.append((constants.RS_UNAVAIL, None))
3789
        continue
3790

    
3791
      logging.info("Executing out-of-band command '%s' using '%s' on %s",
3792
                   self.op.command, oob_program, node.name)
3793
      result = self.rpc.call_run_oob(master_node, oob_program,
3794
                                     self.op.command, node.name,
3795
                                     self.op.timeout)
3796

    
3797
      if result.fail_msg:
3798
        self.LogWarning("Out-of-band RPC failed on node '%s': %s",
3799
                        node.name, result.fail_msg)
3800
        node_entry.append((constants.RS_NODATA, None))
3801
      else:
3802
        try:
3803
          self._CheckPayload(result)
3804
        except errors.OpExecError, err:
3805
          self.LogWarning("Payload returned by node '%s' is not valid: %s",
3806
                          node.name, err)
3807
          node_entry.append((constants.RS_NODATA, None))
3808
        else:
3809
          if self.op.command == constants.OOB_HEALTH:
3810
            # For health we should log important events
3811
            for item, status in result.payload:
3812
              if status in [constants.OOB_STATUS_WARNING,
3813
                            constants.OOB_STATUS_CRITICAL]:
3814
                self.LogWarning("Item '%s' on node '%s' has status '%s'",
3815
                                item, node.name, status)
3816

    
3817
          if self.op.command == constants.OOB_POWER_ON:
3818
            node.powered = True
3819
          elif self.op.command == constants.OOB_POWER_OFF:
3820
            node.powered = False
3821
          elif self.op.command == constants.OOB_POWER_STATUS:
3822
            powered = result.payload[constants.OOB_POWER_STATUS_POWERED]
3823
            if powered != node.powered:
3824
              logging.warning(("Recorded power state (%s) of node '%s' does not"
3825
                               " match actual power state (%s)"), node.powered,
3826
                              node.name, powered)
3827

    
3828
          # For configuration changing commands we should update the node
3829
          if self.op.command in (constants.OOB_POWER_ON,
3830
                                 constants.OOB_POWER_OFF):
3831
            self.cfg.Update(node, feedback_fn)
3832

    
3833
          node_entry.append((constants.RS_NORMAL, result.payload))
3834

    
3835
          if (self.op.command == constants.OOB_POWER_ON and
3836
              idx < len(self.nodes) - 1):
3837
            time.sleep(self.op.power_delay)
3838

    
3839
    return ret
3840

    
3841
  def _CheckPayload(self, result):
3842
    """Checks if the payload is valid.
3843

3844
    @param result: RPC result
3845
    @raises errors.OpExecError: If payload is not valid
3846

3847
    """
3848
    errs = []
3849
    if self.op.command == constants.OOB_HEALTH:
3850
      if not isinstance(result.payload, list):
3851
        errs.append("command 'health' is expected to return a list but got %s" %
3852
                    type(result.payload))
3853
      else:
3854
        for item, status in result.payload:
3855
          if status not in constants.OOB_STATUSES:
3856
            errs.append("health item '%s' has invalid status '%s'" %
3857
                        (item, status))
3858

    
3859
    if self.op.command == constants.OOB_POWER_STATUS:
3860
      if not isinstance(result.payload, dict):
3861
        errs.append("power-status is expected to return a dict but got %s" %
3862
                    type(result.payload))
3863

    
3864
    if self.op.command in [
3865
        constants.OOB_POWER_ON,
3866
        constants.OOB_POWER_OFF,
3867
        constants.OOB_POWER_CYCLE,
3868
        ]:
3869
      if result.payload is not None:
3870
        errs.append("%s is expected to not return payload but got '%s'" %
3871
                    (self.op.command, result.payload))
3872

    
3873
    if errs:
3874
      raise errors.OpExecError("Check of out-of-band payload failed due to %s" %
3875
                               utils.CommaJoin(errs))
3876

    
3877
class _OsQuery(_QueryBase):
3878
  FIELDS = query.OS_FIELDS
3879

    
3880
  def ExpandNames(self, lu):
3881
    # Lock all nodes in shared mode
3882
    # Temporary removal of locks, should be reverted later
3883
    # TODO: reintroduce locks when they are lighter-weight
3884
    lu.needed_locks = {}
3885
    #self.share_locks[locking.LEVEL_NODE] = 1
3886
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3887

    
3888
    # The following variables interact with _QueryBase._GetNames
3889
    if self.names:
3890
      self.wanted = self.names
3891
    else:
3892
      self.wanted = locking.ALL_SET
3893

    
3894
    self.do_locking = self.use_locking
3895

    
3896
  def DeclareLocks(self, lu, level):
3897
    pass
3898

    
3899
  @staticmethod
3900
  def _DiagnoseByOS(rlist):
3901
    """Remaps a per-node return list into an a per-os per-node dictionary
3902

3903
    @param rlist: a map with node names as keys and OS objects as values
3904

3905
    @rtype: dict
3906
    @return: a dictionary with osnames as keys and as value another
3907
        map, with nodes as keys and tuples of (path, status, diagnose,
3908
        variants, parameters, api_versions) as values, eg::
3909

3910
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3911
                                     (/srv/..., False, "invalid api")],
3912
                           "node2": [(/srv/..., True, "", [], [])]}
3913
          }
3914

3915
    """
3916
    all_os = {}
3917
    # we build here the list of nodes that didn't fail the RPC (at RPC
3918
    # level), so that nodes with a non-responding node daemon don't
3919
    # make all OSes invalid
3920
    good_nodes = [node_name for node_name in rlist
3921
                  if not rlist[node_name].fail_msg]
3922
    for node_name, nr in rlist.items():
3923
      if nr.fail_msg or not nr.payload:
3924
        continue
3925
      for (name, path, status, diagnose, variants,
3926
           params, api_versions) in nr.payload:
3927
        if name not in all_os:
3928
          # build a list of nodes for this os containing empty lists
3929
          # for each node in node_list
3930
          all_os[name] = {}
3931
          for nname in good_nodes:
3932
            all_os[name][nname] = []
3933
        # convert params from [name, help] to (name, help)
3934
        params = [tuple(v) for v in params]
3935
        all_os[name][node_name].append((path, status, diagnose,
3936
                                        variants, params, api_versions))
3937
    return all_os
3938

    
3939
  def _GetQueryData(self, lu):
3940
    """Computes the list of nodes and their attributes.
3941

3942
    """
3943
    # Locking is not used
3944
    assert not (compat.any(lu.glm.is_owned(level)
3945
                           for level in locking.LEVELS
3946
                           if level != locking.LEVEL_CLUSTER) or
3947
                self.do_locking or self.use_locking)
3948

    
3949
    valid_nodes = [node.name
3950
                   for node in lu.cfg.GetAllNodesInfo().values()
3951
                   if not node.offline and node.vm_capable]
3952
    pol = self._DiagnoseByOS(lu.rpc.call_os_diagnose(valid_nodes))
3953
    cluster = lu.cfg.GetClusterInfo()
3954

    
3955
    data = {}
3956

    
3957
    for (os_name, os_data) in pol.items():
3958
      info = query.OsInfo(name=os_name, valid=True, node_status=os_data,
3959
                          hidden=(os_name in cluster.hidden_os),
3960
                          blacklisted=(os_name in cluster.blacklisted_os))
3961

    
3962
      variants = set()
3963
      parameters = set()
3964
      api_versions = set()
3965

    
3966
      for idx, osl in enumerate(os_data.values()):
3967
        info.valid = bool(info.valid and osl and osl[0][1])
3968
        if not info.valid:
3969
          break
3970

    
3971
        (node_variants, node_params, node_api) = osl[0][3:6]
3972
        if idx == 0:
3973
          # First entry
3974
          variants.update(node_variants)
3975
          parameters.update(node_params)
3976
          api_versions.update(node_api)
3977
        else:
3978
          # Filter out inconsistent values
3979
          variants.intersection_update(node_variants)
3980
          parameters.intersection_update(node_params)
3981
          api_versions.intersection_update(node_api)
3982

    
3983
      info.variants = list(variants)
3984
      info.parameters = list(parameters)
3985
      info.api_versions = list(api_versions)
3986

    
3987
      data[os_name] = info
3988

    
3989
    # Prepare data in requested order
3990
    return [data[name] for name in self._GetNames(lu, pol.keys(), None)
3991
            if name in data]
3992

    
3993

    
3994
class LUOsDiagnose(NoHooksLU):
3995
  """Logical unit for OS diagnose/query.
3996

3997
  """
3998
  REQ_BGL = False
3999

    
4000
  @staticmethod
4001
  def _BuildFilter(fields, names):
4002
    """Builds a filter for querying OSes.
4003

4004
    """
4005
    name_filter = qlang.MakeSimpleFilter("name", names)
4006

    
4007
    # Legacy behaviour: Hide hidden, blacklisted or invalid OSes if the
4008
    # respective field is not requested
4009
    status_filter = [[qlang.OP_NOT, [qlang.OP_TRUE, fname]]
4010
                     for fname in ["hidden", "blacklisted"]
4011
                     if fname not in fields]
4012
    if "valid" not in fields:
4013
      status_filter.append([qlang.OP_TRUE, "valid"])
4014

    
4015
    if status_filter:
4016
      status_filter.insert(0, qlang.OP_AND)
4017
    else:
4018
      status_filter = None
4019

    
4020
    if name_filter and status_filter:
4021
      return [qlang.OP_AND, name_filter, status_filter]
4022
    elif name_filter:
4023
      return name_filter
4024
    else:
4025
      return status_filter
4026

    
4027
  def CheckArguments(self):
4028
    self.oq = _OsQuery(self._BuildFilter(self.op.output_fields, self.op.names),
4029
                       self.op.output_fields, False)
4030

    
4031
  def ExpandNames(self):
4032
    self.oq.ExpandNames(self)
4033

    
4034
  def Exec(self, feedback_fn):
4035
    return self.oq.OldStyleQuery(self)
4036

    
4037

    
4038
class LUNodeRemove(LogicalUnit):
4039
  """Logical unit for removing a node.
4040

4041
  """
4042
  HPATH = "node-remove"
4043
  HTYPE = constants.HTYPE_NODE
4044

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

4048
    This doesn't run on the target node in the pre phase as a failed
4049
    node would then be impossible to remove.
4050

4051
    """
4052
    return {
4053
      "OP_TARGET": self.op.node_name,
4054
      "NODE_NAME": self.op.node_name,
4055
      }
4056

    
4057
  def BuildHooksNodes(self):
4058
    """Build hooks nodes.
4059

4060
    """
4061
    all_nodes = self.cfg.GetNodeList()
4062
    try:
4063
      all_nodes.remove(self.op.node_name)
4064
    except ValueError:
4065
      logging.warning("Node '%s', which is about to be removed, was not found"
4066
                      " in the list of all nodes", self.op.node_name)
4067
    return (all_nodes, all_nodes)
4068

    
4069
  def CheckPrereq(self):
4070
    """Check prerequisites.
4071

4072
    This checks:
4073
     - the node exists in the configuration
4074
     - it does not have primary or secondary instances
4075
     - it's not the master
4076

4077
    Any errors are signaled by raising errors.OpPrereqError.
4078

4079
    """
4080
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4081
    node = self.cfg.GetNodeInfo(self.op.node_name)
4082
    assert node is not None
4083

    
4084
    instance_list = self.cfg.GetInstanceList()
4085

    
4086
    masternode = self.cfg.GetMasterNode()
4087
    if node.name == masternode:
4088
      raise errors.OpPrereqError("Node is the master node, failover to another"
4089
                                 " node is required", errors.ECODE_INVAL)
4090

    
4091
    for instance_name in instance_list:
4092
      instance = self.cfg.GetInstanceInfo(instance_name)
4093
      if node.name in instance.all_nodes:
4094
        raise errors.OpPrereqError("Instance %s is still running on the node,"
4095
                                   " please remove first" % instance_name,
4096
                                   errors.ECODE_INVAL)
4097
    self.op.node_name = node.name
4098
    self.node = node
4099

    
4100
  def Exec(self, feedback_fn):
4101
    """Removes the node from the cluster.
4102

4103
    """
4104
    node = self.node
4105
    logging.info("Stopping the node daemon and removing configs from node %s",
4106
                 node.name)
4107

    
4108
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
4109

    
4110
    # Promote nodes to master candidate as needed
4111
    _AdjustCandidatePool(self, exceptions=[node.name])
4112
    self.context.RemoveNode(node.name)
4113

    
4114
    # Run post hooks on the node before it's removed
4115
    _RunPostHook(self, node.name)
4116

    
4117
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
4118
    msg = result.fail_msg
4119
    if msg:
4120
      self.LogWarning("Errors encountered on the remote node while leaving"
4121
                      " the cluster: %s", msg)
4122

    
4123
    # Remove node from our /etc/hosts
4124
    if self.cfg.GetClusterInfo().modify_etc_hosts:
4125
      master_node = self.cfg.GetMasterNode()
4126
      result = self.rpc.call_etc_hosts_modify(master_node,
4127
                                              constants.ETC_HOSTS_REMOVE,
4128
                                              node.name, None)
4129
      result.Raise("Can't update hosts file with new host data")
4130
      _RedistributeAncillaryFiles(self)
4131

    
4132

    
4133
class _NodeQuery(_QueryBase):
4134
  FIELDS = query.NODE_FIELDS
4135

    
4136
  def ExpandNames(self, lu):
4137
    lu.needed_locks = {}
4138
    lu.share_locks[locking.LEVEL_NODE] = 1
4139

    
4140
    if self.names:
4141
      self.wanted = _GetWantedNodes(lu, self.names)
4142
    else:
4143
      self.wanted = locking.ALL_SET
4144

    
4145
    self.do_locking = (self.use_locking and
4146
                       query.NQ_LIVE in self.requested_data)
4147

    
4148
    if self.do_locking:
4149
      # if we don't request only static fields, we need to lock the nodes
4150
      lu.needed_locks[locking.LEVEL_NODE] = self.wanted
4151

    
4152
  def DeclareLocks(self, lu, level):
4153
    pass
4154

    
4155
  def _GetQueryData(self, lu):
4156
    """Computes the list of nodes and their attributes.
4157

4158
    """
4159
    all_info = lu.cfg.GetAllNodesInfo()
4160

    
4161
    nodenames = self._GetNames(lu, all_info.keys(), locking.LEVEL_NODE)
4162

    
4163
    # Gather data as requested
4164
    if query.NQ_LIVE in self.requested_data:
4165
      # filter out non-vm_capable nodes
4166
      toquery_nodes = [name for name in nodenames if all_info[name].vm_capable]
4167

    
4168
      node_data = lu.rpc.call_node_info(toquery_nodes, lu.cfg.GetVGName(),
4169
                                        lu.cfg.GetHypervisorType())
4170
      live_data = dict((name, nresult.payload)
4171
                       for (name, nresult) in node_data.items()
4172
                       if not nresult.fail_msg and nresult.payload)
4173
    else:
4174
      live_data = None
4175

    
4176
    if query.NQ_INST in self.requested_data:
4177
      node_to_primary = dict([(name, set()) for name in nodenames])
4178
      node_to_secondary = dict([(name, set()) for name in nodenames])
4179

    
4180
      inst_data = lu.cfg.GetAllInstancesInfo()
4181

    
4182
      for inst in inst_data.values():
4183
        if inst.primary_node in node_to_primary:
4184
          node_to_primary[inst.primary_node].add(inst.name)
4185
        for secnode in inst.secondary_nodes:
4186
          if secnode in node_to_secondary:
4187
            node_to_secondary[secnode].add(inst.name)
4188
    else:
4189
      node_to_primary = None
4190
      node_to_secondary = None
4191

    
4192
    if query.NQ_OOB in self.requested_data:
4193
      oob_support = dict((name, bool(_SupportsOob(lu.cfg, node)))
4194
                         for name, node in all_info.iteritems())
4195
    else:
4196
      oob_support = None
4197

    
4198
    if query.NQ_GROUP in self.requested_data:
4199
      groups = lu.cfg.GetAllNodeGroupsInfo()
4200
    else:
4201
      groups = {}
4202

    
4203
    return query.NodeQueryData([all_info[name] for name in nodenames],
4204
                               live_data, lu.cfg.GetMasterNode(),
4205
                               node_to_primary, node_to_secondary, groups,
4206
                               oob_support, lu.cfg.GetClusterInfo())
4207

    
4208

    
4209
class LUNodeQuery(NoHooksLU):
4210
  """Logical unit for querying nodes.
4211

4212
  """
4213
  # pylint: disable-msg=W0142
4214
  REQ_BGL = False
4215

    
4216
  def CheckArguments(self):
4217
    self.nq = _NodeQuery(qlang.MakeSimpleFilter("name", self.op.names),
4218
                         self.op.output_fields, self.op.use_locking)
4219

    
4220
  def ExpandNames(self):
4221
    self.nq.ExpandNames(self)
4222

    
4223
  def Exec(self, feedback_fn):
4224
    return self.nq.OldStyleQuery(self)
4225

    
4226

    
4227
class LUNodeQueryvols(NoHooksLU):
4228
  """Logical unit for getting volumes on node(s).
4229

4230
  """
4231
  REQ_BGL = False
4232
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
4233
  _FIELDS_STATIC = utils.FieldSet("node")
4234

    
4235
  def CheckArguments(self):
4236
    _CheckOutputFields(static=self._FIELDS_STATIC,
4237
                       dynamic=self._FIELDS_DYNAMIC,
4238
                       selected=self.op.output_fields)
4239

    
4240
  def ExpandNames(self):
4241
    self.needed_locks = {}
4242
    self.share_locks[locking.LEVEL_NODE] = 1
4243
    if not self.op.nodes:
4244
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4245
    else:
4246
      self.needed_locks[locking.LEVEL_NODE] = \
4247
        _GetWantedNodes(self, self.op.nodes)
4248

    
4249
  def Exec(self, feedback_fn):
4250
    """Computes the list of nodes and their attributes.
4251

4252
    """
4253
    nodenames = self.glm.list_owned(locking.LEVEL_NODE)
4254
    volumes = self.rpc.call_node_volumes(nodenames)
4255

    
4256
    ilist = self.cfg.GetAllInstancesInfo()
4257

    
4258
    vol2inst = dict(((node, vol), inst.name)
4259
                    for inst in ilist.values()
4260
                    for (node, vols) in inst.MapLVsByNode().items()
4261
                    for vol in vols)
4262

    
4263
    output = []
4264
    for node in nodenames:
4265
      nresult = volumes[node]
4266
      if nresult.offline:
4267
        continue
4268
      msg = nresult.fail_msg
4269
      if msg:
4270
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
4271
        continue
4272

    
4273
      node_vols = sorted(nresult.payload,
4274
                         key=operator.itemgetter("dev"))
4275

    
4276
      for vol in node_vols:
4277
        node_output = []
4278
        for field in self.op.output_fields:
4279
          if field == "node":
4280
            val = node
4281
          elif field == "phys":
4282
            val = vol['dev']
4283
          elif field == "vg":
4284
            val = vol['vg']
4285
          elif field == "name":
4286
            val = vol['name']
4287
          elif field == "size":
4288
            val = int(float(vol['size']))
4289
          elif field == "instance":
4290
            val = vol2inst.get((node, vol["vg"] + "/" + vol["name"]), "-")
4291
          else:
4292
            raise errors.ParameterError(field)
4293
          node_output.append(str(val))
4294

    
4295
        output.append(node_output)
4296

    
4297
    return output
4298

    
4299

    
4300
class LUNodeQueryStorage(NoHooksLU):
4301
  """Logical unit for getting information on storage units on node(s).
4302

4303
  """
4304
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
4305
  REQ_BGL = False
4306

    
4307
  def CheckArguments(self):
4308
    _CheckOutputFields(static=self._FIELDS_STATIC,
4309
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
4310
                       selected=self.op.output_fields)
4311

    
4312
  def ExpandNames(self):
4313
    self.needed_locks = {}
4314
    self.share_locks[locking.LEVEL_NODE] = 1
4315

    
4316
    if self.op.nodes:
4317
      self.needed_locks[locking.LEVEL_NODE] = \
4318
        _GetWantedNodes(self, self.op.nodes)
4319
    else:
4320
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4321

    
4322
  def Exec(self, feedback_fn):
4323
    """Computes the list of nodes and their attributes.
4324

4325
    """
4326
    self.nodes = self.glm.list_owned(locking.LEVEL_NODE)
4327

    
4328
    # Always get name to sort by
4329
    if constants.SF_NAME in self.op.output_fields:
4330
      fields = self.op.output_fields[:]
4331
    else:
4332
      fields = [constants.SF_NAME] + self.op.output_fields
4333

    
4334
    # Never ask for node or type as it's only known to the LU
4335
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
4336
      while extra in fields:
4337
        fields.remove(extra)
4338

    
4339
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
4340
    name_idx = field_idx[constants.SF_NAME]
4341

    
4342
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4343
    data = self.rpc.call_storage_list(self.nodes,
4344
                                      self.op.storage_type, st_args,
4345
                                      self.op.name, fields)
4346

    
4347
    result = []
4348

    
4349
    for node in utils.NiceSort(self.nodes):
4350
      nresult = data[node]
4351
      if nresult.offline:
4352
        continue
4353

    
4354
      msg = nresult.fail_msg
4355
      if msg:
4356
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
4357
        continue
4358

    
4359
      rows = dict([(row[name_idx], row) for row in nresult.payload])
4360

    
4361
      for name in utils.NiceSort(rows.keys()):
4362
        row = rows[name]
4363

    
4364
        out = []
4365

    
4366
        for field in self.op.output_fields:
4367
          if field == constants.SF_NODE:
4368
            val = node
4369
          elif field == constants.SF_TYPE:
4370
            val = self.op.storage_type
4371
          elif field in field_idx:
4372
            val = row[field_idx[field]]
4373
          else:
4374
            raise errors.ParameterError(field)
4375

    
4376
          out.append(val)
4377

    
4378
        result.append(out)
4379

    
4380
    return result
4381

    
4382

    
4383
class _InstanceQuery(_QueryBase):
4384
  FIELDS = query.INSTANCE_FIELDS
4385

    
4386
  def ExpandNames(self, lu):
4387
    lu.needed_locks = {}
4388
    lu.share_locks[locking.LEVEL_INSTANCE] = 1
4389
    lu.share_locks[locking.LEVEL_NODE] = 1
4390

    
4391
    if self.names:
4392
      self.wanted = _GetWantedInstances(lu, self.names)
4393
    else:
4394
      self.wanted = locking.ALL_SET
4395

    
4396
    self.do_locking = (self.use_locking and
4397
                       query.IQ_LIVE in self.requested_data)
4398
    if self.do_locking:
4399
      lu.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4400
      lu.needed_locks[locking.LEVEL_NODE] = []
4401
      lu.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4402

    
4403
  def DeclareLocks(self, lu, level):
4404
    if level == locking.LEVEL_NODE and self.do_locking:
4405
      lu._LockInstancesNodes() # pylint: disable-msg=W0212
4406

    
4407
  def _GetQueryData(self, lu):
4408
    """Computes the list of instances and their attributes.
4409

4410
    """
4411
    cluster = lu.cfg.GetClusterInfo()
4412
    all_info = lu.cfg.GetAllInstancesInfo()
4413

    
4414
    instance_names = self._GetNames(lu, all_info.keys(), locking.LEVEL_INSTANCE)
4415

    
4416
    instance_list = [all_info[name] for name in instance_names]
4417
    nodes = frozenset(itertools.chain(*(inst.all_nodes
4418
                                        for inst in instance_list)))
4419
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
4420
    bad_nodes = []
4421
    offline_nodes = []
4422
    wrongnode_inst = set()
4423

    
4424
    # Gather data as requested
4425
    if self.requested_data & set([query.IQ_LIVE, query.IQ_CONSOLE]):
4426
      live_data = {}
4427
      node_data = lu.rpc.call_all_instances_info(nodes, hv_list)
4428
      for name in nodes:
4429
        result = node_data[name]
4430
        if result.offline:
4431
          # offline nodes will be in both lists
4432
          assert result.fail_msg
4433
          offline_nodes.append(name)
4434
        if result.fail_msg:
4435
          bad_nodes.append(name)
4436
        elif result.payload:
4437
          for inst in result.payload:
4438
            if inst in all_info:
4439
              if all_info[inst].primary_node == name:
4440
                live_data.update(result.payload)
4441
              else:
4442
                wrongnode_inst.add(inst)
4443
            else:
4444
              # orphan instance; we don't list it here as we don't
4445
              # handle this case yet in the output of instance listing
4446
              logging.warning("Orphan instance '%s' found on node %s",
4447
                              inst, name)
4448
        # else no instance is alive
4449
    else:
4450
      live_data = {}
4451

    
4452
    if query.IQ_DISKUSAGE in self.requested_data:
4453
      disk_usage = dict((inst.name,
4454
                         _ComputeDiskSize(inst.disk_template,
4455
                                          [{constants.IDISK_SIZE: disk.size}
4456
                                           for disk in inst.disks]))
4457
                        for inst in instance_list)
4458
    else:
4459
      disk_usage = None
4460

    
4461
    if query.IQ_CONSOLE in self.requested_data:
4462
      consinfo = {}
4463
      for inst in instance_list:
4464
        if inst.name in live_data:
4465
          # Instance is running
4466
          consinfo[inst.name] = _GetInstanceConsole(cluster, inst)
4467
        else:
4468
          consinfo[inst.name] = None
4469
      assert set(consinfo.keys()) == set(instance_names)
4470
    else:
4471
      consinfo = None
4472

    
4473
    return query.InstanceQueryData(instance_list, lu.cfg.GetClusterInfo(),
4474
                                   disk_usage, offline_nodes, bad_nodes,
4475
                                   live_data, wrongnode_inst, consinfo)
4476

    
4477

    
4478
class LUQuery(NoHooksLU):
4479
  """Query for resources/items of a certain kind.
4480

4481
  """
4482
  # pylint: disable-msg=W0142
4483
  REQ_BGL = False
4484

    
4485
  def CheckArguments(self):
4486
    qcls = _GetQueryImplementation(self.op.what)
4487

    
4488
    self.impl = qcls(self.op.filter, self.op.fields, False)
4489

    
4490
  def ExpandNames(self):
4491
    self.impl.ExpandNames(self)
4492

    
4493
  def DeclareLocks(self, level):
4494
    self.impl.DeclareLocks(self, level)
4495

    
4496
  def Exec(self, feedback_fn):
4497
    return self.impl.NewStyleQuery(self)
4498

    
4499

    
4500
class LUQueryFields(NoHooksLU):
4501
  """Query for resources/items of a certain kind.
4502

4503
  """
4504
  # pylint: disable-msg=W0142
4505
  REQ_BGL = False
4506

    
4507
  def CheckArguments(self):
4508
    self.qcls = _GetQueryImplementation(self.op.what)
4509

    
4510
  def ExpandNames(self):
4511
    self.needed_locks = {}
4512

    
4513
  def Exec(self, feedback_fn):
4514
    return query.QueryFields(self.qcls.FIELDS, self.op.fields)
4515

    
4516

    
4517
class LUNodeModifyStorage(NoHooksLU):
4518
  """Logical unit for modifying a storage volume on a node.
4519

4520
  """
4521
  REQ_BGL = False
4522

    
4523
  def CheckArguments(self):
4524
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4525

    
4526
    storage_type = self.op.storage_type
4527

    
4528
    try:
4529
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
4530
    except KeyError:
4531
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
4532
                                 " modified" % storage_type,
4533
                                 errors.ECODE_INVAL)
4534

    
4535
    diff = set(self.op.changes.keys()) - modifiable
4536
    if diff:
4537
      raise errors.OpPrereqError("The following fields can not be modified for"
4538
                                 " storage units of type '%s': %r" %
4539
                                 (storage_type, list(diff)),
4540
                                 errors.ECODE_INVAL)
4541

    
4542
  def ExpandNames(self):
4543
    self.needed_locks = {
4544
      locking.LEVEL_NODE: self.op.node_name,
4545
      }
4546

    
4547
  def Exec(self, feedback_fn):
4548
    """Computes the list of nodes and their attributes.
4549

4550
    """
4551
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4552
    result = self.rpc.call_storage_modify(self.op.node_name,
4553
                                          self.op.storage_type, st_args,
4554
                                          self.op.name, self.op.changes)
4555
    result.Raise("Failed to modify storage unit '%s' on %s" %
4556
                 (self.op.name, self.op.node_name))
4557

    
4558

    
4559
class LUNodeAdd(LogicalUnit):
4560
  """Logical unit for adding node to the cluster.
4561

4562
  """
4563
  HPATH = "node-add"
4564
  HTYPE = constants.HTYPE_NODE
4565
  _NFLAGS = ["master_capable", "vm_capable"]
4566

    
4567
  def CheckArguments(self):
4568
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
4569
    # validate/normalize the node name
4570
    self.hostname = netutils.GetHostname(name=self.op.node_name,
4571
                                         family=self.primary_ip_family)
4572
    self.op.node_name = self.hostname.name
4573

    
4574
    if self.op.readd and self.op.node_name == self.cfg.GetMasterNode():
4575
      raise errors.OpPrereqError("Cannot readd the master node",
4576
                                 errors.ECODE_STATE)
4577

    
4578
    if self.op.readd and self.op.group:
4579
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
4580
                                 " being readded", errors.ECODE_INVAL)
4581

    
4582
  def BuildHooksEnv(self):
4583
    """Build hooks env.
4584

4585
    This will run on all nodes before, and on all nodes + the new node after.
4586

4587
    """
4588
    return {
4589
      "OP_TARGET": self.op.node_name,
4590
      "NODE_NAME": self.op.node_name,
4591
      "NODE_PIP": self.op.primary_ip,
4592
      "NODE_SIP": self.op.secondary_ip,
4593
      "MASTER_CAPABLE": str(self.op.master_capable),
4594
      "VM_CAPABLE": str(self.op.vm_capable),
4595
      }
4596

    
4597
  def BuildHooksNodes(self):
4598
    """Build hooks nodes.
4599

4600
    """
4601
    # Exclude added node
4602
    pre_nodes = list(set(self.cfg.GetNodeList()) - set([self.op.node_name]))
4603
    post_nodes = pre_nodes + [self.op.node_name, ]
4604

    
4605
    return (pre_nodes, post_nodes)
4606

    
4607
  def CheckPrereq(self):
4608
    """Check prerequisites.
4609

4610
    This checks:
4611
     - the new node is not already in the config
4612
     - it is resolvable
4613
     - its parameters (single/dual homed) matches the cluster
4614

4615
    Any errors are signaled by raising errors.OpPrereqError.
4616

4617
    """
4618
    cfg = self.cfg
4619
    hostname = self.hostname
4620
    node = hostname.name
4621
    primary_ip = self.op.primary_ip = hostname.ip
4622
    if self.op.secondary_ip is None:
4623
      if self.primary_ip_family == netutils.IP6Address.family:
4624
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
4625
                                   " IPv4 address must be given as secondary",
4626
                                   errors.ECODE_INVAL)
4627
      self.op.secondary_ip = primary_ip
4628

    
4629
    secondary_ip = self.op.secondary_ip
4630
    if not netutils.IP4Address.IsValid(secondary_ip):
4631
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4632
                                 " address" % secondary_ip, errors.ECODE_INVAL)
4633

    
4634
    node_list = cfg.GetNodeList()
4635
    if not self.op.readd and node in node_list:
4636
      raise errors.OpPrereqError("Node %s is already in the configuration" %
4637
                                 node, errors.ECODE_EXISTS)
4638
    elif self.op.readd and node not in node_list:
4639
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
4640
                                 errors.ECODE_NOENT)
4641

    
4642
    self.changed_primary_ip = False
4643

    
4644
    for existing_node_name in node_list:
4645
      existing_node = cfg.GetNodeInfo(existing_node_name)
4646

    
4647
      if self.op.readd and node == existing_node_name:
4648
        if existing_node.secondary_ip != secondary_ip:
4649
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
4650
                                     " address configuration as before",
4651
                                     errors.ECODE_INVAL)
4652
        if existing_node.primary_ip != primary_ip:
4653
          self.changed_primary_ip = True
4654

    
4655
        continue
4656

    
4657
      if (existing_node.primary_ip == primary_ip or
4658
          existing_node.secondary_ip == primary_ip or
4659
          existing_node.primary_ip == secondary_ip or
4660
          existing_node.secondary_ip == secondary_ip):
4661
        raise errors.OpPrereqError("New node ip address(es) conflict with"
4662
                                   " existing node %s" % existing_node.name,
4663
                                   errors.ECODE_NOTUNIQUE)
4664

    
4665
    # After this 'if' block, None is no longer a valid value for the
4666
    # _capable op attributes
4667
    if self.op.readd:
4668
      old_node = self.cfg.GetNodeInfo(node)
4669
      assert old_node is not None, "Can't retrieve locked node %s" % node
4670
      for attr in self._NFLAGS:
4671
        if getattr(self.op, attr) is None:
4672
          setattr(self.op, attr, getattr(old_node, attr))
4673
    else:
4674
      for attr in self._NFLAGS:
4675
        if getattr(self.op, attr) is None:
4676
          setattr(self.op, attr, True)
4677

    
4678
    if self.op.readd and not self.op.vm_capable:
4679
      pri, sec = cfg.GetNodeInstances(node)
4680
      if pri or sec:
4681
        raise errors.OpPrereqError("Node %s being re-added with vm_capable"
4682
                                   " flag set to false, but it already holds"
4683
                                   " instances" % node,
4684
                                   errors.ECODE_STATE)
4685

    
4686
    # check that the type of the node (single versus dual homed) is the
4687
    # same as for the master
4688
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
4689
    master_singlehomed = myself.secondary_ip == myself.primary_ip
4690
    newbie_singlehomed = secondary_ip == primary_ip
4691
    if master_singlehomed != newbie_singlehomed:
4692
      if master_singlehomed:
4693
        raise errors.OpPrereqError("The master has no secondary ip but the"
4694
                                   " new node has one",
4695
                                   errors.ECODE_INVAL)
4696
      else:
4697
        raise errors.OpPrereqError("The master has a secondary ip but the"
4698
                                   " new node doesn't have one",
4699
                                   errors.ECODE_INVAL)
4700

    
4701
    # checks reachability
4702
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
4703
      raise errors.OpPrereqError("Node not reachable by ping",
4704
                                 errors.ECODE_ENVIRON)
4705

    
4706
    if not newbie_singlehomed:
4707
      # check reachability from my secondary ip to newbie's secondary ip
4708
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
4709
                           source=myself.secondary_ip):
4710
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4711
                                   " based ping to node daemon port",
4712
                                   errors.ECODE_ENVIRON)
4713

    
4714
    if self.op.readd:
4715
      exceptions = [node]
4716
    else:
4717
      exceptions = []
4718

    
4719
    if self.op.master_capable:
4720
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
4721
    else:
4722
      self.master_candidate = False
4723

    
4724
    if self.op.readd:
4725
      self.new_node = old_node
4726
    else:
4727
      node_group = cfg.LookupNodeGroup(self.op.group)
4728
      self.new_node = objects.Node(name=node,
4729
                                   primary_ip=primary_ip,
4730
                                   secondary_ip=secondary_ip,
4731
                                   master_candidate=self.master_candidate,
4732
                                   offline=False, drained=False,
4733
                                   group=node_group)
4734

    
4735
    if self.op.ndparams:
4736
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
4737

    
4738
  def Exec(self, feedback_fn):
4739
    """Adds the new node to the cluster.
4740

4741
    """
4742
    new_node = self.new_node
4743
    node = new_node.name
4744

    
4745
    # We adding a new node so we assume it's powered
4746
    new_node.powered = True
4747

    
4748
    # for re-adds, reset the offline/drained/master-candidate flags;
4749
    # we need to reset here, otherwise offline would prevent RPC calls
4750
    # later in the procedure; this also means that if the re-add
4751
    # fails, we are left with a non-offlined, broken node
4752
    if self.op.readd:
4753
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
4754
      self.LogInfo("Readding a node, the offline/drained flags were reset")
4755
      # if we demote the node, we do cleanup later in the procedure
4756
      new_node.master_candidate = self.master_candidate
4757
      if self.changed_primary_ip:
4758
        new_node.primary_ip = self.op.primary_ip
4759

    
4760
    # copy the master/vm_capable flags
4761
    for attr in self._NFLAGS:
4762
      setattr(new_node, attr, getattr(self.op, attr))
4763

    
4764
    # notify the user about any possible mc promotion
4765
    if new_node.master_candidate:
4766
      self.LogInfo("Node will be a master candidate")
4767

    
4768
    if self.op.ndparams:
4769
      new_node.ndparams = self.op.ndparams
4770
    else:
4771
      new_node.ndparams = {}
4772

    
4773
    # check connectivity
4774
    result = self.rpc.call_version([node])[node]
4775
    result.Raise("Can't get version information from node %s" % node)
4776
    if constants.PROTOCOL_VERSION == result.payload:
4777
      logging.info("Communication to node %s fine, sw version %s match",
4778
                   node, result.payload)
4779
    else:
4780
      raise errors.OpExecError("Version mismatch master version %s,"
4781
                               " node version %s" %
4782
                               (constants.PROTOCOL_VERSION, result.payload))
4783

    
4784
    # Add node to our /etc/hosts, and add key to known_hosts
4785
    if self.cfg.GetClusterInfo().modify_etc_hosts:
4786
      master_node = self.cfg.GetMasterNode()
4787
      result = self.rpc.call_etc_hosts_modify(master_node,
4788
                                              constants.ETC_HOSTS_ADD,
4789
                                              self.hostname.name,
4790
                                              self.hostname.ip)
4791
      result.Raise("Can't update hosts file with new host data")
4792

    
4793
    if new_node.secondary_ip != new_node.primary_ip:
4794
      _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
4795
                               False)
4796

    
4797
    node_verify_list = [self.cfg.GetMasterNode()]
4798
    node_verify_param = {
4799
      constants.NV_NODELIST: [node],
4800
      # TODO: do a node-net-test as well?
4801
    }
4802

    
4803
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
4804
                                       self.cfg.GetClusterName())
4805
    for verifier in node_verify_list:
4806
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
4807
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
4808
      if nl_payload:
4809
        for failed in nl_payload:
4810
          feedback_fn("ssh/hostname verification failed"
4811
                      " (checking from %s): %s" %
4812
                      (verifier, nl_payload[failed]))
4813
        raise errors.OpExecError("ssh/hostname verification failed")
4814

    
4815
    if self.op.readd:
4816
      _RedistributeAncillaryFiles(self)
4817
      self.context.ReaddNode(new_node)
4818
      # make sure we redistribute the config
4819
      self.cfg.Update(new_node, feedback_fn)
4820
      # and make sure the new node will not have old files around
4821
      if not new_node.master_candidate:
4822
        result = self.rpc.call_node_demote_from_mc(new_node.name)
4823
        msg = result.fail_msg
4824
        if msg:
4825
          self.LogWarning("Node failed to demote itself from master"
4826
                          " candidate status: %s" % msg)
4827
    else:
4828
      _RedistributeAncillaryFiles(self, additional_nodes=[node],
4829
                                  additional_vm=self.op.vm_capable)
4830
      self.context.AddNode(new_node, self.proc.GetECId())
4831

    
4832

    
4833
class LUNodeSetParams(LogicalUnit):
4834
  """Modifies the parameters of a node.
4835

4836
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
4837
      to the node role (as _ROLE_*)
4838
  @cvar _R2F: a dictionary from node role to tuples of flags
4839
  @cvar _FLAGS: a list of attribute names corresponding to the flags
4840

4841
  """
4842
  HPATH = "node-modify"
4843
  HTYPE = constants.HTYPE_NODE
4844
  REQ_BGL = False
4845
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
4846
  _F2R = {
4847
    (True, False, False): _ROLE_CANDIDATE,
4848
    (False, True, False): _ROLE_DRAINED,
4849
    (False, False, True): _ROLE_OFFLINE,
4850
    (False, False, False): _ROLE_REGULAR,
4851
    }
4852
  _R2F = dict((v, k) for k, v in _F2R.items())
4853
  _FLAGS = ["master_candidate", "drained", "offline"]
4854

    
4855
  def CheckArguments(self):
4856
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4857
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
4858
                self.op.master_capable, self.op.vm_capable,
4859
                self.op.secondary_ip, self.op.ndparams]
4860
    if all_mods.count(None) == len(all_mods):
4861
      raise errors.OpPrereqError("Please pass at least one modification",
4862
                                 errors.ECODE_INVAL)
4863
    if all_mods.count(True) > 1:
4864
      raise errors.OpPrereqError("Can't set the node into more than one"
4865
                                 " state at the same time",
4866
                                 errors.ECODE_INVAL)
4867

    
4868
    # Boolean value that tells us whether we might be demoting from MC
4869
    self.might_demote = (self.op.master_candidate == False or
4870
                         self.op.offline == True or
4871
                         self.op.drained == True or
4872
                         self.op.master_capable == False)
4873

    
4874
    if self.op.secondary_ip:
4875
      if not netutils.IP4Address.IsValid(self.op.secondary_ip):
4876
        raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4877
                                   " address" % self.op.secondary_ip,
4878
                                   errors.ECODE_INVAL)
4879

    
4880
    self.lock_all = self.op.auto_promote and self.might_demote
4881
    self.lock_instances = self.op.secondary_ip is not None
4882

    
4883
  def ExpandNames(self):
4884
    if self.lock_all:
4885
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
4886
    else:
4887
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
4888

    
4889
    if self.lock_instances:
4890
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4891

    
4892
  def DeclareLocks(self, level):
4893
    # If we have locked all instances, before waiting to lock nodes, release
4894
    # all the ones living on nodes unrelated to the current operation.
4895
    if level == locking.LEVEL_NODE and self.lock_instances:
4896
      self.affected_instances = []
4897
      if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4898
        instances_keep = []
4899

    
4900
        # Build list of instances to release
4901
        for instance_name in self.glm.list_owned(locking.LEVEL_INSTANCE):
4902
          instance = self.context.cfg.GetInstanceInfo(instance_name)
4903
          if (instance.disk_template in constants.DTS_INT_MIRROR and
4904
              self.op.node_name in instance.all_nodes):
4905
            instances_keep.append(instance_name)
4906
            self.affected_instances.append(instance)
4907

    
4908
        _ReleaseLocks(self, locking.LEVEL_INSTANCE, keep=instances_keep)
4909

    
4910
        assert (set(self.glm.list_owned(locking.LEVEL_INSTANCE)) ==
4911
                set(instances_keep))
4912

    
4913
  def BuildHooksEnv(self):
4914
    """Build hooks env.
4915

4916
    This runs on the master node.
4917

4918
    """
4919
    return {
4920
      "OP_TARGET": self.op.node_name,
4921
      "MASTER_CANDIDATE": str(self.op.master_candidate),
4922
      "OFFLINE": str(self.op.offline),
4923
      "DRAINED": str(self.op.drained),
4924
      "MASTER_CAPABLE": str(self.op.master_capable),
4925
      "VM_CAPABLE": str(self.op.vm_capable),
4926
      }
4927

    
4928
  def BuildHooksNodes(self):
4929
    """Build hooks nodes.
4930

4931
    """
4932
    nl = [self.cfg.GetMasterNode(), self.op.node_name]
4933
    return (nl, nl)
4934

    
4935
  def CheckPrereq(self):
4936
    """Check prerequisites.
4937

4938
    This only checks the instance list against the existing names.
4939

4940
    """
4941
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
4942

    
4943
    if (self.op.master_candidate is not None or
4944
        self.op.drained is not None or
4945
        self.op.offline is not None):
4946
      # we can't change the master's node flags
4947
      if self.op.node_name == self.cfg.GetMasterNode():
4948
        raise errors.OpPrereqError("The master role can be changed"
4949
                                   " only via master-failover",
4950
                                   errors.ECODE_INVAL)
4951

    
4952
    if self.op.master_candidate and not node.master_capable:
4953
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4954
                                 " it a master candidate" % node.name,
4955
                                 errors.ECODE_STATE)
4956

    
4957
    if self.op.vm_capable == False:
4958
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
4959
      if ipri or isec:
4960
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
4961
                                   " the vm_capable flag" % node.name,
4962
                                   errors.ECODE_STATE)
4963

    
4964
    if node.master_candidate and self.might_demote and not self.lock_all:
4965
      assert not self.op.auto_promote, "auto_promote set but lock_all not"
4966
      # check if after removing the current node, we're missing master
4967
      # candidates
4968
      (mc_remaining, mc_should, _) = \
4969
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
4970
      if mc_remaining < mc_should:
4971
        raise errors.OpPrereqError("Not enough master candidates, please"
4972
                                   " pass auto promote option to allow"
4973
                                   " promotion", errors.ECODE_STATE)
4974

    
4975
    self.old_flags = old_flags = (node.master_candidate,
4976
                                  node.drained, node.offline)
4977
    assert old_flags in self._F2R, "Un-handled old flags %s" % str(old_flags)
4978
    self.old_role = old_role = self._F2R[old_flags]
4979

    
4980
    # Check for ineffective changes
4981
    for attr in self._FLAGS:
4982
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
4983
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
4984
        setattr(self.op, attr, None)
4985

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

    
4989
    # TODO: We might query the real power state if it supports OOB
4990
    if _SupportsOob(self.cfg, node):
4991
      if self.op.offline is False and not (node.powered or
4992
                                           self.op.powered == True):
4993
        raise errors.OpPrereqError(("Node %s needs to be turned on before its"
4994
                                    " offline status can be reset") %
4995
                                   self.op.node_name)
4996
    elif self.op.powered is not None:
4997
      raise errors.OpPrereqError(("Unable to change powered state for node %s"
4998
                                  " as it does not support out-of-band"
4999
                                  " handling") % self.op.node_name)
5000

    
5001
    # If we're being deofflined/drained, we'll MC ourself if needed
5002
    if (self.op.drained == False or self.op.offline == False or
5003
        (self.op.master_capable and not node.master_capable)):
5004
      if _DecideSelfPromotion(self):
5005
        self.op.master_candidate = True
5006
        self.LogInfo("Auto-promoting node to master candidate")
5007

    
5008
    # If we're no longer master capable, we'll demote ourselves from MC
5009
    if self.op.master_capable == False and node.master_candidate:
5010
      self.LogInfo("Demoting from master candidate")
5011
      self.op.master_candidate = False
5012

    
5013
    # Compute new role
5014
    assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
5015
    if self.op.master_candidate:
5016
      new_role = self._ROLE_CANDIDATE
5017
    elif self.op.drained:
5018
      new_role = self._ROLE_DRAINED
5019
    elif self.op.offline:
5020
      new_role = self._ROLE_OFFLINE
5021
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
5022
      # False is still in new flags, which means we're un-setting (the
5023
      # only) True flag
5024
      new_role = self._ROLE_REGULAR
5025
    else: # no new flags, nothing, keep old role
5026
      new_role = old_role
5027

    
5028
    self.new_role = new_role
5029

    
5030
    if old_role == self._ROLE_OFFLINE and new_role != old_role:
5031
      # Trying to transition out of offline status
5032
      result = self.rpc.call_version([node.name])[node.name]
5033
      if result.fail_msg:
5034
        raise errors.OpPrereqError("Node %s is being de-offlined but fails"
5035
                                   " to report its version: %s" %
5036
                                   (node.name, result.fail_msg),
5037
                                   errors.ECODE_STATE)
5038
      else:
5039
        self.LogWarning("Transitioning node from offline to online state"
5040
                        " without using re-add. Please make sure the node"
5041
                        " is healthy!")
5042

    
5043
    if self.op.secondary_ip:
5044
      # Ok even without locking, because this can't be changed by any LU
5045
      master = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
5046
      master_singlehomed = master.secondary_ip == master.primary_ip
5047
      if master_singlehomed and self.op.secondary_ip:
5048
        raise errors.OpPrereqError("Cannot change the secondary ip on a single"
5049
                                   " homed cluster", errors.ECODE_INVAL)
5050

    
5051
      if node.offline:
5052
        if self.affected_instances:
5053
          raise errors.OpPrereqError("Cannot change secondary ip: offline"
5054
                                     " node has instances (%s) configured"
5055
                                     " to use it" % self.affected_instances)
5056
      else:
5057
        # On online nodes, check that no instances are running, and that
5058
        # the node has the new ip and we can reach it.
5059
        for instance in self.affected_instances:
5060
          _CheckInstanceDown(self, instance, "cannot change secondary ip")
5061

    
5062
        _CheckNodeHasSecondaryIP(self, node.name, self.op.secondary_ip, True)
5063
        if master.name != node.name:
5064
          # check reachability from master secondary ip to new secondary ip
5065
          if not netutils.TcpPing(self.op.secondary_ip,
5066
                                  constants.DEFAULT_NODED_PORT,
5067
                                  source=master.secondary_ip):
5068
            raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
5069
                                       " based ping to node daemon port",
5070
                                       errors.ECODE_ENVIRON)
5071

    
5072
    if self.op.ndparams:
5073
      new_ndparams = _GetUpdatedParams(self.node.ndparams, self.op.ndparams)
5074
      utils.ForceDictType(new_ndparams, constants.NDS_PARAMETER_TYPES)
5075
      self.new_ndparams = new_ndparams
5076

    
5077
  def Exec(self, feedback_fn):
5078
    """Modifies a node.
5079

5080
    """
5081
    node = self.node
5082
    old_role = self.old_role
5083
    new_role = self.new_role
5084

    
5085
    result = []
5086

    
5087
    if self.op.ndparams:
5088
      node.ndparams = self.new_ndparams
5089

    
5090
    if self.op.powered is not None:
5091
      node.powered = self.op.powered
5092

    
5093
    for attr in ["master_capable", "vm_capable"]:
5094
      val = getattr(self.op, attr)
5095
      if val is not None:
5096
        setattr(node, attr, val)
5097
        result.append((attr, str(val)))
5098

    
5099
    if new_role != old_role:
5100
      # Tell the node to demote itself, if no longer MC and not offline
5101
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
5102
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
5103
        if msg:
5104
          self.LogWarning("Node failed to demote itself: %s", msg)
5105

    
5106
      new_flags = self._R2F[new_role]
5107
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
5108
        if of != nf:
5109
          result.append((desc, str(nf)))
5110
      (node.master_candidate, node.drained, node.offline) = new_flags
5111

    
5112
      # we locked all nodes, we adjust the CP before updating this node
5113
      if self.lock_all:
5114
        _AdjustCandidatePool(self, [node.name])
5115

    
5116
    if self.op.secondary_ip:
5117
      node.secondary_ip = self.op.secondary_ip
5118
      result.append(("secondary_ip", self.op.secondary_ip))
5119

    
5120
    # this will trigger configuration file update, if needed
5121
    self.cfg.Update(node, feedback_fn)
5122

    
5123
    # this will trigger job queue propagation or cleanup if the mc
5124
    # flag changed
5125
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
5126
      self.context.ReaddNode(node)
5127

    
5128
    return result
5129

    
5130

    
5131
class LUNodePowercycle(NoHooksLU):
5132
  """Powercycles a node.
5133

5134
  """
5135
  REQ_BGL = False
5136

    
5137
  def CheckArguments(self):
5138
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5139
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
5140
      raise errors.OpPrereqError("The node is the master and the force"
5141
                                 " parameter was not set",
5142
                                 errors.ECODE_INVAL)
5143

    
5144
  def ExpandNames(self):
5145
    """Locking for PowercycleNode.
5146

5147
    This is a last-resort option and shouldn't block on other
5148
    jobs. Therefore, we grab no locks.
5149

5150
    """
5151
    self.needed_locks = {}
5152

    
5153
  def Exec(self, feedback_fn):
5154
    """Reboots a node.
5155

5156
    """
5157
    result = self.rpc.call_node_powercycle(self.op.node_name,
5158
                                           self.cfg.GetHypervisorType())
5159
    result.Raise("Failed to schedule the reboot")
5160
    return result.payload
5161

    
5162

    
5163
class LUClusterQuery(NoHooksLU):
5164
  """Query cluster configuration.
5165

5166
  """
5167
  REQ_BGL = False
5168

    
5169
  def ExpandNames(self):
5170
    self.needed_locks = {}
5171

    
5172
  def Exec(self, feedback_fn):
5173
    """Return cluster config.
5174

5175
    """
5176
    cluster = self.cfg.GetClusterInfo()
5177
    os_hvp = {}
5178

    
5179
    # Filter just for enabled hypervisors
5180
    for os_name, hv_dict in cluster.os_hvp.items():
5181
      os_hvp[os_name] = {}
5182
      for hv_name, hv_params in hv_dict.items():
5183
        if hv_name in cluster.enabled_hypervisors:
5184
          os_hvp[os_name][hv_name] = hv_params
5185

    
5186
    # Convert ip_family to ip_version
5187
    primary_ip_version = constants.IP4_VERSION
5188
    if cluster.primary_ip_family == netutils.IP6Address.family:
5189
      primary_ip_version = constants.IP6_VERSION
5190

    
5191
    result = {
5192
      "software_version": constants.RELEASE_VERSION,
5193
      "protocol_version": constants.PROTOCOL_VERSION,
5194
      "config_version": constants.CONFIG_VERSION,
5195
      "os_api_version": max(constants.OS_API_VERSIONS),
5196
      "export_version": constants.EXPORT_VERSION,
5197
      "architecture": (platform.architecture()[0], platform.machine()),
5198
      "name": cluster.cluster_name,
5199
      "master": cluster.master_node,
5200
      "default_hypervisor": cluster.enabled_hypervisors[0],
5201
      "enabled_hypervisors": cluster.enabled_hypervisors,
5202
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
5203
                        for hypervisor_name in cluster.enabled_hypervisors]),
5204
      "os_hvp": os_hvp,
5205
      "beparams": cluster.beparams,
5206
      "osparams": cluster.osparams,
5207
      "nicparams": cluster.nicparams,
5208
      "ndparams": cluster.ndparams,
5209
      "candidate_pool_size": cluster.candidate_pool_size,
5210
      "master_netdev": cluster.master_netdev,
5211
      "volume_group_name": cluster.volume_group_name,
5212
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
5213
      "file_storage_dir": cluster.file_storage_dir,
5214
      "shared_file_storage_dir": cluster.shared_file_storage_dir,
5215
      "maintain_node_health": cluster.maintain_node_health,
5216
      "ctime": cluster.ctime,
5217
      "mtime": cluster.mtime,
5218
      "uuid": cluster.uuid,
5219
      "tags": list(cluster.GetTags()),
5220
      "uid_pool": cluster.uid_pool,
5221
      "default_iallocator": cluster.default_iallocator,
5222
      "reserved_lvs": cluster.reserved_lvs,
5223
      "primary_ip_version": primary_ip_version,
5224
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
5225
      "hidden_os": cluster.hidden_os,
5226
      "blacklisted_os": cluster.blacklisted_os,
5227
      }
5228

    
5229
    return result
5230

    
5231

    
5232
class LUClusterConfigQuery(NoHooksLU):
5233
  """Return configuration values.
5234

5235
  """
5236
  REQ_BGL = False
5237
  _FIELDS_DYNAMIC = utils.FieldSet()
5238
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
5239
                                  "watcher_pause", "volume_group_name")
5240

    
5241
  def CheckArguments(self):
5242
    _CheckOutputFields(static=self._FIELDS_STATIC,
5243
                       dynamic=self._FIELDS_DYNAMIC,
5244
                       selected=self.op.output_fields)
5245

    
5246
  def ExpandNames(self):
5247
    self.needed_locks = {}
5248

    
5249
  def Exec(self, feedback_fn):
5250
    """Dump a representation of the cluster config to the standard output.
5251

5252
    """
5253
    values = []
5254
    for field in self.op.output_fields:
5255
      if field == "cluster_name":
5256
        entry = self.cfg.GetClusterName()
5257
      elif field == "master_node":
5258
        entry = self.cfg.GetMasterNode()
5259
      elif field == "drain_flag":
5260
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
5261
      elif field == "watcher_pause":
5262
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
5263
      elif field == "volume_group_name":
5264
        entry = self.cfg.GetVGName()
5265
      else:
5266
        raise errors.ParameterError(field)
5267
      values.append(entry)
5268
    return values
5269

    
5270

    
5271
class LUInstanceActivateDisks(NoHooksLU):
5272
  """Bring up an instance's disks.
5273

5274
  """
5275
  REQ_BGL = False
5276

    
5277
  def ExpandNames(self):
5278
    self._ExpandAndLockInstance()
5279
    self.needed_locks[locking.LEVEL_NODE] = []
5280
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5281

    
5282
  def DeclareLocks(self, level):
5283
    if level == locking.LEVEL_NODE:
5284
      self._LockInstancesNodes()
5285

    
5286
  def CheckPrereq(self):
5287
    """Check prerequisites.
5288

5289
    This checks that the instance is in the cluster.
5290

5291
    """
5292
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5293
    assert self.instance is not None, \
5294
      "Cannot retrieve locked instance %s" % self.op.instance_name
5295
    _CheckNodeOnline(self, self.instance.primary_node)
5296

    
5297
  def Exec(self, feedback_fn):
5298
    """Activate the disks.
5299

5300
    """
5301
    disks_ok, disks_info = \
5302
              _AssembleInstanceDisks(self, self.instance,
5303
                                     ignore_size=self.op.ignore_size)
5304
    if not disks_ok:
5305
      raise errors.OpExecError("Cannot activate block devices")
5306

    
5307
    return disks_info
5308

    
5309

    
5310
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
5311
                           ignore_size=False):
5312
  """Prepare the block devices for an instance.
5313

5314
  This sets up the block devices on all nodes.
5315

5316
  @type lu: L{LogicalUnit}
5317
  @param lu: the logical unit on whose behalf we execute
5318
  @type instance: L{objects.Instance}
5319
  @param instance: the instance for whose disks we assemble
5320
  @type disks: list of L{objects.Disk} or None
5321
  @param disks: which disks to assemble (or all, if None)
5322
  @type ignore_secondaries: boolean
5323
  @param ignore_secondaries: if true, errors on secondary nodes
5324
      won't result in an error return from the function
5325
  @type ignore_size: boolean
5326
  @param ignore_size: if true, the current known size of the disk
5327
      will not be used during the disk activation, useful for cases
5328
      when the size is wrong
5329
  @return: False if the operation failed, otherwise a list of
5330
      (host, instance_visible_name, node_visible_name)
5331
      with the mapping from node devices to instance devices
5332

5333
  """
5334
  device_info = []
5335
  disks_ok = True
5336
  iname = instance.name
5337
  disks = _ExpandCheckDisks(instance, disks)
5338

    
5339
  # With the two passes mechanism we try to reduce the window of
5340
  # opportunity for the race condition of switching DRBD to primary
5341
  # before handshaking occured, but we do not eliminate it
5342

    
5343
  # The proper fix would be to wait (with some limits) until the
5344
  # connection has been made and drbd transitions from WFConnection
5345
  # into any other network-connected state (Connected, SyncTarget,
5346
  # SyncSource, etc.)
5347

    
5348
  # 1st pass, assemble on all nodes in secondary mode
5349
  for idx, inst_disk in enumerate(disks):
5350
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
5351
      if ignore_size:
5352
        node_disk = node_disk.Copy()
5353
        node_disk.UnsetSize()
5354
      lu.cfg.SetDiskID(node_disk, node)
5355
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False, idx)
5356
      msg = result.fail_msg
5357
      if msg:
5358
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
5359
                           " (is_primary=False, pass=1): %s",
5360
                           inst_disk.iv_name, node, msg)
5361
        if not ignore_secondaries:
5362
          disks_ok = False
5363

    
5364
  # FIXME: race condition on drbd migration to primary
5365

    
5366
  # 2nd pass, do only the primary node
5367
  for idx, inst_disk in enumerate(disks):
5368
    dev_path = None
5369

    
5370
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
5371
      if node != instance.primary_node:
5372
        continue
5373
      if ignore_size:
5374
        node_disk = node_disk.Copy()
5375
        node_disk.UnsetSize()
5376
      lu.cfg.SetDiskID(node_disk, node)
5377
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True, idx)
5378
      msg = result.fail_msg
5379
      if msg:
5380
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
5381
                           " (is_primary=True, pass=2): %s",
5382
                           inst_disk.iv_name, node, msg)
5383
        disks_ok = False
5384
      else:
5385
        dev_path = result.payload
5386

    
5387
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
5388

    
5389
  # leave the disks configured for the primary node
5390
  # this is a workaround that would be fixed better by
5391
  # improving the logical/physical id handling
5392
  for disk in disks:
5393
    lu.cfg.SetDiskID(disk, instance.primary_node)
5394

    
5395
  return disks_ok, device_info
5396

    
5397

    
5398
def _StartInstanceDisks(lu, instance, force):
5399
  """Start the disks of an instance.
5400

5401
  """
5402
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
5403
                                           ignore_secondaries=force)
5404
  if not disks_ok:
5405
    _ShutdownInstanceDisks(lu, instance)
5406
    if force is not None and not force:
5407
      lu.proc.LogWarning("", hint="If the message above refers to a"
5408
                         " secondary node,"
5409
                         " you can retry the operation using '--force'.")
5410
    raise errors.OpExecError("Disk consistency error")
5411

    
5412

    
5413
class LUInstanceDeactivateDisks(NoHooksLU):
5414
  """Shutdown an instance's disks.
5415

5416
  """
5417
  REQ_BGL = False
5418

    
5419
  def ExpandNames(self):
5420
    self._ExpandAndLockInstance()
5421
    self.needed_locks[locking.LEVEL_NODE] = []
5422
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5423

    
5424
  def DeclareLocks(self, level):
5425
    if level == locking.LEVEL_NODE:
5426
      self._LockInstancesNodes()
5427

    
5428
  def CheckPrereq(self):
5429
    """Check prerequisites.
5430

5431
    This checks that the instance is in the cluster.
5432

5433
    """
5434
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5435
    assert self.instance is not None, \
5436
      "Cannot retrieve locked instance %s" % self.op.instance_name
5437

    
5438
  def Exec(self, feedback_fn):
5439
    """Deactivate the disks
5440

5441
    """
5442
    instance = self.instance
5443
    if self.op.force:
5444
      _ShutdownInstanceDisks(self, instance)
5445
    else:
5446
      _SafeShutdownInstanceDisks(self, instance)
5447

    
5448

    
5449
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
5450
  """Shutdown block devices of an instance.
5451

5452
  This function checks if an instance is running, before calling
5453
  _ShutdownInstanceDisks.
5454

5455
  """
5456
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
5457
  _ShutdownInstanceDisks(lu, instance, disks=disks)
5458

    
5459

    
5460
def _ExpandCheckDisks(instance, disks):
5461
  """Return the instance disks selected by the disks list
5462

5463
  @type disks: list of L{objects.Disk} or None
5464
  @param disks: selected disks
5465
  @rtype: list of L{objects.Disk}
5466
  @return: selected instance disks to act on
5467

5468
  """
5469
  if disks is None:
5470
    return instance.disks
5471
  else:
5472
    if not set(disks).issubset(instance.disks):
5473
      raise errors.ProgrammerError("Can only act on disks belonging to the"
5474
                                   " target instance")
5475
    return disks
5476

    
5477

    
5478
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
5479
  """Shutdown block devices of an instance.
5480

5481
  This does the shutdown on all nodes of the instance.
5482

5483
  If the ignore_primary is false, errors on the primary node are
5484
  ignored.
5485

5486
  """
5487
  all_result = True
5488
  disks = _ExpandCheckDisks(instance, disks)
5489

    
5490
  for disk in disks:
5491
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
5492
      lu.cfg.SetDiskID(top_disk, node)
5493
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
5494
      msg = result.fail_msg
5495
      if msg:
5496
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
5497
                      disk.iv_name, node, msg)
5498
        if ((node == instance.primary_node and not ignore_primary) or
5499
            (node != instance.primary_node and not result.offline)):
5500
          all_result = False
5501
  return all_result
5502

    
5503

    
5504
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
5505
  """Checks if a node has enough free memory.
5506

5507
  This function check if a given node has the needed amount of free
5508
  memory. In case the node has less memory or we cannot get the
5509
  information from the node, this function raise an OpPrereqError
5510
  exception.
5511

5512
  @type lu: C{LogicalUnit}
5513
  @param lu: a logical unit from which we get configuration data
5514
  @type node: C{str}
5515
  @param node: the node to check
5516
  @type reason: C{str}
5517
  @param reason: string to use in the error message
5518
  @type requested: C{int}
5519
  @param requested: the amount of memory in MiB to check for
5520
  @type hypervisor_name: C{str}
5521
  @param hypervisor_name: the hypervisor to ask for memory stats
5522
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
5523
      we cannot check the node
5524

5525
  """
5526
  nodeinfo = lu.rpc.call_node_info([node], None, hypervisor_name)
5527
  nodeinfo[node].Raise("Can't get data from node %s" % node,
5528
                       prereq=True, ecode=errors.ECODE_ENVIRON)
5529
  free_mem = nodeinfo[node].payload.get('memory_free', None)
5530
  if not isinstance(free_mem, int):
5531
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
5532
                               " was '%s'" % (node, free_mem),
5533
                               errors.ECODE_ENVIRON)
5534
  if requested > free_mem:
5535
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
5536
                               " needed %s MiB, available %s MiB" %
5537
                               (node, reason, requested, free_mem),
5538
                               errors.ECODE_NORES)
5539

    
5540

    
5541
def _CheckNodesFreeDiskPerVG(lu, nodenames, req_sizes):
5542
  """Checks if nodes have enough free disk space in the all VGs.
5543

5544
  This function check if all given nodes have the needed amount of
5545
  free disk. In case any node has less disk or we cannot get the
5546
  information from the node, this function raise an OpPrereqError
5547
  exception.
5548

5549
  @type lu: C{LogicalUnit}
5550
  @param lu: a logical unit from which we get configuration data
5551
  @type nodenames: C{list}
5552
  @param nodenames: the list of node names to check
5553
  @type req_sizes: C{dict}
5554
  @param req_sizes: the hash of vg and corresponding amount of disk in
5555
      MiB to check for
5556
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5557
      or we cannot check the node
5558

5559
  """
5560
  for vg, req_size in req_sizes.items():
5561
    _CheckNodesFreeDiskOnVG(lu, nodenames, vg, req_size)
5562

    
5563

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

5567
  This function check if all given nodes have the needed amount of
5568
  free disk. In case any node has less disk or we cannot get the
5569
  information from the node, this function raise an OpPrereqError
5570
  exception.
5571

5572
  @type lu: C{LogicalUnit}
5573
  @param lu: a logical unit from which we get configuration data
5574
  @type nodenames: C{list}
5575
  @param nodenames: the list of node names to check
5576
  @type vg: C{str}
5577
  @param vg: the volume group to check
5578
  @type requested: C{int}
5579
  @param requested: the amount of disk in MiB to check for
5580
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5581
      or we cannot check the node
5582

5583
  """
5584
  nodeinfo = lu.rpc.call_node_info(nodenames, vg, None)
5585
  for node in nodenames:
5586
    info = nodeinfo[node]
5587
    info.Raise("Cannot get current information from node %s" % node,
5588
               prereq=True, ecode=errors.ECODE_ENVIRON)
5589
    vg_free = info.payload.get("vg_free", None)
5590
    if not isinstance(vg_free, int):
5591
      raise errors.OpPrereqError("Can't compute free disk space on node"
5592
                                 " %s for vg %s, result was '%s'" %
5593
                                 (node, vg, vg_free), errors.ECODE_ENVIRON)
5594
    if requested > vg_free:
5595
      raise errors.OpPrereqError("Not enough disk space on target node %s"
5596
                                 " vg %s: required %d MiB, available %d MiB" %
5597
                                 (node, vg, requested, vg_free),
5598
                                 errors.ECODE_NORES)
5599

    
5600

    
5601
class LUInstanceStartup(LogicalUnit):
5602
  """Starts an instance.
5603

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

    
5609
  def CheckArguments(self):
5610
    # extra beparams
5611
    if self.op.beparams:
5612
      # fill the beparams dict
5613
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5614

    
5615
  def ExpandNames(self):
5616
    self._ExpandAndLockInstance()
5617

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

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

5623
    """
5624
    env = {
5625
      "FORCE": self.op.force,
5626
      }
5627

    
5628
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5629

    
5630
    return env
5631

    
5632
  def BuildHooksNodes(self):
5633
    """Build hooks nodes.
5634

5635
    """
5636
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5637
    return (nl, nl)
5638

    
5639
  def CheckPrereq(self):
5640
    """Check prerequisites.
5641

5642
    This checks that the instance is in the cluster.
5643

5644
    """
5645
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5646
    assert self.instance is not None, \
5647
      "Cannot retrieve locked instance %s" % self.op.instance_name
5648

    
5649
    # extra hvparams
5650
    if self.op.hvparams:
5651
      # check hypervisor parameter syntax (locally)
5652
      cluster = self.cfg.GetClusterInfo()
5653
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5654
      filled_hvp = cluster.FillHV(instance)
5655
      filled_hvp.update(self.op.hvparams)
5656
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
5657
      hv_type.CheckParameterSyntax(filled_hvp)
5658
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
5659

    
5660
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
5661

    
5662
    if self.primary_offline and self.op.ignore_offline_nodes:
5663
      self.proc.LogWarning("Ignoring offline primary node")
5664

    
5665
      if self.op.hvparams or self.op.beparams:
5666
        self.proc.LogWarning("Overridden parameters are ignored")
5667
    else:
5668
      _CheckNodeOnline(self, instance.primary_node)
5669

    
5670
      bep = self.cfg.GetClusterInfo().FillBE(instance)
5671

    
5672
      # check bridges existence
5673
      _CheckInstanceBridgesExist(self, instance)
5674

    
5675
      remote_info = self.rpc.call_instance_info(instance.primary_node,
5676
                                                instance.name,
5677
                                                instance.hypervisor)
5678
      remote_info.Raise("Error checking node %s" % instance.primary_node,
5679
                        prereq=True, ecode=errors.ECODE_ENVIRON)
5680
      if not remote_info.payload: # not running already
5681
        _CheckNodeFreeMemory(self, instance.primary_node,
5682
                             "starting instance %s" % instance.name,
5683
                             bep[constants.BE_MEMORY], instance.hypervisor)
5684

    
5685
  def Exec(self, feedback_fn):
5686
    """Start the instance.
5687

5688
    """
5689
    instance = self.instance
5690
    force = self.op.force
5691

    
5692
    if not self.op.no_remember:
5693
      self.cfg.MarkInstanceUp(instance.name)
5694

    
5695
    if self.primary_offline:
5696
      assert self.op.ignore_offline_nodes
5697
      self.proc.LogInfo("Primary node offline, marked instance as started")
5698
    else:
5699
      node_current = instance.primary_node
5700

    
5701
      _StartInstanceDisks(self, instance, force)
5702

    
5703
      result = self.rpc.call_instance_start(node_current, instance,
5704
                                            self.op.hvparams, self.op.beparams,
5705
                                            self.op.startup_paused)
5706
      msg = result.fail_msg
5707
      if msg:
5708
        _ShutdownInstanceDisks(self, instance)
5709
        raise errors.OpExecError("Could not start instance: %s" % msg)
5710

    
5711

    
5712
class LUInstanceReboot(LogicalUnit):
5713
  """Reboot an instance.
5714

5715
  """
5716
  HPATH = "instance-reboot"
5717
  HTYPE = constants.HTYPE_INSTANCE
5718
  REQ_BGL = False
5719

    
5720
  def ExpandNames(self):
5721
    self._ExpandAndLockInstance()
5722

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

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

5728
    """
5729
    env = {
5730
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
5731
      "REBOOT_TYPE": self.op.reboot_type,
5732
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5733
      }
5734

    
5735
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5736

    
5737
    return env
5738

    
5739
  def BuildHooksNodes(self):
5740
    """Build hooks nodes.
5741

5742
    """
5743
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5744
    return (nl, nl)
5745

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

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

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

    
5756
    _CheckNodeOnline(self, instance.primary_node)
5757

    
5758
    # check bridges existence
5759
    _CheckInstanceBridgesExist(self, instance)
5760

    
5761
  def Exec(self, feedback_fn):
5762
    """Reboot the instance.
5763

5764
    """
5765
    instance = self.instance
5766
    ignore_secondaries = self.op.ignore_secondaries
5767
    reboot_type = self.op.reboot_type
5768

    
5769
    remote_info = self.rpc.call_instance_info(instance.primary_node,
5770
                                              instance.name,
5771
                                              instance.hypervisor)
5772
    remote_info.Raise("Error checking node %s" % instance.primary_node)
5773
    instance_running = bool(remote_info.payload)
5774

    
5775
    node_current = instance.primary_node
5776

    
5777
    if instance_running and reboot_type in [constants.INSTANCE_REBOOT_SOFT,
5778
                                            constants.INSTANCE_REBOOT_HARD]:
5779
      for disk in instance.disks:
5780
        self.cfg.SetDiskID(disk, node_current)
5781
      result = self.rpc.call_instance_reboot(node_current, instance,
5782
                                             reboot_type,
5783
                                             self.op.shutdown_timeout)
5784
      result.Raise("Could not reboot instance")
5785
    else:
5786
      if instance_running:
5787
        result = self.rpc.call_instance_shutdown(node_current, instance,
5788
                                                 self.op.shutdown_timeout)
5789
        result.Raise("Could not shutdown instance for full reboot")
5790
        _ShutdownInstanceDisks(self, instance)
5791
      else:
5792
        self.LogInfo("Instance %s was already stopped, starting now",
5793
                     instance.name)
5794
      _StartInstanceDisks(self, instance, ignore_secondaries)
5795
      result = self.rpc.call_instance_start(node_current, instance,
5796
                                            None, None, False)
5797
      msg = result.fail_msg
5798
      if msg:
5799
        _ShutdownInstanceDisks(self, instance)
5800
        raise errors.OpExecError("Could not start instance for"
5801
                                 " full reboot: %s" % msg)
5802

    
5803
    self.cfg.MarkInstanceUp(instance.name)
5804

    
5805

    
5806
class LUInstanceShutdown(LogicalUnit):
5807
  """Shutdown an instance.
5808

5809
  """
5810
  HPATH = "instance-stop"
5811
  HTYPE = constants.HTYPE_INSTANCE
5812
  REQ_BGL = False
5813

    
5814
  def ExpandNames(self):
5815
    self._ExpandAndLockInstance()
5816

    
5817
  def BuildHooksEnv(self):
5818
    """Build hooks env.
5819

5820
    This runs on master, primary and secondary nodes of the instance.
5821

5822
    """
5823
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5824
    env["TIMEOUT"] = self.op.timeout
5825
    return env
5826

    
5827
  def BuildHooksNodes(self):
5828
    """Build hooks nodes.
5829

5830
    """
5831
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5832
    return (nl, nl)
5833

    
5834
  def CheckPrereq(self):
5835
    """Check prerequisites.
5836

5837
    This checks that the instance is in the cluster.
5838

5839
    """
5840
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5841
    assert self.instance is not None, \
5842
      "Cannot retrieve locked instance %s" % self.op.instance_name
5843

    
5844
    self.primary_offline = \
5845
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
5846

    
5847
    if self.primary_offline and self.op.ignore_offline_nodes:
5848
      self.proc.LogWarning("Ignoring offline primary node")
5849
    else:
5850
      _CheckNodeOnline(self, self.instance.primary_node)
5851

    
5852
  def Exec(self, feedback_fn):
5853
    """Shutdown the instance.
5854

5855
    """
5856
    instance = self.instance
5857
    node_current = instance.primary_node
5858
    timeout = self.op.timeout
5859

    
5860
    if not self.op.no_remember:
5861
      self.cfg.MarkInstanceDown(instance.name)
5862

    
5863
    if self.primary_offline:
5864
      assert self.op.ignore_offline_nodes
5865
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
5866
    else:
5867
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
5868
      msg = result.fail_msg
5869
      if msg:
5870
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
5871

    
5872
      _ShutdownInstanceDisks(self, instance)
5873

    
5874

    
5875
class LUInstanceReinstall(LogicalUnit):
5876
  """Reinstall an instance.
5877

5878
  """
5879
  HPATH = "instance-reinstall"
5880
  HTYPE = constants.HTYPE_INSTANCE
5881
  REQ_BGL = False
5882

    
5883
  def ExpandNames(self):
5884
    self._ExpandAndLockInstance()
5885

    
5886
  def BuildHooksEnv(self):
5887
    """Build hooks env.
5888

5889
    This runs on master, primary and secondary nodes of the instance.
5890

5891
    """
5892
    return _BuildInstanceHookEnvByObject(self, self.instance)
5893

    
5894
  def BuildHooksNodes(self):
5895
    """Build hooks nodes.
5896

5897
    """
5898
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5899
    return (nl, nl)
5900

    
5901
  def CheckPrereq(self):
5902
    """Check prerequisites.
5903

5904
    This checks that the instance is in the cluster and is not running.
5905

5906
    """
5907
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5908
    assert instance is not None, \
5909
      "Cannot retrieve locked instance %s" % self.op.instance_name
5910
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
5911
                     " offline, cannot reinstall")
5912
    for node in instance.secondary_nodes:
5913
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
5914
                       " cannot reinstall")
5915

    
5916
    if instance.disk_template == constants.DT_DISKLESS:
5917
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5918
                                 self.op.instance_name,
5919
                                 errors.ECODE_INVAL)
5920
    _CheckInstanceDown(self, instance, "cannot reinstall")
5921

    
5922
    if self.op.os_type is not None:
5923
      # OS verification
5924
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
5925
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
5926
      instance_os = self.op.os_type
5927
    else:
5928
      instance_os = instance.os
5929

    
5930
    nodelist = list(instance.all_nodes)
5931

    
5932
    if self.op.osparams:
5933
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
5934
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
5935
      self.os_inst = i_osdict # the new dict (without defaults)
5936
    else:
5937
      self.os_inst = None
5938

    
5939
    self.instance = instance
5940

    
5941
  def Exec(self, feedback_fn):
5942
    """Reinstall the instance.
5943

5944
    """
5945
    inst = self.instance
5946

    
5947
    if self.op.os_type is not None:
5948
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
5949
      inst.os = self.op.os_type
5950
      # Write to configuration
5951
      self.cfg.Update(inst, feedback_fn)
5952

    
5953
    _StartInstanceDisks(self, inst, None)
5954
    try:
5955
      feedback_fn("Running the instance OS create scripts...")
5956
      # FIXME: pass debug option from opcode to backend
5957
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
5958
                                             self.op.debug_level,
5959
                                             osparams=self.os_inst)
5960
      result.Raise("Could not install OS for instance %s on node %s" %
5961
                   (inst.name, inst.primary_node))
5962
    finally:
5963
      _ShutdownInstanceDisks(self, inst)
5964

    
5965

    
5966
class LUInstanceRecreateDisks(LogicalUnit):
5967
  """Recreate an instance's missing disks.
5968

5969
  """
5970
  HPATH = "instance-recreate-disks"
5971
  HTYPE = constants.HTYPE_INSTANCE
5972
  REQ_BGL = False
5973

    
5974
  def CheckArguments(self):
5975
    # normalise the disk list
5976
    self.op.disks = sorted(frozenset(self.op.disks))
5977

    
5978
  def ExpandNames(self):
5979
    self._ExpandAndLockInstance()
5980
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5981
    if self.op.nodes:
5982
      self.op.nodes = [_ExpandNodeName(self.cfg, n) for n in self.op.nodes]
5983
      self.needed_locks[locking.LEVEL_NODE] = list(self.op.nodes)
5984
    else:
5985
      self.needed_locks[locking.LEVEL_NODE] = []
5986

    
5987
  def DeclareLocks(self, level):
5988
    if level == locking.LEVEL_NODE:
5989
      # if we replace the nodes, we only need to lock the old primary,
5990
      # otherwise we need to lock all nodes for disk re-creation
5991
      primary_only = bool(self.op.nodes)
5992
      self._LockInstancesNodes(primary_only=primary_only)
5993

    
5994
  def BuildHooksEnv(self):
5995
    """Build hooks env.
5996

5997
    This runs on master, primary and secondary nodes of the instance.
5998

5999
    """
6000
    return _BuildInstanceHookEnvByObject(self, self.instance)
6001

    
6002
  def BuildHooksNodes(self):
6003
    """Build hooks nodes.
6004

6005
    """
6006
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6007
    return (nl, nl)
6008

    
6009
  def CheckPrereq(self):
6010
    """Check prerequisites.
6011

6012
    This checks that the instance is in the cluster and is not running.
6013

6014
    """
6015
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6016
    assert instance is not None, \
6017
      "Cannot retrieve locked instance %s" % self.op.instance_name
6018
    if self.op.nodes:
6019
      if len(self.op.nodes) != len(instance.all_nodes):
6020
        raise errors.OpPrereqError("Instance %s currently has %d nodes, but"
6021
                                   " %d replacement nodes were specified" %
6022
                                   (instance.name, len(instance.all_nodes),
6023
                                    len(self.op.nodes)),
6024
                                   errors.ECODE_INVAL)
6025
      assert instance.disk_template != constants.DT_DRBD8 or \
6026
          len(self.op.nodes) == 2
6027
      assert instance.disk_template != constants.DT_PLAIN or \
6028
          len(self.op.nodes) == 1
6029
      primary_node = self.op.nodes[0]
6030
    else:
6031
      primary_node = instance.primary_node
6032
    _CheckNodeOnline(self, primary_node)
6033

    
6034
    if instance.disk_template == constants.DT_DISKLESS:
6035
      raise errors.OpPrereqError("Instance '%s' has no disks" %
6036
                                 self.op.instance_name, errors.ECODE_INVAL)
6037
    # if we replace nodes *and* the old primary is offline, we don't
6038
    # check
6039
    assert instance.primary_node in self.needed_locks[locking.LEVEL_NODE]
6040
    old_pnode = self.cfg.GetNodeInfo(instance.primary_node)
6041
    if not (self.op.nodes and old_pnode.offline):
6042
      _CheckInstanceDown(self, instance, "cannot recreate disks")
6043

    
6044
    if not self.op.disks:
6045
      self.op.disks = range(len(instance.disks))
6046
    else:
6047
      for idx in self.op.disks:
6048
        if idx >= len(instance.disks):
6049
          raise errors.OpPrereqError("Invalid disk index '%s'" % idx,
6050
                                     errors.ECODE_INVAL)
6051
    if self.op.disks != range(len(instance.disks)) and self.op.nodes:
6052
      raise errors.OpPrereqError("Can't recreate disks partially and"
6053
                                 " change the nodes at the same time",
6054
                                 errors.ECODE_INVAL)
6055
    self.instance = instance
6056

    
6057
  def Exec(self, feedback_fn):
6058
    """Recreate the disks.
6059

6060
    """
6061
    instance = self.instance
6062

    
6063
    to_skip = []
6064
    mods = [] # keeps track of needed logical_id changes
6065

    
6066
    for idx, disk in enumerate(instance.disks):
6067
      if idx not in self.op.disks: # disk idx has not been passed in
6068
        to_skip.append(idx)
6069
        continue
6070
      # update secondaries for disks, if needed
6071
      if self.op.nodes:
6072
        if disk.dev_type == constants.LD_DRBD8:
6073
          # need to update the nodes and minors
6074
          assert len(self.op.nodes) == 2
6075
          assert len(disk.logical_id) == 6 # otherwise disk internals
6076
                                           # have changed
6077
          (_, _, old_port, _, _, old_secret) = disk.logical_id
6078
          new_minors = self.cfg.AllocateDRBDMinor(self.op.nodes, instance.name)
6079
          new_id = (self.op.nodes[0], self.op.nodes[1], old_port,
6080
                    new_minors[0], new_minors[1], old_secret)
6081
          assert len(disk.logical_id) == len(new_id)
6082
          mods.append((idx, new_id))
6083

    
6084
    # now that we have passed all asserts above, we can apply the mods
6085
    # in a single run (to avoid partial changes)
6086
    for idx, new_id in mods:
6087
      instance.disks[idx].logical_id = new_id
6088

    
6089
    # change primary node, if needed
6090
    if self.op.nodes:
6091
      instance.primary_node = self.op.nodes[0]
6092
      self.LogWarning("Changing the instance's nodes, you will have to"
6093
                      " remove any disks left on the older nodes manually")
6094

    
6095
    if self.op.nodes:
6096
      self.cfg.Update(instance, feedback_fn)
6097

    
6098
    _CreateDisks(self, instance, to_skip=to_skip)
6099

    
6100

    
6101
class LUInstanceRename(LogicalUnit):
6102
  """Rename an instance.
6103

6104
  """
6105
  HPATH = "instance-rename"
6106
  HTYPE = constants.HTYPE_INSTANCE
6107

    
6108
  def CheckArguments(self):
6109
    """Check arguments.
6110

6111
    """
6112
    if self.op.ip_check and not self.op.name_check:
6113
      # TODO: make the ip check more flexible and not depend on the name check
6114
      raise errors.OpPrereqError("IP address check requires a name check",
6115
                                 errors.ECODE_INVAL)
6116

    
6117
  def BuildHooksEnv(self):
6118
    """Build hooks env.
6119

6120
    This runs on master, primary and secondary nodes of the instance.
6121

6122
    """
6123
    env = _BuildInstanceHookEnvByObject(self, self.instance)
6124
    env["INSTANCE_NEW_NAME"] = self.op.new_name
6125
    return env
6126

    
6127
  def BuildHooksNodes(self):
6128
    """Build hooks nodes.
6129

6130
    """
6131
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6132
    return (nl, nl)
6133

    
6134
  def CheckPrereq(self):
6135
    """Check prerequisites.
6136

6137
    This checks that the instance is in the cluster and is not running.
6138

6139
    """
6140
    self.op.instance_name = _ExpandInstanceName(self.cfg,
6141
                                                self.op.instance_name)
6142
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6143
    assert instance is not None
6144
    _CheckNodeOnline(self, instance.primary_node)
6145
    _CheckInstanceDown(self, instance, "cannot rename")
6146
    self.instance = instance
6147

    
6148
    new_name = self.op.new_name
6149
    if self.op.name_check:
6150
      hostname = netutils.GetHostname(name=new_name)
6151
      if hostname != new_name:
6152
        self.LogInfo("Resolved given name '%s' to '%s'", new_name,
6153
                     hostname.name)
6154
      if not utils.MatchNameComponent(self.op.new_name, [hostname.name]):
6155
        raise errors.OpPrereqError(("Resolved hostname '%s' does not look the"
6156
                                    " same as given hostname '%s'") %
6157
                                    (hostname.name, self.op.new_name),
6158
                                    errors.ECODE_INVAL)
6159
      new_name = self.op.new_name = hostname.name
6160
      if (self.op.ip_check and
6161
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
6162
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
6163
                                   (hostname.ip, new_name),
6164
                                   errors.ECODE_NOTUNIQUE)
6165

    
6166
    instance_list = self.cfg.GetInstanceList()
6167
    if new_name in instance_list and new_name != instance.name:
6168
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6169
                                 new_name, errors.ECODE_EXISTS)
6170

    
6171
  def Exec(self, feedback_fn):
6172
    """Rename the instance.
6173

6174
    """
6175
    inst = self.instance
6176
    old_name = inst.name
6177

    
6178
    rename_file_storage = False
6179
    if (inst.disk_template in constants.DTS_FILEBASED and
6180
        self.op.new_name != inst.name):
6181
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
6182
      rename_file_storage = True
6183

    
6184
    self.cfg.RenameInstance(inst.name, self.op.new_name)
6185
    # Change the instance lock. This is definitely safe while we hold the BGL.
6186
    # Otherwise the new lock would have to be added in acquired mode.
6187
    assert self.REQ_BGL
6188
    self.glm.remove(locking.LEVEL_INSTANCE, old_name)
6189
    self.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
6190

    
6191
    # re-read the instance from the configuration after rename
6192
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
6193

    
6194
    if rename_file_storage:
6195
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
6196
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
6197
                                                     old_file_storage_dir,
6198
                                                     new_file_storage_dir)
6199
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
6200
                   " (but the instance has been renamed in Ganeti)" %
6201
                   (inst.primary_node, old_file_storage_dir,
6202
                    new_file_storage_dir))
6203

    
6204
    _StartInstanceDisks(self, inst, None)
6205
    try:
6206
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
6207
                                                 old_name, self.op.debug_level)
6208
      msg = result.fail_msg
6209
      if msg:
6210
        msg = ("Could not run OS rename script for instance %s on node %s"
6211
               " (but the instance has been renamed in Ganeti): %s" %
6212
               (inst.name, inst.primary_node, msg))
6213
        self.proc.LogWarning(msg)
6214
    finally:
6215
      _ShutdownInstanceDisks(self, inst)
6216

    
6217
    return inst.name
6218

    
6219

    
6220
class LUInstanceRemove(LogicalUnit):
6221
  """Remove an instance.
6222

6223
  """
6224
  HPATH = "instance-remove"
6225
  HTYPE = constants.HTYPE_INSTANCE
6226
  REQ_BGL = False
6227

    
6228
  def ExpandNames(self):
6229
    self._ExpandAndLockInstance()
6230
    self.needed_locks[locking.LEVEL_NODE] = []
6231
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6232

    
6233
  def DeclareLocks(self, level):
6234
    if level == locking.LEVEL_NODE:
6235
      self._LockInstancesNodes()
6236

    
6237
  def BuildHooksEnv(self):
6238
    """Build hooks env.
6239

6240
    This runs on master, primary and secondary nodes of the instance.
6241

6242
    """
6243
    env = _BuildInstanceHookEnvByObject(self, self.instance)
6244
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
6245
    return env
6246

    
6247
  def BuildHooksNodes(self):
6248
    """Build hooks nodes.
6249

6250
    """
6251
    nl = [self.cfg.GetMasterNode()]
6252
    nl_post = list(self.instance.all_nodes) + nl
6253
    return (nl, nl_post)
6254

    
6255
  def CheckPrereq(self):
6256
    """Check prerequisites.
6257

6258
    This checks that the instance is in the cluster.
6259

6260
    """
6261
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6262
    assert self.instance is not None, \
6263
      "Cannot retrieve locked instance %s" % self.op.instance_name
6264

    
6265
  def Exec(self, feedback_fn):
6266
    """Remove the instance.
6267

6268
    """
6269
    instance = self.instance
6270
    logging.info("Shutting down instance %s on node %s",
6271
                 instance.name, instance.primary_node)
6272

    
6273
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
6274
                                             self.op.shutdown_timeout)
6275
    msg = result.fail_msg
6276
    if msg:
6277
      if self.op.ignore_failures:
6278
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
6279
      else:
6280
        raise errors.OpExecError("Could not shutdown instance %s on"
6281
                                 " node %s: %s" %
6282
                                 (instance.name, instance.primary_node, msg))
6283

    
6284
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
6285

    
6286

    
6287
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
6288
  """Utility function to remove an instance.
6289

6290
  """
6291
  logging.info("Removing block devices for instance %s", instance.name)
6292

    
6293
  if not _RemoveDisks(lu, instance):
6294
    if not ignore_failures:
6295
      raise errors.OpExecError("Can't remove instance's disks")
6296
    feedback_fn("Warning: can't remove instance's disks")
6297

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

    
6300
  lu.cfg.RemoveInstance(instance.name)
6301

    
6302
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
6303
    "Instance lock removal conflict"
6304

    
6305
  # Remove lock for the instance
6306
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
6307

    
6308

    
6309
class LUInstanceQuery(NoHooksLU):
6310
  """Logical unit for querying instances.
6311

6312
  """
6313
  # pylint: disable-msg=W0142
6314
  REQ_BGL = False
6315

    
6316
  def CheckArguments(self):
6317
    self.iq = _InstanceQuery(qlang.MakeSimpleFilter("name", self.op.names),
6318
                             self.op.output_fields, self.op.use_locking)
6319

    
6320
  def ExpandNames(self):
6321
    self.iq.ExpandNames(self)
6322

    
6323
  def DeclareLocks(self, level):
6324
    self.iq.DeclareLocks(self, level)
6325

    
6326
  def Exec(self, feedback_fn):
6327
    return self.iq.OldStyleQuery(self)
6328

    
6329

    
6330
class LUInstanceFailover(LogicalUnit):
6331
  """Failover an instance.
6332

6333
  """
6334
  HPATH = "instance-failover"
6335
  HTYPE = constants.HTYPE_INSTANCE
6336
  REQ_BGL = False
6337

    
6338
  def CheckArguments(self):
6339
    """Check the arguments.
6340

6341
    """
6342
    self.iallocator = getattr(self.op, "iallocator", None)
6343
    self.target_node = getattr(self.op, "target_node", None)
6344

    
6345
  def ExpandNames(self):
6346
    self._ExpandAndLockInstance()
6347

    
6348
    if self.op.target_node is not None:
6349
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6350

    
6351
    self.needed_locks[locking.LEVEL_NODE] = []
6352
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6353

    
6354
    ignore_consistency = self.op.ignore_consistency
6355
    shutdown_timeout = self.op.shutdown_timeout
6356
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
6357
                                       cleanup=False,
6358
                                       failover=True,
6359
                                       ignore_consistency=ignore_consistency,
6360
                                       shutdown_timeout=shutdown_timeout)
6361
    self.tasklets = [self._migrater]
6362

    
6363
  def DeclareLocks(self, level):
6364
    if level == locking.LEVEL_NODE:
6365
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6366
      if instance.disk_template in constants.DTS_EXT_MIRROR:
6367
        if self.op.target_node is None:
6368
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6369
        else:
6370
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6371
                                                   self.op.target_node]
6372
        del self.recalculate_locks[locking.LEVEL_NODE]
6373
      else:
6374
        self._LockInstancesNodes()
6375

    
6376
  def BuildHooksEnv(self):
6377
    """Build hooks env.
6378

6379
    This runs on master, primary and secondary nodes of the instance.
6380

6381
    """
6382
    instance = self._migrater.instance
6383
    source_node = instance.primary_node
6384
    target_node = self.op.target_node
6385
    env = {
6386
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
6387
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6388
      "OLD_PRIMARY": source_node,
6389
      "NEW_PRIMARY": target_node,
6390
      }
6391

    
6392
    if instance.disk_template in constants.DTS_INT_MIRROR:
6393
      env["OLD_SECONDARY"] = instance.secondary_nodes[0]
6394
      env["NEW_SECONDARY"] = source_node
6395
    else:
6396
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = ""
6397

    
6398
    env.update(_BuildInstanceHookEnvByObject(self, instance))
6399

    
6400
    return env
6401

    
6402
  def BuildHooksNodes(self):
6403
    """Build hooks nodes.
6404

6405
    """
6406
    instance = self._migrater.instance
6407
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6408
    return (nl, nl + [instance.primary_node])
6409

    
6410

    
6411
class LUInstanceMigrate(LogicalUnit):
6412
  """Migrate an instance.
6413

6414
  This is migration without shutting down, compared to the failover,
6415
  which is done with shutdown.
6416

6417
  """
6418
  HPATH = "instance-migrate"
6419
  HTYPE = constants.HTYPE_INSTANCE
6420
  REQ_BGL = False
6421

    
6422
  def ExpandNames(self):
6423
    self._ExpandAndLockInstance()
6424

    
6425
    if self.op.target_node is not None:
6426
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6427

    
6428
    self.needed_locks[locking.LEVEL_NODE] = []
6429
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6430

    
6431
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
6432
                                       cleanup=self.op.cleanup,
6433
                                       failover=False,
6434
                                       fallback=self.op.allow_failover)
6435
    self.tasklets = [self._migrater]
6436

    
6437
  def DeclareLocks(self, level):
6438
    if level == locking.LEVEL_NODE:
6439
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6440
      if instance.disk_template in constants.DTS_EXT_MIRROR:
6441
        if self.op.target_node is None:
6442
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6443
        else:
6444
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6445
                                                   self.op.target_node]
6446
        del self.recalculate_locks[locking.LEVEL_NODE]
6447
      else:
6448
        self._LockInstancesNodes()
6449

    
6450
  def BuildHooksEnv(self):
6451
    """Build hooks env.
6452

6453
    This runs on master, primary and secondary nodes of the instance.
6454

6455
    """
6456
    instance = self._migrater.instance
6457
    source_node = instance.primary_node
6458
    target_node = self.op.target_node
6459
    env = _BuildInstanceHookEnvByObject(self, instance)
6460
    env.update({
6461
      "MIGRATE_LIVE": self._migrater.live,
6462
      "MIGRATE_CLEANUP": self.op.cleanup,
6463
      "OLD_PRIMARY": source_node,
6464
      "NEW_PRIMARY": target_node,
6465
      })
6466

    
6467
    if instance.disk_template in constants.DTS_INT_MIRROR:
6468
      env["OLD_SECONDARY"] = target_node
6469
      env["NEW_SECONDARY"] = source_node
6470
    else:
6471
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = None
6472

    
6473
    return env
6474

    
6475
  def BuildHooksNodes(self):
6476
    """Build hooks nodes.
6477

6478
    """
6479
    instance = self._migrater.instance
6480
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6481
    return (nl, nl + [instance.primary_node])
6482

    
6483

    
6484
class LUInstanceMove(LogicalUnit):
6485
  """Move an instance by data-copying.
6486

6487
  """
6488
  HPATH = "instance-move"
6489
  HTYPE = constants.HTYPE_INSTANCE
6490
  REQ_BGL = False
6491

    
6492
  def ExpandNames(self):
6493
    self._ExpandAndLockInstance()
6494
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6495
    self.op.target_node = target_node
6496
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
6497
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6498

    
6499
  def DeclareLocks(self, level):
6500
    if level == locking.LEVEL_NODE:
6501
      self._LockInstancesNodes(primary_only=True)
6502

    
6503
  def BuildHooksEnv(self):
6504
    """Build hooks env.
6505

6506
    This runs on master, primary and secondary nodes of the instance.
6507

6508
    """
6509
    env = {
6510
      "TARGET_NODE": self.op.target_node,
6511
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6512
      }
6513
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6514
    return env
6515

    
6516
  def BuildHooksNodes(self):
6517
    """Build hooks nodes.
6518

6519
    """
6520
    nl = [
6521
      self.cfg.GetMasterNode(),
6522
      self.instance.primary_node,
6523
      self.op.target_node,
6524
      ]
6525
    return (nl, nl)
6526

    
6527
  def CheckPrereq(self):
6528
    """Check prerequisites.
6529

6530
    This checks that the instance is in the cluster.
6531

6532
    """
6533
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6534
    assert self.instance is not None, \
6535
      "Cannot retrieve locked instance %s" % self.op.instance_name
6536

    
6537
    node = self.cfg.GetNodeInfo(self.op.target_node)
6538
    assert node is not None, \
6539
      "Cannot retrieve locked node %s" % self.op.target_node
6540

    
6541
    self.target_node = target_node = node.name
6542

    
6543
    if target_node == instance.primary_node:
6544
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
6545
                                 (instance.name, target_node),
6546
                                 errors.ECODE_STATE)
6547

    
6548
    bep = self.cfg.GetClusterInfo().FillBE(instance)
6549

    
6550
    for idx, dsk in enumerate(instance.disks):
6551
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
6552
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
6553
                                   " cannot copy" % idx, errors.ECODE_STATE)
6554

    
6555
    _CheckNodeOnline(self, target_node)
6556
    _CheckNodeNotDrained(self, target_node)
6557
    _CheckNodeVmCapable(self, target_node)
6558

    
6559
    if instance.admin_up:
6560
      # check memory requirements on the secondary node
6561
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
6562
                           instance.name, bep[constants.BE_MEMORY],
6563
                           instance.hypervisor)
6564
    else:
6565
      self.LogInfo("Not checking memory on the secondary node as"
6566
                   " instance will not be started")
6567

    
6568
    # check bridge existance
6569
    _CheckInstanceBridgesExist(self, instance, node=target_node)
6570

    
6571
  def Exec(self, feedback_fn):
6572
    """Move an instance.
6573

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

6577
    """
6578
    instance = self.instance
6579

    
6580
    source_node = instance.primary_node
6581
    target_node = self.target_node
6582

    
6583
    self.LogInfo("Shutting down instance %s on source node %s",
6584
                 instance.name, source_node)
6585

    
6586
    result = self.rpc.call_instance_shutdown(source_node, instance,
6587
                                             self.op.shutdown_timeout)
6588
    msg = result.fail_msg
6589
    if msg:
6590
      if self.op.ignore_consistency:
6591
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
6592
                             " Proceeding anyway. Please make sure node"
6593
                             " %s is down. Error details: %s",
6594
                             instance.name, source_node, source_node, msg)
6595
      else:
6596
        raise errors.OpExecError("Could not shutdown instance %s on"
6597
                                 " node %s: %s" %
6598
                                 (instance.name, source_node, msg))
6599

    
6600
    # create the target disks
6601
    try:
6602
      _CreateDisks(self, instance, target_node=target_node)
6603
    except errors.OpExecError:
6604
      self.LogWarning("Device creation failed, reverting...")
6605
      try:
6606
        _RemoveDisks(self, instance, target_node=target_node)
6607
      finally:
6608
        self.cfg.ReleaseDRBDMinors(instance.name)
6609
        raise
6610

    
6611
    cluster_name = self.cfg.GetClusterInfo().cluster_name
6612

    
6613
    errs = []
6614
    # activate, get path, copy the data over
6615
    for idx, disk in enumerate(instance.disks):
6616
      self.LogInfo("Copying data for disk %d", idx)
6617
      result = self.rpc.call_blockdev_assemble(target_node, disk,
6618
                                               instance.name, True, idx)
6619
      if result.fail_msg:
6620
        self.LogWarning("Can't assemble newly created disk %d: %s",
6621
                        idx, result.fail_msg)
6622
        errs.append(result.fail_msg)
6623
        break
6624
      dev_path = result.payload
6625
      result = self.rpc.call_blockdev_export(source_node, disk,
6626
                                             target_node, dev_path,
6627
                                             cluster_name)
6628
      if result.fail_msg:
6629
        self.LogWarning("Can't copy data over for disk %d: %s",
6630
                        idx, result.fail_msg)
6631
        errs.append(result.fail_msg)
6632
        break
6633

    
6634
    if errs:
6635
      self.LogWarning("Some disks failed to copy, aborting")
6636
      try:
6637
        _RemoveDisks(self, instance, target_node=target_node)
6638
      finally:
6639
        self.cfg.ReleaseDRBDMinors(instance.name)
6640
        raise errors.OpExecError("Errors during disk copy: %s" %
6641
                                 (",".join(errs),))
6642

    
6643
    instance.primary_node = target_node
6644
    self.cfg.Update(instance, feedback_fn)
6645

    
6646
    self.LogInfo("Removing the disks on the original node")
6647
    _RemoveDisks(self, instance, target_node=source_node)
6648

    
6649
    # Only start the instance if it's marked as up
6650
    if instance.admin_up:
6651
      self.LogInfo("Starting instance %s on node %s",
6652
                   instance.name, target_node)
6653

    
6654
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
6655
                                           ignore_secondaries=True)
6656
      if not disks_ok:
6657
        _ShutdownInstanceDisks(self, instance)
6658
        raise errors.OpExecError("Can't activate the instance's disks")
6659

    
6660
      result = self.rpc.call_instance_start(target_node, instance,
6661
                                            None, None, False)
6662
      msg = result.fail_msg
6663
      if msg:
6664
        _ShutdownInstanceDisks(self, instance)
6665
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
6666
                                 (instance.name, target_node, msg))
6667

    
6668

    
6669
class LUNodeMigrate(LogicalUnit):
6670
  """Migrate all instances from a node.
6671

6672
  """
6673
  HPATH = "node-migrate"
6674
  HTYPE = constants.HTYPE_NODE
6675
  REQ_BGL = False
6676

    
6677
  def CheckArguments(self):
6678
    pass
6679

    
6680
  def ExpandNames(self):
6681
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6682

    
6683
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
6684
    self.needed_locks = {
6685
      locking.LEVEL_NODE: [self.op.node_name],
6686
      }
6687

    
6688
  def BuildHooksEnv(self):
6689
    """Build hooks env.
6690

6691
    This runs on the master, the primary and all the secondaries.
6692

6693
    """
6694
    return {
6695
      "NODE_NAME": self.op.node_name,
6696
      }
6697

    
6698
  def BuildHooksNodes(self):
6699
    """Build hooks nodes.
6700

6701
    """
6702
    nl = [self.cfg.GetMasterNode()]
6703
    return (nl, nl)
6704

    
6705
  def CheckPrereq(self):
6706
    pass
6707

    
6708
  def Exec(self, feedback_fn):
6709
    # Prepare jobs for migration instances
6710
    jobs = [
6711
      [opcodes.OpInstanceMigrate(instance_name=inst.name,
6712
                                 mode=self.op.mode,
6713
                                 live=self.op.live,
6714
                                 iallocator=self.op.iallocator,
6715
                                 target_node=self.op.target_node)]
6716
      for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name)
6717
      ]
6718

    
6719
    # TODO: Run iallocator in this opcode and pass correct placement options to
6720
    # OpInstanceMigrate. Since other jobs can modify the cluster between
6721
    # running the iallocator and the actual migration, a good consistency model
6722
    # will have to be found.
6723

    
6724
    assert (frozenset(self.glm.list_owned(locking.LEVEL_NODE)) ==
6725
            frozenset([self.op.node_name]))
6726

    
6727
    return ResultWithJobs(jobs)
6728

    
6729

    
6730
class TLMigrateInstance(Tasklet):
6731
  """Tasklet class for instance migration.
6732

6733
  @type live: boolean
6734
  @ivar live: whether the migration will be done live or non-live;
6735
      this variable is initalized only after CheckPrereq has run
6736
  @type cleanup: boolean
6737
  @ivar cleanup: Wheater we cleanup from a failed migration
6738
  @type iallocator: string
6739
  @ivar iallocator: The iallocator used to determine target_node
6740
  @type target_node: string
6741
  @ivar target_node: If given, the target_node to reallocate the instance to
6742
  @type failover: boolean
6743
  @ivar failover: Whether operation results in failover or migration
6744
  @type fallback: boolean
6745
  @ivar fallback: Whether fallback to failover is allowed if migration not
6746
                  possible
6747
  @type ignore_consistency: boolean
6748
  @ivar ignore_consistency: Wheter we should ignore consistency between source
6749
                            and target node
6750
  @type shutdown_timeout: int
6751
  @ivar shutdown_timeout: In case of failover timeout of the shutdown
6752

6753
  """
6754
  def __init__(self, lu, instance_name, cleanup=False,
6755
               failover=False, fallback=False,
6756
               ignore_consistency=False,
6757
               shutdown_timeout=constants.DEFAULT_SHUTDOWN_TIMEOUT):
6758
    """Initializes this class.
6759

6760
    """
6761
    Tasklet.__init__(self, lu)
6762

    
6763
    # Parameters
6764
    self.instance_name = instance_name
6765
    self.cleanup = cleanup
6766
    self.live = False # will be overridden later
6767
    self.failover = failover
6768
    self.fallback = fallback
6769
    self.ignore_consistency = ignore_consistency
6770
    self.shutdown_timeout = shutdown_timeout
6771

    
6772
  def CheckPrereq(self):
6773
    """Check prerequisites.
6774

6775
    This checks that the instance is in the cluster.
6776

6777
    """
6778
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
6779
    instance = self.cfg.GetInstanceInfo(instance_name)
6780
    assert instance is not None
6781
    self.instance = instance
6782

    
6783
    if (not self.cleanup and not instance.admin_up and not self.failover and
6784
        self.fallback):
6785
      self.lu.LogInfo("Instance is marked down, fallback allowed, switching"
6786
                      " to failover")
6787
      self.failover = True
6788

    
6789
    if instance.disk_template not in constants.DTS_MIRRORED:
6790
      if self.failover:
6791
        text = "failovers"
6792
      else:
6793
        text = "migrations"
6794
      raise errors.OpPrereqError("Instance's disk layout '%s' does not allow"
6795
                                 " %s" % (instance.disk_template, text),
6796
                                 errors.ECODE_STATE)
6797

    
6798
    if instance.disk_template in constants.DTS_EXT_MIRROR:
6799
      _CheckIAllocatorOrNode(self.lu, "iallocator", "target_node")
6800

    
6801
      if self.lu.op.iallocator:
6802
        self._RunAllocator()
6803
      else:
6804
        # We set set self.target_node as it is required by
6805
        # BuildHooksEnv
6806
        self.target_node = self.lu.op.target_node
6807

    
6808
      # self.target_node is already populated, either directly or by the
6809
      # iallocator run
6810
      target_node = self.target_node
6811
      if self.target_node == instance.primary_node:
6812
        raise errors.OpPrereqError("Cannot migrate instance %s"
6813
                                   " to its primary (%s)" %
6814
                                   (instance.name, instance.primary_node))
6815

    
6816
      if len(self.lu.tasklets) == 1:
6817
        # It is safe to release locks only when we're the only tasklet
6818
        # in the LU
6819
        _ReleaseLocks(self.lu, locking.LEVEL_NODE,
6820
                      keep=[instance.primary_node, self.target_node])
6821

    
6822
    else:
6823
      secondary_nodes = instance.secondary_nodes
6824
      if not secondary_nodes:
6825
        raise errors.ConfigurationError("No secondary node but using"
6826
                                        " %s disk template" %
6827
                                        instance.disk_template)
6828
      target_node = secondary_nodes[0]
6829
      if self.lu.op.iallocator or (self.lu.op.target_node and
6830
                                   self.lu.op.target_node != target_node):
6831
        if self.failover:
6832
          text = "failed over"
6833
        else:
6834
          text = "migrated"
6835
        raise errors.OpPrereqError("Instances with disk template %s cannot"
6836
                                   " be %s to arbitrary nodes"
6837
                                   " (neither an iallocator nor a target"
6838
                                   " node can be passed)" %
6839
                                   (instance.disk_template, text),
6840
                                   errors.ECODE_INVAL)
6841

    
6842
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
6843

    
6844
    # check memory requirements on the secondary node
6845
    if not self.failover or instance.admin_up:
6846
      _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
6847
                           instance.name, i_be[constants.BE_MEMORY],
6848
                           instance.hypervisor)
6849
    else:
6850
      self.lu.LogInfo("Not checking memory on the secondary node as"
6851
                      " instance will not be started")
6852

    
6853
    # check bridge existance
6854
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
6855

    
6856
    if not self.cleanup:
6857
      _CheckNodeNotDrained(self.lu, target_node)
6858
      if not self.failover:
6859
        result = self.rpc.call_instance_migratable(instance.primary_node,
6860
                                                   instance)
6861
        if result.fail_msg and self.fallback:
6862
          self.lu.LogInfo("Can't migrate, instance offline, fallback to"
6863
                          " failover")
6864
          self.failover = True
6865
        else:
6866
          result.Raise("Can't migrate, please use failover",
6867
                       prereq=True, ecode=errors.ECODE_STATE)
6868

    
6869
    assert not (self.failover and self.cleanup)
6870

    
6871
    if not self.failover:
6872
      if self.lu.op.live is not None and self.lu.op.mode is not None:
6873
        raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
6874
                                   " parameters are accepted",
6875
                                   errors.ECODE_INVAL)
6876
      if self.lu.op.live is not None:
6877
        if self.lu.op.live:
6878
          self.lu.op.mode = constants.HT_MIGRATION_LIVE
6879
        else:
6880
          self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6881
        # reset the 'live' parameter to None so that repeated
6882
        # invocations of CheckPrereq do not raise an exception
6883
        self.lu.op.live = None
6884
      elif self.lu.op.mode is None:
6885
        # read the default value from the hypervisor
6886
        i_hv = self.cfg.GetClusterInfo().FillHV(self.instance,
6887
                                                skip_globals=False)
6888
        self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6889

    
6890
      self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6891
    else:
6892
      # Failover is never live
6893
      self.live = False
6894

    
6895
  def _RunAllocator(self):
6896
    """Run the allocator based on input opcode.
6897

6898
    """
6899
    ial = IAllocator(self.cfg, self.rpc,
6900
                     mode=constants.IALLOCATOR_MODE_RELOC,
6901
                     name=self.instance_name,
6902
                     # TODO See why hail breaks with a single node below
6903
                     relocate_from=[self.instance.primary_node,
6904
                                    self.instance.primary_node],
6905
                     )
6906

    
6907
    ial.Run(self.lu.op.iallocator)
6908

    
6909
    if not ial.success:
6910
      raise errors.OpPrereqError("Can't compute nodes using"
6911
                                 " iallocator '%s': %s" %
6912
                                 (self.lu.op.iallocator, ial.info),
6913
                                 errors.ECODE_NORES)
6914
    if len(ial.result) != ial.required_nodes:
6915
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6916
                                 " of nodes (%s), required %s" %
6917
                                 (self.lu.op.iallocator, len(ial.result),
6918
                                  ial.required_nodes), errors.ECODE_FAULT)
6919
    self.target_node = ial.result[0]
6920
    self.lu.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6921
                 self.instance_name, self.lu.op.iallocator,
6922
                 utils.CommaJoin(ial.result))
6923

    
6924
  def _WaitUntilSync(self):
6925
    """Poll with custom rpc for disk sync.
6926

6927
    This uses our own step-based rpc call.
6928

6929
    """
6930
    self.feedback_fn("* wait until resync is done")
6931
    all_done = False
6932
    while not all_done:
6933
      all_done = True
6934
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6935
                                            self.nodes_ip,
6936
                                            self.instance.disks)
6937
      min_percent = 100
6938
      for node, nres in result.items():
6939
        nres.Raise("Cannot resync disks on node %s" % node)
6940
        node_done, node_percent = nres.payload
6941
        all_done = all_done and node_done
6942
        if node_percent is not None:
6943
          min_percent = min(min_percent, node_percent)
6944
      if not all_done:
6945
        if min_percent < 100:
6946
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6947
        time.sleep(2)
6948

    
6949
  def _EnsureSecondary(self, node):
6950
    """Demote a node to secondary.
6951

6952
    """
6953
    self.feedback_fn("* switching node %s to secondary mode" % node)
6954

    
6955
    for dev in self.instance.disks:
6956
      self.cfg.SetDiskID(dev, node)
6957

    
6958
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6959
                                          self.instance.disks)
6960
    result.Raise("Cannot change disk to secondary on node %s" % node)
6961

    
6962
  def _GoStandalone(self):
6963
    """Disconnect from the network.
6964

6965
    """
6966
    self.feedback_fn("* changing into standalone mode")
6967
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6968
                                               self.instance.disks)
6969
    for node, nres in result.items():
6970
      nres.Raise("Cannot disconnect disks node %s" % node)
6971

    
6972
  def _GoReconnect(self, multimaster):
6973
    """Reconnect to the network.
6974

6975
    """
6976
    if multimaster:
6977
      msg = "dual-master"
6978
    else:
6979
      msg = "single-master"
6980
    self.feedback_fn("* changing disks into %s mode" % msg)
6981
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6982
                                           self.instance.disks,
6983
                                           self.instance.name, multimaster)
6984
    for node, nres in result.items():
6985
      nres.Raise("Cannot change disks config on node %s" % node)
6986

    
6987
  def _ExecCleanup(self):
6988
    """Try to cleanup after a failed migration.
6989

6990
    The cleanup is done by:
6991
      - check that the instance is running only on one node
6992
        (and update the config if needed)
6993
      - change disks on its secondary node to secondary
6994
      - wait until disks are fully synchronized
6995
      - disconnect from the network
6996
      - change disks into single-master mode
6997
      - wait again until disks are fully synchronized
6998

6999
    """
7000
    instance = self.instance
7001
    target_node = self.target_node
7002
    source_node = self.source_node
7003

    
7004
    # check running on only one node
7005
    self.feedback_fn("* checking where the instance actually runs"
7006
                     " (if this hangs, the hypervisor might be in"
7007
                     " a bad state)")
7008
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
7009
    for node, result in ins_l.items():
7010
      result.Raise("Can't contact node %s" % node)
7011

    
7012
    runningon_source = instance.name in ins_l[source_node].payload
7013
    runningon_target = instance.name in ins_l[target_node].payload
7014

    
7015
    if runningon_source and runningon_target:
7016
      raise errors.OpExecError("Instance seems to be running on two nodes,"
7017
                               " or the hypervisor is confused; you will have"
7018
                               " to ensure manually that it runs only on one"
7019
                               " and restart this operation")
7020

    
7021
    if not (runningon_source or runningon_target):
7022
      raise errors.OpExecError("Instance does not seem to be running at all;"
7023
                               " in this case it's safer to repair by"
7024
                               " running 'gnt-instance stop' to ensure disk"
7025
                               " shutdown, and then restarting it")
7026

    
7027
    if runningon_target:
7028
      # the migration has actually succeeded, we need to update the config
7029
      self.feedback_fn("* instance running on secondary node (%s),"
7030
                       " updating config" % target_node)
7031
      instance.primary_node = target_node
7032
      self.cfg.Update(instance, self.feedback_fn)
7033
      demoted_node = source_node
7034
    else:
7035
      self.feedback_fn("* instance confirmed to be running on its"
7036
                       " primary node (%s)" % source_node)
7037
      demoted_node = target_node
7038

    
7039
    if instance.disk_template in constants.DTS_INT_MIRROR:
7040
      self._EnsureSecondary(demoted_node)
7041
      try:
7042
        self._WaitUntilSync()
7043
      except errors.OpExecError:
7044
        # we ignore here errors, since if the device is standalone, it
7045
        # won't be able to sync
7046
        pass
7047
      self._GoStandalone()
7048
      self._GoReconnect(False)
7049
      self._WaitUntilSync()
7050

    
7051
    self.feedback_fn("* done")
7052

    
7053
  def _RevertDiskStatus(self):
7054
    """Try to revert the disk status after a failed migration.
7055

7056
    """
7057
    target_node = self.target_node
7058
    if self.instance.disk_template in constants.DTS_EXT_MIRROR:
7059
      return
7060

    
7061
    try:
7062
      self._EnsureSecondary(target_node)
7063
      self._GoStandalone()
7064
      self._GoReconnect(False)
7065
      self._WaitUntilSync()
7066
    except errors.OpExecError, err:
7067
      self.lu.LogWarning("Migration failed and I can't reconnect the drives,"
7068
                         " please try to recover the instance manually;"
7069
                         " error '%s'" % str(err))
7070

    
7071
  def _AbortMigration(self):
7072
    """Call the hypervisor code to abort a started migration.
7073

7074
    """
7075
    instance = self.instance
7076
    target_node = self.target_node
7077
    migration_info = self.migration_info
7078

    
7079
    abort_result = self.rpc.call_finalize_migration(target_node,
7080
                                                    instance,
7081
                                                    migration_info,
7082
                                                    False)
7083
    abort_msg = abort_result.fail_msg
7084
    if abort_msg:
7085
      logging.error("Aborting migration failed on target node %s: %s",
7086
                    target_node, abort_msg)
7087
      # Don't raise an exception here, as we stil have to try to revert the
7088
      # disk status, even if this step failed.
7089

    
7090
  def _ExecMigration(self):
7091
    """Migrate an instance.
7092

7093
    The migrate is done by:
7094
      - change the disks into dual-master mode
7095
      - wait until disks are fully synchronized again
7096
      - migrate the instance
7097
      - change disks on the new secondary node (the old primary) to secondary
7098
      - wait until disks are fully synchronized
7099
      - change disks into single-master mode
7100

7101
    """
7102
    instance = self.instance
7103
    target_node = self.target_node
7104
    source_node = self.source_node
7105

    
7106
    self.feedback_fn("* checking disk consistency between source and target")
7107
    for dev in instance.disks:
7108
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
7109
        raise errors.OpExecError("Disk %s is degraded or not fully"
7110
                                 " synchronized on target node,"
7111
                                 " aborting migration" % dev.iv_name)
7112

    
7113
    # First get the migration information from the remote node
7114
    result = self.rpc.call_migration_info(source_node, instance)
7115
    msg = result.fail_msg
7116
    if msg:
7117
      log_err = ("Failed fetching source migration information from %s: %s" %
7118
                 (source_node, msg))
7119
      logging.error(log_err)
7120
      raise errors.OpExecError(log_err)
7121

    
7122
    self.migration_info = migration_info = result.payload
7123

    
7124
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
7125
      # Then switch the disks to master/master mode
7126
      self._EnsureSecondary(target_node)
7127
      self._GoStandalone()
7128
      self._GoReconnect(True)
7129
      self._WaitUntilSync()
7130

    
7131
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
7132
    result = self.rpc.call_accept_instance(target_node,
7133
                                           instance,
7134
                                           migration_info,
7135
                                           self.nodes_ip[target_node])
7136

    
7137
    msg = result.fail_msg
7138
    if msg:
7139
      logging.error("Instance pre-migration failed, trying to revert"
7140
                    " disk status: %s", msg)
7141
      self.feedback_fn("Pre-migration failed, aborting")
7142
      self._AbortMigration()
7143
      self._RevertDiskStatus()
7144
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
7145
                               (instance.name, msg))
7146

    
7147
    self.feedback_fn("* migrating instance to %s" % target_node)
7148
    result = self.rpc.call_instance_migrate(source_node, instance,
7149
                                            self.nodes_ip[target_node],
7150
                                            self.live)
7151
    msg = result.fail_msg
7152
    if msg:
7153
      logging.error("Instance migration failed, trying to revert"
7154
                    " disk status: %s", msg)
7155
      self.feedback_fn("Migration failed, aborting")
7156
      self._AbortMigration()
7157
      self._RevertDiskStatus()
7158
      raise errors.OpExecError("Could not migrate instance %s: %s" %
7159
                               (instance.name, msg))
7160

    
7161
    instance.primary_node = target_node
7162
    # distribute new instance config to the other nodes
7163
    self.cfg.Update(instance, self.feedback_fn)
7164

    
7165
    result = self.rpc.call_finalize_migration(target_node,
7166
                                              instance,
7167
                                              migration_info,
7168
                                              True)
7169
    msg = result.fail_msg
7170
    if msg:
7171
      logging.error("Instance migration succeeded, but finalization failed:"
7172
                    " %s", msg)
7173
      raise errors.OpExecError("Could not finalize instance migration: %s" %
7174
                               msg)
7175

    
7176
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
7177
      self._EnsureSecondary(source_node)
7178
      self._WaitUntilSync()
7179
      self._GoStandalone()
7180
      self._GoReconnect(False)
7181
      self._WaitUntilSync()
7182

    
7183
    self.feedback_fn("* done")
7184

    
7185
  def _ExecFailover(self):
7186
    """Failover an instance.
7187

7188
    The failover is done by shutting it down on its present node and
7189
    starting it on the secondary.
7190

7191
    """
7192
    instance = self.instance
7193
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
7194

    
7195
    source_node = instance.primary_node
7196
    target_node = self.target_node
7197

    
7198
    if instance.admin_up:
7199
      self.feedback_fn("* checking disk consistency between source and target")
7200
      for dev in instance.disks:
7201
        # for drbd, these are drbd over lvm
7202
        if not _CheckDiskConsistency(self, dev, target_node, False):
7203
          if not self.ignore_consistency:
7204
            raise errors.OpExecError("Disk %s is degraded on target node,"
7205
                                     " aborting failover" % dev.iv_name)
7206
    else:
7207
      self.feedback_fn("* not checking disk consistency as instance is not"
7208
                       " running")
7209

    
7210
    self.feedback_fn("* shutting down instance on source node")
7211
    logging.info("Shutting down instance %s on node %s",
7212
                 instance.name, source_node)
7213

    
7214
    result = self.rpc.call_instance_shutdown(source_node, instance,
7215
                                             self.shutdown_timeout)
7216
    msg = result.fail_msg
7217
    if msg:
7218
      if self.ignore_consistency or primary_node.offline:
7219
        self.lu.LogWarning("Could not shutdown instance %s on node %s,"
7220
                           " proceeding anyway; please make sure node"
7221
                           " %s is down; error details: %s",
7222
                           instance.name, source_node, source_node, msg)
7223
      else:
7224
        raise errors.OpExecError("Could not shutdown instance %s on"
7225
                                 " node %s: %s" %
7226
                                 (instance.name, source_node, msg))
7227

    
7228
    self.feedback_fn("* deactivating the instance's disks on source node")
7229
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
7230
      raise errors.OpExecError("Can't shut down the instance's disks.")
7231

    
7232
    instance.primary_node = target_node
7233
    # distribute new instance config to the other nodes
7234
    self.cfg.Update(instance, self.feedback_fn)
7235

    
7236
    # Only start the instance if it's marked as up
7237
    if instance.admin_up:
7238
      self.feedback_fn("* activating the instance's disks on target node")
7239
      logging.info("Starting instance %s on node %s",
7240
                   instance.name, target_node)
7241

    
7242
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
7243
                                           ignore_secondaries=True)
7244
      if not disks_ok:
7245
        _ShutdownInstanceDisks(self, instance)
7246
        raise errors.OpExecError("Can't activate the instance's disks")
7247

    
7248
      self.feedback_fn("* starting the instance on the target node")
7249
      result = self.rpc.call_instance_start(target_node, instance, None, None,
7250
                                            False)
7251
      msg = result.fail_msg
7252
      if msg:
7253
        _ShutdownInstanceDisks(self, instance)
7254
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
7255
                                 (instance.name, target_node, msg))
7256

    
7257
  def Exec(self, feedback_fn):
7258
    """Perform the migration.
7259

7260
    """
7261
    self.feedback_fn = feedback_fn
7262
    self.source_node = self.instance.primary_node
7263

    
7264
    # FIXME: if we implement migrate-to-any in DRBD, this needs fixing
7265
    if self.instance.disk_template in constants.DTS_INT_MIRROR:
7266
      self.target_node = self.instance.secondary_nodes[0]
7267
      # Otherwise self.target_node has been populated either
7268
      # directly, or through an iallocator.
7269

    
7270
    self.all_nodes = [self.source_node, self.target_node]
7271
    self.nodes_ip = {
7272
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
7273
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
7274
      }
7275

    
7276
    if self.failover:
7277
      feedback_fn("Failover instance %s" % self.instance.name)
7278
      self._ExecFailover()
7279
    else:
7280
      feedback_fn("Migrating instance %s" % self.instance.name)
7281

    
7282
      if self.cleanup:
7283
        return self._ExecCleanup()
7284
      else:
7285
        return self._ExecMigration()
7286

    
7287

    
7288
def _CreateBlockDev(lu, node, instance, device, force_create,
7289
                    info, force_open):
7290
  """Create a tree of block devices on a given node.
7291

7292
  If this device type has to be created on secondaries, create it and
7293
  all its children.
7294

7295
  If not, just recurse to children keeping the same 'force' value.
7296

7297
  @param lu: the lu on whose behalf we execute
7298
  @param node: the node on which to create the device
7299
  @type instance: L{objects.Instance}
7300
  @param instance: the instance which owns the device
7301
  @type device: L{objects.Disk}
7302
  @param device: the device to create
7303
  @type force_create: boolean
7304
  @param force_create: whether to force creation of this device; this
7305
      will be change to True whenever we find a device which has
7306
      CreateOnSecondary() attribute
7307
  @param info: the extra 'metadata' we should attach to the device
7308
      (this will be represented as a LVM tag)
7309
  @type force_open: boolean
7310
  @param force_open: this parameter will be passes to the
7311
      L{backend.BlockdevCreate} function where it specifies
7312
      whether we run on primary or not, and it affects both
7313
      the child assembly and the device own Open() execution
7314

7315
  """
7316
  if device.CreateOnSecondary():
7317
    force_create = True
7318

    
7319
  if device.children:
7320
    for child in device.children:
7321
      _CreateBlockDev(lu, node, instance, child, force_create,
7322
                      info, force_open)
7323

    
7324
  if not force_create:
7325
    return
7326

    
7327
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
7328

    
7329

    
7330
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
7331
  """Create a single block device on a given node.
7332

7333
  This will not recurse over children of the device, so they must be
7334
  created in advance.
7335

7336
  @param lu: the lu on whose behalf we execute
7337
  @param node: the node on which to create the device
7338
  @type instance: L{objects.Instance}
7339
  @param instance: the instance which owns the device
7340
  @type device: L{objects.Disk}
7341
  @param device: the device to create
7342
  @param info: the extra 'metadata' we should attach to the device
7343
      (this will be represented as a LVM tag)
7344
  @type force_open: boolean
7345
  @param force_open: this parameter will be passes to the
7346
      L{backend.BlockdevCreate} function where it specifies
7347
      whether we run on primary or not, and it affects both
7348
      the child assembly and the device own Open() execution
7349

7350
  """
7351
  lu.cfg.SetDiskID(device, node)
7352
  result = lu.rpc.call_blockdev_create(node, device, device.size,
7353
                                       instance.name, force_open, info)
7354
  result.Raise("Can't create block device %s on"
7355
               " node %s for instance %s" % (device, node, instance.name))
7356
  if device.physical_id is None:
7357
    device.physical_id = result.payload
7358

    
7359

    
7360
def _GenerateUniqueNames(lu, exts):
7361
  """Generate a suitable LV name.
7362

7363
  This will generate a logical volume name for the given instance.
7364

7365
  """
7366
  results = []
7367
  for val in exts:
7368
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
7369
    results.append("%s%s" % (new_id, val))
7370
  return results
7371

    
7372

    
7373
def _GenerateDRBD8Branch(lu, primary, secondary, size, vgnames, names,
7374
                         iv_name, p_minor, s_minor):
7375
  """Generate a drbd8 device complete with its children.
7376

7377
  """
7378
  assert len(vgnames) == len(names) == 2
7379
  port = lu.cfg.AllocatePort()
7380
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
7381
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
7382
                          logical_id=(vgnames[0], names[0]))
7383
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7384
                          logical_id=(vgnames[1], names[1]))
7385
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
7386
                          logical_id=(primary, secondary, port,
7387
                                      p_minor, s_minor,
7388
                                      shared_secret),
7389
                          children=[dev_data, dev_meta],
7390
                          iv_name=iv_name)
7391
  return drbd_dev
7392

    
7393

    
7394
def _GenerateDiskTemplate(lu, template_name,
7395
                          instance_name, primary_node,
7396
                          secondary_nodes, disk_info,
7397
                          file_storage_dir, file_driver,
7398
                          base_index, feedback_fn):
7399
  """Generate the entire disk layout for a given template type.
7400

7401
  """
7402
  #TODO: compute space requirements
7403

    
7404
  vgname = lu.cfg.GetVGName()
7405
  disk_count = len(disk_info)
7406
  disks = []
7407
  if template_name == constants.DT_DISKLESS:
7408
    pass
7409
  elif template_name == constants.DT_PLAIN:
7410
    if len(secondary_nodes) != 0:
7411
      raise errors.ProgrammerError("Wrong template configuration")
7412

    
7413
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
7414
                                      for i in range(disk_count)])
7415
    for idx, disk in enumerate(disk_info):
7416
      disk_index = idx + base_index
7417
      vg = disk.get(constants.IDISK_VG, vgname)
7418
      feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
7419
      disk_dev = objects.Disk(dev_type=constants.LD_LV,
7420
                              size=disk[constants.IDISK_SIZE],
7421
                              logical_id=(vg, names[idx]),
7422
                              iv_name="disk/%d" % disk_index,
7423
                              mode=disk[constants.IDISK_MODE])
7424
      disks.append(disk_dev)
7425
  elif template_name == constants.DT_DRBD8:
7426
    if len(secondary_nodes) != 1:
7427
      raise errors.ProgrammerError("Wrong template configuration")
7428
    remote_node = secondary_nodes[0]
7429
    minors = lu.cfg.AllocateDRBDMinor(
7430
      [primary_node, remote_node] * len(disk_info), instance_name)
7431

    
7432
    names = []
7433
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
7434
                                               for i in range(disk_count)]):
7435
      names.append(lv_prefix + "_data")
7436
      names.append(lv_prefix + "_meta")
7437
    for idx, disk in enumerate(disk_info):
7438
      disk_index = idx + base_index
7439
      data_vg = disk.get(constants.IDISK_VG, vgname)
7440
      meta_vg = disk.get(constants.IDISK_METAVG, data_vg)
7441
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
7442
                                      disk[constants.IDISK_SIZE],
7443
                                      [data_vg, meta_vg],
7444
                                      names[idx * 2:idx * 2 + 2],
7445
                                      "disk/%d" % disk_index,
7446
                                      minors[idx * 2], minors[idx * 2 + 1])
7447
      disk_dev.mode = disk[constants.IDISK_MODE]
7448
      disks.append(disk_dev)
7449
  elif template_name == constants.DT_FILE:
7450
    if len(secondary_nodes) != 0:
7451
      raise errors.ProgrammerError("Wrong template configuration")
7452

    
7453
    opcodes.RequireFileStorage()
7454

    
7455
    for idx, disk in enumerate(disk_info):
7456
      disk_index = idx + base_index
7457
      disk_dev = objects.Disk(dev_type=constants.LD_FILE,
7458
                              size=disk[constants.IDISK_SIZE],
7459
                              iv_name="disk/%d" % disk_index,
7460
                              logical_id=(file_driver,
7461
                                          "%s/disk%d" % (file_storage_dir,
7462
                                                         disk_index)),
7463
                              mode=disk[constants.IDISK_MODE])
7464
      disks.append(disk_dev)
7465
  elif template_name == constants.DT_SHARED_FILE:
7466
    if len(secondary_nodes) != 0:
7467
      raise errors.ProgrammerError("Wrong template configuration")
7468

    
7469
    opcodes.RequireSharedFileStorage()
7470

    
7471
    for idx, disk in enumerate(disk_info):
7472
      disk_index = idx + base_index
7473
      disk_dev = objects.Disk(dev_type=constants.LD_FILE,
7474
                              size=disk[constants.IDISK_SIZE],
7475
                              iv_name="disk/%d" % disk_index,
7476
                              logical_id=(file_driver,
7477
                                          "%s/disk%d" % (file_storage_dir,
7478
                                                         disk_index)),
7479
                              mode=disk[constants.IDISK_MODE])
7480
      disks.append(disk_dev)
7481
  elif template_name == constants.DT_BLOCK:
7482
    if len(secondary_nodes) != 0:
7483
      raise errors.ProgrammerError("Wrong template configuration")
7484

    
7485
    for idx, disk in enumerate(disk_info):
7486
      disk_index = idx + base_index
7487
      disk_dev = objects.Disk(dev_type=constants.LD_BLOCKDEV,
7488
                              size=disk[constants.IDISK_SIZE],
7489
                              logical_id=(constants.BLOCKDEV_DRIVER_MANUAL,
7490
                                          disk[constants.IDISK_ADOPT]),
7491
                              iv_name="disk/%d" % disk_index,
7492
                              mode=disk[constants.IDISK_MODE])
7493
      disks.append(disk_dev)
7494

    
7495
  else:
7496
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
7497
  return disks
7498

    
7499

    
7500
def _GetInstanceInfoText(instance):
7501
  """Compute that text that should be added to the disk's metadata.
7502

7503
  """
7504
  return "originstname+%s" % instance.name
7505

    
7506

    
7507
def _CalcEta(time_taken, written, total_size):
7508
  """Calculates the ETA based on size written and total size.
7509

7510
  @param time_taken: The time taken so far
7511
  @param written: amount written so far
7512
  @param total_size: The total size of data to be written
7513
  @return: The remaining time in seconds
7514

7515
  """
7516
  avg_time = time_taken / float(written)
7517
  return (total_size - written) * avg_time
7518

    
7519

    
7520
def _WipeDisks(lu, instance):
7521
  """Wipes instance disks.
7522

7523
  @type lu: L{LogicalUnit}
7524
  @param lu: the logical unit on whose behalf we execute
7525
  @type instance: L{objects.Instance}
7526
  @param instance: the instance whose disks we should create
7527
  @return: the success of the wipe
7528

7529
  """
7530
  node = instance.primary_node
7531

    
7532
  for device in instance.disks:
7533
    lu.cfg.SetDiskID(device, node)
7534

    
7535
  logging.info("Pause sync of instance %s disks", instance.name)
7536
  result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, True)
7537

    
7538
  for idx, success in enumerate(result.payload):
7539
    if not success:
7540
      logging.warn("pause-sync of instance %s for disks %d failed",
7541
                   instance.name, idx)
7542

    
7543
  try:
7544
    for idx, device in enumerate(instance.disks):
7545
      # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
7546
      # MAX_WIPE_CHUNK at max
7547
      wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
7548
                            constants.MIN_WIPE_CHUNK_PERCENT)
7549
      # we _must_ make this an int, otherwise rounding errors will
7550
      # occur
7551
      wipe_chunk_size = int(wipe_chunk_size)
7552

    
7553
      lu.LogInfo("* Wiping disk %d", idx)
7554
      logging.info("Wiping disk %d for instance %s, node %s using"
7555
                   " chunk size %s", idx, instance.name, node, wipe_chunk_size)
7556

    
7557
      offset = 0
7558
      size = device.size
7559
      last_output = 0
7560
      start_time = time.time()
7561

    
7562
      while offset < size:
7563
        wipe_size = min(wipe_chunk_size, size - offset)
7564
        logging.debug("Wiping disk %d, offset %s, chunk %s",
7565
                      idx, offset, wipe_size)
7566
        result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
7567
        result.Raise("Could not wipe disk %d at offset %d for size %d" %
7568
                     (idx, offset, wipe_size))
7569
        now = time.time()
7570
        offset += wipe_size
7571
        if now - last_output >= 60:
7572
          eta = _CalcEta(now - start_time, offset, size)
7573
          lu.LogInfo(" - done: %.1f%% ETA: %s" %
7574
                     (offset / float(size) * 100, utils.FormatSeconds(eta)))
7575
          last_output = now
7576
  finally:
7577
    logging.info("Resume sync of instance %s disks", instance.name)
7578

    
7579
    result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, False)
7580

    
7581
    for idx, success in enumerate(result.payload):
7582
      if not success:
7583
        lu.LogWarning("Resume sync of disk %d failed, please have a"
7584
                      " look at the status and troubleshoot the issue", idx)
7585
        logging.warn("resume-sync of instance %s for disks %d failed",
7586
                     instance.name, idx)
7587

    
7588

    
7589
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
7590
  """Create all disks for an instance.
7591

7592
  This abstracts away some work from AddInstance.
7593

7594
  @type lu: L{LogicalUnit}
7595
  @param lu: the logical unit on whose behalf we execute
7596
  @type instance: L{objects.Instance}
7597
  @param instance: the instance whose disks we should create
7598
  @type to_skip: list
7599
  @param to_skip: list of indices to skip
7600
  @type target_node: string
7601
  @param target_node: if passed, overrides the target node for creation
7602
  @rtype: boolean
7603
  @return: the success of the creation
7604

7605
  """
7606
  info = _GetInstanceInfoText(instance)
7607
  if target_node is None:
7608
    pnode = instance.primary_node
7609
    all_nodes = instance.all_nodes
7610
  else:
7611
    pnode = target_node
7612
    all_nodes = [pnode]
7613

    
7614
  if instance.disk_template in constants.DTS_FILEBASED:
7615
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7616
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
7617

    
7618
    result.Raise("Failed to create directory '%s' on"
7619
                 " node %s" % (file_storage_dir, pnode))
7620

    
7621
  # Note: this needs to be kept in sync with adding of disks in
7622
  # LUInstanceSetParams
7623
  for idx, device in enumerate(instance.disks):
7624
    if to_skip and idx in to_skip:
7625
      continue
7626
    logging.info("Creating volume %s for instance %s",
7627
                 device.iv_name, instance.name)
7628
    #HARDCODE
7629
    for node in all_nodes:
7630
      f_create = node == pnode
7631
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
7632

    
7633

    
7634
def _RemoveDisks(lu, instance, target_node=None):
7635
  """Remove all disks for an instance.
7636

7637
  This abstracts away some work from `AddInstance()` and
7638
  `RemoveInstance()`. Note that in case some of the devices couldn't
7639
  be removed, the removal will continue with the other ones (compare
7640
  with `_CreateDisks()`).
7641

7642
  @type lu: L{LogicalUnit}
7643
  @param lu: the logical unit on whose behalf we execute
7644
  @type instance: L{objects.Instance}
7645
  @param instance: the instance whose disks we should remove
7646
  @type target_node: string
7647
  @param target_node: used to override the node on which to remove the disks
7648
  @rtype: boolean
7649
  @return: the success of the removal
7650

7651
  """
7652
  logging.info("Removing block devices for instance %s", instance.name)
7653

    
7654
  all_result = True
7655
  for device in instance.disks:
7656
    if target_node:
7657
      edata = [(target_node, device)]
7658
    else:
7659
      edata = device.ComputeNodeTree(instance.primary_node)
7660
    for node, disk in edata:
7661
      lu.cfg.SetDiskID(disk, node)
7662
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
7663
      if msg:
7664
        lu.LogWarning("Could not remove block device %s on node %s,"
7665
                      " continuing anyway: %s", device.iv_name, node, msg)
7666
        all_result = False
7667

    
7668
  if instance.disk_template == constants.DT_FILE:
7669
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7670
    if target_node:
7671
      tgt = target_node
7672
    else:
7673
      tgt = instance.primary_node
7674
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
7675
    if result.fail_msg:
7676
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
7677
                    file_storage_dir, instance.primary_node, result.fail_msg)
7678
      all_result = False
7679

    
7680
  return all_result
7681

    
7682

    
7683
def _ComputeDiskSizePerVG(disk_template, disks):
7684
  """Compute disk size requirements in the volume group
7685

7686
  """
7687
  def _compute(disks, payload):
7688
    """Universal algorithm.
7689

7690
    """
7691
    vgs = {}
7692
    for disk in disks:
7693
      vgs[disk[constants.IDISK_VG]] = \
7694
        vgs.get(constants.IDISK_VG, 0) + disk[constants.IDISK_SIZE] + payload
7695

    
7696
    return vgs
7697

    
7698
  # Required free disk space as a function of disk and swap space
7699
  req_size_dict = {
7700
    constants.DT_DISKLESS: {},
7701
    constants.DT_PLAIN: _compute(disks, 0),
7702
    # 128 MB are added for drbd metadata for each disk
7703
    constants.DT_DRBD8: _compute(disks, 128),
7704
    constants.DT_FILE: {},
7705
    constants.DT_SHARED_FILE: {},
7706
  }
7707

    
7708
  if disk_template not in req_size_dict:
7709
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7710
                                 " is unknown" %  disk_template)
7711

    
7712
  return req_size_dict[disk_template]
7713

    
7714

    
7715
def _ComputeDiskSize(disk_template, disks):
7716
  """Compute disk size requirements in the volume group
7717

7718
  """
7719
  # Required free disk space as a function of disk and swap space
7720
  req_size_dict = {
7721
    constants.DT_DISKLESS: None,
7722
    constants.DT_PLAIN: sum(d[constants.IDISK_SIZE] for d in disks),
7723
    # 128 MB are added for drbd metadata for each disk
7724
    constants.DT_DRBD8: sum(d[constants.IDISK_SIZE] + 128 for d in disks),
7725
    constants.DT_FILE: None,
7726
    constants.DT_SHARED_FILE: 0,
7727
    constants.DT_BLOCK: 0,
7728
  }
7729

    
7730
  if disk_template not in req_size_dict:
7731
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7732
                                 " is unknown" %  disk_template)
7733

    
7734
  return req_size_dict[disk_template]
7735

    
7736

    
7737
def _FilterVmNodes(lu, nodenames):
7738
  """Filters out non-vm_capable nodes from a list.
7739

7740
  @type lu: L{LogicalUnit}
7741
  @param lu: the logical unit for which we check
7742
  @type nodenames: list
7743
  @param nodenames: the list of nodes on which we should check
7744
  @rtype: list
7745
  @return: the list of vm-capable nodes
7746

7747
  """
7748
  vm_nodes = frozenset(lu.cfg.GetNonVmCapableNodeList())
7749
  return [name for name in nodenames if name not in vm_nodes]
7750

    
7751

    
7752
def _CheckHVParams(lu, nodenames, hvname, hvparams):
7753
  """Hypervisor parameter validation.
7754

7755
  This function abstract the hypervisor parameter validation to be
7756
  used in both instance create and instance modify.
7757

7758
  @type lu: L{LogicalUnit}
7759
  @param lu: the logical unit for which we check
7760
  @type nodenames: list
7761
  @param nodenames: the list of nodes on which we should check
7762
  @type hvname: string
7763
  @param hvname: the name of the hypervisor we should use
7764
  @type hvparams: dict
7765
  @param hvparams: the parameters which we need to check
7766
  @raise errors.OpPrereqError: if the parameters are not valid
7767

7768
  """
7769
  nodenames = _FilterVmNodes(lu, nodenames)
7770
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
7771
                                                  hvname,
7772
                                                  hvparams)
7773
  for node in nodenames:
7774
    info = hvinfo[node]
7775
    if info.offline:
7776
      continue
7777
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
7778

    
7779

    
7780
def _CheckOSParams(lu, required, nodenames, osname, osparams):
7781
  """OS parameters validation.
7782

7783
  @type lu: L{LogicalUnit}
7784
  @param lu: the logical unit for which we check
7785
  @type required: boolean
7786
  @param required: whether the validation should fail if the OS is not
7787
      found
7788
  @type nodenames: list
7789
  @param nodenames: the list of nodes on which we should check
7790
  @type osname: string
7791
  @param osname: the name of the hypervisor we should use
7792
  @type osparams: dict
7793
  @param osparams: the parameters which we need to check
7794
  @raise errors.OpPrereqError: if the parameters are not valid
7795

7796
  """
7797
  nodenames = _FilterVmNodes(lu, nodenames)
7798
  result = lu.rpc.call_os_validate(required, nodenames, osname,
7799
                                   [constants.OS_VALIDATE_PARAMETERS],
7800
                                   osparams)
7801
  for node, nres in result.items():
7802
    # we don't check for offline cases since this should be run only
7803
    # against the master node and/or an instance's nodes
7804
    nres.Raise("OS Parameters validation failed on node %s" % node)
7805
    if not nres.payload:
7806
      lu.LogInfo("OS %s not found on node %s, validation skipped",
7807
                 osname, node)
7808

    
7809

    
7810
class LUInstanceCreate(LogicalUnit):
7811
  """Create an instance.
7812

7813
  """
7814
  HPATH = "instance-add"
7815
  HTYPE = constants.HTYPE_INSTANCE
7816
  REQ_BGL = False
7817

    
7818
  def CheckArguments(self):
7819
    """Check arguments.
7820

7821
    """
7822
    # do not require name_check to ease forward/backward compatibility
7823
    # for tools
7824
    if self.op.no_install and self.op.start:
7825
      self.LogInfo("No-installation mode selected, disabling startup")
7826
      self.op.start = False
7827
    # validate/normalize the instance name
7828
    self.op.instance_name = \
7829
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
7830

    
7831
    if self.op.ip_check and not self.op.name_check:
7832
      # TODO: make the ip check more flexible and not depend on the name check
7833
      raise errors.OpPrereqError("Cannot do IP address check without a name"
7834
                                 " check", errors.ECODE_INVAL)
7835

    
7836
    # check nics' parameter names
7837
    for nic in self.op.nics:
7838
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
7839

    
7840
    # check disks. parameter names and consistent adopt/no-adopt strategy
7841
    has_adopt = has_no_adopt = False
7842
    for disk in self.op.disks:
7843
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
7844
      if constants.IDISK_ADOPT in disk:
7845
        has_adopt = True
7846
      else:
7847
        has_no_adopt = True
7848
    if has_adopt and has_no_adopt:
7849
      raise errors.OpPrereqError("Either all disks are adopted or none is",
7850
                                 errors.ECODE_INVAL)
7851
    if has_adopt:
7852
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
7853
        raise errors.OpPrereqError("Disk adoption is not supported for the"
7854
                                   " '%s' disk template" %
7855
                                   self.op.disk_template,
7856
                                   errors.ECODE_INVAL)
7857
      if self.op.iallocator is not None:
7858
        raise errors.OpPrereqError("Disk adoption not allowed with an"
7859
                                   " iallocator script", errors.ECODE_INVAL)
7860
      if self.op.mode == constants.INSTANCE_IMPORT:
7861
        raise errors.OpPrereqError("Disk adoption not allowed for"
7862
                                   " instance import", errors.ECODE_INVAL)
7863
    else:
7864
      if self.op.disk_template in constants.DTS_MUST_ADOPT:
7865
        raise errors.OpPrereqError("Disk template %s requires disk adoption,"
7866
                                   " but no 'adopt' parameter given" %
7867
                                   self.op.disk_template,
7868
                                   errors.ECODE_INVAL)
7869

    
7870
    self.adopt_disks = has_adopt
7871

    
7872
    # instance name verification
7873
    if self.op.name_check:
7874
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
7875
      self.op.instance_name = self.hostname1.name
7876
      # used in CheckPrereq for ip ping check
7877
      self.check_ip = self.hostname1.ip
7878
    else:
7879
      self.check_ip = None
7880

    
7881
    # file storage checks
7882
    if (self.op.file_driver and
7883
        not self.op.file_driver in constants.FILE_DRIVER):
7884
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
7885
                                 self.op.file_driver, errors.ECODE_INVAL)
7886

    
7887
    if self.op.disk_template == constants.DT_FILE:
7888
      opcodes.RequireFileStorage()
7889
    elif self.op.disk_template == constants.DT_SHARED_FILE:
7890
      opcodes.RequireSharedFileStorage()
7891

    
7892
    ### Node/iallocator related checks
7893
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
7894

    
7895
    if self.op.pnode is not None:
7896
      if self.op.disk_template in constants.DTS_INT_MIRROR:
7897
        if self.op.snode is None:
7898
          raise errors.OpPrereqError("The networked disk templates need"
7899
                                     " a mirror node", errors.ECODE_INVAL)
7900
      elif self.op.snode:
7901
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
7902
                        " template")
7903
        self.op.snode = None
7904

    
7905
    self._cds = _GetClusterDomainSecret()
7906

    
7907
    if self.op.mode == constants.INSTANCE_IMPORT:
7908
      # On import force_variant must be True, because if we forced it at
7909
      # initial install, our only chance when importing it back is that it
7910
      # works again!
7911
      self.op.force_variant = True
7912

    
7913
      if self.op.no_install:
7914
        self.LogInfo("No-installation mode has no effect during import")
7915

    
7916
    elif self.op.mode == constants.INSTANCE_CREATE:
7917
      if self.op.os_type is None:
7918
        raise errors.OpPrereqError("No guest OS specified",
7919
                                   errors.ECODE_INVAL)
7920
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
7921
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
7922
                                   " installation" % self.op.os_type,
7923
                                   errors.ECODE_STATE)
7924
      if self.op.disk_template is None:
7925
        raise errors.OpPrereqError("No disk template specified",
7926
                                   errors.ECODE_INVAL)
7927

    
7928
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7929
      # Check handshake to ensure both clusters have the same domain secret
7930
      src_handshake = self.op.source_handshake
7931
      if not src_handshake:
7932
        raise errors.OpPrereqError("Missing source handshake",
7933
                                   errors.ECODE_INVAL)
7934

    
7935
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
7936
                                                           src_handshake)
7937
      if errmsg:
7938
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
7939
                                   errors.ECODE_INVAL)
7940

    
7941
      # Load and check source CA
7942
      self.source_x509_ca_pem = self.op.source_x509_ca
7943
      if not self.source_x509_ca_pem:
7944
        raise errors.OpPrereqError("Missing source X509 CA",
7945
                                   errors.ECODE_INVAL)
7946

    
7947
      try:
7948
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
7949
                                                    self._cds)
7950
      except OpenSSL.crypto.Error, err:
7951
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
7952
                                   (err, ), errors.ECODE_INVAL)
7953

    
7954
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
7955
      if errcode is not None:
7956
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
7957
                                   errors.ECODE_INVAL)
7958

    
7959
      self.source_x509_ca = cert
7960

    
7961
      src_instance_name = self.op.source_instance_name
7962
      if not src_instance_name:
7963
        raise errors.OpPrereqError("Missing source instance name",
7964
                                   errors.ECODE_INVAL)
7965

    
7966
      self.source_instance_name = \
7967
          netutils.GetHostname(name=src_instance_name).name
7968

    
7969
    else:
7970
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
7971
                                 self.op.mode, errors.ECODE_INVAL)
7972

    
7973
  def ExpandNames(self):
7974
    """ExpandNames for CreateInstance.
7975

7976
    Figure out the right locks for instance creation.
7977

7978
    """
7979
    self.needed_locks = {}
7980

    
7981
    instance_name = self.op.instance_name
7982
    # this is just a preventive check, but someone might still add this
7983
    # instance in the meantime, and creation will fail at lock-add time
7984
    if instance_name in self.cfg.GetInstanceList():
7985
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
7986
                                 instance_name, errors.ECODE_EXISTS)
7987

    
7988
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
7989

    
7990
    if self.op.iallocator:
7991
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7992
    else:
7993
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
7994
      nodelist = [self.op.pnode]
7995
      if self.op.snode is not None:
7996
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
7997
        nodelist.append(self.op.snode)
7998
      self.needed_locks[locking.LEVEL_NODE] = nodelist
7999

    
8000
    # in case of import lock the source node too
8001
    if self.op.mode == constants.INSTANCE_IMPORT:
8002
      src_node = self.op.src_node
8003
      src_path = self.op.src_path
8004

    
8005
      if src_path is None:
8006
        self.op.src_path = src_path = self.op.instance_name
8007

    
8008
      if src_node is None:
8009
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8010
        self.op.src_node = None
8011
        if os.path.isabs(src_path):
8012
          raise errors.OpPrereqError("Importing an instance from an absolute"
8013
                                     " path requires a source node option",
8014
                                     errors.ECODE_INVAL)
8015
      else:
8016
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
8017
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
8018
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
8019
        if not os.path.isabs(src_path):
8020
          self.op.src_path = src_path = \
8021
            utils.PathJoin(constants.EXPORT_DIR, src_path)
8022

    
8023
  def _RunAllocator(self):
8024
    """Run the allocator based on input opcode.
8025

8026
    """
8027
    nics = [n.ToDict() for n in self.nics]
8028
    ial = IAllocator(self.cfg, self.rpc,
8029
                     mode=constants.IALLOCATOR_MODE_ALLOC,
8030
                     name=self.op.instance_name,
8031
                     disk_template=self.op.disk_template,
8032
                     tags=self.op.tags,
8033
                     os=self.op.os_type,
8034
                     vcpus=self.be_full[constants.BE_VCPUS],
8035
                     memory=self.be_full[constants.BE_MEMORY],
8036
                     disks=self.disks,
8037
                     nics=nics,
8038
                     hypervisor=self.op.hypervisor,
8039
                     )
8040

    
8041
    ial.Run(self.op.iallocator)
8042

    
8043
    if not ial.success:
8044
      raise errors.OpPrereqError("Can't compute nodes using"
8045
                                 " iallocator '%s': %s" %
8046
                                 (self.op.iallocator, ial.info),
8047
                                 errors.ECODE_NORES)
8048
    if len(ial.result) != ial.required_nodes:
8049
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
8050
                                 " of nodes (%s), required %s" %
8051
                                 (self.op.iallocator, len(ial.result),
8052
                                  ial.required_nodes), errors.ECODE_FAULT)
8053
    self.op.pnode = ial.result[0]
8054
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
8055
                 self.op.instance_name, self.op.iallocator,
8056
                 utils.CommaJoin(ial.result))
8057
    if ial.required_nodes == 2:
8058
      self.op.snode = ial.result[1]
8059

    
8060
  def BuildHooksEnv(self):
8061
    """Build hooks env.
8062

8063
    This runs on master, primary and secondary nodes of the instance.
8064

8065
    """
8066
    env = {
8067
      "ADD_MODE": self.op.mode,
8068
      }
8069
    if self.op.mode == constants.INSTANCE_IMPORT:
8070
      env["SRC_NODE"] = self.op.src_node
8071
      env["SRC_PATH"] = self.op.src_path
8072
      env["SRC_IMAGES"] = self.src_images
8073

    
8074
    env.update(_BuildInstanceHookEnv(
8075
      name=self.op.instance_name,
8076
      primary_node=self.op.pnode,
8077
      secondary_nodes=self.secondaries,
8078
      status=self.op.start,
8079
      os_type=self.op.os_type,
8080
      memory=self.be_full[constants.BE_MEMORY],
8081
      vcpus=self.be_full[constants.BE_VCPUS],
8082
      nics=_NICListToTuple(self, self.nics),
8083
      disk_template=self.op.disk_template,
8084
      disks=[(d[constants.IDISK_SIZE], d[constants.IDISK_MODE])
8085
             for d in self.disks],
8086
      bep=self.be_full,
8087
      hvp=self.hv_full,
8088
      hypervisor_name=self.op.hypervisor,
8089
      tags=self.op.tags,
8090
    ))
8091

    
8092
    return env
8093

    
8094
  def BuildHooksNodes(self):
8095
    """Build hooks nodes.
8096

8097
    """
8098
    nl = [self.cfg.GetMasterNode(), self.op.pnode] + self.secondaries
8099
    return nl, nl
8100

    
8101
  def _ReadExportInfo(self):
8102
    """Reads the export information from disk.
8103

8104
    It will override the opcode source node and path with the actual
8105
    information, if these two were not specified before.
8106

8107
    @return: the export information
8108

8109
    """
8110
    assert self.op.mode == constants.INSTANCE_IMPORT
8111

    
8112
    src_node = self.op.src_node
8113
    src_path = self.op.src_path
8114

    
8115
    if src_node is None:
8116
      locked_nodes = self.glm.list_owned(locking.LEVEL_NODE)
8117
      exp_list = self.rpc.call_export_list(locked_nodes)
8118
      found = False
8119
      for node in exp_list:
8120
        if exp_list[node].fail_msg:
8121
          continue
8122
        if src_path in exp_list[node].payload:
8123
          found = True
8124
          self.op.src_node = src_node = node
8125
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
8126
                                                       src_path)
8127
          break
8128
      if not found:
8129
        raise errors.OpPrereqError("No export found for relative path %s" %
8130
                                    src_path, errors.ECODE_INVAL)
8131

    
8132
    _CheckNodeOnline(self, src_node)
8133
    result = self.rpc.call_export_info(src_node, src_path)
8134
    result.Raise("No export or invalid export found in dir %s" % src_path)
8135

    
8136
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
8137
    if not export_info.has_section(constants.INISECT_EXP):
8138
      raise errors.ProgrammerError("Corrupted export config",
8139
                                   errors.ECODE_ENVIRON)
8140

    
8141
    ei_version = export_info.get(constants.INISECT_EXP, "version")
8142
    if (int(ei_version) != constants.EXPORT_VERSION):
8143
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
8144
                                 (ei_version, constants.EXPORT_VERSION),
8145
                                 errors.ECODE_ENVIRON)
8146
    return export_info
8147

    
8148
  def _ReadExportParams(self, einfo):
8149
    """Use export parameters as defaults.
8150

8151
    In case the opcode doesn't specify (as in override) some instance
8152
    parameters, then try to use them from the export information, if
8153
    that declares them.
8154

8155
    """
8156
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
8157

    
8158
    if self.op.disk_template is None:
8159
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
8160
        self.op.disk_template = einfo.get(constants.INISECT_INS,
8161
                                          "disk_template")
8162
      else:
8163
        raise errors.OpPrereqError("No disk template specified and the export"
8164
                                   " is missing the disk_template information",
8165
                                   errors.ECODE_INVAL)
8166

    
8167
    if not self.op.disks:
8168
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
8169
        disks = []
8170
        # TODO: import the disk iv_name too
8171
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
8172
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
8173
          disks.append({constants.IDISK_SIZE: disk_sz})
8174
        self.op.disks = disks
8175
      else:
8176
        raise errors.OpPrereqError("No disk info specified and the export"
8177
                                   " is missing the disk information",
8178
                                   errors.ECODE_INVAL)
8179

    
8180
    if (not self.op.nics and
8181
        einfo.has_option(constants.INISECT_INS, "nic_count")):
8182
      nics = []
8183
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
8184
        ndict = {}
8185
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
8186
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
8187
          ndict[name] = v
8188
        nics.append(ndict)
8189
      self.op.nics = nics
8190

    
8191
    if not self.op.tags and einfo.has_option(constants.INISECT_INS, "tags"):
8192
      self.op.tags = einfo.get(constants.INISECT_INS, "tags").split()
8193

    
8194
    if (self.op.hypervisor is None and
8195
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
8196
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
8197

    
8198
    if einfo.has_section(constants.INISECT_HYP):
8199
      # use the export parameters but do not override the ones
8200
      # specified by the user
8201
      for name, value in einfo.items(constants.INISECT_HYP):
8202
        if name not in self.op.hvparams:
8203
          self.op.hvparams[name] = value
8204

    
8205
    if einfo.has_section(constants.INISECT_BEP):
8206
      # use the parameters, without overriding
8207
      for name, value in einfo.items(constants.INISECT_BEP):
8208
        if name not in self.op.beparams:
8209
          self.op.beparams[name] = value
8210
    else:
8211
      # try to read the parameters old style, from the main section
8212
      for name in constants.BES_PARAMETERS:
8213
        if (name not in self.op.beparams and
8214
            einfo.has_option(constants.INISECT_INS, name)):
8215
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
8216

    
8217
    if einfo.has_section(constants.INISECT_OSP):
8218
      # use the parameters, without overriding
8219
      for name, value in einfo.items(constants.INISECT_OSP):
8220
        if name not in self.op.osparams:
8221
          self.op.osparams[name] = value
8222

    
8223
  def _RevertToDefaults(self, cluster):
8224
    """Revert the instance parameters to the default values.
8225

8226
    """
8227
    # hvparams
8228
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
8229
    for name in self.op.hvparams.keys():
8230
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
8231
        del self.op.hvparams[name]
8232
    # beparams
8233
    be_defs = cluster.SimpleFillBE({})
8234
    for name in self.op.beparams.keys():
8235
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
8236
        del self.op.beparams[name]
8237
    # nic params
8238
    nic_defs = cluster.SimpleFillNIC({})
8239
    for nic in self.op.nics:
8240
      for name in constants.NICS_PARAMETERS:
8241
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
8242
          del nic[name]
8243
    # osparams
8244
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
8245
    for name in self.op.osparams.keys():
8246
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
8247
        del self.op.osparams[name]
8248

    
8249
  def _CalculateFileStorageDir(self):
8250
    """Calculate final instance file storage dir.
8251

8252
    """
8253
    # file storage dir calculation/check
8254
    self.instance_file_storage_dir = None
8255
    if self.op.disk_template in constants.DTS_FILEBASED:
8256
      # build the full file storage dir path
8257
      joinargs = []
8258

    
8259
      if self.op.disk_template == constants.DT_SHARED_FILE:
8260
        get_fsd_fn = self.cfg.GetSharedFileStorageDir
8261
      else:
8262
        get_fsd_fn = self.cfg.GetFileStorageDir
8263

    
8264
      cfg_storagedir = get_fsd_fn()
8265
      if not cfg_storagedir:
8266
        raise errors.OpPrereqError("Cluster file storage dir not defined")
8267
      joinargs.append(cfg_storagedir)
8268

    
8269
      if self.op.file_storage_dir is not None:
8270
        joinargs.append(self.op.file_storage_dir)
8271

    
8272
      joinargs.append(self.op.instance_name)
8273

    
8274
      # pylint: disable-msg=W0142
8275
      self.instance_file_storage_dir = utils.PathJoin(*joinargs)
8276

    
8277
  def CheckPrereq(self):
8278
    """Check prerequisites.
8279

8280
    """
8281
    self._CalculateFileStorageDir()
8282

    
8283
    if self.op.mode == constants.INSTANCE_IMPORT:
8284
      export_info = self._ReadExportInfo()
8285
      self._ReadExportParams(export_info)
8286

    
8287
    if (not self.cfg.GetVGName() and
8288
        self.op.disk_template not in constants.DTS_NOT_LVM):
8289
      raise errors.OpPrereqError("Cluster does not support lvm-based"
8290
                                 " instances", errors.ECODE_STATE)
8291

    
8292
    if self.op.hypervisor is None:
8293
      self.op.hypervisor = self.cfg.GetHypervisorType()
8294

    
8295
    cluster = self.cfg.GetClusterInfo()
8296
    enabled_hvs = cluster.enabled_hypervisors
8297
    if self.op.hypervisor not in enabled_hvs:
8298
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
8299
                                 " cluster (%s)" % (self.op.hypervisor,
8300
                                  ",".join(enabled_hvs)),
8301
                                 errors.ECODE_STATE)
8302

    
8303
    # Check tag validity
8304
    for tag in self.op.tags:
8305
      objects.TaggableObject.ValidateTag(tag)
8306

    
8307
    # check hypervisor parameter syntax (locally)
8308
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
8309
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
8310
                                      self.op.hvparams)
8311
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
8312
    hv_type.CheckParameterSyntax(filled_hvp)
8313
    self.hv_full = filled_hvp
8314
    # check that we don't specify global parameters on an instance
8315
    _CheckGlobalHvParams(self.op.hvparams)
8316

    
8317
    # fill and remember the beparams dict
8318
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
8319
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
8320

    
8321
    # build os parameters
8322
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
8323

    
8324
    # now that hvp/bep are in final format, let's reset to defaults,
8325
    # if told to do so
8326
    if self.op.identify_defaults:
8327
      self._RevertToDefaults(cluster)
8328

    
8329
    # NIC buildup
8330
    self.nics = []
8331
    for idx, nic in enumerate(self.op.nics):
8332
      nic_mode_req = nic.get(constants.INIC_MODE, None)
8333
      nic_mode = nic_mode_req
8334
      if nic_mode is None:
8335
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
8336

    
8337
      # in routed mode, for the first nic, the default ip is 'auto'
8338
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
8339
        default_ip_mode = constants.VALUE_AUTO
8340
      else:
8341
        default_ip_mode = constants.VALUE_NONE
8342

    
8343
      # ip validity checks
8344
      ip = nic.get(constants.INIC_IP, default_ip_mode)
8345
      if ip is None or ip.lower() == constants.VALUE_NONE:
8346
        nic_ip = None
8347
      elif ip.lower() == constants.VALUE_AUTO:
8348
        if not self.op.name_check:
8349
          raise errors.OpPrereqError("IP address set to auto but name checks"
8350
                                     " have been skipped",
8351
                                     errors.ECODE_INVAL)
8352
        nic_ip = self.hostname1.ip
8353
      else:
8354
        if not netutils.IPAddress.IsValid(ip):
8355
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
8356
                                     errors.ECODE_INVAL)
8357
        nic_ip = ip
8358

    
8359
      # TODO: check the ip address for uniqueness
8360
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
8361
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
8362
                                   errors.ECODE_INVAL)
8363

    
8364
      # MAC address verification
8365
      mac = nic.get(constants.INIC_MAC, constants.VALUE_AUTO)
8366
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8367
        mac = utils.NormalizeAndValidateMac(mac)
8368

    
8369
        try:
8370
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
8371
        except errors.ReservationError:
8372
          raise errors.OpPrereqError("MAC address %s already in use"
8373
                                     " in cluster" % mac,
8374
                                     errors.ECODE_NOTUNIQUE)
8375

    
8376
      #  Build nic parameters
8377
      link = nic.get(constants.INIC_LINK, None)
8378
      nicparams = {}
8379
      if nic_mode_req:
8380
        nicparams[constants.NIC_MODE] = nic_mode_req
8381
      if link:
8382
        nicparams[constants.NIC_LINK] = link
8383

    
8384
      check_params = cluster.SimpleFillNIC(nicparams)
8385
      objects.NIC.CheckParameterSyntax(check_params)
8386
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
8387

    
8388
    # disk checks/pre-build
8389
    default_vg = self.cfg.GetVGName()
8390
    self.disks = []
8391
    for disk in self.op.disks:
8392
      mode = disk.get(constants.IDISK_MODE, constants.DISK_RDWR)
8393
      if mode not in constants.DISK_ACCESS_SET:
8394
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
8395
                                   mode, errors.ECODE_INVAL)
8396
      size = disk.get(constants.IDISK_SIZE, None)
8397
      if size is None:
8398
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
8399
      try:
8400
        size = int(size)
8401
      except (TypeError, ValueError):
8402
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
8403
                                   errors.ECODE_INVAL)
8404

    
8405
      data_vg = disk.get(constants.IDISK_VG, default_vg)
8406
      new_disk = {
8407
        constants.IDISK_SIZE: size,
8408
        constants.IDISK_MODE: mode,
8409
        constants.IDISK_VG: data_vg,
8410
        constants.IDISK_METAVG: disk.get(constants.IDISK_METAVG, data_vg),
8411
        }
8412
      if constants.IDISK_ADOPT in disk:
8413
        new_disk[constants.IDISK_ADOPT] = disk[constants.IDISK_ADOPT]
8414
      self.disks.append(new_disk)
8415

    
8416
    if self.op.mode == constants.INSTANCE_IMPORT:
8417

    
8418
      # Check that the new instance doesn't have less disks than the export
8419
      instance_disks = len(self.disks)
8420
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
8421
      if instance_disks < export_disks:
8422
        raise errors.OpPrereqError("Not enough disks to import."
8423
                                   " (instance: %d, export: %d)" %
8424
                                   (instance_disks, export_disks),
8425
                                   errors.ECODE_INVAL)
8426

    
8427
      disk_images = []
8428
      for idx in range(export_disks):
8429
        option = 'disk%d_dump' % idx
8430
        if export_info.has_option(constants.INISECT_INS, option):
8431
          # FIXME: are the old os-es, disk sizes, etc. useful?
8432
          export_name = export_info.get(constants.INISECT_INS, option)
8433
          image = utils.PathJoin(self.op.src_path, export_name)
8434
          disk_images.append(image)
8435
        else:
8436
          disk_images.append(False)
8437

    
8438
      self.src_images = disk_images
8439

    
8440
      old_name = export_info.get(constants.INISECT_INS, 'name')
8441
      try:
8442
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
8443
      except (TypeError, ValueError), err:
8444
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
8445
                                   " an integer: %s" % str(err),
8446
                                   errors.ECODE_STATE)
8447
      if self.op.instance_name == old_name:
8448
        for idx, nic in enumerate(self.nics):
8449
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
8450
            nic_mac_ini = 'nic%d_mac' % idx
8451
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
8452

    
8453
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
8454

    
8455
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
8456
    if self.op.ip_check:
8457
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
8458
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
8459
                                   (self.check_ip, self.op.instance_name),
8460
                                   errors.ECODE_NOTUNIQUE)
8461

    
8462
    #### mac address generation
8463
    # By generating here the mac address both the allocator and the hooks get
8464
    # the real final mac address rather than the 'auto' or 'generate' value.
8465
    # There is a race condition between the generation and the instance object
8466
    # creation, which means that we know the mac is valid now, but we're not
8467
    # sure it will be when we actually add the instance. If things go bad
8468
    # adding the instance will abort because of a duplicate mac, and the
8469
    # creation job will fail.
8470
    for nic in self.nics:
8471
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8472
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
8473

    
8474
    #### allocator run
8475

    
8476
    if self.op.iallocator is not None:
8477
      self._RunAllocator()
8478

    
8479
    #### node related checks
8480

    
8481
    # check primary node
8482
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
8483
    assert self.pnode is not None, \
8484
      "Cannot retrieve locked node %s" % self.op.pnode
8485
    if pnode.offline:
8486
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
8487
                                 pnode.name, errors.ECODE_STATE)
8488
    if pnode.drained:
8489
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
8490
                                 pnode.name, errors.ECODE_STATE)
8491
    if not pnode.vm_capable:
8492
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
8493
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
8494

    
8495
    self.secondaries = []
8496

    
8497
    # mirror node verification
8498
    if self.op.disk_template in constants.DTS_INT_MIRROR:
8499
      if self.op.snode == pnode.name:
8500
        raise errors.OpPrereqError("The secondary node cannot be the"
8501
                                   " primary node", errors.ECODE_INVAL)
8502
      _CheckNodeOnline(self, self.op.snode)
8503
      _CheckNodeNotDrained(self, self.op.snode)
8504
      _CheckNodeVmCapable(self, self.op.snode)
8505
      self.secondaries.append(self.op.snode)
8506

    
8507
    nodenames = [pnode.name] + self.secondaries
8508

    
8509
    if not self.adopt_disks:
8510
      # Check lv size requirements, if not adopting
8511
      req_sizes = _ComputeDiskSizePerVG(self.op.disk_template, self.disks)
8512
      _CheckNodesFreeDiskPerVG(self, nodenames, req_sizes)
8513

    
8514
    elif self.op.disk_template == constants.DT_PLAIN: # Check the adoption data
8515
      all_lvs = set(["%s/%s" % (disk[constants.IDISK_VG],
8516
                                disk[constants.IDISK_ADOPT])
8517
                     for disk in self.disks])
8518
      if len(all_lvs) != len(self.disks):
8519
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
8520
                                   errors.ECODE_INVAL)
8521
      for lv_name in all_lvs:
8522
        try:
8523
          # FIXME: lv_name here is "vg/lv" need to ensure that other calls
8524
          # to ReserveLV uses the same syntax
8525
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
8526
        except errors.ReservationError:
8527
          raise errors.OpPrereqError("LV named %s used by another instance" %
8528
                                     lv_name, errors.ECODE_NOTUNIQUE)
8529

    
8530
      vg_names = self.rpc.call_vg_list([pnode.name])[pnode.name]
8531
      vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
8532

    
8533
      node_lvs = self.rpc.call_lv_list([pnode.name],
8534
                                       vg_names.payload.keys())[pnode.name]
8535
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
8536
      node_lvs = node_lvs.payload
8537

    
8538
      delta = all_lvs.difference(node_lvs.keys())
8539
      if delta:
8540
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
8541
                                   utils.CommaJoin(delta),
8542
                                   errors.ECODE_INVAL)
8543
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
8544
      if online_lvs:
8545
        raise errors.OpPrereqError("Online logical volumes found, cannot"
8546
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
8547
                                   errors.ECODE_STATE)
8548
      # update the size of disk based on what is found
8549
      for dsk in self.disks:
8550
        dsk[constants.IDISK_SIZE] = \
8551
          int(float(node_lvs["%s/%s" % (dsk[constants.IDISK_VG],
8552
                                        dsk[constants.IDISK_ADOPT])][0]))
8553

    
8554
    elif self.op.disk_template == constants.DT_BLOCK:
8555
      # Normalize and de-duplicate device paths
8556
      all_disks = set([os.path.abspath(disk[constants.IDISK_ADOPT])
8557
                       for disk in self.disks])
8558
      if len(all_disks) != len(self.disks):
8559
        raise errors.OpPrereqError("Duplicate disk names given for adoption",
8560
                                   errors.ECODE_INVAL)
8561
      baddisks = [d for d in all_disks
8562
                  if not d.startswith(constants.ADOPTABLE_BLOCKDEV_ROOT)]
8563
      if baddisks:
8564
        raise errors.OpPrereqError("Device node(s) %s lie outside %s and"
8565
                                   " cannot be adopted" %
8566
                                   (", ".join(baddisks),
8567
                                    constants.ADOPTABLE_BLOCKDEV_ROOT),
8568
                                   errors.ECODE_INVAL)
8569

    
8570
      node_disks = self.rpc.call_bdev_sizes([pnode.name],
8571
                                            list(all_disks))[pnode.name]
8572
      node_disks.Raise("Cannot get block device information from node %s" %
8573
                       pnode.name)
8574
      node_disks = node_disks.payload
8575
      delta = all_disks.difference(node_disks.keys())
8576
      if delta:
8577
        raise errors.OpPrereqError("Missing block device(s): %s" %
8578
                                   utils.CommaJoin(delta),
8579
                                   errors.ECODE_INVAL)
8580
      for dsk in self.disks:
8581
        dsk[constants.IDISK_SIZE] = \
8582
          int(float(node_disks[dsk[constants.IDISK_ADOPT]]))
8583

    
8584
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
8585

    
8586
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
8587
    # check OS parameters (remotely)
8588
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
8589

    
8590
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
8591

    
8592
    # memory check on primary node
8593
    if self.op.start:
8594
      _CheckNodeFreeMemory(self, self.pnode.name,
8595
                           "creating instance %s" % self.op.instance_name,
8596
                           self.be_full[constants.BE_MEMORY],
8597
                           self.op.hypervisor)
8598

    
8599
    self.dry_run_result = list(nodenames)
8600

    
8601
  def Exec(self, feedback_fn):
8602
    """Create and add the instance to the cluster.
8603

8604
    """
8605
    instance = self.op.instance_name
8606
    pnode_name = self.pnode.name
8607

    
8608
    ht_kind = self.op.hypervisor
8609
    if ht_kind in constants.HTS_REQ_PORT:
8610
      network_port = self.cfg.AllocatePort()
8611
    else:
8612
      network_port = None
8613

    
8614
    disks = _GenerateDiskTemplate(self,
8615
                                  self.op.disk_template,
8616
                                  instance, pnode_name,
8617
                                  self.secondaries,
8618
                                  self.disks,
8619
                                  self.instance_file_storage_dir,
8620
                                  self.op.file_driver,
8621
                                  0,
8622
                                  feedback_fn)
8623

    
8624
    iobj = objects.Instance(name=instance, os=self.op.os_type,
8625
                            primary_node=pnode_name,
8626
                            nics=self.nics, disks=disks,
8627
                            disk_template=self.op.disk_template,
8628
                            admin_up=False,
8629
                            network_port=network_port,
8630
                            beparams=self.op.beparams,
8631
                            hvparams=self.op.hvparams,
8632
                            hypervisor=self.op.hypervisor,
8633
                            osparams=self.op.osparams,
8634
                            )
8635

    
8636
    if self.op.tags:
8637
      for tag in self.op.tags:
8638
        iobj.AddTag(tag)
8639

    
8640
    if self.adopt_disks:
8641
      if self.op.disk_template == constants.DT_PLAIN:
8642
        # rename LVs to the newly-generated names; we need to construct
8643
        # 'fake' LV disks with the old data, plus the new unique_id
8644
        tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
8645
        rename_to = []
8646
        for t_dsk, a_dsk in zip (tmp_disks, self.disks):
8647
          rename_to.append(t_dsk.logical_id)
8648
          t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk[constants.IDISK_ADOPT])
8649
          self.cfg.SetDiskID(t_dsk, pnode_name)
8650
        result = self.rpc.call_blockdev_rename(pnode_name,
8651
                                               zip(tmp_disks, rename_to))
8652
        result.Raise("Failed to rename adoped LVs")
8653
    else:
8654
      feedback_fn("* creating instance disks...")
8655
      try:
8656
        _CreateDisks(self, iobj)
8657
      except errors.OpExecError:
8658
        self.LogWarning("Device creation failed, reverting...")
8659
        try:
8660
          _RemoveDisks(self, iobj)
8661
        finally:
8662
          self.cfg.ReleaseDRBDMinors(instance)
8663
          raise
8664

    
8665
    feedback_fn("adding instance %s to cluster config" % instance)
8666

    
8667
    self.cfg.AddInstance(iobj, self.proc.GetECId())
8668

    
8669
    # Declare that we don't want to remove the instance lock anymore, as we've
8670
    # added the instance to the config
8671
    del self.remove_locks[locking.LEVEL_INSTANCE]
8672

    
8673
    if self.op.mode == constants.INSTANCE_IMPORT:
8674
      # Release unused nodes
8675
      _ReleaseLocks(self, locking.LEVEL_NODE, keep=[self.op.src_node])
8676
    else:
8677
      # Release all nodes
8678
      _ReleaseLocks(self, locking.LEVEL_NODE)
8679

    
8680
    disk_abort = False
8681
    if not self.adopt_disks and self.cfg.GetClusterInfo().prealloc_wipe_disks:
8682
      feedback_fn("* wiping instance disks...")
8683
      try:
8684
        _WipeDisks(self, iobj)
8685
      except errors.OpExecError, err:
8686
        logging.exception("Wiping disks failed")
8687
        self.LogWarning("Wiping instance disks failed (%s)", err)
8688
        disk_abort = True
8689

    
8690
    if disk_abort:
8691
      # Something is already wrong with the disks, don't do anything else
8692
      pass
8693
    elif self.op.wait_for_sync:
8694
      disk_abort = not _WaitForSync(self, iobj)
8695
    elif iobj.disk_template in constants.DTS_INT_MIRROR:
8696
      # make sure the disks are not degraded (still sync-ing is ok)
8697
      time.sleep(15)
8698
      feedback_fn("* checking mirrors status")
8699
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
8700
    else:
8701
      disk_abort = False
8702

    
8703
    if disk_abort:
8704
      _RemoveDisks(self, iobj)
8705
      self.cfg.RemoveInstance(iobj.name)
8706
      # Make sure the instance lock gets removed
8707
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
8708
      raise errors.OpExecError("There are some degraded disks for"
8709
                               " this instance")
8710

    
8711
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
8712
      if self.op.mode == constants.INSTANCE_CREATE:
8713
        if not self.op.no_install:
8714
          feedback_fn("* running the instance OS create scripts...")
8715
          # FIXME: pass debug option from opcode to backend
8716
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
8717
                                                 self.op.debug_level)
8718
          result.Raise("Could not add os for instance %s"
8719
                       " on node %s" % (instance, pnode_name))
8720

    
8721
      elif self.op.mode == constants.INSTANCE_IMPORT:
8722
        feedback_fn("* running the instance OS import scripts...")
8723

    
8724
        transfers = []
8725

    
8726
        for idx, image in enumerate(self.src_images):
8727
          if not image:
8728
            continue
8729

    
8730
          # FIXME: pass debug option from opcode to backend
8731
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
8732
                                             constants.IEIO_FILE, (image, ),
8733
                                             constants.IEIO_SCRIPT,
8734
                                             (iobj.disks[idx], idx),
8735
                                             None)
8736
          transfers.append(dt)
8737

    
8738
        import_result = \
8739
          masterd.instance.TransferInstanceData(self, feedback_fn,
8740
                                                self.op.src_node, pnode_name,
8741
                                                self.pnode.secondary_ip,
8742
                                                iobj, transfers)
8743
        if not compat.all(import_result):
8744
          self.LogWarning("Some disks for instance %s on node %s were not"
8745
                          " imported successfully" % (instance, pnode_name))
8746

    
8747
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
8748
        feedback_fn("* preparing remote import...")
8749
        # The source cluster will stop the instance before attempting to make a
8750
        # connection. In some cases stopping an instance can take a long time,
8751
        # hence the shutdown timeout is added to the connection timeout.
8752
        connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
8753
                           self.op.source_shutdown_timeout)
8754
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
8755

    
8756
        assert iobj.primary_node == self.pnode.name
8757
        disk_results = \
8758
          masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
8759
                                        self.source_x509_ca,
8760
                                        self._cds, timeouts)
8761
        if not compat.all(disk_results):
8762
          # TODO: Should the instance still be started, even if some disks
8763
          # failed to import (valid for local imports, too)?
8764
          self.LogWarning("Some disks for instance %s on node %s were not"
8765
                          " imported successfully" % (instance, pnode_name))
8766

    
8767
        # Run rename script on newly imported instance
8768
        assert iobj.name == instance
8769
        feedback_fn("Running rename script for %s" % instance)
8770
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
8771
                                                   self.source_instance_name,
8772
                                                   self.op.debug_level)
8773
        if result.fail_msg:
8774
          self.LogWarning("Failed to run rename script for %s on node"
8775
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
8776

    
8777
      else:
8778
        # also checked in the prereq part
8779
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
8780
                                     % self.op.mode)
8781

    
8782
    if self.op.start:
8783
      iobj.admin_up = True
8784
      self.cfg.Update(iobj, feedback_fn)
8785
      logging.info("Starting instance %s on node %s", instance, pnode_name)
8786
      feedback_fn("* starting instance...")
8787
      result = self.rpc.call_instance_start(pnode_name, iobj,
8788
                                            None, None, False)
8789
      result.Raise("Could not start instance")
8790

    
8791
    return list(iobj.all_nodes)
8792

    
8793

    
8794
class LUInstanceConsole(NoHooksLU):
8795
  """Connect to an instance's console.
8796

8797
  This is somewhat special in that it returns the command line that
8798
  you need to run on the master node in order to connect to the
8799
  console.
8800

8801
  """
8802
  REQ_BGL = False
8803

    
8804
  def ExpandNames(self):
8805
    self._ExpandAndLockInstance()
8806

    
8807
  def CheckPrereq(self):
8808
    """Check prerequisites.
8809

8810
    This checks that the instance is in the cluster.
8811

8812
    """
8813
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8814
    assert self.instance is not None, \
8815
      "Cannot retrieve locked instance %s" % self.op.instance_name
8816
    _CheckNodeOnline(self, self.instance.primary_node)
8817

    
8818
  def Exec(self, feedback_fn):
8819
    """Connect to the console of an instance
8820

8821
    """
8822
    instance = self.instance
8823
    node = instance.primary_node
8824

    
8825
    node_insts = self.rpc.call_instance_list([node],
8826
                                             [instance.hypervisor])[node]
8827
    node_insts.Raise("Can't get node information from %s" % node)
8828

    
8829
    if instance.name not in node_insts.payload:
8830
      if instance.admin_up:
8831
        state = constants.INSTST_ERRORDOWN
8832
      else:
8833
        state = constants.INSTST_ADMINDOWN
8834
      raise errors.OpExecError("Instance %s is not running (state %s)" %
8835
                               (instance.name, state))
8836

    
8837
    logging.debug("Connecting to console of %s on %s", instance.name, node)
8838

    
8839
    return _GetInstanceConsole(self.cfg.GetClusterInfo(), instance)
8840

    
8841

    
8842
def _GetInstanceConsole(cluster, instance):
8843
  """Returns console information for an instance.
8844

8845
  @type cluster: L{objects.Cluster}
8846
  @type instance: L{objects.Instance}
8847
  @rtype: dict
8848

8849
  """
8850
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
8851
  # beparams and hvparams are passed separately, to avoid editing the
8852
  # instance and then saving the defaults in the instance itself.
8853
  hvparams = cluster.FillHV(instance)
8854
  beparams = cluster.FillBE(instance)
8855
  console = hyper.GetInstanceConsole(instance, hvparams, beparams)
8856

    
8857
  assert console.instance == instance.name
8858
  assert console.Validate()
8859

    
8860
  return console.ToDict()
8861

    
8862

    
8863
class LUInstanceReplaceDisks(LogicalUnit):
8864
  """Replace the disks of an instance.
8865

8866
  """
8867
  HPATH = "mirrors-replace"
8868
  HTYPE = constants.HTYPE_INSTANCE
8869
  REQ_BGL = False
8870

    
8871
  def CheckArguments(self):
8872
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
8873
                                  self.op.iallocator)
8874

    
8875
  def ExpandNames(self):
8876
    self._ExpandAndLockInstance()
8877

    
8878
    assert locking.LEVEL_NODE not in self.needed_locks
8879
    assert locking.LEVEL_NODEGROUP not in self.needed_locks
8880

    
8881
    assert self.op.iallocator is None or self.op.remote_node is None, \
8882
      "Conflicting options"
8883

    
8884
    if self.op.remote_node is not None:
8885
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8886

    
8887
      # Warning: do not remove the locking of the new secondary here
8888
      # unless DRBD8.AddChildren is changed to work in parallel;
8889
      # currently it doesn't since parallel invocations of
8890
      # FindUnusedMinor will conflict
8891
      self.needed_locks[locking.LEVEL_NODE] = [self.op.remote_node]
8892
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
8893
    else:
8894
      self.needed_locks[locking.LEVEL_NODE] = []
8895
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8896

    
8897
      if self.op.iallocator is not None:
8898
        # iallocator will select a new node in the same group
8899
        self.needed_locks[locking.LEVEL_NODEGROUP] = []
8900

    
8901
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
8902
                                   self.op.iallocator, self.op.remote_node,
8903
                                   self.op.disks, False, self.op.early_release)
8904

    
8905
    self.tasklets = [self.replacer]
8906

    
8907
  def DeclareLocks(self, level):
8908
    if level == locking.LEVEL_NODEGROUP:
8909
      assert self.op.remote_node is None
8910
      assert self.op.iallocator is not None
8911
      assert not self.needed_locks[locking.LEVEL_NODEGROUP]
8912

    
8913
      self.share_locks[locking.LEVEL_NODEGROUP] = 1
8914
      self.needed_locks[locking.LEVEL_NODEGROUP] = \
8915
        self.cfg.GetInstanceNodeGroups(self.op.instance_name)
8916

    
8917
    elif level == locking.LEVEL_NODE:
8918
      if self.op.iallocator is not None:
8919
        assert self.op.remote_node is None
8920
        assert not self.needed_locks[locking.LEVEL_NODE]
8921

    
8922
        # Lock member nodes of all locked groups
8923
        self.needed_locks[locking.LEVEL_NODE] = [node_name
8924
          for group_uuid in self.glm.list_owned(locking.LEVEL_NODEGROUP)
8925
          for node_name in self.cfg.GetNodeGroup(group_uuid).members]
8926
      else:
8927
        self._LockInstancesNodes()
8928

    
8929
  def BuildHooksEnv(self):
8930
    """Build hooks env.
8931

8932
    This runs on the master, the primary and all the secondaries.
8933

8934
    """
8935
    instance = self.replacer.instance
8936
    env = {
8937
      "MODE": self.op.mode,
8938
      "NEW_SECONDARY": self.op.remote_node,
8939
      "OLD_SECONDARY": instance.secondary_nodes[0],
8940
      }
8941
    env.update(_BuildInstanceHookEnvByObject(self, instance))
8942
    return env
8943

    
8944
  def BuildHooksNodes(self):
8945
    """Build hooks nodes.
8946

8947
    """
8948
    instance = self.replacer.instance
8949
    nl = [
8950
      self.cfg.GetMasterNode(),
8951
      instance.primary_node,
8952
      ]
8953
    if self.op.remote_node is not None:
8954
      nl.append(self.op.remote_node)
8955
    return nl, nl
8956

    
8957
  def CheckPrereq(self):
8958
    """Check prerequisites.
8959

8960
    """
8961
    assert (self.glm.is_owned(locking.LEVEL_NODEGROUP) or
8962
            self.op.iallocator is None)
8963

    
8964
    owned_groups = self.glm.list_owned(locking.LEVEL_NODEGROUP)
8965
    if owned_groups:
8966
      groups = self.cfg.GetInstanceNodeGroups(self.op.instance_name)
8967
      if owned_groups != groups:
8968
        raise errors.OpExecError("Node groups used by instance '%s' changed"
8969
                                 " since lock was acquired, current list is %r,"
8970
                                 " used to be '%s'" %
8971
                                 (self.op.instance_name,
8972
                                  utils.CommaJoin(groups),
8973
                                  utils.CommaJoin(owned_groups)))
8974

    
8975
    return LogicalUnit.CheckPrereq(self)
8976

    
8977

    
8978
class TLReplaceDisks(Tasklet):
8979
  """Replaces disks for an instance.
8980

8981
  Note: Locking is not within the scope of this class.
8982

8983
  """
8984
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
8985
               disks, delay_iallocator, early_release):
8986
    """Initializes this class.
8987

8988
    """
8989
    Tasklet.__init__(self, lu)
8990

    
8991
    # Parameters
8992
    self.instance_name = instance_name
8993
    self.mode = mode
8994
    self.iallocator_name = iallocator_name
8995
    self.remote_node = remote_node
8996
    self.disks = disks
8997
    self.delay_iallocator = delay_iallocator
8998
    self.early_release = early_release
8999

    
9000
    # Runtime data
9001
    self.instance = None
9002
    self.new_node = None
9003
    self.target_node = None
9004
    self.other_node = None
9005
    self.remote_node_info = None
9006
    self.node_secondary_ip = None
9007

    
9008
  @staticmethod
9009
  def CheckArguments(mode, remote_node, iallocator):
9010
    """Helper function for users of this class.
9011

9012
    """
9013
    # check for valid parameter combination
9014
    if mode == constants.REPLACE_DISK_CHG:
9015
      if remote_node is None and iallocator is None:
9016
        raise errors.OpPrereqError("When changing the secondary either an"
9017
                                   " iallocator script must be used or the"
9018
                                   " new node given", errors.ECODE_INVAL)
9019

    
9020
      if remote_node is not None and iallocator is not None:
9021
        raise errors.OpPrereqError("Give either the iallocator or the new"
9022
                                   " secondary, not both", errors.ECODE_INVAL)
9023

    
9024
    elif remote_node is not None or iallocator is not None:
9025
      # Not replacing the secondary
9026
      raise errors.OpPrereqError("The iallocator and new node options can"
9027
                                 " only be used when changing the"
9028
                                 " secondary node", errors.ECODE_INVAL)
9029

    
9030
  @staticmethod
9031
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
9032
    """Compute a new secondary node using an IAllocator.
9033

9034
    """
9035
    ial = IAllocator(lu.cfg, lu.rpc,
9036
                     mode=constants.IALLOCATOR_MODE_RELOC,
9037
                     name=instance_name,
9038
                     relocate_from=relocate_from)
9039

    
9040
    ial.Run(iallocator_name)
9041

    
9042
    if not ial.success:
9043
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
9044
                                 " %s" % (iallocator_name, ial.info),
9045
                                 errors.ECODE_NORES)
9046

    
9047
    if len(ial.result) != ial.required_nodes:
9048
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
9049
                                 " of nodes (%s), required %s" %
9050
                                 (iallocator_name,
9051
                                  len(ial.result), ial.required_nodes),
9052
                                 errors.ECODE_FAULT)
9053

    
9054
    remote_node_name = ial.result[0]
9055

    
9056
    lu.LogInfo("Selected new secondary for instance '%s': %s",
9057
               instance_name, remote_node_name)
9058

    
9059
    return remote_node_name
9060

    
9061
  def _FindFaultyDisks(self, node_name):
9062
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
9063
                                    node_name, True)
9064

    
9065
  def _CheckDisksActivated(self, instance):
9066
    """Checks if the instance disks are activated.
9067

9068
    @param instance: The instance to check disks
9069
    @return: True if they are activated, False otherwise
9070

9071
    """
9072
    nodes = instance.all_nodes
9073

    
9074
    for idx, dev in enumerate(instance.disks):
9075
      for node in nodes:
9076
        self.lu.LogInfo("Checking disk/%d on %s", idx, node)
9077
        self.cfg.SetDiskID(dev, node)
9078

    
9079
        result = self.rpc.call_blockdev_find(node, dev)
9080

    
9081
        if result.offline:
9082
          continue
9083
        elif result.fail_msg or not result.payload:
9084
          return False
9085

    
9086
    return True
9087

    
9088
  def CheckPrereq(self):
9089
    """Check prerequisites.
9090

9091
    This checks that the instance is in the cluster.
9092

9093
    """
9094
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
9095
    assert instance is not None, \
9096
      "Cannot retrieve locked instance %s" % self.instance_name
9097

    
9098
    if instance.disk_template != constants.DT_DRBD8:
9099
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
9100
                                 " instances", errors.ECODE_INVAL)
9101

    
9102
    if len(instance.secondary_nodes) != 1:
9103
      raise errors.OpPrereqError("The instance has a strange layout,"
9104
                                 " expected one secondary but found %d" %
9105
                                 len(instance.secondary_nodes),
9106
                                 errors.ECODE_FAULT)
9107

    
9108
    if not self.delay_iallocator:
9109
      self._CheckPrereq2()
9110

    
9111
  def _CheckPrereq2(self):
9112
    """Check prerequisites, second part.
9113

9114
    This function should always be part of CheckPrereq. It was separated and is
9115
    now called from Exec because during node evacuation iallocator was only
9116
    called with an unmodified cluster model, not taking planned changes into
9117
    account.
9118

9119
    """
9120
    instance = self.instance
9121
    secondary_node = instance.secondary_nodes[0]
9122

    
9123
    if self.iallocator_name is None:
9124
      remote_node = self.remote_node
9125
    else:
9126
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
9127
                                       instance.name, instance.secondary_nodes)
9128

    
9129
    if remote_node is None:
9130
      self.remote_node_info = None
9131
    else:
9132
      assert remote_node in self.lu.glm.list_owned(locking.LEVEL_NODE), \
9133
             "Remote node '%s' is not locked" % remote_node
9134

    
9135
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
9136
      assert self.remote_node_info is not None, \
9137
        "Cannot retrieve locked node %s" % remote_node
9138

    
9139
    if remote_node == self.instance.primary_node:
9140
      raise errors.OpPrereqError("The specified node is the primary node of"
9141
                                 " the instance", errors.ECODE_INVAL)
9142

    
9143
    if remote_node == secondary_node:
9144
      raise errors.OpPrereqError("The specified node is already the"
9145
                                 " secondary node of the instance",
9146
                                 errors.ECODE_INVAL)
9147

    
9148
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
9149
                                    constants.REPLACE_DISK_CHG):
9150
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
9151
                                 errors.ECODE_INVAL)
9152

    
9153
    if self.mode == constants.REPLACE_DISK_AUTO:
9154
      if not self._CheckDisksActivated(instance):
9155
        raise errors.OpPrereqError("Please run activate-disks on instance %s"
9156
                                   " first" % self.instance_name,
9157
                                   errors.ECODE_STATE)
9158
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
9159
      faulty_secondary = self._FindFaultyDisks(secondary_node)
9160

    
9161
      if faulty_primary and faulty_secondary:
9162
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
9163
                                   " one node and can not be repaired"
9164
                                   " automatically" % self.instance_name,
9165
                                   errors.ECODE_STATE)
9166

    
9167
      if faulty_primary:
9168
        self.disks = faulty_primary
9169
        self.target_node = instance.primary_node
9170
        self.other_node = secondary_node
9171
        check_nodes = [self.target_node, self.other_node]
9172
      elif faulty_secondary:
9173
        self.disks = faulty_secondary
9174
        self.target_node = secondary_node
9175
        self.other_node = instance.primary_node
9176
        check_nodes = [self.target_node, self.other_node]
9177
      else:
9178
        self.disks = []
9179
        check_nodes = []
9180

    
9181
    else:
9182
      # Non-automatic modes
9183
      if self.mode == constants.REPLACE_DISK_PRI:
9184
        self.target_node = instance.primary_node
9185
        self.other_node = secondary_node
9186
        check_nodes = [self.target_node, self.other_node]
9187

    
9188
      elif self.mode == constants.REPLACE_DISK_SEC:
9189
        self.target_node = secondary_node
9190
        self.other_node = instance.primary_node
9191
        check_nodes = [self.target_node, self.other_node]
9192

    
9193
      elif self.mode == constants.REPLACE_DISK_CHG:
9194
        self.new_node = remote_node
9195
        self.other_node = instance.primary_node
9196
        self.target_node = secondary_node
9197
        check_nodes = [self.new_node, self.other_node]
9198

    
9199
        _CheckNodeNotDrained(self.lu, remote_node)
9200
        _CheckNodeVmCapable(self.lu, remote_node)
9201

    
9202
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
9203
        assert old_node_info is not None
9204
        if old_node_info.offline and not self.early_release:
9205
          # doesn't make sense to delay the release
9206
          self.early_release = True
9207
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
9208
                          " early-release mode", secondary_node)
9209

    
9210
      else:
9211
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
9212
                                     self.mode)
9213

    
9214
      # If not specified all disks should be replaced
9215
      if not self.disks:
9216
        self.disks = range(len(self.instance.disks))
9217

    
9218
    for node in check_nodes:
9219
      _CheckNodeOnline(self.lu, node)
9220

    
9221
    touched_nodes = frozenset(node_name for node_name in [self.new_node,
9222
                                                          self.other_node,
9223
                                                          self.target_node]
9224
                              if node_name is not None)
9225

    
9226
    # Release unneeded node locks
9227
    _ReleaseLocks(self.lu, locking.LEVEL_NODE, keep=touched_nodes)
9228

    
9229
    # Release any owned node group
9230
    if self.lu.glm.is_owned(locking.LEVEL_NODEGROUP):
9231
      _ReleaseLocks(self.lu, locking.LEVEL_NODEGROUP)
9232

    
9233
    # Check whether disks are valid
9234
    for disk_idx in self.disks:
9235
      instance.FindDisk(disk_idx)
9236

    
9237
    # Get secondary node IP addresses
9238
    self.node_secondary_ip = \
9239
      dict((node_name, self.cfg.GetNodeInfo(node_name).secondary_ip)
9240
           for node_name in touched_nodes)
9241

    
9242
  def Exec(self, feedback_fn):
9243
    """Execute disk replacement.
9244

9245
    This dispatches the disk replacement to the appropriate handler.
9246

9247
    """
9248
    if self.delay_iallocator:
9249
      self._CheckPrereq2()
9250

    
9251
    if __debug__:
9252
      # Verify owned locks before starting operation
9253
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_NODE)
9254
      assert set(owned_locks) == set(self.node_secondary_ip), \
9255
          ("Incorrect node locks, owning %s, expected %s" %
9256
           (owned_locks, self.node_secondary_ip.keys()))
9257

    
9258
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_INSTANCE)
9259
      assert list(owned_locks) == [self.instance_name], \
9260
          "Instance '%s' not locked" % self.instance_name
9261

    
9262
      assert not self.lu.glm.is_owned(locking.LEVEL_NODEGROUP), \
9263
          "Should not own any node group lock at this point"
9264

    
9265
    if not self.disks:
9266
      feedback_fn("No disks need replacement")
9267
      return
9268

    
9269
    feedback_fn("Replacing disk(s) %s for %s" %
9270
                (utils.CommaJoin(self.disks), self.instance.name))
9271

    
9272
    activate_disks = (not self.instance.admin_up)
9273

    
9274
    # Activate the instance disks if we're replacing them on a down instance
9275
    if activate_disks:
9276
      _StartInstanceDisks(self.lu, self.instance, True)
9277

    
9278
    try:
9279
      # Should we replace the secondary node?
9280
      if self.new_node is not None:
9281
        fn = self._ExecDrbd8Secondary
9282
      else:
9283
        fn = self._ExecDrbd8DiskOnly
9284

    
9285
      result = fn(feedback_fn)
9286
    finally:
9287
      # Deactivate the instance disks if we're replacing them on a
9288
      # down instance
9289
      if activate_disks:
9290
        _SafeShutdownInstanceDisks(self.lu, self.instance)
9291

    
9292
    if __debug__:
9293
      # Verify owned locks
9294
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_NODE)
9295
      nodes = frozenset(self.node_secondary_ip)
9296
      assert ((self.early_release and not owned_locks) or
9297
              (not self.early_release and not (set(owned_locks) - nodes))), \
9298
        ("Not owning the correct locks, early_release=%s, owned=%r,"
9299
         " nodes=%r" % (self.early_release, owned_locks, nodes))
9300

    
9301
    return result
9302

    
9303
  def _CheckVolumeGroup(self, nodes):
9304
    self.lu.LogInfo("Checking volume groups")
9305

    
9306
    vgname = self.cfg.GetVGName()
9307

    
9308
    # Make sure volume group exists on all involved nodes
9309
    results = self.rpc.call_vg_list(nodes)
9310
    if not results:
9311
      raise errors.OpExecError("Can't list volume groups on the nodes")
9312

    
9313
    for node in nodes:
9314
      res = results[node]
9315
      res.Raise("Error checking node %s" % node)
9316
      if vgname not in res.payload:
9317
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
9318
                                 (vgname, node))
9319

    
9320
  def _CheckDisksExistence(self, nodes):
9321
    # Check disk existence
9322
    for idx, dev in enumerate(self.instance.disks):
9323
      if idx not in self.disks:
9324
        continue
9325

    
9326
      for node in nodes:
9327
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
9328
        self.cfg.SetDiskID(dev, node)
9329

    
9330
        result = self.rpc.call_blockdev_find(node, dev)
9331

    
9332
        msg = result.fail_msg
9333
        if msg or not result.payload:
9334
          if not msg:
9335
            msg = "disk not found"
9336
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
9337
                                   (idx, node, msg))
9338

    
9339
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
9340
    for idx, dev in enumerate(self.instance.disks):
9341
      if idx not in self.disks:
9342
        continue
9343

    
9344
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
9345
                      (idx, node_name))
9346

    
9347
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
9348
                                   ldisk=ldisk):
9349
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
9350
                                 " replace disks for instance %s" %
9351
                                 (node_name, self.instance.name))
9352

    
9353
  def _CreateNewStorage(self, node_name):
9354
    """Create new storage on the primary or secondary node.
9355

9356
    This is only used for same-node replaces, not for changing the
9357
    secondary node, hence we don't want to modify the existing disk.
9358

9359
    """
9360
    iv_names = {}
9361

    
9362
    for idx, dev in enumerate(self.instance.disks):
9363
      if idx not in self.disks:
9364
        continue
9365

    
9366
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
9367

    
9368
      self.cfg.SetDiskID(dev, node_name)
9369

    
9370
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
9371
      names = _GenerateUniqueNames(self.lu, lv_names)
9372

    
9373
      vg_data = dev.children[0].logical_id[0]
9374
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
9375
                             logical_id=(vg_data, names[0]))
9376
      vg_meta = dev.children[1].logical_id[0]
9377
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
9378
                             logical_id=(vg_meta, names[1]))
9379

    
9380
      new_lvs = [lv_data, lv_meta]
9381
      old_lvs = [child.Copy() for child in dev.children]
9382
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
9383

    
9384
      # we pass force_create=True to force the LVM creation
9385
      for new_lv in new_lvs:
9386
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
9387
                        _GetInstanceInfoText(self.instance), False)
9388

    
9389
    return iv_names
9390

    
9391
  def _CheckDevices(self, node_name, iv_names):
9392
    for name, (dev, _, _) in iv_names.iteritems():
9393
      self.cfg.SetDiskID(dev, node_name)
9394

    
9395
      result = self.rpc.call_blockdev_find(node_name, dev)
9396

    
9397
      msg = result.fail_msg
9398
      if msg or not result.payload:
9399
        if not msg:
9400
          msg = "disk not found"
9401
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
9402
                                 (name, msg))
9403

    
9404
      if result.payload.is_degraded:
9405
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
9406

    
9407
  def _RemoveOldStorage(self, node_name, iv_names):
9408
    for name, (_, old_lvs, _) in iv_names.iteritems():
9409
      self.lu.LogInfo("Remove logical volumes for %s" % name)
9410

    
9411
      for lv in old_lvs:
9412
        self.cfg.SetDiskID(lv, node_name)
9413

    
9414
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
9415
        if msg:
9416
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
9417
                             hint="remove unused LVs manually")
9418

    
9419
  def _ExecDrbd8DiskOnly(self, feedback_fn): # pylint: disable-msg=W0613
9420
    """Replace a disk on the primary or secondary for DRBD 8.
9421

9422
    The algorithm for replace is quite complicated:
9423

9424
      1. for each disk to be replaced:
9425

9426
        1. create new LVs on the target node with unique names
9427
        1. detach old LVs from the drbd device
9428
        1. rename old LVs to name_replaced.<time_t>
9429
        1. rename new LVs to old LVs
9430
        1. attach the new LVs (with the old names now) to the drbd device
9431

9432
      1. wait for sync across all devices
9433

9434
      1. for each modified disk:
9435

9436
        1. remove old LVs (which have the name name_replaces.<time_t>)
9437

9438
    Failures are not very well handled.
9439

9440
    """
9441
    steps_total = 6
9442

    
9443
    # Step: check device activation
9444
    self.lu.LogStep(1, steps_total, "Check device existence")
9445
    self._CheckDisksExistence([self.other_node, self.target_node])
9446
    self._CheckVolumeGroup([self.target_node, self.other_node])
9447

    
9448
    # Step: check other node consistency
9449
    self.lu.LogStep(2, steps_total, "Check peer consistency")
9450
    self._CheckDisksConsistency(self.other_node,
9451
                                self.other_node == self.instance.primary_node,
9452
                                False)
9453

    
9454
    # Step: create new storage
9455
    self.lu.LogStep(3, steps_total, "Allocate new storage")
9456
    iv_names = self._CreateNewStorage(self.target_node)
9457

    
9458
    # Step: for each lv, detach+rename*2+attach
9459
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
9460
    for dev, old_lvs, new_lvs in iv_names.itervalues():
9461
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
9462

    
9463
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
9464
                                                     old_lvs)
9465
      result.Raise("Can't detach drbd from local storage on node"
9466
                   " %s for device %s" % (self.target_node, dev.iv_name))
9467
      #dev.children = []
9468
      #cfg.Update(instance)
9469

    
9470
      # ok, we created the new LVs, so now we know we have the needed
9471
      # storage; as such, we proceed on the target node to rename
9472
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
9473
      # using the assumption that logical_id == physical_id (which in
9474
      # turn is the unique_id on that node)
9475

    
9476
      # FIXME(iustin): use a better name for the replaced LVs
9477
      temp_suffix = int(time.time())
9478
      ren_fn = lambda d, suff: (d.physical_id[0],
9479
                                d.physical_id[1] + "_replaced-%s" % suff)
9480

    
9481
      # Build the rename list based on what LVs exist on the node
9482
      rename_old_to_new = []
9483
      for to_ren in old_lvs:
9484
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
9485
        if not result.fail_msg and result.payload:
9486
          # device exists
9487
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
9488

    
9489
      self.lu.LogInfo("Renaming the old LVs on the target node")
9490
      result = self.rpc.call_blockdev_rename(self.target_node,
9491
                                             rename_old_to_new)
9492
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
9493

    
9494
      # Now we rename the new LVs to the old LVs
9495
      self.lu.LogInfo("Renaming the new LVs on the target node")
9496
      rename_new_to_old = [(new, old.physical_id)
9497
                           for old, new in zip(old_lvs, new_lvs)]
9498
      result = self.rpc.call_blockdev_rename(self.target_node,
9499
                                             rename_new_to_old)
9500
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
9501

    
9502
      # Intermediate steps of in memory modifications
9503
      for old, new in zip(old_lvs, new_lvs):
9504
        new.logical_id = old.logical_id
9505
        self.cfg.SetDiskID(new, self.target_node)
9506

    
9507
      # We need to modify old_lvs so that removal later removes the
9508
      # right LVs, not the newly added ones; note that old_lvs is a
9509
      # copy here
9510
      for disk in old_lvs:
9511
        disk.logical_id = ren_fn(disk, temp_suffix)
9512
        self.cfg.SetDiskID(disk, self.target_node)
9513

    
9514
      # Now that the new lvs have the old name, we can add them to the device
9515
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
9516
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
9517
                                                  new_lvs)
9518
      msg = result.fail_msg
9519
      if msg:
9520
        for new_lv in new_lvs:
9521
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
9522
                                               new_lv).fail_msg
9523
          if msg2:
9524
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
9525
                               hint=("cleanup manually the unused logical"
9526
                                     "volumes"))
9527
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
9528

    
9529
    cstep = 5
9530
    if self.early_release:
9531
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9532
      cstep += 1
9533
      self._RemoveOldStorage(self.target_node, iv_names)
9534
      # WARNING: we release both node locks here, do not do other RPCs
9535
      # than WaitForSync to the primary node
9536
      _ReleaseLocks(self.lu, locking.LEVEL_NODE,
9537
                    names=[self.target_node, self.other_node])
9538

    
9539
    # Wait for sync
9540
    # This can fail as the old devices are degraded and _WaitForSync
9541
    # does a combined result over all disks, so we don't check its return value
9542
    self.lu.LogStep(cstep, steps_total, "Sync devices")
9543
    cstep += 1
9544
    _WaitForSync(self.lu, self.instance)
9545

    
9546
    # Check all devices manually
9547
    self._CheckDevices(self.instance.primary_node, iv_names)
9548

    
9549
    # Step: remove old storage
9550
    if not self.early_release:
9551
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9552
      cstep += 1
9553
      self._RemoveOldStorage(self.target_node, iv_names)
9554

    
9555
  def _ExecDrbd8Secondary(self, feedback_fn):
9556
    """Replace the secondary node for DRBD 8.
9557

9558
    The algorithm for replace is quite complicated:
9559
      - for all disks of the instance:
9560
        - create new LVs on the new node with same names
9561
        - shutdown the drbd device on the old secondary
9562
        - disconnect the drbd network on the primary
9563
        - create the drbd device on the new secondary
9564
        - network attach the drbd on the primary, using an artifice:
9565
          the drbd code for Attach() will connect to the network if it
9566
          finds a device which is connected to the good local disks but
9567
          not network enabled
9568
      - wait for sync across all devices
9569
      - remove all disks from the old secondary
9570

9571
    Failures are not very well handled.
9572

9573
    """
9574
    steps_total = 6
9575

    
9576
    # Step: check device activation
9577
    self.lu.LogStep(1, steps_total, "Check device existence")
9578
    self._CheckDisksExistence([self.instance.primary_node])
9579
    self._CheckVolumeGroup([self.instance.primary_node])
9580

    
9581
    # Step: check other node consistency
9582
    self.lu.LogStep(2, steps_total, "Check peer consistency")
9583
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
9584

    
9585
    # Step: create new storage
9586
    self.lu.LogStep(3, steps_total, "Allocate new storage")
9587
    for idx, dev in enumerate(self.instance.disks):
9588
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
9589
                      (self.new_node, idx))
9590
      # we pass force_create=True to force LVM creation
9591
      for new_lv in dev.children:
9592
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
9593
                        _GetInstanceInfoText(self.instance), False)
9594

    
9595
    # Step 4: dbrd minors and drbd setups changes
9596
    # after this, we must manually remove the drbd minors on both the
9597
    # error and the success paths
9598
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
9599
    minors = self.cfg.AllocateDRBDMinor([self.new_node
9600
                                         for dev in self.instance.disks],
9601
                                        self.instance.name)
9602
    logging.debug("Allocated minors %r", minors)
9603

    
9604
    iv_names = {}
9605
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
9606
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
9607
                      (self.new_node, idx))
9608
      # create new devices on new_node; note that we create two IDs:
9609
      # one without port, so the drbd will be activated without
9610
      # networking information on the new node at this stage, and one
9611
      # with network, for the latter activation in step 4
9612
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
9613
      if self.instance.primary_node == o_node1:
9614
        p_minor = o_minor1
9615
      else:
9616
        assert self.instance.primary_node == o_node2, "Three-node instance?"
9617
        p_minor = o_minor2
9618

    
9619
      new_alone_id = (self.instance.primary_node, self.new_node, None,
9620
                      p_minor, new_minor, o_secret)
9621
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
9622
                    p_minor, new_minor, o_secret)
9623

    
9624
      iv_names[idx] = (dev, dev.children, new_net_id)
9625
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
9626
                    new_net_id)
9627
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
9628
                              logical_id=new_alone_id,
9629
                              children=dev.children,
9630
                              size=dev.size)
9631
      try:
9632
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
9633
                              _GetInstanceInfoText(self.instance), False)
9634
      except errors.GenericError:
9635
        self.cfg.ReleaseDRBDMinors(self.instance.name)
9636
        raise
9637

    
9638
    # We have new devices, shutdown the drbd on the old secondary
9639
    for idx, dev in enumerate(self.instance.disks):
9640
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
9641
      self.cfg.SetDiskID(dev, self.target_node)
9642
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
9643
      if msg:
9644
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
9645
                           "node: %s" % (idx, msg),
9646
                           hint=("Please cleanup this device manually as"
9647
                                 " soon as possible"))
9648

    
9649
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
9650
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
9651
                                               self.node_secondary_ip,
9652
                                               self.instance.disks)\
9653
                                              [self.instance.primary_node]
9654

    
9655
    msg = result.fail_msg
9656
    if msg:
9657
      # detaches didn't succeed (unlikely)
9658
      self.cfg.ReleaseDRBDMinors(self.instance.name)
9659
      raise errors.OpExecError("Can't detach the disks from the network on"
9660
                               " old node: %s" % (msg,))
9661

    
9662
    # if we managed to detach at least one, we update all the disks of
9663
    # the instance to point to the new secondary
9664
    self.lu.LogInfo("Updating instance configuration")
9665
    for dev, _, new_logical_id in iv_names.itervalues():
9666
      dev.logical_id = new_logical_id
9667
      self.cfg.SetDiskID(dev, self.instance.primary_node)
9668

    
9669
    self.cfg.Update(self.instance, feedback_fn)
9670

    
9671
    # and now perform the drbd attach
9672
    self.lu.LogInfo("Attaching primary drbds to new secondary"
9673
                    " (standalone => connected)")
9674
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
9675
                                            self.new_node],
9676
                                           self.node_secondary_ip,
9677
                                           self.instance.disks,
9678
                                           self.instance.name,
9679
                                           False)
9680
    for to_node, to_result in result.items():
9681
      msg = to_result.fail_msg
9682
      if msg:
9683
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
9684
                           to_node, msg,
9685
                           hint=("please do a gnt-instance info to see the"
9686
                                 " status of disks"))
9687
    cstep = 5
9688
    if self.early_release:
9689
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9690
      cstep += 1
9691
      self._RemoveOldStorage(self.target_node, iv_names)
9692
      # WARNING: we release all node locks here, do not do other RPCs
9693
      # than WaitForSync to the primary node
9694
      _ReleaseLocks(self.lu, locking.LEVEL_NODE,
9695
                    names=[self.instance.primary_node,
9696
                           self.target_node,
9697
                           self.new_node])
9698

    
9699
    # Wait for sync
9700
    # This can fail as the old devices are degraded and _WaitForSync
9701
    # does a combined result over all disks, so we don't check its return value
9702
    self.lu.LogStep(cstep, steps_total, "Sync devices")
9703
    cstep += 1
9704
    _WaitForSync(self.lu, self.instance)
9705

    
9706
    # Check all devices manually
9707
    self._CheckDevices(self.instance.primary_node, iv_names)
9708

    
9709
    # Step: remove old storage
9710
    if not self.early_release:
9711
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9712
      self._RemoveOldStorage(self.target_node, iv_names)
9713

    
9714

    
9715
class LURepairNodeStorage(NoHooksLU):
9716
  """Repairs the volume group on a node.
9717

9718
  """
9719
  REQ_BGL = False
9720

    
9721
  def CheckArguments(self):
9722
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
9723

    
9724
    storage_type = self.op.storage_type
9725

    
9726
    if (constants.SO_FIX_CONSISTENCY not in
9727
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
9728
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
9729
                                 " repaired" % storage_type,
9730
                                 errors.ECODE_INVAL)
9731

    
9732
  def ExpandNames(self):
9733
    self.needed_locks = {
9734
      locking.LEVEL_NODE: [self.op.node_name],
9735
      }
9736

    
9737
  def _CheckFaultyDisks(self, instance, node_name):
9738
    """Ensure faulty disks abort the opcode or at least warn."""
9739
    try:
9740
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
9741
                                  node_name, True):
9742
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
9743
                                   " node '%s'" % (instance.name, node_name),
9744
                                   errors.ECODE_STATE)
9745
    except errors.OpPrereqError, err:
9746
      if self.op.ignore_consistency:
9747
        self.proc.LogWarning(str(err.args[0]))
9748
      else:
9749
        raise
9750

    
9751
  def CheckPrereq(self):
9752
    """Check prerequisites.
9753

9754
    """
9755
    # Check whether any instance on this node has faulty disks
9756
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
9757
      if not inst.admin_up:
9758
        continue
9759
      check_nodes = set(inst.all_nodes)
9760
      check_nodes.discard(self.op.node_name)
9761
      for inst_node_name in check_nodes:
9762
        self._CheckFaultyDisks(inst, inst_node_name)
9763

    
9764
  def Exec(self, feedback_fn):
9765
    feedback_fn("Repairing storage unit '%s' on %s ..." %
9766
                (self.op.name, self.op.node_name))
9767

    
9768
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
9769
    result = self.rpc.call_storage_execute(self.op.node_name,
9770
                                           self.op.storage_type, st_args,
9771
                                           self.op.name,
9772
                                           constants.SO_FIX_CONSISTENCY)
9773
    result.Raise("Failed to repair storage unit '%s' on %s" %
9774
                 (self.op.name, self.op.node_name))
9775

    
9776

    
9777
class LUNodeEvacuate(NoHooksLU):
9778
  """Evacuates instances off a list of nodes.
9779

9780
  """
9781
  REQ_BGL = False
9782

    
9783
  def CheckArguments(self):
9784
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
9785

    
9786
  def ExpandNames(self):
9787
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
9788

    
9789
    if self.op.remote_node is not None:
9790
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9791
      assert self.op.remote_node
9792

    
9793
      if self.op.remote_node == self.op.node_name:
9794
        raise errors.OpPrereqError("Can not use evacuated node as a new"
9795
                                   " secondary node", errors.ECODE_INVAL)
9796

    
9797
      if self.op.mode != constants.IALLOCATOR_NEVAC_SEC:
9798
        raise errors.OpPrereqError("Without the use of an iallocator only"
9799
                                   " secondary instances can be evacuated",
9800
                                   errors.ECODE_INVAL)
9801

    
9802
    # Declare locks
9803
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9804
    self.needed_locks = {
9805
      locking.LEVEL_INSTANCE: [],
9806
      locking.LEVEL_NODEGROUP: [],
9807
      locking.LEVEL_NODE: [],
9808
      }
9809

    
9810
    if self.op.remote_node is None:
9811
      # Iallocator will choose any node(s) in the same group
9812
      group_nodes = self.cfg.GetNodeGroupMembersByNodes([self.op.node_name])
9813
    else:
9814
      group_nodes = frozenset([self.op.remote_node])
9815

    
9816
    # Determine nodes to be locked
9817
    self.lock_nodes = set([self.op.node_name]) | group_nodes
9818

    
9819
  def _DetermineInstances(self):
9820
    """Builds list of instances to operate on.
9821

9822
    """
9823
    assert self.op.mode in constants.IALLOCATOR_NEVAC_MODES
9824

    
9825
    if self.op.mode == constants.IALLOCATOR_NEVAC_PRI:
9826
      # Primary instances only
9827
      inst_fn = _GetNodePrimaryInstances
9828
      assert self.op.remote_node is None, \
9829
        "Evacuating primary instances requires iallocator"
9830
    elif self.op.mode == constants.IALLOCATOR_NEVAC_SEC:
9831
      # Secondary instances only
9832
      inst_fn = _GetNodeSecondaryInstances
9833
    else:
9834
      # All instances
9835
      assert self.op.mode == constants.IALLOCATOR_NEVAC_ALL
9836
      inst_fn = _GetNodeInstances
9837

    
9838
    return inst_fn(self.cfg, self.op.node_name)
9839

    
9840
  def DeclareLocks(self, level):
9841
    if level == locking.LEVEL_INSTANCE:
9842
      # Lock instances optimistically, needs verification once node and group
9843
      # locks have been acquired
9844
      self.needed_locks[locking.LEVEL_INSTANCE] = \
9845
        set(i.name for i in self._DetermineInstances())
9846

    
9847
    elif level == locking.LEVEL_NODEGROUP:
9848
      # Lock node groups optimistically, needs verification once nodes have
9849
      # been acquired
9850
      self.needed_locks[locking.LEVEL_NODEGROUP] = \
9851
        self.cfg.GetNodeGroupsFromNodes(self.lock_nodes)
9852

    
9853
    elif level == locking.LEVEL_NODE:
9854
      self.needed_locks[locking.LEVEL_NODE] = self.lock_nodes
9855

    
9856
  def CheckPrereq(self):
9857
    # Verify locks
9858
    owned_instances = self.glm.list_owned(locking.LEVEL_INSTANCE)
9859
    owned_nodes = self.glm.list_owned(locking.LEVEL_NODE)
9860
    owned_groups = self.glm.list_owned(locking.LEVEL_NODEGROUP)
9861

    
9862
    assert owned_nodes == self.lock_nodes
9863

    
9864
    wanted_groups = self.cfg.GetNodeGroupsFromNodes(owned_nodes)
9865
    if owned_groups != wanted_groups:
9866
      raise errors.OpExecError("Node groups changed since locks were acquired,"
9867
                               " current groups are '%s', used to be '%s'" %
9868
                               (utils.CommaJoin(wanted_groups),
9869
                                utils.CommaJoin(owned_groups)))
9870

    
9871
    # Determine affected instances
9872
    self.instances = self._DetermineInstances()
9873
    self.instance_names = [i.name for i in self.instances]
9874

    
9875
    if set(self.instance_names) != owned_instances:
9876
      raise errors.OpExecError("Instances on node '%s' changed since locks"
9877
                               " were acquired, current instances are '%s',"
9878
                               " used to be '%s'" %
9879
                               (self.op.node_name,
9880
                                utils.CommaJoin(self.instance_names),
9881
                                utils.CommaJoin(owned_instances)))
9882

    
9883
    if self.instance_names:
9884
      self.LogInfo("Evacuating instances from node '%s': %s",
9885
                   self.op.node_name,
9886
                   utils.CommaJoin(utils.NiceSort(self.instance_names)))
9887
    else:
9888
      self.LogInfo("No instances to evacuate from node '%s'",
9889
                   self.op.node_name)
9890

    
9891
    if self.op.remote_node is not None:
9892
      for i in self.instances:
9893
        if i.primary_node == self.op.remote_node:
9894
          raise errors.OpPrereqError("Node %s is the primary node of"
9895
                                     " instance %s, cannot use it as"
9896
                                     " secondary" %
9897
                                     (self.op.remote_node, i.name),
9898
                                     errors.ECODE_INVAL)
9899

    
9900
  def Exec(self, feedback_fn):
9901
    assert (self.op.iallocator is not None) ^ (self.op.remote_node is not None)
9902

    
9903
    if not self.instance_names:
9904
      # No instances to evacuate
9905
      jobs = []
9906

    
9907
    elif self.op.iallocator is not None:
9908
      # TODO: Implement relocation to other group
9909
      ial = IAllocator(self.cfg, self.rpc, constants.IALLOCATOR_MODE_NODE_EVAC,
9910
                       evac_mode=self.op.mode,
9911
                       instances=list(self.instance_names))
9912

    
9913
      ial.Run(self.op.iallocator)
9914

    
9915
      if not ial.success:
9916
        raise errors.OpPrereqError("Can't compute node evacuation using"
9917
                                   " iallocator '%s': %s" %
9918
                                   (self.op.iallocator, ial.info),
9919
                                   errors.ECODE_NORES)
9920

    
9921
      jobs = _LoadNodeEvacResult(self, ial.result, self.op.early_release, True)
9922

    
9923
    elif self.op.remote_node is not None:
9924
      assert self.op.mode == constants.IALLOCATOR_NEVAC_SEC
9925
      jobs = [
9926
        [opcodes.OpInstanceReplaceDisks(instance_name=instance_name,
9927
                                        remote_node=self.op.remote_node,
9928
                                        disks=[],
9929
                                        mode=constants.REPLACE_DISK_CHG,
9930
                                        early_release=self.op.early_release)]
9931
        for instance_name in self.instance_names
9932
        ]
9933

    
9934
    else:
9935
      raise errors.ProgrammerError("No iallocator or remote node")
9936

    
9937
    return ResultWithJobs(jobs)
9938

    
9939

    
9940
def _SetOpEarlyRelease(early_release, op):
9941
  """Sets C{early_release} flag on opcodes if available.
9942

9943
  """
9944
  try:
9945
    op.early_release = early_release
9946
  except AttributeError:
9947
    assert not isinstance(op, opcodes.OpInstanceReplaceDisks)
9948

    
9949
  return op
9950

    
9951

    
9952
def _NodeEvacDest(use_nodes, group, nodes):
9953
  """Returns group or nodes depending on caller's choice.
9954

9955
  """
9956
  if use_nodes:
9957
    return utils.CommaJoin(nodes)
9958
  else:
9959
    return group
9960

    
9961

    
9962
def _LoadNodeEvacResult(lu, alloc_result, early_release, use_nodes):
9963
  """Unpacks the result of change-group and node-evacuate iallocator requests.
9964

9965
  Iallocator modes L{constants.IALLOCATOR_MODE_NODE_EVAC} and
9966
  L{constants.IALLOCATOR_MODE_CHG_GROUP}.
9967

9968
  @type lu: L{LogicalUnit}
9969
  @param lu: Logical unit instance
9970
  @type alloc_result: tuple/list
9971
  @param alloc_result: Result from iallocator
9972
  @type early_release: bool
9973
  @param early_release: Whether to release locks early if possible
9974
  @type use_nodes: bool
9975
  @param use_nodes: Whether to display node names instead of groups
9976

9977
  """
9978
  (moved, failed, jobs) = alloc_result
9979

    
9980
  if failed:
9981
    lu.LogWarning("Unable to evacuate instances %s",
9982
                  utils.CommaJoin("%s (%s)" % (name, reason)
9983
                                  for (name, reason) in failed))
9984

    
9985
  if moved:
9986
    lu.LogInfo("Instances to be moved: %s",
9987
               utils.CommaJoin("%s (to %s)" %
9988
                               (name, _NodeEvacDest(use_nodes, group, nodes))
9989
                               for (name, group, nodes) in moved))
9990

    
9991
  return [map(compat.partial(_SetOpEarlyRelease, early_release),
9992
              map(opcodes.OpCode.LoadOpCode, ops))
9993
          for ops in jobs]
9994

    
9995

    
9996
class LUInstanceGrowDisk(LogicalUnit):
9997
  """Grow a disk of an instance.
9998

9999
  """
10000
  HPATH = "disk-grow"
10001
  HTYPE = constants.HTYPE_INSTANCE
10002
  REQ_BGL = False
10003

    
10004
  def ExpandNames(self):
10005
    self._ExpandAndLockInstance()
10006
    self.needed_locks[locking.LEVEL_NODE] = []
10007
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
10008

    
10009
  def DeclareLocks(self, level):
10010
    if level == locking.LEVEL_NODE:
10011
      self._LockInstancesNodes()
10012

    
10013
  def BuildHooksEnv(self):
10014
    """Build hooks env.
10015

10016
    This runs on the master, the primary and all the secondaries.
10017

10018
    """
10019
    env = {
10020
      "DISK": self.op.disk,
10021
      "AMOUNT": self.op.amount,
10022
      }
10023
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
10024
    return env
10025

    
10026
  def BuildHooksNodes(self):
10027
    """Build hooks nodes.
10028

10029
    """
10030
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
10031
    return (nl, nl)
10032

    
10033
  def CheckPrereq(self):
10034
    """Check prerequisites.
10035

10036
    This checks that the instance is in the cluster.
10037

10038
    """
10039
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
10040
    assert instance is not None, \
10041
      "Cannot retrieve locked instance %s" % self.op.instance_name
10042
    nodenames = list(instance.all_nodes)
10043
    for node in nodenames:
10044
      _CheckNodeOnline(self, node)
10045

    
10046
    self.instance = instance
10047

    
10048
    if instance.disk_template not in constants.DTS_GROWABLE:
10049
      raise errors.OpPrereqError("Instance's disk layout does not support"
10050
                                 " growing", errors.ECODE_INVAL)
10051

    
10052
    self.disk = instance.FindDisk(self.op.disk)
10053

    
10054
    if instance.disk_template not in (constants.DT_FILE,
10055
                                      constants.DT_SHARED_FILE):
10056
      # TODO: check the free disk space for file, when that feature will be
10057
      # supported
10058
      _CheckNodesFreeDiskPerVG(self, nodenames,
10059
                               self.disk.ComputeGrowth(self.op.amount))
10060

    
10061
  def Exec(self, feedback_fn):
10062
    """Execute disk grow.
10063

10064
    """
10065
    instance = self.instance
10066
    disk = self.disk
10067

    
10068
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
10069
    if not disks_ok:
10070
      raise errors.OpExecError("Cannot activate block device to grow")
10071

    
10072
    # First run all grow ops in dry-run mode
10073
    for node in instance.all_nodes:
10074
      self.cfg.SetDiskID(disk, node)
10075
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, True)
10076
      result.Raise("Grow request failed to node %s" % node)
10077

    
10078
    # We know that (as far as we can test) operations across different
10079
    # nodes will succeed, time to run it for real
10080
    for node in instance.all_nodes:
10081
      self.cfg.SetDiskID(disk, node)
10082
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, False)
10083
      result.Raise("Grow request failed to node %s" % node)
10084

    
10085
      # TODO: Rewrite code to work properly
10086
      # DRBD goes into sync mode for a short amount of time after executing the
10087
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
10088
      # calling "resize" in sync mode fails. Sleeping for a short amount of
10089
      # time is a work-around.
10090
      time.sleep(5)
10091

    
10092
    disk.RecordGrow(self.op.amount)
10093
    self.cfg.Update(instance, feedback_fn)
10094
    if self.op.wait_for_sync:
10095
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
10096
      if disk_abort:
10097
        self.proc.LogWarning("Disk sync-ing has not returned a good"
10098
                             " status; please check the instance")
10099
      if not instance.admin_up:
10100
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
10101
    elif not instance.admin_up:
10102
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
10103
                           " not supposed to be running because no wait for"
10104
                           " sync mode was requested")
10105

    
10106

    
10107
class LUInstanceQueryData(NoHooksLU):
10108
  """Query runtime instance data.
10109

10110
  """
10111
  REQ_BGL = False
10112

    
10113
  def ExpandNames(self):
10114
    self.needed_locks = {}
10115

    
10116
    # Use locking if requested or when non-static information is wanted
10117
    if not (self.op.static or self.op.use_locking):
10118
      self.LogWarning("Non-static data requested, locks need to be acquired")
10119
      self.op.use_locking = True
10120

    
10121
    if self.op.instances or not self.op.use_locking:
10122
      # Expand instance names right here
10123
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
10124
    else:
10125
      # Will use acquired locks
10126
      self.wanted_names = None
10127

    
10128
    if self.op.use_locking:
10129
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
10130

    
10131
      if self.wanted_names is None:
10132
        self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
10133
      else:
10134
        self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
10135

    
10136
      self.needed_locks[locking.LEVEL_NODE] = []
10137
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
10138
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
10139

    
10140
  def DeclareLocks(self, level):
10141
    if self.op.use_locking and level == locking.LEVEL_NODE:
10142
      self._LockInstancesNodes()
10143

    
10144
  def CheckPrereq(self):
10145
    """Check prerequisites.
10146

10147
    This only checks the optional instance list against the existing names.
10148

10149
    """
10150
    if self.wanted_names is None:
10151
      assert self.op.use_locking, "Locking was not used"
10152
      self.wanted_names = self.glm.list_owned(locking.LEVEL_INSTANCE)
10153

    
10154
    self.wanted_instances = [self.cfg.GetInstanceInfo(name)
10155
                             for name in self.wanted_names]
10156

    
10157
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
10158
    """Returns the status of a block device
10159

10160
    """
10161
    if self.op.static or not node:
10162
      return None
10163

    
10164
    self.cfg.SetDiskID(dev, node)
10165

    
10166
    result = self.rpc.call_blockdev_find(node, dev)
10167
    if result.offline:
10168
      return None
10169

    
10170
    result.Raise("Can't compute disk status for %s" % instance_name)
10171

    
10172
    status = result.payload
10173
    if status is None:
10174
      return None
10175

    
10176
    return (status.dev_path, status.major, status.minor,
10177
            status.sync_percent, status.estimated_time,
10178
            status.is_degraded, status.ldisk_status)
10179

    
10180
  def _ComputeDiskStatus(self, instance, snode, dev):
10181
    """Compute block device status.
10182

10183
    """
10184
    if dev.dev_type in constants.LDS_DRBD:
10185
      # we change the snode then (otherwise we use the one passed in)
10186
      if dev.logical_id[0] == instance.primary_node:
10187
        snode = dev.logical_id[1]
10188
      else:
10189
        snode = dev.logical_id[0]
10190

    
10191
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
10192
                                              instance.name, dev)
10193
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
10194

    
10195
    if dev.children:
10196
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
10197
                      for child in dev.children]
10198
    else:
10199
      dev_children = []
10200

    
10201
    return {
10202
      "iv_name": dev.iv_name,
10203
      "dev_type": dev.dev_type,
10204
      "logical_id": dev.logical_id,
10205
      "physical_id": dev.physical_id,
10206
      "pstatus": dev_pstatus,
10207
      "sstatus": dev_sstatus,
10208
      "children": dev_children,
10209
      "mode": dev.mode,
10210
      "size": dev.size,
10211
      }
10212

    
10213
  def Exec(self, feedback_fn):
10214
    """Gather and return data"""
10215
    result = {}
10216

    
10217
    cluster = self.cfg.GetClusterInfo()
10218

    
10219
    for instance in self.wanted_instances:
10220
      if not self.op.static:
10221
        remote_info = self.rpc.call_instance_info(instance.primary_node,
10222
                                                  instance.name,
10223
                                                  instance.hypervisor)
10224
        remote_info.Raise("Error checking node %s" % instance.primary_node)
10225
        remote_info = remote_info.payload
10226
        if remote_info and "state" in remote_info:
10227
          remote_state = "up"
10228
        else:
10229
          remote_state = "down"
10230
      else:
10231
        remote_state = None
10232
      if instance.admin_up:
10233
        config_state = "up"
10234
      else:
10235
        config_state = "down"
10236

    
10237
      disks = [self._ComputeDiskStatus(instance, None, device)
10238
               for device in instance.disks]
10239

    
10240
      result[instance.name] = {
10241
        "name": instance.name,
10242
        "config_state": config_state,
10243
        "run_state": remote_state,
10244
        "pnode": instance.primary_node,
10245
        "snodes": instance.secondary_nodes,
10246
        "os": instance.os,
10247
        # this happens to be the same format used for hooks
10248
        "nics": _NICListToTuple(self, instance.nics),
10249
        "disk_template": instance.disk_template,
10250
        "disks": disks,
10251
        "hypervisor": instance.hypervisor,
10252
        "network_port": instance.network_port,
10253
        "hv_instance": instance.hvparams,
10254
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
10255
        "be_instance": instance.beparams,
10256
        "be_actual": cluster.FillBE(instance),
10257
        "os_instance": instance.osparams,
10258
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
10259
        "serial_no": instance.serial_no,
10260
        "mtime": instance.mtime,
10261
        "ctime": instance.ctime,
10262
        "uuid": instance.uuid,
10263
        }
10264

    
10265
    return result
10266

    
10267

    
10268
class LUInstanceSetParams(LogicalUnit):
10269
  """Modifies an instances's parameters.
10270

10271
  """
10272
  HPATH = "instance-modify"
10273
  HTYPE = constants.HTYPE_INSTANCE
10274
  REQ_BGL = False
10275

    
10276
  def CheckArguments(self):
10277
    if not (self.op.nics or self.op.disks or self.op.disk_template or
10278
            self.op.hvparams or self.op.beparams or self.op.os_name):
10279
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
10280

    
10281
    if self.op.hvparams:
10282
      _CheckGlobalHvParams(self.op.hvparams)
10283

    
10284
    # Disk validation
10285
    disk_addremove = 0
10286
    for disk_op, disk_dict in self.op.disks:
10287
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
10288
      if disk_op == constants.DDM_REMOVE:
10289
        disk_addremove += 1
10290
        continue
10291
      elif disk_op == constants.DDM_ADD:
10292
        disk_addremove += 1
10293
      else:
10294
        if not isinstance(disk_op, int):
10295
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
10296
        if not isinstance(disk_dict, dict):
10297
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
10298
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
10299

    
10300
      if disk_op == constants.DDM_ADD:
10301
        mode = disk_dict.setdefault(constants.IDISK_MODE, constants.DISK_RDWR)
10302
        if mode not in constants.DISK_ACCESS_SET:
10303
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
10304
                                     errors.ECODE_INVAL)
10305
        size = disk_dict.get(constants.IDISK_SIZE, None)
10306
        if size is None:
10307
          raise errors.OpPrereqError("Required disk parameter size missing",
10308
                                     errors.ECODE_INVAL)
10309
        try:
10310
          size = int(size)
10311
        except (TypeError, ValueError), err:
10312
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
10313
                                     str(err), errors.ECODE_INVAL)
10314
        disk_dict[constants.IDISK_SIZE] = size
10315
      else:
10316
        # modification of disk
10317
        if constants.IDISK_SIZE in disk_dict:
10318
          raise errors.OpPrereqError("Disk size change not possible, use"
10319
                                     " grow-disk", errors.ECODE_INVAL)
10320

    
10321
    if disk_addremove > 1:
10322
      raise errors.OpPrereqError("Only one disk add or remove operation"
10323
                                 " supported at a time", errors.ECODE_INVAL)
10324

    
10325
    if self.op.disks and self.op.disk_template is not None:
10326
      raise errors.OpPrereqError("Disk template conversion and other disk"
10327
                                 " changes not supported at the same time",
10328
                                 errors.ECODE_INVAL)
10329

    
10330
    if (self.op.disk_template and
10331
        self.op.disk_template in constants.DTS_INT_MIRROR and
10332
        self.op.remote_node is None):
10333
      raise errors.OpPrereqError("Changing the disk template to a mirrored"
10334
                                 " one requires specifying a secondary node",
10335
                                 errors.ECODE_INVAL)
10336

    
10337
    # NIC validation
10338
    nic_addremove = 0
10339
    for nic_op, nic_dict in self.op.nics:
10340
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
10341
      if nic_op == constants.DDM_REMOVE:
10342
        nic_addremove += 1
10343
        continue
10344
      elif nic_op == constants.DDM_ADD:
10345
        nic_addremove += 1
10346
      else:
10347
        if not isinstance(nic_op, int):
10348
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
10349
        if not isinstance(nic_dict, dict):
10350
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
10351
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
10352

    
10353
      # nic_dict should be a dict
10354
      nic_ip = nic_dict.get(constants.INIC_IP, None)
10355
      if nic_ip is not None:
10356
        if nic_ip.lower() == constants.VALUE_NONE:
10357
          nic_dict[constants.INIC_IP] = None
10358
        else:
10359
          if not netutils.IPAddress.IsValid(nic_ip):
10360
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
10361
                                       errors.ECODE_INVAL)
10362

    
10363
      nic_bridge = nic_dict.get('bridge', None)
10364
      nic_link = nic_dict.get(constants.INIC_LINK, None)
10365
      if nic_bridge and nic_link:
10366
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
10367
                                   " at the same time", errors.ECODE_INVAL)
10368
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
10369
        nic_dict['bridge'] = None
10370
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
10371
        nic_dict[constants.INIC_LINK] = None
10372

    
10373
      if nic_op == constants.DDM_ADD:
10374
        nic_mac = nic_dict.get(constants.INIC_MAC, None)
10375
        if nic_mac is None:
10376
          nic_dict[constants.INIC_MAC] = constants.VALUE_AUTO
10377

    
10378
      if constants.INIC_MAC in nic_dict:
10379
        nic_mac = nic_dict[constants.INIC_MAC]
10380
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
10381
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
10382

    
10383
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
10384
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
10385
                                     " modifying an existing nic",
10386
                                     errors.ECODE_INVAL)
10387

    
10388
    if nic_addremove > 1:
10389
      raise errors.OpPrereqError("Only one NIC add or remove operation"
10390
                                 " supported at a time", errors.ECODE_INVAL)
10391

    
10392
  def ExpandNames(self):
10393
    self._ExpandAndLockInstance()
10394
    self.needed_locks[locking.LEVEL_NODE] = []
10395
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
10396

    
10397
  def DeclareLocks(self, level):
10398
    if level == locking.LEVEL_NODE:
10399
      self._LockInstancesNodes()
10400
      if self.op.disk_template and self.op.remote_node:
10401
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
10402
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
10403

    
10404
  def BuildHooksEnv(self):
10405
    """Build hooks env.
10406

10407
    This runs on the master, primary and secondaries.
10408

10409
    """
10410
    args = dict()
10411
    if constants.BE_MEMORY in self.be_new:
10412
      args['memory'] = self.be_new[constants.BE_MEMORY]
10413
    if constants.BE_VCPUS in self.be_new:
10414
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
10415
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
10416
    # information at all.
10417
    if self.op.nics:
10418
      args['nics'] = []
10419
      nic_override = dict(self.op.nics)
10420
      for idx, nic in enumerate(self.instance.nics):
10421
        if idx in nic_override:
10422
          this_nic_override = nic_override[idx]
10423
        else:
10424
          this_nic_override = {}
10425
        if constants.INIC_IP in this_nic_override:
10426
          ip = this_nic_override[constants.INIC_IP]
10427
        else:
10428
          ip = nic.ip
10429
        if constants.INIC_MAC in this_nic_override:
10430
          mac = this_nic_override[constants.INIC_MAC]
10431
        else:
10432
          mac = nic.mac
10433
        if idx in self.nic_pnew:
10434
          nicparams = self.nic_pnew[idx]
10435
        else:
10436
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
10437
        mode = nicparams[constants.NIC_MODE]
10438
        link = nicparams[constants.NIC_LINK]
10439
        args['nics'].append((ip, mac, mode, link))
10440
      if constants.DDM_ADD in nic_override:
10441
        ip = nic_override[constants.DDM_ADD].get(constants.INIC_IP, None)
10442
        mac = nic_override[constants.DDM_ADD][constants.INIC_MAC]
10443
        nicparams = self.nic_pnew[constants.DDM_ADD]
10444
        mode = nicparams[constants.NIC_MODE]
10445
        link = nicparams[constants.NIC_LINK]
10446
        args['nics'].append((ip, mac, mode, link))
10447
      elif constants.DDM_REMOVE in nic_override:
10448
        del args['nics'][-1]
10449

    
10450
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
10451
    if self.op.disk_template:
10452
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
10453

    
10454
    return env
10455

    
10456
  def BuildHooksNodes(self):
10457
    """Build hooks nodes.
10458

10459
    """
10460
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
10461
    return (nl, nl)
10462

    
10463
  def CheckPrereq(self):
10464
    """Check prerequisites.
10465

10466
    This only checks the instance list against the existing names.
10467

10468
    """
10469
    # checking the new params on the primary/secondary nodes
10470

    
10471
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
10472
    cluster = self.cluster = self.cfg.GetClusterInfo()
10473
    assert self.instance is not None, \
10474
      "Cannot retrieve locked instance %s" % self.op.instance_name
10475
    pnode = instance.primary_node
10476
    nodelist = list(instance.all_nodes)
10477

    
10478
    # OS change
10479
    if self.op.os_name and not self.op.force:
10480
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
10481
                      self.op.force_variant)
10482
      instance_os = self.op.os_name
10483
    else:
10484
      instance_os = instance.os
10485

    
10486
    if self.op.disk_template:
10487
      if instance.disk_template == self.op.disk_template:
10488
        raise errors.OpPrereqError("Instance already has disk template %s" %
10489
                                   instance.disk_template, errors.ECODE_INVAL)
10490

    
10491
      if (instance.disk_template,
10492
          self.op.disk_template) not in self._DISK_CONVERSIONS:
10493
        raise errors.OpPrereqError("Unsupported disk template conversion from"
10494
                                   " %s to %s" % (instance.disk_template,
10495
                                                  self.op.disk_template),
10496
                                   errors.ECODE_INVAL)
10497
      _CheckInstanceDown(self, instance, "cannot change disk template")
10498
      if self.op.disk_template in constants.DTS_INT_MIRROR:
10499
        if self.op.remote_node == pnode:
10500
          raise errors.OpPrereqError("Given new secondary node %s is the same"
10501
                                     " as the primary node of the instance" %
10502
                                     self.op.remote_node, errors.ECODE_STATE)
10503
        _CheckNodeOnline(self, self.op.remote_node)
10504
        _CheckNodeNotDrained(self, self.op.remote_node)
10505
        # FIXME: here we assume that the old instance type is DT_PLAIN
10506
        assert instance.disk_template == constants.DT_PLAIN
10507
        disks = [{constants.IDISK_SIZE: d.size,
10508
                  constants.IDISK_VG: d.logical_id[0]}
10509
                 for d in instance.disks]
10510
        required = _ComputeDiskSizePerVG(self.op.disk_template, disks)
10511
        _CheckNodesFreeDiskPerVG(self, [self.op.remote_node], required)
10512

    
10513
    # hvparams processing
10514
    if self.op.hvparams:
10515
      hv_type = instance.hypervisor
10516
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
10517
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
10518
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
10519

    
10520
      # local check
10521
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
10522
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
10523
      self.hv_new = hv_new # the new actual values
10524
      self.hv_inst = i_hvdict # the new dict (without defaults)
10525
    else:
10526
      self.hv_new = self.hv_inst = {}
10527

    
10528
    # beparams processing
10529
    if self.op.beparams:
10530
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
10531
                                   use_none=True)
10532
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
10533
      be_new = cluster.SimpleFillBE(i_bedict)
10534
      self.be_new = be_new # the new actual values
10535
      self.be_inst = i_bedict # the new dict (without defaults)
10536
    else:
10537
      self.be_new = self.be_inst = {}
10538
    be_old = cluster.FillBE(instance)
10539

    
10540
    # osparams processing
10541
    if self.op.osparams:
10542
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
10543
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
10544
      self.os_inst = i_osdict # the new dict (without defaults)
10545
    else:
10546
      self.os_inst = {}
10547

    
10548
    self.warn = []
10549

    
10550
    if (constants.BE_MEMORY in self.op.beparams and not self.op.force and
10551
        be_new[constants.BE_MEMORY] > be_old[constants.BE_MEMORY]):
10552
      mem_check_list = [pnode]
10553
      if be_new[constants.BE_AUTO_BALANCE]:
10554
        # either we changed auto_balance to yes or it was from before
10555
        mem_check_list.extend(instance.secondary_nodes)
10556
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
10557
                                                  instance.hypervisor)
10558
      nodeinfo = self.rpc.call_node_info(mem_check_list, None,
10559
                                         instance.hypervisor)
10560
      pninfo = nodeinfo[pnode]
10561
      msg = pninfo.fail_msg
10562
      if msg:
10563
        # Assume the primary node is unreachable and go ahead
10564
        self.warn.append("Can't get info from primary node %s: %s" %
10565
                         (pnode,  msg))
10566
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
10567
        self.warn.append("Node data from primary node %s doesn't contain"
10568
                         " free memory information" % pnode)
10569
      elif instance_info.fail_msg:
10570
        self.warn.append("Can't get instance runtime information: %s" %
10571
                        instance_info.fail_msg)
10572
      else:
10573
        if instance_info.payload:
10574
          current_mem = int(instance_info.payload['memory'])
10575
        else:
10576
          # Assume instance not running
10577
          # (there is a slight race condition here, but it's not very probable,
10578
          # and we have no other way to check)
10579
          current_mem = 0
10580
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
10581
                    pninfo.payload['memory_free'])
10582
        if miss_mem > 0:
10583
          raise errors.OpPrereqError("This change will prevent the instance"
10584
                                     " from starting, due to %d MB of memory"
10585
                                     " missing on its primary node" % miss_mem,
10586
                                     errors.ECODE_NORES)
10587

    
10588
      if be_new[constants.BE_AUTO_BALANCE]:
10589
        for node, nres in nodeinfo.items():
10590
          if node not in instance.secondary_nodes:
10591
            continue
10592
          nres.Raise("Can't get info from secondary node %s" % node,
10593
                     prereq=True, ecode=errors.ECODE_STATE)
10594
          if not isinstance(nres.payload.get('memory_free', None), int):
10595
            raise errors.OpPrereqError("Secondary node %s didn't return free"
10596
                                       " memory information" % node,
10597
                                       errors.ECODE_STATE)
10598
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
10599
            raise errors.OpPrereqError("This change will prevent the instance"
10600
                                       " from failover to its secondary node"
10601
                                       " %s, due to not enough memory" % node,
10602
                                       errors.ECODE_STATE)
10603

    
10604
    # NIC processing
10605
    self.nic_pnew = {}
10606
    self.nic_pinst = {}
10607
    for nic_op, nic_dict in self.op.nics:
10608
      if nic_op == constants.DDM_REMOVE:
10609
        if not instance.nics:
10610
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
10611
                                     errors.ECODE_INVAL)
10612
        continue
10613
      if nic_op != constants.DDM_ADD:
10614
        # an existing nic
10615
        if not instance.nics:
10616
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
10617
                                     " no NICs" % nic_op,
10618
                                     errors.ECODE_INVAL)
10619
        if nic_op < 0 or nic_op >= len(instance.nics):
10620
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
10621
                                     " are 0 to %d" %
10622
                                     (nic_op, len(instance.nics) - 1),
10623
                                     errors.ECODE_INVAL)
10624
        old_nic_params = instance.nics[nic_op].nicparams
10625
        old_nic_ip = instance.nics[nic_op].ip
10626
      else:
10627
        old_nic_params = {}
10628
        old_nic_ip = None
10629

    
10630
      update_params_dict = dict([(key, nic_dict[key])
10631
                                 for key in constants.NICS_PARAMETERS
10632
                                 if key in nic_dict])
10633

    
10634
      if 'bridge' in nic_dict:
10635
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
10636

    
10637
      new_nic_params = _GetUpdatedParams(old_nic_params,
10638
                                         update_params_dict)
10639
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
10640
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
10641
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
10642
      self.nic_pinst[nic_op] = new_nic_params
10643
      self.nic_pnew[nic_op] = new_filled_nic_params
10644
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
10645

    
10646
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
10647
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
10648
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
10649
        if msg:
10650
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
10651
          if self.op.force:
10652
            self.warn.append(msg)
10653
          else:
10654
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
10655
      if new_nic_mode == constants.NIC_MODE_ROUTED:
10656
        if constants.INIC_IP in nic_dict:
10657
          nic_ip = nic_dict[constants.INIC_IP]
10658
        else:
10659
          nic_ip = old_nic_ip
10660
        if nic_ip is None:
10661
          raise errors.OpPrereqError('Cannot set the nic ip to None'
10662
                                     ' on a routed nic', errors.ECODE_INVAL)
10663
      if constants.INIC_MAC in nic_dict:
10664
        nic_mac = nic_dict[constants.INIC_MAC]
10665
        if nic_mac is None:
10666
          raise errors.OpPrereqError('Cannot set the nic mac to None',
10667
                                     errors.ECODE_INVAL)
10668
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
10669
          # otherwise generate the mac
10670
          nic_dict[constants.INIC_MAC] = \
10671
            self.cfg.GenerateMAC(self.proc.GetECId())
10672
        else:
10673
          # or validate/reserve the current one
10674
          try:
10675
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
10676
          except errors.ReservationError:
10677
            raise errors.OpPrereqError("MAC address %s already in use"
10678
                                       " in cluster" % nic_mac,
10679
                                       errors.ECODE_NOTUNIQUE)
10680

    
10681
    # DISK processing
10682
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
10683
      raise errors.OpPrereqError("Disk operations not supported for"
10684
                                 " diskless instances",
10685
                                 errors.ECODE_INVAL)
10686
    for disk_op, _ in self.op.disks:
10687
      if disk_op == constants.DDM_REMOVE:
10688
        if len(instance.disks) == 1:
10689
          raise errors.OpPrereqError("Cannot remove the last disk of"
10690
                                     " an instance", errors.ECODE_INVAL)
10691
        _CheckInstanceDown(self, instance, "cannot remove disks")
10692

    
10693
      if (disk_op == constants.DDM_ADD and
10694
          len(instance.disks) >= constants.MAX_DISKS):
10695
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
10696
                                   " add more" % constants.MAX_DISKS,
10697
                                   errors.ECODE_STATE)
10698
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
10699
        # an existing disk
10700
        if disk_op < 0 or disk_op >= len(instance.disks):
10701
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
10702
                                     " are 0 to %d" %
10703
                                     (disk_op, len(instance.disks)),
10704
                                     errors.ECODE_INVAL)
10705

    
10706
    return
10707

    
10708
  def _ConvertPlainToDrbd(self, feedback_fn):
10709
    """Converts an instance from plain to drbd.
10710

10711
    """
10712
    feedback_fn("Converting template to drbd")
10713
    instance = self.instance
10714
    pnode = instance.primary_node
10715
    snode = self.op.remote_node
10716

    
10717
    # create a fake disk info for _GenerateDiskTemplate
10718
    disk_info = [{constants.IDISK_SIZE: d.size, constants.IDISK_MODE: d.mode,
10719
                  constants.IDISK_VG: d.logical_id[0]}
10720
                 for d in instance.disks]
10721
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
10722
                                      instance.name, pnode, [snode],
10723
                                      disk_info, None, None, 0, feedback_fn)
10724
    info = _GetInstanceInfoText(instance)
10725
    feedback_fn("Creating aditional volumes...")
10726
    # first, create the missing data and meta devices
10727
    for disk in new_disks:
10728
      # unfortunately this is... not too nice
10729
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
10730
                            info, True)
10731
      for child in disk.children:
10732
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
10733
    # at this stage, all new LVs have been created, we can rename the
10734
    # old ones
10735
    feedback_fn("Renaming original volumes...")
10736
    rename_list = [(o, n.children[0].logical_id)
10737
                   for (o, n) in zip(instance.disks, new_disks)]
10738
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
10739
    result.Raise("Failed to rename original LVs")
10740

    
10741
    feedback_fn("Initializing DRBD devices...")
10742
    # all child devices are in place, we can now create the DRBD devices
10743
    for disk in new_disks:
10744
      for node in [pnode, snode]:
10745
        f_create = node == pnode
10746
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
10747

    
10748
    # at this point, the instance has been modified
10749
    instance.disk_template = constants.DT_DRBD8
10750
    instance.disks = new_disks
10751
    self.cfg.Update(instance, feedback_fn)
10752

    
10753
    # disks are created, waiting for sync
10754
    disk_abort = not _WaitForSync(self, instance,
10755
                                  oneshot=not self.op.wait_for_sync)
10756
    if disk_abort:
10757
      raise errors.OpExecError("There are some degraded disks for"
10758
                               " this instance, please cleanup manually")
10759

    
10760
  def _ConvertDrbdToPlain(self, feedback_fn):
10761
    """Converts an instance from drbd to plain.
10762

10763
    """
10764
    instance = self.instance
10765
    assert len(instance.secondary_nodes) == 1
10766
    pnode = instance.primary_node
10767
    snode = instance.secondary_nodes[0]
10768
    feedback_fn("Converting template to plain")
10769

    
10770
    old_disks = instance.disks
10771
    new_disks = [d.children[0] for d in old_disks]
10772

    
10773
    # copy over size and mode
10774
    for parent, child in zip(old_disks, new_disks):
10775
      child.size = parent.size
10776
      child.mode = parent.mode
10777

    
10778
    # update instance structure
10779
    instance.disks = new_disks
10780
    instance.disk_template = constants.DT_PLAIN
10781
    self.cfg.Update(instance, feedback_fn)
10782

    
10783
    feedback_fn("Removing volumes on the secondary node...")
10784
    for disk in old_disks:
10785
      self.cfg.SetDiskID(disk, snode)
10786
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
10787
      if msg:
10788
        self.LogWarning("Could not remove block device %s on node %s,"
10789
                        " continuing anyway: %s", disk.iv_name, snode, msg)
10790

    
10791
    feedback_fn("Removing unneeded volumes on the primary node...")
10792
    for idx, disk in enumerate(old_disks):
10793
      meta = disk.children[1]
10794
      self.cfg.SetDiskID(meta, pnode)
10795
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
10796
      if msg:
10797
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
10798
                        " continuing anyway: %s", idx, pnode, msg)
10799

    
10800
  def Exec(self, feedback_fn):
10801
    """Modifies an instance.
10802

10803
    All parameters take effect only at the next restart of the instance.
10804

10805
    """
10806
    # Process here the warnings from CheckPrereq, as we don't have a
10807
    # feedback_fn there.
10808
    for warn in self.warn:
10809
      feedback_fn("WARNING: %s" % warn)
10810

    
10811
    result = []
10812
    instance = self.instance
10813
    # disk changes
10814
    for disk_op, disk_dict in self.op.disks:
10815
      if disk_op == constants.DDM_REMOVE:
10816
        # remove the last disk
10817
        device = instance.disks.pop()
10818
        device_idx = len(instance.disks)
10819
        for node, disk in device.ComputeNodeTree(instance.primary_node):
10820
          self.cfg.SetDiskID(disk, node)
10821
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
10822
          if msg:
10823
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
10824
                            " continuing anyway", device_idx, node, msg)
10825
        result.append(("disk/%d" % device_idx, "remove"))
10826
      elif disk_op == constants.DDM_ADD:
10827
        # add a new disk
10828
        if instance.disk_template in (constants.DT_FILE,
10829
                                        constants.DT_SHARED_FILE):
10830
          file_driver, file_path = instance.disks[0].logical_id
10831
          file_path = os.path.dirname(file_path)
10832
        else:
10833
          file_driver = file_path = None
10834
        disk_idx_base = len(instance.disks)
10835
        new_disk = _GenerateDiskTemplate(self,
10836
                                         instance.disk_template,
10837
                                         instance.name, instance.primary_node,
10838
                                         instance.secondary_nodes,
10839
                                         [disk_dict],
10840
                                         file_path,
10841
                                         file_driver,
10842
                                         disk_idx_base, feedback_fn)[0]
10843
        instance.disks.append(new_disk)
10844
        info = _GetInstanceInfoText(instance)
10845

    
10846
        logging.info("Creating volume %s for instance %s",
10847
                     new_disk.iv_name, instance.name)
10848
        # Note: this needs to be kept in sync with _CreateDisks
10849
        #HARDCODE
10850
        for node in instance.all_nodes:
10851
          f_create = node == instance.primary_node
10852
          try:
10853
            _CreateBlockDev(self, node, instance, new_disk,
10854
                            f_create, info, f_create)
10855
          except errors.OpExecError, err:
10856
            self.LogWarning("Failed to create volume %s (%s) on"
10857
                            " node %s: %s",
10858
                            new_disk.iv_name, new_disk, node, err)
10859
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
10860
                       (new_disk.size, new_disk.mode)))
10861
      else:
10862
        # change a given disk
10863
        instance.disks[disk_op].mode = disk_dict[constants.IDISK_MODE]
10864
        result.append(("disk.mode/%d" % disk_op,
10865
                       disk_dict[constants.IDISK_MODE]))
10866

    
10867
    if self.op.disk_template:
10868
      r_shut = _ShutdownInstanceDisks(self, instance)
10869
      if not r_shut:
10870
        raise errors.OpExecError("Cannot shutdown instance disks, unable to"
10871
                                 " proceed with disk template conversion")
10872
      mode = (instance.disk_template, self.op.disk_template)
10873
      try:
10874
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
10875
      except:
10876
        self.cfg.ReleaseDRBDMinors(instance.name)
10877
        raise
10878
      result.append(("disk_template", self.op.disk_template))
10879

    
10880
    # NIC changes
10881
    for nic_op, nic_dict in self.op.nics:
10882
      if nic_op == constants.DDM_REMOVE:
10883
        # remove the last nic
10884
        del instance.nics[-1]
10885
        result.append(("nic.%d" % len(instance.nics), "remove"))
10886
      elif nic_op == constants.DDM_ADD:
10887
        # mac and bridge should be set, by now
10888
        mac = nic_dict[constants.INIC_MAC]
10889
        ip = nic_dict.get(constants.INIC_IP, None)
10890
        nicparams = self.nic_pinst[constants.DDM_ADD]
10891
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
10892
        instance.nics.append(new_nic)
10893
        result.append(("nic.%d" % (len(instance.nics) - 1),
10894
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
10895
                       (new_nic.mac, new_nic.ip,
10896
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
10897
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
10898
                       )))
10899
      else:
10900
        for key in (constants.INIC_MAC, constants.INIC_IP):
10901
          if key in nic_dict:
10902
            setattr(instance.nics[nic_op], key, nic_dict[key])
10903
        if nic_op in self.nic_pinst:
10904
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
10905
        for key, val in nic_dict.iteritems():
10906
          result.append(("nic.%s/%d" % (key, nic_op), val))
10907

    
10908
    # hvparams changes
10909
    if self.op.hvparams:
10910
      instance.hvparams = self.hv_inst
10911
      for key, val in self.op.hvparams.iteritems():
10912
        result.append(("hv/%s" % key, val))
10913

    
10914
    # beparams changes
10915
    if self.op.beparams:
10916
      instance.beparams = self.be_inst
10917
      for key, val in self.op.beparams.iteritems():
10918
        result.append(("be/%s" % key, val))
10919

    
10920
    # OS change
10921
    if self.op.os_name:
10922
      instance.os = self.op.os_name
10923

    
10924
    # osparams changes
10925
    if self.op.osparams:
10926
      instance.osparams = self.os_inst
10927
      for key, val in self.op.osparams.iteritems():
10928
        result.append(("os/%s" % key, val))
10929

    
10930
    self.cfg.Update(instance, feedback_fn)
10931

    
10932
    return result
10933

    
10934
  _DISK_CONVERSIONS = {
10935
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
10936
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
10937
    }
10938

    
10939

    
10940
class LUBackupQuery(NoHooksLU):
10941
  """Query the exports list
10942

10943
  """
10944
  REQ_BGL = False
10945

    
10946
  def ExpandNames(self):
10947
    self.needed_locks = {}
10948
    self.share_locks[locking.LEVEL_NODE] = 1
10949
    if not self.op.nodes:
10950
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10951
    else:
10952
      self.needed_locks[locking.LEVEL_NODE] = \
10953
        _GetWantedNodes(self, self.op.nodes)
10954

    
10955
  def Exec(self, feedback_fn):
10956
    """Compute the list of all the exported system images.
10957

10958
    @rtype: dict
10959
    @return: a dictionary with the structure node->(export-list)
10960
        where export-list is a list of the instances exported on
10961
        that node.
10962

10963
    """
10964
    self.nodes = self.glm.list_owned(locking.LEVEL_NODE)
10965
    rpcresult = self.rpc.call_export_list(self.nodes)
10966
    result = {}
10967
    for node in rpcresult:
10968
      if rpcresult[node].fail_msg:
10969
        result[node] = False
10970
      else:
10971
        result[node] = rpcresult[node].payload
10972

    
10973
    return result
10974

    
10975

    
10976
class LUBackupPrepare(NoHooksLU):
10977
  """Prepares an instance for an export and returns useful information.
10978

10979
  """
10980
  REQ_BGL = False
10981

    
10982
  def ExpandNames(self):
10983
    self._ExpandAndLockInstance()
10984

    
10985
  def CheckPrereq(self):
10986
    """Check prerequisites.
10987

10988
    """
10989
    instance_name = self.op.instance_name
10990

    
10991
    self.instance = self.cfg.GetInstanceInfo(instance_name)
10992
    assert self.instance is not None, \
10993
          "Cannot retrieve locked instance %s" % self.op.instance_name
10994
    _CheckNodeOnline(self, self.instance.primary_node)
10995

    
10996
    self._cds = _GetClusterDomainSecret()
10997

    
10998
  def Exec(self, feedback_fn):
10999
    """Prepares an instance for an export.
11000

11001
    """
11002
    instance = self.instance
11003

    
11004
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
11005
      salt = utils.GenerateSecret(8)
11006

    
11007
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
11008
      result = self.rpc.call_x509_cert_create(instance.primary_node,
11009
                                              constants.RIE_CERT_VALIDITY)
11010
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
11011

    
11012
      (name, cert_pem) = result.payload
11013

    
11014
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
11015
                                             cert_pem)
11016

    
11017
      return {
11018
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
11019
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
11020
                          salt),
11021
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
11022
        }
11023

    
11024
    return None
11025

    
11026

    
11027
class LUBackupExport(LogicalUnit):
11028
  """Export an instance to an image in the cluster.
11029

11030
  """
11031
  HPATH = "instance-export"
11032
  HTYPE = constants.HTYPE_INSTANCE
11033
  REQ_BGL = False
11034

    
11035
  def CheckArguments(self):
11036
    """Check the arguments.
11037

11038
    """
11039
    self.x509_key_name = self.op.x509_key_name
11040
    self.dest_x509_ca_pem = self.op.destination_x509_ca
11041

    
11042
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
11043
      if not self.x509_key_name:
11044
        raise errors.OpPrereqError("Missing X509 key name for encryption",
11045
                                   errors.ECODE_INVAL)
11046

    
11047
      if not self.dest_x509_ca_pem:
11048
        raise errors.OpPrereqError("Missing destination X509 CA",
11049
                                   errors.ECODE_INVAL)
11050

    
11051
  def ExpandNames(self):
11052
    self._ExpandAndLockInstance()
11053

    
11054
    # Lock all nodes for local exports
11055
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
11056
      # FIXME: lock only instance primary and destination node
11057
      #
11058
      # Sad but true, for now we have do lock all nodes, as we don't know where
11059
      # the previous export might be, and in this LU we search for it and
11060
      # remove it from its current node. In the future we could fix this by:
11061
      #  - making a tasklet to search (share-lock all), then create the
11062
      #    new one, then one to remove, after
11063
      #  - removing the removal operation altogether
11064
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
11065

    
11066
  def DeclareLocks(self, level):
11067
    """Last minute lock declaration."""
11068
    # All nodes are locked anyway, so nothing to do here.
11069

    
11070
  def BuildHooksEnv(self):
11071
    """Build hooks env.
11072

11073
    This will run on the master, primary node and target node.
11074

11075
    """
11076
    env = {
11077
      "EXPORT_MODE": self.op.mode,
11078
      "EXPORT_NODE": self.op.target_node,
11079
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
11080
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
11081
      # TODO: Generic function for boolean env variables
11082
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
11083
      }
11084

    
11085
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
11086

    
11087
    return env
11088

    
11089
  def BuildHooksNodes(self):
11090
    """Build hooks nodes.
11091

11092
    """
11093
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
11094

    
11095
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
11096
      nl.append(self.op.target_node)
11097

    
11098
    return (nl, nl)
11099

    
11100
  def CheckPrereq(self):
11101
    """Check prerequisites.
11102

11103
    This checks that the instance and node names are valid.
11104

11105
    """
11106
    instance_name = self.op.instance_name
11107

    
11108
    self.instance = self.cfg.GetInstanceInfo(instance_name)
11109
    assert self.instance is not None, \
11110
          "Cannot retrieve locked instance %s" % self.op.instance_name
11111
    _CheckNodeOnline(self, self.instance.primary_node)
11112

    
11113
    if (self.op.remove_instance and self.instance.admin_up and
11114
        not self.op.shutdown):
11115
      raise errors.OpPrereqError("Can not remove instance without shutting it"
11116
                                 " down before")
11117

    
11118
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
11119
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
11120
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
11121
      assert self.dst_node is not None
11122

    
11123
      _CheckNodeOnline(self, self.dst_node.name)
11124
      _CheckNodeNotDrained(self, self.dst_node.name)
11125

    
11126
      self._cds = None
11127
      self.dest_disk_info = None
11128
      self.dest_x509_ca = None
11129

    
11130
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
11131
      self.dst_node = None
11132

    
11133
      if len(self.op.target_node) != len(self.instance.disks):
11134
        raise errors.OpPrereqError(("Received destination information for %s"
11135
                                    " disks, but instance %s has %s disks") %
11136
                                   (len(self.op.target_node), instance_name,
11137
                                    len(self.instance.disks)),
11138
                                   errors.ECODE_INVAL)
11139

    
11140
      cds = _GetClusterDomainSecret()
11141

    
11142
      # Check X509 key name
11143
      try:
11144
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
11145
      except (TypeError, ValueError), err:
11146
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
11147

    
11148
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
11149
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
11150
                                   errors.ECODE_INVAL)
11151

    
11152
      # Load and verify CA
11153
      try:
11154
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
11155
      except OpenSSL.crypto.Error, err:
11156
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
11157
                                   (err, ), errors.ECODE_INVAL)
11158

    
11159
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
11160
      if errcode is not None:
11161
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
11162
                                   (msg, ), errors.ECODE_INVAL)
11163

    
11164
      self.dest_x509_ca = cert
11165

    
11166
      # Verify target information
11167
      disk_info = []
11168
      for idx, disk_data in enumerate(self.op.target_node):
11169
        try:
11170
          (host, port, magic) = \
11171
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
11172
        except errors.GenericError, err:
11173
          raise errors.OpPrereqError("Target info for disk %s: %s" %
11174
                                     (idx, err), errors.ECODE_INVAL)
11175

    
11176
        disk_info.append((host, port, magic))
11177

    
11178
      assert len(disk_info) == len(self.op.target_node)
11179
      self.dest_disk_info = disk_info
11180

    
11181
    else:
11182
      raise errors.ProgrammerError("Unhandled export mode %r" %
11183
                                   self.op.mode)
11184

    
11185
    # instance disk type verification
11186
    # TODO: Implement export support for file-based disks
11187
    for disk in self.instance.disks:
11188
      if disk.dev_type == constants.LD_FILE:
11189
        raise errors.OpPrereqError("Export not supported for instances with"
11190
                                   " file-based disks", errors.ECODE_INVAL)
11191

    
11192
  def _CleanupExports(self, feedback_fn):
11193
    """Removes exports of current instance from all other nodes.
11194

11195
    If an instance in a cluster with nodes A..D was exported to node C, its
11196
    exports will be removed from the nodes A, B and D.
11197

11198
    """
11199
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
11200

    
11201
    nodelist = self.cfg.GetNodeList()
11202
    nodelist.remove(self.dst_node.name)
11203

    
11204
    # on one-node clusters nodelist will be empty after the removal
11205
    # if we proceed the backup would be removed because OpBackupQuery
11206
    # substitutes an empty list with the full cluster node list.
11207
    iname = self.instance.name
11208
    if nodelist:
11209
      feedback_fn("Removing old exports for instance %s" % iname)
11210
      exportlist = self.rpc.call_export_list(nodelist)
11211
      for node in exportlist:
11212
        if exportlist[node].fail_msg:
11213
          continue
11214
        if iname in exportlist[node].payload:
11215
          msg = self.rpc.call_export_remove(node, iname).fail_msg
11216
          if msg:
11217
            self.LogWarning("Could not remove older export for instance %s"
11218
                            " on node %s: %s", iname, node, msg)
11219

    
11220
  def Exec(self, feedback_fn):
11221
    """Export an instance to an image in the cluster.
11222

11223
    """
11224
    assert self.op.mode in constants.EXPORT_MODES
11225

    
11226
    instance = self.instance
11227
    src_node = instance.primary_node
11228

    
11229
    if self.op.shutdown:
11230
      # shutdown the instance, but not the disks
11231
      feedback_fn("Shutting down instance %s" % instance.name)
11232
      result = self.rpc.call_instance_shutdown(src_node, instance,
11233
                                               self.op.shutdown_timeout)
11234
      # TODO: Maybe ignore failures if ignore_remove_failures is set
11235
      result.Raise("Could not shutdown instance %s on"
11236
                   " node %s" % (instance.name, src_node))
11237

    
11238
    # set the disks ID correctly since call_instance_start needs the
11239
    # correct drbd minor to create the symlinks
11240
    for disk in instance.disks:
11241
      self.cfg.SetDiskID(disk, src_node)
11242

    
11243
    activate_disks = (not instance.admin_up)
11244

    
11245
    if activate_disks:
11246
      # Activate the instance disks if we'exporting a stopped instance
11247
      feedback_fn("Activating disks for %s" % instance.name)
11248
      _StartInstanceDisks(self, instance, None)
11249

    
11250
    try:
11251
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
11252
                                                     instance)
11253

    
11254
      helper.CreateSnapshots()
11255
      try:
11256
        if (self.op.shutdown and instance.admin_up and
11257
            not self.op.remove_instance):
11258
          assert not activate_disks
11259
          feedback_fn("Starting instance %s" % instance.name)
11260
          result = self.rpc.call_instance_start(src_node, instance,
11261
                                                None, None, False)
11262
          msg = result.fail_msg
11263
          if msg:
11264
            feedback_fn("Failed to start instance: %s" % msg)
11265
            _ShutdownInstanceDisks(self, instance)
11266
            raise errors.OpExecError("Could not start instance: %s" % msg)
11267

    
11268
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
11269
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
11270
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
11271
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
11272
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
11273

    
11274
          (key_name, _, _) = self.x509_key_name
11275

    
11276
          dest_ca_pem = \
11277
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
11278
                                            self.dest_x509_ca)
11279

    
11280
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
11281
                                                     key_name, dest_ca_pem,
11282
                                                     timeouts)
11283
      finally:
11284
        helper.Cleanup()
11285

    
11286
      # Check for backwards compatibility
11287
      assert len(dresults) == len(instance.disks)
11288
      assert compat.all(isinstance(i, bool) for i in dresults), \
11289
             "Not all results are boolean: %r" % dresults
11290

    
11291
    finally:
11292
      if activate_disks:
11293
        feedback_fn("Deactivating disks for %s" % instance.name)
11294
        _ShutdownInstanceDisks(self, instance)
11295

    
11296
    if not (compat.all(dresults) and fin_resu):
11297
      failures = []
11298
      if not fin_resu:
11299
        failures.append("export finalization")
11300
      if not compat.all(dresults):
11301
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
11302
                               if not dsk)
11303
        failures.append("disk export: disk(s) %s" % fdsk)
11304

    
11305
      raise errors.OpExecError("Export failed, errors in %s" %
11306
                               utils.CommaJoin(failures))
11307

    
11308
    # At this point, the export was successful, we can cleanup/finish
11309

    
11310
    # Remove instance if requested
11311
    if self.op.remove_instance:
11312
      feedback_fn("Removing instance %s" % instance.name)
11313
      _RemoveInstance(self, feedback_fn, instance,
11314
                      self.op.ignore_remove_failures)
11315

    
11316
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
11317
      self._CleanupExports(feedback_fn)
11318

    
11319
    return fin_resu, dresults
11320

    
11321

    
11322
class LUBackupRemove(NoHooksLU):
11323
  """Remove exports related to the named instance.
11324

11325
  """
11326
  REQ_BGL = False
11327

    
11328
  def ExpandNames(self):
11329
    self.needed_locks = {}
11330
    # We need all nodes to be locked in order for RemoveExport to work, but we
11331
    # don't need to lock the instance itself, as nothing will happen to it (and
11332
    # we can remove exports also for a removed instance)
11333
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
11334

    
11335
  def Exec(self, feedback_fn):
11336
    """Remove any export.
11337

11338
    """
11339
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
11340
    # If the instance was not found we'll try with the name that was passed in.
11341
    # This will only work if it was an FQDN, though.
11342
    fqdn_warn = False
11343
    if not instance_name:
11344
      fqdn_warn = True
11345
      instance_name = self.op.instance_name
11346

    
11347
    locked_nodes = self.glm.list_owned(locking.LEVEL_NODE)
11348
    exportlist = self.rpc.call_export_list(locked_nodes)
11349
    found = False
11350
    for node in exportlist:
11351
      msg = exportlist[node].fail_msg
11352
      if msg:
11353
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
11354
        continue
11355
      if instance_name in exportlist[node].payload:
11356
        found = True
11357
        result = self.rpc.call_export_remove(node, instance_name)
11358
        msg = result.fail_msg
11359
        if msg:
11360
          logging.error("Could not remove export for instance %s"
11361
                        " on node %s: %s", instance_name, node, msg)
11362

    
11363
    if fqdn_warn and not found:
11364
      feedback_fn("Export not found. If trying to remove an export belonging"
11365
                  " to a deleted instance please use its Fully Qualified"
11366
                  " Domain Name.")
11367

    
11368

    
11369
class LUGroupAdd(LogicalUnit):
11370
  """Logical unit for creating node groups.
11371

11372
  """
11373
  HPATH = "group-add"
11374
  HTYPE = constants.HTYPE_GROUP
11375
  REQ_BGL = False
11376

    
11377
  def ExpandNames(self):
11378
    # We need the new group's UUID here so that we can create and acquire the
11379
    # corresponding lock. Later, in Exec(), we'll indicate to cfg.AddNodeGroup
11380
    # that it should not check whether the UUID exists in the configuration.
11381
    self.group_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
11382
    self.needed_locks = {}
11383
    self.add_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
11384

    
11385
  def CheckPrereq(self):
11386
    """Check prerequisites.
11387

11388
    This checks that the given group name is not an existing node group
11389
    already.
11390

11391
    """
11392
    try:
11393
      existing_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11394
    except errors.OpPrereqError:
11395
      pass
11396
    else:
11397
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
11398
                                 " node group (UUID: %s)" %
11399
                                 (self.op.group_name, existing_uuid),
11400
                                 errors.ECODE_EXISTS)
11401

    
11402
    if self.op.ndparams:
11403
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
11404

    
11405
  def BuildHooksEnv(self):
11406
    """Build hooks env.
11407

11408
    """
11409
    return {
11410
      "GROUP_NAME": self.op.group_name,
11411
      }
11412

    
11413
  def BuildHooksNodes(self):
11414
    """Build hooks nodes.
11415

11416
    """
11417
    mn = self.cfg.GetMasterNode()
11418
    return ([mn], [mn])
11419

    
11420
  def Exec(self, feedback_fn):
11421
    """Add the node group to the cluster.
11422

11423
    """
11424
    group_obj = objects.NodeGroup(name=self.op.group_name, members=[],
11425
                                  uuid=self.group_uuid,
11426
                                  alloc_policy=self.op.alloc_policy,
11427
                                  ndparams=self.op.ndparams)
11428

    
11429
    self.cfg.AddNodeGroup(group_obj, self.proc.GetECId(), check_uuid=False)
11430
    del self.remove_locks[locking.LEVEL_NODEGROUP]
11431

    
11432

    
11433
class LUGroupAssignNodes(NoHooksLU):
11434
  """Logical unit for assigning nodes to groups.
11435

11436
  """
11437
  REQ_BGL = False
11438

    
11439
  def ExpandNames(self):
11440
    # These raise errors.OpPrereqError on their own:
11441
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11442
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
11443

    
11444
    # We want to lock all the affected nodes and groups. We have readily
11445
    # available the list of nodes, and the *destination* group. To gather the
11446
    # list of "source" groups, we need to fetch node information later on.
11447
    self.needed_locks = {
11448
      locking.LEVEL_NODEGROUP: set([self.group_uuid]),
11449
      locking.LEVEL_NODE: self.op.nodes,
11450
      }
11451

    
11452
  def DeclareLocks(self, level):
11453
    if level == locking.LEVEL_NODEGROUP:
11454
      assert len(self.needed_locks[locking.LEVEL_NODEGROUP]) == 1
11455

    
11456
      # Try to get all affected nodes' groups without having the group or node
11457
      # lock yet. Needs verification later in the code flow.
11458
      groups = self.cfg.GetNodeGroupsFromNodes(self.op.nodes)
11459

    
11460
      self.needed_locks[locking.LEVEL_NODEGROUP].update(groups)
11461

    
11462
  def CheckPrereq(self):
11463
    """Check prerequisites.
11464

11465
    """
11466
    assert self.needed_locks[locking.LEVEL_NODEGROUP]
11467
    assert (frozenset(self.glm.list_owned(locking.LEVEL_NODE)) ==
11468
            frozenset(self.op.nodes))
11469

    
11470
    expected_locks = (set([self.group_uuid]) |
11471
                      self.cfg.GetNodeGroupsFromNodes(self.op.nodes))
11472
    actual_locks = self.glm.list_owned(locking.LEVEL_NODEGROUP)
11473
    if actual_locks != expected_locks:
11474
      raise errors.OpExecError("Nodes changed groups since locks were acquired,"
11475
                               " current groups are '%s', used to be '%s'" %
11476
                               (utils.CommaJoin(expected_locks),
11477
                                utils.CommaJoin(actual_locks)))
11478

    
11479
    self.node_data = self.cfg.GetAllNodesInfo()
11480
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
11481
    instance_data = self.cfg.GetAllInstancesInfo()
11482

    
11483
    if self.group is None:
11484
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11485
                               (self.op.group_name, self.group_uuid))
11486

    
11487
    (new_splits, previous_splits) = \
11488
      self.CheckAssignmentForSplitInstances([(node, self.group_uuid)
11489
                                             for node in self.op.nodes],
11490
                                            self.node_data, instance_data)
11491

    
11492
    if new_splits:
11493
      fmt_new_splits = utils.CommaJoin(utils.NiceSort(new_splits))
11494

    
11495
      if not self.op.force:
11496
        raise errors.OpExecError("The following instances get split by this"
11497
                                 " change and --force was not given: %s" %
11498
                                 fmt_new_splits)
11499
      else:
11500
        self.LogWarning("This operation will split the following instances: %s",
11501
                        fmt_new_splits)
11502

    
11503
        if previous_splits:
11504
          self.LogWarning("In addition, these already-split instances continue"
11505
                          " to be split across groups: %s",
11506
                          utils.CommaJoin(utils.NiceSort(previous_splits)))
11507

    
11508
  def Exec(self, feedback_fn):
11509
    """Assign nodes to a new group.
11510

11511
    """
11512
    for node in self.op.nodes:
11513
      self.node_data[node].group = self.group_uuid
11514

    
11515
    # FIXME: Depends on side-effects of modifying the result of
11516
    # C{cfg.GetAllNodesInfo}
11517

    
11518
    self.cfg.Update(self.group, feedback_fn) # Saves all modified nodes.
11519

    
11520
  @staticmethod
11521
  def CheckAssignmentForSplitInstances(changes, node_data, instance_data):
11522
    """Check for split instances after a node assignment.
11523

11524
    This method considers a series of node assignments as an atomic operation,
11525
    and returns information about split instances after applying the set of
11526
    changes.
11527

11528
    In particular, it returns information about newly split instances, and
11529
    instances that were already split, and remain so after the change.
11530

11531
    Only instances whose disk template is listed in constants.DTS_INT_MIRROR are
11532
    considered.
11533

11534
    @type changes: list of (node_name, new_group_uuid) pairs.
11535
    @param changes: list of node assignments to consider.
11536
    @param node_data: a dict with data for all nodes
11537
    @param instance_data: a dict with all instances to consider
11538
    @rtype: a two-tuple
11539
    @return: a list of instances that were previously okay and result split as a
11540
      consequence of this change, and a list of instances that were previously
11541
      split and this change does not fix.
11542

11543
    """
11544
    changed_nodes = dict((node, group) for node, group in changes
11545
                         if node_data[node].group != group)
11546

    
11547
    all_split_instances = set()
11548
    previously_split_instances = set()
11549

    
11550
    def InstanceNodes(instance):
11551
      return [instance.primary_node] + list(instance.secondary_nodes)
11552

    
11553
    for inst in instance_data.values():
11554
      if inst.disk_template not in constants.DTS_INT_MIRROR:
11555
        continue
11556

    
11557
      instance_nodes = InstanceNodes(inst)
11558

    
11559
      if len(set(node_data[node].group for node in instance_nodes)) > 1:
11560
        previously_split_instances.add(inst.name)
11561

    
11562
      if len(set(changed_nodes.get(node, node_data[node].group)
11563
                 for node in instance_nodes)) > 1:
11564
        all_split_instances.add(inst.name)
11565

    
11566
    return (list(all_split_instances - previously_split_instances),
11567
            list(previously_split_instances & all_split_instances))
11568

    
11569

    
11570
class _GroupQuery(_QueryBase):
11571
  FIELDS = query.GROUP_FIELDS
11572

    
11573
  def ExpandNames(self, lu):
11574
    lu.needed_locks = {}
11575

    
11576
    self._all_groups = lu.cfg.GetAllNodeGroupsInfo()
11577
    name_to_uuid = dict((g.name, g.uuid) for g in self._all_groups.values())
11578

    
11579
    if not self.names:
11580
      self.wanted = [name_to_uuid[name]
11581
                     for name in utils.NiceSort(name_to_uuid.keys())]
11582
    else:
11583
      # Accept names to be either names or UUIDs.
11584
      missing = []
11585
      self.wanted = []
11586
      all_uuid = frozenset(self._all_groups.keys())
11587

    
11588
      for name in self.names:
11589
        if name in all_uuid:
11590
          self.wanted.append(name)
11591
        elif name in name_to_uuid:
11592
          self.wanted.append(name_to_uuid[name])
11593
        else:
11594
          missing.append(name)
11595

    
11596
      if missing:
11597
        raise errors.OpPrereqError("Some groups do not exist: %s" %
11598
                                   utils.CommaJoin(missing),
11599
                                   errors.ECODE_NOENT)
11600

    
11601
  def DeclareLocks(self, lu, level):
11602
    pass
11603

    
11604
  def _GetQueryData(self, lu):
11605
    """Computes the list of node groups and their attributes.
11606

11607
    """
11608
    do_nodes = query.GQ_NODE in self.requested_data
11609
    do_instances = query.GQ_INST in self.requested_data
11610

    
11611
    group_to_nodes = None
11612
    group_to_instances = None
11613

    
11614
    # For GQ_NODE, we need to map group->[nodes], and group->[instances] for
11615
    # GQ_INST. The former is attainable with just GetAllNodesInfo(), but for the
11616
    # latter GetAllInstancesInfo() is not enough, for we have to go through
11617
    # instance->node. Hence, we will need to process nodes even if we only need
11618
    # instance information.
11619
    if do_nodes or do_instances:
11620
      all_nodes = lu.cfg.GetAllNodesInfo()
11621
      group_to_nodes = dict((uuid, []) for uuid in self.wanted)
11622
      node_to_group = {}
11623

    
11624
      for node in all_nodes.values():
11625
        if node.group in group_to_nodes:
11626
          group_to_nodes[node.group].append(node.name)
11627
          node_to_group[node.name] = node.group
11628

    
11629
      if do_instances:
11630
        all_instances = lu.cfg.GetAllInstancesInfo()
11631
        group_to_instances = dict((uuid, []) for uuid in self.wanted)
11632

    
11633
        for instance in all_instances.values():
11634
          node = instance.primary_node
11635
          if node in node_to_group:
11636
            group_to_instances[node_to_group[node]].append(instance.name)
11637

    
11638
        if not do_nodes:
11639
          # Do not pass on node information if it was not requested.
11640
          group_to_nodes = None
11641

    
11642
    return query.GroupQueryData([self._all_groups[uuid]
11643
                                 for uuid in self.wanted],
11644
                                group_to_nodes, group_to_instances)
11645

    
11646

    
11647
class LUGroupQuery(NoHooksLU):
11648
  """Logical unit for querying node groups.
11649

11650
  """
11651
  REQ_BGL = False
11652

    
11653
  def CheckArguments(self):
11654
    self.gq = _GroupQuery(qlang.MakeSimpleFilter("name", self.op.names),
11655
                          self.op.output_fields, False)
11656

    
11657
  def ExpandNames(self):
11658
    self.gq.ExpandNames(self)
11659

    
11660
  def Exec(self, feedback_fn):
11661
    return self.gq.OldStyleQuery(self)
11662

    
11663

    
11664
class LUGroupSetParams(LogicalUnit):
11665
  """Modifies the parameters of a node group.
11666

11667
  """
11668
  HPATH = "group-modify"
11669
  HTYPE = constants.HTYPE_GROUP
11670
  REQ_BGL = False
11671

    
11672
  def CheckArguments(self):
11673
    all_changes = [
11674
      self.op.ndparams,
11675
      self.op.alloc_policy,
11676
      ]
11677

    
11678
    if all_changes.count(None) == len(all_changes):
11679
      raise errors.OpPrereqError("Please pass at least one modification",
11680
                                 errors.ECODE_INVAL)
11681

    
11682
  def ExpandNames(self):
11683
    # This raises errors.OpPrereqError on its own:
11684
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11685

    
11686
    self.needed_locks = {
11687
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11688
      }
11689

    
11690
  def CheckPrereq(self):
11691
    """Check prerequisites.
11692

11693
    """
11694
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
11695

    
11696
    if self.group is None:
11697
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11698
                               (self.op.group_name, self.group_uuid))
11699

    
11700
    if self.op.ndparams:
11701
      new_ndparams = _GetUpdatedParams(self.group.ndparams, self.op.ndparams)
11702
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
11703
      self.new_ndparams = new_ndparams
11704

    
11705
  def BuildHooksEnv(self):
11706
    """Build hooks env.
11707

11708
    """
11709
    return {
11710
      "GROUP_NAME": self.op.group_name,
11711
      "NEW_ALLOC_POLICY": self.op.alloc_policy,
11712
      }
11713

    
11714
  def BuildHooksNodes(self):
11715
    """Build hooks nodes.
11716

11717
    """
11718
    mn = self.cfg.GetMasterNode()
11719
    return ([mn], [mn])
11720

    
11721
  def Exec(self, feedback_fn):
11722
    """Modifies the node group.
11723

11724
    """
11725
    result = []
11726

    
11727
    if self.op.ndparams:
11728
      self.group.ndparams = self.new_ndparams
11729
      result.append(("ndparams", str(self.group.ndparams)))
11730

    
11731
    if self.op.alloc_policy:
11732
      self.group.alloc_policy = self.op.alloc_policy
11733

    
11734
    self.cfg.Update(self.group, feedback_fn)
11735
    return result
11736

    
11737

    
11738

    
11739
class LUGroupRemove(LogicalUnit):
11740
  HPATH = "group-remove"
11741
  HTYPE = constants.HTYPE_GROUP
11742
  REQ_BGL = False
11743

    
11744
  def ExpandNames(self):
11745
    # This will raises errors.OpPrereqError on its own:
11746
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11747
    self.needed_locks = {
11748
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11749
      }
11750

    
11751
  def CheckPrereq(self):
11752
    """Check prerequisites.
11753

11754
    This checks that the given group name exists as a node group, that is
11755
    empty (i.e., contains no nodes), and that is not the last group of the
11756
    cluster.
11757

11758
    """
11759
    # Verify that the group is empty.
11760
    group_nodes = [node.name
11761
                   for node in self.cfg.GetAllNodesInfo().values()
11762
                   if node.group == self.group_uuid]
11763

    
11764
    if group_nodes:
11765
      raise errors.OpPrereqError("Group '%s' not empty, has the following"
11766
                                 " nodes: %s" %
11767
                                 (self.op.group_name,
11768
                                  utils.CommaJoin(utils.NiceSort(group_nodes))),
11769
                                 errors.ECODE_STATE)
11770

    
11771
    # Verify the cluster would not be left group-less.
11772
    if len(self.cfg.GetNodeGroupList()) == 1:
11773
      raise errors.OpPrereqError("Group '%s' is the only group,"
11774
                                 " cannot be removed" %
11775
                                 self.op.group_name,
11776
                                 errors.ECODE_STATE)
11777

    
11778
  def BuildHooksEnv(self):
11779
    """Build hooks env.
11780

11781
    """
11782
    return {
11783
      "GROUP_NAME": self.op.group_name,
11784
      }
11785

    
11786
  def BuildHooksNodes(self):
11787
    """Build hooks nodes.
11788

11789
    """
11790
    mn = self.cfg.GetMasterNode()
11791
    return ([mn], [mn])
11792

    
11793
  def Exec(self, feedback_fn):
11794
    """Remove the node group.
11795

11796
    """
11797
    try:
11798
      self.cfg.RemoveNodeGroup(self.group_uuid)
11799
    except errors.ConfigurationError:
11800
      raise errors.OpExecError("Group '%s' with UUID %s disappeared" %
11801
                               (self.op.group_name, self.group_uuid))
11802

    
11803
    self.remove_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
11804

    
11805

    
11806
class LUGroupRename(LogicalUnit):
11807
  HPATH = "group-rename"
11808
  HTYPE = constants.HTYPE_GROUP
11809
  REQ_BGL = False
11810

    
11811
  def ExpandNames(self):
11812
    # This raises errors.OpPrereqError on its own:
11813
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11814

    
11815
    self.needed_locks = {
11816
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11817
      }
11818

    
11819
  def CheckPrereq(self):
11820
    """Check prerequisites.
11821

11822
    Ensures requested new name is not yet used.
11823

11824
    """
11825
    try:
11826
      new_name_uuid = self.cfg.LookupNodeGroup(self.op.new_name)
11827
    except errors.OpPrereqError:
11828
      pass
11829
    else:
11830
      raise errors.OpPrereqError("Desired new name '%s' clashes with existing"
11831
                                 " node group (UUID: %s)" %
11832
                                 (self.op.new_name, new_name_uuid),
11833
                                 errors.ECODE_EXISTS)
11834

    
11835
  def BuildHooksEnv(self):
11836
    """Build hooks env.
11837

11838
    """
11839
    return {
11840
      "OLD_NAME": self.op.group_name,
11841
      "NEW_NAME": self.op.new_name,
11842
      }
11843

    
11844
  def BuildHooksNodes(self):
11845
    """Build hooks nodes.
11846

11847
    """
11848
    mn = self.cfg.GetMasterNode()
11849

    
11850
    all_nodes = self.cfg.GetAllNodesInfo()
11851
    all_nodes.pop(mn, None)
11852

    
11853
    run_nodes = [mn]
11854
    run_nodes.extend(node.name for node in all_nodes.values()
11855
                     if node.group == self.group_uuid)
11856

    
11857
    return (run_nodes, run_nodes)
11858

    
11859
  def Exec(self, feedback_fn):
11860
    """Rename the node group.
11861

11862
    """
11863
    group = self.cfg.GetNodeGroup(self.group_uuid)
11864

    
11865
    if group is None:
11866
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11867
                               (self.op.group_name, self.group_uuid))
11868

    
11869
    group.name = self.op.new_name
11870
    self.cfg.Update(group, feedback_fn)
11871

    
11872
    return self.op.new_name
11873

    
11874

    
11875
class LUGroupEvacuate(LogicalUnit):
11876
  HPATH = "group-evacuate"
11877
  HTYPE = constants.HTYPE_GROUP
11878
  REQ_BGL = False
11879

    
11880
  def ExpandNames(self):
11881
    # This raises errors.OpPrereqError on its own:
11882
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11883

    
11884
    if self.op.target_groups:
11885
      self.req_target_uuids = map(self.cfg.LookupNodeGroup,
11886
                                  self.op.target_groups)
11887
    else:
11888
      self.req_target_uuids = []
11889

    
11890
    if self.group_uuid in self.req_target_uuids:
11891
      raise errors.OpPrereqError("Group to be evacuated (%s) can not be used"
11892
                                 " as a target group (targets are %s)" %
11893
                                 (self.group_uuid,
11894
                                  utils.CommaJoin(self.req_target_uuids)),
11895
                                 errors.ECODE_INVAL)
11896

    
11897
    if not self.op.iallocator:
11898
      # Use default iallocator
11899
      self.op.iallocator = self.cfg.GetDefaultIAllocator()
11900

    
11901
    if not self.op.iallocator:
11902
      raise errors.OpPrereqError("No iallocator was specified, neither in the"
11903
                                 " opcode nor as a cluster-wide default",
11904
                                 errors.ECODE_INVAL)
11905

    
11906
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
11907
    self.needed_locks = {
11908
      locking.LEVEL_INSTANCE: [],
11909
      locking.LEVEL_NODEGROUP: [],
11910
      locking.LEVEL_NODE: [],
11911
      }
11912

    
11913
  def DeclareLocks(self, level):
11914
    if level == locking.LEVEL_INSTANCE:
11915
      assert not self.needed_locks[locking.LEVEL_INSTANCE]
11916

    
11917
      # Lock instances optimistically, needs verification once node and group
11918
      # locks have been acquired
11919
      self.needed_locks[locking.LEVEL_INSTANCE] = \
11920
        self.cfg.GetNodeGroupInstances(self.group_uuid)
11921

    
11922
    elif level == locking.LEVEL_NODEGROUP:
11923
      assert not self.needed_locks[locking.LEVEL_NODEGROUP]
11924

    
11925
      if self.req_target_uuids:
11926
        lock_groups = set([self.group_uuid] + self.req_target_uuids)
11927

    
11928
        # Lock all groups used by instances optimistically; this requires going
11929
        # via the node before it's locked, requiring verification later on
11930
        lock_groups.update(group_uuid
11931
                           for instance_name in
11932
                             self.glm.list_owned(locking.LEVEL_INSTANCE)
11933
                           for group_uuid in
11934
                             self.cfg.GetInstanceNodeGroups(instance_name))
11935
      else:
11936
        # No target groups, need to lock all of them
11937
        lock_groups = locking.ALL_SET
11938

    
11939
      self.needed_locks[locking.LEVEL_NODEGROUP] = lock_groups
11940

    
11941
    elif level == locking.LEVEL_NODE:
11942
      # This will only lock the nodes in the group to be evacuated which
11943
      # contain actual instances
11944
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
11945
      self._LockInstancesNodes()
11946

    
11947
      # Lock all nodes in group to be evacuated
11948
      assert self.group_uuid in self.glm.list_owned(locking.LEVEL_NODEGROUP)
11949
      member_nodes = self.cfg.GetNodeGroup(self.group_uuid).members
11950
      self.needed_locks[locking.LEVEL_NODE].extend(member_nodes)
11951

    
11952
  def CheckPrereq(self):
11953
    owned_instances = frozenset(self.glm.list_owned(locking.LEVEL_INSTANCE))
11954
    owned_groups = frozenset(self.glm.list_owned(locking.LEVEL_NODEGROUP))
11955
    owned_nodes = frozenset(self.glm.list_owned(locking.LEVEL_NODE))
11956

    
11957
    assert owned_groups.issuperset(self.req_target_uuids)
11958
    assert self.group_uuid in owned_groups
11959

    
11960
    # Check if locked instances are still correct
11961
    wanted_instances = self.cfg.GetNodeGroupInstances(self.group_uuid)
11962
    if owned_instances != wanted_instances:
11963
      raise errors.OpPrereqError("Instances in node group to be evacuated (%s)"
11964
                                 " changed since locks were acquired, wanted"
11965
                                 " %s, have %s; retry the operation" %
11966
                                 (self.group_uuid,
11967
                                  utils.CommaJoin(wanted_instances),
11968
                                  utils.CommaJoin(owned_instances)),
11969
                                 errors.ECODE_STATE)
11970

    
11971
    # Get instance information
11972
    self.instances = dict((name, self.cfg.GetInstanceInfo(name))
11973
                          for name in owned_instances)
11974

    
11975
    # Check if node groups for locked instances are still correct
11976
    for instance_name in owned_instances:
11977
      inst = self.instances[instance_name]
11978
      assert self.group_uuid in self.cfg.GetInstanceNodeGroups(instance_name), \
11979
        "Instance %s has no node in group %s" % (instance_name, self.group_uuid)
11980
      assert owned_nodes.issuperset(inst.all_nodes), \
11981
        "Instance %s's nodes changed while we kept the lock" % instance_name
11982

    
11983
      inst_groups = self.cfg.GetInstanceNodeGroups(instance_name)
11984
      if not owned_groups.issuperset(inst_groups):
11985
        raise errors.OpPrereqError("Instance's node groups changed since locks"
11986
                                   " were acquired, current groups are '%s',"
11987
                                   " owning groups '%s'; retry the operation" %
11988
                                   (utils.CommaJoin(inst_groups),
11989
                                    utils.CommaJoin(owned_groups)),
11990
                                   errors.ECODE_STATE)
11991

    
11992
    if self.req_target_uuids:
11993
      # User requested specific target groups
11994
      self.target_uuids = self.req_target_uuids
11995
    else:
11996
      # All groups except the one to be evacuated are potential targets
11997
      self.target_uuids = [group_uuid for group_uuid in owned_groups
11998
                           if group_uuid != self.group_uuid]
11999

    
12000
      if not self.target_uuids:
12001
        raise errors.OpExecError("There are no possible target groups")
12002

    
12003
  def BuildHooksEnv(self):
12004
    """Build hooks env.
12005

12006
    """
12007
    return {
12008
      "GROUP_NAME": self.op.group_name,
12009
      "TARGET_GROUPS": " ".join(self.target_uuids),
12010
      }
12011

    
12012
  def BuildHooksNodes(self):
12013
    """Build hooks nodes.
12014

12015
    """
12016
    mn = self.cfg.GetMasterNode()
12017

    
12018
    assert self.group_uuid in self.glm.list_owned(locking.LEVEL_NODEGROUP)
12019

    
12020
    run_nodes = [mn] + self.cfg.GetNodeGroup(self.group_uuid).members
12021

    
12022
    return (run_nodes, run_nodes)
12023

    
12024
  def Exec(self, feedback_fn):
12025
    instances = list(self.glm.list_owned(locking.LEVEL_INSTANCE))
12026

    
12027
    assert self.group_uuid not in self.target_uuids
12028

    
12029
    ial = IAllocator(self.cfg, self.rpc, constants.IALLOCATOR_MODE_CHG_GROUP,
12030
                     instances=instances, target_groups=self.target_uuids)
12031

    
12032
    ial.Run(self.op.iallocator)
12033

    
12034
    if not ial.success:
12035
      raise errors.OpPrereqError("Can't compute group evacuation using"
12036
                                 " iallocator '%s': %s" %
12037
                                 (self.op.iallocator, ial.info),
12038
                                 errors.ECODE_NORES)
12039

    
12040
    jobs = _LoadNodeEvacResult(self, ial.result, self.op.early_release, False)
12041

    
12042
    self.LogInfo("Iallocator returned %s job(s) for evacuating node group %s",
12043
                 len(jobs), self.op.group_name)
12044

    
12045
    return ResultWithJobs(jobs)
12046

    
12047

    
12048
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
12049
  """Generic tags LU.
12050

12051
  This is an abstract class which is the parent of all the other tags LUs.
12052

12053
  """
12054
  def ExpandNames(self):
12055
    self.group_uuid = None
12056
    self.needed_locks = {}
12057
    if self.op.kind == constants.TAG_NODE:
12058
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
12059
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
12060
    elif self.op.kind == constants.TAG_INSTANCE:
12061
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
12062
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
12063
    elif self.op.kind == constants.TAG_NODEGROUP:
12064
      self.group_uuid = self.cfg.LookupNodeGroup(self.op.name)
12065

    
12066
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
12067
    # not possible to acquire the BGL based on opcode parameters)
12068

    
12069
  def CheckPrereq(self):
12070
    """Check prerequisites.
12071

12072
    """
12073
    if self.op.kind == constants.TAG_CLUSTER:
12074
      self.target = self.cfg.GetClusterInfo()
12075
    elif self.op.kind == constants.TAG_NODE:
12076
      self.target = self.cfg.GetNodeInfo(self.op.name)
12077
    elif self.op.kind == constants.TAG_INSTANCE:
12078
      self.target = self.cfg.GetInstanceInfo(self.op.name)
12079
    elif self.op.kind == constants.TAG_NODEGROUP:
12080
      self.target = self.cfg.GetNodeGroup(self.group_uuid)
12081
    else:
12082
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
12083
                                 str(self.op.kind), errors.ECODE_INVAL)
12084

    
12085

    
12086
class LUTagsGet(TagsLU):
12087
  """Returns the tags of a given object.
12088

12089
  """
12090
  REQ_BGL = False
12091

    
12092
  def ExpandNames(self):
12093
    TagsLU.ExpandNames(self)
12094

    
12095
    # Share locks as this is only a read operation
12096
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
12097

    
12098
  def Exec(self, feedback_fn):
12099
    """Returns the tag list.
12100

12101
    """
12102
    return list(self.target.GetTags())
12103

    
12104

    
12105
class LUTagsSearch(NoHooksLU):
12106
  """Searches the tags for a given pattern.
12107

12108
  """
12109
  REQ_BGL = False
12110

    
12111
  def ExpandNames(self):
12112
    self.needed_locks = {}
12113

    
12114
  def CheckPrereq(self):
12115
    """Check prerequisites.
12116

12117
    This checks the pattern passed for validity by compiling it.
12118

12119
    """
12120
    try:
12121
      self.re = re.compile(self.op.pattern)
12122
    except re.error, err:
12123
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
12124
                                 (self.op.pattern, err), errors.ECODE_INVAL)
12125

    
12126
  def Exec(self, feedback_fn):
12127
    """Returns the tag list.
12128

12129
    """
12130
    cfg = self.cfg
12131
    tgts = [("/cluster", cfg.GetClusterInfo())]
12132
    ilist = cfg.GetAllInstancesInfo().values()
12133
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
12134
    nlist = cfg.GetAllNodesInfo().values()
12135
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
12136
    tgts.extend(("/nodegroup/%s" % n.name, n)
12137
                for n in cfg.GetAllNodeGroupsInfo().values())
12138
    results = []
12139
    for path, target in tgts:
12140
      for tag in target.GetTags():
12141
        if self.re.search(tag):
12142
          results.append((path, tag))
12143
    return results
12144

    
12145

    
12146
class LUTagsSet(TagsLU):
12147
  """Sets a tag on a given object.
12148

12149
  """
12150
  REQ_BGL = False
12151

    
12152
  def CheckPrereq(self):
12153
    """Check prerequisites.
12154

12155
    This checks the type and length of the tag name and value.
12156

12157
    """
12158
    TagsLU.CheckPrereq(self)
12159
    for tag in self.op.tags:
12160
      objects.TaggableObject.ValidateTag(tag)
12161

    
12162
  def Exec(self, feedback_fn):
12163
    """Sets the tag.
12164

12165
    """
12166
    try:
12167
      for tag in self.op.tags:
12168
        self.target.AddTag(tag)
12169
    except errors.TagError, err:
12170
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
12171
    self.cfg.Update(self.target, feedback_fn)
12172

    
12173

    
12174
class LUTagsDel(TagsLU):
12175
  """Delete a list of tags from a given object.
12176

12177
  """
12178
  REQ_BGL = False
12179

    
12180
  def CheckPrereq(self):
12181
    """Check prerequisites.
12182

12183
    This checks that we have the given tag.
12184

12185
    """
12186
    TagsLU.CheckPrereq(self)
12187
    for tag in self.op.tags:
12188
      objects.TaggableObject.ValidateTag(tag)
12189
    del_tags = frozenset(self.op.tags)
12190
    cur_tags = self.target.GetTags()
12191

    
12192
    diff_tags = del_tags - cur_tags
12193
    if diff_tags:
12194
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
12195
      raise errors.OpPrereqError("Tag(s) %s not found" %
12196
                                 (utils.CommaJoin(diff_names), ),
12197
                                 errors.ECODE_NOENT)
12198

    
12199
  def Exec(self, feedback_fn):
12200
    """Remove the tag from the object.
12201

12202
    """
12203
    for tag in self.op.tags:
12204
      self.target.RemoveTag(tag)
12205
    self.cfg.Update(self.target, feedback_fn)
12206

    
12207

    
12208
class LUTestDelay(NoHooksLU):
12209
  """Sleep for a specified amount of time.
12210

12211
  This LU sleeps on the master and/or nodes for a specified amount of
12212
  time.
12213

12214
  """
12215
  REQ_BGL = False
12216

    
12217
  def ExpandNames(self):
12218
    """Expand names and set required locks.
12219

12220
    This expands the node list, if any.
12221

12222
    """
12223
    self.needed_locks = {}
12224
    if self.op.on_nodes:
12225
      # _GetWantedNodes can be used here, but is not always appropriate to use
12226
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
12227
      # more information.
12228
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
12229
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
12230

    
12231
  def _TestDelay(self):
12232
    """Do the actual sleep.
12233

12234
    """
12235
    if self.op.on_master:
12236
      if not utils.TestDelay(self.op.duration):
12237
        raise errors.OpExecError("Error during master delay test")
12238
    if self.op.on_nodes:
12239
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
12240
      for node, node_result in result.items():
12241
        node_result.Raise("Failure during rpc call to node %s" % node)
12242

    
12243
  def Exec(self, feedback_fn):
12244
    """Execute the test delay opcode, with the wanted repetitions.
12245

12246
    """
12247
    if self.op.repeat == 0:
12248
      self._TestDelay()
12249
    else:
12250
      top_value = self.op.repeat - 1
12251
      for i in range(self.op.repeat):
12252
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
12253
        self._TestDelay()
12254

    
12255

    
12256
class LUTestJqueue(NoHooksLU):
12257
  """Utility LU to test some aspects of the job queue.
12258

12259
  """
12260
  REQ_BGL = False
12261

    
12262
  # Must be lower than default timeout for WaitForJobChange to see whether it
12263
  # notices changed jobs
12264
  _CLIENT_CONNECT_TIMEOUT = 20.0
12265
  _CLIENT_CONFIRM_TIMEOUT = 60.0
12266

    
12267
  @classmethod
12268
  def _NotifyUsingSocket(cls, cb, errcls):
12269
    """Opens a Unix socket and waits for another program to connect.
12270

12271
    @type cb: callable
12272
    @param cb: Callback to send socket name to client
12273
    @type errcls: class
12274
    @param errcls: Exception class to use for errors
12275

12276
    """
12277
    # Using a temporary directory as there's no easy way to create temporary
12278
    # sockets without writing a custom loop around tempfile.mktemp and
12279
    # socket.bind
12280
    tmpdir = tempfile.mkdtemp()
12281
    try:
12282
      tmpsock = utils.PathJoin(tmpdir, "sock")
12283

    
12284
      logging.debug("Creating temporary socket at %s", tmpsock)
12285
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
12286
      try:
12287
        sock.bind(tmpsock)
12288
        sock.listen(1)
12289

    
12290
        # Send details to client
12291
        cb(tmpsock)
12292

    
12293
        # Wait for client to connect before continuing
12294
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
12295
        try:
12296
          (conn, _) = sock.accept()
12297
        except socket.error, err:
12298
          raise errcls("Client didn't connect in time (%s)" % err)
12299
      finally:
12300
        sock.close()
12301
    finally:
12302
      # Remove as soon as client is connected
12303
      shutil.rmtree(tmpdir)
12304

    
12305
    # Wait for client to close
12306
    try:
12307
      try:
12308
        # pylint: disable-msg=E1101
12309
        # Instance of '_socketobject' has no ... member
12310
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
12311
        conn.recv(1)
12312
      except socket.error, err:
12313
        raise errcls("Client failed to confirm notification (%s)" % err)
12314
    finally:
12315
      conn.close()
12316

    
12317
  def _SendNotification(self, test, arg, sockname):
12318
    """Sends a notification to the client.
12319

12320
    @type test: string
12321
    @param test: Test name
12322
    @param arg: Test argument (depends on test)
12323
    @type sockname: string
12324
    @param sockname: Socket path
12325

12326
    """
12327
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
12328

    
12329
  def _Notify(self, prereq, test, arg):
12330
    """Notifies the client of a test.
12331

12332
    @type prereq: bool
12333
    @param prereq: Whether this is a prereq-phase test
12334
    @type test: string
12335
    @param test: Test name
12336
    @param arg: Test argument (depends on test)
12337

12338
    """
12339
    if prereq:
12340
      errcls = errors.OpPrereqError
12341
    else:
12342
      errcls = errors.OpExecError
12343

    
12344
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
12345
                                                  test, arg),
12346
                                   errcls)
12347

    
12348
  def CheckArguments(self):
12349
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
12350
    self.expandnames_calls = 0
12351

    
12352
  def ExpandNames(self):
12353
    checkargs_calls = getattr(self, "checkargs_calls", 0)
12354
    if checkargs_calls < 1:
12355
      raise errors.ProgrammerError("CheckArguments was not called")
12356

    
12357
    self.expandnames_calls += 1
12358

    
12359
    if self.op.notify_waitlock:
12360
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
12361

    
12362
    self.LogInfo("Expanding names")
12363

    
12364
    # Get lock on master node (just to get a lock, not for a particular reason)
12365
    self.needed_locks = {
12366
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
12367
      }
12368

    
12369
  def Exec(self, feedback_fn):
12370
    if self.expandnames_calls < 1:
12371
      raise errors.ProgrammerError("ExpandNames was not called")
12372

    
12373
    if self.op.notify_exec:
12374
      self._Notify(False, constants.JQT_EXEC, None)
12375

    
12376
    self.LogInfo("Executing")
12377

    
12378
    if self.op.log_messages:
12379
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
12380
      for idx, msg in enumerate(self.op.log_messages):
12381
        self.LogInfo("Sending log message %s", idx + 1)
12382
        feedback_fn(constants.JQT_MSGPREFIX + msg)
12383
        # Report how many test messages have been sent
12384
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
12385

    
12386
    if self.op.fail:
12387
      raise errors.OpExecError("Opcode failure was requested")
12388

    
12389
    return True
12390

    
12391

    
12392
class IAllocator(object):
12393
  """IAllocator framework.
12394

12395
  An IAllocator instance has three sets of attributes:
12396
    - cfg that is needed to query the cluster
12397
    - input data (all members of the _KEYS class attribute are required)
12398
    - four buffer attributes (in|out_data|text), that represent the
12399
      input (to the external script) in text and data structure format,
12400
      and the output from it, again in two formats
12401
    - the result variables from the script (success, info, nodes) for
12402
      easy usage
12403

12404
  """
12405
  # pylint: disable-msg=R0902
12406
  # lots of instance attributes
12407

    
12408
  def __init__(self, cfg, rpc, mode, **kwargs):
12409
    self.cfg = cfg
12410
    self.rpc = rpc
12411
    # init buffer variables
12412
    self.in_text = self.out_text = self.in_data = self.out_data = None
12413
    # init all input fields so that pylint is happy
12414
    self.mode = mode
12415
    self.memory = self.disks = self.disk_template = None
12416
    self.os = self.tags = self.nics = self.vcpus = None
12417
    self.hypervisor = None
12418
    self.relocate_from = None
12419
    self.name = None
12420
    self.evac_nodes = None
12421
    self.instances = None
12422
    self.evac_mode = None
12423
    self.target_groups = []
12424
    # computed fields
12425
    self.required_nodes = None
12426
    # init result fields
12427
    self.success = self.info = self.result = None
12428

    
12429
    try:
12430
      (fn, keydata, self._result_check) = self._MODE_DATA[self.mode]
12431
    except KeyError:
12432
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
12433
                                   " IAllocator" % self.mode)
12434

    
12435
    keyset = [n for (n, _) in keydata]
12436

    
12437
    for key in kwargs:
12438
      if key not in keyset:
12439
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
12440
                                     " IAllocator" % key)
12441
      setattr(self, key, kwargs[key])
12442

    
12443
    for key in keyset:
12444
      if key not in kwargs:
12445
        raise errors.ProgrammerError("Missing input parameter '%s' to"
12446
                                     " IAllocator" % key)
12447
    self._BuildInputData(compat.partial(fn, self), keydata)
12448

    
12449
  def _ComputeClusterData(self):
12450
    """Compute the generic allocator input data.
12451

12452
    This is the data that is independent of the actual operation.
12453

12454
    """
12455
    cfg = self.cfg
12456
    cluster_info = cfg.GetClusterInfo()
12457
    # cluster data
12458
    data = {
12459
      "version": constants.IALLOCATOR_VERSION,
12460
      "cluster_name": cfg.GetClusterName(),
12461
      "cluster_tags": list(cluster_info.GetTags()),
12462
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
12463
      # we don't have job IDs
12464
      }
12465
    ninfo = cfg.GetAllNodesInfo()
12466
    iinfo = cfg.GetAllInstancesInfo().values()
12467
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
12468

    
12469
    # node data
12470
    node_list = [n.name for n in ninfo.values() if n.vm_capable]
12471

    
12472
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
12473
      hypervisor_name = self.hypervisor
12474
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
12475
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
12476
    else:
12477
      hypervisor_name = cluster_info.enabled_hypervisors[0]
12478

    
12479
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
12480
                                        hypervisor_name)
12481
    node_iinfo = \
12482
      self.rpc.call_all_instances_info(node_list,
12483
                                       cluster_info.enabled_hypervisors)
12484

    
12485
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
12486

    
12487
    config_ndata = self._ComputeBasicNodeData(ninfo)
12488
    data["nodes"] = self._ComputeDynamicNodeData(ninfo, node_data, node_iinfo,
12489
                                                 i_list, config_ndata)
12490
    assert len(data["nodes"]) == len(ninfo), \
12491
        "Incomplete node data computed"
12492

    
12493
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
12494

    
12495
    self.in_data = data
12496

    
12497
  @staticmethod
12498
  def _ComputeNodeGroupData(cfg):
12499
    """Compute node groups data.
12500

12501
    """
12502
    ng = dict((guuid, {
12503
      "name": gdata.name,
12504
      "alloc_policy": gdata.alloc_policy,
12505
      })
12506
      for guuid, gdata in cfg.GetAllNodeGroupsInfo().items())
12507

    
12508
    return ng
12509

    
12510
  @staticmethod
12511
  def _ComputeBasicNodeData(node_cfg):
12512
    """Compute global node data.
12513

12514
    @rtype: dict
12515
    @returns: a dict of name: (node dict, node config)
12516

12517
    """
12518
    # fill in static (config-based) values
12519
    node_results = dict((ninfo.name, {
12520
      "tags": list(ninfo.GetTags()),
12521
      "primary_ip": ninfo.primary_ip,
12522
      "secondary_ip": ninfo.secondary_ip,
12523
      "offline": ninfo.offline,
12524
      "drained": ninfo.drained,
12525
      "master_candidate": ninfo.master_candidate,
12526
      "group": ninfo.group,
12527
      "master_capable": ninfo.master_capable,
12528
      "vm_capable": ninfo.vm_capable,
12529
      })
12530
      for ninfo in node_cfg.values())
12531

    
12532
    return node_results
12533

    
12534
  @staticmethod
12535
  def _ComputeDynamicNodeData(node_cfg, node_data, node_iinfo, i_list,
12536
                              node_results):
12537
    """Compute global node data.
12538

12539
    @param node_results: the basic node structures as filled from the config
12540

12541
    """
12542
    # make a copy of the current dict
12543
    node_results = dict(node_results)
12544
    for nname, nresult in node_data.items():
12545
      assert nname in node_results, "Missing basic data for node %s" % nname
12546
      ninfo = node_cfg[nname]
12547

    
12548
      if not (ninfo.offline or ninfo.drained):
12549
        nresult.Raise("Can't get data for node %s" % nname)
12550
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
12551
                                nname)
12552
        remote_info = nresult.payload
12553

    
12554
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
12555
                     'vg_size', 'vg_free', 'cpu_total']:
12556
          if attr not in remote_info:
12557
            raise errors.OpExecError("Node '%s' didn't return attribute"
12558
                                     " '%s'" % (nname, attr))
12559
          if not isinstance(remote_info[attr], int):
12560
            raise errors.OpExecError("Node '%s' returned invalid value"
12561
                                     " for '%s': %s" %
12562
                                     (nname, attr, remote_info[attr]))
12563
        # compute memory used by primary instances
12564
        i_p_mem = i_p_up_mem = 0
12565
        for iinfo, beinfo in i_list:
12566
          if iinfo.primary_node == nname:
12567
            i_p_mem += beinfo[constants.BE_MEMORY]
12568
            if iinfo.name not in node_iinfo[nname].payload:
12569
              i_used_mem = 0
12570
            else:
12571
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
12572
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
12573
            remote_info['memory_free'] -= max(0, i_mem_diff)
12574

    
12575
            if iinfo.admin_up:
12576
              i_p_up_mem += beinfo[constants.BE_MEMORY]
12577

    
12578
        # compute memory used by instances
12579
        pnr_dyn = {
12580
          "total_memory": remote_info['memory_total'],
12581
          "reserved_memory": remote_info['memory_dom0'],
12582
          "free_memory": remote_info['memory_free'],
12583
          "total_disk": remote_info['vg_size'],
12584
          "free_disk": remote_info['vg_free'],
12585
          "total_cpus": remote_info['cpu_total'],
12586
          "i_pri_memory": i_p_mem,
12587
          "i_pri_up_memory": i_p_up_mem,
12588
          }
12589
        pnr_dyn.update(node_results[nname])
12590
        node_results[nname] = pnr_dyn
12591

    
12592
    return node_results
12593

    
12594
  @staticmethod
12595
  def _ComputeInstanceData(cluster_info, i_list):
12596
    """Compute global instance data.
12597

12598
    """
12599
    instance_data = {}
12600
    for iinfo, beinfo in i_list:
12601
      nic_data = []
12602
      for nic in iinfo.nics:
12603
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
12604
        nic_dict = {
12605
          "mac": nic.mac,
12606
          "ip": nic.ip,
12607
          "mode": filled_params[constants.NIC_MODE],
12608
          "link": filled_params[constants.NIC_LINK],
12609
          }
12610
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
12611
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
12612
        nic_data.append(nic_dict)
12613
      pir = {
12614
        "tags": list(iinfo.GetTags()),
12615
        "admin_up": iinfo.admin_up,
12616
        "vcpus": beinfo[constants.BE_VCPUS],
12617
        "memory": beinfo[constants.BE_MEMORY],
12618
        "os": iinfo.os,
12619
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
12620
        "nics": nic_data,
12621
        "disks": [{constants.IDISK_SIZE: dsk.size,
12622
                   constants.IDISK_MODE: dsk.mode}
12623
                  for dsk in iinfo.disks],
12624
        "disk_template": iinfo.disk_template,
12625
        "hypervisor": iinfo.hypervisor,
12626
        }
12627
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
12628
                                                 pir["disks"])
12629
      instance_data[iinfo.name] = pir
12630

    
12631
    return instance_data
12632

    
12633
  def _AddNewInstance(self):
12634
    """Add new instance data to allocator structure.
12635

12636
    This in combination with _AllocatorGetClusterData will create the
12637
    correct structure needed as input for the allocator.
12638

12639
    The checks for the completeness of the opcode must have already been
12640
    done.
12641

12642
    """
12643
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
12644

    
12645
    if self.disk_template in constants.DTS_INT_MIRROR:
12646
      self.required_nodes = 2
12647
    else:
12648
      self.required_nodes = 1
12649

    
12650
    request = {
12651
      "name": self.name,
12652
      "disk_template": self.disk_template,
12653
      "tags": self.tags,
12654
      "os": self.os,
12655
      "vcpus": self.vcpus,
12656
      "memory": self.memory,
12657
      "disks": self.disks,
12658
      "disk_space_total": disk_space,
12659
      "nics": self.nics,
12660
      "required_nodes": self.required_nodes,
12661
      "hypervisor": self.hypervisor,
12662
      }
12663

    
12664
    return request
12665

    
12666
  def _AddRelocateInstance(self):
12667
    """Add relocate instance data to allocator structure.
12668

12669
    This in combination with _IAllocatorGetClusterData will create the
12670
    correct structure needed as input for the allocator.
12671

12672
    The checks for the completeness of the opcode must have already been
12673
    done.
12674

12675
    """
12676
    instance = self.cfg.GetInstanceInfo(self.name)
12677
    if instance is None:
12678
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
12679
                                   " IAllocator" % self.name)
12680

    
12681
    if instance.disk_template not in constants.DTS_MIRRORED:
12682
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
12683
                                 errors.ECODE_INVAL)
12684

    
12685
    if instance.disk_template in constants.DTS_INT_MIRROR and \
12686
        len(instance.secondary_nodes) != 1:
12687
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
12688
                                 errors.ECODE_STATE)
12689

    
12690
    self.required_nodes = 1
12691
    disk_sizes = [{constants.IDISK_SIZE: disk.size} for disk in instance.disks]
12692
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
12693

    
12694
    request = {
12695
      "name": self.name,
12696
      "disk_space_total": disk_space,
12697
      "required_nodes": self.required_nodes,
12698
      "relocate_from": self.relocate_from,
12699
      }
12700
    return request
12701

    
12702
  def _AddEvacuateNodes(self):
12703
    """Add evacuate nodes data to allocator structure.
12704

12705
    """
12706
    request = {
12707
      "evac_nodes": self.evac_nodes
12708
      }
12709
    return request
12710

    
12711
  def _AddNodeEvacuate(self):
12712
    """Get data for node-evacuate requests.
12713

12714
    """
12715
    return {
12716
      "instances": self.instances,
12717
      "evac_mode": self.evac_mode,
12718
      }
12719

    
12720
  def _AddChangeGroup(self):
12721
    """Get data for node-evacuate requests.
12722

12723
    """
12724
    return {
12725
      "instances": self.instances,
12726
      "target_groups": self.target_groups,
12727
      }
12728

    
12729
  def _BuildInputData(self, fn, keydata):
12730
    """Build input data structures.
12731

12732
    """
12733
    self._ComputeClusterData()
12734

    
12735
    request = fn()
12736
    request["type"] = self.mode
12737
    for keyname, keytype in keydata:
12738
      if keyname not in request:
12739
        raise errors.ProgrammerError("Request parameter %s is missing" %
12740
                                     keyname)
12741
      val = request[keyname]
12742
      if not keytype(val):
12743
        raise errors.ProgrammerError("Request parameter %s doesn't pass"
12744
                                     " validation, value %s, expected"
12745
                                     " type %s" % (keyname, val, keytype))
12746
    self.in_data["request"] = request
12747

    
12748
    self.in_text = serializer.Dump(self.in_data)
12749

    
12750
  _STRING_LIST = ht.TListOf(ht.TString)
12751
  _JOB_LIST = ht.TListOf(ht.TListOf(ht.TStrictDict(True, False, {
12752
     # pylint: disable-msg=E1101
12753
     # Class '...' has no 'OP_ID' member
12754
     "OP_ID": ht.TElemOf([opcodes.OpInstanceFailover.OP_ID,
12755
                          opcodes.OpInstanceMigrate.OP_ID,
12756
                          opcodes.OpInstanceReplaceDisks.OP_ID])
12757
     })))
12758

    
12759
  _NEVAC_MOVED = \
12760
    ht.TListOf(ht.TAnd(ht.TIsLength(3),
12761
                       ht.TItems([ht.TNonEmptyString,
12762
                                  ht.TNonEmptyString,
12763
                                  ht.TListOf(ht.TNonEmptyString),
12764
                                 ])))
12765
  _NEVAC_FAILED = \
12766
    ht.TListOf(ht.TAnd(ht.TIsLength(2),
12767
                       ht.TItems([ht.TNonEmptyString,
12768
                                  ht.TMaybeString,
12769
                                 ])))
12770
  _NEVAC_RESULT = ht.TAnd(ht.TIsLength(3),
12771
                          ht.TItems([_NEVAC_MOVED, _NEVAC_FAILED, _JOB_LIST]))
12772

    
12773
  _MODE_DATA = {
12774
    constants.IALLOCATOR_MODE_ALLOC:
12775
      (_AddNewInstance,
12776
       [
12777
        ("name", ht.TString),
12778
        ("memory", ht.TInt),
12779
        ("disks", ht.TListOf(ht.TDict)),
12780
        ("disk_template", ht.TString),
12781
        ("os", ht.TString),
12782
        ("tags", _STRING_LIST),
12783
        ("nics", ht.TListOf(ht.TDict)),
12784
        ("vcpus", ht.TInt),
12785
        ("hypervisor", ht.TString),
12786
        ], ht.TList),
12787
    constants.IALLOCATOR_MODE_RELOC:
12788
      (_AddRelocateInstance,
12789
       [("name", ht.TString), ("relocate_from", _STRING_LIST)],
12790
       ht.TList),
12791
    constants.IALLOCATOR_MODE_MEVAC:
12792
      (_AddEvacuateNodes, [("evac_nodes", _STRING_LIST)],
12793
       ht.TListOf(ht.TAnd(ht.TIsLength(2), _STRING_LIST))),
12794
     constants.IALLOCATOR_MODE_NODE_EVAC:
12795
      (_AddNodeEvacuate, [
12796
        ("instances", _STRING_LIST),
12797
        ("evac_mode", ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)),
12798
        ], _NEVAC_RESULT),
12799
     constants.IALLOCATOR_MODE_CHG_GROUP:
12800
      (_AddChangeGroup, [
12801
        ("instances", _STRING_LIST),
12802
        ("target_groups", _STRING_LIST),
12803
        ], _NEVAC_RESULT),
12804
    }
12805

    
12806
  def Run(self, name, validate=True, call_fn=None):
12807
    """Run an instance allocator and return the results.
12808

12809
    """
12810
    if call_fn is None:
12811
      call_fn = self.rpc.call_iallocator_runner
12812

    
12813
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
12814
    result.Raise("Failure while running the iallocator script")
12815

    
12816
    self.out_text = result.payload
12817
    if validate:
12818
      self._ValidateResult()
12819

    
12820
  def _ValidateResult(self):
12821
    """Process the allocator results.
12822

12823
    This will process and if successful save the result in
12824
    self.out_data and the other parameters.
12825

12826
    """
12827
    try:
12828
      rdict = serializer.Load(self.out_text)
12829
    except Exception, err:
12830
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
12831

    
12832
    if not isinstance(rdict, dict):
12833
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
12834

    
12835
    # TODO: remove backwards compatiblity in later versions
12836
    if "nodes" in rdict and "result" not in rdict:
12837
      rdict["result"] = rdict["nodes"]
12838
      del rdict["nodes"]
12839

    
12840
    for key in "success", "info", "result":
12841
      if key not in rdict:
12842
        raise errors.OpExecError("Can't parse iallocator results:"
12843
                                 " missing key '%s'" % key)
12844
      setattr(self, key, rdict[key])
12845

    
12846
    if not self._result_check(self.result):
12847
      raise errors.OpExecError("Iallocator returned invalid result,"
12848
                               " expected %s, got %s" %
12849
                               (self._result_check, self.result),
12850
                               errors.ECODE_INVAL)
12851

    
12852
    if self.mode in (constants.IALLOCATOR_MODE_RELOC,
12853
                     constants.IALLOCATOR_MODE_MEVAC):
12854
      node2group = dict((name, ndata["group"])
12855
                        for (name, ndata) in self.in_data["nodes"].items())
12856

    
12857
      fn = compat.partial(self._NodesToGroups, node2group,
12858
                          self.in_data["nodegroups"])
12859

    
12860
      if self.mode == constants.IALLOCATOR_MODE_RELOC:
12861
        assert self.relocate_from is not None
12862
        assert self.required_nodes == 1
12863

    
12864
        request_groups = fn(self.relocate_from)
12865
        result_groups = fn(rdict["result"])
12866

    
12867
        if result_groups != request_groups:
12868
          raise errors.OpExecError("Groups of nodes returned by iallocator (%s)"
12869
                                   " differ from original groups (%s)" %
12870
                                   (utils.CommaJoin(result_groups),
12871
                                    utils.CommaJoin(request_groups)))
12872
      elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
12873
        request_groups = fn(self.evac_nodes)
12874
        for (instance_name, secnode) in self.result:
12875
          result_groups = fn([secnode])
12876
          if result_groups != request_groups:
12877
            raise errors.OpExecError("Iallocator returned new secondary node"
12878
                                     " '%s' (group '%s') for instance '%s'"
12879
                                     " which is not in original group '%s'" %
12880
                                     (secnode, utils.CommaJoin(result_groups),
12881
                                      instance_name,
12882
                                      utils.CommaJoin(request_groups)))
12883
      else:
12884
        raise errors.ProgrammerError("Unhandled mode '%s'" % self.mode)
12885

    
12886
    elif self.mode == constants.IALLOCATOR_MODE_NODE_EVAC:
12887
      assert self.evac_mode in constants.IALLOCATOR_NEVAC_MODES
12888

    
12889
    self.out_data = rdict
12890

    
12891
  @staticmethod
12892
  def _NodesToGroups(node2group, groups, nodes):
12893
    """Returns a list of unique group names for a list of nodes.
12894

12895
    @type node2group: dict
12896
    @param node2group: Map from node name to group UUID
12897
    @type groups: dict
12898
    @param groups: Group information
12899
    @type nodes: list
12900
    @param nodes: Node names
12901

12902
    """
12903
    result = set()
12904

    
12905
    for node in nodes:
12906
      try:
12907
        group_uuid = node2group[node]
12908
      except KeyError:
12909
        # Ignore unknown node
12910
        pass
12911
      else:
12912
        try:
12913
          group = groups[group_uuid]
12914
        except KeyError:
12915
          # Can't find group, let's use UUID
12916
          group_name = group_uuid
12917
        else:
12918
          group_name = group["name"]
12919

    
12920
        result.add(group_name)
12921

    
12922
    return sorted(result)
12923

    
12924

    
12925
class LUTestAllocator(NoHooksLU):
12926
  """Run allocator tests.
12927

12928
  This LU runs the allocator tests
12929

12930
  """
12931
  def CheckPrereq(self):
12932
    """Check prerequisites.
12933

12934
    This checks the opcode parameters depending on the director and mode test.
12935

12936
    """
12937
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
12938
      for attr in ["memory", "disks", "disk_template",
12939
                   "os", "tags", "nics", "vcpus"]:
12940
        if not hasattr(self.op, attr):
12941
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
12942
                                     attr, errors.ECODE_INVAL)
12943
      iname = self.cfg.ExpandInstanceName(self.op.name)
12944
      if iname is not None:
12945
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
12946
                                   iname, errors.ECODE_EXISTS)
12947
      if not isinstance(self.op.nics, list):
12948
        raise errors.OpPrereqError("Invalid parameter 'nics'",
12949
                                   errors.ECODE_INVAL)
12950
      if not isinstance(self.op.disks, list):
12951
        raise errors.OpPrereqError("Invalid parameter 'disks'",
12952
                                   errors.ECODE_INVAL)
12953
      for row in self.op.disks:
12954
        if (not isinstance(row, dict) or
12955
            constants.IDISK_SIZE not in row or
12956
            not isinstance(row[constants.IDISK_SIZE], int) or
12957
            constants.IDISK_MODE not in row or
12958
            row[constants.IDISK_MODE] not in constants.DISK_ACCESS_SET):
12959
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
12960
                                     " parameter", errors.ECODE_INVAL)
12961
      if self.op.hypervisor is None:
12962
        self.op.hypervisor = self.cfg.GetHypervisorType()
12963
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
12964
      fname = _ExpandInstanceName(self.cfg, self.op.name)
12965
      self.op.name = fname
12966
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
12967
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
12968
      if not hasattr(self.op, "evac_nodes"):
12969
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
12970
                                   " opcode input", errors.ECODE_INVAL)
12971
    elif self.op.mode in (constants.IALLOCATOR_MODE_CHG_GROUP,
12972
                          constants.IALLOCATOR_MODE_NODE_EVAC):
12973
      if not self.op.instances:
12974
        raise errors.OpPrereqError("Missing instances", errors.ECODE_INVAL)
12975
      self.op.instances = _GetWantedInstances(self, self.op.instances)
12976
    else:
12977
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
12978
                                 self.op.mode, errors.ECODE_INVAL)
12979

    
12980
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
12981
      if self.op.allocator is None:
12982
        raise errors.OpPrereqError("Missing allocator name",
12983
                                   errors.ECODE_INVAL)
12984
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
12985
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
12986
                                 self.op.direction, errors.ECODE_INVAL)
12987

    
12988
  def Exec(self, feedback_fn):
12989
    """Run the allocator test.
12990

12991
    """
12992
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
12993
      ial = IAllocator(self.cfg, self.rpc,
12994
                       mode=self.op.mode,
12995
                       name=self.op.name,
12996
                       memory=self.op.memory,
12997
                       disks=self.op.disks,
12998
                       disk_template=self.op.disk_template,
12999
                       os=self.op.os,
13000
                       tags=self.op.tags,
13001
                       nics=self.op.nics,
13002
                       vcpus=self.op.vcpus,
13003
                       hypervisor=self.op.hypervisor,
13004
                       )
13005
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
13006
      ial = IAllocator(self.cfg, self.rpc,
13007
                       mode=self.op.mode,
13008
                       name=self.op.name,
13009
                       relocate_from=list(self.relocate_from),
13010
                       )
13011
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
13012
      ial = IAllocator(self.cfg, self.rpc,
13013
                       mode=self.op.mode,
13014
                       evac_nodes=self.op.evac_nodes)
13015
    elif self.op.mode == constants.IALLOCATOR_MODE_CHG_GROUP:
13016
      ial = IAllocator(self.cfg, self.rpc,
13017
                       mode=self.op.mode,
13018
                       instances=self.op.instances,
13019
                       target_groups=self.op.target_groups)
13020
    elif self.op.mode == constants.IALLOCATOR_MODE_NODE_EVAC:
13021
      ial = IAllocator(self.cfg, self.rpc,
13022
                       mode=self.op.mode,
13023
                       instances=self.op.instances,
13024
                       evac_mode=self.op.evac_mode)
13025
    else:
13026
      raise errors.ProgrammerError("Uncatched mode %s in"
13027
                                   " LUTestAllocator.Exec", self.op.mode)
13028

    
13029
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
13030
      result = ial.in_text
13031
    else:
13032
      ial.Run(self.op.allocator, validate=False)
13033
      result = ial.out_text
13034
    return result
13035

    
13036

    
13037
#: Query type implementations
13038
_QUERY_IMPL = {
13039
  constants.QR_INSTANCE: _InstanceQuery,
13040
  constants.QR_NODE: _NodeQuery,
13041
  constants.QR_GROUP: _GroupQuery,
13042
  constants.QR_OS: _OsQuery,
13043
  }
13044

    
13045
assert set(_QUERY_IMPL.keys()) == constants.QR_VIA_OP
13046

    
13047

    
13048
def _GetQueryImplementation(name):
13049
  """Returns the implemtnation for a query type.
13050

13051
  @param name: Query type, must be one of L{constants.QR_VIA_OP}
13052

13053
  """
13054
  try:
13055
    return _QUERY_IMPL[name]
13056
  except KeyError:
13057
    raise errors.OpPrereqError("Unknown query resource '%s'" % name,
13058
                               errors.ECODE_INVAL)